[rhq] Branch 'stefan/backingcontent' - modules/plugins
by snegrea
modules/plugins/tomcat/pom.xml | 18
modules/plugins/tomcat/src/test/java/org/jboss/on/plugins/tomcat/test/FileContentDelegateTest.java | 246 +++++++++
modules/plugins/tomcat/src/test/java/org/jboss/on/plugins/tomcat/test/TomcatVHostComponentTest.java | 155 +++++
modules/plugins/tomcat/src/test/java/org/jboss/on/plugins/tomcat/test/TomcatWarComponentTest.java | 270 ++++++++++
modules/plugins/tomcat/src/test/resources/sampleWithImplementation.war |binary
modules/plugins/tomcat/src/test/resources/sampleWithManifest.war |binary
modules/plugins/tomcat/src/test/resources/sampleWithSpecification.war |binary
modules/plugins/tomcat/src/test/resources/sampleWithSpecificationImplementation.war |binary
modules/plugins/tomcat/src/test/resources/sampleWithoutManifest.war |binary
9 files changed, 689 insertions(+)
New commits:
commit c2578e177cc898d19436beaaf859cd9da58a6e5d
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Fri Feb 3 17:32:32 2012 -0600
[BZ 761593] Add unit tests for changed content system code.
diff --git a/modules/plugins/tomcat/pom.xml b/modules/plugins/tomcat/pom.xml
index 4837c5b..ce258a9 100644
--- a/modules/plugins/tomcat/pom.xml
+++ b/modules/plugins/tomcat/pom.xml
@@ -14,6 +14,10 @@
<name>RHQ Tomcat Plugin</name>
<description>A plugin for managing standalone JBoss EWS and Apache Tomcat Servers</description>
+
+ <properties>
+ <powermock.version>1.4.11</powermock.version>
+ </properties>
<dependencies>
@@ -24,6 +28,20 @@
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-module-testng</artifactId>
+ <version>${powermock.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-api-mockito</artifactId>
+ <version>${powermock.version}</version>
+ <scope>test</scope>
+ </dependency>
+
</dependencies>
<profiles>
diff --git a/modules/plugins/tomcat/src/test/java/org/jboss/on/plugins/tomcat/test/FileContentDelegateTest.java b/modules/plugins/tomcat/src/test/java/org/jboss/on/plugins/tomcat/test/FileContentDelegateTest.java
new file mode 100644
index 0000000..9a2dc49
--- /dev/null
+++ b/modules/plugins/tomcat/src/test/java/org/jboss/on/plugins/tomcat/test/FileContentDelegateTest.java
@@ -0,0 +1,246 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2008 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+package org.jboss.on.plugins.tomcat.test;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.util.jar.Manifest;
+
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import org.jboss.on.plugins.tomcat.helper.FileContentDelegate;
+
+import org.rhq.core.util.MessageDigestGenerator;
+import org.rhq.core.util.ZipUtil;
+
+public class FileContentDelegateTest {
+
+ @Test
+ public void testDeployExplodedWithManifestInArchive() throws Exception {
+ //tell the method story as it happens: mock or create dependencies and configure
+ //those dependencies to get the method under test to completion.
+ File deploymentDirectory = new File(this.getClass().getResource("/").getFile() + "deploymentDirectory");
+ deleteRecursive(deploymentDirectory);
+
+ File sampleWithManifestWar = new File(this.getClass().getResource("/sampleWithManifest.war").getFile());
+ Assert.assertTrue(sampleWithManifestWar.exists());
+
+ //create object to test and inject required dependencies
+ FileContentDelegate objectUnderTest = new FileContentDelegate(deploymentDirectory);
+
+ //run code under test
+ objectUnderTest.createContent(deploymentDirectory, sampleWithManifestWar, true);
+ String actualShaReturned = objectUnderTest.getSHA(deploymentDirectory);
+
+ //verify the results (Assert and mock verification)
+ File manifestFile = new File(deploymentDirectory.getAbsolutePath() + "/META-INF/MANIFEST.MF");
+ Assert.assertTrue(manifestFile.exists(), "Manifest file not created properly!");
+ Assert.assertNotEquals(manifestFile.length(), 0, "Empty manifest!!");
+
+ InputStream manifestStream = new FileInputStream(manifestFile);
+ Manifest manifest = new Manifest(manifestStream);
+ String actualSha256Attribute = manifest.getMainAttributes().getValue("RHQ-Sha256");
+ manifestStream.close();
+
+ MessageDigestGenerator digest = new MessageDigestGenerator(MessageDigestGenerator.SHA_256);
+ String expectedSHA256 = digest.calcDigestString(sampleWithManifestWar);
+
+ Assert.assertEquals(actualSha256Attribute, expectedSHA256);
+ Assert.assertEquals(actualShaReturned, expectedSHA256);
+
+ //cleanup resources created for this test
+ deleteRecursive(deploymentDirectory);
+ }
+
+ @Test
+ public void testGetShaExplodedWithManifest() throws Exception {
+ //tell the method story as it happens: mock or create dependencies and configure
+ //those dependencies to get the method under test to completion.
+ File deploymentDirectory = new File(this.getClass().getResource("/").getFile() + "deploymentDirectory");
+ deleteRecursive(deploymentDirectory);
+
+ File sampleWithManifestWar = new File(this.getClass().getResource("/sampleWithManifest.war").getFile());
+ Assert.assertTrue(sampleWithManifestWar.exists());
+
+ ZipUtil.unzipFile(sampleWithManifestWar, deploymentDirectory);
+
+ //create object to test and inject required dependencies
+ FileContentDelegate objectUnderTest = new FileContentDelegate(deploymentDirectory);
+
+ //run code under test
+ String actualShaReturned = objectUnderTest.getSHA(deploymentDirectory);
+
+ //verify the results (Assert and mock verification)
+ File manifestFile = new File(deploymentDirectory.getAbsolutePath() + "/META-INF/MANIFEST.MF");
+ Assert.assertTrue(manifestFile.exists(), "Manifest file not created properly!");
+ Assert.assertNotEquals(manifestFile.length(), 0, "Empty manifest!!");
+
+ InputStream manifestStream = new FileInputStream(manifestFile);
+ Manifest manifest = new Manifest(manifestStream);
+ String actualSha256Attribute = manifest.getMainAttributes().getValue("RHQ-Sha256");
+ manifestStream.close();
+
+ Assert.assertEquals(actualSha256Attribute, "342b0c96b83cc1b36184cb7e67a7df986ef305a5891041ea1c36afd9c04afd4d");
+ Assert.assertEquals(actualShaReturned, "342b0c96b83cc1b36184cb7e67a7df986ef305a5891041ea1c36afd9c04afd4d");
+
+ deleteRecursive(deploymentDirectory);
+ }
+
+ @Test
+ public void testDeployExplodedWithoutManifestInArchive() throws Exception {
+ //tell the method story as it happens: mock dependencies and configure
+ //those dependencies to get the method under test to completion.
+ File deploymentDirectory = new File(this.getClass().getResource("/").getFile() + "deploymentDirectory");
+ deleteRecursive(deploymentDirectory);
+
+ File sampleWithoutManifestWar = new File(this.getClass().getResource("/sampleWithoutManifest.war").getFile());
+ Assert.assertTrue(sampleWithoutManifestWar.exists());
+
+ //create object to test and inject required dependencies
+ FileContentDelegate objectUnderTest = new FileContentDelegate(deploymentDirectory);
+
+ //run code under test
+ objectUnderTest.createContent(deploymentDirectory, sampleWithoutManifestWar, true);
+ String actualShaReturned = objectUnderTest.getSHA(deploymentDirectory);
+
+ //verify the results (Assert and mock verification)
+ File manifestFile = new File(deploymentDirectory.getAbsolutePath() + "/META-INF/MANIFEST.MF");
+ Assert.assertTrue(manifestFile.exists(), "Manifest file not created properly!");
+ Assert.assertNotEquals(manifestFile.length(), 0, "Empty manifest!!");
+
+ InputStream manifestStream = new FileInputStream(manifestFile);
+ Manifest manifest = new Manifest(manifestStream);
+ String actualSha256Attribute = manifest.getMainAttributes().getValue("RHQ-Sha256");
+ manifestStream.close();
+
+ MessageDigestGenerator digest = new MessageDigestGenerator(MessageDigestGenerator.SHA_256);
+ String expectedSHA256 = digest.calcDigestString(sampleWithoutManifestWar);
+
+ Assert.assertEquals(actualSha256Attribute, expectedSHA256);
+ Assert.assertEquals(actualShaReturned, expectedSHA256);
+
+ deleteRecursive(deploymentDirectory);
+ }
+
+ @Test
+ public void testGetShaExplodedWithoutManifest() throws Exception {
+ //tell the method story as it happens: mock or create dependencies and configure
+ //those dependencies to get the method under test to completion.
+ File deploymentDirectory = new File(this.getClass().getResource("/").getFile() + "deploymentDirectory");
+ deleteRecursive(deploymentDirectory);
+
+ File sampleWithoutManifestWar = new File(this.getClass().getResource("/sampleWithoutManifest.war").getFile());
+ Assert.assertTrue(sampleWithoutManifestWar.exists());
+
+ //create object to test and inject required dependencies
+ ZipUtil.unzipFile(sampleWithoutManifestWar, deploymentDirectory);
+
+ //run code under test
+ FileContentDelegate objectUnderTest = new FileContentDelegate(deploymentDirectory);
+ String actualShaReturned = objectUnderTest.getSHA(deploymentDirectory);
+
+ //verify the results (Assert and mock verification)
+ File manifestFile = new File(deploymentDirectory.getAbsolutePath() + "/META-INF/MANIFEST.MF");
+ Assert.assertTrue(manifestFile.exists(), "Manifest file not created properly!");
+ Assert.assertNotEquals(manifestFile.length(), 0, "Empty manifest!!");
+
+ InputStream manifestStream = new FileInputStream(manifestFile);
+ Manifest manifest = new Manifest(manifestStream);
+ String actualSha256Attribute = manifest.getMainAttributes().getValue("RHQ-Sha256");
+ manifestStream.close();
+
+ Assert.assertEquals(actualSha256Attribute, "f2fa6712d19d25b47639f2ad7bd9dd1cb5af8d5551120f9f4a775edee7c5bb20");
+ Assert.assertEquals(actualShaReturned, "f2fa6712d19d25b47639f2ad7bd9dd1cb5af8d5551120f9f4a775edee7c5bb20");
+
+ //cleanup resources created for this test
+ deleteRecursive(deploymentDirectory);
+ }
+
+ @Test
+ public void testDeployZipped() throws Exception {
+ //tell the method story as it happens: mock or create dependencies and configure
+ //those dependencies to get the method under test to completion.
+ File deploymentFile = new File(this.getClass().getResource("/").getFile() + "deploymentDirectory.war");
+ deleteRecursive(deploymentFile);
+
+ File sampleWithoutManifestWar = new File(this.getClass().getResource("/sampleWithoutManifest.war").getFile());
+ Assert.assertTrue(sampleWithoutManifestWar.exists());
+
+ //create object to test and inject required dependencies
+ FileContentDelegate objectUnderTest = new FileContentDelegate(deploymentFile);
+
+ //run code under test
+ objectUnderTest.createContent(deploymentFile, sampleWithoutManifestWar, false);
+ String actualShaReturned = objectUnderTest.getSHA(sampleWithoutManifestWar);
+
+ //verify the results (Assert and mock verification)
+ Assert.assertTrue(deploymentFile.exists(), "Deployment did not happen.");
+ Assert.assertFalse(deploymentFile.isDirectory(), "Deployment was exploded when it should not have been.");
+
+ MessageDigestGenerator digest = new MessageDigestGenerator(MessageDigestGenerator.SHA_256);
+ String expectedSHA256 = digest.calcDigestString(sampleWithoutManifestWar);
+ String actualSHA256OfDeployment = digest.calcDigestString(deploymentFile);
+
+ Assert.assertEquals(actualSHA256OfDeployment, expectedSHA256);
+ Assert.assertEquals(actualShaReturned, expectedSHA256);
+
+ //cleanup resources created for this test
+ deleteRecursive(deploymentFile);
+ }
+
+ @Test
+ public void testGetShaZipped() throws Exception {
+ //tell the method story as it happens: mock or create dependencies and configure
+ //those dependencies to get the method under test to completion.
+ File sampleWithoutManifestWar = new File(this.getClass().getResource("/sampleWithoutManifest.war").getFile());
+ Assert.assertTrue(sampleWithoutManifestWar.exists());
+
+ //create object to test and inject required dependencies
+ FileContentDelegate objectUnderTest = new FileContentDelegate(sampleWithoutManifestWar);
+
+ //run code under test
+ String actualShaReturned = objectUnderTest.getSHA(sampleWithoutManifestWar);
+
+ //verify the results (Assert and mock verification)
+ MessageDigestGenerator digest = new MessageDigestGenerator(MessageDigestGenerator.SHA_256);
+ String expectedSHA256 = digest.calcDigestString(sampleWithoutManifestWar);
+
+ //cleanup resources created for this test
+ Assert.assertEquals(actualShaReturned, expectedSHA256);
+ }
+
+ private void deleteRecursive(File fileToDelete) throws Exception {
+ if (fileToDelete.exists()) {
+ if (fileToDelete.isDirectory()) {
+ for (File file : fileToDelete.listFiles()) {
+ if (file.isDirectory()) {
+ deleteRecursive(file);
+ } else {
+ file.delete();
+ }
+ }
+ }
+
+ fileToDelete.delete();
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/modules/plugins/tomcat/src/test/java/org/jboss/on/plugins/tomcat/test/TomcatVHostComponentTest.java b/modules/plugins/tomcat/src/test/java/org/jboss/on/plugins/tomcat/test/TomcatVHostComponentTest.java
new file mode 100644
index 0000000..73a30ae
--- /dev/null
+++ b/modules/plugins/tomcat/src/test/java/org/jboss/on/plugins/tomcat/test/TomcatVHostComponentTest.java
@@ -0,0 +1,155 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2008 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+package org.jboss.on.plugins.tomcat.test;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.jar.Manifest;
+
+import org.mc4j.ems.connection.bean.EmsBean;
+import org.mc4j.ems.connection.bean.attribute.EmsAttribute;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import org.jboss.on.plugins.tomcat.TomcatServerComponent;
+import org.jboss.on.plugins.tomcat.TomcatVHostComponent;
+
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.content.PackageDetailsKey;
+import org.rhq.core.domain.content.transfer.ResourcePackageDetails;
+import org.rhq.core.domain.resource.CreateResourceStatus;
+import org.rhq.core.domain.resource.ResourceType;
+import org.rhq.core.pluginapi.content.ContentContext;
+import org.rhq.core.pluginapi.content.ContentServices;
+import org.rhq.core.pluginapi.inventory.CreateResourceReport;
+import org.rhq.core.pluginapi.inventory.ResourceContext;
+
+public class TomcatVHostComponentTest{
+
+ @Test
+ public void testCreateSource() throws Exception {
+ //create the object under test as a partial mock because only one
+ //public method will be tested, while the rest will be mocked.
+ TomcatVHostComponent objectUnderTest = mock(TomcatVHostComponent.class);
+
+ //tell the method story as it happens: mock dependencies and configure
+ //those dependencies to get the method under test to completion.
+ CreateResourceReport mockCreateResourceReport = mock(CreateResourceReport.class);
+ ResourceType mockResourceType = mock(ResourceType.class);
+ when(mockCreateResourceReport.getResourceType()).thenReturn(mockResourceType);
+ when(mockResourceType.getName()).thenReturn("Tomcat Web Application (WAR)");
+
+ ResourcePackageDetails mockResourcePackageDetails = mock(ResourcePackageDetails.class);
+ when(mockCreateResourceReport.getPackageDetails()).thenReturn(mockResourcePackageDetails);
+ PackageDetailsKey mockPackageDetailsKey = mock(PackageDetailsKey.class);
+ when(mockResourcePackageDetails.getKey()).thenReturn(mockPackageDetailsKey);
+ when(mockPackageDetailsKey.getName()).thenReturn("testApplication.war");
+
+ Configuration mockConfiguration = mock(Configuration.class);
+ when(mockResourcePackageDetails.getDeploymentTimeConfiguration()).thenReturn(mockConfiguration);
+ PropertySimple mockPropertySimple = mock(PropertySimple.class);
+ when(mockConfiguration.getSimple(any(String.class))).thenReturn(mockPropertySimple);
+ when(mockPropertySimple.getBooleanValue()).thenReturn(Boolean.TRUE);
+
+ EmsBean mockEmsBean = mock(EmsBean.class);
+ when(objectUnderTest.getEmsBean()).thenReturn(mockEmsBean);
+ EmsAttribute mockEmsAttribute = mock(EmsAttribute.class);
+ when(mockEmsBean.getAttribute(anyString())).thenReturn(mockEmsAttribute);
+ when(mockEmsAttribute.getValue()).thenReturn(Boolean.TRUE);
+
+ File deploymentDirectory = new File(this.getClass().getResource("/").getFile() + "deploymentDirectory");
+ deleteRecursive(deploymentDirectory);
+ when(objectUnderTest.getConfigurationPath()).thenReturn(deploymentDirectory);
+
+ File tempDirectory = new File(this.getClass().getResource("/").getFile() + "tempDirectory");
+ deleteRecursive(tempDirectory);
+ tempDirectory.mkdirs();
+
+ @SuppressWarnings("unchecked")
+ ResourceContext<TomcatServerComponent<?>> mockResourceContext = mock(ResourceContext.class);
+ when(objectUnderTest.getResourceContext()).thenReturn(mockResourceContext);
+ when(mockResourceContext.getTemporaryDirectory()).thenReturn(tempDirectory);
+
+ ContentContext mockContentContext = mock(ContentContext.class);
+ when(mockResourceContext.getContentContext()).thenReturn(mockContentContext);
+ ContentServices mockContentServices = mock(ContentServices.class);
+ when(mockContentContext.getContentServices()).thenReturn(mockContentServices);
+
+ when(objectUnderTest.isWebApplication(any(File.class))).thenReturn(Boolean.TRUE);
+
+ //run code under test
+ when(objectUnderTest.createResource(any(CreateResourceReport.class))).thenCallRealMethod();
+ objectUnderTest.createResource(mockCreateResourceReport);
+
+ //verify the results (Assert and mock verification)
+ verify(objectUnderTest).getEmsBean();
+ verify(objectUnderTest, times(2)).getResourceContext();
+ verify(objectUnderTest).getConfigurationPath();
+ verify(objectUnderTest).isWebApplication(any(File.class));
+
+ verify(mockContentServices).downloadPackageBitsForChildResource(any(ContentContext.class), anyString(),
+ any(PackageDetailsKey.class), any(OutputStream.class));
+
+ verify(mockCreateResourceReport).setStatus(eq(CreateResourceStatus.SUCCESS));
+ verify(mockCreateResourceReport).setResourceName(eq("testApplication"));
+
+ File manifestFile = new File(deploymentDirectory.getAbsolutePath() + "/testApplication/META-INF/MANIFEST.MF");
+ Assert.assertTrue(manifestFile.exists(), "Manifest file not created properly!");
+ Assert.assertNotEquals(manifestFile.length(), 0, "Empty manifest!!");
+
+ InputStream manifestStream = new FileInputStream(manifestFile);
+ Manifest manifest = new Manifest(manifestStream);
+ String actualSha256Attribute = manifest.getMainAttributes().getValue("RHQ-Sha256");
+ manifestStream.close();
+
+ Assert.assertNotNull(actualSha256Attribute);
+ Assert.assertEquals(actualSha256Attribute.length(), 64);
+
+ //cleanup resources created for this test
+ deleteRecursive(deploymentDirectory);
+ deleteRecursive(tempDirectory);
+ }
+
+ private void deleteRecursive(File fileToDelete) throws Exception {
+ if (fileToDelete.exists()) {
+ if (fileToDelete.isDirectory()) {
+ for (File file : fileToDelete.listFiles()) {
+ if (file.isDirectory()) {
+ deleteRecursive(file);
+ } else {
+ file.delete();
+ }
+ }
+ }
+
+ fileToDelete.delete();
+ }
+ }
+}
\ No newline at end of file
diff --git a/modules/plugins/tomcat/src/test/java/org/jboss/on/plugins/tomcat/test/TomcatWarComponentTest.java b/modules/plugins/tomcat/src/test/java/org/jboss/on/plugins/tomcat/test/TomcatWarComponentTest.java
new file mode 100644
index 0000000..f7a395b
--- /dev/null
+++ b/modules/plugins/tomcat/src/test/java/org/jboss/on/plugins/tomcat/test/TomcatWarComponentTest.java
@@ -0,0 +1,270 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2008 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+package org.jboss.on.plugins.tomcat.test;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Matchers.isNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.jar.Manifest;
+
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import org.jboss.on.plugins.tomcat.TomcatVHostComponent;
+import org.jboss.on.plugins.tomcat.TomcatWarComponent;
+
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.content.PackageType;
+import org.rhq.core.domain.content.transfer.ResourcePackageDetails;
+import org.rhq.core.pluginapi.inventory.ResourceContext;
+import org.rhq.core.util.MessageDigestGenerator;
+import org.rhq.core.util.ZipUtil;
+
+public class TomcatWarComponentTest {
+
+ @Test
+ public void testDiscoverZippedDeployment() throws Exception {
+ //create the object under test as a partial mock because only one
+ //public method will be tested, while the rest will be mocked.
+ TomcatWarComponent objectUnderTest = mock(TomcatWarComponent.class);
+
+ //tell the method story as it happens: mock dependencies and configure
+ //those dependencies to get the method under test to completion.
+ File fileUsedInTest = new File(this.getClass().getResource("/sampleWithManifest.war").getFile());
+
+ @SuppressWarnings("unchecked")
+ ResourceContext<TomcatVHostComponent> mockResourceContext = mock(ResourceContext.class);
+ when(objectUnderTest.getResourceContext()).thenReturn(mockResourceContext);
+ Configuration mockConfiguration = mock(Configuration.class);
+ when(mockResourceContext.getPluginConfiguration()).thenReturn(mockConfiguration);
+ when(mockConfiguration.getSimpleValue(eq("filename"), isNull(String.class))).thenReturn(
+ fileUsedInTest.getAbsolutePath());
+
+ PackageType mockPackageType = mock(PackageType.class);
+
+ when(objectUnderTest.discoverDeployedPackages(any(PackageType.class))).thenCallRealMethod();
+
+ //run code under test
+ Set<ResourcePackageDetails> actualResult = objectUnderTest.discoverDeployedPackages(mockPackageType);
+
+ //verify the results (Assert and mock verification)
+ Assert.assertEquals(actualResult.size(), 1);
+
+ ResourcePackageDetails actualResourcePackageDetails = (ResourcePackageDetails) actualResult.toArray()[0];
+ Assert.assertEquals(actualResourcePackageDetails.getFileName(), fileUsedInTest.getName());
+ Assert.assertEquals(actualResourcePackageDetails.getLocation(), fileUsedInTest.getPath());
+ Assert.assertEquals((long) actualResourcePackageDetails.getFileSize(), fileUsedInTest.length());
+ if (actualResourcePackageDetails.getInstallationTimestamp() > System.currentTimeMillis()) {
+ Assert.fail("Timestamp is not in the past.");
+ }
+
+ MessageDigestGenerator digest = new MessageDigestGenerator(MessageDigestGenerator.SHA_256);
+ String expectedSha256 = digest.calcDigestString(fileUsedInTest);
+
+ Assert.assertEquals(actualResourcePackageDetails.getSHA256(), expectedSha256);
+ Assert.assertEquals(actualResourcePackageDetails.getDisplayVersion(), null);
+
+ verify(mockResourceContext, times(1)).getPluginConfiguration();
+ verify(objectUnderTest, times(1)).getResourceContext();
+ verify(mockConfiguration, times(1)).getSimpleValue(eq("filename"), isNull(String.class));
+ verifyNoMoreInteractions(mockPackageType);
+ }
+
+ @Test
+ public void testDiscoverExplodedDeployments() throws Exception {
+
+ //Presetup resources for the test
+ String[] testArchiveFiles = new String[] { "/sampleWithManifest.war", "/sampleWithoutManifest.war",
+ "/sampleWithImplementation.war", "/sampleWithSpecification.war",
+ "/sampleWithSpecificationImplementation.war" };
+
+ Map<String, String> expectedSha256 = new HashMap<String, String>();
+ expectedSha256.put(testArchiveFiles[0], "342b0c96b83cc1b36184cb7e67a7df986ef305a5891041ea1c36afd9c04afd4d");
+ expectedSha256.put(testArchiveFiles[1], "f2fa6712d19d25b47639f2ad7bd9dd1cb5af8d5551120f9f4a775edee7c5bb20");
+ expectedSha256.put(testArchiveFiles[2], "c72750a8952fcd50ee3e9dce8766a75aecdc57f4b654eca5787d3fa12dc78a55");
+ expectedSha256.put(testArchiveFiles[3], "968382bcd2f7550c2785a622c24671feaed4cca033bd9fe17665d9d66d8d3646");
+ expectedSha256.put(testArchiveFiles[4], "a96d9a054ead08575c11a79ec51ac0174da5ab02d213c008d248b6a59da6dc53");
+
+ Map<String, String> expectedDisplayVersion = new HashMap<String, String>();
+ expectedDisplayVersion.put(testArchiveFiles[0], null);
+ expectedDisplayVersion.put(testArchiveFiles[1], null);
+ expectedDisplayVersion.put(testArchiveFiles[2], "9.99");
+ expectedDisplayVersion.put(testArchiveFiles[3], "1.234");
+ expectedDisplayVersion.put(testArchiveFiles[4], "1.234 (9.990)");
+
+ for (String availableArchiveFile : testArchiveFiles) {
+ //create the object under test as a partial mock because only one
+ //public method will be tested, while the rest will be mocked.
+ TomcatWarComponent objectUnderTest = mock(TomcatWarComponent.class);
+
+ //tell the method story as it happens: mock dependencies and configure
+ //those dependencies to get the method under test to completion.
+ File archiveUsedInTest = new File(this.getClass().getResource(availableArchiveFile).getFile());
+ File deploymentFolderUsedInTest = new File(this.getClass().getResource("/").getFile() + "deploymentFolder");
+ ZipUtil.unzipFile(archiveUsedInTest, deploymentFolderUsedInTest);
+
+ @SuppressWarnings("unchecked")
+ ResourceContext<TomcatVHostComponent> mockResourceContext = mock(ResourceContext.class);
+ when(objectUnderTest.getResourceContext()).thenReturn(mockResourceContext);
+ Configuration mockConfiguration = mock(Configuration.class);
+ when(mockResourceContext.getPluginConfiguration()).thenReturn(mockConfiguration);
+ when(mockConfiguration.getSimpleValue(eq("filename"), isNull(String.class))).thenReturn(
+ deploymentFolderUsedInTest.getAbsolutePath());
+
+ PackageType mockPackageType = mock(PackageType.class);
+
+ when(objectUnderTest.discoverDeployedPackages(any(PackageType.class))).thenCallRealMethod();
+
+ //run code under test
+ Set<ResourcePackageDetails> actualResult = objectUnderTest.discoverDeployedPackages(mockPackageType);
+
+ //verify the results (Assert and mock verification)
+ Assert.assertEquals(actualResult.size(), 1);
+
+ ResourcePackageDetails actualResourcePackageDetails = (ResourcePackageDetails) actualResult.toArray()[0];
+ Assert.assertEquals(actualResourcePackageDetails.getFileName(), deploymentFolderUsedInTest.getName());
+ Assert.assertEquals(actualResourcePackageDetails.getLocation(), deploymentFolderUsedInTest.getPath());
+ Assert.assertEquals(actualResourcePackageDetails.getFileSize(), null);
+ if (actualResourcePackageDetails.getInstallationTimestamp() > System.currentTimeMillis()) {
+ Assert.fail("Timestamp is not in the past.");
+ }
+
+ String expectedSha256ForDeployment = expectedSha256.get(availableArchiveFile);
+
+ Assert.assertEquals(actualResourcePackageDetails.getSHA256(), expectedSha256.get(availableArchiveFile));
+ Assert.assertEquals(actualResourcePackageDetails.getDisplayVersion(),
+ expectedDisplayVersion.get(availableArchiveFile));
+
+ File manifestFile = new File(deploymentFolderUsedInTest.getAbsolutePath() + "/META-INF/MANIFEST.MF");
+ Assert.assertTrue(manifestFile.exists(), "Manifest file not created properly!");
+ Assert.assertNotEquals(manifestFile.length(), 0, "Empty manifest!!");
+
+ InputStream manifestStream = new FileInputStream(manifestFile);
+ Manifest manifest = new Manifest(manifestStream);
+ String actualSha256Attribute = manifest.getMainAttributes().getValue("RHQ-Sha256");
+ manifestStream.close();
+
+ Assert.assertEquals(actualSha256Attribute, expectedSha256ForDeployment);
+
+ verify(mockResourceContext, times(1)).getPluginConfiguration();
+ verify(objectUnderTest, times(1)).getResourceContext();
+ verify(mockConfiguration, times(1)).getSimpleValue(eq("filename"), isNull(String.class));
+ verifyNoMoreInteractions(mockPackageType);
+
+ //cleanup resources created for this test
+ deleteRecursive(deploymentFolderUsedInTest);
+ }
+ }
+
+ @Test
+ public void testDiscoverNoFileOnDisk() throws Exception {
+ //create the object under test as a partial mock because only one
+ //public method will be tested, while the rest will be mocked.
+ TomcatWarComponent objectUnderTest = mock(TomcatWarComponent.class);
+
+ //tell the method story as it happens: mock dependencies and configure
+ //those dependencies to get the method under test to completion.
+ File fileUsedInTest = new File(this.getClass().getResource("/").getFile() + "randomNonExistingFile");
+
+ @SuppressWarnings("unchecked")
+ ResourceContext<TomcatVHostComponent> mockResourceContext = mock(ResourceContext.class);
+ when(objectUnderTest.getResourceContext()).thenReturn(mockResourceContext);
+ Configuration mockConfiguration = mock(Configuration.class);
+ when(mockResourceContext.getPluginConfiguration()).thenReturn(mockConfiguration);
+ when(mockConfiguration.getSimpleValue(eq("filename"), isNull(String.class))).thenReturn(
+ fileUsedInTest.getAbsolutePath());
+
+ PackageType mockPackageType = mock(PackageType.class);
+
+ when(objectUnderTest.discoverDeployedPackages(any(PackageType.class))).thenCallRealMethod();
+
+ //run code under test
+ Set<ResourcePackageDetails> actualResult = objectUnderTest.discoverDeployedPackages(mockPackageType);
+
+ //verify the results (Assert and mock verification)
+ Assert.assertEquals(actualResult.size(), 0);
+
+ verify(mockResourceContext, times(1)).getPluginConfiguration();
+ verify(objectUnderTest, times(1)).getResourceContext();
+ verify(mockConfiguration, times(1)).getSimpleValue(eq("filename"), isNull(String.class));
+
+ verifyNoMoreInteractions(mockPackageType);
+ }
+
+ @Test(expectedExceptions = IllegalStateException.class)
+ public void testDiscoverIncorrectConfiguration() throws Exception {
+ //create the object under test as a partial mock because only one
+ //public method will be tested, while the rest will be mocked.
+ TomcatWarComponent objectUnderTest = mock(TomcatWarComponent.class);
+
+ //tell the method story as it happens: mock dependencies and configure
+ //those dependencies to get the method under test to completion.
+ @SuppressWarnings("unchecked")
+ ResourceContext<TomcatVHostComponent> mockResourceContext = mock(ResourceContext.class);
+ when(objectUnderTest.getResourceContext()).thenReturn(mockResourceContext);
+ Configuration mockConfiguration = mock(Configuration.class);
+ when(mockResourceContext.getPluginConfiguration()).thenReturn(mockConfiguration);
+ when(mockConfiguration.getSimpleValue(eq("filename"), isNull(String.class))).thenReturn(null);
+
+ PackageType mockPackageType = mock(PackageType.class);
+
+ when(objectUnderTest.discoverDeployedPackages(any(PackageType.class))).thenCallRealMethod();
+
+ //run code under test
+ Set<ResourcePackageDetails> actualResult = objectUnderTest.discoverDeployedPackages(mockPackageType);
+
+ //verify the results (Assert and mock verification)
+ Assert.assertEquals(actualResult.size(), 0);
+
+ verify(mockResourceContext, times(1)).getPluginConfiguration();
+ verify(objectUnderTest, times(1)).getResourceContext();
+ verify(mockConfiguration, times(1)).getSimpleValue(eq("filename"), isNull(String.class));
+
+ verifyNoMoreInteractions(mockPackageType);
+ }
+
+ private void deleteRecursive(File fileToDelete) throws Exception {
+ if (fileToDelete.exists()) {
+ if (fileToDelete.isDirectory()) {
+ for (File file : fileToDelete.listFiles()) {
+ if (file.isDirectory()) {
+ deleteRecursive(file);
+ } else {
+ file.delete();
+ }
+ }
+ }
+
+ fileToDelete.delete();
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/modules/plugins/tomcat/src/test/resources/sampleWithImplementation.war b/modules/plugins/tomcat/src/test/resources/sampleWithImplementation.war
new file mode 100644
index 0000000..9a5b7f4
Binary files /dev/null and b/modules/plugins/tomcat/src/test/resources/sampleWithImplementation.war differ
diff --git a/modules/plugins/tomcat/src/test/resources/sampleWithManifest.war b/modules/plugins/tomcat/src/test/resources/sampleWithManifest.war
new file mode 100644
index 0000000..0a127e6
Binary files /dev/null and b/modules/plugins/tomcat/src/test/resources/sampleWithManifest.war differ
diff --git a/modules/plugins/tomcat/src/test/resources/sampleWithSpecification.war b/modules/plugins/tomcat/src/test/resources/sampleWithSpecification.war
new file mode 100644
index 0000000..5f021e7
Binary files /dev/null and b/modules/plugins/tomcat/src/test/resources/sampleWithSpecification.war differ
diff --git a/modules/plugins/tomcat/src/test/resources/sampleWithSpecificationImplementation.war b/modules/plugins/tomcat/src/test/resources/sampleWithSpecificationImplementation.war
new file mode 100644
index 0000000..43fa852
Binary files /dev/null and b/modules/plugins/tomcat/src/test/resources/sampleWithSpecificationImplementation.war differ
diff --git a/modules/plugins/tomcat/src/test/resources/sampleWithoutManifest.war b/modules/plugins/tomcat/src/test/resources/sampleWithoutManifest.war
new file mode 100644
index 0000000..0f938f5
Binary files /dev/null and b/modules/plugins/tomcat/src/test/resources/sampleWithoutManifest.war differ
12 years, 4 months
[rhq] Branch 'jshaughn/avail' - modules/core modules/enterprise
by Jay Shaughnessy
modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java | 48 ++++------
modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/AvailabilityPromptCommand.java | 9 +
2 files changed, 30 insertions(+), 27 deletions(-)
New commits:
commit d511f140d6d8c5a4ba12094d4faaaf09ae0d5aae
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Fri Feb 3 17:13:08 2012 -0500
Stop sending avail reports for just the platform resource. In other
words, no longer send avail reports as an agent heartbeat, that's now the
ping job.
So, assuming committed inventory, send avail reports only for full scans
and changeOnly scans if and only if there has been an avail change.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java
index e623cb0..48bc173 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java
@@ -98,14 +98,16 @@ public class AvailabilityExecutor implements Runnable, Callable<AvailabilityRepo
/**
* Returns the availability report that should be sent to the Server.
*
- * <p>This will return <code>null</code> if there is no committed inventory and thus no availability reports should
- * be sent. This will rarely happen - only if this is a brand new agent whose inventory hasn't been committed yet or
- * if the platform and all its children have been deleted (in which case the agent should be uninstalled, or the user
- * will want to re-import the platform). In either case, it will be in rare, corner cases that this will ever return
- * null, and the condition that caused the null should eventually go away.</p>
+ * <p>This will return <code>null</code> if there is nothing committed to inventory. Having no committed inventory
+ * is rare. There will be no committed inventory if this is a brand new agent whose inventory hasn't been committed
+ * yet or if the platform and all its children have been deleted (in which case the agent should be uninstalled, or
+ * the user will want to re-import the platform).
+ *
+ * The report can be empty if there is nothing to report. This can happen for a changes-only report when there
+ * are no changes.</p>
*
* @return the report containing all the availabilities that need to be sent to the Server, or <code>null</code> if
- * there is no committed inventory and thus no availability reports should be sent
+ * there is no inventory or nothing to report. The report can be empty
*
* @throws Exception if failed to create and prepare the report
*/
@@ -127,27 +129,23 @@ public class AvailabilityExecutor implements Runnable, Callable<AvailabilityRepo
checkInventory(inventoryManager.getPlatform(), availabilityReport,
availabilityReport.isChangesOnlyReport(), true, false);
- // In enterprise mode, the server will need at least one resource so it can derive what agent
- // is sending this report. If the report is empty (meaning, nothing has changed since the last
- // availability check), let's add the platform record to the report
- if (availabilityReport.getResourceAvailability().isEmpty()) {
- checkInventory(inventoryManager.getPlatform(), availabilityReport, false, false, false);
- }
+ // If the report is empty (meaning, nothing has changed since the last availability check), don't
+ // send any report. In the past we needed to send a report as it doubled as an Agent heartbeat, but
+ // that is now handled but the Ping job.
+ if (!availabilityReport.getResourceAvailability().isEmpty()) {
- // if we have non-platform resources in the report, the agent has had
- // resources imported. So next time, only send changed only reports.
- if (availabilityReport.getResourceAvailability().size() > 1) {
+ // Whenever sending a report the next report should be changes only
sendChangedOnlyReportNextTime();
- }
- long end = System.currentTimeMillis();
+ long end = System.currentTimeMillis();
- if (log.isDebugEnabled()) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(10000);
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(availabilityReport);
- log.debug("Built availability report for [" + availabilityReport.getResourceAvailability().size()
- + "] resources with a size of [" + baos.size() + "] bytes in [" + (end - start) + "]ms");
+ if (log.isDebugEnabled()) {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream(10000);
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(availabilityReport);
+ log.debug("Built availability report for [" + availabilityReport.getResourceAvailability().size()
+ + "] resources with a size of [" + baos.size() + "] bytes in [" + (end - start) + "]ms");
+ }
}
}
@@ -205,8 +203,8 @@ public class AvailabilityExecutor implements Runnable, Callable<AvailabilityRepo
}
}
} catch (Throwable t) {
- ResourceError resourceError = new ResourceError(resource, ResourceErrorType.AVAILABILITY_CHECK, t
- .getLocalizedMessage(), ThrowableUtil.getStackAsString(t), System.currentTimeMillis());
+ ResourceError resourceError = new ResourceError(resource, ResourceErrorType.AVAILABILITY_CHECK,
+ t.getLocalizedMessage(), ThrowableUtil.getStackAsString(t), System.currentTimeMillis());
this.inventoryManager.sendResourceErrorToServer(resourceError);
// TODO GH: Put errors in report, rather than sending them to the Server separately.
if (log.isDebugEnabled()) {
diff --git a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/AvailabilityPromptCommand.java b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/AvailabilityPromptCommand.java
index d36915c..22deada 100644
--- a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/AvailabilityPromptCommand.java
+++ b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/AvailabilityPromptCommand.java
@@ -146,14 +146,19 @@ public class AvailabilityPromptCommand implements AgentPromptCommand {
out.println(MSG.getMsg(AgentI18NResourceKeys.AVAILABILITY_REPORT_HEADER, new Date(), availabilities.size(),
report.isChangesOnlyReport()));
+ // Now that we printed out the report summary, return if there is nothing to send
+ if (availabilities.isEmpty()) {
+ return;
+ }
+
for (AvailabilityReport.Datum datum : availabilities) {
// lookup the heavy-weight resource object
int resourceId = datum.getResourceId();
Resource resource = inventoryManager.getResourceContainer(resourceId).getResource();
if (verbose) {
- out.println(MSG.getMsg(AgentI18NResourceKeys.AVAILABILITY_REPORT_RESOURCE_VERBOSE, datum
- .getAvailabilityType(), resource.getName(), resource.getId(), resource.getResourceKey()));
+ out.println(MSG.getMsg(AgentI18NResourceKeys.AVAILABILITY_REPORT_RESOURCE_VERBOSE,
+ datum.getAvailabilityType(), resource.getName(), resource.getId(), resource.getResourceKey()));
} else {
out.println(MSG.getMsg(AgentI18NResourceKeys.AVAILABILITY_REPORT_RESOURCE, datum.getAvailabilityType(),
resource.getName()));
12 years, 4 months
[rhq] Branch 'release/jon3.0.x' - 3 commits - modules/core
by mazz
modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java | 280 +++++-----
modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java | 4
modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java | 10
3 files changed, 165 insertions(+), 129 deletions(-)
New commits:
commit 841dccecd66424c5f7286298f64b098ec2034a9e
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Fri Feb 3 13:11:27 2012 -0500
[BZ 773031] enhance test to check and make sure the state is set properly
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
index 39ae23d..f35965a 100644
--- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
+++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
@@ -35,7 +35,9 @@ import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.pc.PluginContainer;
import org.rhq.core.pc.ServerServices;
+import org.rhq.core.pc.inventory.InventoryManager;
import org.rhq.core.pc.inventory.ResourceContainer;
+import org.rhq.core.pc.inventory.ResourceContainer.ResourceComponentState;
import org.rhq.test.pc.PluginContainerSetup;
import org.rhq.test.pc.PluginContainerTest;
@@ -299,6 +301,14 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase {
assertEquals(discoveredResource.getName(), "resource-name-v1");
assertEquals(discoveredResource.getDescription(), "resource-description-v1");
+ InventoryManager im = PluginContainer.getInstance().getInventoryManager();
+ ResourceContainer container = im.getResourceContainer(discoveredResource.getId());
+ if (discoveredResource.getInventoryStatus() == InventoryStatus.COMMITTED) {
+ assert container.getResourceComponentState() == ResourceComponentState.STARTED;
+ } else {
+ assert container.getResourceComponentState() == ResourceComponentState.STOPPED;
+ }
+
return inv;
}
commit 81dd1704b92668879b6b83efd946f44d09d5a343
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Thu Feb 2 13:32:01 2012 -0500
[BZ 768706] add some more code to make sure we do proper error correction/checking
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
index 2a4a3f2..c350176 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
@@ -1464,6 +1464,7 @@ public class InventoryManager extends AgentService implements ContainerService,
// state is a transient field, so reinitialize it just in case this is invoked just after loadFromDisk()
if (state == null) {
container.setResourceComponentState(ResourceComponentState.STOPPED);
+ state = ResourceComponentState.STOPPED;
}
// if the component exists and is not stopped then we may not have to do anything
@@ -1590,11 +1591,19 @@ public class InventoryManager extends AgentService implements ContainerService,
if (prepareResourceForActivation(resource, container, updatedPluginConfig)) {
container.setResourceComponentState(ResourceComponentState.STARTING);
- ResourceContext context = container.getResourceContext();
+ ResourceContext context;
+ ResourceComponent component;
- // Wrap the component in a proxy that will provide locking and a timeout for the call to start().
- ResourceComponent component = container.createResourceComponentProxy(ResourceComponent.class,
- FacetLockType.READ, COMPONENT_START_TIMEOUT, true, false);
+ try {
+ context = container.getResourceContext();
+
+ // Wrap the component in a proxy that will provide locking and a timeout for the call to start().
+ component = container.createResourceComponentProxy(ResourceComponent.class, FacetLockType.READ,
+ COMPONENT_START_TIMEOUT, true, false);
+ } catch (Throwable t) {
+ container.setResourceComponentState(ResourceComponentState.STOPPED);
+ throw new PluginContainerException("Failed getting proxy for resource " + resource + ".", t);
+ }
try {
component.start(context);
commit 4e39e89a96afaa6878c82a511171cd7052961722
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Fri Feb 3 15:13:42 2012 -0500
[Bug 773031 - Component start() called more than once without an intervening stop()]
A variety of auto-formatting changes took place, actual changes are in:
InventoryManager.prepareResourceForActivation
InventoryManager.activateResource
The resource component state could be STOPPED or STARTED. There was a
large window while a component was actually starting that a call
to prepareResourceForActivation would happily allow the component to
again be activated. So, added an actual STARTING state that can block
redundant activation.
Additionally, if forcing reactivation ensure a STARTED component is
stopped before being restarted.
Also:
- remove unnecessary and bad lazy state check
- comment out some unused/debug code
- remove warnings
Conflicts:
modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
index eaee690..2a4a3f2 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
@@ -130,6 +130,7 @@ import org.rhq.core.util.exception.WrappedRemotingException;
* @author Ian Springer
* @author Jay Shaughnessy
*/
+@SuppressWarnings({ "rawtypes", "unchecked" })
public class InventoryManager extends AgentService implements ContainerService, DiscoveryAgentService {
private static final String INVENTORY_THREAD_POOL_NAME = "InventoryManager.discovery";
private static final String AVAIL_THREAD_POOL_NAME = "InventoryManager.availability";
@@ -245,16 +246,19 @@ public class InventoryManager extends AgentService implements ContainerService,
// inside EmbJopr).
if (configuration.isInsideAgent()) {
// After an initial delay (5s by default), periodically run an availability check (every 1m by default).
- availabilityThreadPoolExecutor.scheduleWithFixedDelay(availabilityExecutor, configuration
- .getAvailabilityScanInitialDelay(), configuration.getAvailabilityScanPeriod(), TimeUnit.SECONDS);
+ availabilityThreadPoolExecutor.scheduleWithFixedDelay(availabilityExecutor,
+ configuration.getAvailabilityScanInitialDelay(), configuration.getAvailabilityScanPeriod(),
+ TimeUnit.SECONDS);
// After an initial delay (10s by default), periodically run a server discovery scan (every 15m by default).
- inventoryThreadPoolExecutor.scheduleWithFixedDelay(serverScanExecutor, configuration
- .getServerDiscoveryInitialDelay(), configuration.getServerDiscoveryPeriod(), TimeUnit.SECONDS);
+ inventoryThreadPoolExecutor.scheduleWithFixedDelay(serverScanExecutor,
+ configuration.getServerDiscoveryInitialDelay(), configuration.getServerDiscoveryPeriod(),
+ TimeUnit.SECONDS);
// After an initial delay (20s by default), periodically run a service discovery scan (every 1d by default).
- inventoryThreadPoolExecutor.scheduleWithFixedDelay(serviceScanExecutor, configuration
- .getServiceDiscoveryInitialDelay(), configuration.getServiceDiscoveryPeriod(), TimeUnit.SECONDS);
+ inventoryThreadPoolExecutor.scheduleWithFixedDelay(serviceScanExecutor,
+ configuration.getServiceDiscoveryInitialDelay(), configuration.getServiceDiscoveryPeriod(),
+ TimeUnit.SECONDS);
}
} finally {
inventoryLock.writeLock().unlock();
@@ -311,8 +315,8 @@ public class InventoryManager extends AgentService implements ContainerService,
long timeout = getDiscoveryComponentTimeout(context.getResourceType());
try {
- ResourceDiscoveryComponent proxy = this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(context
- .getResourceType(), component, timeout, parentResourceContainer);
+ ResourceDiscoveryComponent proxy = this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(
+ context.getResourceType(), component, timeout, parentResourceContainer);
Set<DiscoveredResourceDetails> results = proxy.discoverResources(context);
return results;
} catch (TimeoutException te) {
@@ -347,8 +351,8 @@ public class InventoryManager extends AgentService implements ContainerService,
long timeout = getDiscoveryComponentTimeout(context.getResourceType());
try {
- ManualAddFacet proxy = this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(context
- .getResourceType(), component, timeout, ManualAddFacet.class, parentResourceContainer);
+ ManualAddFacet proxy = this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(
+ context.getResourceType(), component, timeout, ManualAddFacet.class, parentResourceContainer);
DiscoveredResourceDetails result = proxy.discoverResource(pluginConfig, context);
return result;
} catch (TimeoutException te) {
@@ -387,8 +391,8 @@ public class InventoryManager extends AgentService implements ContainerService,
component, timeout, ClassLoaderFacet.class, parentContainer);
ResourceDiscoveryContext discoveryContext = new ResourceDiscoveryContext(resourceType, parentComponent,
- parentResourceContext, SystemInfoFactory.createSystemInfo(), null, null, this.configuration
- .getContainerName(), this.configuration.getPluginContainerDeployment());
+ parentResourceContext, SystemInfoFactory.createSystemInfo(), null, null,
+ this.configuration.getContainerName(), this.configuration.getPluginContainerDeployment());
// Configurations are not immutable, so clone the plugin config, so the plugin will not be able to change the
// actual PC-managed plugin config.
@@ -409,7 +413,6 @@ public class InventoryManager extends AgentService implements ContainerService,
long timeout = getDiscoveryComponentTimeout(resourceType);
try {
- @SuppressWarnings("unchecked")
ResourceUpgradeFacet<T> proxy = this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(
resourceType, component, timeout, ResourceUpgradeFacet.class, parentResourceContainer);
@@ -641,7 +644,6 @@ public class InventoryManager extends AgentService implements ContainerService,
return new Availability(resource, new Date(), availType);
}
- @SuppressWarnings("unchecked")
public MergeResourceResponse manuallyAddResource(ResourceType resourceType, int parentResourceId,
Configuration pluginConfiguration, int ownerSubjectId) throws InvalidPluginConfigurationClientException,
PluginContainerException {
@@ -676,8 +678,8 @@ public class InventoryManager extends AgentService implements ContainerService,
ResourceDiscoveryContext<ResourceComponent<?>> discoveryContext = new ResourceDiscoveryContext<ResourceComponent<?>>(
resourceType, parentResourceComponent, parentResourceContainer.getResourceContext(),
SystemInfoFactory.createSystemInfo(), new ArrayList<ProcessScanResult>(0),
- new ArrayList<Configuration>(0), this.configuration.getContainerName(), this.configuration
- .getPluginContainerDeployment());
+ new ArrayList<Configuration>(0), this.configuration.getContainerName(),
+ this.configuration.getPluginContainerDeployment());
// Ask the plugin's discovery component to find the new resource, throwing exceptions if it cannot be
// found at all.
@@ -880,8 +882,7 @@ public class InventoryManager extends AgentService implements ContainerService,
if ((this.platform != null) && (this.platform.getInventoryStatus() == InventoryStatus.NEW)
&& newPlatformWasDeletedRecently) {
// let's make sure we are registered; its probable that our platform was deleted and we need to re-register
- log
- .info("No committed resources to send in our availability report - the platform/agent was deleted, let's re-register again");
+ log.info("No committed resources to send in our availability report - the platform/agent was deleted, let's re-register again");
registerWithServer();
newPlatformWasDeletedRecently = false; // we've tried to recover from our platform being deleted, let's not do it again
}
@@ -924,8 +925,8 @@ public class InventoryManager extends AgentService implements ContainerService,
log.debug("Availability report content: " + report.toString(log.isTraceEnabled()));
}
- boolean ok = configuration.getServerServices().getDiscoveryServerService().mergeAvailabilityReport(
- report);
+ boolean ok = configuration.getServerServices().getDiscoveryServerService()
+ .mergeAvailabilityReport(report);
if (!ok) {
// I guess I could immediately call executeAvailabilityScanImmediately and pass its results to
// mergeAvailabilityReport again right now, but what happens if we've queued up a bunch of
@@ -971,10 +972,9 @@ public class InventoryManager extends AgentService implements ContainerService,
(System.currentTimeMillis() - startTime)));
}
} catch (StaleTypeException e) {
- log
- .error("Failed to merge inventory report with server. The report contains one or more resource types "
- + "that have been marked for deletion. Notifying the plugin container that a reboot is needed to purge "
- + "stale types.");
+ log.error("Failed to merge inventory report with server. The report contains one or more resource types "
+ + "that have been marked for deletion. Notifying the plugin container that a reboot is needed to purge "
+ + "stale types.");
PluginContainer.getInstance().notifyRebootRequestListener();
return false;
} catch (InvalidInventoryReportException e) {
@@ -982,8 +982,7 @@ public class InventoryManager extends AgentService implements ContainerService,
if ((this.platform != null) && (this.platform.getInventoryStatus() == InventoryStatus.NEW)
&& newPlatformWasDeletedRecently) {
// let's make sure we are registered; its probable that our platform was deleted and we need to re-register
- log
- .info("The inventory report was invalid probably because the platform/Agent was deleted; let's re-register...");
+ log.info("The inventory report was invalid probably because the platform/Agent was deleted; let's re-register...");
registerWithServer();
newPlatformWasDeletedRecently = false; // we've tried to recover from our platform being deleted, let's not do it again
}
@@ -1179,8 +1178,8 @@ public class InventoryManager extends AgentService implements ContainerService,
parent.removeChildResource(resource);
}
- PluginContainer.getInstance().getMeasurementManager().unscheduleCollection(
- Collections.singleton(resource.getId()));
+ PluginContainer.getInstance().getMeasurementManager()
+ .unscheduleCollection(Collections.singleton(resource.getId()));
if (this.resourceContainers.remove(resource.getUuid()) == null) {
if (log.isDebugEnabled()) {
@@ -1286,8 +1285,8 @@ public class InventoryManager extends AgentService implements ContainerService,
logMessage.append("description, ");
}
- logMessage.replace(logMessage.length() - 1, logMessage.length(), "to become [").append(
- existingResource.toString()).append("]");
+ logMessage.replace(logMessage.length() - 1, logMessage.length(), "to become [")
+ .append(existingResource.toString()).append("]");
log.info(logMessage.toString());
} else {
@@ -1450,25 +1449,48 @@ public class InventoryManager extends AgentService implements ContainerService,
*/
private boolean prepareResourceForActivation(Resource resource, @NotNull ResourceContainer container,
boolean forceReinitialization) throws InvalidPluginConfigurationException, PluginContainerException {
+
if (resourceUpgradeDelegate.hasUpgradeFailed(resource)) {
if (log.isTraceEnabled()) {
log.trace("Skipping activation of " + resource + " - it has failed to upgrade.");
}
+
return false;
}
ResourceComponent component = container.getResourceComponent();
+ ResourceComponentState state = container.getResourceComponentState();
- // if the component already exists and is started, and the resource's plugin config has not changed, there is
- // nothing to do, so return immediately
- if ((component != null)
- && (container.getResourceComponentState() == ResourceComponentState.STARTED && !forceReinitialization)) {
- if (log.isTraceEnabled()) {
- log.trace("No need to prepare the activation of resource " + resource
- + " - its component is already started and its plugin "
- + "config has not been updated since it was last started.");
+ // state is a transient field, so reinitialize it just in case this is invoked just after loadFromDisk()
+ if (state == null) {
+ container.setResourceComponentState(ResourceComponentState.STOPPED);
+ }
+
+ // if the component exists and is not stopped then we may not have to do anything
+ if ((component != null) && (state != ResourceComponentState.STOPPED)) {
+
+ // if STARTED and we are forced to restart (e.g. plugin config change), then stop the component
+ // and continue. If STARTING just let it continue to start as interruption could put us in a bad state.
+ if (forceReinitialization) {
+ switch (state) {
+ case STARTED:
+ component.stop();
+ break;
+ case STARTING:
+ log.warn("Could not force initialization of component for resource [" + resource.getId()
+ + "] as it is already in the process of starting.");
+
+ return false;
+ }
+ } else {
+ if (log.isTraceEnabled()) {
+ log.trace("No need to prepare the activation of resource " + resource
+ + " - its component is already started and its plugin "
+ + "config has not been updated since it was last started.");
+ }
+
+ return false;
}
- return false;
}
if (log.isDebugEnabled()) {
@@ -1484,16 +1506,13 @@ public class InventoryManager extends AgentService implements ContainerService,
}
try {
component = PluginContainer.getInstance().getPluginComponentFactory().buildResourceComponent(resource);
+
} catch (Throwable e) {
throw new PluginContainerException("Could not build component for Resource [" + resource + "]", e);
}
container.setResourceComponent(component);
}
- //this is a transient field, so reinitialize it just in case this is invoked just after
- //loadFromDisk()
- container.setResourceComponentState(ResourceComponentState.STOPPED);
-
// start the resource, but only if its parent component is running. If the parent is null, that means
// the resource is, itself, the root platform and we always activate that.
ResourceContainer parentResourceContainer;
@@ -1523,8 +1542,8 @@ public class InventoryManager extends AgentService implements ContainerService,
log.warn("Cannot give activated resource its discovery component. Cause: " + e);
}
- ConfigurationUtility.normalizeConfiguration(resource.getPluginConfiguration(), type
- .getPluginConfigurationDefinition());
+ ConfigurationUtility.normalizeConfiguration(resource.getPluginConfiguration(),
+ type.getPluginConfigurationDefinition());
ResourceComponent<?> parentComponent = null;
if (resource.getParentResource() != null) {
@@ -1532,10 +1551,9 @@ public class InventoryManager extends AgentService implements ContainerService,
}
ResourceContext context = createResourceContext(resource, parentComponent, discoveryComponent);
-
container.setResourceContext(context);
-
return true;
+
} else {
if (log.isDebugEnabled()) {
log.debug("Resource [" + resource + "] not being prepared for activation; parent isn't started: "
@@ -1559,9 +1577,9 @@ public class InventoryManager extends AgentService implements ContainerService,
* plugin configuration
* @throws PluginContainerException for all other errors
*/
- @SuppressWarnings("unchecked")
public void activateResource(Resource resource, @NotNull ResourceContainer container, boolean updatedPluginConfig)
throws InvalidPluginConfigurationException, PluginContainerException {
+
if (resourceUpgradeDelegate.hasUpgradeFailed(resource)) {
if (log.isTraceEnabled()) {
log.trace("Skipping activation of " + resource + " - it has failed to upgrade.");
@@ -1570,6 +1588,7 @@ public class InventoryManager extends AgentService implements ContainerService,
}
if (prepareResourceForActivation(resource, container, updatedPluginConfig)) {
+ container.setResourceComponentState(ResourceComponentState.STARTING);
ResourceContext context = container.getResourceContext();
@@ -1578,27 +1597,26 @@ public class InventoryManager extends AgentService implements ContainerService,
FacetLockType.READ, COMPONENT_START_TIMEOUT, true, false);
try {
- // One last check to make sure another thread didn't beat us to the punch.
- // TODO: Add some real synchronization to this method. (ips, 07/09/07)
- if (container.getResourceComponentState() == ResourceComponentState.STARTED) {
- if (log.isTraceEnabled()) {
- log.trace("Skipping activation of " + resource + " - its component is already started.");
- }
- return;
- }
component.start(context);
container.setResourceComponentState(ResourceComponentState.STARTED);
resource.setConnected(true); // This tells the server-side that the resource has connected successfully.
+
} catch (Throwable t) {
+ // Don't leave in a STARTING state. Don't actually call component.stop(),
+ // because we're not actually STARTED
+ container.setResourceComponentState(ResourceComponentState.STOPPED);
+
if (updatedPluginConfig || (t instanceof InvalidPluginConfigurationException)) {
if (log.isDebugEnabled()) {
log.debug("Resource has a bad config, waiting for this to go away: " + resource);
}
InventoryEventListener iel = new ResourceGotActivatedListener();
addInventoryEventListener(iel);
+
throw new InvalidPluginConfigurationException("Failed to start component for resource " + resource
+ ".", t);
}
+
throw new PluginContainerException("Failed to start component for resource " + resource + ".", t);
}
@@ -1662,8 +1680,8 @@ public class InventoryManager extends AgentService implements ContainerService,
resource.setConnected(false); // invalid plugin configuration infers the resource component is disconnected
// Give the server-side an error message describing the connection failure that can be
// displayed on the resource's Inventory page.
- ResourceError resourceError = new ResourceError(resource, ResourceErrorType.INVALID_PLUGIN_CONFIGURATION, t
- .getLocalizedMessage(), ThrowableUtil.getStackAsString(t), System.currentTimeMillis());
+ ResourceError resourceError = new ResourceError(resource, ResourceErrorType.INVALID_PLUGIN_CONFIGURATION,
+ t.getLocalizedMessage(), ThrowableUtil.getStackAsString(t), System.currentTimeMillis());
return sendResourceErrorToServer(resourceError);
}
@@ -1751,37 +1769,39 @@ public class InventoryManager extends AgentService implements ContainerService,
return servers;
}
- private void activateFromDisk(Resource resource) throws PluginContainerException {
- if (resource.getId() == 0) {
- return; // This is for the case of a resource that hadn't been synced to the server (there are probably better places to handle this)
- }
-
- resource.setAgent(this.agent);
- ResourceContainer container = getResourceContainer(resource.getId());
- if (container == null) {
- if (log.isDebugEnabled()) {
- log.debug("Could not find a container for resource: " + resource);
- }
- return;
- }
- if (container.getSynchronizationState() != ResourceContainer.SynchronizationState.SYNCHRONIZED) {
- if (log.isDebugEnabled()) {
- log.debug("Stopped activating resources at unsynchronized resource [" + resource + "]");
- }
- return;
- }
-
- try {
- activateResource(resource, container, false);
- } catch (Exception e) {
- log.debug("Failed to activate from disk [" + resource + "]");
- }
-
- for (Resource child : resource.getChildResources()) {
- initResourceContainer(child);
- activateFromDisk(child);
- }
- }
+ // commenting out dead code, leaving for reference -jshaughn
+ //
+ // private void activateFromDisk(Resource resource) throws PluginContainerException {
+ // if (resource.getId() == 0) {
+ // return; // This is for the case of a resource that hadn't been synced to the server (there are probably better places to handle this)
+ // }
+ //
+ // resource.setAgent(this.agent);
+ // ResourceContainer container = getResourceContainer(resource.getId());
+ // if (container == null) {
+ // if (log.isDebugEnabled()) {
+ // log.debug("Could not find a container for resource: " + resource);
+ // }
+ // return;
+ // }
+ // if (container.getSynchronizationState() != ResourceContainer.SynchronizationState.SYNCHRONIZED) {
+ // if (log.isDebugEnabled()) {
+ // log.debug("Stopped activating resources at unsynchronized resource [" + resource + "]");
+ // }
+ // return;
+ // }
+ //
+ // try {
+ // activateResource(resource, container, false);
+ // } catch (Exception e) {
+ // log.debug("Failed to activate from disk [" + resource + "]");
+ // }
+ //
+ // for (Resource child : resource.getChildResources()) {
+ // initResourceContainer(child);
+ // activateFromDisk(child);
+ // }
+ // }
/**
* Tries to load an existing inventory from the file data/inventory.dat
@@ -1876,7 +1896,6 @@ public class InventoryManager extends AgentService implements ContainerService,
* TODO GH: Move this to another class (this one is getting too big)
* @return The discovered platform (which might be a dummy in case of testing)
*/
- @SuppressWarnings("unchecked")
private Resource discoverPlatform() {
PluginManager pluginManager = PluginContainer.getInstance().getPluginManager();
PluginComponentFactory componentFactory = PluginContainer.getInstance().getPluginComponentFactory();
@@ -1922,8 +1941,7 @@ public class InventoryManager extends AgentService implements ContainerService,
}
} else {
// This is very strange - there are no platform types - we should never be missing the built-in platform plugin.
- log
- .error("Missing platform plugin(s) - falling back to dummy platform impl; this should only occur in tests!");
+ log.error("Missing platform plugin(s) - falling back to dummy platform impl; this should only occur in tests!");
// TODO: Set sysprop (e.g. rhq.test.mode=true) in integration tests,
// and throw a runtime exception here if that sysprop is not set.
return getTestPlatform();
@@ -2308,8 +2326,8 @@ public class InventoryManager extends AgentService implements ContainerService,
try {
ResourceDiscoveryContext context = new ResourceDiscoveryContext(resourceType, parentComponent,
parentResourceContext, SystemInfoFactory.createSystemInfo(), processScanResults,
- Collections.EMPTY_LIST, this.configuration.getContainerName(), this.configuration
- .getPluginContainerDeployment());
+ Collections.EMPTY_LIST, this.configuration.getContainerName(),
+ this.configuration.getPluginContainerDeployment());
newResources = new HashSet<Resource>();
try {
Set<DiscoveredResourceDetails> discoveredResources = invokeDiscoveryComponent(parentContainer,
@@ -2420,19 +2438,19 @@ public class InventoryManager extends AgentService implements ContainerService,
return contentContext;
}
- private ResourceComponent<?> createTestPlatformComponent() {
- return new ResourceComponent() {
- public AvailabilityType getAvailability() {
- return AvailabilityType.UP;
- }
-
- public void start(ResourceContext context) {
- }
-
- public void stop() {
- }
- };
- }
+ // private ResourceComponent<?> createTestPlatformComponent() {
+ // return new ResourceComponent() {
+ // public AvailabilityType getAvailability() {
+ // return AvailabilityType.UP;
+ // }
+ //
+ // public void start(ResourceContext context) {
+ // }
+ //
+ // public void stop() {
+ // }
+ // };
+ // }
private void updateResourceVersion(Resource resource, String version) {
String existingVersion = resource.getVersion();
@@ -2548,8 +2566,8 @@ public class InventoryManager extends AgentService implements ContainerService,
if (log.isDebugEnabled()) {
log.debug("Merging [" + modifiedResourceIds.size() + "] modified Resources into local inventory...");
}
- Set<Resource> modifiedResources = configuration.getServerServices().getDiscoveryServerService().getResources(
- modifiedResourceIds, false);
+ Set<Resource> modifiedResources = configuration.getServerServices().getDiscoveryServerService()
+ .getResources(modifiedResourceIds, false);
syncSchedules(modifiedResources); // RHQ-792, mtime is the indicator that schedules should be sync'ed too
syncDriftDefinitions(modifiedResources);
for (Resource modifiedResource : modifiedResources) {
@@ -2591,16 +2609,16 @@ public class InventoryManager extends AgentService implements ContainerService,
return;
}
- private void print(Resource resourceTreeNode, int level) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < level; i++) {
- builder.append(" ");
- }
- log.info(builder.toString() + resourceTreeNode.getId() + " " + resourceTreeNode.getUuid());
- for (Resource child : resourceTreeNode.getChildResources()) {
- print(child, level + 1);
- }
- }
+ // private void print(Resource resourceTreeNode, int level) {
+ // StringBuilder builder = new StringBuilder();
+ // for (int i = 0; i < level; i++) {
+ // builder.append(" ");
+ // }
+ // log.info(builder.toString() + resourceTreeNode.getId() + " " + resourceTreeNode.getUuid());
+ // for (Resource child : resourceTreeNode.getChildResources()) {
+ // print(child, level + 1);
+ // }
+ // }
private void mergeResource(Resource resource) {
if (log.isDebugEnabled()) {
@@ -2798,10 +2816,9 @@ public class InventoryManager extends AgentService implements ContainerService,
log.info("Resource activation and upgrade finished.");
} catch (Throwable t) {
- log
- .error(
- "Resource activation or upgrade failed with an exception. An attempt to merely activate the resources will be made now.",
- t);
+ log.error(
+ "Resource activation or upgrade failed with an exception. An attempt to merely activate the resources will be made now.",
+ t);
//make sure to at least activate the resources
activateAndUpgradeResourceRecursively(getPlatform(), false);
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java
index 854e624..c348a57 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java
@@ -67,7 +67,7 @@ import org.rhq.core.pluginapi.inventory.ResourceContext;
* @author John Mazzitelli
* @author Ian Springer
*/
-@SuppressWarnings("unchecked")
+@SuppressWarnings({ "rawtypes", "unchecked" })
public class ResourceContainer implements Serializable {
private static final long serialVersionUID = 1L;
@@ -76,7 +76,7 @@ public class ResourceContainer implements Serializable {
}
public enum ResourceComponentState {
- STARTED, STOPPED
+ STARTED, STOPPED, STARTING
}
// thread pools used to invoke methods on container's components
12 years, 4 months
[rhq] Branch 'release/jon3.0.x' - 2 commits - modules/core modules/enterprise
by Jay Shaughnessy
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java | 151 ++++++----
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftCarouselView.java | 17 -
2 files changed, 103 insertions(+), 65 deletions(-)
New commits:
commit ac6eedae2d41ac18cf05672a1a37e7b0b8ea917a
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Mon Dec 5 15:51:07 2011 -0500
[Bug 760289 - Excessive file scanning in drift detection when using includes filters]
Now, when using includes file paths limit the directory scanning to only
those included directories.
Note that using a "." as an includes path basically translates to using
the base directory, in which case the scan will be as it is now.
A future enhancement may be to analyze the pattern and decide
whether a recursive scan is necessary. Currently. So, using includes
patterns to just look for certain files in the base directory will
expose you to the full scan.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
index b376c59..8099de5 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
@@ -27,6 +27,7 @@ import org.rhq.common.drift.FileEntry;
import org.rhq.common.drift.Headers;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
import org.rhq.core.domain.drift.DriftDefinition;
+import org.rhq.core.domain.drift.Filter;
import org.rhq.core.util.MessageDigestGenerator;
import org.rhq.core.util.file.FileVisitor;
@@ -172,13 +173,12 @@ public class DriftDetector implements Runnable {
log.debug("Generating drift change set for " + schedule);
- File currentSnapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
- schedule.getDriftDefinition().getName(), COVERAGE);
+ File currentSnapshot = changeSetMgr.findChangeSet(schedule.getResourceId(), schedule.getDriftDefinition()
+ .getName(), COVERAGE);
File snapshotFile = currentSnapshot;
if (schedule.getDriftDefinition().isPinned()) {
snapshotFile = new File(snapshotFile.getParentFile(), "snapshot.pinned");
-
}
final File basedir = new File(basedir(schedule.getResourceId(), schedule.getDriftDefinition()));
@@ -208,43 +208,50 @@ public class DriftDetector implements Runnable {
}
// First look for files that have either been modified or deleted
- scanForModifiedOrDeletedFiles(schedule, basedir, processedFiles, snapshotEntries, deltaEntries, coverageReader);
+ scanForModifiedOrDeletedFiles(schedule, basedir, processedFiles, snapshotEntries, deltaEntries,
+ coverageReader);
} finally {
coverageReader.close();
}
// If the basedir is still valid we need to do a directory tree scan to look for newly added files
if (basedir.isDirectory()) {
- forEachFile(basedir, new FilterFileVisitor(basedir, schedule.getDriftDefinition().getIncludes(), schedule
- .getDriftDefinition().getExcludes(), new FileVisitor() {
- @Override
- public void visit(File file) {
- try {
- if (processedFiles.contains(file)) {
- return;
- }
+ DriftDefinition driftDef = schedule.getDriftDefinition();
+ List<Filter> includes = driftDef.getIncludes();
+ List<Filter> excludes = driftDef.getExcludes();
+
+ for (File dir : getScanDirectories(basedir, includes)) {
+ forEachFile(dir, new FilterFileVisitor(basedir, includes, excludes, new FileVisitor() {
+ @Override
+ public void visit(File file) {
+ try {
+ if (processedFiles.contains(file)) {
+ return;
+ }
- if (!file.canRead()) {
- if (log.isDebugEnabled()) {
- log.debug("Skipping " + file.getPath() + " since it is not readable.");
+ if (!file.canRead()) {
+ if (log.isDebugEnabled()) {
+ log.debug("Skipping " + file.getPath() + " since it is not readable.");
+ }
+ return;
}
- return;
- }
- if (log.isInfoEnabled()) {
- log.info("Detected added file for " + schedule + " --> " + file.getAbsolutePath());
- }
+ if (log.isInfoEnabled()) {
+ log.info("Detected added file for " + schedule + " --> " + file.getAbsolutePath());
+ }
- FileEntry newEntry = addedFileEntry(relativePath(basedir, file), sha256(file));
- deltaEntries.add(newEntry);
- snapshotEntries.add(newEntry);
- } catch (IOException e) {
- log.error("An error occurred while generating a drift change set for " + schedule + ": "
- + e.getMessage());
- throw new DriftDetectionException("An error occurred while generating a drift change set", e);
+ FileEntry newEntry = addedFileEntry(relativePath(basedir, file), sha256(file));
+ deltaEntries.add(newEntry);
+ snapshotEntries.add(newEntry);
+ } catch (IOException e) {
+ log.error("An error occurred while generating a drift change set for " + schedule + ": "
+ + e.getMessage());
+ throw new DriftDetectionException("An error occurred while generating a drift change set",
+ e);
+ }
}
- }
- }));
+ }));
+ }
}
if (deltaEntries.isEmpty()) {
@@ -255,8 +262,8 @@ public class DriftDetector implements Runnable {
// the current snapshot to match the pinned snapshot. Note though
// that we increment the snapshot version in order to let the server
// know about the state change.
- if (schedule.getDriftDefinition().isPinned() && newVersion > 1 && !isPreviousChangeSetEmpty(
- schedule.getResourceId(), schedule.getDriftDefinition())) {
+ if (schedule.getDriftDefinition().isPinned() && newVersion > 1
+ && !isPreviousChangeSetEmpty(schedule.getResourceId(), schedule.getDriftDefinition())) {
currentSnapshot.delete();
File newSnapshot = updateCurrentSnapshot(schedule, snapshotEntries, newVersion);
@@ -264,8 +271,8 @@ public class DriftDetector implements Runnable {
// TODO report back to the server that we are back in compliance
}
} else {
- if (schedule.getDriftDefinition().isPinned() && newVersion > 1 &&
- isSameAsPreviousChangeSet(deltaEntries, currentSnapshot)) {
+ if (schedule.getDriftDefinition().isPinned() && newVersion > 1
+ && isSameAsPreviousChangeSet(deltaEntries, currentSnapshot)) {
// if we are still out of compliance just report, we report a
// repeat change set to indicate no changes but also still out
// of compliance.
@@ -281,6 +288,26 @@ public class DriftDetector implements Runnable {
}
}
+ private Set<File> getScanDirectories(final File basedir, List<Filter> includes) {
+
+ Set<File> directories = new HashSet<File>();
+
+ if (null == includes || includes.isEmpty()) {
+ directories.add(basedir);
+ } else {
+ for (Filter filter : includes) {
+ String path = filter.getPath();
+ if (".".equals(path)) {
+ directories.add(basedir);
+ } else {
+ directories.add(new File(basedir, path));
+ }
+ }
+ }
+
+ return directories;
+ }
+
private void scanForModifiedOrDeletedFiles(DriftDetectionSchedule schedule, File basedir, Set<File> processedFiles,
List<FileEntry> snapshotEntries, List<FileEntry> deltaEntries, ChangeSetReader coverageReader)
throws IOException {
@@ -317,6 +344,7 @@ public class DriftDetector implements Runnable {
}
}
+ @SuppressWarnings("unused")
private boolean isPreviousChangeSetEmpty(int resourceId, DriftDefinition definition) throws IOException {
File changeSet = changeSetMgr.findChangeSet(resourceId, definition.getName(), DRIFT);
if (!changeSet.exists()) {
@@ -342,15 +370,14 @@ public class DriftDetector implements Runnable {
}
private void updateDeltaSnapshot(DriftDetectionSummary summary, DriftDetectionSchedule schedule,
- List<FileEntry> deltaEntries, int newVersion, File oldSnapshot, File newSnapshot)
- throws IOException {
+ List<FileEntry> deltaEntries, int newVersion, File oldSnapshot, File newSnapshot) throws IOException {
ChangeSetWriter deltaWriter = null;
try {
Headers deltaHeaders = createHeaders(schedule, DRIFT, newVersion);
- File driftChangeSet = changeSetMgr.findChangeSet(schedule.getResourceId(),
- schedule.getDriftDefinition().getName(), DRIFT);
+ File driftChangeSet = changeSetMgr.findChangeSet(schedule.getResourceId(), schedule.getDriftDefinition()
+ .getName(), DRIFT);
deltaWriter = changeSetMgr.getChangeSetWriter(driftChangeSet, deltaHeaders);
summary.setDriftChangeSet(driftChangeSet);
@@ -381,10 +408,9 @@ public class DriftDetector implements Runnable {
try {
Headers snapshotHeaders = createHeaders(schedule, COVERAGE, newVersion);
- File newSnapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
- schedule.getDriftDefinition().getName(), COVERAGE);
- newSnapshotWriter = changeSetMgr.getChangeSetWriter(schedule.getResourceId(),
- snapshotHeaders);
+ File newSnapshot = changeSetMgr.findChangeSet(schedule.getResourceId(), schedule.getDriftDefinition()
+ .getName(), COVERAGE);
+ newSnapshotWriter = changeSetMgr.getChangeSetWriter(schedule.getResourceId(), snapshotHeaders);
for (FileEntry entry : snapshotEntries) {
newSnapshotWriter.write(entry);
@@ -416,19 +442,19 @@ public class DriftDetector implements Runnable {
return false;
}
switch (entry.getType()) {
- case FILE_ADDED:
- if (!entry.getNewSHA().equals(newEntry.getNewSHA())) {
- return false;
- }
- case FILE_CHANGED:
- if (!entry.getNewSHA().equals(newEntry.getNewSHA()) ||
- !entry.getOldSHA().equals(newEntry.getOldSHA())) {
- return false;
- }
- default: // FILE_REMOVED
- if (!entry.getOldSHA().equals(newEntry.getOldSHA())) {
- return false;
- }
+ case FILE_ADDED:
+ if (!entry.getNewSHA().equals(newEntry.getNewSHA())) {
+ return false;
+ }
+ case FILE_CHANGED:
+ if (!entry.getNewSHA().equals(newEntry.getNewSHA())
+ || !entry.getOldSHA().equals(newEntry.getOldSHA())) {
+ return false;
+ }
+ default: // FILE_REMOVED
+ if (!entry.getOldSHA().equals(newEntry.getOldSHA())) {
+ return false;
+ }
}
numEntries++;
}
@@ -448,9 +474,9 @@ public class DriftDetector implements Runnable {
if (!basedir.exists()) {
if (log.isWarnEnabled()) {
- log.warn("The base directory [" + basedir.getAbsolutePath() + "] for " + schedule + " does not " +
- "exist. You may want review the drift definition and verify that the value of the base " +
- "directory is in fact correct.");
+ log.warn("The base directory [" + basedir.getAbsolutePath() + "] for " + schedule + " does not "
+ + "exist. You may want review the drift definition and verify that the value of the base "
+ + "directory is in fact correct.");
}
summary.setBaseDirExists(false);
return;
@@ -482,9 +508,13 @@ public class DriftDetector implements Runnable {
}
private void doDirectoryScan(final DriftDetectionSchedule schedule, DriftDefinition driftDef, final File basedir,
- final ChangeSetWriter writer) {
- forEachFile(basedir, new FilterFileVisitor(basedir, driftDef.getIncludes(), driftDef.getExcludes(),
- new FileVisitor() {
+ final ChangeSetWriter writer) {
+
+ List<Filter> includes = driftDef.getIncludes();
+ List<Filter> excludes = driftDef.getExcludes();
+
+ for (File dir : getScanDirectories(basedir, includes)) {
+ forEachFile(dir, new FilterFileVisitor(basedir, includes, excludes, new FileVisitor() {
@Override
public void visit(File file) {
try {
@@ -506,6 +536,7 @@ public class DriftDetector implements Runnable {
}
}
}));
+ }
}
private String relativePath(File basedir, File file) {
commit 3595dcc97f66f1b280eb5e8b46e764cc937dba00
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Fri Dec 9 14:05:05 2011 -0500
[Bug 765592 - drift diff is different depending on order in which files are selected]
Fixed, the new changes will now always get the "+" prefixes and the older
will get the "-" prefixes.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftCarouselView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftCarouselView.java
index 544ef81..6899913 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftCarouselView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftCarouselView.java
@@ -267,11 +267,18 @@ public class DriftCarouselView extends BookmarkableCarousel implements DetailsVi
public void executeAction(Object actionValue) {
- String id1 = selectedRecords.get(0).getAttribute(DriftDataSource.ATTR_ID);
- String id2 = selectedRecords.get(1).getAttribute(DriftDataSource.ATTR_ID);
- final String path = selectedRecords.get(0).getAttribute(DriftDataSource.ATTR_PATH);
-
- GWTServiceLookup.getDriftService().generateUnifiedDiffByIds(id1, id2,
+ Record record1 = selectedRecords.get(0);
+ Record record2 = selectedRecords.get(1);
+ final String path = record1.getAttribute(DriftDataSource.ATTR_PATH);
+ String id1 = record1.getAttribute(DriftDataSource.ATTR_ID);
+ String id2 = record2.getAttribute(DriftDataSource.ATTR_ID);
+ // regardless of selection order, compare the same way, showing newest changes with '+' signs
+ int version1 = record1.getAttributeAsInt(DriftDataSource.ATTR_CHANGESET_VERSION);
+ int version2 = record2.getAttributeAsInt(DriftDataSource.ATTR_CHANGESET_VERSION);
+ String diffOldId = (version1 < version2) ? id1 : id2;
+ String diffNewId = (version1 < version2) ? id2 : id1;
+
+ GWTServiceLookup.getDriftService().generateUnifiedDiffByIds(diffOldId, diffNewId,
new AsyncCallback<FileDiffReport>() {
@Override
public void onFailure(Throwable caught) {
12 years, 4 months
[rhq] Branch 'feature/gwt-upgrade' - modules/enterprise
by mike thompson
modules/enterprise/gui/coregui/pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
New commits:
commit 5cffc6ca928d62408fc9d699f7e0ff2f2ecb8e3e
Author: Mike Thompson <mithomps(a)redhat.com>
Date: Fri Feb 3 12:10:51 2012 -0800
[BZ787248 - Add IE9 user agent support for GWT]
diff --git a/modules/enterprise/gui/coregui/pom.xml b/modules/enterprise/gui/coregui/pom.xml
index bcd909f..c54086a 100644
--- a/modules/enterprise/gui/coregui/pom.xml
+++ b/modules/enterprise/gui/coregui/pom.xml
@@ -53,7 +53,7 @@
Multiple agents can be specified as a comma-delimited list, as demonstrated by the default
value below.
-->
- <gwt.userAgent>ie6,ie8,gecko1_8,safari,opera</gwt.userAgent>
+ <gwt.userAgent>ie6,ie8,ie9,gecko1_8,safari,opera</gwt.userAgent>
<!-- Change this to "true" via the mvn command line or your ~/.m2/settings.xml to speed
up gwt compilation. -->
12 years, 4 months
[rhq] Branch 'jshaughn/avail' - 2 commits - modules/core modules/enterprise
by Jay Shaughnessy
modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml | 9 +
modules/core/domain/src/main/java/org/rhq/core/domain/measurement/Availability.java | 43 ++++--
modules/core/domain/src/main/java/org/rhq/core/domain/measurement/ResourceAvailability.java | 15 +-
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerBean.java | 41 +++--
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerLocal.java | 2
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/AvailabilityManagerBean.java | 69 ++++++----
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/AvailabilityManagerLocal.java | 13 +
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerBean.java | 13 +
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerLocal.java | 11 +
modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/AvailabilityManagerTest.java | 25 +--
10 files changed, 159 insertions(+), 82 deletions(-)
New commits:
commit 4e98d566c9de90f56311ec59e0489f5f2632d54d
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Fri Feb 3 15:05:14 2012 -0500
Backfilling working for graceful or sudden agent shutdown. Now platform
is set DOWN but children are set UNKNOWN to reflect the fact that we
don't actually know the true avail status.
Future: Note that existing GOES DOWN alert conditions will likely change
such that they are now GOES DOWN or UNKNOWN to provide back compat. And
GOES DOWN will actually be a new, strict interpretation.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/Availability.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/Availability.java
index 38029d8..cc4fb1a 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/Availability.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/Availability.java
@@ -57,12 +57,13 @@ import org.rhq.core.domain.resource.Resource;
* @author John Mazzitelli
*/
@Entity
-@NamedQueries( { @NamedQuery(name = Availability.FIND_CURRENT_BY_RESOURCE, query = "" //
- + " SELECT av " //
- + " FROM Availability av " //
- + " WHERE av.resource.id = :resourceId " //
- + " AND av.endTime IS NULL " //
- + "ORDER BY av.startTime ASC "), // this order by is on purpose - for handling NonUniqueResultException problems
+@NamedQueries({
+ @NamedQuery(name = Availability.FIND_CURRENT_BY_RESOURCE, query = "" //
+ + " SELECT av " //
+ + " FROM Availability av " //
+ + " WHERE av.resource.id = :resourceId " //
+ + " AND av.endTime IS NULL " //
+ + "ORDER BY av.startTime ASC "), // this order by is on purpose - for handling NonUniqueResultException problems
@NamedQuery(name = Availability.FIND_BY_RESOURCE, query = "" //
+ " SELECT av " //
+ " FROM Availability av " //
@@ -72,15 +73,25 @@ import org.rhq.core.domain.resource.Resource;
+ "SELECT av " //
+ " FROM Availability av " //
+ " WHERE av.resource.id = :resourceId "), //
-
- // get all current resource availabilities for those that do not match a given availability type
- @NamedQuery(name = Availability.FIND_NONMATCHING_WITH_RESOURCE_ID_BY_AGENT_AND_TYPE, query = "" //
+ // get platform resource avail (i.e. most recent avail) for agent not matching given availability type
+ @NamedQuery(name = Availability.FIND_PLATFORM_COMPOSITE_BY_AGENT_AND_NONMATCHING_TYPE, query = "" //
+ "SELECT new org.rhq.core.domain.resource.composite.ResourceIdWithAvailabilityComposite(av.resource.id, av) " //
+ " FROM Availability av " //
+ " WHERE av.resource.agent.id = :agentId " //
+ + " AND av.resource.parentResource IS NULL " //
+ " AND ((av.availabilityType <> :availabilityType AND :availabilityType IS NOT NULL) " //
+ " OR (av.availabilityType IS NOT NULL AND :availabilityType IS NULL) " //
- + " OR (av.availabilityType IS NULL AND :availabilityType IS NOT NULL))" //
+ + " OR (av.availabilityType IS NULL AND :availabilityType IS NOT NULL)) " //
+ + " AND av.endTime IS NULL"), //
+ // get child resource avail (i.e. most recent avail) for agent not matching given availability type
+ @NamedQuery(name = Availability.FIND_CHILD_COMPOSITE_BY_AGENT_AND_NONMATCHING_TYPE, query = "" //
+ + "SELECT new org.rhq.core.domain.resource.composite.ResourceIdWithAvailabilityComposite(av.resource.id, av) " //
+ + " FROM Availability av " //
+ + " WHERE av.resource.agent.id = :agentId " //
+ + " AND av.resource.parentResource IS NOT NULL " //
+ + " AND ((av.availabilityType <> :availabilityType AND :availabilityType IS NOT NULL) " //
+ + " OR (av.availabilityType IS NOT NULL AND :availabilityType IS NULL) " //
+ + " OR (av.availabilityType IS NULL AND :availabilityType IS NOT NULL)) " //
+ " AND av.endTime IS NULL"), //
@NamedQuery(name = Availability.FIND_FOR_RESOURCE_WITHIN_INTERVAL, query = "" //
+ "SELECT av FROM Availability av " //
@@ -112,7 +123,13 @@ import org.rhq.core.domain.resource.Resource;
+ " AND ( av.endTime >= :aTime OR av.endTime IS NULL ) "), //
@NamedQuery(name = Availability.QUERY_DELETE_BY_RESOURCES, query = "" //
+ " DELETE Availability a " //
- + " WHERE a.resource.id IN ( :resourceIds )") })
+ + " WHERE a.resource.id IN ( :resourceIds )"),
+ @NamedQuery(name = Availability.FIND_FOR_AGENT_PLATFORM, query = "" //
+ + "SELECT av FROM Availability av " //
+ + " WHERE av.resource.id = " //
+ + " ( SELECT res.id FROM Resource res " //
+ + " WHERE res.agent.id = :agentId " //
+ + " AND res.parentResource.id IS NULL )") })
@SequenceGenerator(name = "Generator", sequenceName = "RHQ_AVAILABILITY_ID_SEQ")
@Table(name = "RHQ_AVAILABILITY")
@XmlRootElement
@@ -122,12 +139,14 @@ public class Availability implements Serializable {
public static final String FIND_CURRENT_BY_RESOURCE = "Availability.findCurrentByResource";
public static final String FIND_BY_RESOURCE = "Availability.findByResource";
public static final String FIND_BY_RESOURCE_NO_SORT = "Availability.findByResourceNoSort";
- public static final String FIND_NONMATCHING_WITH_RESOURCE_ID_BY_AGENT_AND_TYPE = "Availability.findNonmatchingWithResourceIdByAgentAndType";
+ public static final String FIND_PLATFORM_COMPOSITE_BY_AGENT_AND_NONMATCHING_TYPE = "Availability.findPlatformCompositeByAgentAndNonmatchingType";
+ public static final String FIND_CHILD_COMPOSITE_BY_AGENT_AND_NONMATCHING_TYPE = "Availability.findChildCompositeByAgentAndNonmatchingType";
public static final String FIND_FOR_RESOURCE_WITHIN_INTERVAL = "Availability.findForResourceWithinInterval";
public static final String FIND_FOR_RESOURCE_GROUP_WITHIN_INTERVAL = "Availability.findForResourceGroupWithinInterval";
public static final String FIND_FOR_AUTO_GROUP_WITHIN_INTERVAL = "Availability.findForAutoGroupWithinInterval";
public static final String FIND_BY_RESOURCE_AND_DATE = "Availability.findByResourceAndDate";
public static final String QUERY_DELETE_BY_RESOURCES = "Availability.deleteByResources";
+ public static final String FIND_FOR_AGENT_PLATFORM = "Availability.findForAgentPlatform";
public static final String NATIVE_QUERY_PURGE = "DELETE FROM RHQ_AVAILABILITY WHERE END_TIME < ?";
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/ResourceAvailability.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/ResourceAvailability.java
index 4e008f9..263dfa2 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/ResourceAvailability.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/ResourceAvailability.java
@@ -51,12 +51,20 @@ import org.rhq.core.domain.resource.Resource;
@NamedQueries( //
{ @NamedQuery(name = ResourceAvailability.QUERY_FIND_BY_RESOURCE_ID, query = "" //
+ " SELECT ra FROM ResourceAvailability ra WHERE ra.resourceId = :resourceId "),
- @NamedQuery(name = ResourceAvailability.UPDATE_BY_AGENT_ID, query = "" //
+ @NamedQuery(name = ResourceAvailability.UPDATE_PLATFORM_BY_AGENT_ID, query = "" //
+ " UPDATE ResourceAvailability " //
+ " SET availabilityType = :availabilityType " //
+ " WHERE resourceId IN ( SELECT res.id " //
+ " FROM Resource res " //
- + " WHERE res.agent.id = :agentId ) "),
+ + " WHERE res.agent.id = :agentId " //
+ + " AND res.parentResource IS NULL )"),
+ @NamedQuery(name = ResourceAvailability.UPDATE_CHILD_BY_AGENT_ID, query = "" //
+ + " UPDATE ResourceAvailability " //
+ + " SET availabilityType = :availabilityType " //
+ + " WHERE resourceId IN ( SELECT res.id " //
+ + " FROM Resource res " //
+ + " WHERE res.agent.id = :agentId " //
+ + " AND res.parentResource IS NOT NULL )"),
@NamedQuery(name = ResourceAvailability.INSERT_BY_RESOURCE_IDS, query = "" //
+ " INSERT INTO ResourceAvailability ( resourceId ) " //
+ " SELECT res.id " //
@@ -86,7 +94,8 @@ public class ResourceAvailability implements Serializable {
public static final String TABLE_NAME = "RHQ_RESOURCE_AVAIL";
public static final String QUERY_FIND_BY_RESOURCE_ID = "ResourceAvailability.findByResourceId";
- public static final String UPDATE_BY_AGENT_ID = "ResourceAvailability.updateByAgentId";
+ public static final String UPDATE_CHILD_BY_AGENT_ID = "ResourceAvailability.updateChildByAgentId";
+ public static final String UPDATE_PLATFORM_BY_AGENT_ID = "ResourceAvailability.updatePlatformByAgentId";
public static final String INSERT_BY_RESOURCE_IDS = "ResourceAvailability.insertByResourceIds";
public static final String QUERY_IS_AGENT_BACKFILLED = "ResourceAvailability.isAgentBackfilled";
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerBean.java
index 8cfaf4e..d851761 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerBean.java
@@ -218,7 +218,7 @@ public class AgentManagerBean implements AgentManagerLocal {
public void checkForSuspectAgents() {
log.debug("Checking to see if there are agents that we suspect are down...");
- long maximumQuietTimeAllowed = 900000L;
+ long maximumQuietTimeAllowed = 300000L;
try {
String prop = systemManager.getSystemSettings(subjectManager.getOverlord()).get(
SystemSetting.AGENT_MAX_QUIET_TIME_ALLOWED);
@@ -280,14 +280,35 @@ public class AgentManagerBean implements AgentManagerLocal {
// problems
AvailabilityReportSerializer.getSingleton().lock(agentName);
try {
+ // This marks the Agent as backfilled=true
agentManager.setAgentBackfilled(agentId, true);
- availabilityManager.setAllAgentResourceAvailabilities(agentId, AvailabilityType.UNKNOWN);
+
+ // This marks the top-level platform DOWN since we have not heard from it and all
+ // child resources UNKNOWN since they are not reporting and may very well be up
+ availabilityManager.updateAgentResourceAvailabilities(agentId, AvailabilityType.DOWN,
+ AvailabilityType.UNKNOWN);
} finally {
AvailabilityReportSerializer.getSingleton().unlock(agentName);
}
}
+ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
+ public void setAgentBackfilled(int agentId, boolean backfilled) {
+ Query query = entityManager.createNamedQuery(Agent.QUERY_SET_AGENT_BACKFILLED);
+ query.setParameter("agentId", agentId);
+ query.setParameter("backfilled", backfilled);
+ query.executeUpdate();
+ }
+
+ public boolean isAgentBackfilled(int agentId) {
+ // query returns 0 if the agent's platform is DOWN (or does not exist), 1 if not
+ Query query = entityManager.createNamedQuery(Agent.QUERY_IS_AGENT_BACKFILLED);
+ query.setParameter("agentId", agentId);
+ Long backfilledCount = (Long) query.getSingleResult();
+ return backfilledCount != 0L;
+ }
+
@SuppressWarnings("unchecked")
@ExcludeDefaultInterceptors
public List<Agent> getAllAgents() {
@@ -589,22 +610,6 @@ public class AgentManagerBean implements AgentManagerLocal {
query.executeUpdate();
}
- @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
- public void setAgentBackfilled(int agentId, boolean backfilled) {
- Query query = entityManager.createNamedQuery(Agent.QUERY_SET_AGENT_BACKFILLED);
- query.setParameter("agentId", agentId);
- query.setParameter("backfilled", backfilled);
- query.executeUpdate();
- }
-
- public boolean isAgentBackfilled(int agentId) {
- // query returns 0 if the agent's platform is DOWN (or does not exist), 1 if not
- Query query = entityManager.createNamedQuery(Agent.QUERY_IS_AGENT_BACKFILLED);
- query.setParameter("agentId", agentId);
- Long backfilledCount = (Long) query.getSingleResult();
- return backfilledCount != 0L;
- }
-
@ExcludeDefaultInterceptors
public Boolean pingAgentByResourceId(Subject subject, int resourceId) {
Boolean pingResults = Boolean.FALSE;
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerLocal.java
index 6295fcc..afd566b 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerLocal.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerLocal.java
@@ -278,7 +278,7 @@ public interface AgentManagerLocal {
*/
File getAgentDownloadDir() throws Exception;
- public void setAgentBackfilled(int agentId, boolean backfilled);
+ void setAgentBackfilled(int agentId, boolean backfilled);
/**
* Returns <code>true</code> if the agent is "suspect" and has been backfilled. A "suspect agent" means one that the
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/AvailabilityManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/AvailabilityManagerBean.java
index 80c1ff0..2c8d376 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/AvailabilityManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/AvailabilityManagerBean.java
@@ -129,8 +129,7 @@ public class AvailabilityManagerBean implements AvailabilityManagerLocal, Availa
Resource resource = resourceManager.getResourceById(subject, resourceId);
List<Availability> availList = resource.getAvailability();
if ((availList != null) && (availList.size() > 0)) {
- log
- .warn("Could not query for latest avail but found one - missing null end time (this should never happen)");
+ log.warn("Could not query for latest avail but found one - missing null end time (this should never happen)");
retAvailability = availList.get(availList.size() - 1);
} else {
retAvailability = new Availability(resource, new Date(), null);
@@ -508,10 +507,8 @@ public class AvailabilityManagerBean implements AvailabilityManagerLocal, Availa
} else {
log.error("Could not figure out which agent sent availability report. "
+ "This error is harmless and should stop appearing after a short while if the platform of the agent ["
- + agentName
- + "] was recently removed. In any other case this is a bug."
- + report);
- }
+ + agentName + "] was recently removed. In any other case this is a bug." + report);
+ }
return true; // everything is OK and things look to be in sync
}
@@ -549,16 +546,29 @@ public class AvailabilityManagerBean implements AvailabilityManagerLocal, Availa
@SuppressWarnings("unchecked")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
- public void setAllAgentResourceAvailabilities(int agentId, AvailabilityType availabilityType) {
- String typeString = (availabilityType != null) ? availabilityType.toString() : "unknown";
+ public void updateAgentResourceAvailabilities(int agentId, AvailabilityType platformAvailType,
+ AvailabilityType childAvailType) {
+
+ platformAvailType = (null == platformAvailType) ? AvailabilityType.UNKNOWN : platformAvailType;
+ childAvailType = (null == childAvailType) ? AvailabilityType.UNKNOWN : childAvailType;
+
+ // get the platform resource as well as all child resources not already at childAvailType (since these are the
+ // ones we need to change)
+ Query query = entityManager
+ .createNamedQuery(Availability.FIND_PLATFORM_COMPOSITE_BY_AGENT_AND_NONMATCHING_TYPE);
+ query.setParameter("agentId", agentId);
+ query.setParameter("availabilityType", platformAvailType);
+ // should be 0 or 1 entry
+ List<ResourceIdWithAvailabilityComposite> platformResourcesWithStatus = query.getResultList();
- // get all resources that are not already of the given availability type (since these are the ones we need to change)
- Query query = entityManager.createNamedQuery(Availability.FIND_NONMATCHING_WITH_RESOURCE_ID_BY_AGENT_AND_TYPE);
+ // get the platform resource as well as all child resources not already at childAvailType (since these are the
+ // ones we need to change)
+ query = entityManager.createNamedQuery(Availability.FIND_CHILD_COMPOSITE_BY_AGENT_AND_NONMATCHING_TYPE);
query.setParameter("agentId", agentId);
- query.setParameter("availabilityType", availabilityType);
+ query.setParameter("availabilityType", childAvailType);
List<ResourceIdWithAvailabilityComposite> resourcesWithStatus = query.getResultList();
- // The above query only returns resources if they have at least one row in Availability.
+ // The above queries only return resources if they have at least one row in Availability.
// This may be a problem in the future, and may need to be fixed.
// If a resource has 0 rows of availability, then it is by definition "unknown". If,
// availabilityType is null, we don't have to do anything since the unknown state hasn't changed.
@@ -570,27 +580,44 @@ public class AvailabilityManagerBean implements AvailabilityManagerLocal, Availa
// (since the agent sends avail reports every 60 seconds or so by default). So this problem might not
// be as bad as first thought.
- log.debug("Agent #[" + agentId + "] is going to have [" + resourcesWithStatus.size()
- + "] resources backfilled with [" + typeString + "]");
+ if (log.isDebugEnabled()) {
+ log.debug("Agent #[" + agentId + "] is going to have [" + resourcesWithStatus.size()
+ + "] resources backfilled with [" + childAvailType.getName() + "]");
+ }
Date now = new Date();
- // for those resources that have a current availability status that is different, change them
- List<Availability> newAvailabilities = new ArrayList<Availability>(resourcesWithStatus.size());
+ int newAvailsSize = platformResourcesWithStatus.size() + resourcesWithStatus.size();
+ List<Availability> newAvailabilities = new ArrayList<Availability>(newAvailsSize);
+
+ // if the platform is being set to a new status handle it now
+ if (!platformResourcesWithStatus.isEmpty()) {
+ Availability newAvailabilityInterval = getNewInterval(platformResourcesWithStatus.get(0), now,
+ platformAvailType);
+ if (newAvailabilityInterval != null) {
+ newAvailabilities.add(newAvailabilityInterval);
+ }
+
+ resourceAvailabilityManager.updateAgentResourcesLatestAvailability(agentId, platformAvailType, true);
+ }
+
+ // for those resources that have a current availability status that is different, change them
for (ResourceIdWithAvailabilityComposite record : resourcesWithStatus) {
- Availability newAvailabilityInterval = getNewInterval(record, now, availabilityType);
+ Availability newAvailabilityInterval = getNewInterval(record, now, childAvailType);
if (newAvailabilityInterval != null) {
newAvailabilities.add(newAvailabilityInterval);
}
}
- resourceAvailabilityManager.updateAllResourcesAvailabilitiesForAgent(agentId, availabilityType);
+ resourceAvailabilityManager.updateAgentResourcesLatestAvailability(agentId, childAvailType, false);
// To handle backfilling process, which will mark them down
- notifyAlertConditionCacheManager("setAllAgentResourceAvailabilities", newAvailabilities
- .toArray(new Availability[newAvailabilities.size()]));
+ notifyAlertConditionCacheManager("setAllAgentResourceAvailabilities",
+ newAvailabilities.toArray(new Availability[newAvailabilities.size()]));
- log.debug("Resources for agent #[" + agentId + "] have been fully backfilled with [" + typeString + "]");
+ if (log.isDebugEnabled()) {
+ log.debug("Resources for agent #[" + agentId + "] have been fully backfilled.");
+ }
return;
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/AvailabilityManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/AvailabilityManagerLocal.java
index 1baa788..55327fb 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/AvailabilityManagerLocal.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/AvailabilityManagerLocal.java
@@ -136,13 +136,16 @@ public interface AvailabilityManagerLocal {
void updateLastAvailabilityReport(int agentId);
/**
- * Sets all availabilities for all resources managed by the given agent to the given availability type (which may be
- * <code>null</code> to indicate unknown).
+ * Update availabilities for all resources managed by the given agent to the given availability type (which may be
+ * <code>null</code> to indicate unknown). NOTE: This does not include the top-level platform resource for
+ * the agent. To update a single resource avail see {@link #updateResourceAvailability(Subject, Availability)}.
*
- * @param agentId all resources managed by this agent will have their availabilities changed
- * @param availabilityType the type that all of the agent's resources will have
+ * @param agentId all resources managed by this agent will have their availabilities changed
+ * @param platformAvailabilityType the type that the agent's top level platform resource will have
+ * @param childAvailabilityType the type that the agent's child resources will have
*/
- void setAllAgentResourceAvailabilities(int agentId, AvailabilityType availabilityType);
+ void updateAgentResourceAvailabilities(int agentId, AvailabilityType platformAvailabilityType,
+ AvailabilityType childAvailabilityType);
List<Availability> findAvailabilityWithinInterval(int resourceId, Date startDate, Date endDate);
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerBean.java
index e8e90b2..7a2e021 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerBean.java
@@ -131,11 +131,12 @@ public class ResourceAvailabilityManagerBean implements ResourceAvailabilityMana
int[] resourceIdArray = ArrayUtils.unwrapCollection(resourceIds);
int fromIndex = 0;
while (fromIndex < resourceIdArray.length) {
- int toIndex = (resourceIdArray.length < (fromIndex + 1000)) ? resourceIdArray.length : (fromIndex + 1000);
+ int toIndex = (resourceIdArray.length < (fromIndex + 1000)) ? resourceIdArray.length
+ : (fromIndex + 1000);
int[] resourceIdSubArray = Arrays.copyOfRange(resourceIdArray, fromIndex, toIndex);
String transformedQuery = JDBCUtil.transformQueryForMultipleInParameters(query, ":resourceIds",
- resourceIdSubArray.length);
+ resourceIdSubArray.length);
ps = conn.prepareStatement(transformedQuery);
JDBCUtil.bindNTimes(ps, resourceIdSubArray, 1);
ps.execute();
@@ -170,14 +171,16 @@ public class ResourceAvailabilityManagerBean implements ResourceAvailabilityMana
Throwable cause = re.getCause();
if (cause instanceof SQLException) {
log.error("Failed to get latest avail for Resource [" + resourceId + "]: "
- + JDBCUtil.convertSQLExceptionToString((SQLException)cause));
+ + JDBCUtil.convertSQLExceptionToString((SQLException) cause));
}
throw re;
}
}
- public void updateAllResourcesAvailabilitiesForAgent(int agentId, AvailabilityType availabilityType) {
- Query query = entityManager.createNamedQuery(ResourceAvailability.UPDATE_BY_AGENT_ID);
+ public void updateAgentResourcesLatestAvailability(int agentId, AvailabilityType availabilityType,
+ boolean isPlatform) {
+ Query query = entityManager.createNamedQuery((isPlatform) ? ResourceAvailability.UPDATE_PLATFORM_BY_AGENT_ID
+ : ResourceAvailability.UPDATE_CHILD_BY_AGENT_ID);
query.setParameter("availabilityType", availabilityType);
query.setParameter("agentId", agentId);
query.executeUpdate();
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerLocal.java
index cc86006..b507d2e 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerLocal.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerLocal.java
@@ -24,8 +24,8 @@ import javax.ejb.Local;
import javax.persistence.EntityManager;
import javax.persistence.PostPersist;
-import org.rhq.core.domain.auth.Subject;
import org.rhq.core.clientapi.server.discovery.InventoryReport;
+import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.measurement.AvailabilityType;
import org.rhq.core.domain.measurement.ResourceAvailability;
import org.rhq.core.domain.resource.InventoryStatus;
@@ -76,9 +76,12 @@ public interface ResourceAvailabilityManagerLocal {
ResourceAvailability getLatestAvailability(int resourceId);
/**
- * Marks all resources managed by the specified agent as down
- *
+ * Update latest availabilities for all resources managed by the given agent to the given availability type.
+ * NOTE: This does not include the top-level platform resource for the agent.
+ *
* @param agentId the id of the agent
+ * @param availabilityType the type that all of the agent's resources will have *
+ * @param isPlatform if true, updates only the agent's top level platform, if false only the children
*/
- void updateAllResourcesAvailabilitiesForAgent(int agentId, AvailabilityType availabilityType);
+ void updateAgentResourcesLatestAvailability(int agentId, AvailabilityType availabilityType, boolean isPlatform);
}
\ No newline at end of file
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/AvailabilityManagerTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/AvailabilityManagerTest.java
index 739b8d3..492a700 100644
--- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/AvailabilityManagerTest.java
+++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/test/AvailabilityManagerTest.java
@@ -56,7 +56,7 @@ import org.rhq.enterprise.server.util.LookupUtil;
* @author John Mazzitelli
*/
public class AvailabilityManagerTest extends AbstractEJB3Test {
- private static final boolean ENABLE_TESTS = false;
+ // private static final boolean ENABLE_TESTS = false;
private static final AvailabilityType UP = AvailabilityType.UP;
private static final AvailabilityType DOWN = AvailabilityType.DOWN;
@@ -110,7 +110,7 @@ public class AvailabilityManagerTest extends AbstractEJB3Test {
theResource = null;
}
- if (additionalResources!=null) {
+ if (additionalResources != null) {
getTransactionManager().begin();
EntityManager em = getEntityManager();
@@ -179,7 +179,7 @@ public class AvailabilityManagerTest extends AbstractEJB3Test {
q.setParameter("resourceId", theResource.getId());
List<Availability> avails = q.getResultList();
- assert avails.size()==2 : "Did not get 2 availabilities but " + avails.size(); // TODO Wrong assumption ?
+ assert avails.size() == 2 : "Did not get 2 availabilities but " + avails.size(); // TODO Wrong assumption ?
} catch (Exception e) {
e.printStackTrace();
@@ -192,7 +192,6 @@ public class AvailabilityManagerTest extends AbstractEJB3Test {
}
}
-
@SuppressWarnings("unchecked")
@Test(enabled = true)
public void testPurgeAvailabilities() throws Exception {
@@ -274,8 +273,8 @@ public class AvailabilityManagerTest extends AbstractEJB3Test {
AvailabilityReport report = new AvailabilityReport(false, theAgent.getName());
- availPoints = availabilityManager.findAvailabilitiesForResource(overlord, theResource.getId(), 1, System
- .currentTimeMillis(), 3, false);
+ availPoints = availabilityManager.findAvailabilitiesForResource(overlord, theResource.getId(), 1,
+ System.currentTimeMillis(), 3, false);
assert availPoints.size() == 3 : "There is no avail data, but should still get 3 availability points";
assert availPoints.get(0).getValue() == DOWN.ordinal(); // aka unknown
assert availPoints.get(1).getValue() == DOWN.ordinal(); // aka unknown
@@ -409,11 +408,11 @@ public class AvailabilityManagerTest extends AbstractEJB3Test {
persistAvailability(avail);
assert availabilityManager.getCurrentAvailabilityTypeForResource(overlord, theResource.getId()) == null;
- availabilityManager.setAllAgentResourceAvailabilities(theAgent.getId(), UP);
+ availabilityManager.updateAgentResourceAvailabilities(theAgent.getId(), UP, UP);
assert availabilityManager.getCurrentAvailabilityTypeForResource(overlord, theResource.getId()) == UP;
- availabilityManager.setAllAgentResourceAvailabilities(theAgent.getId(), DOWN);
+ availabilityManager.updateAgentResourceAvailabilities(theAgent.getId(), DOWN, DOWN);
assert availabilityManager.getCurrentAvailabilityTypeForResource(overlord, theResource.getId()) == DOWN;
- availabilityManager.setAllAgentResourceAvailabilities(theAgent.getId(), DOWN); // extend it
+ availabilityManager.updateAgentResourceAvailabilities(theAgent.getId(), DOWN, DOWN); // extend it
assert availabilityManager.getCurrentAvailabilityTypeForResource(overlord, theResource.getId()) == DOWN;
} catch (Exception e) {
e.printStackTrace();
@@ -858,8 +857,8 @@ public class AvailabilityManagerTest extends AbstractEJB3Test {
avail = new Availability(theResource, date6, AvailabilityType.DOWN);
persistAvailability(avail);
- List<AvailabilityPoint> points = availabilityManager.findAvailabilitiesForResource(overlord, theResource
- .getId(), date1.getTime(), date6.getTime(), 5, false);
+ List<AvailabilityPoint> points = availabilityManager.findAvailabilitiesForResource(overlord,
+ theResource.getId(), date1.getTime(), date6.getTime(), 5, false);
assert points.size() == 5;
assert points.get(0).getValue() == 1;
assert points.get(1).getValue() == 0;
@@ -938,8 +937,8 @@ public class AvailabilityManagerTest extends AbstractEJB3Test {
assert new Date(agent.getLastAvailabilityReport()).after(lastReport);
assert countAvailabilitiesInDB(null) == (allAvailCount + 1);
assert availabilityManager.getCurrentAvailabilityTypeForResource(overlord, theResource.getId()) == DOWN;
- Availability queriedAvail = availabilityManager.getCurrentAvailabilityForResource(overlord, theResource
- .getId());
+ Availability queriedAvail = availabilityManager.getCurrentAvailabilityForResource(overlord,
+ theResource.getId());
assert queriedAvail.getId() > 0;
assert queriedAvail.getAvailabilityType() == avail.getAvailabilityType();
assert Math.abs(queriedAvail.getStartTime().getTime() - avail.getStartTime().getTime()) < 1000;
commit 99e61a966cb2877c1434ab60ea04ebeee6b2d1e8
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Fri Feb 3 15:00:53 2012 -0500
Drop AGENT_MAX_QUIET_TIME_ALLOWED config setting from 15 to 5 minutes in
the db-upgrade.
diff --git a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml
index 76d77ed..8b93489 100644
--- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml
+++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml
@@ -3851,6 +3851,15 @@
</schema-directSQL>
</schemaSpec>
+ <!-- Drop agent quiet time (i.e. suspect agent time) from 15 to 5 minutes -->
+ <schema-directSQL>
+ <statement desc="Changing AGENT_MAX_QUIET_TIME_ALLOWED to 5 minutes from 15 minutes">
+ UPDATE RHQ_SYSTEM_CONFIG
+ SET PROPERTY_VALUE = '300000', DEFAULT_PROPERTY_VALUE = '300000'
+ WHERE PROPERTY_KEY = 'AGENT_MAX_QUIET_TIME_ALLOWED'
+ </statement>
+ </schema-directSQL>
+
</dbupgrade>
</target>
</project>
12 years, 4 months
[rhq] modules/enterprise
by ips
modules/enterprise/agent/src/etc/rhq-agent-env.bat | 9 ++++++---
modules/enterprise/agent/src/etc/rhq-agent-env.sh | 9 ++++++---
2 files changed, 12 insertions(+), 6 deletions(-)
New commits:
commit 0ed38f2bf952d9cf773e092856b93f1d438fcabe
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Fri Feb 3 13:17:37 2012 -0500
[787250] add comment telling user not to include the --daemon option in
RHQ_AGENT_CMDLINE_OPTS (https://bugzilla.redhat.com/show_bug.cgi?id=787250)
diff --git a/modules/enterprise/agent/src/etc/rhq-agent-env.bat b/modules/enterprise/agent/src/etc/rhq-agent-env.bat
index 7116516..62d727b 100644
--- a/modules/enterprise/agent/src/etc/rhq-agent-env.bat
+++ b/modules/enterprise/agent/src/etc/rhq-agent-env.bat
@@ -103,11 +103,14 @@ rem passed through to the RHQ Agent.
rem If you want to have command line arguments
rem added to the arguments specified here, append
rem '%*' to the end of this option. For example,
-rem "--daemon %*". In this case, both the command
+rem "--nonative %*". In this case, both the command
rem line options and the ones specified here will
-rem be passed to the agent.
+rem be passed to the Agent. Note, the --daemon option
+rem should generally not be included here, since it
+rem would cause the Agent to always start in daemon
+rem mode, even when started via rhq-agent.bat.
rem
-rem set RHQ_AGENT_CMDLINE_OPTS=--nonative
+rem set RHQ_AGENT_CMDLINE_OPTS=--nonative %*
rem ===========================================================================
rem THE FOLLOWING ARE USED SOLELY FOR THE rhq-agent-wrapper.bat SCRIPT
diff --git a/modules/enterprise/agent/src/etc/rhq-agent-env.sh b/modules/enterprise/agent/src/etc/rhq-agent-env.sh
index bb679ef..c7a259e 100755
--- a/modules/enterprise/agent/src/etc/rhq-agent-env.sh
+++ b/modules/enterprise/agent/src/etc/rhq-agent-env.sh
@@ -99,11 +99,14 @@
# If you want to have command line arguments
# added to the arguments specified here, append
# '$*' to the end of this option. For example,
-# "--daemon $*". In this case, both the command
+# "--nonative $*". In this case, both the command
# line options and the ones specified here will
-# be passed to the agent.
+# be passed to the Agent. Note, the --daemon option
+# should generally not be included here, since it
+# would cause the Agent to always start in daemon
+# mode, even when started via rhq-agent.sh.
#
-#RHQ_AGENT_CMDLINE_OPTS="--daemon --nonative"
+#RHQ_AGENT_CMDLINE_OPTS="--nonative $*"
# RHQ_AGENT_IN_BACKGROUND - If this is defined, the RHQ Agent JVM will
# be launched in the background (thus causing this
12 years, 4 months
[rhq] modules/core
by mazz
modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java | 10 ++++++++++
1 file changed, 10 insertions(+)
New commits:
commit 16224a4092762e54928f411026f3c674cf210efa
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Fri Feb 3 13:11:27 2012 -0500
[BZ 773031] enhance test to check and make sure the state is set properly
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
index 39ae23d..f35965a 100644
--- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
+++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
@@ -35,7 +35,9 @@ import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.pc.PluginContainer;
import org.rhq.core.pc.ServerServices;
+import org.rhq.core.pc.inventory.InventoryManager;
import org.rhq.core.pc.inventory.ResourceContainer;
+import org.rhq.core.pc.inventory.ResourceContainer.ResourceComponentState;
import org.rhq.test.pc.PluginContainerSetup;
import org.rhq.test.pc.PluginContainerTest;
@@ -299,6 +301,14 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase {
assertEquals(discoveredResource.getName(), "resource-name-v1");
assertEquals(discoveredResource.getDescription(), "resource-description-v1");
+ InventoryManager im = PluginContainer.getInstance().getInventoryManager();
+ ResourceContainer container = im.getResourceContainer(discoveredResource.getId());
+ if (discoveredResource.getInventoryStatus() == InventoryStatus.COMMITTED) {
+ assert container.getResourceComponentState() == ResourceComponentState.STARTED;
+ } else {
+ assert container.getResourceComponentState() == ResourceComponentState.STOPPED;
+ }
+
return inv;
}
12 years, 4 months
[rhq] Branch 'feature/gwt-upgrade' - modules/enterprise
by John Sanda
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ViewPath.java | 2 -
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java | 17 ++++++++++
2 files changed, 18 insertions(+), 1 deletion(-)
New commits:
commit b340d788cb663411d93bd3116acf52d4512f26b7
Author: John Sanda <jsanda(a)redhat.com>
Date: Fri Feb 3 10:50:05 2012 -0500
[BZ 742698] Send user to history page for operation scheduled immediately
With this commit, the user will now be sent to the history page when an
operation is scheduled for immediate execution. This change applies both
at the resource and group level.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ViewPath.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ViewPath.java
index e448610..5d66f5d 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ViewPath.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ViewPath.java
@@ -83,7 +83,7 @@ public class ViewPath {
return getPathToIndex(this.index);
}
- private String getPathToIndex(int endIndex) {
+ public String getPathToIndex(int endIndex) {
String path = "";
for (int i = 0; i < endIndex; i++) {
if (i > 0) {
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java
index c06a8b1..192711f 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java
@@ -45,6 +45,7 @@ import org.rhq.core.domain.operation.OperationDefinition;
import org.rhq.core.domain.resource.ResourceType;
import org.rhq.enterprise.gui.coregui.client.CoreGUI;
import org.rhq.enterprise.gui.coregui.client.UserSessionManager;
+import org.rhq.enterprise.gui.coregui.client.ViewId;
import org.rhq.enterprise.gui.coregui.client.ViewPath;
import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor;
import org.rhq.enterprise.gui.coregui.client.components.form.*;
@@ -52,6 +53,7 @@ import org.rhq.enterprise.gui.coregui.client.components.trigger.JobTriggerEditor
import org.rhq.enterprise.gui.coregui.client.gwt.ConfigurationGWTServiceAsync;
import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.schedule.ResourceOperationScheduleDataSource;
+import org.rhq.enterprise.gui.coregui.client.operation.OperationHistoryView;
import org.rhq.enterprise.gui.coregui.client.util.FormUtility;
import org.rhq.enterprise.gui.coregui.client.util.TypeConversionUtility;
import org.rhq.enterprise.gui.coregui.client.util.message.Message;
@@ -85,6 +87,8 @@ public abstract class AbstractOperationScheduleDetailsView extends
private JobTriggerEditor triggerEditor;
private EnhancedDynamicForm notesForm;
private Integer operationDefinitionId;
+ private ViewPath viewPath;
+ private boolean isImmediateExecution;
public AbstractOperationScheduleDetailsView(String locatorId, AbstractOperationScheduleDataSource dataSource,
ResourceType resourceType, int scheduleId) {
@@ -104,7 +108,19 @@ public abstract class AbstractOperationScheduleDetailsView extends
protected abstract boolean hasControlPermission();
@Override
+ public String getListViewPath() {
+ // If the operation is scheduled for immediate execution, we will send the user
+ // to the history page so that he can view the status/result of the operation;
+ // otherwise, the user will stay on the schedules list view.
+ if (isImmediateExecution) {
+ return viewPath.getPathToIndex(viewPath.getCurrentIndex() - 2) + "/History";
+ }
+ return super.getListViewPath();
+ }
+
+ @Override
public void renderView(ViewPath viewPath) {
+ this.viewPath = viewPath;
super.renderView(viewPath);
// If the operationDefId has been seeded capture it now
@@ -344,6 +360,7 @@ public abstract class AbstractOperationScheduleDetailsView extends
Record jobTriggerRecord = new ListGridRecord();
Date startTime = this.triggerEditor.getStartTime();
+ isImmediateExecution = startTime == null;
jobTriggerRecord.setAttribute(AbstractOperationScheduleDataSource.Field.START_TIME, startTime);
Date endTime = this.triggerEditor.getEndTime();
12 years, 4 months
[rhq] modules/enterprise modules/integration-tests
by lkrejci
modules/enterprise/server/itests/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java | 26 +++++-----
modules/integration-tests/jndi-access/jndi-access-test/src/test/java/org/rhq/jndi/test/JndiAccessTest.java | 15 ++---
2 files changed, 19 insertions(+), 22 deletions(-)
New commits:
commit cb78bd893aa614d0fcc5760f2a25a73175fe6c2e
Author: Lukas Krejci <lkrejci(a)redhat.com>
Date: Fri Feb 3 14:12:51 2012 +0100
update the JNDI access tests to not use the "context" variable which seems
to be predefined.
diff --git a/modules/enterprise/server/itests/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java b/modules/enterprise/server/itests/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java
index f6772e5..06fc76a 100644
--- a/modules/enterprise/server/itests/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java
+++ b/modules/enterprise/server/itests/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java
@@ -67,8 +67,8 @@ public class JndiAccessTest extends AbstractEJB3Test {
try {
engine.eval(""
- + "context = new javax.naming.InitialContext();\n"
- + "subjectManager = context.lookup('SubjectManagerBean/local');\n"
+ + "var ctx = new javax.naming.InitialContext();\n"
+ + "var subjectManager = ctx.lookup('SubjectManagerBean/local');\n"
+ "subjectManager.getOverlord();");
Assert.fail("The script shouldn't have been able to call local SLSB method.");
@@ -84,8 +84,8 @@ public class JndiAccessTest extends AbstractEJB3Test {
try {
engine.eval(""
- + "context = new javax.naming.InitialContext();\n"
- + "subjectManager = context.lookup('SubjectManagerBean/remote');\n"
+ + "var ctx = new javax.naming.InitialContext();\n"
+ + "var subjectManager = ctx.lookup('SubjectManagerBean/remote');\n"
+ "subjectManager.getSubjectByName('rhqadmin');");
Assert.fail("The script shouldn't have been able to call remote SLSB method directly.");
@@ -133,8 +133,8 @@ public class JndiAccessTest extends AbstractEJB3Test {
try {
engine.eval(""
- + "context = new javax.naming.InitialContext();\n"
- + "datasource = context.lookup('java:/RHQDS');\n"
+ + "var ctx = new javax.naming.InitialContext();\n"
+ + "var datasource = ctx.lookup('java:/RHQDS');\n"
+ "con = datasource.getConnection();");
Assert.fail("The script shouldn't have been able to obtain the datasource from the JNDI.");
@@ -150,9 +150,9 @@ public class JndiAccessTest extends AbstractEJB3Test {
try {
engine.eval(""
- + "context = new javax.naming.InitialContext();\n"
- + "entityManagerFactory = context.lookup('java:/RHQEntityManagerFactory');\n"
- + "entityManager = entityManagerFactory.createEntityManager();\n"
+ + "var ctx = new javax.naming.InitialContext();\n"
+ + "var entityManagerFactory = ctx.lookup('java:/RHQEntityManagerFactory');\n"
+ + "var entityManager = entityManagerFactory.createEntityManager();\n"
+ "entityManager.find(java.lang.Class.forName('org.rhq.core.domain.resource.Resource'), java.lang.Integer.valueOf('10001'));");
Assert.fail("The script shouldn't have been able to use the EntityManager.");
@@ -163,12 +163,12 @@ public class JndiAccessTest extends AbstractEJB3Test {
//try harder with manually specifying the initial context factory
try {
engine.eval(""
- + "env = new java.util.Hashtable();"
+ + "var env = new java.util.Hashtable();"
+ "env.put('java.naming.factory.initial', 'org.jnp.interfaces.LocalOnlyContextFactory');"
+ "env.put('java.naming.factory.url.pkgs', 'org.jboss.naming:org.jnp.interfaces');"
- + "context = new javax.naming.InitialContext(env);\n"
- + "entityManagerFactory = context.lookup('java:/RHQEntityManagerFactory');\n"
- + "entityManager = entityManagerFactory.createEntityManager();\n"
+ + "var ctx = new javax.naming.InitialContext(env);\n"
+ + "var entityManagerFactory = ctx.lookup('java:/RHQEntityManagerFactory');\n"
+ + "var entityManager = entityManagerFactory.createEntityManager();\n"
+ "entityManager.find(java.lang.Class.forName('org.rhq.core.domain.resource.Resource'), java.lang.Integer.valueOf('10001'));");
Assert.fail("The script shouldn't have been able to use the EntityManager even using custom initial context factory.");
diff --git a/modules/integration-tests/jndi-access/jndi-access-test/src/test/java/org/rhq/jndi/test/JndiAccessTest.java b/modules/integration-tests/jndi-access/jndi-access-test/src/test/java/org/rhq/jndi/test/JndiAccessTest.java
index c6140a0..3c4f530 100644
--- a/modules/integration-tests/jndi-access/jndi-access-test/src/test/java/org/rhq/jndi/test/JndiAccessTest.java
+++ b/modules/integration-tests/jndi-access/jndi-access-test/src/test/java/org/rhq/jndi/test/JndiAccessTest.java
@@ -24,8 +24,6 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
-import java.io.SerializablePermission;
-import java.security.PermissionCollection;
import java.util.Collections;
import java.util.Properties;
@@ -41,7 +39,6 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
-import org.rhq.bindings.SandboxedScriptEngine;
import org.rhq.bindings.ScriptEngineFactory;
import org.rhq.bindings.StandardBindings;
import org.rhq.bindings.StandardScriptPermissions;
@@ -145,9 +142,9 @@ public class JndiAccessTest extends AbstractEJB3Test {
try {
engine.eval(""
- + "context = new javax.naming.InitialContext();\n"
- + "entityManagerFactory = context.lookup('java:/RHQEntityManagerFactory');\n"
- + "entityManager = entityManagerFactory.createEntityManager();\n"
+ + "var ctx = new javax.naming.InitialContext();\n"
+ + "var entityManagerFactory = ctx.lookup('java:/RHQEntityManagerFactory');\n"
+ + "var entityManager = entityManagerFactory.createEntityManager();\n"
+ "entityManager.find(java.lang.Class.forName('org.rhq.core.domain.resource.Resource'), java.lang.Integer.valueOf('10001'));");
Assert.fail("The script shouldn't have been able to use the EntityManager.");
@@ -164,11 +161,11 @@ public class JndiAccessTest extends AbstractEJB3Test {
try {
engine.eval(""
- + "env = new java.util.Hashtable();"
+ + "var env = new java.util.Hashtable();"
+ "env.put('java.naming.factory.initial', 'org.jboss.naming.NamingContextFactory');"
+ "env.put('java.naming.provider.url', 'jnp://localhost:" + jnpPort + "');"
- + "context = new javax.naming.InitialContext(env);\n"
- + "kachny = context.lookup('kachny');\n"
+ + "var ctx = new javax.naming.InitialContext(env);\n"
+ + "var kachny = ctx.lookup('kachny');\n"
+ "assertNotNull(kachny);\n");
} catch (ScriptException e) {
Assert.fail("The script should have been able to access a remote JNDI server.", e);
12 years, 4 months