[rhq] 3 commits - modules/common modules/plugins
by John Sanda
modules/common/cassandra-ccm/cassandra-ccm-core/src/main/bundle/cassandra/conf/cassandra-jvm.properties | 2
modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java | 16 ++
modules/common/cassandra-util/src/test/java/org/rhq/cassandra/util/ConfigEditorTest.java | 28 +++++
modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeConfigDelegate.java | 55 ++++++++++
modules/plugins/rhq-storage/src/main/resources/META-INF/rhq-plugin.xml | 11 ++
modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeConfigDelegateTest.java | 41 ++++++-
6 files changed, 143 insertions(+), 10 deletions(-)
New commits:
commit 13371f91328e26f66d687196acbc6b7e5aab4bd0
Author: John Sanda <jsanda(a)redhat.com>
Date: Tue Jul 30 14:28:38 2013 -0400
add resource config support for cql and gossip ports in rhq-storage plugin
diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/bundle/cassandra/conf/cassandra-jvm.properties b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/bundle/cassandra/conf/cassandra-jvm.properties
index 1faee9d..2eb5ab5 100644
--- a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/bundle/cassandra/conf/cassandra-jvm.properties
+++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/bundle/cassandra/conf/cassandra-jvm.properties
@@ -13,7 +13,7 @@ heap_new="-Xmn64M"
heap_dump_on_OOMError="-XX:+HeapDumpOnOutOfMemoryError"
-heap_dump_dir=""
+heap_dump_dir=
thread_stack_size="-Xss180k"
diff --git a/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java b/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
index 5276c84..c53c19b 100644
--- a/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
+++ b/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
@@ -108,7 +108,7 @@ public class ConfigEditor {
return (Integer) config.get("native_transport_port");
}
- public void setNativeTransportPort(int port) {
+ public void setNativeTransportPort(Integer port) {
config.put("native_transport_port", port);
}
@@ -116,7 +116,7 @@ public class ConfigEditor {
return (Integer) config.get("storage_port");
}
- public void setStoragePort(int port) {
+ public void setStoragePort(Integer port) {
config.put("storage_port", port);
}
diff --git a/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeConfigDelegate.java b/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeConfigDelegate.java
index dd5b8a2..edaf9f9 100644
--- a/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeConfigDelegate.java
+++ b/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeConfigDelegate.java
@@ -5,6 +5,12 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.yaml.snakeyaml.error.YAMLException;
+
+import org.rhq.cassandra.util.ConfigEditor;
+import org.rhq.cassandra.util.ConfigEditorException;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
import org.rhq.core.domain.configuration.PropertySimple;
@@ -18,12 +24,16 @@ import org.rhq.core.util.StringUtil;
*/
public class StorageNodeConfigDelegate implements ConfigurationFacet {
+ private Log log = LogFactory.getLog(StorageNodeConfigDelegate.class);
+
private File jvmOptsFile;
private File wrapperEnvFile;
+ private File cassandraYamlFile;
public StorageNodeConfigDelegate(File basedir) {
File confDir = new File(basedir, "conf");
jvmOptsFile = new File(confDir, "cassandra-jvm.properties");
+ cassandraYamlFile = new File(confDir, "cassandra.yaml");
// for windows, config props also get propagated to the wrapper env
if (isWindows()) {
@@ -60,6 +70,11 @@ public class StorageNodeConfigDelegate implements ConfigurationFacet {
config.put(new PropertySimple("heapDumpDir", new File(basedir, "bin").getAbsolutePath()));
}
+ ConfigEditor yamlEditor = new ConfigEditor(cassandraYamlFile);
+ yamlEditor.load();
+ config.put(new PropertySimple("cqlPort", yamlEditor.getNativeTransportPort()));
+ config.put(new PropertySimple("gossipPort", yamlEditor.getStoragePort()));
+
return config;
}
@@ -135,6 +150,7 @@ public class StorageNodeConfigDelegate implements ConfigurationFacet {
Configuration config = configurationUpdateReport.getConfiguration();
updateCassandraJvmProps(config);
+ updateCassandraYaml(config);
if (isWindows()) {
updateWrapperEnv(config);
@@ -145,6 +161,8 @@ public class StorageNodeConfigDelegate implements ConfigurationFacet {
configurationUpdateReport.setErrorMessage("No configuration update was applied: " + e.getMessage());
} catch (IOException e) {
configurationUpdateReport.setErrorMessageFromThrowable(e);
+ } catch (ConfigEditorException e) {
+ configurationUpdateReport.setErrorMessageFromThrowable(e);
}
}
@@ -195,6 +213,43 @@ public class StorageNodeConfigDelegate implements ConfigurationFacet {
propertiesUpdater.update(properties);
}
+ private void updateCassandraYaml(Configuration newConfig) {
+ ConfigEditor editor = new ConfigEditor(cassandraYamlFile);
+ try {
+ editor.load();
+
+ PropertySimple cqlPortProperty = newConfig.getSimple("cqlPort");
+ if (cqlPortProperty != null) {
+ editor.setNativeTransportPort(cqlPortProperty.getIntegerValue());
+ }
+
+ PropertySimple gossipPortProperty = newConfig.getSimple("gossipPort");
+ if (gossipPortProperty != null) {
+ editor.setStoragePort(gossipPortProperty.getIntegerValue());
+ }
+
+ editor.save();
+ } catch (ConfigEditorException e) {
+ if (e.getCause() instanceof YAMLException) {
+ log.error("Failed to update " + cassandraYamlFile);
+ log.info("Attempting to restore " + cassandraYamlFile);
+ try {
+ editor.restore();
+ throw e;
+ } catch (ConfigEditorException e1) {
+ log.error("Failed to restore " + cassandraYamlFile + ". A copy of the file prior to any " +
+ "modifications can be found at " + editor.getBackupFile());
+ throw new ConfigEditorException("There was an error updating " + cassandraYamlFile + " and " +
+ "undoing the changes failed. A copy of the file can be found at " + editor.getBackupFile() +
+ ". See the agent logs for more details.", e);
+ }
+ } else {
+ log.error("No updates were made to " + cassandraYamlFile + " due to an unexpected error", e);
+ throw e;
+ }
+ }
+ }
+
private void updateWrapperEnv(Configuration config) throws IOException {
PropertiesFileUpdate propertiesUpdater = new PropertiesFileUpdate(wrapperEnvFile.getAbsolutePath());
Properties properties = propertiesUpdater.loadExistingProperties();
diff --git a/modules/plugins/rhq-storage/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/rhq-storage/src/main/resources/META-INF/rhq-plugin.xml
index f5a4f6d..84bb832 100644
--- a/modules/plugins/rhq-storage/src/main/resources/META-INF/rhq-plugin.xml
+++ b/modules/plugins/rhq-storage/src/main/resources/META-INF/rhq-plugin.xml
@@ -175,6 +175,17 @@
<c:simple-property name="heapDumpDir" displayName="Heap Dump Directory" required="false"
description="The directory in which heap dumps will be written."/>
</c:group>
+ <c:group name="Ports">
+ <c:simple-property name="cqlPort"
+ displayName="CQL Port"
+ type="integer"
+ description="The port on which to listen for client requests over the native, CQL protocol.
+ This is a shared, cluster-wide setting."/>
+ <c:simple-property name="gossipPort"
+ type="integer"
+ description="The port used for internode communication. This is a shared, cluster-wide setting."/>
+
+ </c:group>
</resource-configuration>
<server name="Cassandra Server JVM"
diff --git a/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeConfigDelegateTest.java b/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeConfigDelegateTest.java
index 64d14b2..15861c1 100644
--- a/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeConfigDelegateTest.java
+++ b/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeConfigDelegateTest.java
@@ -6,17 +6,20 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import org.rhq.cassandra.util.ConfigEditor;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
import org.rhq.core.domain.configuration.PropertySimple;
import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport;
import org.rhq.core.util.file.FileUtil;
+import org.rhq.core.util.stream.StreamUtil;
/**
* @author John Sanda
@@ -25,6 +28,8 @@ public class StorageNodeConfigDelegateTest {
private File basedir;
+ private File cassandraYamlFile;
+
private StorageNodeConfigDelegate configDelegate;
@BeforeMethod
@@ -33,6 +38,11 @@ public class StorageNodeConfigDelegateTest {
basedir = new File(dir, getClass().getSimpleName() + "/" + test.getName());
FileUtil.purge(basedir, true);
configDelegate = new StorageNodeConfigDelegate(basedir);
+
+ cassandraYamlFile = new File(confDir(), "cassandra.yaml");
+ InputStream inputStream = getClass().getResourceAsStream("/cassandra.yaml");
+ FileOutputStream outputStream = new FileOutputStream(cassandraYamlFile);
+ StreamUtil.copy(inputStream, outputStream);
}
@@ -55,13 +65,24 @@ public class StorageNodeConfigDelegateTest {
public void updateValidConfig() throws Exception {
createDefaultConfig();
- Configuration config = new Configuration();
- config.put(new PropertySimple("minHeapSize", "1024M"));
- config.put(new PropertySimple("maxHeapSize", "1024M"));
- config.put(new PropertySimple("heapNewSize", "256M"));
- config.put(new PropertySimple("threadStackSize", "240"));
- config.put(new PropertySimple("heapDumpOnOOMError", true));
- config.put(new PropertySimple("heapDumpDir", confDir()));
+ Configuration config = Configuration.builder()
+ .addSimple("minHeapSize", "1024M")
+ .addSimple("maxHeapSize", "1024M")
+ .addSimple("heapNewSize", "256M")
+ .addSimple("threadStackSize", "240")
+ .addSimple("heapDumpOnOOMError", true)
+ .addSimple("heapDumpDir", confDir())
+ .addSimple("cqlPort", 9595)
+ .addSimple("gossipPort", 9696)
+ .build();
+// config.put(new PropertySimple("minHeapSize", "1024M"));
+// config.put(new PropertySimple("maxHeapSize", "1024M"));
+// config.put(new PropertySimple("heapNewSize", "256M"));
+// config.put(new PropertySimple("threadStackSize", "240"));
+// config.put(new PropertySimple("heapDumpOnOOMError", true));
+// config.put(new PropertySimple("heapDumpDir", confDir()));
+// config.put(new PropertySimple("cqlPort", 9595));
+// config.put(new PropertySimple("gossipPort", 9696));
ConfigurationUpdateReport report = new ConfigurationUpdateReport(config);
@@ -78,6 +99,12 @@ public class StorageNodeConfigDelegateTest {
"Failed to update property [heap_dump_on_OOMError]");
assertEquals(properties.getProperty("heap_dump_dir"), confDir().getAbsolutePath(),
"Failed to update property [heap_dump_dir]");
+
+ ConfigEditor yamlEditor = new ConfigEditor(cassandraYamlFile);
+ yamlEditor.load();
+
+ assertEquals(yamlEditor.getNativeTransportPort(), (Integer) 9595, "Failed to update native_transport_port");
+ assertEquals(yamlEditor.getStoragePort(), (Integer) 9696, "Failed to update storage_port");
}
@Test
commit 6de86c41792464bdab2197227ba32df34e77e16d
Author: John Sanda <jsanda(a)redhat.com>
Date: Tue Jul 30 13:17:15 2013 -0400
make dataFileDirectories property read/write
diff --git a/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java b/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
index 9e1f86b..5276c84 100644
--- a/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
+++ b/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
@@ -88,6 +88,10 @@ public class ConfigEditor {
return (List<String>) config.get("data_file_directories");
}
+ public void setDataFileDirectories(List<String> dirs) {
+ config.put("data_file_directories", dirs);
+ }
+
public String getSavedCachesDirectory() {
return (String) config.get("saved_caches_directory");
}
diff --git a/modules/common/cassandra-util/src/test/java/org/rhq/cassandra/util/ConfigEditorTest.java b/modules/common/cassandra-util/src/test/java/org/rhq/cassandra/util/ConfigEditorTest.java
index f339b48..9c3cc16 100644
--- a/modules/common/cassandra-util/src/test/java/org/rhq/cassandra/util/ConfigEditorTest.java
+++ b/modules/common/cassandra-util/src/test/java/org/rhq/cassandra/util/ConfigEditorTest.java
@@ -1,5 +1,6 @@
package org.rhq.cassandra.util;
+import static java.util.Arrays.asList;
import static org.testng.Assert.assertEquals;
import java.io.File;
@@ -88,6 +89,24 @@ public class ConfigEditorTest {
assertEquals(editor.getStoragePort(), config.storage_port, "Failed to fetch storage_port");
}
+ @Test
+ public void updateDataFilesDirectories() throws Exception {
+ ConfigEditor editor = new ConfigEditor(configFile);
+ editor.load();
+ editor.setDataFileDirectories(asList("/data/dir1", "/data/dir2", "data/dir3"));
+ editor.save();
+
+ Config config = loadConfig();
+
+ assertEquals(config.data_file_directories, new String[] {"/data/dir1", "/data/dir2", "data/dir3"},
+ "Failed to update data_file_directories");
+
+ editor.load();
+
+ assertEquals(editor.getDataFileDirectories().toArray(new String[3]), config.data_file_directories,
+ "Failed to fetch data_file_directories");
+ }
+
private Config loadConfig() throws Exception {
FileInputStream inputStream = new FileInputStream(configFile);
org.yaml.snakeyaml.constructor.Constructor constructor =
commit 8affd85fb953f7b32e1439cefc436285546cb662
Author: John Sanda <jsanda(a)redhat.com>
Date: Tue Jul 30 12:57:25 2013 -0400
make storagePort and nativeTransportPort read/write properties
diff --git a/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java b/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
index 0b4a127..9e1f86b 100644
--- a/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
+++ b/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
@@ -100,10 +100,18 @@ public class ConfigEditor {
params.put("seeds", StringUtil.arrayToString(seeds));
}
+ public Integer getNativeTransportPort() {
+ return (Integer) config.get("native_transport_port");
+ }
+
public void setNativeTransportPort(int port) {
config.put("native_transport_port", port);
}
+ public Integer getStoragePort() {
+ return (Integer) config.get("storage_port");
+ }
+
public void setStoragePort(int port) {
config.put("storage_port", port);
}
diff --git a/modules/common/cassandra-util/src/test/java/org/rhq/cassandra/util/ConfigEditorTest.java b/modules/common/cassandra-util/src/test/java/org/rhq/cassandra/util/ConfigEditorTest.java
index cf344e2..f339b48 100644
--- a/modules/common/cassandra-util/src/test/java/org/rhq/cassandra/util/ConfigEditorTest.java
+++ b/modules/common/cassandra-util/src/test/java/org/rhq/cassandra/util/ConfigEditorTest.java
@@ -65,6 +65,11 @@ public class ConfigEditorTest {
Config config = loadConfig();
assertEquals(config.native_transport_port, (Integer) 9393, "Failed to update native_transport_port");
+
+ editor.load();
+
+ assertEquals(editor.getNativeTransportPort(), config.native_transport_port,
+ "Failed to fetch native_transport_port");
}
@Test
@@ -77,6 +82,10 @@ public class ConfigEditorTest {
Config config = loadConfig();
assertEquals(config.storage_port, (Integer) 6767, "Failed to update storage_port");
+
+ editor.load();
+
+ assertEquals(editor.getStoragePort(), config.storage_port, "Failed to fetch storage_port");
}
private Config loadConfig() throws Exception {
10 years, 9 months
[rhq] modules/core modules/enterprise
by John Sanda
modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java | 3
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java | 366 +++++++---
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerLocal.java | 9
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java | 7
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/storage/StorageClusterMonitor.java | 14
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/storage/StorageNodeOperationsHandler.java | 17
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/storage/StorageNodeOperationsHandlerBean.java | 90 ++
7 files changed, 418 insertions(+), 88 deletions(-)
New commits:
commit 490af59ea3141e94f865475df51ba061db82a716
Author: John Sanda <jsanda(a)redhat.com>
Date: Tue Jul 30 10:53:24 2013 -0400
adding back support for deploying additional nodes with internode authentication
When the user installs a new storage node the following steps occur,
* The node is committed into inventory (but not part of storage cluster)
* StorageNode entity is created with mode set to INSTALLED
* New node is announced to the cluster
* Server schedules operation for cluster nodes to update internode auth conf
file to include the new node
* Server prepares new node for bootstrap
* Schedules operation on new node to
* Apply cluster settings
* Update internode auth conf settings
* Restart the node so it bootstraps into cluster
* Token ranges will be assigned to node
* New node will stream data from other nodes
* Server is notified that new node is up and part of the cluster
* The operation mode is set to NORMAL
* addNodeMaintenance operation is run on each cluster node
* Updates replication_factor if necessary
* Runs repair if necessary
* Deletes old keys
* Updates seeds property
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java b/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java
index 575edc74..f4d3934 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java
@@ -56,6 +56,8 @@ import org.rhq.core.domain.resource.Resource;
+ " FROM StorageNode s " //
+ "LEFT JOIN FETCH s.resource r " //
+ " WHERE s.address = :address"),
+ @NamedQuery(name = StorageNode.QUERY_FIND_ALL_BY_MODE, query =
+ "SELECT s FROM StorageNode s WHERE s.operationMode = :operationMode"),
@NamedQuery(name = StorageNode.QUERY_FIND_ALL_NOT_INSTALLED, query = "SELECT s FROM StorageNode s WHERE NOT s.operationMode = 'INSTALLED'"),
@NamedQuery(name = StorageNode.QUERY_FIND_ALL_NORMAL, query = "SELECT s FROM StorageNode s WHERE s.operationMode = 'NORMAL'"),
@NamedQuery(name = StorageNode.QUERY_DELETE_BY_ID, query = "" //
@@ -91,6 +93,7 @@ public class StorageNode implements Serializable {
public static final String QUERY_FIND_ALL = "StorageNode.findAll";
public static final String QUERY_FIND_BY_ADDRESS = "StorageNode.findByAddress";
+ public static final String QUERY_FIND_ALL_BY_MODE = "StorageNode.findAllByMode";
public static final String QUERY_FIND_ALL_NOT_INSTALLED = "StorageNode.findAllCloudMembers";
public static final String QUERY_DELETE_BY_ID = "StorageNode.deleteById";
public static final String QUERY_FIND_ALL_NORMAL = "StorageNode.findAllNormalCloudMembers";
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java
index 049cf42..ee0f406 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java
@@ -24,6 +24,8 @@
*/
package org.rhq.enterprise.server.cloud;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
@@ -47,6 +49,7 @@ import org.quartz.JobDataMap;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
+import org.rhq.cassandra.schema.SchemaManager;
import org.rhq.core.domain.alert.Alert;
import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.authz.Permission;
@@ -57,6 +60,8 @@ import org.rhq.core.domain.cloud.StorageNodeConfigurationComposite;
import org.rhq.core.domain.cloud.StorageNodeLoadComposite;
import org.rhq.core.domain.common.JobTrigger;
import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.PropertySimple;
import org.rhq.core.domain.criteria.AlertCriteria;
import org.rhq.core.domain.criteria.ResourceGroupCriteria;
import org.rhq.core.domain.criteria.ResourceOperationHistoryCriteria;
@@ -73,6 +78,7 @@ import org.rhq.core.domain.resource.group.ResourceGroup;
import org.rhq.core.domain.util.PageControl;
import org.rhq.core.domain.util.PageList;
import org.rhq.core.domain.util.PageOrdering;
+import org.rhq.core.util.StringUtil;
import org.rhq.enterprise.server.RHQConstants;
import org.rhq.enterprise.server.alert.AlertManagerLocal;
import org.rhq.enterprise.server.auth.SubjectManagerLocal;
@@ -82,6 +88,7 @@ import org.rhq.enterprise.server.cloud.instance.ServerManagerLocal;
import org.rhq.enterprise.server.configuration.ConfigurationManagerLocal;
import org.rhq.enterprise.server.measurement.MeasurementDataManagerLocal;
import org.rhq.enterprise.server.operation.OperationManagerLocal;
+import org.rhq.enterprise.server.resource.ResourceManagerLocal;
import org.rhq.enterprise.server.resource.ResourceTypeManagerLocal;
import org.rhq.enterprise.server.resource.group.ResourceGroupManagerLocal;
import org.rhq.enterprise.server.rest.reporting.MeasurementConverter;
@@ -100,6 +107,14 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
private final Log log = LogFactory.getLog(StorageNodeManagerBean.class);
+ private static final String USERNAME_PROPERTY = "rhq.cassandra.username";
+ private static final String PASSWORD_PROPERTY = "rhq.cassandra.password";
+ private final static String MAINTENANCE_OPERATION = "addNodeMaintenance";
+ private final static String MAINTENANCE_OPERATION_NOTE = "Topology change maintenance.";
+ private final static String RUN_REPAIR_PROPERTY = "runRepair";
+ private final static String UPDATE_SEEDS_LIST = "updateSeedsList";
+ private final static String SEEDS_LIST = "seedsList";
+
private static final String RHQ_STORAGE_CQL_PORT_PROPERTY = "nativeTransportPort";
private static final String RHQ_STORAGE_JMX_PORT_PROPERTY = "jmxPort";
private static final String RHQ_STORAGE_ADDRESS_PROPERTY = "host";
@@ -139,46 +154,86 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
@EJB
private StorageNodeManagerLocal storageNodeManger;
+ @EJB
+ private ResourceManagerLocal resourceManager;
+
@Override
public void linkResource(Resource resource) {
- List<StorageNode> storageNodes = this.getStorageNodes();
-
Configuration resourceConfig = resource.getPluginConfiguration();
- String configAddress = resourceConfig.getSimpleValue(RHQ_STORAGE_ADDRESS_PROPERTY);
-
- if (configAddress != null) {
- // TODO Do not add the node to the group until we have verified it has joined the cluster
- // StorageNodeMaintenanceJob currently determines if a new node has successfully joined the cluster.
- addStorageNodeToGroup(resource);
-
- boolean storageNodeFound = false;
- if (storageNodes != null) {
- for (StorageNode storageNode : storageNodes) {
- if (configAddress.equals(storageNode.getAddress())) {
- storageNode.setResource(resource);
- storageNode.setOperationMode(OperationMode.NORMAL);
- storageNodeFound = true;
- break;
- }
- }
- }
+ String address = resourceConfig.getSimpleValue(RHQ_STORAGE_ADDRESS_PROPERTY);
- if (!storageNodeFound) {
- int cqlPort = Integer.parseInt(resourceConfig.getSimpleValue(RHQ_STORAGE_CQL_PORT_PROPERTY));
- int jmxPort = Integer.parseInt(resourceConfig.getSimpleValue(RHQ_STORAGE_JMX_PORT_PROPERTY));
+ if (log.isInfoEnabled()) {
+ log.info("Linking " + resource + " to storage node at " + address);
+ }
+ try {
+ StorageNode storageNode = findStorageNodeByAddress(InetAddress.getByName(address));
- StorageNode storageNode = new StorageNode();
- storageNode.setAddress(configAddress);
- storageNode.setCqlPort(cqlPort);
- storageNode.setJmxPort(jmxPort);
+ if (storageNode != null) {
+ if (log.isInfoEnabled()) {
+ log.info(storageNode + " is an existing storage node. No cluster maintenance is necessary.");
+ }
storageNode.setResource(resource);
storageNode.setOperationMode(OperationMode.NORMAL);
+ addStorageNodeToGroup(resource);
+ } else {
+ storageNode = new StorageNode();
+ storageNode.setAddress(address);
+ storageNode.setCqlPort(Integer.parseInt(resourceConfig.getSimpleValue(RHQ_STORAGE_CQL_PORT_PROPERTY)));
+ storageNode.setJmxPort(Integer.parseInt(resourceConfig.getSimpleValue(RHQ_STORAGE_JMX_PORT_PROPERTY)));
+ storageNode.setResource(resource);
+ storageNode.setOperationMode(OperationMode.INSTALLED);
entityManager.persist(storageNode);
-// scheduleQuartzJob(storageNodes.size());
+ if (log.isInfoEnabled()) {
+ log.info(storageNode + " is a new storage node and not part of the storage node cluster.");
+ log.info("Scheduling maintenance operations to bring " + storageNode + " into the cluster...");
+ }
+
+ announceNewNode(storageNode);
}
+ } catch (UnknownHostException e) {
+ throw new RuntimeException("Could not resolve address [" + address + "]. The resource " + resource +
+ " cannot be linked to a storage node", e);
+ }
+ }
+
+ private void announceNewNode(StorageNode newStorageNode) {
+ if (log.isInfoEnabled()) {
+ log.info("Announcing " + newStorageNode + " to storage node cluster.");
+ }
+
+ ResourceGroup storageNodeGroup = getStorageNodeGroup();
+
+ GroupOperationSchedule schedule = new GroupOperationSchedule();
+ schedule.setGroup(storageNodeGroup);
+ schedule.setHaltOnFailure(false);
+ schedule.setExecutionOrder(new ArrayList<Resource>(storageNodeGroup.getExplicitResources()));
+ schedule.setJobTrigger(JobTrigger.createNowTrigger());
+ schedule.setSubject(subjectManager.getOverlord());
+ schedule.setOperationName("updateKnownNodes");
+
+ Configuration parameters = new Configuration();
+ parameters.put(createPropertyListOfAddresses("ipAddresses", combine(getStorageNodes(), newStorageNode)));
+ schedule.setParameters(parameters);
+
+ operationManager.scheduleGroupOperation(subjectManager.getOverlord(), schedule);
+ }
+
+ private List<StorageNode> combine(List<StorageNode> storageNodes, StorageNode storageNode) {
+ List<StorageNode> newList = new ArrayList<StorageNode>(storageNodes.size() + 1);
+ newList.addAll(storageNodes);
+ newList.add(storageNode);
+
+ return newList;
+ }
+
+ private PropertyList createPropertyListOfAddresses(String propertyName, List<StorageNode> nodes) {
+ PropertyList list = new PropertyList(propertyName);
+ for (StorageNode storageNode : nodes) {
+ list.add(new PropertySimple("address", storageNode.getAddress()));
}
+ return list;
}
@Override
@@ -214,7 +269,7 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
ResourceGroup group = getStorageNodeGroup();
resourceGroupManager.addResourcesToGroup(subjectManager.getOverlord(), group.getId(),
- new int[] {resource.getId()});
+ new int[]{resource.getId()});
}
@Override
@@ -232,6 +287,13 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
}
@Override
+ public void addToStorageNodeGroup(StorageNode storageNode) {
+ storageNode.setOperationMode(OperationMode.NORMAL);
+ entityManager.merge(storageNode);
+ addStorageNodeToGroup(storageNode.getResource());
+ }
+
+ @Override
public ResourceGroup getStorageNodeGroup() {
Subject overlord = subjectManager.getOverlord();
@@ -398,6 +460,19 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
return runner.execute();
}
+ public StorageNode findStorageNodeByAddress(InetAddress address) {
+ TypedQuery<StorageNode> query = entityManager.<StorageNode> createNamedQuery(StorageNode.QUERY_FIND_BY_ADDRESS,
+ StorageNode.class);
+ query.setParameter("address", address.getHostAddress());
+ List<StorageNode> result = query.getResultList();
+
+ if (result != null && result.size() > 0) {
+ return result.get(0);
+ }
+
+ return null;
+ }
+
@Override
@RequiredPermissions({ @RequiredPermission(Permission.MANAGE_SETTINGS),
@RequiredPermission(Permission.MANAGE_INVENTORY) })
@@ -472,19 +547,6 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
entityManager.flush();
}
- private StorageNode findStorageNodeByAddress(String address) {
- TypedQuery<StorageNode> query = entityManager.<StorageNode> createNamedQuery(StorageNode.QUERY_FIND_BY_ADDRESS,
- StorageNode.class);
- query.setParameter("address", address);
- List<StorageNode> result = query.getResultList();
-
- if (result != null && result.size() > 0) {
- return result.get(0);
- }
-
- return null;
- }
-
private StorageNodeLoadComposite.MeasurementAggregateWithUnits getMeasurementAggregateWithUnits(Subject subject,
int schedId, MeasurementUnits units, long beginTime, long endTime) {
MeasurementAggregate measurementAggregate = measurementManager.getAggregate(subject, schedId, beginTime,
@@ -641,63 +703,68 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
@Override
public boolean updateConfiguration(Subject subject, StorageNodeConfigurationComposite storageNodeConfiguration) {
- StorageNode storageNode = findStorageNodeByAddress(storageNodeConfiguration.getStorageNode().getAddress());
+ try {
+ StorageNode storageNode = findStorageNodeByAddress(InetAddress.getByName(
+ storageNodeConfiguration.getStorageNode().getAddress()));
+
+ if (storageNode != null && storageNode.getResource() != null) {
+ Configuration parameters = new Configuration();
+ parameters.setSimpleValue("jmxPort", storageNodeConfiguration.getJmxPort() + "");
+ if (storageNodeConfiguration.getHeapSize() != null) {
+ parameters.setSimpleValue("heapSize", storageNodeConfiguration.getHeapSize() + "");
+ }
+ if (storageNodeConfiguration.getHeapNewSize() != null) {
+ parameters.setSimpleValue("heapNewSize", storageNodeConfiguration.getHeapNewSize() + "");
+ }
+ if (storageNodeConfiguration.getThreadStackSize() != null) {
+ parameters.setSimpleValue("threadStackSize", storageNodeConfiguration.getThreadStackSize() + "");
+ }
+ parameters.setSimpleValue("restartIfRequired", "false");
- if (storageNode != null && storageNode.getResource() != null) {
- Configuration parameters = new Configuration();
- parameters.setSimpleValue("jmxPort", storageNodeConfiguration.getJmxPort() + "");
- if (storageNodeConfiguration.getHeapSize() != null) {
- parameters.setSimpleValue("heapSize", storageNodeConfiguration.getHeapSize() + "");
- }
- if (storageNodeConfiguration.getHeapNewSize() != null) {
- parameters.setSimpleValue("heapNewSize", storageNodeConfiguration.getHeapNewSize() + "");
- }
- if (storageNodeConfiguration.getThreadStackSize() != null) {
- parameters.setSimpleValue("threadStackSize", storageNodeConfiguration.getThreadStackSize() + "");
- }
- parameters.setSimpleValue("restartIfRequired", "false");
+ Resource storageNodeResource = storageNode.getResource();
- Resource storageNodeResource = storageNode.getResource();
+ boolean result = runOperationAndWaitForResult(subject, storageNodeResource, UPDATE_CONFIGURATION_OPERATION,
+ parameters);
- boolean result = runOperationAndWaitForResult(subject, storageNodeResource, UPDATE_CONFIGURATION_OPERATION,
- parameters);
+ if (result) {
+ //2. Update the JMX port
+ //this is a fast operation compared to the restart
+ storageNode.setJmxPort(storageNodeConfiguration.getJmxPort());
+ entityManager.merge(storageNode);
- if (result) {
- //2. Update the JMX port
- //this is a fast operation compared to the restart
- storageNode.setJmxPort(storageNodeConfiguration.getJmxPort());
- entityManager.merge(storageNode);
+ //3. Restart the storage node
+ result = runOperationAndWaitForResult(subject, storageNodeResource, RESTART_OPERATION,
+ new Configuration());
- //3. Restart the storage node
- result = runOperationAndWaitForResult(subject, storageNodeResource, RESTART_OPERATION,
- new Configuration());
+ //4. Update the plugin configuration to talk with the new server
+ //Up to this point communication with the storage node should not have been affected by the intermediate
+ //changes
+ Configuration storageNodePluginConfig = configurationManager.getPluginConfiguration(subject,
+ storageNodeResource.getId());
- //4. Update the plugin configuration to talk with the new server
- //Up to this point communication with the storage node should not have been affected by the intermediate
- //changes
- Configuration storageNodePluginConfig = configurationManager.getPluginConfiguration(subject,
- storageNodeResource.getId());
+ String existingJMXPort = storageNodePluginConfig.getSimpleValue("jmxPort");
+ String newJMXPort = storageNodeConfiguration.getJmxPort() + "";
- String existingJMXPort = storageNodePluginConfig.getSimpleValue("jmxPort");
- String newJMXPort = storageNodeConfiguration.getJmxPort() + "";
+ if (!existingJMXPort.equals(newJMXPort)) {
+ storageNodePluginConfig.setSimpleValue("jmxPort", newJMXPort);
- if (!existingJMXPort.equals(newJMXPort)) {
- storageNodePluginConfig.setSimpleValue("jmxPort", newJMXPort);
+ String existingConnectionURL = storageNodePluginConfig.getSimpleValue("connectorAddress");
+ String newConnectionURL = existingConnectionURL.replace(":" + existingJMXPort + "/", ":"
+ + storageNodeConfiguration.getJmxPort() + "/");
+ storageNodePluginConfig.setSimpleValue("connectorAddress", newConnectionURL);
- String existingConnectionURL = storageNodePluginConfig.getSimpleValue("connectorAddress");
- String newConnectionURL = existingConnectionURL.replace(":" + existingJMXPort + "/", ":"
- + storageNodeConfiguration.getJmxPort() + "/");
- storageNodePluginConfig.setSimpleValue("connectorAddress", newConnectionURL);
+ configurationManager.updatePluginConfiguration(subject, storageNodeResource.getId(),
+ storageNodePluginConfig);
+ }
- configurationManager.updatePluginConfiguration(subject, storageNodeResource.getId(),
- storageNodePluginConfig);
+ return result;
}
-
- return result;
}
- }
- return false;
+ return false;
+ } catch (UnknownHostException e) {
+ throw new RuntimeException("Failed to resolve address for " + storageNodeConfiguration, e);
+ }
}
@Override
@@ -754,4 +821,129 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
return successResultFound;
}
-}
+
+ @Override
+ public void prepareNewNodesForBootstrap() {
+ List<StorageNode> newStorageNodes = entityManager.createNamedQuery(StorageNode.QUERY_FIND_ALL_BY_MODE)
+ .setParameter("operationMode", OperationMode.INSTALLED).getResultList();
+ if (newStorageNodes.isEmpty()) {
+ throw new RuntimeException("Failed to find storage node to bootstrap into cluster.");
+ }
+ // Right now, without some user input, we can only reliably bootstrap one node at a
+ // time. To support bootstrapping multiple nodes concurrently, a mechanism will have
+ // to be put in place for the user to declare in advance the nodes that are coming
+ // online. Then we can wait until all declared nodes have been committed into
+ // inventory and announced to the cluster
+ StorageNode storageNode = newStorageNodes.get(0);
+
+ if (log.isInfoEnabled()) {
+ log.info("Preparing to bootstrap " + storageNode + " into cluster...");
+ }
+
+ List<StorageNode> existingStorageNodes = getStorageNodes();
+
+ ResourceOperationSchedule schedule = new ResourceOperationSchedule();
+ schedule.setResource(storageNode.getResource());
+ schedule.setJobTrigger(JobTrigger.createNowTrigger());
+ schedule.setSubject(subjectManager.getOverlord());
+ schedule.setOperationName("prepareForBootstrap");
+
+ Configuration parameters = new Configuration();
+ parameters.put(new PropertySimple("cqlPort", existingStorageNodes.get(0).getCqlPort()));
+ // TODO need to add support for storage_port in cassandra/storage plugins
+ parameters.put(new PropertySimple("gossipPort", 7100));
+ parameters.put(createPropertyListOfAddresses("storageNodeIPAddresses", getStorageNodes()));
+
+ schedule.setParameters(parameters);
+
+ operationManager.scheduleResourceOperation(subjectManager.getOverlord(), schedule);
+ }
+
+ @Override
+ public void runAddNodeMaintenance() {
+ log.info("Preparing to schedule addNodeMaintenance on the storage cluster...");
+
+ List<StorageNode> storageNodes = entityManager.createNamedQuery(StorageNode.QUERY_FIND_ALL_BY_MODE,
+ StorageNode.class).setParameter("operationMode", OperationMode.NORMAL).getResultList();
+
+ int clusterSize = storageNodes.size();
+ boolean isReadRepairNeeded;
+
+ if (clusterSize >= 4) {
+ // At 4 nodes we increase the RF to 3. We are not increasing the RF beyond
+ // that for additional nodes; so, there is no need to run repair if we are
+ // expanding from a 4 node cluster since the RF remains the same.
+ isReadRepairNeeded = false;
+ } else if (clusterSize == 1) {
+ // The RF will increase since we are going from a single to a multi-node
+ // cluster; therefore, we want to run repair.
+ isReadRepairNeeded = true;
+ } else if (clusterSize == 2) {
+ if (storageNodes.size() > 3) {
+ // If we go from 2 to > 3 nodes we will increase the RF to 3; therefore
+ // we want to run repair.
+ isReadRepairNeeded = true;
+ } else {
+ // If we go from 2 to 3 nodes, we keep the RF at 2 so there is no need
+ // to run repair.
+ isReadRepairNeeded = false;
+ }
+ } else if (clusterSize == 3) {
+ // We are increasing the cluster size > 3 which means the RF will be
+ // updated to 3; therefore, we want to run repair.
+ isReadRepairNeeded = true;
+ } else {
+ // If we cluster size of zero, then something is really screwed up. It
+ // should always be > 0.
+ isReadRepairNeeded = storageNodes.size() > 1;
+ }
+
+ if (isReadRepairNeeded) {
+ updateTopology(storageNodes);
+ }
+
+ ResourceGroup storageNodeGroup = getStorageNodeGroup();
+
+ GroupOperationSchedule schedule = new GroupOperationSchedule();
+ schedule.setGroup(storageNodeGroup);
+ schedule.setHaltOnFailure(false);
+ schedule.setExecutionOrder(new ArrayList<Resource>(storageNodeGroup.getExplicitResources()));
+ schedule.setJobTrigger(JobTrigger.createNowTrigger());
+ schedule.setSubject(subjectManager.getOverlord());
+ schedule.setOperationName(MAINTENANCE_OPERATION);
+ schedule.setDescription(MAINTENANCE_OPERATION_NOTE);
+
+ Configuration config = new Configuration();
+ config.put(createPropertyListOfAddresses(SEEDS_LIST, storageNodes));
+ config.put(new PropertySimple(RUN_REPAIR_PROPERTY, isReadRepairNeeded));
+ config.put(new PropertySimple(UPDATE_SEEDS_LIST, Boolean.TRUE));
+
+ schedule.setParameters(config);
+
+ operationManager.scheduleGroupOperation(subjectManager.getOverlord(), schedule);
+ }
+
+ private boolean updateTopology(List<StorageNode> storageNodes) {
+ String username = getRequiredStorageProperty(USERNAME_PROPERTY);
+ String password = getRequiredStorageProperty(PASSWORD_PROPERTY);
+ SchemaManager schemaManager = new SchemaManager(username, password, storageNodes);
+ try{
+ return schemaManager.updateTopology(false);
+ } catch (Exception e) {
+ log.error("An error occurred while applying schema topology changes", e);
+ }
+
+ return false;
+ }
+
+ private String getRequiredStorageProperty(String property) {
+ String value = System.getProperty(property);
+ if (StringUtil.isEmpty(property)) {
+ throw new IllegalStateException("The system property [" + property + "] is not set. The RHQ "
+ + "server will not be able connect to the RHQ storage node(s). This property should be defined "
+ + "in rhq-server.properties.");
+ }
+ return value;
+ }
+
+}
\ No newline at end of file
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerLocal.java
index 15fa85c..00ba9e7 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerLocal.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerLocal.java
@@ -18,6 +18,7 @@
*/
package org.rhq.enterprise.server.cloud;
+import java.net.InetAddress;
import java.util.List;
import javax.ejb.Local;
@@ -106,6 +107,8 @@ public interface StorageNodeManagerLocal {
*/
PageList<Alert> findAllStorageNodeAlerts(Subject subject, StorageNode storageNode);
+ StorageNode findStorageNodeByAddress(InetAddress address);
+
/**
* Find ids for all resources and sub-resources of Storage Nodes that
@@ -170,6 +173,8 @@ public interface StorageNodeManagerLocal {
*/
boolean storageNodeGroupExists();
+ void addToStorageNodeGroup(StorageNode storageNode);
+
/**
* This method assumes the storage node resource group already exists; as such, it should only be called from places
* in the code that are after the point(s) where the group has been created.
@@ -181,4 +186,8 @@ public interface StorageNodeManagerLocal {
void scheduleOperationInNewTransaction(Subject subject, ResourceOperationSchedule schedule);
+ void prepareNewNodesForBootstrap();
+
+ void runAddNodeMaintenance();
+
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java
index 088f13e..5d3b1ae 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java
@@ -96,6 +96,7 @@ import org.rhq.enterprise.server.resource.ResourceNotFoundException;
import org.rhq.enterprise.server.resource.group.ResourceGroupManagerLocal;
import org.rhq.enterprise.server.resource.group.ResourceGroupNotFoundException;
import org.rhq.enterprise.server.scheduler.SchedulerLocal;
+import org.rhq.enterprise.server.storage.StorageNodeOperationsHandler;
import org.rhq.enterprise.server.util.CriteriaQueryGenerator;
import org.rhq.enterprise.server.util.CriteriaQueryRunner;
@@ -123,6 +124,9 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan
@EJB
private SubjectManagerLocal subjectManager;
+ @EJB
+ private StorageNodeOperationsHandler storageNodeOperationsHandler;
+
@SuppressWarnings("unchecked")
public List<IntegerOptionItem> getResourceNameOptionItems(int groupId) {
String queryName = ResourceGroup.QUERY_FIND_RESOURCE_NAMES_BY_GROUP_ID;
@@ -917,7 +921,7 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan
if (history.getParameters() != null) {
history.getParameters().getId(); // eagerly reload the parameters
}
-
+ storageNodeOperationsHandler.handleOperationUpdateIfNecessary(history);
notifyAlertConditionCacheManager("updateOperationHistory", history);
return history;
}
@@ -1723,6 +1727,7 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan
if (!stillInProgress) {
groupHistory.setErrorMessage((groupErrorMessage == null) ? null : groupErrorMessage.toString());
groupHistory.setStatus(groupStatus);
+ storageNodeOperationsHandler.handleGroupOperationUpdateIfNecessary(groupHistory);
notifyAlertConditionCacheManager("checkForCompletedGroupOperation", groupHistory);
}
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/storage/StorageClusterMonitor.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/storage/StorageClusterMonitor.java
index ec28888..0b404bb 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/storage/StorageClusterMonitor.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/storage/StorageClusterMonitor.java
@@ -9,7 +9,9 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.rhq.core.domain.cloud.Server;
+import org.rhq.core.domain.cloud.StorageNode;
import org.rhq.enterprise.server.auth.SubjectManagerLocal;
+import org.rhq.enterprise.server.cloud.StorageNodeManagerLocal;
import org.rhq.enterprise.server.cloud.TopologyManagerLocal;
import org.rhq.enterprise.server.cloud.instance.ServerManagerLocal;
import org.rhq.enterprise.server.util.LookupUtil;
@@ -36,6 +38,18 @@ public class StorageClusterMonitor implements StorageStateListener {
log.info("Taking server out of maintenance mode");
updateServerMode(Server.OperationMode.NORMAL);
}
+
+ StorageNodeManagerLocal storageNodeManager = LookupUtil.getStorageNodeManager();
+ StorageNode newClusterNode = storageNodeManager.findStorageNodeByAddress(address);
+
+ if (newClusterNode == null) {
+ log.error("Did not find storage node with address [" + address.getHostAddress() + "]. This should not " +
+ "happen.");
+ } else {
+ log.info("Adding " + newClusterNode + " to storage cluster and scheduling cluster maintenance...");
+ storageNodeManager.addToStorageNodeGroup(newClusterNode);
+ storageNodeManager.runAddNodeMaintenance();
+ }
}
@Override
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/storage/StorageNodeOperationsHandler.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/storage/StorageNodeOperationsHandler.java
new file mode 100644
index 0000000..96e8de8
--- /dev/null
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/storage/StorageNodeOperationsHandler.java
@@ -0,0 +1,17 @@
+package org.rhq.enterprise.server.storage;
+
+import javax.ejb.Asynchronous;
+
+import org.rhq.core.domain.operation.GroupOperationHistory;
+import org.rhq.core.domain.operation.OperationHistory;
+
+/**
+ * @author John Sanda
+ */
+public interface StorageNodeOperationsHandler {
+ @Asynchronous
+ void handleOperationUpdateIfNecessary(OperationHistory operationHistory);
+
+ @Asynchronous
+ void handleGroupOperationUpdateIfNecessary(GroupOperationHistory operationHistory);
+}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/storage/StorageNodeOperationsHandlerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/storage/StorageNodeOperationsHandlerBean.java
new file mode 100644
index 0000000..6da5cca
--- /dev/null
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/storage/StorageNodeOperationsHandlerBean.java
@@ -0,0 +1,90 @@
+package org.rhq.enterprise.server.storage;
+
+import javax.ejb.Asynchronous;
+import javax.ejb.EJB;
+import javax.ejb.Stateless;
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.rhq.core.domain.cloud.StorageNode;
+import org.rhq.core.domain.operation.GroupOperationHistory;
+import org.rhq.core.domain.operation.OperationDefinition;
+import org.rhq.core.domain.operation.OperationHistory;
+import org.rhq.core.domain.operation.OperationRequestStatus;
+import org.rhq.core.domain.resource.Resource;
+import org.rhq.core.domain.resource.ResourceType;
+import org.rhq.enterprise.server.RHQConstants;
+import org.rhq.enterprise.server.cloud.StorageNodeManagerLocal;
+
+/**
+ * @author John Sanda
+ */
+@Stateless
+public class StorageNodeOperationsHandlerBean implements StorageNodeOperationsHandler {
+
+ private final Log log = LogFactory.getLog(StorageNodeOperationsHandlerBean.class);
+
+ private static final String STORAGE_NODE_TYPE_NAME = "RHQ Storage Node";
+ private static final String STORAGE_NODE_PLUGIN_NAME = "RHQStorage";
+
+ @PersistenceContext(unitName = RHQConstants.PERSISTENCE_UNIT_NAME)
+ private EntityManager entityManager;
+
+ @EJB
+ private StorageNodeManagerLocal storageNodeManager;
+
+ @Override
+ @Asynchronous
+ public void handleOperationUpdateIfNecessary(OperationHistory operationHistory) {
+// if (isStorageNodeOperation(operationHistory.getOperationDefinition())) {
+// if (operationHistory.getOperationDefinition().getName().equals("prepareForBootstrap")) {
+// ResourceOperationHistory resourceOperationHistory = entityManager.find(ResourceOperationHistory.class,
+// operationHistory.getId());
+// if (resourceOperationHistory.getStatus() == OperationRequestStatus.SUCCESS) {
+//
+// }
+// StorageNode storageNode = findStorageNode(resourceOperationHistory.getResource());
+// storageNode.setOperationMode(StorageNode.OperationMode.NORMAL);
+// }
+// }
+ }
+
+ private StorageNode findStorageNode(Resource resource) {
+ for (StorageNode storageNode : storageNodeManager.getStorageNodes()) {
+ if (storageNode.getResource().getId() == resource.getId()) {
+ return storageNode;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ @Asynchronous
+ public void handleGroupOperationUpdateIfNecessary(GroupOperationHistory groupOperationHistory) {
+ if (isStorageNodeOperation(groupOperationHistory.getOperationDefinition())) {
+ if (groupOperationHistory.getOperationDefinition().getName().equals("updateKnownNodes")) {
+ if (groupOperationHistory.getStatus() == OperationRequestStatus.SUCCESS) {
+ log.info("New storage has been successfully announced to the storage node cluster.");
+ storageNodeManager.prepareNewNodesForBootstrap();
+ } else if (groupOperationHistory.getStatus() == OperationRequestStatus.FAILURE) {
+ log.warn("Failed to announce new storage node to the cluster. It cannot join the cluster until " +
+ "it has been announced to existing cluster nodes.");
+ } else if (groupOperationHistory.getStatus() == OperationRequestStatus.CANCELED) {
+ log.warn("New storage node has not been announced to the cluster. The group operation " +
+ groupOperationHistory.getOperationDefinition().getName() + " has been canceled. The new node " +
+ "cannot join the cluster until it has been announced to existing cluster nodes.");
+ }
+ }
+ }
+ }
+
+ private boolean isStorageNodeOperation(OperationDefinition operationDefinition) {
+ ResourceType resourceType = operationDefinition.getResourceType();
+ return resourceType.getName().equals(STORAGE_NODE_TYPE_NAME) &&
+ resourceType.getPlugin().equals(STORAGE_NODE_PLUGIN_NAME);
+ }
+
+}
10 years, 9 months
[rhq] Branch 'feature/bundle-group' - 2 commits - modules/core modules/enterprise
by Jay Shaughnessy
modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java | 20
modules/core/domain/src/main/java/org/rhq/core/domain/authz/Permission.java | 35
modules/core/domain/src/main/java/org/rhq/core/domain/bundle/Bundle.java | 3
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/PermissionsEditor.java | 6
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties | 1
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_cs.properties | 1
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties | 1
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ja.properties | 1
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ko.properties | 1
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_pt.properties | 1
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ru.properties | 1
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_zh.properties | 1
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerBean.java | 52 +
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerLocal.java | 25
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java | 423 ++++++++--
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java | 20
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java | 45 -
17 files changed, 524 insertions(+), 113 deletions(-)
New commits:
commit b36674c735aea47d668f840e4cd53560de3e80d8
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Mon Jul 29 17:22:29 2013 -0400
In progress: working through the bundle remote API and adding fine-grained authz...
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java b/modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java
index 27ac704..5f86d8e 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java
@@ -58,7 +58,7 @@ import org.rhq.core.domain.resource.group.ResourceGroup;
* @author Greg Hinkle
*/
@Entity
-@NamedQueries( {
+@NamedQueries({
@NamedQuery(name = Subject.QUERY_GET_SUBJECTS_ASSIGNED_TO_ROLE, query = "" //
+ "SELECT s " //
@@ -139,6 +139,16 @@ import org.rhq.core.domain.resource.group.ResourceGroup;
+ " JOIN r.permissions p " //
+ " JOIN r.subjects s " //
+ " WHERE s.id = :subjectId and p = :permission ) ) "),
+
+ @NamedQuery(name = Subject.QUERY_HAS_BUNDLE_PERMISSION, query = "SELECT COUNT(b) "
+ + "FROM Bundle b, IN (b.bundleGroups) bg, IN (bg.roles) r, IN (r.subjects) s, IN (r.permissions) p "
+ + "WHERE s = :subject AND b.id = :bundleId AND p = :permission"),
+
+ @NamedQuery(name = Subject.QUERY_HAS_BUNDLE_GROUP_PERMISSION, query = "SELECT count(r) "
+ + "FROM Role r JOIN r.subjects s JOIN r.permissions p "
+ + "WHERE r in (SELECT r2 from BundleGroup bg JOIN bg.roles r2 WHERE bg.id = :bundleGroupId) "
+ + " AND s = :subject " + " AND p = :permission"),
+
@NamedQuery(name = Subject.QUERY_CAN_VIEW_RESOURCE, query = "SELECT COUNT(res) "
+ "FROM Resource res, IN (res.implicitGroups) g, IN (g.roles) r, IN (r.subjects) s "
+ "WHERE s = :subject AND res.id = :resourceId"),
@@ -228,6 +238,8 @@ public class Subject implements Serializable {
public static final String QUERY_HAS_PRIVATE_GROUP_PERMISSION = "Subject.hasPrivateGroupPermission";
public static final String QUERY_HAS_RESOURCE_PERMISSION = "Subject.hasResourcePermission";
public static final String QUERY_HAS_AUTO_GROUP_PERMISSION = "Subject.hasAutoGroupPermission";
+ public static final String QUERY_HAS_BUNDLE_PERMISSION = "Subject.hasBundlePermission";
+ public static final String QUERY_HAS_BUNDLE_GROUP_PERMISSION = "Subject.hasBundleGroupPermission";
/** This query can return more than 1 if the resource is accessible via separate groups */
public static final String QUERY_CAN_VIEW_RESOURCE = "Subject.canViewResource";
@@ -314,7 +326,8 @@ public class Subject implements Serializable {
init();
}
- public Subject(@NotNull String name, boolean factive, boolean fsystem) {
+ public Subject(@NotNull
+ String name, boolean factive, boolean fsystem) {
init();
this.name = name;
this.factive = factive;
@@ -353,7 +366,8 @@ public class Subject implements Serializable {
return this.name;
}
- public void setName(@NotNull String name) {
+ public void setName(@NotNull
+ String name) {
this.name = name;
}
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/authz/Permission.java b/modules/core/domain/src/main/java/org/rhq/core/domain/authz/Permission.java
index 4ca733c..77f66fc 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/authz/Permission.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/authz/Permission.java
@@ -104,10 +104,8 @@ public enum Permission {
CONFIGURE_WRITE(Target.RESOURCE), // 11
/**
- * can C/U/D provisioning bundles
+ * can perform any bundle action, assigns all other bundle permissions
*/
- // NOTE: This is a GLOBAL permission, but is defined down here so as to maintain the ordinal indexes of the other
- // pre-existing permissions.
MANAGE_BUNDLE(Target.GLOBAL), // 12
/**
@@ -124,7 +122,6 @@ public enum Permission {
/**
* Can C/U/D repositories and content sources
*/
- // NOTE: This is a GLOBAL permission but defined here to maintain the ordinal indexes
MANAGE_REPOSITORIES(Target.GLOBAL), // 15
/**
@@ -135,7 +132,6 @@ public enum Permission {
/**
* Can view other RHQ users, except for their assigned roles
*/
- // NOTE: This is a GLOBAL permission but defined here to maintain the ordinal indexes
VIEW_USERS(Target.GLOBAL), // 17
/**
@@ -146,54 +142,59 @@ public enum Permission {
/**
* Can create Bundle [Versions]s
* Can assign to viewable bundle groups
- * Can create global Bundle [Versions] if holding Global.VIEW_BUNDLES
+ * Can create unassigned Bundle [Versions] if holding Global.VIEW_BUNDLES
*/
CREATE_BUNDLES(Target.GLOBAL), // 19
/**
* Can delete viewable bundle [Versions]s
* Can unassign from viewable bundle groups
- * Can delete global bundles if holding Global.VIEW_BUNDLES
+ * Can delete unassigned bundles if holding Global.VIEW_BUNDLES
*/
DELETE_BUNDLES(Target.GLOBAL), // 20
/**
- * Can view any bundle, including global bundles
+ * Can view any bundle, including unassigned bundles
*/
VIEW_BUNDLES(Target.GLOBAL), // 21
/**
- * Can deploy any viewable bundle version to any viewable (deployable, compatible) resource group
+ * Can deploy any viewable bundle version to any viewable [deployable, compatible] resource group
*/
DEPLOY_BUNDLES(Target.GLOBAL), // 22
/**
- * Can assign viewable bundles to the bundle group
+ * Can assign viewable bundles to the bundle groups associated with the role.
* - this can be a copy from another viewable bundle group
- * - this can be a global bundle if holding Global.VIEW_BUNDLES
+ * - this can be an unassigned bundle if holding Global.VIEW_BUNDLES
*/
ASSIGN_BUNDLES_TO_GROUP(Target.BUNDLE), // 23
/**
- * Can unassign bundles from the bundle group
- * - the bundle is not deleted and becomes a global bundle if assigned to no other bundle group
+ * Can unassign bundles assigned to bundle groups associated with the role.
+ * - the bundle is not deleted and becomes an unassigned bundle if assigned to no other bundle group
*/
UNASSIGN_BUNDLES_FROM_GROUP(Target.BUNDLE), // 24
/**
- * Can create bundle [version]s for this bundle group
+ * Can create [implicitly assigned] bundle [version]s for bundle groups associated with the role.
*/
CREATE_BUNDLES_IN_GROUP(Target.BUNDLE), // 25
/**
- * Can delete bundle [version]s from the bundle group
+ * Can delete assigned bundle [version]s from the bundle groups associated with the role.
*/
DELETE_BUNDLES_FROM_GROUP(Target.BUNDLE), // 26
/**
- * Implied - Can view bundles in the bundle group
+ * Implied - Can view the bundles assigned to the bundle groups associated with the role.
*/
- VIEW_BUNDLES_IN_GROUP(Target.BUNDLE) // 27
+ VIEW_BUNDLES_IN_GROUP(Target.BUNDLE), // 27
+
+ /**
+ * Can deploy viewable bundles to the [compatible, deployable] resource groups associated with the role.
+ */
+ DEPLOY_BUNDLES_TO_GROUP(Target.RESOURCE) // 28
;
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/Bundle.java b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/Bundle.java
index 7b5499f..3a8569f 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/Bundle.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/bundle/Bundle.java
@@ -105,6 +105,9 @@ public class Bundle implements Serializable {
private List<BundleVersion> bundleVersions = new ArrayList<BundleVersion>();
@ManyToMany(mappedBy = "bundles", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
+ private Set<BundleGroup> bundleGroups;
+
+ @ManyToMany(mappedBy = "bundles", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
private Set<Tag> tags;
public Bundle() {
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/PermissionsEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/PermissionsEditor.java
index 5e80d82..77beefb 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/PermissionsEditor.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/roles/PermissionsEditor.java
@@ -431,6 +431,7 @@ public class PermissionsEditor extends EnhancedVStack {
String permissionName = record.getAttribute(nameField);
Permission permission = Permission.valueOf(permissionName);
String permissionDisplayName = record.getAttribute("displayName");
+
if (permission == Permission.VIEW_RESOURCE) {
String messageString = MSG.view_adminRoles_permissions_readAccessImplied(permissionDisplayName);
handleIllegalPermissionSelection(event, messageString);
@@ -449,6 +450,11 @@ public class PermissionsEditor extends EnhancedVStack {
String messageString = MSG
.view_adminRoles_permissions_illegalDeselectionDueToCorrespondingWritePermSelection(permissionDisplayName);
handleIllegalPermissionSelection(event, messageString);
+ } else if (!authorized && selectedPermissions.contains(Permission.MANAGE_BUNDLE)
+ && Permission.BUNDLE_ALL.contains(permission)) {
+ String messageString = MSG
+ .view_adminRoles_permissions_illegalDeselectionDueToManageBundleSelection(permissionDisplayName);
+ handleIllegalPermissionSelection(event, messageString);
} else {
updatePermissions(authorized, permission);
diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties
index 25f5171..5a42502 100644
--- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties
+++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties
@@ -509,6 +509,7 @@ view_adminRoles_permissions_autoselecting_manageSecurity_implied = Autoselected
view_adminRoles_permissions_bundleGroupPermissions = Bundle Group Permissions
view_adminRoles_permissions_globalPermissions = Global Permissions
view_adminRoles_permissions_illegalDeselectionDueToCorrespondingWritePermSelection = {0} read permission cannot be deselected, unless the {0} write permission, which implies the read permission, is deselected first.
+view_adminRoles_permissions_illegalDeselectionDueToManageBundleSelection = {0} permission cannot be deselected, unless Manage Bundle, which implies all Bundle permissions, is deselected first.
view_adminRoles_permissions_illegalDeselectionDueToManageInventorySelection = {0} permission cannot be deselected, unless Manage Inventory, which implies all Resource permissions, is deselected first.
view_adminRoles_permissions_illegalDeselectionDueToManageSecuritySelection = {0} permission cannot be deselected, unless the Manage Security permission, which implies all other permissions, is deselected first.
view_adminRoles_permissions_isAuthorized = Authorized?
diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_cs.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_cs.properties
index 8982a54..69c8452 100644
--- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_cs.properties
+++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_cs.properties
@@ -528,6 +528,7 @@ view_adminRoles_permissions_autoselecting_manageSecurity_implied = Automaticky o
view_adminRoles_permissions_bundleGroupPermissions = Bundle Group Permissions
view_adminRoles_permissions_globalPermissions = Globální povolení
##view_adminRoles_permissions_illegalDeselectionDueToCorrespondingWritePermSelection = {0} read permission cannot be deselected, unless the {0} write permission, which implies the read permission, is deselected first.
+##view_adminRoles_permissions_illegalDeselectionDueToManageBundleSelection = {0} permission cannot be deselected, unless Manage Bundle, which implies all Bundle permissions, is deselected first.
##view_adminRoles_permissions_illegalDeselectionDueToManageInventorySelection = {0} permission cannot be deselected, unless Manage Inventory, which implies all Resource permissions, is deselected first.
##view_adminRoles_permissions_illegalDeselectionDueToManageSecuritySelection = {0} permission cannot be deselected, unless the Manage Security permission, which implies all other permissions, is deselected first.
view_adminRoles_permissions_isAuthorized = Autorizován?
diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties
index 8b086a7..ddd4686 100644
--- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties
+++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties
@@ -507,6 +507,7 @@ view_adminRoles_noLdap = Die LDAP-Integration ist nicht konfiguriert. Um LDAP zu
view_adminRoles_permissions_bundleGroupPermissions = Bundle Group Permissions
view_adminRoles_permissions_globalPermissions = Globale Rechte
##view_adminRoles_permissions_illegalDeselectionDueToCorrespondingWritePermSelection = {0} read permission cannot be deselected, unless the {0} write permission, which implies the read permission, is deselected first.
+##view_adminRoles_permissions_illegalDeselectionDueToManageBundleSelection = {0} permission cannot be deselected, unless Manage Bundle, which implies all Bundle permissions, is deselected first.
##view_adminRoles_permissions_illegalDeselectionDueToManageInventorySelection = {0} permission cannot be deselected, unless Manage Inventory, which implies all Resource permissions, is deselected first.
##view_adminRoles_permissions_illegalDeselectionDueToManageSecuritySelection = {0} permission cannot be deselected, unless the Manage Security permission, which implies all other permissions, is deselected first.
view_adminRoles_permissions_isAuthorized = Berechtigt?
diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ja.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ja.properties
index a78ab58..49cc7e6 100644
--- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ja.properties
+++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ja.properties
@@ -506,6 +506,7 @@ view_adminRoles_permissions_autoselecting_manageSecurity_implied = 未選択の
view_adminRoles_permissions_bundleGroupPermissions = Bundle Group Permissions
view_adminRoles_permissions_globalPermissions = グローバル権限
view_adminRoles_permissions_illegalDeselectionDueToCorrespondingWritePermSelection = {0} 読み取り権限は選択解除できませんでした。読み取り権限を暗示する {0} 書き込み権限が最初に選択解除されなければそれはできません。
+##view_adminRoles_permissions_illegalDeselectionDueToManageBundleSelection = {0} permission cannot be deselected, unless Manage Bundle, which implies all Bundle permissions, is deselected first.
view_adminRoles_permissions_illegalDeselectionDueToManageInventorySelection = {0} 権限は選択解除できませんでした。他のすべてのリソースを暗示する管理インベントリが最初に選択解除されなければそれはできません。
view_adminRoles_permissions_illegalDeselectionDueToManageSecuritySelection = {0} 権限は選択解除できませんでした。他のすべての権限を暗示する管理セキュリティ権限が最初に選択解除されなければそれはできません。
view_adminRoles_permissions_isAuthorized = 権限があるか?
diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ko.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ko.properties
index a00f560..89c10c0 100644
--- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ko.properties
+++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ko.properties
@@ -457,6 +457,7 @@ view_adminRoles_noLdap = LDAP 보안 통합이 설정되지 않았습니다. LDA
view_adminRoles_permissions_bundleGroupPermissions = Bundle Group Permissions
view_adminRoles_permissions_globalPermissions = 글로벌 권한
view_adminRoles_permissions_illegalDeselectionDueToCorrespondingWritePermSelection = {0} 읽기 권한은 선택 해제 할 수 없습니다. 읽기 권한을 암시하는 {0} 쓰기 권한이 먼저 선택 해제되어야 그것은 수행할 수 있습니다.
+##view_adminRoles_permissions_illegalDeselectionDueToManageBundleSelection = {0} permission cannot be deselected, unless Manage Bundle, which implies all Bundle permissions, is deselected first.
view_adminRoles_permissions_illegalDeselectionDueToManageInventorySelection = {0} 권한은 선택 해제 할 수 없습니다. 다른 모든 자원을 암시하는 관리 인벤토리가 먼저 선택 해제되어야 그것은 수행할 수 있습니다.
view_adminRoles_permissions_illegalDeselectionDueToManageSecuritySelection = {0} 권한은 선택 해제 할 수 없습니다. 다른 모든 권한을 암시하는 관리 보안 권한이 먼저 선택 해제되어야 그것은 수행할 수 있습니다.
view_adminRoles_permissions_isAuthorized = 권한이 있습니까?
diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_pt.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_pt.properties
index e6a7864..26546fb 100644
--- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_pt.properties
+++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_pt.properties
@@ -511,6 +511,7 @@ view_adminRoles_permissions_autoselecting_manageSecurity_implied = Autoselected
view_adminRoles_permissions_bundleGroupPermissions = Bundle Group Permissions
view_adminRoles_permissions_globalPermissions = Permiss\u00F5es Globais
view_adminRoles_permissions_illegalDeselectionDueToCorrespondingWritePermSelection = {0} permiss\u00E3o de leitura n\u00E3 pode ser desmarcada, a menos que {0} permiss\u00E3o de escrita, que implica na permiss\u00E3o de leitura, seja desmarcada primeiro.
+##view_adminRoles_permissions_illegalDeselectionDueToManageBundleSelection = {0} permission cannot be deselected, unless Manage Bundle, which implies all Bundle permissions, is deselected first.
view_adminRoles_permissions_illegalDeselectionDueToManageInventorySelection = {0} permiss\u00E3o n\u00E3o pode ser desmarcada, a menos que Gerenciar Invent\u00E1rio, que implica todas as permiss\u00F5es de Recurso, seja desmarcada primeiro.
view_adminRoles_permissions_illegalDeselectionDueToManageSecuritySelection = {0} permiss\u00E3o n\u00E3o pode ser desmarcada, a menos que a permiss\u00E3 Gerenciar SeguranÁa, que implica em todas outras permissıes, seja desmarcada primeiro.
view_adminRoles_permissions_isAuthorized = Autorizado?
diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ru.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ru.properties
index 4f9a97e..5692d33 100644
--- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ru.properties
+++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ru.properties
@@ -2591,6 +2591,7 @@ view_adminRoles_permissions_autoselecting_manageSecurity_implied = Автома
view_adminRoles_permissions_bundleGroupPermissions = Bundle Group Permissions
view_adminRoles_permissions_globalPermissions = Глобальные полномчия
view_adminRoles_permissions_illegalDeselectionDueToCorrespondingWritePermSelection = {0} полномочия на чтение не могут быть отключены, пока предварительно {0} полномочия записи, которые включают полномочия на чтение, не будут отключены.
+##view_adminRoles_permissions_illegalDeselectionDueToManageBundleSelection = {0} permission cannot be deselected, unless Manage Bundle, which implies all Bundle permissions, is deselected first.
view_adminRoles_permissions_illegalDeselectionDueToManageInventorySelection = {0} полномочия не могут быть отключены, пока предварительно Manage Inventory, которая включает все полномочия ресурса, не будет отключено.
view_adminRoles_permissions_illegalDeselectionDueToManageSecuritySelection = {0} полномочия не могут быть отключены, пока предватильно Manage Security полномочие, которое включает все другие полномочия, не будет отключено.
view_adminRoles_permissions_isAuthorized = Авторизованы?
diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_zh.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_zh.properties
index 547ebd5..f126e51 100644
--- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_zh.properties
+++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_zh.properties
@@ -500,6 +500,7 @@ view_adminRoles_noLdap = \u6ca1\u6709\u96c6\u6210LDAP\u5b89\u5168, \u5230<a {0}>
view_adminRoles_permissions_bundleGroupPermissions = Bundle Group Permissions
view_adminRoles_permissions_globalPermissions = \u5168\u5c40\u6388\u6743
##view_adminRoles_permissions_illegalDeselectionDueToCorrespondingWritePermSelection = {0} read permission cannot be deselected, unless the {0} write permission, which implies the read permission, is deselected first.
+##view_adminRoles_permissions_illegalDeselectionDueToManageBundleSelection = {0} permission cannot be deselected, unless Manage Bundle, which implies all Bundle permissions, is deselected first.
##view_adminRoles_permissions_illegalDeselectionDueToManageInventorySelection = {0} permission cannot be deselected, unless Manage Inventory, which implies all Resource permissions, is deselected first.
##view_adminRoles_permissions_illegalDeselectionDueToManageSecuritySelection = {0} permission cannot be deselected, unless the Manage Security permission, which implies all other permissions, is deselected first.
view_adminRoles_permissions_isAuthorized = \u6388\u6743?
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerBean.java
index 2fda53e..d71095f 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerBean.java
@@ -51,6 +51,7 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
@PersistenceContext(unitName = RHQConstants.PERSISTENCE_UNIT_NAME)
private EntityManager entityManager;
+ @Override
@SuppressWarnings("unchecked")
public Set<Permission> getExplicitGlobalPermissions(Subject subject) {
Query query = entityManager.createNamedQuery(Subject.QUERY_GET_GLOBAL_PERMISSIONS);
@@ -66,6 +67,7 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
return results;
}
+ @Override
@SuppressWarnings("unchecked")
public Set<Permission> getExplicitGroupPermissions(Subject subject, int groupId) {
Set<Permission> result = new HashSet<Permission>();
@@ -99,12 +101,14 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
return result;
}
+ @Override
public Set<Permission> getImplicitGroupPermissions(Subject subject, int groupId) {
Set<Permission> permissions = isInventoryManager(subject) ? Permission.RESOURCE_ALL
: getExplicitGroupPermissions(subject, groupId);
return permissions;
}
+ @Override
@SuppressWarnings("unchecked")
public Set<Permission> getExplicitResourcePermissions(Subject subject, int resourceId) {
Query query = entityManager.createNamedQuery(Subject.QUERY_GET_PERMISSIONS_BY_RESOURCE_ID);
@@ -119,12 +123,14 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
return results;
}
+ @Override
public Set<Permission> getImplicitResourcePermissions(Subject subject, int resourceId) {
Set<Permission> permissions = isInventoryManager(subject) ? Permission.RESOURCE_ALL
: getExplicitResourcePermissions(subject, resourceId);
return permissions;
}
+ @Override
public boolean hasGlobalPermission(Subject subject, Permission permission) {
if (isOverlord(subject)) {
return true;
@@ -137,6 +143,7 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
return (count != 0);
}
+ @Override
@SuppressWarnings("unchecked")
public boolean hasGroupPermission(Subject subject, Permission permission, int groupId) {
if (isInventoryManager(subject)) {
@@ -170,6 +177,7 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
}
}
+ @Override
public boolean hasResourcePermission(Subject subject, Permission permission, int resourceId) {
if (isInventoryManager(subject)) {
return true;
@@ -183,6 +191,31 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
return (count != 0);
}
+ @SuppressWarnings("unchecked")
+ @Override
+ public boolean hasBundlePermission(Subject subject, Permission permission, int bundleId) {
+
+ Query query = entityManager.createNamedQuery(Subject.QUERY_HAS_BUNDLE_PERMISSION);
+ query.setParameter("subject", subject);
+ query.setParameter("permission", permission);
+ query.setParameter("bundleId", bundleId);
+ long count = (Long) query.getSingleResult();
+ return (count != 0);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public boolean hasBundleGroupPermission(Subject subject, Permission permission, int bundleGroupId) {
+
+ Query query = entityManager.createNamedQuery(Subject.QUERY_HAS_BUNDLE_GROUP_PERMISSION);
+ query.setParameter("subject", subject);
+ query.setParameter("permission", permission);
+ query.setParameter("bundleGroupId", bundleGroupId);
+ long count = (Long) query.getSingleResult();
+ return (count != 0);
+ }
+
+ @Override
public boolean hasAutoGroupPermission(Subject subject, Permission permission, int parentResourceId,
int resourceTypeId) {
if (isInventoryManager(subject)) {
@@ -207,6 +240,7 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
return (baseCount == subjectCount);
}
+ @Override
public boolean canViewResource(Subject subject, int resourceId) {
if (isInventoryManager(subject)) {
return true;
@@ -219,6 +253,7 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
return (count != 0);
}
+ @Override
public boolean canViewResources(Subject subject, List<Integer> resourceIds) {
if (isInventoryManager(subject)) {
return true;
@@ -232,6 +267,7 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
return count == resourceIds.size();
}
+ @Override
public boolean canViewGroup(Subject subject, int groupId) {
if (isInventoryManager(subject)) {
return true;
@@ -244,6 +280,7 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
return (count != 0);
}
+ @Override
public boolean canViewAutoGroup(Subject subject, int parentResourceId, int resourceTypeId) {
if (isInventoryManager(subject)) {
return true;
@@ -266,10 +303,12 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
return (baseCount == subjectCount);
}
+ @Override
public boolean isInventoryManager(Subject subject) {
return hasGlobalPermission(subject, Permission.MANAGE_INVENTORY);
}
+ @Override
@SuppressWarnings("unchecked")
public boolean hasResourcePermission(Subject subject, Permission permission, Collection<Integer> resourceIds) {
if (isInventoryManager(subject)) {
@@ -284,16 +323,20 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
return results.containsAll(resourceIds);
}
+ @Override
public boolean isSystemSuperuser(Subject subject) {
// We know that our overlord is always id=1 and the rhqadmin user is always id=2.
- return (subject != null) && ((subject.getId() == SUBJECT_ID_OVERLORD) || (subject.getId() == SUBJECT_ID_RHQADMIN));
+ return (subject != null)
+ && ((subject.getId() == SUBJECT_ID_OVERLORD) || (subject.getId() == SUBJECT_ID_RHQADMIN));
}
+ @Override
public boolean isOverlord(Subject subject) {
// We know that our overlord is always id=1.
return (subject != null) && (subject.getId() == SUBJECT_ID_OVERLORD);
}
+ @Override
public boolean canUpdateRepo(Subject subject, int repoId) {
if (hasGlobalPermission(subject, Permission.MANAGE_REPOSITORIES)) {
return true;
@@ -301,11 +344,12 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
Query q = entityManager.createNamedQuery(Repo.QUERY_CHECK_REPO_OWNED_BY_SUBJECT_ID);
q.setParameter("repoId", repoId);
q.setParameter("subjectId", subject.getId());
-
+
Long num = (Long) q.getSingleResult();
return num > 0;
}
-
+
+ @Override
public boolean canViewRepo(Subject subject, int repoId) {
if (hasGlobalPermission(subject, Permission.MANAGE_REPOSITORIES)) {
return true;
@@ -314,7 +358,7 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal {
Query q = entityManager.createNamedQuery(Repo.QUERY_CHECK_REPO_VISIBLE_BY_SUBJECT_ID);
q.setParameter("repoId", repoId);
q.setParameter("subjectId", subject.getId());
-
+
Long num = (Long) q.getSingleResult();
return num > 0;
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerLocal.java
index 194e345..8872d61 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerLocal.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerLocal.java
@@ -20,7 +20,6 @@ package org.rhq.enterprise.server.authz;
import java.util.Collection;
import java.util.List;
-import java.util.Properties;
import java.util.Set;
import javax.ejb.Local;
@@ -135,6 +134,30 @@ public interface AuthorizationManagerLocal {
boolean hasAutoGroupPermission(Subject subject, Permission permission, int parentResourceId, int resourceTypeId);
/**
+ * Returns true if the current user possesses the specified bundle permission for the specified bundle.
+ *
+ * @param subject the current subject or caller
+ * @param permission a bundle permission (i.e. permission.getTarget() == Permission.Target.BUNDLE)
+ * @param bundleId the id of the bundle to check permissions against
+ *
+ * @return true if the current user possesses the specified resource permission for the specified resource
+ */
+
+ boolean hasBundlePermission(Subject subject, Permission permission, int bundleId);
+
+ /**
+ * Returns true if the current user possesses the specified bundle permission for the specified bundle group.
+ *
+ * @param subject the current subject or caller
+ * @param permission a bundle permission (i.e. permission.getTarget() == Permission.Target.BUNDLE)
+ * @param bundleGroupId the id of the bundle group to check permissions against
+ *
+ * @return true if the current user possesses the specified resource permission for the specified resource
+ */
+
+ boolean hasBundleGroupPermission(Subject subject, Permission permission, int bundleGroupId);
+
+ /**
* Returns true if the current user possesses the specified global permission.
*
* @param subject the current subject or caller
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java
index 139a26e..51e59ff 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java
@@ -214,12 +214,6 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
- public void assignBundlesToBundleGroup(Subject subject, int bundleGroupId, int... bundleIds) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
@RequiredPermission(Permission.MANAGE_BUNDLE)
public Bundle createBundle(Subject subject, String name, String description, int bundleTypeId) throws Exception {
if (null == name || "".equals(name.trim())) {
@@ -281,7 +275,6 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE)
public BundleDeployment createBundleDeployment(Subject subject, int bundleVersionId, int bundleDestinationId,
String description, Configuration configuration) throws Exception {
@@ -294,6 +287,8 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
throw new IllegalArgumentException("Invalid bundleDestinationId: " + bundleDestinationId);
}
+ checkBundleDeploymentAuthz(subject, bundleVersion.getBundle().getId(), bundleDestination.getGroup().getId());
+
String name = getBundleDeploymentNameImpl(subject, bundleDestination, bundleVersion, null);
return this.createBundleDeploymentImpl(subject, bundleVersion, bundleDestination, name, description,
configuration);
@@ -326,7 +321,6 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE)
public BundleDestination createBundleDestination(Subject subject, int bundleId, String name, String description,
String destBaseDirName, String deployDir, Integer groupId) throws Exception {
@@ -354,6 +348,8 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
ResourceGroup group = entityManager.find(ResourceGroup.class, groups.get(0).getId());
+ checkBundleDeploymentAuthz(subject, bundle.getId(), groupId);
+
BundleDestination dest = new BundleDestination(bundle, name, group, destBaseDirName, deployDir);
dest.setDescription(description);
entityManager.persist(dest);
@@ -561,37 +557,78 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE)
public BundleVersion createBundleVersionViaRecipe(Subject subject, String recipe) throws Exception {
+ return createBundleVersionViaRecipeImpl(subject, recipe, false, 0);
+ }
+
+ @Override
+ public BundleVersion createInitialBundleVersionViaRecipe(Subject subject, int bundleGroupId, String recipe)
+ throws Exception {
+
+ return createBundleVersionViaRecipeImpl(subject, recipe, true, bundleGroupId);
+ }
+
+ private BundleVersion createBundleVersionViaRecipeImpl(Subject subject, String recipe,
+ boolean mustBeInitialVersion, int initialBundleGroupId) throws Exception {
+
BundleServerPluginManager manager = BundleManagerHelper.getPluginContainer().getBundleServerPluginManager();
BundleDistributionInfo info = manager.parseRecipe(recipe);
- BundleVersion bundleVersion = createBundleVersionViaDistributionInfo(subject, info);
+ BundleVersion bundleVersion = createBundleVersionViaDistributionInfo(subject, info, mustBeInitialVersion,
+ initialBundleGroupId);
return bundleVersion;
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE)
@TransactionAttribute(TransactionAttributeType.NEVER)
public BundleVersion createBundleVersionViaFile(Subject subject, File distributionFile) throws Exception {
+ return createBundleVersionViaFileImpl(subject, distributionFile, false, 0);
+ }
+
+ @Override
+ @TransactionAttribute(TransactionAttributeType.NEVER)
+ public BundleVersion createInitialBundleVersionViaFile(Subject subject, int bundleGroupId, File distributionFile)
+ throws Exception {
+
+ return createBundleVersionViaFileImpl(subject, distributionFile, true, bundleGroupId);
+ }
+
+ private BundleVersion createBundleVersionViaFileImpl(Subject subject, File distributionFile,
+ boolean mustBeInitialVersion, int initialBundleGroupId) throws Exception {
+
BundleServerPluginManager manager = BundleManagerHelper.getPluginContainer().getBundleServerPluginManager();
BundleDistributionInfo info = manager.processBundleDistributionFile(distributionFile);
- BundleVersion bundleVersion = createBundleVersionViaDistributionInfo(subject, info);
+ BundleVersion bundleVersion = createBundleVersionViaDistributionInfo(subject, info, mustBeInitialVersion,
+ initialBundleGroupId);
return bundleVersion;
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE)
@TransactionAttribute(TransactionAttributeType.NEVER)
public BundleVersion createBundleVersionViaByteArray(Subject subject, byte[] fileBytes) throws Exception {
+ return createBundleVersionViaByteArrayImpl(subject, fileBytes, false, 0);
+ }
+
+ @Override
+ @TransactionAttribute(TransactionAttributeType.NEVER)
+ public BundleVersion createInitialBundleVersionViaByteArray(Subject subject, int bundleGroupId, byte[] fileBytes)
+ throws Exception {
+
+ return createBundleVersionViaByteArrayImpl(subject, fileBytes, true, bundleGroupId);
+ }
+
+ private BundleVersion createBundleVersionViaByteArrayImpl(Subject subject, byte[] fileBytes,
+ boolean mustBeInitialVersion, int bundleGroupId) throws Exception {
+
File tmpFile = File.createTempFile("bundleDistroBits", ".zip");
try {
StreamUtil.copy(new ByteArrayInputStream(fileBytes), new FileOutputStream(tmpFile));
- BundleVersion bundleVersion = createBundleVersionViaFile(subject, tmpFile);
+ BundleVersion bundleVersion = createBundleVersionViaFileImpl(subject, tmpFile, mustBeInitialVersion,
+ bundleGroupId);
return bundleVersion;
} finally {
if (tmpFile != null) {
@@ -601,17 +638,36 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE)
@TransactionAttribute(TransactionAttributeType.NEVER)
public BundleVersion createBundleVersionViaURL(Subject subject, String distributionFileUrl) throws Exception {
+
return createBundleVersionViaURL(subject, distributionFileUrl, null, null);
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE)
@TransactionAttribute(TransactionAttributeType.NEVER)
public BundleVersion createBundleVersionViaURL(Subject subject, String distributionFileUrl, String username,
String password) throws Exception {
+
+ return createBundleVersionViaURLImpl(subject, distributionFileUrl, username, password, false, 0);
+ }
+
+ @Override
+ public BundleVersion createInitialBundleVersionViaURL(Subject subject, int bundleGroupId, String distributionFileUrl)
+ throws Exception {
+
+ return createInitialBundleVersionViaURL(subject, bundleGroupId, distributionFileUrl, null, null);
+ }
+
+ @Override
+ public BundleVersion createInitialBundleVersionViaURL(Subject subject, int bundleGroupId,
+ String distributionFileUrl, String username, String password) throws Exception {
+
+ return createBundleVersionViaURLImpl(subject, distributionFileUrl, username, password, true, bundleGroupId);
+ }
+
+ public BundleVersion createBundleVersionViaURLImpl(Subject subject, String distributionFileUrl, String username,
+ String password, boolean mustBeInitialVersion, int initialBundleGroupId) throws Exception {
File file = null;
try {
file = downloadFile(distributionFileUrl, username, password);
@@ -619,7 +675,7 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
log.debug("Copied [" + file.length() + "] bytes from [" + distributionFileUrl + "] into [" + file.getPath()
+ "]");
- return createBundleVersionViaFile(subject, file);
+ return createBundleVersionViaFileImpl(subject, file, mustBeInitialVersion, initialBundleGroupId);
} finally {
if (file != null) {
file.delete();
@@ -669,8 +725,8 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
return file;
}
- private BundleVersion createBundleVersionViaDistributionInfo(Subject subject, BundleDistributionInfo info)
- throws Exception {
+ private BundleVersion createBundleVersionViaDistributionInfo(Subject subject, BundleDistributionInfo info,
+ boolean mustBeInitialVersion, Integer initialBundleGroupId) throws Exception {
BundleType bundleType = bundleManager.getBundleType(subject, info.getBundleTypeName());
String bundleName = info.getRecipeParseResults().getBundleMetadata().getBundleName();
@@ -680,7 +736,7 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
String version = info.getRecipeParseResults().getBundleMetadata().getBundleVersion();
String recipe = info.getRecipe();
- // first see if the bundle exists or not; if not, create one
+ // first see if the bundle exists or not
boolean createdBundle;
BundleCriteria criteria = new BundleCriteria();
criteria.setStrict(true);
@@ -689,11 +745,19 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
PageList<Bundle> bundles = bundleManager.findBundlesByCriteria(subject, criteria);
Bundle bundle;
- if (bundles.getTotalSize() == 0) {
+ boolean isInitialVersion = (bundles.getTotalSize() == 0);
+
+ if (!isInitialVersion && mustBeInitialVersion) {
+ throw new PermissionException("This must be the initial version of a new Bundle.");
+ }
+
+ if (isInitialVersion) {
+ checkCreateInitialBundleVersionAuthz(subject, initialBundleGroupId);
bundle = bundleManager.createBundle(subject, bundleName, bundleDescription, bundleType.getId());
createdBundle = true;
} else {
bundle = bundles.get(0);
+ checkCreateBundleVersionAuthz(subject, bundle.getId());
createdBundle = false;
}
@@ -808,7 +872,6 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE)
public BundleFile addBundleFile(Subject subject, int bundleVersionId, String name, String version,
Architecture architecture, InputStream fileStream) throws Exception {
@@ -826,6 +889,9 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
throw new IllegalArgumentException("Invalid bundleVersionId: " + bundleVersionId);
}
+ // Check authorization
+ checkCreateBundleVersionAuthz(subject, bundleVersion.getBundle().getId());
+
// Create the PackageVersion the BundleFile is tied to. This implicitly creates the
// Package for the PackageVersion.
Bundle bundle = bundleVersion.getBundle();
@@ -866,7 +932,6 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE)
public BundleFile addBundleFileViaByteArray(Subject subject, int bundleVersionId, String name, String version,
Architecture architecture, byte[] fileBytes) throws Exception {
@@ -874,7 +939,6 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE)
public BundleFile addBundleFileViaURL(Subject subject, int bundleVersionId, String name, String version,
Architecture architecture, String bundleFileUrl) throws Exception {
@@ -885,11 +949,17 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE)
@TransactionAttribute(TransactionAttributeType.NEVER)
public BundleFile addBundleFileViaURL(Subject subject, int bundleVersionId, String name, String version,
Architecture architecture, String bundleFileUrl, String userName, String password) throws Exception {
+ // Check authorization prior to performing any file download
+ BundleVersion bundleVersion = entityManager.find(BundleVersion.class, bundleVersionId);
+ if (null == bundleVersion) {
+ throw new IllegalArgumentException("Invalid bundleVersionId: " + bundleVersionId);
+ }
+ checkCreateBundleVersionAuthz(subject, bundleVersion.getBundle().getId());
+
File file = null;
FileInputStream fis = null;
try {
@@ -925,8 +995,11 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
throw new IllegalArgumentException("Invalid packageVersionId: " + packageVersionId);
}
+ // Check authorization
+ checkCreateBundleVersionAuthz(subject, bundleVersion.getBundle().getId());
+
// With all the plumbing in place, create and persist the BundleFile. Tie it to the Package if the caller
- // wants this BundleFile pinned to themost recent version.
+ // wants this BundleFile pinned to the most recent version.
BundleFile bundleFile = new BundleFile();
bundleFile.setBundleVersion(bundleVersion);
bundleFile.setPackageVersion(packageVersion);
@@ -1317,31 +1390,6 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE_GROUPS)
- public BundleGroup createBundleGroup(Subject subject, String name, String description) throws Exception {
- if (null == name || "".equals(name.trim())) {
- throw new IllegalArgumentException("Invalid bundleGroupName: " + name);
- }
-
- BundleGroupCriteria c = new BundleGroupCriteria();
- c.addFilterName(name);
- c.setStrict(true);
- if (!bundleManager.findBundleGroupsByCriteria(subject, c).isEmpty()) {
- throw new IllegalArgumentException("Invalid bundleGroupName, bundle group already exists with name: "
- + name);
- }
-
- // create and add the required Repo. the Repo is a detached object which helps in its eventual
- // removal.
- BundleGroup bg = new BundleGroup(name);
- bg.setDescription(description);
-
- entityManager.persist(bg);
-
- return bg;
- }
-
- @Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@RequiredPermission(Permission.MANAGE_BUNDLE)
public BundleResourceDeployment createBundleResourceDeployment(Subject subject, int bundleDeploymentId,
@@ -1661,14 +1709,6 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
return queryRunner.execute();
}
- @Override
- public PageList<BundleGroup> findBundleGroupsByCriteria(Subject subject, BundleGroupCriteria criteria) {
- CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria);
- CriteriaQueryRunner<BundleGroup> queryRunner = new CriteriaQueryRunner<BundleGroup>(criteria, generator,
- entityManager);
- return queryRunner.execute();
- }
-
/**
* Fetch bundles by criteria and then filter destination on the result objects to limit what the user can see
* @param subject Caller
@@ -1697,27 +1737,6 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE_GROUPS)
- public void deleteBundleGroups(Subject subject, int... bundleGroupIds) throws Exception {
-
- for (int bundleGroupId : bundleGroupIds) {
- BundleGroup bundleGroup = this.entityManager.find(BundleGroup.class, bundleGroupIds);
- if (null == bundleGroup) {
- return;
- }
-
- // unassign any bundles assigned to the bundle group
- for (Bundle b : bundleGroup.getBundles()) {
- bundleGroup.removeBundle(b);
- }
- bundleGroup = entityManager.merge(bundleGroup);
-
- // now remove the bundle group
- entityManager.remove(bundleGroup);
- }
- }
-
- @Override
public PageList<BundleWithLatestVersionComposite> findBundlesWithLatestVersionCompositesByCriteria(Subject subject,
BundleCriteria criteria) {
@@ -1862,12 +1881,6 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
return;
}
- @Override
- public void unassignBundlesFromBundleGroup(Subject subject, int bundleGroupId, int... bundleIds) {
- // TODO Auto-generated method stub
-
- }
-
private void safeClose(InputStream is) {
if (null != is) {
try {
@@ -1888,4 +1901,246 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
}
+ @Override
+ public void assignBundlesToBundleGroup(Subject subject, int bundleGroupId, int[] bundleIds) {
+ BundleGroup bundleGroup = entityManager.find(BundleGroup.class, bundleGroupId);
+ if (null == bundleGroup) {
+ throw new IllegalArgumentException("BundleGroup does not exist for bundleGroupId [" + bundleGroupId + "]");
+ }
+
+ checkAssignBundleGroupAuthz(subject, bundleGroupId, bundleIds);
+
+ for (int bundleId : bundleIds) {
+ Bundle bundle = entityManager.find(Bundle.class, bundleId);
+ if (null == bundle) {
+ throw new IllegalArgumentException("Bundle does not exist for bundleId [" + bundleId + "]");
+ }
+
+ bundleGroup.addBundle(bundle);
+ }
+ }
+
+ @Override
+ @RequiredPermission(Permission.MANAGE_BUNDLE_GROUPS)
+ public BundleGroup createBundleGroup(Subject subject, String name, String description) throws Exception {
+ if (null == name || "".equals(name.trim())) {
+ throw new IllegalArgumentException("Invalid bundleGroupName: " + name);
+ }
+
+ BundleGroupCriteria c = new BundleGroupCriteria();
+ c.addFilterName(name);
+ c.setStrict(true);
+ if (!bundleManager.findBundleGroupsByCriteria(subject, c).isEmpty()) {
+ throw new IllegalArgumentException("Invalid bundleGroupName, bundle group already exists with name: "
+ + name);
+ }
+
+ // create and add the required Repo. the Repo is a detached object which helps in its eventual
+ // removal.
+ BundleGroup bg = new BundleGroup(name);
+ bg.setDescription(description);
+
+ entityManager.persist(bg);
+
+ return bg;
+ }
+
+ @Override
+ @RequiredPermission(Permission.MANAGE_BUNDLE_GROUPS)
+ public void deleteBundleGroups(Subject subject, int[] bundleGroupIds) throws Exception {
+
+ for (int bundleGroupId : bundleGroupIds) {
+ BundleGroup bundleGroup = this.entityManager.find(BundleGroup.class, bundleGroupIds);
+ if (null == bundleGroup) {
+ return;
+ }
+
+ // unassign any bundles assigned to the bundle group
+ for (Bundle b : bundleGroup.getBundles()) {
+ bundleGroup.removeBundle(b);
+ }
+ bundleGroup = entityManager.merge(bundleGroup);
+
+ // now remove the bundle group
+ entityManager.remove(bundleGroup);
+ }
+ }
+
+ @Override
+ public PageList<BundleGroup> findBundleGroupsByCriteria(Subject subject, BundleGroupCriteria criteria) {
+ CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria);
+
+ if (!authorizationManager.hasGlobalPermission(subject, Permission.VIEW_BUNDLES)) {
+
+ generator.setAuthorizationResourceFragment(CriteriaQueryGenerator.AuthorizationTokenType.BUNDLE, null,
+ subject.getId());
+ }
+
+ CriteriaQueryRunner<BundleGroup> queryRunner = new CriteriaQueryRunner<BundleGroup>(criteria, generator,
+ entityManager);
+ return queryRunner.execute();
+ }
+
+ @Override
+ public void unassignBundlesFromBundleGroup(Subject subject, int bundleGroupId, int[] bundleIds) {
+ // TODO Auto-generated method stub
+
+ }
+
+ /**
+ * @param subject
+ * @param bundleGroupId null or 0 for unassigned initial bundle version creation
+ * @throws PermissionException
+ */
+ private void checkCreateInitialBundleVersionAuthz(Subject subject, Integer bundleGroupId)
+ throws PermissionException {
+ Set<Permission> globalPerms = authorizationManager.getExplicitGlobalPermissions(subject);
+ boolean hasGlobalCreateBundles = globalPerms.contains(Permission.CREATE_BUNDLES);
+
+ if (hasGlobalCreateBundles && globalPerms.contains(Permission.VIEW_BUNDLES)) {
+ return;
+ }
+
+ if (null == bundleGroupId || bundleGroupId.intValue() <= 0) {
+ String msg = "Subject [" + subject.getName()
+ + "] requires Global CREATE_BUNDLES and VIEW_BUNDLES to create unsassigned initial bundle version.";
+ throw new PermissionException(msg);
+ }
+
+ if (hasGlobalCreateBundles) {
+ if (authorizationManager.hasBundleGroupPermission(subject, Permission.VIEW_BUNDLES_IN_GROUP, bundleGroupId)) {
+ return;
+ }
+ } else {
+ if (authorizationManager.hasBundleGroupPermission(subject, Permission.CREATE_BUNDLES_IN_GROUP,
+ bundleGroupId)) {
+ return;
+ }
+ }
+
+ String msg = "Subject ["
+ + subject.getName()
+ + "] requires either Global.CREATE_BUNDLES + BundleGroup.VIEW_BUNDLES_IN_GROUP, or BundleGroup.CREATE_BUNDLES_IN_GROUP, to create or update a bundle in bundle group ["
+ + bundleGroupId + "].";
+ throw new PermissionException(msg);
+ }
+
+ /**
+ * @param subject
+ * @param bundleId required, bundleId of bundle in which bundle version is being created/updated
+ * @throws PermissionException
+ */
+ private void checkCreateBundleVersionAuthz(Subject subject, int bundleId) throws PermissionException {
+
+ if (bundleId <= 0) {
+ throw new IllegalArgumentException(
+ "Must supply valid bundleId for bundle version being created. BundleId specified [" + bundleId + "]");
+ }
+
+ Set<Permission> globalPerms = authorizationManager.getExplicitGlobalPermissions(subject);
+ boolean hasGlobalCreateBundles = globalPerms.contains(Permission.CREATE_BUNDLES);
+
+ if (hasGlobalCreateBundles && globalPerms.contains(Permission.VIEW_BUNDLES)) {
+ return;
+ }
+
+ if (hasGlobalCreateBundles) {
+ if (authorizationManager.hasBundlePermission(subject, Permission.VIEW_BUNDLES_IN_GROUP, bundleId)) {
+ return;
+ }
+ } else {
+ if (authorizationManager.hasBundlePermission(subject, Permission.CREATE_BUNDLES_IN_GROUP, bundleId)) {
+ return;
+ }
+ }
+
+ String msg = "Subject ["
+ + subject.getName()
+ + "] requires either Global.CREATE_BUNDLES + BundleGroup.VIEW_BUNDLES_IN_GROUP, or BundleGroup.CREATE_BUNDLES_IN_GROUP, to create or update a bundleVersion for bundle ["
+ + bundleId + "].";
+ throw new PermissionException(msg);
+ }
+
+ /**
+ * @param subject
+ * @param bundleGroupId an existing bundle group
+ * @param bundleIds existing bundles
+ * @throws PermissionException
+ */
+ private void checkAssignBundleGroupAuthz(Subject subject, int bundleGroupId, int[] bundleIds)
+ throws PermissionException {
+
+ Set<Permission> globalPerms = authorizationManager.getExplicitGlobalPermissions(subject);
+ boolean hasGlobalCreateBundles = globalPerms.contains(Permission.CREATE_BUNDLES);
+ boolean hasGlobalViewBundles = globalPerms.contains(Permission.VIEW_BUNDLES);
+
+ if (hasGlobalCreateBundles && hasGlobalViewBundles) {
+ return;
+ }
+
+ boolean hasBundleGroupCreate = hasGlobalCreateBundles
+ || authorizationManager
+ .hasBundleGroupPermission(subject, Permission.CREATE_BUNDLES_IN_GROUP, bundleGroupId);
+ boolean hasBundleGroupAssign = hasBundleGroupCreate
+ || authorizationManager
+ .hasBundleGroupPermission(subject, Permission.ASSIGN_BUNDLES_TO_GROUP, bundleGroupId);
+
+ if (!hasBundleGroupAssign) {
+ String msg = "Subject ["
+ + subject.getName()
+ + "] requires one of Global.CREATE_BUNDLES, BundleGroup.CREATE_BUNDLES_IN_GROUP, or BundleGroup.ASSIGN_BUNDLES_TO_GROUP to assign a bundle to undle group ["
+ + bundleGroupId + "].";
+ throw new PermissionException(msg);
+ }
+
+ for (int bundleId : bundleIds) {
+ if (bundleId <= 0) {
+ throw new IllegalArgumentException("Invalid bundleId: [" + bundleId + "]");
+ }
+
+ if (!authorizationManager.hasBundlePermission(subject, Permission.VIEW_BUNDLES_IN_GROUP, bundleId)) {
+ String msg = "Subject [" + subject.getName()
+ + "] requires either Global.VIEW_BUNDLES or BundleGroup.VIEW_BUNDLES_IN_GROUP to assign bundle ["
+ + bundleId + "] to bundle group [" + bundleGroupId + "]";
+ throw new PermissionException(msg);
+ }
+ }
+
+ return;
+ }
+
+ private void checkBundleDeploymentAuthz(Subject subject, int bundleId, int resourceGroupId)
+ throws PermissionException {
+
+ boolean hasResourceGroupView = authorizationManager.hasGroupPermission(subject, Permission.VIEW_RESOURCE,
+ resourceGroupId);
+
+ if (!hasResourceGroupView) {
+ String msg = "Subject [" + subject.getName() + "] requires VIEW permission on resource group ["
+ + resourceGroupId + "].";
+ throw new PermissionException(msg);
+ }
+
+ Set<Permission> globalPerms = authorizationManager.getExplicitGlobalPermissions(subject);
+ boolean hasGlobalDeployBundles = globalPerms.contains(Permission.DEPLOY_BUNDLES);
+ boolean hasGlobalViewBundles = globalPerms.contains(Permission.VIEW_BUNDLES);
+
+ if (hasGlobalDeployBundles && hasGlobalViewBundles) {
+ return;
+ }
+
+ boolean hasResourceGroupDeploy = hasGlobalDeployBundles
+ || authorizationManager.hasGroupPermission(subject, Permission.DEPLOY_BUNDLES_TO_GROUP, resourceGroupId);
+ boolean hasBundleView = hasGlobalViewBundles
+ || authorizationManager.hasBundlePermission(subject, Permission.VIEW_BUNDLES_IN_GROUP, bundleId);
+
+ if (!(hasResourceGroupDeploy && hasBundleView)) {
+ String msg = "Subject [" + subject.getName()
+ + "] requires DEPLOY permission (global or on for resource group [" + resourceGroupId
+ + "] and VIEW permission for bundle [" + bundleId + "]";
+ throw new PermissionException(msg);
+ }
+
+ return;
+ }
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java
index cffe363..5ff63d0 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java
@@ -247,8 +247,8 @@ public interface BundleManagerRemote {
* </p>
* Required Permissions: Either:
* - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
- * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
- * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG
+ * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG
*
* @param subject user that must have proper permissions
* @param bundleGroupId identifies the bundle group that the new bundle will be associated with; 0 if no group
@@ -289,8 +289,8 @@ public interface BundleManagerRemote {
* </p>
* Required Permissions: Either:
* - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
- * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
- * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG
+ * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG
*
* @param subject user that must have proper permissions
* @param bundleGroupId identifies the bundle group that the new bundle will be associated with; 0 if no group
@@ -332,8 +332,8 @@ public interface BundleManagerRemote {
* </p>
* Required Permissions: Either:
* - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
- * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
- * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG
+ * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG
*
* @param subject user that must have proper permissions
* @param bundleGroupId identifies the bundle group that the new bundle will be associated with; 0 if no group
@@ -379,8 +379,8 @@ public interface BundleManagerRemote {
* </p>
* Required Permissions: Either:
* - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
- * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
- * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG
+ * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG
*
* @param subject user that must have proper permissions
* @param bundleGroupId identifies the bundle group that the new bundle will be associated with; 0 if no group
@@ -418,8 +418,8 @@ public interface BundleManagerRemote {
* </p>
* Required Permissions: Either:
* - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
- * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
- * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG
+ * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG
*
* @see #createBundleVersionViaURL(org.rhq.core.domain.auth.Subject, String)
*/
commit dac01526994e7de15ef99a72768bd9a81d7b8818
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Fri Jul 26 15:44:58 2013 -0400
Add new auth token for bundles
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java
index ac05e20..139a26e 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerBean.java
@@ -214,6 +214,12 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
+ public void assignBundlesToBundleGroup(Subject subject, int bundleGroupId, int... bundleIds) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
@RequiredPermission(Permission.MANAGE_BUNDLE)
public Bundle createBundle(Subject subject, String name, String description, int bundleTypeId) throws Exception {
if (null == name || "".equals(name.trim())) {
@@ -257,31 +263,6 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE_GROUPS)
- public BundleGroup createBundleGroup(Subject subject, String name, String description) throws Exception {
- if (null == name || "".equals(name.trim())) {
- throw new IllegalArgumentException("Invalid bundleGroupName: " + name);
- }
-
- BundleGroupCriteria c = new BundleGroupCriteria();
- c.addFilterName(name);
- c.setStrict(true);
- if (!bundleManager.findBundleGroupsByCriteria(subject, c).isEmpty()) {
- throw new IllegalArgumentException("Invalid bundleGroupName, bundle group already exists with name: "
- + name);
- }
-
- // create and add the required Repo. the Repo is a detached object which helps in its eventual
- // removal.
- BundleGroup bg = new BundleGroup(name);
- bg.setDescription(description);
-
- entityManager.persist(bg);
-
- return bg;
- }
-
- @Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@RequiredPermission(Permission.MANAGE_BUNDLE)
public BundleDeployment createBundleDeploymentInNewTrans(Subject subject, int bundleVersionId,
@@ -1336,6 +1317,31 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
+ @RequiredPermission(Permission.MANAGE_BUNDLE_GROUPS)
+ public BundleGroup createBundleGroup(Subject subject, String name, String description) throws Exception {
+ if (null == name || "".equals(name.trim())) {
+ throw new IllegalArgumentException("Invalid bundleGroupName: " + name);
+ }
+
+ BundleGroupCriteria c = new BundleGroupCriteria();
+ c.addFilterName(name);
+ c.setStrict(true);
+ if (!bundleManager.findBundleGroupsByCriteria(subject, c).isEmpty()) {
+ throw new IllegalArgumentException("Invalid bundleGroupName, bundle group already exists with name: "
+ + name);
+ }
+
+ // create and add the required Repo. the Repo is a detached object which helps in its eventual
+ // removal.
+ BundleGroup bg = new BundleGroup(name);
+ bg.setDescription(description);
+
+ entityManager.persist(bg);
+
+ return bg;
+ }
+
+ @Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@RequiredPermission(Permission.MANAGE_BUNDLE)
public BundleResourceDeployment createBundleResourceDeployment(Subject subject, int bundleDeploymentId,
@@ -1642,7 +1648,15 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
@Override
public PageList<Bundle> findBundlesByCriteria(Subject subject, BundleCriteria criteria) {
+
CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria);
+
+ if (!authorizationManager.hasGlobalPermission(subject, Permission.VIEW_BUNDLES)) {
+
+ generator.setAuthorizationResourceFragment(CriteriaQueryGenerator.AuthorizationTokenType.BUNDLE, null,
+ subject.getId());
+ }
+
CriteriaQueryRunner<Bundle> queryRunner = new CriteriaQueryRunner<Bundle>(criteria, generator, entityManager);
return queryRunner.execute();
}
@@ -1683,6 +1697,27 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
+ @RequiredPermission(Permission.MANAGE_BUNDLE_GROUPS)
+ public void deleteBundleGroups(Subject subject, int... bundleGroupIds) throws Exception {
+
+ for (int bundleGroupId : bundleGroupIds) {
+ BundleGroup bundleGroup = this.entityManager.find(BundleGroup.class, bundleGroupIds);
+ if (null == bundleGroup) {
+ return;
+ }
+
+ // unassign any bundles assigned to the bundle group
+ for (Bundle b : bundleGroup.getBundles()) {
+ bundleGroup.removeBundle(b);
+ }
+ bundleGroup = entityManager.merge(bundleGroup);
+
+ // now remove the bundle group
+ entityManager.remove(bundleGroup);
+ }
+ }
+
+ @Override
public PageList<BundleWithLatestVersionComposite> findBundlesWithLatestVersionCompositesByCriteria(Subject subject,
BundleCriteria criteria) {
@@ -1780,27 +1815,6 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
}
@Override
- @RequiredPermission(Permission.MANAGE_BUNDLE_GROUPS)
- public void deleteBundleGroups(Subject subject, int... bundleGroupIds) throws Exception {
-
- for (int bundleGroupId : bundleGroupIds) {
- BundleGroup bundleGroup = this.entityManager.find(BundleGroup.class, bundleGroupIds);
- if (null == bundleGroup) {
- return;
- }
-
- // unassign any bundles assigned to the bundle group
- for (Bundle b : bundleGroup.getBundles()) {
- bundleGroup.removeBundle(b);
- }
- bundleGroup = entityManager.merge(bundleGroup);
-
- // now remove the bundle group
- entityManager.remove(bundleGroup);
- }
- }
-
- @Override
@RequiredPermission(Permission.MANAGE_BUNDLE)
public void deleteBundleVersion(Subject subject, int bundleVersionId, boolean deleteBundleIfEmpty) throws Exception {
BundleVersion bundleVersion = this.entityManager.find(BundleVersion.class, bundleVersionId);
@@ -1848,6 +1862,12 @@ public class BundleManagerBean implements BundleManagerLocal, BundleManagerRemot
return;
}
+ @Override
+ public void unassignBundlesFromBundleGroup(Subject subject, int bundleGroupId, int... bundleIds) {
+ // TODO Auto-generated method stub
+
+ }
+
private void safeClose(InputStream is) {
if (null != is) {
try {
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java
index 574fe73..e65d9f3 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java
@@ -68,7 +68,8 @@ public final class CriteriaQueryGenerator {
public enum AuthorizationTokenType {
RESOURCE, // specifies the resource alias to join on for standard res-group-role-subject authorization checking
- GROUP; // specifies the group alias to join on for standard group-role-subject authorization checking
+ GROUP, // specifies the group alias to join on for standard group-role-subject authorization checking
+ BUNDLE; // specifies the bundle alias to join on for standard bundle-bundleGroup-role-subject authorization checking
}
private Criteria criteria;
@@ -118,10 +119,13 @@ public final class CriteriaQueryGenerator {
String defaultFragment = null;
if (type == AuthorizationTokenType.RESOURCE) {
defaultFragment = "resource";
+ setAuthorizationResourceFragment(type, defaultFragment, subjectId);
} else if (type == AuthorizationTokenType.GROUP) {
defaultFragment = "group";
+ setAuthorizationResourceFragment(type, defaultFragment, subjectId);
+ } else if (type == AuthorizationTokenType.BUNDLE) {
+ setAuthorizationBundleFragment(subjectId);
}
- setAuthorizationResourceFragment(type, defaultFragment, subjectId);
}
private String fixFilterOverride(String expression, String fieldName) {
@@ -173,9 +177,9 @@ public final class CriteriaQueryGenerator {
+ " does not yet support generating queries for '" + type + "' token types");
}
- // If the query results are narrowed by requiredParams generate the fragment now. It's done
+ // If the query results are narrowed by requiredPerms generate the fragment now. It's done
// here for two reasons. First, it seems to make sense to apply this only when an authFragment is
- // being used. Second, because ond day the query may be less brute force and may modify or
+ // being used. Second, because one day the query may be less brute force and may modify or
// leverage the joinFragment above. But, after extensive trying a more elegant
// query could not be constructed due to Hibernate limitations. So, for now, here it is...
List<Permission> requiredPerms = this.criteria.getRequiredPermissions();
@@ -230,6 +234,39 @@ public final class CriteriaQueryGenerator {
return customAuthzFragment;
}
+ public void setAuthorizationBundleFragment(int subjectId) {
+ this.authorizationSubjectId = subjectId;
+
+ String fragment = "bundle";
+ String customAuthzFragment = "" //
+ + "( %aliasWithFragment%.id IN ( SELECT %innerAlias%.id " + NL //
+ + " FROM %alias% innerAlias " + NL //
+ + " JOIN %innerAlias%.bundleGroups g JOIN g.roles r JOIN r.subjects s " + NL //
+ + " WHERE s.id = %subjectId% ) )" + NL; //
+ String aliasReplacement = criteria.getAlias() + (fragment != null ? "." + fragment : "");
+ String innerAliasReplacement = "innerAlias" + (fragment != null ? "." + fragment : "");
+ customAuthzFragment = customAuthzFragment.replace("%alias%", criteria.getAlias());
+ customAuthzFragment = customAuthzFragment.replace("%aliasWithFragment%", aliasReplacement);
+ customAuthzFragment = customAuthzFragment.replace("%innerAlias%", innerAliasReplacement);
+ customAuthzFragment = customAuthzFragment.replace("%subjectId%", String.valueOf(subjectId));
+
+ // If the query results are narrowed by requiredPerms generate the fragment now. It's done
+ // here for two reasons. First, it seems to make sense to apply this only when an authFragment is
+ // being used. Second, because one day the query may be less brute force and may modify or
+ // leverage the joinFragment above. But, after extensive trying a more elegant
+ // query could not be constructed due to Hibernate limitations. So, for now, here it is...
+ List<Permission> requiredPerms = this.criteria.getRequiredPermissions();
+ if (!(null == requiredPerms || requiredPerms.isEmpty())) {
+ this.authorizationPermsFragment = "" //
+ + "( SELECT COUNT(DISTINCT p)" + NL //
+ + " FROM Subject innerSubject" + NL //
+ + " JOIN innerSubject.roles r" + NL //
+ + " JOIN r.permissions p" + NL //
+ + " WHERE innerSubject.id = " + this.authorizationSubjectId + NL //
+ + " AND p IN ( :requiredPerms ) ) = :requiredPermsSize" + NL;
+ }
+ }
+
public String getParameterReplacedQuery(boolean countQuery) {
String query = getQueryString(countQuery);
10 years, 9 months
[rhq] modules/enterprise
by Jiri Kremser
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java | 29 ++++++----
1 file changed, 20 insertions(+), 9 deletions(-)
New commits:
commit 160452fff76ba285b5774c866f1a6f07aae239e9
Author: Jirka Kremser <jkremser(a)redhat.com>
Date: Mon Jul 29 14:45:30 2013 +0200
If there is just one group definition in ConfigurationEditor, normal form is used instead SectionStack component. Also the "Jump to Section" navigation is hidden for just one group to save some space on the screen.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java
index 779772f..418300f 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java
@@ -415,17 +415,29 @@ public class ConfigurationEditor extends EnhancedVLayout {
EnhancedVLayout layout = new EnhancedVLayout();
List<PropertyGroupDefinition> groupDefinitions = configurationDefinition.getGroupDefinitions();
- if (groupDefinitions.isEmpty()) {
- // No prop groups, so we just need a single form for the non-grouped props.
+ if (groupDefinitions.isEmpty() || groupDefinitions.size() == 1) {
+ // No or one prop groups, so we just need a single form for the non-grouped props
+ // and another one if there is just one group
List<PropertyDefinition> propertyDefinitions = new ArrayList<PropertyDefinition>(
configurationDefinition.getNonGroupedProperties());
-
- DynamicForm form = buildPropertiesForm(propertyDefinitions, configuration);
- form.setBorder("1px solid #AAA");
- form.validate();
- layout.addMember(form);
+ if (!propertyDefinitions.isEmpty()) {
+ DynamicForm form = buildPropertiesForm(propertyDefinitions, configuration);
+ form.setBorder("1px solid #AAA");
+ form.validate();
+ layout.addMember(form);
+ }
+ if (groupDefinitions.size() == 1) {
+ propertyDefinitions.addAll(configurationDefinition.getPropertiesInGroup(groupDefinitions.get(0)
+ .getName()));
+ DynamicForm groupForm = buildPropertiesForm(propertyDefinitions, configuration);
+ groupForm.setIsGroup(true);
+ groupForm.setGroupTitle(groupDefinitions.get(0).getDisplayName());
+ groupForm.setBorder("1px solid #AAA");
+ groupForm.validate();
+ layout.addMember(groupForm);
+ }
} else {
- // One or more prop groups, so create a section stack with one section per group.
+ // Two or more prop groups, so create a section stack with one section per group.
final SectionStack sectionStack = new SectionStack();
sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE);
sectionStack.setWidth100();
@@ -441,7 +453,6 @@ public class ConfigurationEditor extends EnhancedVLayout {
// com.allen_sauer.gwt.log.client.Log.info("building: " + definition.getDisplayName());
sectionStack.addSection(buildGroupSection(definition));
}
-
this.toolStrip = buildToolStrip(layout, sectionStack);
layout.addMember(toolStrip);
layout.addMember(sectionStack);
10 years, 9 months
[rhq] 2 commits - etc/rhq-ircBot modules/enterprise
by Jiri Kremser
etc/rhq-ircBot/src/main/resources/org/rhq/etc/ircbot/cacerts.jks |binary
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java | 4 ++--
2 files changed, 2 insertions(+), 2 deletions(-)
New commits:
commit ef3e3e3912fa2f015edf6f2eea8b0217bb7b9999
Author: Jirka Kremser <jkremser(a)redhat.com>
Date: Mon Jul 29 13:19:16 2013 +0200
Adding the newly (6/28/13) issued certificate for accessing the pto calendar (mail.corp.redhat.com domain) to the rhq-ircbot keystore. This one should be valid until 6/28/15.
diff --git a/etc/rhq-ircBot/src/main/resources/org/rhq/etc/ircbot/cacerts.jks b/etc/rhq-ircBot/src/main/resources/org/rhq/etc/ircbot/cacerts.jks
index 3d73cbc..431de7c 100644
Binary files a/etc/rhq-ircBot/src/main/resources/org/rhq/etc/ircbot/cacerts.jks and b/etc/rhq-ircBot/src/main/resources/org/rhq/etc/ircbot/cacerts.jks differ
commit f9f495ce4c2c0419cd75ca47096c3af9644a3250
Author: Jirka Kremser <jkremser(a)redhat.com>
Date: Mon Jul 29 12:54:06 2013 +0200
Calling the right setter.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java
index 7d861f1..049cf42 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java
@@ -310,7 +310,7 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
if ((scheduleId = scheduleIdsMap.get(totalDiskUsedPercentageMetric)) != null) {
StorageNodeLoadComposite.MeasurementAggregateWithUnits totalDiskUsedPercentageAggregateWithUnits = getMeasurementAggregateWithUnits(
subject, scheduleId, MeasurementUnits.PERCENTAGE, beginTime, endTime);
- result.setDataDiskUsedPercentage(totalDiskUsedPercentageAggregateWithUnits);
+ result.setTotalDiskUsedPercentage(totalDiskUsedPercentageAggregateWithUnits);
}
if ((scheduleId = scheduleIdsMap.get(freeDiskToDataRatioMetric)) != null) {
MeasurementAggregate freeDiskToDataRatioAggregate = measurementManager.getAggregate(subject,
@@ -754,4 +754,4 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
return successResultFound;
}
-}
\ No newline at end of file
+}
10 years, 9 months
[rhq] modules/plugins
by John Sanda
modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java | 19 ++++++++--
1 file changed, 16 insertions(+), 3 deletions(-)
New commits:
commit c781acf5ce4680f4722cc6dfdeaadca2dfc110c8
Author: John Sanda <jsanda(a)redhat.com>
Date: Sun Jul 28 07:36:07 2013 -0400
override default ring delay to speed up test and hopefully fix jenkins failure
diff --git a/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java b/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java
index ef92510..bd171a4 100644
--- a/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java
+++ b/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java
@@ -29,6 +29,7 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.net.InetAddress;
+import java.util.Properties;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
@@ -73,6 +74,7 @@ import org.rhq.core.system.ProcessExecution;
import org.rhq.core.system.ProcessExecutionResults;
import org.rhq.core.system.SystemInfo;
import org.rhq.core.system.SystemInfoFactory;
+import org.rhq.core.util.PropertiesFileUpdate;
import org.rhq.core.util.stream.StreamUtil;
/**
@@ -124,6 +126,18 @@ public class StorageNodeComponentITest {
deployer.updateFilePerms();
deployer.updateStorageAuthConf(Sets.newHashSet(InetAddress.getByName(address)));
+ File confDir = new File(basedir, "conf");
+ File cassandraJvmPropsFile = new File(confDir, "cassandra-jvm.properties");
+ PropertiesFileUpdate propertiesUpdater = new PropertiesFileUpdate(cassandraJvmPropsFile.getAbsolutePath());
+ Properties properties = propertiesUpdater.loadExistingProperties();
+
+ String jvmOpts = properties.getProperty("JVM_OPTS");
+ jvmOpts = jvmOpts.substring(0, jvmOpts.lastIndexOf("\""));
+ jvmOpts = jvmOpts + " -Dcassandra.ring_delay_ms=100\"";
+ properties.setProperty("JVM_OPTS", jvmOpts);
+
+ propertiesUpdater.update(properties);
+
File binDir = new File(basedir, "bin");
SystemInfo systemInfo = SystemInfoFactory.createSystemInfo();
@@ -261,9 +275,8 @@ public class StorageNodeComponentITest {
log.info("Waiting for node to boostrap...");
// When a node goes through bootstrap, StorageService sleeps for RING_DELAY ms
// while it determines the ranges of the token ring it will own. RING_DELAY defaults
- // to 30 seconds by default.
- // TODO Override the default RING_DELAY to speed up tests
- Thread.sleep(33000);
+ // to 30 seconds by default but we are overriding it to be 100 ms.
+ Thread.sleep(3000);
assertEquals(result.getResultCode(), OperationServicesResultCode.SUCCESS, "The operation failed: " +
result.getErrorStackTrace());
10 years, 9 months
[rhq] modules/plugins
by John Sanda
modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/InternodeAuthConfUpdateException.java | 22 ++
modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java | 104 +++-------
modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java | 4
3 files changed, 64 insertions(+), 66 deletions(-)
New commits:
commit 96745558fb5c803bda91f5ac1180b17db8a76364
Author: John Sanda <jsanda(a)redhat.com>
Date: Sat Jul 27 14:08:18 2013 -0400
updating exception handling and logging in prepareForBootstrap
diff --git a/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/InternodeAuthConfUpdateException.java b/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/InternodeAuthConfUpdateException.java
new file mode 100644
index 0000000..d1e6e56
--- /dev/null
+++ b/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/InternodeAuthConfUpdateException.java
@@ -0,0 +1,22 @@
+package org.rhq.plugins.storage;
+
+/**
+ * @author John Sanda
+ */
+public class InternodeAuthConfUpdateException extends Exception {
+
+ public InternodeAuthConfUpdateException() {
+ }
+
+ public InternodeAuthConfUpdateException(String message) {
+ super(message);
+ }
+
+ public InternodeAuthConfUpdateException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public InternodeAuthConfUpdateException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java b/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java
index eb0b9fd..2cb9501 100644
--- a/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java
+++ b/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java
@@ -29,12 +29,10 @@ import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
-import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
-import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
@@ -95,6 +93,14 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
return new File(pluginConfig.getSimpleValue("baseDir"));
}
+ private File getConfDir() {
+ return new File(getBasedir(), "conf");
+ }
+
+ private File getInternodeAuthConfFile() {
+ return new File(getConfDir(), "rhq-storage-auth.conf");
+ }
+
@Override
public OperationResult invokeOperation(String name, Configuration parameters) throws Exception {
if (name.equals("addNodeMaintenance")) {
@@ -242,56 +248,24 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
ipAddresses.add(propertySimple.getStringValue());
}
- if (updateAuthFile(result, ipAddresses)) return result;
-
- EmsBean authBean = getEmsConnection().getBean("org.rhq.cassandra.auth:type=RhqInternodeAuthenticator");
- EmsOperation emsOperation = authBean.getOperation("reloadConfiguration");
- emsOperation.invoke();
-
- result.setSimpleResult("Successfully updated the set of known nodes.");
-
- return result;
- }
-
- private boolean updateAuthFile(OperationResult result, Set<String> ipAddresses) {
- log.info("Updating known nodes to " + ipAddresses);
+ try {
+ updateInternodeAuthConfFile(ipAddresses);
- File confDir = new File(getBasedir(), "conf");
- File authFile = new File(confDir, "rhq-storage-auth.conf");
- File authBackupFile = new File(confDir, "." + authFile.getName() + ".bak");
+ EmsBean authBean = getEmsConnection().getBean("org.rhq.cassandra.auth:type=RhqInternodeAuthenticator");
+ EmsOperation emsOperation = authBean.getOperation("reloadConfiguration");
+ emsOperation.invoke();
- if (authBackupFile.exists()) {
- if (log.isDebugEnabled()) {
- log.debug(authBackupFile + " already exists. Deleting it now in preparation of creating new backup " +
- "for " + authFile.getName());
- }
- if (!authBackupFile.delete()) {
- String msg = "Failed to delete backup file " + authBackupFile + ". The operation will abort " +
- "since " + authFile + " cannot reliably be backed up before making changes. Please delete " +
- authBackupFile + " manually and reschedule the operation once the file has been removed.";
- log.error(msg);
- result.setErrorMessage(msg);
-
- return true;
- }
- }
+ result.setSimpleResult("Successfully updated the set of known nodes.");
- try {
- StreamUtil.copy(new StringReader(StringUtil.collectionToString(ipAddresses, "\n")),
- new FileWriter(authFile), true);
- } catch (IOException e) {
- log.error("An error occurred while updating " + authFile, e);
- try {
- log.info("Restoring back up file " + authBackupFile);
- FileUtil.copyFile(authBackupFile, authFile);
- authBackupFile.delete();
- } catch (IOException e1) {
- log.error("Failed to revert backup of " + authFile, e1);
- }
- result.setErrorMessage("There was an unexpected error while updating " + authFile);
- return true;
+ return result;
+ } catch (InternodeAuthConfUpdateException e) {
+ File authFile = getInternodeAuthConfFile();
+ log.error("Failed to update set of trusted nodes in " + authFile + " due to the following error(s): " +
+ ThrowableUtil.getAllMessages(e)) ;
+ result.setErrorMessage("Failed to update set of trusted nodes in " + authFile + " due to the following " +
+ "error(s): " + ThrowableUtil.getAllMessages(e));
+ return result;
}
- return false;
}
private OperationResult prepareForBootstrap(Configuration params) {
@@ -326,7 +300,6 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
}
purgeDir(new File(configEditor.getSavedCachesDirectory()));
-
log.info("Updating cluster settings");
String address = pluginConfig.getSimpleValue("host");
@@ -344,10 +317,9 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
configEditor.setStoragePort(gossipPort);
configEditor.save();
+ log.info("Cluster configuration settings have been applied to " + yamlFile);
- if (updateAuthFile(result, new HashSet<String>(addresses))) {
- return result;
- }
+ updateInternodeAuthConfFile(new HashSet<String>(addresses));
log.info(this + " is ready to be bootstrap. Restarting storage node...");
OperationResult startResult = startNode();
@@ -376,6 +348,11 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
}
}
return result;
+ } catch (InternodeAuthConfUpdateException e) {
+ File authFile = getInternodeAuthConfFile();
+ result.setErrorMessage("Failed to update " + authFile + " due to the following error(s): " +
+ ThrowableUtil.getAllMessages(e));
+ return result;
}
}
@@ -384,23 +361,18 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
FileUtil.purge(dir, true);
}
- private File getCommitLogDir(Map yamlConfig) {
- return new File((String) yamlConfig.get("commitlog_directory"));
- }
+ private void updateInternodeAuthConfFile(Set<String> ipAddresses) throws InternodeAuthConfUpdateException {
+ File authFile = getInternodeAuthConfFile();
- private List<File> getDataDirs(Map yamlConfig) {
- List<File> dirs = new ArrayList<File>();
- List<String> dirNames = (List<String>) yamlConfig.get("data_file_directories");
+ log.info("Updating " + authFile);
- for (String dirName : dirNames) {
- dirs.add(new File(dirName));
+ try {
+ StreamUtil.copy(new StringReader(StringUtil.collectionToString(ipAddresses, "\n")),
+ new FileWriter(authFile), true);
+ } catch (Exception e) {
+ log.error("An error occurred while trying to update " + authFile, e);
+ throw new InternodeAuthConfUpdateException("An error occurred while trying to update " + authFile, e);
}
-
- return dirs;
- }
-
- private File getSavedCachesDir(Map yamlConfig) {
- return new File((String) yamlConfig.get("saved_caches_directory"));
}
private OperationResult nodeAdded(Configuration params) {
diff --git a/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java b/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java
index d10e428..ef92510 100644
--- a/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java
+++ b/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java
@@ -259,6 +259,10 @@ public class StorageNodeComponentITest {
params, timeout);
log.info("Waiting for node to boostrap...");
+ // When a node goes through bootstrap, StorageService sleeps for RING_DELAY ms
+ // while it determines the ranges of the token ring it will own. RING_DELAY defaults
+ // to 30 seconds by default.
+ // TODO Override the default RING_DELAY to speed up tests
Thread.sleep(33000);
assertEquals(result.getResultCode(), OperationServicesResultCode.SUCCESS, "The operation failed: " +
10 years, 9 months
[rhq] 2 commits - modules/common modules/plugins
by John Sanda
modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java | 111 +
modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditorException.java | 21
modules/common/cassandra-util/src/test/java/org/rhq/cassandra/util/ConfigEditorTest.java | 94 +
modules/common/cassandra-util/src/test/resources/cassandra.yaml | 690 ++++++++++
modules/plugins/cassandra/pom.xml | 9
modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java | 128 -
modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java | 51
7 files changed, 1031 insertions(+), 73 deletions(-)
New commits:
commit 237d38ea10fe57dfb699f01cd999c3aa53391ef4
Author: John Sanda <jsanda(a)redhat.com>
Date: Sat Jul 27 12:49:30 2013 -0400
adding some initial test coverage for prepareForBootstrap operation
The prepareForBootstrap method has been refactored to use ConfigEditor but
there is still a good bit of clean up to do.
diff --git a/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java b/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
index 679a84c..0b4a127 100644
--- a/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
+++ b/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
@@ -76,6 +76,22 @@ public class ConfigEditor {
}
}
+ public File getBackupFile() {
+ return backupFile;
+ }
+
+ public String getCommitLogDirectory() {
+ return (String) config.get("commitlog_directory");
+ }
+
+ public List<String> getDataFileDirectories() {
+ return (List<String>) config.get("data_file_directories");
+ }
+
+ public String getSavedCachesDirectory() {
+ return (String) config.get("saved_caches_directory");
+ }
+
public void setSeeds(String... seeds) {
List seedProviderList = (List) config.get("seed_provider");
Map seedProvider = (Map) seedProviderList.get(0);
diff --git a/modules/plugins/cassandra/pom.xml b/modules/plugins/cassandra/pom.xml
index da90f09..bafc8d7 100644
--- a/modules/plugins/cassandra/pom.xml
+++ b/modules/plugins/cassandra/pom.xml
@@ -36,6 +36,11 @@
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
+ <artifactId>rhq-cassandra-util</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
<artifactId>rhq-core-domain</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
@@ -89,6 +94,10 @@
<outputDirectory>${project.build.outputDirectory}/lib</outputDirectory>
<artifactItems>
<artifactItem>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>rhq-cassandra-util</artifactId>
+ </artifactItem>
+ <artifactItem>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>${cassandra.driver.version}</version>
diff --git a/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java b/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java
index 5933093..eb0b9fd 100644
--- a/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java
+++ b/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java
@@ -26,7 +26,6 @@
package org.rhq.plugins.storage;
import java.io.File;
-import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
@@ -45,9 +44,10 @@ import org.mc4j.ems.connection.EmsConnection;
import org.mc4j.ems.connection.bean.EmsBean;
import org.mc4j.ems.connection.bean.attribute.EmsAttribute;
import org.mc4j.ems.connection.bean.operation.EmsOperation;
-import org.yaml.snakeyaml.DumperOptions;
-import org.yaml.snakeyaml.Yaml;
+import org.yaml.snakeyaml.error.YAMLException;
+import org.rhq.cassandra.util.ConfigEditor;
+import org.rhq.cassandra.util.ConfigEditorException;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
import org.rhq.core.domain.configuration.Property;
@@ -277,27 +277,18 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
}
try {
- FileUtil.copyFile(authFile, authBackupFile);
- } catch (IOException e) {
- String msg = "Failed to backup " + authFile + " prior to making updates. The operation will abort due " +
- "to unexpected error";
- log.error(msg, e);
- result.setErrorMessage(msg + ": " + ThrowableUtil.getRootMessage(e));
- return true;
- }
-
- try {
StreamUtil.copy(new StringReader(StringUtil.collectionToString(ipAddresses, "\n")),
new FileWriter(authFile), true);
} catch (IOException e) {
log.error("An error occurred while updating " + authFile, e);
try {
+ log.info("Restoring back up file " + authBackupFile);
FileUtil.copyFile(authBackupFile, authFile);
+ authBackupFile.delete();
} catch (IOException e1) {
log.error("Failed to revert backup of " + authFile, e1);
}
- result.setErrorMessage("There was an unexpected error while updating " + authFile + ". Make sure that " +
- "it matches " + authBackupFile + " and then reschedule the operation.");
+ result.setErrorMessage("There was an unexpected error while updating " + authFile);
return true;
}
return false;
@@ -325,74 +316,67 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
String yamlProp = pluginConfig.getSimpleValue("yamlConfiguration");
File yamlFile = new File(yamlProp);
- DumperOptions options = new DumperOptions();
- options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
- Yaml yaml = new Yaml(options);
-
- Map yamlConfig = null;
+ ConfigEditor configEditor = new ConfigEditor(yamlFile);
try {
- yamlConfig = (Map) yaml.load(new FileInputStream(yamlFile));
- } catch (FileNotFoundException e) {
- log.error("Failed to load " + yamlFile, e);
- log.error("Cannot prepare " + this + " for bootstrap. " + yamlFile + " must exist in order to make the " +
- "necessary configuration changes.");
- result.setErrorMessage("Cannot prepare storage node for bootstrap. It appears that " + yamlFile +
- " does not exist. Make sure that it exists so that the necessary configuration changes can be made.");
+ configEditor.load();
- return result;
- }
+ purgeDir(new File(configEditor.getCommitLogDirectory()));
+ for (String dir : configEditor.getDataFileDirectories()) {
+ purgeDir(new File(dir));
+ }
+ purgeDir(new File(configEditor.getSavedCachesDirectory()));
- purgeDir(getCommitLogDir(yamlConfig));
- for (File dataDir : getDataDirs(yamlConfig)) {
- purgeDir(dataDir);
- }
- purgeDir(getSavedCachesDir(yamlConfig));
- log.info("Updating cluster settings");
+ log.info("Updating cluster settings");
- String address = pluginConfig.getSimpleValue("host");
- List<String> seeds = getAddresses(params.getList("storageNodeIPAddresses"));
- // Make sure this node's address is not in the list; otherwise, it
- // won't bootstrap properly.
- seeds.remove(address);
- try {
- updateSeedsList(seeds);
- } catch (IOException e) {
- log.error("Failed to update seeds property in " + yamlFile, e);
- result.setErrorMessage("Failed to prepared node for bootstrap due to unexpected error that occurred " +
- "while updating seeds property in " + yamlFile + ":\n" + ThrowableUtil.getAllMessages(e));
- return result;
- }
+ String address = pluginConfig.getSimpleValue("host");
+ int cqlPort = Integer.parseInt(params.getSimpleValue("cqlPort"));
+ int gossipPort = Integer.parseInt(params.getSimpleValue("gossipPort"));
+ List<String> addresses = getAddresses(params.getList("storageNodeIPAddresses"));
- if (updateAuthFile(result, new HashSet<String>(seeds))) {
- return result;
- }
+ // Make sure this node's address is not in the list; otherwise, it
+ // won't bootstrap properly.
+ List<String> seeds = new ArrayList<String>(addresses);
+ seeds.remove(address);
- int cqlPort = Integer.parseInt(params.getSimpleValue("cqlPort"));
- int gossipPort = Integer.parseInt(params.getSimpleValue("gossipPort"));
+ configEditor.setSeeds(seeds.toArray(new String[seeds.size()]));
+ configEditor.setNativeTransportPort(cqlPort);
+ configEditor.setStoragePort(gossipPort);
- yamlConfig.put("native_transport_port", cqlPort);
- yamlConfig.put("storage_port", gossipPort);
+ configEditor.save();
- try {
- yaml.dump(yamlConfig, new FileWriter(yamlFile));
- } catch (IOException e) {
- log.error("Could not update cluster settings in " + yamlFile, e);
- result.setErrorMessage("Could not update cluster settings in " + yamlFile + ":\n" +
- ThrowableUtil.getAllMessages(e));
- return result;
- }
+ if (updateAuthFile(result, new HashSet<String>(addresses))) {
+ return result;
+ }
- log.info(this + " is ready to be bootstrap. Restarting storage node...");
- OperationResult startResult = startNode();
- if (startResult.getErrorMessage() != null) {
- log.error("Failed to restart storage node:\n" + startResult.getErrorMessage());
- result.setErrorMessage("Failed to restart storage node:\n" + startResult.getErrorMessage());
- } else {
- result.setSimpleResult("The storage node was succesfully updated is now bootstrapping into the cluster.");
- }
+ log.info(this + " is ready to be bootstrap. Restarting storage node...");
+ OperationResult startResult = startNode();
+ if (startResult.getErrorMessage() != null) {
+ log.error("Failed to restart storage node:\n" + startResult.getErrorMessage());
+ result.setErrorMessage("Failed to restart storage node:\n" + startResult.getErrorMessage());
+ } else {
+ result.setSimpleResult("The storage node was succesfully updated is now bootstrapping into the cluster.");
+ }
- return result;
+ return result;
+ } catch (ConfigEditorException e) {
+ log.error("There was an error while trying to update " + yamlFile, e);
+ if (e.getCause() instanceof YAMLException) {
+ log.info("Attempting to restore " + yamlFile);
+ try {
+ configEditor.restore();
+ result.setErrorMessage("Failed to update configuration file [" + yamlFile + "]: " +
+ ThrowableUtil.getAllMessages(e.getCause()));
+ } catch (ConfigEditorException e1) {
+ log.error("Failed to restore " + yamlFile + ". A copy of the file prior to any modifications " +
+ "can be found at " + configEditor.getBackupFile());
+ result.setErrorMessage("There was an error updating [" + yamlFile + "] and undoing the changes " +
+ "Failed. A copy of the file can be found at " + configEditor.getBackupFile() + ". See the " +
+ "agent logs for more details");
+ }
+ }
+ return result;
+ }
}
private void purgeDir(File dir) {
diff --git a/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java b/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java
index eb4d545..d10e428 100644
--- a/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java
+++ b/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java
@@ -26,15 +26,25 @@ import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileReader;
import java.net.InetAddress;
import java.util.Set;
+import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
+import org.apache.cassandra.config.Config;
+import org.apache.cassandra.config.SeedProviderDef;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.hyperic.sigar.OperatingSystem;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
+import org.yaml.snakeyaml.Loader;
+import org.yaml.snakeyaml.TypeDescription;
+import org.yaml.snakeyaml.Yaml;
import org.rhq.cassandra.CassandraClusterManager;
import org.rhq.cassandra.ClusterInitService;
@@ -63,12 +73,15 @@ import org.rhq.core.system.ProcessExecution;
import org.rhq.core.system.ProcessExecutionResults;
import org.rhq.core.system.SystemInfo;
import org.rhq.core.system.SystemInfoFactory;
+import org.rhq.core.util.stream.StreamUtil;
/**
* @author John Sanda
*/
public class StorageNodeComponentITest {
+ private final Log log = LogFactory.getLog(StorageNodeComponentITest.class);
+
private File basedir;
private Resource storageNode;
@@ -232,7 +245,7 @@ public class StorageNodeComponentITest {
}
@Test(dependsOnMethods = "restartStorageNode")
- public void prepareForBootstrap() {
+ public void prepareForBootstrap() throws Exception {
Configuration params = Configuration.builder().addSimple("cqlPort", 9242).addSimple("gossipPort", 7200)
.openList("storageNodeIPAddresses", "storageNodeIPAddresse").addSimples("127.0.0.1", "127.0.0.2")
.closeList().build();
@@ -245,10 +258,22 @@ public class StorageNodeComponentITest {
OperationServicesResult result = operationsService.invokeOperation(operationContext, "prepareForBootstrap",
params, timeout);
+ log.info("Waiting for node to boostrap...");
+ Thread.sleep(33000);
+
assertEquals(result.getResultCode(), OperationServicesResultCode.SUCCESS, "The operation failed: " +
result.getErrorStackTrace());
assertNodeIsUp("Expected " + storageNode + " to be up after the prepareForBootstrap operation completes.");
+
+ assertThatInternodeAuthConfFileMatches("127.0.0.1", "127.0.0.2");
+
+ File confDir = new File(basedir, "conf");
+ File cassandraYamlFile = new File(confDir, "cassandra.yaml");
+ Config config = loadConfig(cassandraYamlFile);
+
+ assertEquals(config.seed_provider.parameters.get("seeds"), "127.0.0.2", "Failed to update seeds " +
+ "property in " + cassandraYamlFile);
}
private void assertNodeIsUp(String msg) {
@@ -292,4 +317,28 @@ public class StorageNodeComponentITest {
return type.getPlugin().equals("RHQStorage") && type.getName().equals("RHQ Storage Node");
}
+ private void assertThatInternodeAuthConfFileMatches(String... addresses) throws Exception {
+ File confDir = new File(basedir, "conf");
+ File internodeAuthConfFile = new File(confDir, "rhq-storage-auth.conf");
+ String contents = StreamUtil.slurp(new FileReader(internodeAuthConfFile));
+
+ Set<String> expected = ImmutableSet.copyOf(addresses);
+ Set<String> actual = ImmutableSet.copyOf(contents.split("\n"));
+
+ assertEquals(actual, expected, "Failed to update internode authentication conf file " +
+ internodeAuthConfFile + ".");
+ }
+
+ private Config loadConfig(File configFile) throws Exception {
+ FileInputStream inputStream = new FileInputStream(configFile);
+ org.yaml.snakeyaml.constructor.Constructor constructor =
+ new org.yaml.snakeyaml.constructor.Constructor(Config.class);
+ TypeDescription seedDesc = new TypeDescription(SeedProviderDef.class);
+ seedDesc.putMapPropertyType("parameters", String.class, String.class);
+ constructor.addTypeDescription(seedDesc);
+ Yaml yaml = new Yaml(new Loader(constructor));
+
+ return (Config) yaml.load(inputStream);
+ }
+
}
commit 30c6d6678edbb44bd7b07db0cd2855b9f1790aba
Author: John Sanda <jsanda(a)redhat.com>
Date: Sat Jul 27 10:14:18 2013 -0400
initial commit for ConfigEditor which handles updating cassandra.yaml
diff --git a/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java b/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
new file mode 100644
index 0000000..679a84c
--- /dev/null
+++ b/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditor.java
@@ -0,0 +1,95 @@
+package org.rhq.cassandra.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+import org.yaml.snakeyaml.DumperOptions;
+import org.yaml.snakeyaml.Yaml;
+
+import org.rhq.core.util.StringUtil;
+import org.rhq.core.util.file.FileUtil;
+
+/**
+ * @author John Sanda
+ */
+public class ConfigEditor {
+
+ private File configFile;
+
+ private File backupFile;
+
+ private Yaml yaml;
+
+ private Map config;
+
+ public ConfigEditor(File cassandraYamlFile) {
+ configFile = cassandraYamlFile;
+ }
+
+ public void load() {
+ try {
+ DumperOptions options = new DumperOptions();
+ options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
+ yaml = new Yaml(options);
+ config = (Map) yaml.load(new FileInputStream(configFile));
+ createBackup();
+ } catch (FileNotFoundException e) {
+ throw new ConfigEditorException("Failed to load " + configFile, e);
+ }
+ }
+
+ public void save() {
+ try {
+ yaml.dump(config, new FileWriter(configFile));
+ backupFile.delete();
+ yaml = null;
+ config = null;
+ backupFile = null;
+ } catch (Exception e) {
+ throw new ConfigEditorException("Failed to save changes to " + configFile, e);
+ }
+ }
+
+ public void restore() {
+ try {
+ FileUtil.copyFile(backupFile, configFile);
+ backupFile.delete();
+ yaml = null;
+ config = null;
+ backupFile = null;
+ } catch (IOException e) {
+ throw new ConfigEditorException("Failed to restore " + configFile + " from " + backupFile, e);
+ }
+ }
+
+ private void createBackup() {
+ backupFile = new File(configFile.getParent(), "." + configFile.getName() + ".bak");
+ try {
+ FileUtil.copyFile(configFile, backupFile);
+ } catch (IOException e) {
+ throw new ConfigEditorException("Failed to create " + backupFile, e);
+ }
+ }
+
+ public void setSeeds(String... seeds) {
+ List seedProviderList = (List) config.get("seed_provider");
+ Map seedProvider = (Map) seedProviderList.get(0);
+ List paramsList = (List) seedProvider.get("parameters");
+ Map params = (Map) paramsList.get(0);
+ params.put("seeds", StringUtil.arrayToString(seeds));
+ }
+
+ public void setNativeTransportPort(int port) {
+ config.put("native_transport_port", port);
+ }
+
+ public void setStoragePort(int port) {
+ config.put("storage_port", port);
+ }
+
+}
diff --git a/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditorException.java b/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditorException.java
new file mode 100644
index 0000000..db9e7ea
--- /dev/null
+++ b/modules/common/cassandra-util/src/main/java/org/rhq/cassandra/util/ConfigEditorException.java
@@ -0,0 +1,21 @@
+package org.rhq.cassandra.util;
+
+/**
+ * @author John Sanda
+ */
+public class ConfigEditorException extends RuntimeException {
+
+ public ConfigEditorException() {
+ }
+
+ public ConfigEditorException(String message) {
+ }
+
+ public ConfigEditorException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public ConfigEditorException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/modules/common/cassandra-util/src/test/java/org/rhq/cassandra/util/ConfigEditorTest.java b/modules/common/cassandra-util/src/test/java/org/rhq/cassandra/util/ConfigEditorTest.java
new file mode 100644
index 0000000..cf344e2
--- /dev/null
+++ b/modules/common/cassandra-util/src/test/java/org/rhq/cassandra/util/ConfigEditorTest.java
@@ -0,0 +1,94 @@
+package org.rhq.cassandra.util;
+
+import static org.testng.Assert.assertEquals;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.lang.reflect.Method;
+
+import org.apache.cassandra.config.Config;
+import org.apache.cassandra.config.SeedProviderDef;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.yaml.snakeyaml.Loader;
+import org.yaml.snakeyaml.TypeDescription;
+import org.yaml.snakeyaml.Yaml;
+
+import org.rhq.core.util.file.FileUtil;
+import org.rhq.core.util.stream.StreamUtil;
+
+/**
+ * @author John Sanda
+ */
+public class ConfigEditorTest {
+
+ private File basedir;
+
+ private File configFile;
+
+ @BeforeMethod
+ public void initTestDir(Method test) throws Exception {
+ File dir = new File(getClass().getResource(".").toURI());
+ basedir = new File(dir, getClass().getSimpleName() + "/" + test.getName());
+ FileUtil.purge(basedir, true);
+ basedir.mkdirs();
+
+ configFile = new File(basedir, "cassandra.yaml");
+
+ InputStream inputStream = getClass().getResourceAsStream("/cassandra.yaml");
+ FileOutputStream outputStream = new FileOutputStream(configFile);
+ StreamUtil.copy(inputStream, outputStream);
+ }
+
+ @Test
+ public void updateSeeds() throws Exception {
+ ConfigEditor editor = new ConfigEditor(configFile);
+ editor.load();
+ editor.setSeeds("127.0.0.1", "127.0.0.2", "127.0.0.3");
+ editor.save();
+
+ Config config = loadConfig();
+
+ assertEquals(config.seed_provider.parameters.get("seeds"), "127.0.0.1,127.0.0.2,127.0.0.3",
+ "Failed to update seeds property.");
+ }
+
+ @Test
+ public void updateNativeTransportPort() throws Exception {
+ ConfigEditor editor = new ConfigEditor(configFile);
+ editor.load();
+ editor.setNativeTransportPort(9393);
+ editor.save();
+
+ Config config = loadConfig();
+
+ assertEquals(config.native_transport_port, (Integer) 9393, "Failed to update native_transport_port");
+ }
+
+ @Test
+ public void updateStoragePort() throws Exception {
+ ConfigEditor editor = new ConfigEditor(configFile);
+ editor.load();
+ editor.setStoragePort(6767);
+ editor.save();
+
+ Config config = loadConfig();
+
+ assertEquals(config.storage_port, (Integer) 6767, "Failed to update storage_port");
+ }
+
+ private Config loadConfig() throws Exception {
+ FileInputStream inputStream = new FileInputStream(configFile);
+ org.yaml.snakeyaml.constructor.Constructor constructor =
+ new org.yaml.snakeyaml.constructor.Constructor(Config.class);
+ TypeDescription seedDesc = new TypeDescription(SeedProviderDef.class);
+ seedDesc.putMapPropertyType("parameters", String.class, String.class);
+ constructor.addTypeDescription(seedDesc);
+ Yaml yaml = new Yaml(new Loader(constructor));
+
+ return (Config) yaml.load(inputStream);
+ }
+
+}
diff --git a/modules/common/cassandra-util/src/test/resources/cassandra.yaml b/modules/common/cassandra-util/src/test/resources/cassandra.yaml
new file mode 100644
index 0000000..fd7973b
--- /dev/null
+++ b/modules/common/cassandra-util/src/test/resources/cassandra.yaml
@@ -0,0 +1,690 @@
+# Cassandra storage config YAML
+
+# NOTE:
+# See http://wiki.apache.org/cassandra/StorageConfiguration for
+# full explanations of configuration directives
+# /NOTE
+
+# The name of the cluster. This is mainly used to prevent machines in
+# one logical cluster from joining another.
+cluster_name: rhq
+
+# This defines the number of tokens randomly assigned to this node on the ring
+# The more tokens, relative to other nodes, the larger the proportion of data
+# that this node will store. You probably want all nodes to have the same number
+# of tokens assuming they have equal hardware capability.
+#
+# If you leave this unspecified, Cassandra will use the default of 1 token for legacy compatibility,
+# and will use the initial_token as described below.
+#
+# Specifying initial_token will override this setting.
+#
+# If you already have a cluster with 1 token per node, and wish to migrate to
+# multiple tokens per node, see http://wiki.apache.org/cassandra/Operations
+num_tokens: 256
+
+# If you haven't specified num_tokens, or have set it to the default of 1 then
+# you should always specify InitialToken when setting up a production
+# cluster for the first time, and often when adding capacity later.
+# The principle is that each node should be given an equal slice of
+# the token ring; see http://wiki.apache.org/cassandra/Operations
+# for more details.
+#
+# If blank, Cassandra will request a token bisecting the range of
+# the heaviest-loaded existing node. If there is no load information
+# available, such as is the case with a new cluster, it will pick
+# a random token, which will lead to hot spots.
+#initial_token:
+
+# See http://wiki.apache.org/cassandra/HintedHandoff
+hinted_handoff_enabled: true
+# this defines the maximum amount of time a dead host will have hints
+# generated. After it has been dead this long, new hints for it will not be
+# created until it has been seen alive and gone down again.
+max_hint_window_in_ms: 10800000 # 3 hours
+# throttle in KB's per second, per delivery thread
+hinted_handoff_throttle_in_kb: 1024
+# Number of threads with which to deliver hints;
+# Consider increasing this number when you have multi-dc deployments, since
+# cross-dc handoff tends to be slower
+max_hints_delivery_threads: 2
+
+# The following setting populates the page cache on memtable flush and compaction
+# WARNING: Enable this setting only when the whole node's data fits in memory.
+# Defaults to: false
+# populate_io_cache_on_flush: false
+
+# Authentication backend, implementing IAuthenticator; used to identify users
+# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthenticator,
+# PasswordAuthenticator}.
+#
+# - AllowAllAuthenticator performs no checks - set it to disable authentication.
+# - PasswordAuthenticator relies on username/password pairs to authenticate
+# users. It keeps usernames and hashed passwords in system_auth.credentials table.
+# Please increase system_auth keyspace replication factor if you use this authenticator.
+authenticator: org.apache.cassandra.auth.PasswordAuthenticator
+
+# Authorization backend, implementing IAuthorizer; used to limit access/provide permissions
+# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthorizer,
+# CassandraAuthorizer}.
+#
+# - AllowAllAuthorizer allows any action to any user - set it to disable authorization.
+# - CassandraAuthorizer stores permissions in system_auth.permissions table. Please
+# increase system_auth keyspace replication factor if you use this authorizer.
+authorizer: org.apache.cassandra.auth.CassandraAuthorizer
+
+# Validity period for permissions cache (fetching permissions can be an
+# expensive operation depending on the authorizer, CassandraAuthorizer is
+# one example). Defaults to 2000, set to 0 to disable.
+# Will be disabled automatically for AllowAllAuthorizer.
+permissions_validity_in_ms: 2000
+
+# The partitioner is responsible for distributing rows (by key) across
+# nodes in the cluster. Any IPartitioner may be used, including your
+# own as long as it is on the classpath. Out of the box, Cassandra
+# provides org.apache.cassandra.dht.{Murmur3Partitioner, RandomPartitioner
+# ByteOrderedPartitioner, OrderPreservingPartitioner (deprecated)}.
+#
+# - RandomPartitioner distributes rows across the cluster evenly by md5.
+# This is the default prior to 1.2 and is retained for compatibility.
+# - Murmur3Partitioner is similar to RandomPartioner but uses Murmur3_128
+# Hash Function instead of md5. When in doubt, this is the best option.
+# - ByteOrderedPartitioner orders rows lexically by key bytes. BOP allows
+# scanning rows in key order, but the ordering can generate hot spots
+# for sequential insertion workloads.
+# - OrderPreservingPartitioner is an obsolete form of BOP, that stores
+# - keys in a less-efficient format and only works with keys that are
+# UTF8-encoded Strings.
+# - CollatingOPP colates according to EN,US rules rather than lexical byte
+# ordering. Use this as an example if you need custom collation.
+#
+# See http://wiki.apache.org/cassandra/Operations for more on
+# partitioners and token selection.
+partitioner: org.apache.cassandra.dht.Murmur3Partitioner
+
+# directories where Cassandra should store data on disk.
+data_file_directories:
+ - /Users/jsanda/Development/redhat/rhq/rhq-data/storage-1/data
+
+# commit log
+commitlog_directory: /Users/jsanda/Development/redhat/rhq/rhq-data/storage-1/commit_log
+
+# policy for data disk failures:
+# stop: shut down gossip and Thrift, leaving the node effectively dead, but
+# still inspectable via JMX.
+# best_effort: stop using the failed disk and respond to requests based on
+# remaining available sstables. This means you WILL see obsolete
+# data at CL.ONE!
+# ignore: ignore fatal errors and let requests fail, as in pre-1.2 Cassandra
+disk_failure_policy: stop
+
+# Maximum size of the key cache in memory.
+#
+# Each key cache hit saves 1 seek and each row cache hit saves 2 seeks at the
+# minimum, sometimes more. The key cache is fairly tiny for the amount of
+# time it saves, so it's worthwhile to use it at large numbers.
+# The row cache saves even more time, but must store the whole values of
+# its rows, so it is extremely space-intensive. It's best to only use the
+# row cache if you have hot rows or static rows.
+#
+# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.
+#
+# Default value is empty to make it "auto" (min(5% of Heap (in MB), 100MB)). Set to 0 to disable key cache.
+key_cache_size_in_mb:
+
+# Duration in seconds after which Cassandra should
+# safe the keys cache. Caches are saved to saved_caches_directory as
+# specified in this configuration file.
+#
+# Saved caches greatly improve cold-start speeds, and is relatively cheap in
+# terms of I/O for the key cache. Row cache saving is much more expensive and
+# has limited use.
+#
+# Default is 14400 or 4 hours.
+key_cache_save_period: 14400
+
+# Number of keys from the key cache to save
+# Disabled by default, meaning all keys are going to be saved
+# key_cache_keys_to_save: 100
+
+# Maximum size of the row cache in memory.
+# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.
+#
+# Default value is 0, to disable row caching.
+row_cache_size_in_mb: 0
+
+# Duration in seconds after which Cassandra should
+# safe the row cache. Caches are saved to saved_caches_directory as specified
+# in this configuration file.
+#
+# Saved caches greatly improve cold-start speeds, and is relatively cheap in
+# terms of I/O for the key cache. Row cache saving is much more expensive and
+# has limited use.
+#
+# Default is 0 to disable saving the row cache.
+row_cache_save_period: 0
+
+# Number of keys from the row cache to save
+# Disabled by default, meaning all keys are going to be saved
+# row_cache_keys_to_save: 100
+
+# The provider for the row cache to use.
+#
+# Supported values are: ConcurrentLinkedHashCacheProvider, SerializingCacheProvider
+#
+# SerializingCacheProvider serialises the contents of the row and stores
+# it in native memory, i.e., off the JVM Heap. Serialized rows take
+# significantly less memory than "live" rows in the JVM, so you can cache
+# more rows in a given memory footprint. And storing the cache off-heap
+# means you can use smaller heap sizes, reducing the impact of GC pauses.
+#
+# It is also valid to specify the fully-qualified class name to a class
+# that implements org.apache.cassandra.cache.IRowCacheProvider.
+#
+# Defaults to SerializingCacheProvider
+row_cache_provider: SerializingCacheProvider
+
+# saved caches
+saved_caches_directory: /Users/jsanda/Development/redhat/rhq/rhq-data/storage-1/saved_caches
+
+# commitlog_sync may be either "periodic" or "batch."
+# When in batch mode, Cassandra won't ack writes until the commit log
+# has been fsynced to disk. It will wait up to
+# commitlog_sync_batch_window_in_ms milliseconds for other writes, before
+# performing the sync.
+#
+# commitlog_sync: batch
+# commitlog_sync_batch_window_in_ms: 50
+#
+# the other option is "periodic" where writes may be acked immediately
+# and the CommitLog is simply synced every commitlog_sync_period_in_ms
+# milliseconds.
+commitlog_sync: periodic
+commitlog_sync_period_in_ms: 10000
+
+# The size of the individual commitlog file segments. A commitlog
+# segment may be archived, deleted, or recycled once all the data
+# in it (potentally from each columnfamily in the system) has been
+# flushed to sstables.
+#
+# The default size is 32, which is almost always fine, but if you are
+# archiving commitlog segments (see commitlog_archiving.properties),
+# then you probably want a finer granularity of archiving; 8 or 16 MB
+# is reasonable.
+commitlog_segment_size_in_mb: 32
+
+# any class that implements the SeedProvider interface and has a
+# constructor that takes a Map<String, String> of parameters will do.
+seed_provider:
+ # Addresses of hosts that are deemed contact points.
+ # Cassandra nodes use this list of hosts to find each other and learn
+ # the topology of the ring. You must change this if you are running
+ # multiple nodes!
+ - class_name: org.apache.cassandra.locator.SimpleSeedProvider
+ parameters:
+ # seeds is actually a comma-delimited list of addresses.
+ # Ex: "<ip1>,<ip2>,<ip3>"
+ - seeds: "127.0.0.1"
+
+# emergency pressure valve: each time heap usage after a full (CMS)
+# garbage collection is above this fraction of the max, Cassandra will
+# flush the largest memtables.
+#
+# Set to 1.0 to disable. Setting this lower than
+# CMSInitiatingOccupancyFraction is not likely to be useful.
+#
+# RELYING ON THIS AS YOUR PRIMARY TUNING MECHANISM WILL WORK POORLY:
+# it is most effective under light to moderate load, or read-heavy
+# workloads; under truly massive write load, it will often be too
+# little, too late.
+flush_largest_memtables_at: 0.75
+
+# emergency pressure valve #2: the first time heap usage after a full
+# (CMS) garbage collection is above this fraction of the max,
+# Cassandra will reduce cache maximum _capacity_ to the given fraction
+# of the current _size_. Should usually be set substantially above
+# flush_largest_memtables_at, since that will have less long-term
+# impact on the system.
+#
+# Set to 1.0 to disable. Setting this lower than
+# CMSInitiatingOccupancyFraction is not likely to be useful.
+reduce_cache_sizes_at: 0.85
+reduce_cache_capacity_to: 0.6
+
+# For workloads with more data than can fit in memory, Cassandra's
+# bottleneck will be reads that need to fetch data from
+# disk. "concurrent_reads" should be set to (16 * number_of_drives) in
+# order to allow the operations to enqueue low enough in the stack
+# that the OS and drives can reorder them.
+#
+# On the other hand, since writes are almost never IO bound, the ideal
+# number of "concurrent_writes" is dependent on the number of cores in
+# your system; (8 * number_of_cores) is a good rule of thumb.
+concurrent_reads: 32
+concurrent_writes: 32
+
+# Total memory to use for memtables. Cassandra will flush the largest
+# memtable when this much memory is used.
+# If omitted, Cassandra will set it to 1/3 of the heap.
+# memtable_total_space_in_mb: 2048
+
+# Total space to use for commitlogs. Since commitlog segments are
+# mmapped, and hence use up address space, the default size is 32
+# on 32-bit JVMs, and 1024 on 64-bit JVMs.
+#
+# If space gets above this value (it will round up to the next nearest
+# segment multiple), Cassandra will flush every dirty CF in the oldest
+# segment and remove it. So a small total commitlog space will tend
+# to cause more flush activity on less-active columnfamilies.
+# commitlog_total_space_in_mb: 4096
+
+# This sets the amount of memtable flush writer threads. These will
+# be blocked by disk io, and each one will hold a memtable in memory
+# while blocked. If you have a large heap and many data directories,
+# you can increase this value for better flush performance.
+# By default this will be set to the amount of data directories defined.
+#memtable_flush_writers: 1
+
+# the number of full memtables to allow pending flush, that is,
+# waiting for a writer thread. At a minimum, this should be set to
+# the maximum number of secondary indexes created on a single CF.
+memtable_flush_queue_size: 4
+
+# Whether to, when doing sequential writing, fsync() at intervals in
+# order to force the operating system to flush the dirty
+# buffers. Enable this to avoid sudden dirty buffer flushing from
+# impacting read latencies. Almost always a good idea on SSD:s; not
+# necessarily on platters.
+trickle_fsync: false
+trickle_fsync_interval_in_kb: 10240
+
+# TCP port, for commands and data
+storage_port: 7100
+
+# SSL port, for encrypted communication. Unused unless enabled in
+# encryption_options
+ssl_storage_port: 7101
+
+# Address to bind to and tell other Cassandra nodes to connect to. You
+# _must_ change this if you want multiple nodes to be able to
+# communicate!
+#
+# Leaving it blank leaves it up to InetAddress.getLocalHost(). This
+# will always do the Right Thing *if* the node is properly configured
+# (hostname, name resolution, etc), and the Right Thing is to use the
+# address associated with the hostname (it might not be).
+#
+# Setting this to 0.0.0.0 is always wrong.
+listen_address: 127.0.0.1
+
+# Address to broadcast to other Cassandra nodes
+# Leaving this blank will set it to the same value as listen_address
+# broadcast_address: 1.2.3.4
+
+# Internode authentication backend, implementing IInternodeAuthenticator;
+# used to allow/disallow connections from peer nodes.
+internode_authenticator: org.rhq.cassandra.auth.RhqInternodeAuthenticator
+
+# Whether to start the native transport server.
+# Currently, only the thrift server is started by default because the native
+# transport is considered beta.
+# Please note that the address on which the native transport is bound is the
+# same as the rpc_address. The port however is different and specified below.
+start_native_transport: true
+# port for the CQL native transport to listen for clients on
+native_transport_port: 9142
+# The minimum and maximum threads for handling requests when the native
+# transport is used. The meaning is those is similar to the one of
+# rpc_min_threads and rpc_max_threads, though the default differ slightly and
+# are the ones below:
+# native_transport_min_threads: 16
+native_transport_max_threads: 128
+
+
+# Whether to start the thrift rpc server.
+start_rpc: false
+# The address to bind the Thrift RPC service to -- clients connect
+# here. Unlike ListenAddress above, you *can* specify 0.0.0.0 here if
+# you want Thrift to listen on all interfaces.
+#
+# Leaving this blank has the same effect it does for ListenAddress,
+# (i.e. it will be based on the configured hostname of the node).
+rpc_address: 127.0.0.1
+# port for Thrift to listen for clients on
+rpc_port: 9160
+
+# enable or disable keepalive on rpc connections
+rpc_keepalive: true
+
+# Cassandra provides three out-of-the-box options for the RPC Server:
+#
+# sync -> One thread per thrift connection. For a very large number of clients, memory
+# will be your limiting factor. On a 64 bit JVM, 128KB is the minimum stack size
+# per thread, and that will correspond to your use of virtual memory (but physical memory
+# may be limited depending on use of stack space).
+#
+# hsha -> Stands for "half synchronous, half asynchronous." All thrift clients are handled
+# asynchronously using a small number of threads that does not vary with the amount
+# of thrift clients (and thus scales well to many clients). The rpc requests are still
+# synchronous (one thread per active request).
+#
+# The default is sync because on Windows hsha is about 30% slower. On Linux,
+# sync/hsha performance is about the same, with hsha of course using less memory.
+#
+# Alternatively, can provide your own RPC server by providing the fully-qualified class name
+# of an o.a.c.t.TServerFactory that can create an instance of it.
+rpc_server_type: sync
+
+# Uncomment rpc_min|max_thread to set request pool size limits.
+#
+# Regardless of your choice of RPC server (see above), the number of maximum requests in the
+# RPC thread pool dictates how many concurrent requests are possible (but if you are using the sync
+# RPC server, it also dictates the number of clients that can be connected at all).
+#
+# The default is unlimited and thus provide no protection against clients overwhelming the server. You are
+# encouraged to set a maximum that makes sense for you in production, but do keep in mind that
+# rpc_max_threads represents the maximum number of client requests this server may execute concurrently.
+#
+# rpc_min_threads: 16
+# rpc_max_threads: 2048
+
+# uncomment to set socket buffer sizes on rpc connections
+# rpc_send_buff_size_in_bytes:
+# rpc_recv_buff_size_in_bytes:
+
+# uncomment to set socket buffer size for internode communication
+# Note that when setting this, the buffer size is limited by net.core.wmem_max
+# and when not setting it it is defined by net.ipv4.tcp_wmem
+# See:
+# /proc/sys/net/core/wmem_max
+# /proc/sys/net/core/rmem_max
+# /proc/sys/net/ipv4/tcp_wmem
+# /proc/sys/net/ipv4/tcp_wmem
+# and: man tcp
+# internode_send_buff_size_in_bytes:
+# internode_recv_buff_size_in_bytes:
+
+# Frame size for thrift (maximum field length).
+thrift_framed_transport_size_in_mb: 15
+
+# The max length of a thrift message, including all fields and
+# internal thrift overhead.
+thrift_max_message_length_in_mb: 16
+
+# Set to true to have Cassandra create a hard link to each sstable
+# flushed or streamed locally in a backups/ subdirectory of the
+# Keyspace data. Removing these links is the operator's
+# responsibility.
+incremental_backups: false
+
+# Whether or not to take a snapshot before each compaction. Be
+# careful using this option, since Cassandra won't clean up the
+# snapshots for you. Mostly useful if you're paranoid when there
+# is a data format change.
+snapshot_before_compaction: false
+
+# Whether or not a snapshot is taken of the data before keyspace truncation
+# or dropping of column families. The STRONGLY advised default of true
+# should be used to provide data safety. If you set this flag to false, you will
+# lose data on truncation or drop.
+auto_snapshot: true
+
+# Add column indexes to a row after its contents reach this size.
+# Increase if your column values are large, or if you have a very large
+# number of columns. The competing causes are, Cassandra has to
+# deserialize this much of the row to read a single column, so you want
+# it to be small - at least if you do many partial-row reads - but all
+# the index data is read for each access, so you don't want to generate
+# that wastefully either.
+column_index_size_in_kb: 64
+
+# Size limit for rows being compacted in memory. Larger rows will spill
+# over to disk and use a slower two-pass compaction process. A message
+# will be logged specifying the row key.
+in_memory_compaction_limit_in_mb: 64
+
+# Number of simultaneous compactions to allow, NOT including
+# validation "compactions" for anti-entropy repair. Simultaneous
+# compactions can help preserve read performance in a mixed read/write
+# workload, by mitigating the tendency of small sstables to accumulate
+# during a single long running compactions. The default is usually
+# fine and if you experience problems with compaction running too
+# slowly or too fast, you should look at
+# compaction_throughput_mb_per_sec first.
+#
+# concurrent_compactors defaults to the number of cores.
+# Uncomment to make compaction mono-threaded, the pre-0.8 default.
+#concurrent_compactors: 1
+
+# Multi-threaded compaction. When enabled, each compaction will use
+# up to one thread per core, plus one thread per sstable being merged.
+# This is usually only useful for SSD-based hardware: otherwise,
+# your concern is usually to get compaction to do LESS i/o (see:
+# compaction_throughput_mb_per_sec), not more.
+multithreaded_compaction: false
+
+# Throttles compaction to the given total throughput across the entire
+# system. The faster you insert data, the faster you need to compact in
+# order to keep the sstable count down, but in general, setting this to
+# 16 to 32 times the rate you are inserting data is more than sufficient.
+# Setting this to 0 disables throttling. Note that this account for all types
+# of compaction, including validation compaction.
+compaction_throughput_mb_per_sec: 16
+
+# Track cached row keys during compaction, and re-cache their new
+# positions in the compacted sstable. Disable if you use really large
+# key caches.
+compaction_preheat_key_cache: true
+
+# Throttles all outbound streaming file transfers on this node to the
+# given total throughput in Mbps. This is necessary because Cassandra does
+# mostly sequential IO when streaming data during bootstrap or repair, which
+# can lead to saturating the network connection and degrading rpc performance.
+# When unset, the default is 200 Mbps or 25 MB/s.
+# stream_throughput_outbound_megabits_per_sec: 200
+
+# How long the coordinator should wait for read operations to complete
+read_request_timeout_in_ms: 20000
+# How long the coordinator should wait for seq or index scans to complete
+range_request_timeout_in_ms: 20000
+# How long the coordinator should wait for writes to complete
+write_request_timeout_in_ms: 20000
+# How long the coordinator should wait for truncates to complete
+# (This can be much longer, because we need to flush all CFs
+# to make sure we can clear out anythink in the commitlog that could
+# cause truncated data to reappear.)
+truncate_request_timeout_in_ms: 60000
+# The default timeout for other, miscellaneous operations
+request_timeout_in_ms: 20000
+
+# Enable operation timeout information exchange between nodes to accurately
+# measure request timeouts, If disabled cassandra will assuming the request
+# was forwarded to the replica instantly by the coordinator
+#
+# Warning: before enabling this property make sure to ntp is installed
+# and the times are synchronized between the nodes.
+cross_node_timeout: false
+
+# Enable socket timeout for streaming operation.
+# When a timeout occurs during streaming, streaming is retried from the start
+# of the current file. This *can* involve re-streaming an important amount of
+# data, so you should avoid setting the value too low.
+# Default value is 0, which never timeout streams.
+# streaming_socket_timeout_in_ms: 0
+
+# phi value that must be reached for a host to be marked down.
+# most users should never need to adjust this.
+# phi_convict_threshold: 8
+
+# endpoint_snitch -- Set this to a class that implements
+# IEndpointSnitch. The snitch has two functions:
+# - it teaches Cassandra enough about your network topology to route
+# requests efficiently
+# - it allows Cassandra to spread replicas around your cluster to avoid
+# correlated failures. It does this by grouping machines into
+# "datacenters" and "racks." Cassandra will do its best not to have
+# more than one replica on the same "rack" (which may not actually
+# be a physical location)
+#
+# IF YOU CHANGE THE SNITCH AFTER DATA IS INSERTED INTO THE CLUSTER,
+# YOU MUST RUN A FULL REPAIR, SINCE THE SNITCH AFFECTS WHERE REPLICAS
+# ARE PLACED.
+#
+# Out of the box, Cassandra provides
+# - SimpleSnitch:
+# Treats Strategy order as proximity. This improves cache locality
+# when disabling read repair, which can further improve throughput.
+# Only appropriate for single-datacenter deployments.
+# - PropertyFileSnitch:
+# Proximity is determined by rack and data center, which are
+# explicitly configured in cassandra-topology.properties.
+# - GossipingPropertyFileSnitch
+# The rack and datacenter for the local node are defined in
+# cassandra-rackdc.properties and propagated to other nodes via gossip. If
+# cassandra-topology.properties exists, it is used as a fallback, allowing
+# migration from the PropertyFileSnitch.
+# - RackInferringSnitch:
+# Proximity is determined by rack and data center, which are
+# assumed to correspond to the 3rd and 2nd octet of each node's
+# IP address, respectively. Unless this happens to match your
+# deployment conventions (as it did Facebook's), this is best used
+# as an example of writing a custom Snitch class.
+# - Ec2Snitch:
+# Appropriate for EC2 deployments in a single Region. Loads Region
+# and Availability Zone information from the EC2 API. The Region is
+# treated as the Datacenter, and the Availability Zone as the rack.
+# Only private IPs are used, so this will not work across multiple
+# Regions.
+# - Ec2MultiRegionSnitch:
+# Uses public IPs as broadcast_address to allow cross-region
+# connectivity. (Thus, you should set seed addresses to the public
+# IP as well.) You will need to open the storage_port or
+# ssl_storage_port on the public IP firewall. (For intra-Region
+# traffic, Cassandra will switch to the private IP after
+# establishing a connection.)
+#
+# You can use a custom Snitch by setting this to the full class name
+# of the snitch, which will be assumed to be on your classpath.
+endpoint_snitch: SimpleSnitch
+
+# controls how often to perform the more expensive part of host score
+# calculation
+dynamic_snitch_update_interval_in_ms: 100
+# controls how often to reset all host scores, allowing a bad host to
+# possibly recover
+dynamic_snitch_reset_interval_in_ms: 600000
+# if set greater than zero and read_repair_chance is < 1.0, this will allow
+# 'pinning' of replicas to hosts in order to increase cache capacity.
+# The badness threshold will control how much worse the pinned host has to be
+# before the dynamic snitch will prefer other replicas over it. This is
+# expressed as a double which represents a percentage. Thus, a value of
+# 0.2 means Cassandra would continue to prefer the static snitch values
+# until the pinned host was 20% worse than the fastest.
+dynamic_snitch_badness_threshold: 0.1
+
+# request_scheduler -- Set this to a class that implements
+# RequestScheduler, which will schedule incoming client requests
+# according to the specific policy. This is useful for multi-tenancy
+# with a single Cassandra cluster.
+# NOTE: This is specifically for requests from the client and does
+# not affect inter node communication.
+# org.apache.cassandra.scheduler.NoScheduler - No scheduling takes place
+# org.apache.cassandra.scheduler.RoundRobinScheduler - Round robin of
+# client requests to a node with a separate queue for each
+# request_scheduler_id. The scheduler is further customized by
+# request_scheduler_options as described below.
+request_scheduler: org.apache.cassandra.scheduler.NoScheduler
+
+# Scheduler Options vary based on the type of scheduler
+# NoScheduler - Has no options
+# RoundRobin
+# - throttle_limit -- The throttle_limit is the number of in-flight
+# requests per client. Requests beyond
+# that limit are queued up until
+# running requests can complete.
+# The value of 80 here is twice the number of
+# concurrent_reads + concurrent_writes.
+# - default_weight -- default_weight is optional and allows for
+# overriding the default which is 1.
+# - weights -- Weights are optional and will default to 1 or the
+# overridden default_weight. The weight translates into how
+# many requests are handled during each turn of the
+# RoundRobin, based on the scheduler id.
+#
+# request_scheduler_options:
+# throttle_limit: 80
+# default_weight: 5
+# weights:
+# Keyspace1: 1
+# Keyspace2: 5
+
+# request_scheduler_id -- An identifer based on which to perform
+# the request scheduling. Currently the only valid option is keyspace.
+# request_scheduler_id: keyspace
+
+# index_interval controls the sampling of entries from the primrary
+# row index in terms of space versus time. The larger the interval,
+# the smaller and less effective the sampling will be. In technicial
+# terms, the interval coresponds to the number of index entries that
+# are skipped between taking each sample. All the sampled entries
+# must fit in memory. Generally, a value between 128 and 512 here
+# coupled with a large key cache size on CFs results in the best trade
+# offs. This value is not often changed, however if you have many
+# very small rows (many to an OS page), then increasing this will
+# often lower memory usage without a impact on performance.
+index_interval: 128
+
+# Enable or disable inter-node encryption
+# Default settings are TLS v1, RSA 1024-bit keys (it is imperative that
+# users generate their own keys) TLS_RSA_WITH_AES_128_CBC_SHA as the cipher
+# suite for authentication, key exchange and encryption of the actual data transfers.
+# NOTE: No custom encryption options are enabled at the moment
+# The available internode options are : all, none, dc, rack
+#
+# If set to dc cassandra will encrypt the traffic between the DCs
+# If set to rack cassandra will encrypt the traffic between the racks
+#
+# The passwords used in these options must match the passwords used when generating
+# the keystore and truststore. For instructions on generating these files, see:
+# http://download.oracle.com/javase/6/docs/technotes/guides/security/jsse/J...
+#
+server_encryption_options:
+ internode_encryption: none
+ keystore: conf/.keystore
+ keystore_password: cassandra
+ truststore: conf/.truststore
+ truststore_password: cassandra
+ # More advanced defaults below:
+ # protocol: TLS
+ # algorithm: SunX509
+ # store_type: JKS
+ # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA]
+ # require_client_auth: false
+
+# enable or disable client/server encryption.
+client_encryption_options:
+ enabled: false
+ keystore: conf/.keystore
+ keystore_password: cassandra
+ # require_client_auth: false
+ # Set trustore and truststore_password if require_client_auth is true
+ # truststore: conf/.truststore
+ # truststore_password: cassandra
+ # More advanced defaults below:
+ # protocol: TLS
+ # algorithm: SunX509
+ # store_type: JKS
+ # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA]
+
+# internode_compression controls whether traffic between nodes is
+# compressed.
+# can be: all - all traffic is compressed
+# dc - traffic between different datacenters is compressed
+# none - nothing is compressed.
+internode_compression: none
+
+# Enable or disable tcp_nodelay for inter-dc communication.
+# Disabling it will result in larger (but fewer) network packets being sent,
+# reducing overhead from the TCP protocol itself, at the cost of increasing
+# latency if you block for cross-datacenter responses.
+inter_dc_tcp_nodelay: true
10 years, 9 months
[rhq] Branch 'feature/bundle-group' - modules/enterprise
by mazz
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java | 115 ++++++++++
1 file changed, 115 insertions(+)
New commits:
commit f7fea2d432ad92b49574387af1964245acd490aa
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Fri Jul 26 17:01:56 2013 -0400
add createInitialBundleVersion APIs
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java
index 8b4dae6..cffe363 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/bundle/BundleManagerRemote.java
@@ -223,6 +223,9 @@ public interface BundleManagerRemote {
* bundle the bundle will be implicitly created. The bundle type is discovered by the bundle server
* plugin that can parse the recipe.
* </p>
+ * If this bundle version is the initial version of a new bundle that needs to be created, the subject must
+ * have Global.VIEW_BUNDLES because the new bundle will not be associated with any bundle group.
+ * </p>
* Required Permissions: Either:
* - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
* - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
@@ -236,12 +239,35 @@ public interface BundleManagerRemote {
BundleVersion createBundleVersionViaRecipe(Subject subject, String recipe) throws Exception;
/**
+ * Like #createBundleVersionViaRecipe except this method will assume this is a new bundle and is responsible
+ * for creating the bundle as well as the bundle version. The caller can indicate which bundle group the new bundle
+ * should be assigned to.
+ * If bundleGroupId is 0, then the new bundle will not be associated with any bundle group - this is only
+ * allowed if the caller has the permission Global.VIEW_BUNDLES.
+ * </p>
+ * Required Permissions: Either:
+ * - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
+ * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ *
+ * @param subject user that must have proper permissions
+ * @param bundleGroupId identifies the bundle group that the new bundle will be associated with; 0 if no group
+ * @param recipe the recipe that defines the bundle version to be created
+ * @return the persisted BundleVersion with alot of the internal relationships filled in to help the caller
+ * understand all that this method did.
+ */
+ BundleVersion createInitialBundleVersionViaRecipe(Subject subject, int bundleGroupId, String recipe) throws Exception;
+
+ /**
* Creates a bundle version based on a Bundle Distribution file. Typically a zip file, the bundle distribution
* contains the recipe for a supported bundle type, along with 0, 1 or more bundle files that will be associated
* with the bundle version. The recipe specifies the bundle name, version, version name and version description.
* If this is the initial version for the named bundle the bundle will be implicitly created. The bundle type
* is discovered by inspecting the distribution file.
* </p>
+ * If this bundle version is the initial version of a new bundle that needs to be created, the subject must
+ * have Global.VIEW_BUNDLES because the new bundle will not be associated with any bundle group.
+ * </p>
* Required Permissions: Either:
* - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
* - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
@@ -255,12 +281,36 @@ public interface BundleManagerRemote {
BundleVersion createBundleVersionViaFile(Subject subject, File distributionFile) throws Exception;
/**
+ * Like #createBundleVersionViaFile except this method will assume this is a new bundle and is responsible
+ * for creating the bundle as well as the bundle version. The caller can indicate which bundle group the new bundle
+ * should be assigned to.
+ * If bundleGroupId is 0, then the new bundle will not be associated with any bundle group - this is only
+ * allowed if the caller has the permission Global.VIEW_BUNDLES.
+ * </p>
+ * Required Permissions: Either:
+ * - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
+ * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ *
+ * @param subject user that must have proper permissions
+ * @param bundleGroupId identifies the bundle group that the new bundle will be associated with; 0 if no group
+ * @param distributionFile a local Bundle Distribution file. It must be read accessible by the RHQ server process.
+ * @return the persisted BundleVersion with alot of the internal relationships filled in to help the caller
+ * understand all that this method did. Bundle files specifically are returned.
+ * @throws Exception
+ */
+ BundleVersion createInitialBundleVersionViaFile(Subject subject, int bundleGroupId, File distributionFile) throws Exception;
+
+ /**
* Creates a bundle version based on the actual bytes of a Bundle Distribution file. This is essentially
* the same as {@link #createBundleVersionViaFile(Subject, File)} but the caller is providing the actual
* bytes of the file as opposed to the file itself.
* WARNING: obviously, this requires the entire distribution file to have been loaded fully in memory.
* For very large distribution files, this could cause OutOfMemoryErrors.
* </p>
+ * If this bundle version is the initial version of a new bundle that needs to be created, the subject must
+ * have Global.VIEW_BUNDLES because the new bundle will not be associated with any bundle group.
+ * </p>
* Required Permissions: Either:
* - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
* - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
@@ -274,6 +324,27 @@ public interface BundleManagerRemote {
BundleVersion createBundleVersionViaByteArray(Subject subject, byte[] fileBytes) throws Exception;
/**
+ * Like #createBundleVersionViaByteArray except this method will assume this is a new bundle and is responsible
+ * for creating the bundle as well as the bundle version. The caller can indicate which bundle group the new bundle
+ * should be assigned to.
+ * If bundleGroupId is 0, then the new bundle will not be associated with any bundle group - this is only
+ * allowed if the caller has the permission Global.VIEW_BUNDLES.
+ * </p>
+ * Required Permissions: Either:
+ * - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
+ * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ *
+ * @param subject user that must have proper permissions
+ * @param bundleGroupId identifies the bundle group that the new bundle will be associated with; 0 if no group
+ * @param fileBytes the file bits that make up the entire bundle distribution file
+ * @return the persisted BundleVersion with a lot of the internal relationships filled in to help the caller
+ * understand all that this method did. Bundle files specifically are returned.
+ * @throws Exception
+ */
+ BundleVersion createInitialBundleVersionViaByteArray(Subject subject, int bundleGroupId, byte[] fileBytes) throws Exception;
+
+ /**
* Creates a bundle version based on a Bundle Distribution file. Typically a zip file, the bundle distribution
* contains the recipe for a supported bundle type, along with 0, 1 or more bundle files that will be associated
* with the bundle version. The recipe specifies the bundle name, version, version name and version description.
@@ -282,6 +353,9 @@ public interface BundleManagerRemote {
* <br/></br>
* Note, if the file is local it is more efficient to use {@link #createBundleVersionViaFile(Subject,File)}.
* </p>
+ * If this bundle version is the initial version of a new bundle that needs to be created, the subject must
+ * have Global.VIEW_BUNDLES because the new bundle will not be associated with any bundle group.
+ * </p>
* Required Permissions: Either:
* - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
* - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
@@ -297,9 +371,34 @@ public interface BundleManagerRemote {
BundleVersion createBundleVersionViaURL(Subject subject, String distributionFileUrl) throws Exception;
/**
+ * Like #createBundleVersionViaURL except this method will assume this is a new bundle and is responsible
+ * for creating the bundle as well as the bundle version. The caller can indicate which bundle group the new bundle
+ * should be assigned to.
+ * If bundleGroupId is 0, then the new bundle will not be associated with any bundle group - this is only
+ * allowed if the caller has the permission Global.VIEW_BUNDLES.
+ * </p>
+ * Required Permissions: Either:
+ * - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
+ * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ *
+ * @param subject user that must have proper permissions
+ * @param bundleGroupId identifies the bundle group that the new bundle will be associated with; 0 if no group
+ * @param distributionFileUrl a URL String to the Bundle Distribution file. It must be live, resolvable and read accessible
+ * by the RHQ server process.
+ * @return the persisted BundleVersion with a lot of the internal relationships filled in to help the caller
+ * understand all that this method did. Bundle files specifically are returned.
+ * @throws Exception
+ */
+ BundleVersion createInitialBundleVersionViaURL(Subject subject, int bundleGroupId, String distributionFileUrl) throws Exception;
+
+ /**
* A version of the {@link #createBundleVersionViaURL(org.rhq.core.domain.auth.Subject, String)} that accepts a
* username and password for basic authentication on the HTTP URLs.
* </p>
+ * If this bundle version is the initial version of a new bundle that needs to be created, the subject must
+ * have Global.VIEW_BUNDLES because the new bundle will not be associated with any bundle group.
+ * </p>
* Required Permissions: Either:
* - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
* - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
@@ -311,6 +410,22 @@ public interface BundleManagerRemote {
String password) throws Exception;
/**
+ * Like #createBundleVersionViaURL except this method will assume this is a new bundle and is responsible
+ * for creating the bundle as well as the bundle version. The caller can indicate which bundle group the new bundle
+ * should be assigned to.
+ * If bundleGroupId is 0, then the new bundle will not be associated with any bundle group - this is only
+ * allowed if the caller has the permission Global.VIEW_BUNDLES.
+ * </p>
+ * Required Permissions: Either:
+ * - Global.CREATE_BUNDLES and Global.VIEW_BUNDLES
+ * - Global.CREATE_BUNDLES and BundleGroup.VIEW_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ * - BundleGroup.CREATE_BUNDLES_IN_GROUP for bundle group BG and the relevant bundle is assigned to BG
+ *
+ * @see #createBundleVersionViaURL(org.rhq.core.domain.auth.Subject, String)
+ */
+ BundleVersion createInitialBundleVersionViaURL(Subject subject, int bundleGroupId, String distributionFileUrl, String username, String password) throws Exception;
+
+ /**
* Remove everything associated with the Bundles with the exception of files laid down by related deployments.
* Deployed files are left as is on the deployment platforms but the bundle mechanism will no longer track
* the deployment of all bundles that have been deleted.
10 years, 9 months
[rhq] modules/plugins
by John Sanda
modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/CassandraNodeComponent.java | 4
modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java | 75 +++++++++-
modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java | 21 ++
3 files changed, 95 insertions(+), 5 deletions(-)
New commits:
commit d01c43b697ef67f598016824d6cd47b5de2ac83e
Author: John Sanda <jsanda(a)redhat.com>
Date: Fri Jul 26 15:42:46 2013 -0400
add storage node shutdown operation that uses pid file
There can be problems with getting the actual, current pid from Sigar, so the
storage node plugin will first attempt to get the pid from the pid file which
should exist on disk. If that fails, then we will attempt to get the pid from
Sigar.
This implementation for shutdown does not work for Windows so need to revist it
to add in Windows support. We may even consider delegating to rhqtcl.
diff --git a/modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/CassandraNodeComponent.java b/modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/CassandraNodeComponent.java
index 3e55a93..d648ad8 100644
--- a/modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/CassandraNodeComponent.java
+++ b/modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/CassandraNodeComponent.java
@@ -246,8 +246,6 @@ public class CassandraNodeComponent extends JMXServerComponent<ResourceComponent
long pid = process.getPid();
try {
- getEmsConnection().close();
-
process.kill("KILL");
Configuration pluginConfig = getResourceContext().getPluginConfiguration();
@@ -266,7 +264,7 @@ public class CassandraNodeComponent extends JMXServerComponent<ResourceComponent
}
}
- private void waitForNodeToGoDown() throws InterruptedException {
+ protected void waitForNodeToGoDown() throws InterruptedException {
if (OperatingSystem.getInstance().getName().equals(OperatingSystem.NAME_MACOSX)) {
// See this thread on VMWare forum: http://communities.vmware.com/message/2187972#2187972
// Unfortunately there is no work around for this failure on Mac OSX so the method will silently return on
diff --git a/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java b/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java
index 125f4d2..5933093 100644
--- a/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java
+++ b/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java
@@ -28,6 +28,7 @@ package org.rhq.plugins.storage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
+import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
@@ -39,6 +40,7 @@ import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.hyperic.sigar.SigarException;
import org.mc4j.ems.connection.EmsConnection;
import org.mc4j.ems.connection.bean.EmsBean;
import org.mc4j.ems.connection.bean.attribute.EmsAttribute;
@@ -54,9 +56,11 @@ import org.rhq.core.domain.configuration.PropertyMap;
import org.rhq.core.domain.configuration.PropertySimple;
import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport;
+import org.rhq.core.pluginapi.inventory.ProcessScanResult;
import org.rhq.core.pluginapi.inventory.ResourceContext;
import org.rhq.core.pluginapi.operation.OperationFacet;
import org.rhq.core.pluginapi.operation.OperationResult;
+import org.rhq.core.system.ProcessInfo;
import org.rhq.core.util.StringUtil;
import org.rhq.core.util.exception.ThrowableUtil;
import org.rhq.core.util.file.FileUtil;
@@ -105,11 +109,80 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
return updateKnownNodes(parameters);
} else if (name.equals("prepareForBootstrap")) {
return prepareForBootstrap(parameters);
+ } else if (name.equals("shutdown")) {
+ return shutdownStorageNode();
} else {
return super.invokeOperation(name, parameters);
}
}
+ private OperationResult shutdownStorageNode() {
+ OperationResult result = new OperationResult();
+ File binDir = new File(getBasedir(), "bin");
+ File pidFile = new File(binDir, "cassandra.pid");
+
+ try {
+ if (pidFile.exists()) {
+ long pid = readPidFile(pidFile);
+ log.info("Shutting down storage node with pid " + pid);
+ ProcessInfo process = findProcessInfo(pid);
+ if (process != null) {
+ try {
+ process.kill("KILL");
+ waitForNodeToGoDown();
+ pidFile.delete();
+ result.setSimpleResult("Successfully storage node with pid " + pid);
+ } catch (SigarException e) {
+ log.error("Failed to delete storage node with pid " + process.getPid(), e);
+ result.setErrorMessage("Failed to delete storage node with pid " + pid + ": " +
+ ThrowableUtil.getAllMessages(e));
+ }
+ } else {
+ log.warn("Could not find process info for pid " + pid);
+ result = shutdownUsingNativeProcessInfo();
+ }
+
+ } else {
+ log.warn("Did not find pid file " + pidFile + ". It should not be modified, deleted, or moved.");
+ result = shutdownUsingNativeProcessInfo();
+ }
+ } catch (FileNotFoundException e) {
+ log.error("Could not read pid file " + pidFile, e);
+ result.setErrorMessage("Could not read pid file " + pidFile + ": " + ThrowableUtil.getAllMessages(e));
+ } catch (InterruptedException e) {
+ log.warn("The shutdown operation was cancelled or interrupted. This interruption occurred while trying " +
+ "to verify that the storage node process has exited.");
+ result.setErrorMessage("The operation was cancelled or interrupted while trying to verify that the " +
+ "storage node process has exited.");
+ }
+ return result;
+ }
+
+ private long readPidFile(File pidFile) throws FileNotFoundException {
+ return Long.parseLong(StreamUtil.slurp(new FileReader(pidFile)));
+ }
+
+ private ProcessInfo findProcessInfo(long pid) {
+ List<ProcessScanResult> scanResults = getResourceContext().getNativeProcessesForType();
+
+ for (ProcessScanResult scanResult : scanResults) {
+ if (scanResult.getProcessInfo().getPid() == pid) {
+ return scanResult.getProcessInfo();
+ }
+ }
+ return null;
+ }
+
+ private OperationResult shutdownUsingNativeProcessInfo() throws InterruptedException {
+ log.warn("Could not obtain process info from pid file");
+ log.info("Obtaining process info from the system to perform the shutdown");
+
+ OperationResult result = shutdownNode();
+ waitForNodeToGoDown();
+
+ return result;
+ }
+
private OperationResult updateConfiguration(Configuration params) {
boolean restartIsRequired = false;
@@ -237,7 +310,7 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
OperationResult result = new OperationResult();
log.info("Stopping storage node");
- OperationResult stopNodeResult = stopNode();
+ OperationResult stopNodeResult = shutdownStorageNode();
if (stopNodeResult.getErrorMessage() != null) {
log.error("Failed to stop storage node " + this + " Cannot prepare the node for bootstrap which means " +
"that the storage node cannot join the cluster. Make sure the storage node is not running and retry " +
diff --git a/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java b/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java
index f0744a4..eb4d545 100644
--- a/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java
+++ b/modules/plugins/rhq-storage/src/test/java/org/rhq/plugins/storage/StorageNodeComponentITest.java
@@ -231,6 +231,26 @@ public class StorageNodeComponentITest {
assertNodeIsUp("Expected " + storageNode + " to be up after restarting it.");
}
+ @Test(dependsOnMethods = "restartStorageNode")
+ public void prepareForBootstrap() {
+ Configuration params = Configuration.builder().addSimple("cqlPort", 9242).addSimple("gossipPort", 7200)
+ .openList("storageNodeIPAddresses", "storageNodeIPAddresse").addSimples("127.0.0.1", "127.0.0.2")
+ .closeList().build();
+
+ OperationManager operationManager = PluginContainer.getInstance().getOperationManager();
+ OperationServicesAdapter operationsService = new OperationServicesAdapter(operationManager);
+
+ long timeout = 1000 * 60;
+ OperationContextImpl operationContext = new OperationContextImpl(storageNode.getId());
+ OperationServicesResult result = operationsService.invokeOperation(operationContext, "prepareForBootstrap",
+ params, timeout);
+
+ assertEquals(result.getResultCode(), OperationServicesResultCode.SUCCESS, "The operation failed: " +
+ result.getErrorStackTrace());
+
+ assertNodeIsUp("Expected " + storageNode + " to be up after the prepareForBootstrap operation completes.");
+ }
+
private void assertNodeIsUp(String msg) {
executeAvailabilityScan();
@@ -251,7 +271,6 @@ public class StorageNodeComponentITest {
private Availability getAvailability() {
InventoryManager inventoryManager = PluginContainer.getInstance().getInventoryManager();
-// return inventoryManager.getAvailabilityIfKnown(storageNode);
return inventoryManager.getCurrentAvailability(storageNode);
}
10 years, 9 months