dev/null |binary modules/common/cassandra-ccm/cassandra-ccm-cli/pom.xml | 170 ++ modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/java/org/rhq/cassandra/CLI.java | 190 ++ modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/resources/logging.properties | 27 modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/resources/module/main/module.xml | 36 modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/scripts/module-assembly.xml | 37 modules/common/cassandra-ccm/cassandra-ccm-core/pom.xml | 251 +++ modules/common/cassandra-ccm/cassandra-ccm-core/src/main/cassandra/cli/dbsetup.script | 40 modules/common/cassandra-ccm/cassandra-ccm-core/src/main/cassandra/cql/create_keyspace.cql | 1 modules/common/cassandra-ccm/cassandra-ccm-core/src/main/cassandra/cql/dbsetup.cql | 42 modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/BootstrapDeployer.java | 323 +++++ modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CLibrary.java | 47 modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java | 195 +++ modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraException.java | 47 modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraNode.java | 74 + modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/ClusterInitService.java | 256 +++ modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/DeploymentOptions.java | 285 ++++ modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/.DS_Store |binary modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra.properties | 77 + modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/access.properties | 46 modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/cassandra-env.sh | 235 +++ modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/cassandra.yaml | 645 ++++++++++ modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/log4j-server.properties | 45 modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/passwd.properties | 23 modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/lib/jna-3.4.1.jar |binary modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/lib/platform-3.4.1.jar |binary modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/deploy.xml | 226 +++ modules/common/cassandra-ccm/cassandra-ccm-testng/pom.xml | 40 modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CCMTestNGListener.java | 153 ++ modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/DeployCluster.java | 70 + modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/ShutdownCluster.java | 39 modules/common/cassandra-ccm/cassandra-ccm-testng/src/test/java/org/rhq/cassandra/common/BootstrapDeployerTest.java | 86 + modules/common/cassandra-ccm/pom.xml | 21 modules/common/cassandra-common-itests/pom.xml | 65 - modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/CCMTestNGListener.java | 153 -- modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/CLibrary.java | 47 modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/DeployCluster.java | 70 - modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/ShutdownCluster.java | 39 modules/common/cassandra-common-itests/src/test/java/org/rhq/cassandra/common/BootstrapDeployerTest.java | 86 - modules/common/cassandra-common/pom.xml | 365 ----- modules/common/cassandra-common/src/main/cassandra/cli/dbsetup.script | 40 modules/common/cassandra-common/src/main/cassandra/cql/create_keyspace.cql | 1 modules/common/cassandra-common/src/main/cassandra/cql/dbsetup.cql | 42 modules/common/cassandra-common/src/main/java/org/rhq/cassandra/BootstrapDeployer.java | 323 ----- modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraClusterManager.java | 171 -- modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraException.java | 47 modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraNode.java | 74 - modules/common/cassandra-common/src/main/java/org/rhq/cassandra/ClusterInitService.java | 256 --- modules/common/cassandra-common/src/main/java/org/rhq/cassandra/DeploymentOptions.java | 285 ---- modules/common/cassandra-common/src/main/resources/cassandra.properties | 77 - modules/common/cassandra-common/src/main/resources/cassandra/conf/access.properties | 46 modules/common/cassandra-common/src/main/resources/cassandra/conf/cassandra-env.sh | 235 --- modules/common/cassandra-common/src/main/resources/cassandra/conf/cassandra.yaml | 645 ---------- modules/common/cassandra-common/src/main/resources/cassandra/conf/log4j-server.properties | 45 modules/common/cassandra-common/src/main/resources/cassandra/conf/passwd.properties | 23 modules/common/cassandra-common/src/main/resources/deploy.xml | 226 --- modules/common/cassandra-common/src/main/resources/logging.properties | 27 modules/common/cassandra-common/src/main/resources/module/main/module.xml | 35 modules/common/cassandra-common/src/main/scripts/module-assembly.xml | 37 modules/common/pom.xml | 3 modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-ccm.sh | 2 modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml | 6 modules/enterprise/server/jar/pom.xml | 2 modules/enterprise/server/server-metrics/pom.xml | 4 pom.xml | 2 65 files changed, 3737 insertions(+), 3469 deletions(-)
New commits: commit 7f4003afd28226d82c32e48c3504b9273c58595d Author: John Sanda jsanda@redhat.com Date: Fri Dec 21 15:55:05 2012 -0500
Moving impl of cluster shutdown out of testng listener and into CCM
This commit also update the dependencies in the server modules with the new module names. Fixing the rhq-container-build.xml ant script so that it deploys cassandra-ccm-cli as the jboss module.
diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/pom.xml b/modules/common/cassandra-ccm/cassandra-ccm-core/pom.xml index db6f412..25d38c0 100644 --- a/modules/common/cassandra-ccm/cassandra-ccm-core/pom.xml +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/pom.xml @@ -41,6 +41,12 @@ <artifactId>cassandra-thrift</artifactId> <version>${cassandra.version}</version> </dependency> + + <dependency> + <groupId>net.java.dev.jna</groupId> + <artifactId>jna</artifactId> + <version>3.2.7</version> + </dependency> </dependencies>
<build> diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CLibrary.java b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CLibrary.java new file mode 100644 index 0000000..9157b42 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CLibrary.java @@ -0,0 +1,47 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra; + +import com.sun.jna.Native; + +/** + * @author John Sanda + */ +public class CLibrary { + + static { + //try { + Native.register("c"); + //} catch () + } + + public static native int kill(int pid, int signal); + +// public static int killProcess(int pid, int signal) { +// +// } + +} diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java index 22bd11e..6dca74a 100644 --- a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java @@ -28,8 +28,10 @@ package org.rhq.cassandra; import static java.util.Arrays.asList;
import java.io.File; +import java.io.FileReader; import java.io.IOException; import java.io.InputStream; +import java.io.StringWriter; import java.util.ArrayList; import java.util.List;
@@ -44,6 +46,7 @@ import org.rhq.core.system.SystemInfo; import org.rhq.core.system.SystemInfoFactory; import org.rhq.core.util.PropertiesFileUpdate; import org.rhq.core.util.StringUtil; +import org.rhq.core.util.stream.StreamUtil;
/** * @author John Sanda @@ -126,7 +129,27 @@ public class CassandraClusterManager { }
public void shutdownCluster() { + File basedir = new File(deploymentOptions.getClusterDir()); + for (int i = 0; i < deploymentOptions.getNumNodes(); ++i) { + try { + killNode(new File(basedir, "node" + i)); + } catch (Exception e) { + throw new RuntimeException("Faililed to shut down cluster", e); + } + } + } + + private void killNode(File nodeDir) throws Exception { + long pid = getPid(nodeDir); + CLibrary.kill((int) pid, 9); + } + + private long getPid(File nodeDir) throws IOException { + File binDir = new File(nodeDir, "bin"); + StringWriter writer = new StringWriter(); + StreamUtil.copy(new FileReader(new File(binDir, "cassandra.pid")), writer);
+ return Long.parseLong(writer.getBuffer().toString()); }
public List<String> getHostNames() { diff --git a/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CLibrary.java b/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CLibrary.java deleted file mode 100644 index 9157b42..0000000 --- a/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CLibrary.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * * RHQ Management Platform - * * Copyright (C) 2005-2012 Red Hat, Inc. - * * All rights reserved. - * * - * * This program is free software; you can redistribute it and/or modify - * * it under the terms of the GNU General Public License, version 2, as - * * published by the Free Software Foundation, and/or the GNU Lesser - * * General Public License, version 2.1, also as published by the Free - * * Software Foundation. - * * - * * This program is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * * GNU General Public License and the GNU Lesser General Public License - * * for more details. - * * - * * You should have received a copy of the GNU General Public License - * * and the GNU Lesser General Public License along with this program; - * * if not, write to the Free Software Foundation, Inc., - * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package org.rhq.cassandra; - -import com.sun.jna.Native; - -/** - * @author John Sanda - */ -public class CLibrary { - - static { - //try { - Native.register("c"); - //} catch () - } - - public static native int kill(int pid, int signal); - -// public static int killProcess(int pid, int signal) { -// -// } - -} diff --git a/modules/common/pom.xml b/modules/common/pom.xml index 23673a8..f131ccf 100644 --- a/modules/common/pom.xml +++ b/modules/common/pom.xml @@ -32,7 +32,6 @@ <module>jboss-as-dmr-client</module> <module>cassandra-auth</module> <module>cassandra-schema</module> - <module>cassandra-common</module> - <module>cassandra-common-itests</module> + <module>cassandra-ccm</module> </modules> </project> diff --git a/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-ccm.sh b/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-ccm.sh index 033ea44..eafb1f7 100755 --- a/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-ccm.sh +++ b/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-ccm.sh @@ -237,7 +237,7 @@ debug_msg "_JBOSS_MODULEPATH: $_JBOSS_MODULEPATH" echo "Starting RHQ CCM ..."
# start the AS instance with our main installer module -"$RHQ_SERVER_JAVA_EXE_FILE_PATH" ${RHQ_CCM_JAVA_OPTS} ${RHQ_CCM_ADDITIONAL_JAVA_OPTS} -jar "${RHQ_SERVER_JBOSS_HOME}/jboss-modules.jar" -mp "$_JBOSS_MODULEPATH" org.rhq.rhq-cassandra-common "$@" +"$RHQ_SERVER_JAVA_EXE_FILE_PATH" ${RHQ_CCM_JAVA_OPTS} ${RHQ_CCM_ADDITIONAL_JAVA_OPTS} -jar "${RHQ_SERVER_JBOSS_HOME}/jboss-modules.jar" -mp "$_JBOSS_MODULEPATH" org.rhq.rhq-cassandra-ccm-cli "$@"
_EXIT_STATUS=$? exit $_EXIT_STATUS diff --git a/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml b/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml index 6412c06..8adf18d 100644 --- a/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml +++ b/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml @@ -334,7 +334,7 @@ <echo>*** Preparing bin dir ***</echo>
<loadproperties> - <zipentry zipfile="${settings.localRepository}/org/rhq/rhq-cassandra-common/${project.version}/rhq-cassandra-common-${project.version}.jar" + <zipentry zipfile="${settings.localRepository}/org/rhq/rhq-cassandra-ccm-core/${project.version}/rhq-cassandra-ccm-core-${project.version}.jar" name="cassandra.properties"/> </loadproperties>
@@ -638,7 +638,7 @@ rhq.casandra.native-transport-max-threads=${rhq.casandra.native-transport-max-th <fileset dir="src/main/dev-resources" /> </copy> <loadproperties> - <zipentry zipfile="${settings.localRepository}/org/rhq/rhq-cassandra-common/${project.version}/rhq-cassandra-common-${project.version}.jar" + <zipentry zipfile="${settings.localRepository}/org/rhq/rhq-cassandra-ccm-core/${project.version}/rhq-cassandra-ccm-core-${project.version}.jar" name="cassandra.properties"/> </loadproperties> <echo>Putting a developer setting in rhq-server.properties to turn on/off strict agent update version checking</echo> @@ -675,7 +675,7 @@ rhq.cassandra.logging.level=${rhq.cassandra.logging.level} </replace>
<echo>Adding cassandra-db module to ${jboss.modules.dir} ...</echo> - <unzip src="${settings.localRepository}/org/rhq/rhq-cassandra-common/${project.version}/rhq-cassandra-common-${project.version}.zip" + <unzip src="${settings.localRepository}/org/rhq/rhq-cassandra-ccm-cli/${project.version}/rhq-cassandra-ccm-cli-${project.version}.zip" dest="${jboss.modules.dir}" /> </target>
diff --git a/modules/enterprise/server/jar/pom.xml b/modules/enterprise/server/jar/pom.xml index 75f5c9b..19a12c4 100644 --- a/modules/enterprise/server/jar/pom.xml +++ b/modules/enterprise/server/jar/pom.xml @@ -89,7 +89,7 @@
<dependency> <groupId>org.rhq</groupId> - <artifactId>rhq-cassandra-common</artifactId> + <artifactId>rhq-cassandra-ccm-core</artifactId> <version>${project.version}</version> </dependency>
diff --git a/modules/enterprise/server/server-metrics/pom.xml b/modules/enterprise/server/server-metrics/pom.xml index 84d05f1..0e5b43a 100644 --- a/modules/enterprise/server/server-metrics/pom.xml +++ b/modules/enterprise/server/server-metrics/pom.xml @@ -46,7 +46,7 @@ <dependencies> <dependency> <groupId>${project.groupId}</groupId> - <artifactId>rhq-cassandra-common</artifactId> + <artifactId>rhq-cassandra-ccm-core</artifactId> <version>${project.version}</version> <exclusions> <exclusion> @@ -58,7 +58,7 @@
<dependency> <groupId>${project.groupId}</groupId> - <artifactId>rhq-cassandra-common-itests</artifactId> + <artifactId>rhq-cassandra-ccm-testng</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> diff --git a/pom.xml b/pom.xml index a593cf1..c00699c 100644 --- a/pom.xml +++ b/pom.xml @@ -1326,6 +1326,8 @@ <modules> <module>modules</module> <module>code-coverage</module> + <module>cassandra-ccm-cli</module> + <module>cassandra-ccm-testng</module> </modules>
commit f1513cfa482ceeabd7d6966879f5a56183dbf3ee Author: John Sanda jsanda@redhat.com Date: Fri Dec 21 15:36:32 2012 -0500
major refactoring of the former cassandra-common module
The cassandra-common module and cassandra-common-itests module were evolving into a few different things so this was a good time to reorganzie things.
We now have rhq/common/cassandra-ccm which is a parent pom. Under it we have cassandra-ccm-core which contains most of the stuff that was previously in cassandra-common.
We also have cassandra-ccm-cli which contains the new CLI class and this maven module produces the JBoss AS module that is run by the rhq-ccm script.
Lastly we have cassandra-ccm-testng which contains the classes that were in cassandra-common-itests.
diff --git a/modules/common/cassandra-ccm/cassandra-ccm-cli/pom.xml b/modules/common/cassandra-ccm/cassandra-ccm-cli/pom.xml new file mode 100644 index 0000000..55b5ba6 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-cli/pom.xml @@ -0,0 +1,170 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd%22%3E + + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.rhq</groupId> + <artifactId>rhq-cassandra-ccm</artifactId> + <version>4.6.0-SNAPSHOT</version> + </parent> + + <artifactId>rhq-cassandra-ccm-cli</artifactId> + <name>RHQ Cassandra CCM CLI</name> + + <properties> + <moduleName>org.rhq.${project.artifactId}</moduleName> + <moduleDir>org/rhq/${project.artifactId}</moduleDir> + </properties> + + <dependencies> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>rhq-cassandra-ccm-core</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>commons-cli</groupId> + <artifactId>commons-cli</artifactId> + <version>1.2</version> + <scope>provided</scope> + </dependency> + </dependencies> + + <build> + <resources> + <resource> + <directory>src/main/resources</directory> + <filtering>true</filtering> + </resource> + </resources> + + <plugins> + <plugin> + <artifactId>maven-dependency-plugin</artifactId> + <executions> + <execution> + <id>copy-deps</id> + <phase>prepare-package</phase> + <goals> + <goal>copy</goal> + </goals> + <configuration> + <outputDirectory>${project.build.directory}/dependencies</outputDirectory> + <artifactItems> + <artifactItem> + <groupId>${project.groupId}</groupId> + <artifactId>rhq-cassandra-ccm-core</artifactId> + </artifactItem> + <artifactItem> + <groupId>${project.groupId}</groupId> + <artifactId>rhq-ant-bundle-common</artifactId> + <version>${project.version}</version> + </artifactItem> + <artifactItem> + <groupId>${project.groupId}</groupId> + <artifactId>rhq-core-util</artifactId> + <version>${project.version}</version> + </artifactItem> + <artifactItem> + <groupId>jdom</groupId> + <artifactId>jdom</artifactId> + <version>1.0</version> + </artifactItem> + <artifactItem> + <groupId>i18nlog</groupId> + <artifactId>i18nlog</artifactId> + <version>1.0.10</version> + </artifactItem> + <artifactItem> + <groupId>${project.groupId}</groupId> + <artifactId>rhq-core-native-system</artifactId> + <version>${project.version}</version> + </artifactItem> + <artifactItem> + <groupId>org.apache.ant</groupId> + <artifactId>ant</artifactId> + <version>1.8.0</version> + </artifactItem> + <artifactItem> + <groupId>org.apache.ant</groupId> + <artifactId>ant-launcher</artifactId> + <version>1.8.0</version> + </artifactItem> + <artifactItem> + <groupId>org.apache.ant</groupId> + <artifactId>ant-nodeps</artifactId> + <version>1.8.0</version> + </artifactItem> + <artifactItem> + <groupId>ant-contrib</groupId> + <artifactId>ant-contrib</artifactId> + <version>1.0b3</version> + </artifactItem> + <artifactItem> + <groupId>${project.groupId}</groupId> + <artifactId>rhq-core-plugin-api</artifactId> + <version>${project.version}</version> + </artifactItem> + <artifactItem> + <groupId>org.apache.cassandra</groupId> + <artifactId>cassandra-thrift</artifactId> + <version>${cassandra.version}</version> + </artifactItem> + <artifactItem> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + <version>1.7.2</version> + </artifactItem> + <artifactItem> + <groupId>${project.groupId}</groupId> + <artifactId>rhq-core-domain</artifactId> + <version>${project.version}</version> + </artifactItem> + <artifactItem> + <groupId>commons-lang</groupId> + <artifactId>commons-lang</artifactId> + <version>2.4</version> + </artifactItem> + <artifactItem> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + <version>1.7.2</version> + </artifactItem> + <artifactItem> + <groupId>org.apache.thrift</groupId> + <artifactId>libthrift</artifactId> + <version>0.7.0</version> + </artifactItem> + <artifactItem> + <groupId>commons-codec</groupId> + <artifactId>commons-codec</artifactId> + <version>1.3</version> + </artifactItem> + </artifactItems> + </configuration> + </execution> + </executions> + </plugin> + + <plugin> + <artifactId>maven-assembly-plugin</artifactId> + <configuration> + <descriptors> + <descriptor>src/main/scripts/module-assembly.xml</descriptor> + </descriptors> + </configuration> + <executions> + <execution> + <id>module-assembly</id> + <phase>package</phase> + <goals> + <goal>single</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> diff --git a/modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/java/org/rhq/cassandra/CLI.java b/modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/java/org/rhq/cassandra/CLI.java new file mode 100644 index 0000000..9808662 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/java/org/rhq/cassandra/CLI.java @@ -0,0 +1,190 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra; + +import java.io.File; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.OptionBuilder; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.apache.commons.cli.PosixParser; + +/** + * @author John Sanda + */ +public class CLI { + + private Set<Option> supportedArgs = new HashSet<Option>(); + + private Option deployCommand; + + private Option shutdownCommand; + + private String deployDescription = "Creates an embedded cluster and then starts each node"; + + public CLI() { + deployCommand = OptionBuilder + .withArgName("[options]") + .hasOptionalArgs() + .withDescription(deployDescription) + .create("deploy"); + + shutdownCommand = OptionBuilder + .withArgName("[options]") + .hasOptionalArg() + .withDescription("Shuts down all of the cluster nodes.") + .create("shutdown"); + } + + public void printUsage() { + HelpFormatter helpFormatter = new HelpFormatter(); + String syntax = "rhq-ccm.sh <cmd> [options]"; + String header = "\nwhere <cmd> is one of:"; + + Options options = new Options().addOption(deployCommand).addOption(shutdownCommand); + + helpFormatter.setOptPrefix(""); + helpFormatter.printHelp(syntax, header, options, null); + } + + public void exec(String[] args) { + if (args.length == 0) { + printUsage(); + return; + } + + List<String> commands = new LinkedList<String>(); + for (String arg : args) { + if (arg.equals(deployCommand.getOpt()) || arg.equals(shutdownCommand.getOpt())) { + commands.add(arg); + } + } + + if (commands.size() != 1) { + printUsage(); + return; + } + + String cmd = commands.get(0); + + if (cmd.equals(deployCommand.getOpt())) { + deploy(getCommandLine(cmd, args)); + } + } + + public void deploy(String [] args) { + Options options = new Options() + .addOption("h", "help", false, "Show this message.") + .addOption("n", "num-nodes", true, "The number of nodes to install and configure. The top level or base " + + "directory for each node will be nodeN where N is the node number."); + + try { + CommandLineParser parser = new PosixParser(); + CommandLine cmdLine = parser.parse(options, args); + + if (cmdLine.hasOption("h")) { + printDeployUsage(options); + } else { + DeploymentOptions deploymentOptions = new DeploymentOptions(); + if (cmdLine.hasOption("n")) { + int numNodes = Integer.parseInt(cmdLine.getOptionValue("n")); + deploymentOptions.setNumNodes(numNodes); + } + + CassandraClusterManager ccm = new CassandraClusterManager(deploymentOptions); + List<File> nodeDirs = ccm.installCluster(); + ccm.startCluster(nodeDirs); + } + } catch (ParseException e) { + printDeployUsage(options); + } + } + + private void printDeployUsage(Options options) { + HelpFormatter helpFormatter = new HelpFormatter(); + String syntax = "rhq-ccm.sh deploy [options]"; + String header = "\n" + deployDescription + "\n\n"; + + helpFormatter.setNewLine("\n"); + helpFormatter.printHelp(syntax, header, options, null); + } + + public void shutdown() { + + } + + private String[] getCommandLine(String cmd, String[] args) { + String[] cmdLine = new String[args.length - 1]; + int i = 0; + for (String arg : args) { + if (arg.equals(cmd)) { + continue; + } + cmdLine[i++] = arg; + } + return cmdLine; + } + + public static void main(String[] args) { +// OptionGroup ccmArgs = new OptionGroup(); +// +// Option deploy = OptionBuilder +// .withArgName("[options]") +// .hasOptionalArgs() +// .withDescription("Creates an embedded cluster and then starts each node") +// .create("deploy"); +// +// Option shutdown = OptionBuilder +// .withArgName("[options]") +// .hasOptionalArg() +// .withDescription("Shuts down all of the cluster nodes.") +// .create("shutdown"); +// +// ccmArgs.addOption(deploy).addOption(shutdown); +// //ccmArgs.setRequired(true); +// +// CommandLineParser parser = new PosixParser(); +// Options options = new Options(); +// options.addOptionGroup(ccmArgs); +// +// try { +// CommandLine cmdLine = parser.parse(options, args); +// } catch (ParseException e) { +// e.printStackTrace(); +// } + CLI cli = new CLI(); + cli.exec(args); + } + +} diff --git a/modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/resources/logging.properties b/modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/resources/logging.properties new file mode 100644 index 0000000..3a4f2b6 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/resources/logging.properties @@ -0,0 +1,27 @@ +# Additional logger names to configure (root logger is always configured) +loggers=org.rhq + +# Root logger level +logger.level=${rhq.ccm.loglevel:DEBUG} +# Root logger handlers +logger.handlers=FILE,CONSOLE + +# Console handler configuration +handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler +handler.CONSOLE.properties=autoFlush +handler.CONSOLE.level=${rhq.ccm.loglevel:DEBUG} +handler.CONSOLE.autoFlush=true +handler.CONSOLE.formatter=PATTERN + +# File handler configuration +handler.FILE=org.jboss.logmanager.handlers.FileHandler +handler.FILE.level=${rhq.ccm.loglevel:DEBUG} +handler.FILE.properties=autoFlush,fileName +handler.FILE.autoFlush=true +handler.FILE.fileName=${rhq.ccm.logdir:.}/rhq-ccm.log +handler.FILE.formatter=PATTERN + +# Formatter pattern configuration +formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter +formatter.PATTERN.properties=pattern +formatter.PATTERN.pattern=%d{HH:mm:ss,SSS} %-5p [%c] %s%E%n diff --git a/modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/resources/module/main/module.xml b/modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/resources/module/main/module.xml new file mode 100644 index 0000000..4fdbea4 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/resources/module/main/module.xml @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<module xmlns="urn:jboss:module:1.0" name="${moduleName}"> + <main-class name="org.rhq.cassandra.CLI"/> + + <resources> + <resource-root path="${project.build.finalName}.jar"/> + <resource-root path="rhq-ant-bundle-common-${project.version}.jar"/> + <resource-root path="rhq-core-util-${project.version}.jar"/> + <resource-root path="jdom-1.0.jar"/> + <resource-root path="i18nlog-1.0.10.jar"/> + <resource-root path="rhq-core-native-system-${project.version}.jar"/> + <resource-root path="ant-1.8.0.jar"/> + <resource-root path="ant-launcher-1.8.0.jar"/> + <resource-root path="ant-nodeps-1.8.0.jar"/> + <resource-root path="ant-contrib-1.0b3.jar"/> + <resource-root path="rhq-core-plugin-api-${project.version}.jar"/> + <resource-root path="cassandra-thrift-${cassandra.version}.jar"/> + <resource-root path="slf4j-api-1.7.2.jar"/> + <resource-root path="rhq-core-domain-${project.version}.jar"/> + <resource-root path="commons-lang-2.4.jar"/> + <resource-root path="slf4j-api-1.7.2.jar"/> + <resource-root path="libthrift-0.7.0.jar"/> + </resources> + + <dependencies> + <module name="com.sun.xml.bind"/> + <module name="javax.api"/> + <module name="org.apache.commons.logging"/> + <module name="org.apache.commons.cli"/> + <module name="org.apache.log4j"/> + <module name="javax.api"/> + <module name="org.jboss.logmanager" services="import"/> + <module name="org.jboss.logging"/> + </dependencies> +</module> \ No newline at end of file diff --git a/modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/scripts/module-assembly.xml b/modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/scripts/module-assembly.xml new file mode 100644 index 0000000..30dd591 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-cli/src/main/scripts/module-assembly.xml @@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<assembly> + <id>module-assembly</id> + <formats> + <format>zip</format> + </formats> + <includeBaseDirectory>false</includeBaseDirectory> + <baseDirectory>${project.build.finalName}-module</baseDirectory> + <fileSets> + <fileSet> + <directory>${project.build.outputDirectory}/module</directory> + <outputDirectory>/org/rhq/${artifactId}</outputDirectory> + <includes> + <include>main/module.xml</include> + </includes> + <fileMode>0644</fileMode> + <directoryMode>0755</directoryMode> + </fileSet> + <fileSet> + <directory>${project.build.directory}</directory> + <outputDirectory>/org/rhq/${artifactId}/main</outputDirectory> + <includes> + <include>${project.build.finalName}.jar</include> + </includes> + <fileMode>0644</fileMode> + <directoryMode>0755</directoryMode> + </fileSet> + <fileSet> + <directory>${project.build.directory}/dependencies</directory> + <outputDirectory>/org/rhq/${artifactId}/main</outputDirectory> + <fileMode>0644</fileMode> + <directoryMode>0755</directoryMode> + </fileSet> + </fileSets> +</assembly> + diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/pom.xml b/modules/common/cassandra-ccm/cassandra-ccm-core/pom.xml new file mode 100644 index 0000000..db6f412 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/pom.xml @@ -0,0 +1,245 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd%22%3E + + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.rhq</groupId> + <artifactId>rhq-cassandra-ccm</artifactId> + <version>4.6.0-SNAPSHOT</version> + </parent> + + <artifactId>rhq-cassandra-ccm-core</artifactId> + <name>RHQ Cassandra CCM Core</name> + + <properties> + <cassandra.version>1.2.0-rc1</cassandra.version> + <local.repo>${settings.localRepository}</local.repo> + </properties> + + <dependencies> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>rhq-ant-bundle-common</artifactId> + <version>${project.version}</version> + <exclusions> + <exclusion> + <groupId>org.liquibase</groupId> + <artifactId>liquibase-core</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>rhq-core-plugin-api</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.cassandra</groupId> + <artifactId>cassandra-thrift</artifactId> + <version>${cassandra.version}</version> + </dependency> + </dependencies> + + <build> + <resources> + <resource> + <directory>src/main/resources</directory> + <filtering>true</filtering> + </resource> + <resource> + <directory>src/main/cassandra/cql</directory> + </resource> + </resources> + + <filters> + <filter>src/main/resources/cassandra.properties</filter> + </filters> + + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <executions> + <execution> + <!-- + This execution is a place holder or stub to do some pre-processing before + packaging up the bundle. See the snappy-mac-workaround profile below for more + details. + --> + <id>setup-pkg</id> + </execution> + <execution> + <id>get-cassandra</id> + <phase>generate-resources</phase> + <goals> + <goal>run</goal> + </goals> + <configuration> + <target> + <property name="cassandra.download.dir" + value="${project.build.directory}/cassandra-download"/> + <mkdir dir="${cassandra.download.dir}"/> + <mkdir dir="${settings.localRepository}/org/apache/cassandra/apache-cassandra/${cassandra.version}"/> + <get src="http://repo1.maven.org/maven2/org/apache/cassandra/apache-cassandra/$%7Bcass..." + dest="${settings.localRepository}/org/apache/cassandra/apache-cassandra/${cassandra.version}/apache-cassandra-${cassandra.version}-bin.tar.gz" + skipexisting="true" + verbose="true"/> + <gunzip src="${settings.localRepository}/org/apache/cassandra/apache-cassandra/${cassandra.version}/apache-cassandra-${cassandra.version}-bin.tar.gz" + dest="${cassandra.download.dir}"/> + <untar src="${cassandra.download.dir}/apache-cassandra-${cassandra.version}-bin.tar" + dest="${cassandra.download.dir}"/> + <move file="${cassandra.download.dir}/apache-cassandra-${cassandra.version}" + tofile="${project.build.outputDirectory}/cassandra-${cassandra.version}"/> + <delete dir="${cassandra.download.dir}"/> + </target> + </configuration> + </execution> + <execution> + <id>create-cassandra-pkg</id> + <phase>prepare-package</phase> + <goals> + <goal>run</goal> + </goals> + <configuration> + <target> + <property name="cassandra.dir" + value="${project.build.outputDirectory}/cassandra-${cassandra.version}"/> + <property name="cassandra.distro.filename" value="cassandra.zip"/> + <property name="cassandra.distro.zip" + value="${project.build.outputDirectory}/${cassandra.distro.filename}"/> + <copy file="${settings.localRepository}/org/rhq/rhq-cassandra-auth/${project.version}/rhq-cassandra-auth-${project.version}.jar" + todir="${cassandra.dir}/lib"/> + <move file="${project.build.outputDirectory}/cassandra/conf" todir="${cassandra.dir}"/> + <move file="${project.build.outputDirectory}/cassandra/lib" todir="${cassandra.dir}"/> + <!--<move file="${project.build.outputDirectory}/passwd.properties" todir="${cassandra.dir}/conf"/>--> + <!--<move file="${project.build.outputDirectory}/access.properties" todir="${cassandra.dir}/conf"/>--> + <zip basedir="${cassandra.dir}" destfile="${cassandra.distro.zip}"/> + <delete dir="${cassandra.dir}"/> + <zip basedir="${project.build.outputDirectory}" + destfile="${project.build.outputDirectory}/cassandra-bundle.zip" + includes="${cassandra.distro.filename},deploy.xml"/> + <delete file="${project.build.outputDirectory}/deploy.xml"/> + <delete file="${project.build.outputDirectory}/cassandra}"/> + <delete file="${cassandra.distro.zip}"/> + </target> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + + <profiles> + <profile> + <id>dev</id> + <properties> + <rhq.rootDir>../../..</rhq.rootDir> + <rhq.containerDir>${rhq.rootDir}/${rhq.defaultDevContainerPath}</rhq.containerDir> + <rhq.deploymentDir>${rhq.containerDir}/${rhq.earLibDir}</rhq.deploymentDir> + </properties> + + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <executions> + <execution> + <id>deploy</id> + <phase>package</phase> + <configuration> + <target> + <mkdir dir="${rhq.deploymentDir}"/> + <property name="deployment.file" location="${rhq.deploymentDir}/${project.build.finalName}.jar"/> + <echo>*** Updating ${deployment.file}...</echo> + <jar destfile="${deployment.file}" basedir="${project.build.outputDirectory}"/> + </target> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + + <execution> + <id>undeploy</id> + <phase>clean</phase> + <configuration> + <target> + <property name="deployment.file" location="${rhq.deploymentDir}/${project.build.finalName}.jar"/> + <echo>*** Deleting ${deployment.file}...</echo> + <delete file="${deployment.file}"/> + </target> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + + </executions> + </plugin> + </plugins> + </build> + </profile> + + <!-- + Cassandra uses the snappy-java compression library, and it uses a native library that + is packaged in the snappy-java JAR. Running on Mac OS X with Java 7 will result in, + + NoClassDefFoundError Could not initialize class org.xerial.snappy.Snappy + + due to the file name extension that the Java 7 JVM looks for on Mac OS X. This issue + was logged and fixed under https://github.com/xerial/snappy-java/issues/6. Cassandra + however does not yet bundle a newer version of snappy-java. This profile is activated + when running on Mac OS X and replaces the packaged version of snappy-java with a newer + version so that snappy compression can still be used during development. Note that + this is **not** an issue when running on Java 6. + + - jsanda 10/03/2012 + --> + <profile> + <id>snappy-mac-workaround</id> + <activation> + <os> + <family>Mac</family> + </os> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <inherited>false</inherited> + <dependencies> + <dependency> + <groupId>org.xerial.snappy</groupId> + <artifactId>snappy-java</artifactId> + <version>1.0.5-M3</version> + </dependency> + </dependencies> + <executions> + <execution> + <id>setup-pkg-mac</id> + <phase>process-resources</phase> + <goals> + <goal>run</goal> + </goals> + <configuration> + <target> + <property name="cassandra.dir" + value="${project.build.outputDirectory}/cassandra-${cassandra.version}"/> + <property name="cassandra.lib.dir" value="${cassandra.dir}/lib"/> + <property name="snappy.jar.original" value="${cassandra.lib.dir}/snappy-java-1.0.4.1.jar"/> + <property name="snappy.jar.updated" + value="${local.repo}/org/xerial/snappy/snappy-java/1.0.5-M3/snappy-java-1.0.5-M3.jar"/> + <delete file="${snappy.jar.original}"/> + <copy file="${snappy.jar.updated}" todir="${cassandra.lib.dir}"/> + </target> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + </profiles> +</project> diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/cassandra/cli/dbsetup.script b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/cassandra/cli/dbsetup.script new file mode 100644 index 0000000..73bc2a7 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/cassandra/cli/dbsetup.script @@ -0,0 +1,40 @@ +create keyspace rhq + with placement_strategy = 'org.apache.cassandra.locator.SimpleStrategy' and + strategy_options = {replication_factor:1}; + +use rhq; + +create column family raw_metrics + with comparator = DateType and + default_validation_class = DoubleType and + key_validation_class = Int32Type; + +create column family one_hour_metric_data + with comparator = 'CompositeType(DateType, Int32Type)' and + default_validation_class = DoubleType and + key_validation_class = Int32Type; + +create column family six_hour_metric_data + with comparator = 'CompositeType(DateType, Int32Type)' and + default_validation_class = DoubleType and + key_validation_class = Int32Type; + +create column family twenty_four_hour_metric_data + with comparator = 'CompositeType(DateType, Int32Type)' and + default_validation_class = DoubleType and + key_validation_class = Int32Type; + +create column family metrics_work_queue + with comparator = 'CompositeType(DateType, Int32Type)' and + default_validation_class = Int32Type and + key_validation_class = UTF8Type; + +create column family resource_traits + with comparator = 'CompositeType(DateType, Int32Type, Int32Type, UTF8Type, UTF8Type)' and + default_validation_class = UTF8Type and + key_validation_class = Int32Type; + +create column family traits + with comparator = DateType and + default_validation_class = UTF8Type and + key_validation_class = Int32Type; diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/cassandra/cql/create_keyspace.cql b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/cassandra/cql/create_keyspace.cql new file mode 100644 index 0000000..9df13a0 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/cassandra/cql/create_keyspace.cql @@ -0,0 +1 @@ +CREATE KEYSPACE rhq WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}; diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/cassandra/cql/dbsetup.cql b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/cassandra/cql/dbsetup.cql new file mode 100644 index 0000000..189b35b --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/cassandra/cql/dbsetup.cql @@ -0,0 +1,42 @@ +CREATE KEYSPACE rhq WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}; + +USE rhq; + +CREATE TABLE raw_metrics ( + schedule_id int, + time timestamp, + value double, + PRIMARY KEY (schedule_id, time) +); + +CREATE TABLE one_hour_metrics ( + schedule_id int, + time timestamp, + type int, + value double, + PRIMARY KEY (schedule_id, time, type) +); + +CREATE TABLE six_hour_metrics ( + schedule_id int, + time timestamp, + type int, + value double, + PRIMARY KEY (schedule_id, time, type) +); + +CREATE TABLE twenty_four_hour_metrics ( + schedule_id int, + time timestamp, + type int, + value double, + PRIMARY KEY (schedule_id, time, type) +); + +CREATE TABLE metrics_index ( + bucket varchar, + time timestamp, + schedule_id int, + null_col boolean, + PRIMARY KEY (bucket, time, schedule_id) +); diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/BootstrapDeployer.java b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/BootstrapDeployer.java new file mode 100644 index 0000000..73015c7 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/BootstrapDeployer.java @@ -0,0 +1,323 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra; + +import static java.util.Arrays.asList; +import static org.rhq.core.util.StringUtil.collectionToString; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.thrift.transport.TSocket; +import org.apache.thrift.transport.TTransportException; + +import org.rhq.bundle.ant.AntLauncher; +import org.rhq.core.pluginapi.util.ProcessExecutionUtility; +import org.rhq.core.system.OperatingSystemType; +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.StringUtil; +import org.rhq.core.util.ZipUtil; +import org.rhq.core.util.file.FileUtil; +import org.rhq.core.util.stream.StreamUtil; + +/** + * @author John Sanda + */ +public class BootstrapDeployer { + + private final Log log = LogFactory.getLog(BootstrapDeployer.class); + + private DeploymentOptions deploymentOptions; + + public void setDeploymentOptions(DeploymentOptions deploymentOptions) { + this.deploymentOptions = deploymentOptions; + } + + public String getCassandraHosts() { + StringBuilder hosts = new StringBuilder(); + for (int i = 0; i < deploymentOptions.getNumNodes(); ++i) { + hosts.append(getLocalIPAddress(i + 1)).append(":9160,"); + } + hosts.deleteCharAt(hosts.length() - 1); + return hosts.toString(); + } + + public List<File> deploy() throws CassandraException { + Set<String> ipAddresses = calculateLocalIPAddresses(deploymentOptions.getNumNodes()); + File clusterDir = new File(deploymentOptions.getClusterDir()); + File installedMarker = new File(clusterDir, ".installed"); + + if (isClusterInstalled()) { + return Collections.emptyList(); + } + + FileUtil.purge(clusterDir, false); + + File bundleZipeFile = null; + File bundleDir = null; + List<File> nodeDirs = new LinkedList<File>(); + + try { + deploymentOptions.load(); + bundleZipeFile = unpackBundleZipFile(); + bundleDir = unpackBundle(bundleZipeFile); + + for (int i = 0; i < deploymentOptions.getNumNodes(); ++i) { + Set<String> seeds = getSeeds(ipAddresses, i + 1); + int jmxPort = 7200 + i; + String address = getLocalIPAddress(i + 1); + File nodeBasedir = new File(clusterDir, "node" + i); + nodeDirs.add(nodeBasedir); + + Properties props = new Properties(); + props.put("cluster.name", "rhq"); + props.put("cluster.dir", clusterDir.getAbsolutePath()); + props.put("auto.bootstrap", deploymentOptions.isAutoDeploy()); + props.put("data.dir", "data"); + props.put("commitlog.dir", "commit_log"); + props.put("log.dir", "logs"); + props.put("saved.caches.dir", "saved_caches"); + props.put("hostname", address); + props.put("seeds", collectionToString(ipAddresses)); + props.put("jmx.port", Integer.toString(jmxPort)); + props.put("initial.token", generateToken(i, deploymentOptions.getNumNodes())); + props.put("rhq.deploy.dir", nodeBasedir.getAbsolutePath()); + props.put("rhq.deploy.id", i); + props.put("rhq.deploy.phase", "install"); + props.put("listen.address", address); + props.put("rpc.address", address); + props.put("logging.level", deploymentOptions.getLoggingLevel()); + props.put("rhq.cassandra.username", deploymentOptions.getUsername()); + props.put("rhq.cassandra.password", deploymentOptions.getPassword()); + + if (deploymentOptions.getRingDelay() != null) { + props.put("cassandra.ring.delay.property", "-Dcassandra.ring_delay_ms="); + props.put("cassandra.ring.delay", deploymentOptions.getRingDelay()); + } + + props.put("rhq.cassandra.node.num_tokens", deploymentOptions.getNumTokens()); + props.put("rhq.cassandra.authenticator", deploymentOptions.getAuthenticator()); + props.put("rhq.cassandra.authorizer", deploymentOptions.getAuthorizer()); + + doLocalDeploy(props, bundleDir); +// startNode(nodeBasedir); +// if (i == 0) { +// waitForNodeToStart(10, address); +// } + } + FileUtil.writeFile(new ByteArrayInputStream(new byte[] {0}), installedMarker); + } catch (IOException e) { + throw new CassandraException("Failed to deploy embedded cluster", e); + } finally { + if (bundleZipeFile != null) { + bundleZipeFile.delete(); + } + + if (bundleDir != null) { + FileUtil.purge(bundleDir, true); + } + } + + return nodeDirs; + } + + public static void main(String[] args) { + long start = System.currentTimeMillis(); + BootstrapDeployer deployer = new BootstrapDeployer(); + + DeploymentOptions deploymentOptions = new DeploymentOptions(); + try { + deploymentOptions.setNumNodes(2); + deploymentOptions.load(); + } catch (IOException e) { + throw new RuntimeException("Failed to load deployment options.", e); + } + deployer.setDeploymentOptions(deploymentOptions); + try { + deployer.deploy(); + PropertiesFileUpdate serverPropertiesUpdater = getServerProperties(); + + String[] hostNames = getHostNames(deployer.getCassandraHosts()); + serverPropertiesUpdater.update("rhq.cassandra.cluster.seeds", StringUtil.arrayToString(hostNames)); + + long end = System.currentTimeMillis(); + deployer.log.info("Finished installing embedded cluster in " + (end - start) + " ms"); + } catch (CassandraException e) { + throw new RuntimeException("A deployment error occurred.", e); + } catch (IOException e) { + throw new RuntimeException("An error occurred while trying to update RHQ server properties", e); + } + } + + private static PropertiesFileUpdate getServerProperties() { + String sysprop = System.getProperty("rhq.server.properties-file"); + if (sysprop == null) { + throw new RuntimeException("The required system property [rhq.server.properties] is not defined."); + } + + File file = new File(sysprop); + if (!(file.exists() && file.isFile())) { + throw new RuntimeException("System property [" + sysprop + "] points to in invalid file."); + } + + return new PropertiesFileUpdate(file.getAbsolutePath()); + } + + private static String[] getHostNames(String hosts) { + List<String> hostNames = new ArrayList<String>(); + for (String s : hosts.split(",")) { + String[] params = s.split(":"); + hostNames.add(params[0]); + } + return hostNames.toArray(new String[hostNames.size()]); + } + + private boolean isClusterInstalled() { + File clusterDir = new File(deploymentOptions.getClusterDir()); + File installedMarker = new File(clusterDir, ".installed"); + + if (installedMarker.exists()) { + return true; + } + return false; + } + + private void doLocalDeploy(Properties deployProps, File bundleDir) throws CassandraException { + AntLauncher launcher = new AntLauncher(); + try { + File recipeFile = new File(bundleDir, "deploy.xml"); + launcher.executeBundleDeployFile(recipeFile, deployProps, null); + } catch (Exception e) { + String msg = "Failed to execute local rhq cassandra bundle deployment"; + //logException(msg, e); + throw new CassandraException(msg, e); + } + } + + private void startNode(File basedir) { + File binDir = new File(basedir, "bin"); + File startScript; + SystemInfo systemInfo = SystemInfoFactory.createSystemInfo(); + + if (systemInfo.getOperatingSystemType() == OperatingSystemType.WINDOWS) { + startScript = new File(binDir, "cassandra.bat"); + } else { + startScript = new File(binDir, "cassandra"); + } + + ProcessExecution startScriptExe = ProcessExecutionUtility.createProcessExecution(startScript); + startScriptExe.setArguments(asList("-p", "cassandra.pid")); + + ProcessExecutionResults results = systemInfo.executeProcess(startScriptExe); + } + + private void waitForNodeToStart(int maxRetries, String host) throws CassandraException { + int port = 9160; + int timeout = 50; + for (int i = 0; i < maxRetries; ++i) { + TSocket socket = new TSocket(host, port, timeout); + try { + socket.open(); + return; + } catch (TTransportException e) { + try { + Thread.sleep(1000); + } catch (InterruptedException e1) { + } + } + } + Date timestamp = new Date(); + throw new CassandraException("[" + timestamp + "] Could not connect to " + host + " after " + maxRetries + + " tries"); + } + + private File unpackBundleZipFile() throws IOException { + InputStream bundleInputStream = getClass().getResourceAsStream("/cassandra-bundle.zip"); + File bundleZipFile = File.createTempFile("cassandra-bundle.zip", null); + StreamUtil.copy(bundleInputStream, new FileOutputStream(bundleZipFile)); + + return bundleZipFile; + } + + private File unpackBundle(File bundleZipFile) throws IOException { + File bundleDir = new File(System.getProperty("java.io.tmpdir"), "rhq-cassandra-bundle"); + bundleDir.mkdir(); + ZipUtil.unzipFile(bundleZipFile, bundleDir); + + return bundleDir; + } + + private Set<String> calculateLocalIPAddresses(int numNodes) { + Set<String> addresses = new HashSet<String>(); + for (int i = 1; i <= numNodes; ++i) { + addresses.add(getLocalIPAddress(i)); + } + return addresses; + } + + private String getLocalIPAddress(int i) { + return "127.0.0." + i; + } + + private String generateToken(int i, int numNodes) { + BigInteger num = new BigInteger("2").pow(127).divide(new BigInteger(Integer.toString(numNodes))); + return num.multiply(new BigInteger(Integer.toString(i))).toString(); + } + + private Set<String> getSeeds(Set<String> addresses, int i) { + Set<String> seeds = new HashSet<String>(); + String address = getLocalIPAddress(i); + + for (String nodeAddress : addresses) { + if (nodeAddress.equals(address)) { + continue; + } else { + seeds.add(nodeAddress); + } + } + + return seeds; + } + +} diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java new file mode 100644 index 0000000..22bd11e --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java @@ -0,0 +1,172 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra; + +import static java.util.Arrays.asList; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.rhq.core.pluginapi.util.ProcessExecutionUtility; +import org.rhq.core.system.OperatingSystemType; +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.StringUtil; + +/** + * @author John Sanda + */ +public class CassandraClusterManager { + + private final Log log = LogFactory.getLog(CassandraClusterManager.class); + + private DeploymentOptions deploymentOptions; + + public CassandraClusterManager() { + this(new DeploymentOptions()); + } + + public CassandraClusterManager(DeploymentOptions deploymentOptions) { + this.deploymentOptions = deploymentOptions; + try { + this.deploymentOptions.load(); + } catch (IOException e) { + log.error("Failed to load deployment options", e); + throw new IllegalStateException("An initialization error occurred.", e); + } + } + + public List<File> installCluster() { + if (log.isDebugEnabled()) { + log.debug("Installing embedded " + deploymentOptions.getNumNodes() + " node cluster to " + + deploymentOptions.getClusterDir()); + } else { + log.info("Installing embedded cluster"); + } + + BootstrapDeployer deployer = new BootstrapDeployer(); + deployer.setDeploymentOptions(deploymentOptions); + try { + return deployer.deploy(); + } catch (CassandraException e) { + String msg = "Failed to install cluster."; + log.error(msg, e); + throw new RuntimeException(msg, e); + } + } + + public void startCluster(List<File> nodeDirs) { + long start = System.currentTimeMillis(); + log.info("Starting embedded cluster"); + for (File dir : nodeDirs) { + ProcessExecutionResults results = startNode(dir); + if (results.getError() != null) { + log.warn("An unexpected error occurred while starting the node at " + dir, results.getError()); + } + } + long end = System.currentTimeMillis(); + log.info("Started embedded cluster in " + (end - start) + " ms"); + } + + private ProcessExecutionResults startNode(File basedir) { + if (log.isDebugEnabled()) { + log.debug("Starting node at " + basedir); + } + File binDir = new File(basedir, "bin"); + File startScript; + SystemInfo systemInfo = SystemInfoFactory.createSystemInfo(); + + if (systemInfo.getOperatingSystemType() == OperatingSystemType.WINDOWS) { + startScript = new File(binDir, "cassandra.bat"); + } else { + startScript = new File(binDir, "cassandra"); + } + + ProcessExecution startScriptExe = ProcessExecutionUtility.createProcessExecution(startScript); + startScriptExe.setArguments(asList("-p", "cassandra.pid")); + + ProcessExecutionResults results = systemInfo.executeProcess(startScriptExe); + if (log.isDebugEnabled()) { + log.debug(startScript + " returned with exit code [" + results.getExitCode() + "]"); + } + + return results; + } + + public void shutdownCluster() { + + } + + public List<String> getHostNames() { + List<String> hosts = new ArrayList<String>(deploymentOptions.getNumNodes()); + for (int i = 0; i < deploymentOptions.getNumNodes(); ++i) { + hosts.add("127.0.0." + (i + 1)); + } + return hosts; + } + + public InputStream loadBundle() { + return null; + } + + public static void main(String[] args) { + CassandraClusterManager ccm = new CassandraClusterManager(); + List<File> nodeDirs = ccm.installCluster(); + ccm.startCluster(nodeDirs); + + PropertiesFileUpdate serverPropertiesUpdater = getServerProperties(); + try { + serverPropertiesUpdater.update("rhq.cassandra.cluster.seeds", + StringUtil.collectionToString(ccm.getHostNames())); + } catch (IOException e) { + throw new RuntimeException("An error occurred while trying to update RHQ server properties", e); + } + } + + private static PropertiesFileUpdate getServerProperties() { + String sysprop = System.getProperty("rhq.server.properties-file"); + if (sysprop == null) { + throw new RuntimeException("The required system property [rhq.server.properties] is not defined."); + } + + File file = new File(sysprop); + if (!(file.exists() && file.isFile())) { + throw new RuntimeException("System property [" + sysprop + "] points to in invalid file."); + } + + return new PropertiesFileUpdate(file.getAbsolutePath()); + } + +} diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraException.java b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraException.java new file mode 100644 index 0000000..43259ac --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraException.java @@ -0,0 +1,47 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra; + +/** + * @author John Sanda + */ +public class CassandraException extends Exception { + public CassandraException() { + super(); + } + + public CassandraException(String message) { + super(message); + } + + public CassandraException(String message, Throwable cause) { + super(message, cause); + } + + public CassandraException(Throwable cause) { + super(cause); + } +} diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraNode.java b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraNode.java new file mode 100644 index 0000000..6b1cd27 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraNode.java @@ -0,0 +1,74 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra; + +/** + * @author John Sanda + */ +public class CassandraNode { + + private String hostName; + + private int thriftPort; + + public CassandraNode(String hostName, int thriftPort) { + this.hostName = hostName; + this.thriftPort = thriftPort; + } + + public String getHostName() { + return hostName; + } + + public int getThriftPort() { + return thriftPort; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + CassandraNode that = (CassandraNode) o; + + if (thriftPort != that.thriftPort) return false; + if (!hostName.equals(that.hostName)) return false; + + return true; + } + + @Override + public int hashCode() { + int result = hostName.hashCode(); + result = 41 * result + thriftPort; + return result; + } + + @Override + public String toString() { + return "CassandraNode[hostName: " + hostName + ", thriftPort: " + thriftPort + "]"; + } +} diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/ClusterInitService.java b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/ClusterInitService.java new file mode 100644 index 0000000..fb9d011 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/ClusterInitService.java @@ -0,0 +1,256 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; + +import org.apache.cassandra.thrift.Cassandra; +import org.apache.cassandra.thrift.InvalidRequestException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.thrift.TException; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.transport.TFramedTransport; +import org.apache.thrift.transport.TSocket; +import org.apache.thrift.transport.TTransportException; + +/** + * This class provides operations to ensure a cluster is initialized and in a consistent + * state. It does not offer functionality for initializing a cluster but rather to make + * sure that nodes have started up and are accepting client connections for example. + * + * @author John Sanda + */ +public class ClusterInitService { + + private final Log log = LogFactory.getLog(ClusterInitService.class); + + /** + * Attempts to establish a Thrift RPC connection to the hosts for the number specified. + * In other words, if there are four hosts and <code>numHosts</code> is two, this + * method will immediately return after making two successful connections. + * + * @param hosts The cluster nodes to which a connection should be made + * @param numHosts The number of hosts to which a successful connection has to be made + * before returning. + * @return true if connections are made to the number of specified hosts, false + * otherwise. + */ + public boolean ping(List<CassandraNode> hosts, int numHosts) { + long sleep = 100; + int timeout = 50; + int connections = 0; + + for (CassandraNode host : hosts) { + TSocket socket = new TSocket(host.getHostName(), host.getThriftPort(), timeout); + try { + socket.open(); + if (log.isDebugEnabled()) { + log.debug("Successfully connected to cassandra node [" + host + "]"); + } + ++connections; + socket.close(); + if (connections == numHosts) { + return true; + } + } catch (TTransportException e) { + String msg = "Unable to open thrift connection to cassandra node [" + host + "]"; + logException(msg, e); + } + try { + Thread.sleep(sleep); + } catch (InterruptedException e) { + } + } + + return false; + } + + /** + * This method attempts to establish a Thrift RPC connection to each host. If the + * connection fails, the host is retried after going through the other, remaining + * hosts. + * + * @param hosts The cluster nodes to which a connection should be made + */ + public void waitForClusterToStart(List<CassandraNode> hosts) { + waitForClusterToStart(hosts, hosts.size()); + } + + /** + * This method attempts to establish a Thrift RPC connection to each host for the + * number specified. In other words, if there are four hosts and <code>numHosts</code> + * is 2, this method will block only until it can connect to two of the hosts. If the + * connection fails, the host is retried after going through the other, remaining + * hosts. + * + * @param hosts The cluster nodes to which a connection should be made + * @param numHosts The number of hosts to which a successful connection has to be made + * before returning. + */ + public void waitForClusterToStart(List<CassandraNode> hosts, int numHosts) { + long sleep = 100; + int timeout = 50; + int connections = 0; + Queue<CassandraNode> queue = new LinkedList<CassandraNode>(hosts); + CassandraNode host = queue.poll(); + + while (host != null) { + TSocket socket = new TSocket(host.getHostName(), host.getThriftPort(), timeout); + try { + socket.open(); + if (log.isDebugEnabled()) { + log.debug("Successfully connected to cassandra node [" + host + "]"); + } + ++connections; + socket.close(); + if (connections == numHosts) { + return; + } + } catch (TTransportException e) { + queue.offer(host); + String msg = "Unable to open thrift connection to cassandra node [" + host + "]"; + logException(msg, e); + } + try { + Thread.sleep(sleep); + } catch (InterruptedException e) { + } + host = queue.poll(); + } + } + + /** + * Waits for the cluster to reach schema agreement. During cluster initialization + * before and while schema changes propagate throughout the cluster, there could be + * multiple schema versions found among nodes. Schema agreement is reached when there + * is a single schema version and all nodes are on that version. + * + * @param clusterName The cluster name used by underlying Hector APIs. + * @param hosts The cluster nodes + */ + public void waitForSchemaAgreement(String clusterName, List<CassandraNode> hosts) { + long sleep = 100L; + CassandraClient client = createClient(hosts.get(0)); + client.openConnection(); + boolean schemaInAgreement = false; + String schemaVersion = null; + + while (!schemaInAgreement) { + Map<String, List<String>> schemaVersions = null; + try { + schemaVersions = client.describe_schema_versions(); + } catch (InvalidRequestException e) { + throw new RuntimeException("Unable to get schema versions from " + hosts.get(0), e); + } catch (TException e) { + throw new RuntimeException("Unable to get schema versions from " + hosts.get(0), e); + } + if (schemaVersions.size() > 1) { + if (log.isInfoEnabled()) { + log.info("Schema agreement has not been reached. Found " + schemaVersions.size() + + " schema versions"); + } + if (log.isDebugEnabled()) { + log.debug("Found the following schema versions: " + schemaVersions.keySet()); + } + try { + Thread.sleep(sleep); + } catch (InterruptedException e) { + } + } else { + schemaVersion = schemaVersions.keySet().iterator().next(); + List<String> hostAddresses = schemaVersions.get(schemaVersion); + if (hostAddresses.size() == hosts.size()) { + schemaInAgreement = true; + } else { + if (log.isInfoEnabled()) { + log.info("Schema agreement has not been reached. Found one schema version but only " + + hostAddresses.size() + " of " + hosts.size() + " nodes at version [" + schemaVersion + "]"); + } + if (log.isDebugEnabled()) { + log.debug("Found the following nodes at schema version [" + schemaVersion + "]: " + + hostAddresses); + } + try { + Thread.sleep(sleep); + } catch (InterruptedException e) { + } + } + } + } + client.closeConnection(); + + if (log.isInfoEnabled()) { + log.info("Schema agreement has been reached at version [" + schemaVersion + "]"); + } + } + + private CassandraClient createClient(CassandraNode node) { + TSocket socket = new TSocket(node.getHostName(), node.getThriftPort()); + TFramedTransport transport = new TFramedTransport(socket); + TProtocol protocol = new TBinaryProtocol(transport); + + return new CassandraClient(socket, protocol, node); + } + + private void logException(String msg, Exception e) { + if (log.isDebugEnabled()) { + log.debug(msg, e); + } else if (log.isInfoEnabled()) { + log.info(msg + ": " + e.getMessage()); + } else { + log.warn(msg); + } + } + + private static class CassandraClient extends Cassandra.Client { + private TSocket socket; + private CassandraNode node; + + public CassandraClient(TSocket socket, TProtocol protocol, CassandraNode node) { + super(protocol); + this.socket = socket; + this.node = node; + } + + public void openConnection() { + try { + socket.open(); + } catch (TTransportException e) { + throw new RuntimeException("Could not open thrift connection to " + node, e); + } + } + + public void closeConnection() { + socket.close(); + } + } + +} diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/DeploymentOptions.java b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/DeploymentOptions.java new file mode 100644 index 0000000..098b1b0 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/DeploymentOptions.java @@ -0,0 +1,285 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * @author John Sanda + */ +public class DeploymentOptions { + + private final Log log = LogFactory.getLog(DeploymentOptions.class); + + private boolean loaded; + + private String bundleFileName; + private String bundleName; + private String bundleVersion; + private String clusterDir; + private Integer numNodes; + private Boolean autoDeploy; + private Boolean embedded; + private String loggingLevel; + private Long ringDelay; + private Integer numTokens; + private Integer nativeTransportPort; + private Integer nativeTransportMaxThreads; + private String username; + private String password; + private String authenticator; + private String authorizer; + + public DeploymentOptions() { + } + + public void load() throws IOException { + if (loaded) { + return; + } + InputStream stream = null; + try { + stream = getClass().getResourceAsStream("/cassandra.properties"); + Properties props = new Properties(); + props.load(stream); + + init(props); + loaded = true; + } catch (IOException e) { + log.warn("Unable to load deployment options from cassandra.properties."); + log.info("The following error occurred while trying to load options.", e); + throw e; + } finally { + if (stream != null) { + try { + stream.close(); + } catch (IOException e) { + String msg = "An error occurred while closing input stream on cassandra.properties"; + log.info(msg, e); + } + } + } + } + + private void init(Properties properties) { + setBundleFileName(properties.getProperty("rhq.cassandra.bundle.filename")); + setBundleName(properties.getProperty("rhq.cassandra.bundle.name")); + setBundleVersion(properties.getProperty("rhq.cassandra.bundle.version")); + setClusterDir(loadProperty("rhq.cassandra.cluster.dir", properties)); + setNumNodes(Integer.parseInt(loadProperty("rhq.cassandra.cluster.num-nodes", properties))); + setAutoDeploy(Boolean.valueOf(loadProperty("rhq.cassandra.cluster.auto-deploy", properties))); + setEmbedded(Boolean.valueOf(loadProperty("rhq.cassandra.cluster.is-embedded", properties))); + setLoggingLevel(loadProperty("rhq.cassandra.logging.level", properties)); + + String ringDelay = loadProperty("rhq.cassandra.ring.delay", properties); + if (ringDelay != null && !ringDelay.isEmpty()) { + setRingDelay(Long.valueOf(ringDelay)); + } + + setNumTokens(Integer.valueOf(loadProperty("rhq.cassandra.num-tokens", properties))); + setNativeTransportPort(Integer.valueOf(loadProperty("rhq.cassandra.native-transport-port", properties))); + setNativeTransportMaxThreads(Integer.valueOf(loadProperty("rhq.casandra.native-transport-max-threads", + properties))); + setUsername(loadProperty("rhq.cassandra.username", properties)); + setPassword(loadProperty("rhq.cassandra.password", properties)); + setAuthenticator(loadProperty("rhq.cassandra.authenticator", properties)); + setAuthorizer(loadProperty("rhq.cassandra.authorizer", properties)); + } + + private String loadProperty(String key, Properties properties) { + String value = System.getProperty(key); + if (value == null || value.isEmpty()) { + return properties.getProperty(key); + } + return value; + } + + public String getBundleFileName() { + return bundleFileName; + } + + public void setBundleFileName(String name) { + if (bundleFileName == null) { + bundleFileName = name; + } + } + + public String getBundleName() { + return bundleName; + } + + public void setBundleName(String name) { + if (bundleName == null) { + bundleName = name; + } + } + + public String getBundleVersion() { + return bundleVersion; + } + + public void setBundleVersion(String version) { + if (bundleVersion == null) { + bundleVersion = version; + } + } + + public String getClusterDir() { + return clusterDir; + } + + public void setClusterDir(String dir) { + if (clusterDir == null) { + clusterDir = dir; + } + } + + public int getNumNodes() { + return numNodes; + } + + public void setNumNodes(int numNodes) { + if (this.numNodes == null) { + this.numNodes = numNodes; + } + } + + public boolean isAutoDeploy() { + return autoDeploy; + } + + public void setAutoDeploy(boolean autoDeploy) { + if (this.autoDeploy == null) { + this.autoDeploy = autoDeploy; + } + } + + public boolean isEmbedded() { + return embedded; + } + + public void setEmbedded(boolean embedded) { + if (this.embedded == null) { + this.embedded = embedded; + } + } + + public String getLoggingLevel() { + return loggingLevel; + } + + public void setLoggingLevel(String loggingLevel) { + if (this.loggingLevel == null) { + this.loggingLevel = loggingLevel; + } + } + + public Long getRingDelay() { + return ringDelay; + } + + public void setRingDelay(Long ringDelay) { + if (this.ringDelay == null) { + this.ringDelay = ringDelay; + } + } + + public Integer getNumTokens() { + return numTokens; + } + + public void setNumTokens(int numTokens) { + if (this.numTokens == null) { + this.numTokens = numTokens; + } + } + + public Integer getNativeTransportPort() { + return nativeTransportPort; + } + + public void setNativeTransportPort(Integer port) { + if (nativeTransportPort == null) { + nativeTransportPort = port; + } + } + + public Integer getNativeTransportMaxThreads() { + return nativeTransportMaxThreads; + } + + public void setNativeTransportMaxThreads(int numThreads) { + if (nativeTransportMaxThreads == null) { + nativeTransportMaxThreads = numThreads; + } + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + if (this.username == null) { + this.username = username; + } + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + if (this.password == null) { + this.password = password; + } + } + + public String getAuthenticator() { + return authenticator; + } + + public void setAuthenticator(String authenticator) { + if (this.authenticator == null) { + this.authenticator = authenticator; + } + } + + public String getAuthorizer() { + return authorizer; + } + + public void setAuthorizer(String authorizer) { + if (this.authorizer == null) { + this.authorizer = authorizer; + } + } + +} diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/.DS_Store b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/.DS_Store new file mode 100644 index 0000000..856cdc6 Binary files /dev/null and b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/.DS_Store differ diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra.properties b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra.properties new file mode 100644 index 0000000..fb844da --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra.properties @@ -0,0 +1,77 @@ +# These properties are used for the Cassandra bundle deployment and for embedded cluster +# deployments. Properties that affect embedded cluster deployments are used only in +# development and test environments, not production environments. +cassandra.version=1.2.0-beta3 +rhq.cassandra.bundle.filename=/cassandra-bundle.zip +rhq.cassandra.bundle.name=RHQ Cassandra Bundle +rhq.cassandra.bundle.version=1.0 + +# The username with which to authenticate requests to Cassandra. +rhq.cassandra.username=rhqadmin + +# The password with which to authenticate requests to Cassandra. +rhq.cassandra.password=rhqadmin + +# When a node initializes it contacts a seed and then sleeps for RING_DELAY (milliseconds) +# to learn about other nodes in the cluster. This defaults to 30 seconds. Cassandra gets +# the value from the cassandra.ring_delay_ms system property +# rhq.cassandra.ring.delay + +# Defines the number of tokens randomly assigned to a 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. Tokens are randomly generated with the expectation of an even +# distribution. With that said, there can be some variation. Either increasing this value +# or increasing the number of nodes in the cluster will help even out the distribution. +rhq.cassandra.num-tokens=256 + +# A class that performs authentication. The value should be a fully qualified class name +# and implement IAuthenticator. +rhq.cassandra.authenticator=org.rhq.cassandra.auth.SimpleAuthenticator +#rhq.cassandra.authenticator=org.apache.cassandra.auth.AllowAllAuthenticator + +# A class that performs authorization. Used to limit/provide permissions. The value should +# be a fully qualified class name and implement IAuthorizer. +rhq.cassandra.authorizer=org.rhq.cassandra.auth.SimpleAuthorizer +#rhq.cassandra.authorizer=org.apache.cassandra.auth.AllowAllAuthorizer + +# The location of the password properties file used by SimpleAuthenticator. If a relative +# path is specified, its location is resolved relative to Cassandra's bin directory. +rhq.cassandra.password.properties.file=./../conf/passwd.properties + +# The location of the authorization properties file used by SimpleAuthority. If a relative +# path is specified, its location is resolved relative to Cassandra's bin directory. +rhq.cassandra.access.properties.file=./../conf/access.properties + +# The maximum number of threads handling native CQL requests. +rhq.casandra.native-transport-max-threads=64 + +# The port for the CQL native transport to listen for clients on. +rhq.cassandra.native-transport-port=9042 + +# The remaining properties pertain to cluster configuration and are only used in +# development and testing environments when an embedded cluster is used. These properties +# are also loaded into the container build (when the dev profile is active) in the +# rhq-container.build.xml script. If you add any properties below here that pertain to +# cluster configuration for an embedded cluster, please also update +# rhq-container.build.xml. This is done as a convenience for developers so that they can +# just update rhq-server.properties to change the cluster configuration. +# +# +# Accepts a value of true or false and specifies whether or not the cluster is embedded. +# Note that if this property is set to false, the other, remaining cluster configuration +# properties that are set will be ignored as they are only used with embedded clusters. +rhq.cassandra.cluster.is-embedded=true + +# The directory in which cluster nodes will be installed. +rhq.cassandra.cluster.dir=${rhq.rootDir}/cassandra + +# The number of nodes in the cluster. This specifies how many nodes to install and +# configure. The top level or base directory for each node will be nodeN where N is the +# node number. +rhq.cassandra.cluster.num-nodes=2 + +rhq.cassandra.cluster.auto-deploy=true + +# The log4j logging level to use on each node. +rhq.cassandra.logging.level=DEBUG diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/access.properties b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/access.properties new file mode 100644 index 0000000..4465450 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/access.properties @@ -0,0 +1,46 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This is a sample access file for SimpleAuthority. The format of this file +# is KEYSPACE[.COLUMNFAMILY].PERMISSION=USERS, where: +# +# * KEYSPACE is the keyspace name. +# * COLUMNFAMILY is the column family name. +# * PERMISSION is one of <ro> or <rw> for read-only or read-write respectively. +# * USERS is a comma delimited list of users from passwd.properties. +# +# See below for example entries. + +# NOTE: This file contains potentially sensitive information, please keep +# this in mind when setting its mode and ownership. + +# The magical '<modify-keyspaces>' property lists users who can modify the +# list of keyspaces: all users will be able to view the list of keyspaces. +<modify-keyspaces>=cassandra + +# Access to Keyspace1 (add/remove column families, etc). +Keyspace1.<ro>=jsmith,Elvis Presley +Keyspace1.<rw>=dilbert + +# Access to Standard1 (keyspace Keyspace1) +#Keyspace1.Standard1.<rw>=jsmith,Elvis Presley,dilbert + +system.local.<ro>=rhqadmin +system.peers.<ro>=rhqadmin +system.schema_keyspaces.<ro>=rhqadmin +system.schema_columnfamilies.<ro>=rhqadmin +system.schema_columns.<ro>=rhqadmin +rhq.<rw>=rhqadmin diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/cassandra-env.sh b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/cassandra-env.sh new file mode 100644 index 0000000..a80b05b --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/cassandra-env.sh @@ -0,0 +1,235 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +calculate_heap_sizes() +{ + case "`uname`" in + Linux) + system_memory_in_mb=`free -m | awk '/Mem:/ {print $2}'` + system_cpu_cores=`egrep -c 'processor([[:space:]]+):.*' /proc/cpuinfo` + ;; + FreeBSD) + system_memory_in_bytes=`sysctl hw.physmem | awk '{print $2}'` + system_memory_in_mb=`expr $system_memory_in_bytes / 1024 / 1024` + system_cpu_cores=`sysctl hw.ncpu | awk '{print $2}'` + ;; + SunOS) + system_memory_in_mb=`prtconf | awk '/Memory size:/ {print $3}'` + system_cpu_cores=`psrinfo | wc -l` + ;; + *) + # assume reasonable defaults for e.g. a modern desktop or + # cheap server + system_memory_in_mb="2048" + system_cpu_cores="2" + ;; + esac + + # some systems like the raspberry pi don't report cores, use at least 1 + if [ "$system_cpu_cores" -lt "1" ] + then + system_cpu_cores="1" + fi + + # set max heap size based on the following + # max(min(1/2 ram, 1024MB), min(1/4 ram, 8GB)) + # calculate 1/2 ram and cap to 1024MB + # calculate 1/4 ram and cap to 8192MB + # pick the max + half_system_memory_in_mb=`expr $system_memory_in_mb / 2` + quarter_system_memory_in_mb=`expr $half_system_memory_in_mb / 2` + if [ "$half_system_memory_in_mb" -gt "1024" ] + then + half_system_memory_in_mb="1024" + fi + if [ "$quarter_system_memory_in_mb" -gt "8192" ] + then + quarter_system_memory_in_mb="8192" + fi + if [ "$half_system_memory_in_mb" -gt "$quarter_system_memory_in_mb" ] + then + max_heap_size_in_mb="$half_system_memory_in_mb" + else + max_heap_size_in_mb="$quarter_system_memory_in_mb" + fi + MAX_HEAP_SIZE="${max_heap_size_in_mb}M" + + # Young gen: min(max_sensible_per_modern_cpu_core * num_cores, 1/4 * heap size) + max_sensible_yg_per_core_in_mb="100" + max_sensible_yg_in_mb=`expr $max_sensible_yg_per_core_in_mb "*" $system_cpu_cores` + + desired_yg_in_mb=`expr $max_heap_size_in_mb / 4` + + if [ "$desired_yg_in_mb" -gt "$max_sensible_yg_in_mb" ] + then + HEAP_NEWSIZE="${max_sensible_yg_in_mb}M" + else + HEAP_NEWSIZE="${desired_yg_in_mb}M" + fi +} + +# Determine the sort of JVM we'll be running on. + +java_ver_output=`"${JAVA:-java}" -version 2>&1` + +jvmver=`echo "$java_ver_output" | awk -F'"' 'NR==1 {print $2}'` +JVM_VERSION=${jvmver%_*} +JVM_PATCH_VERSION=${jvmver#*_} + +jvm=`echo "$java_ver_output" | awk 'NR==2 {print $1}'` +case "$jvm" in + OpenJDK) + JVM_VENDOR=OpenJDK + # this will be "64-Bit" or "32-Bit" + JVM_ARCH=`echo "$java_ver_output" | awk 'NR==3 {print $2}'` + ;; + "Java(TM)") + JVM_VENDOR=Oracle + # this will be "64-Bit" or "32-Bit" + JVM_ARCH=`echo "$java_ver_output" | awk 'NR==3 {print $3}'` + ;; + *) + # Help fill in other JVM values + JVM_VENDOR=other + JVM_ARCH=unknown + ;; +esac + + +# Override these to set the amount of memory to allocate to the JVM at +# start-up. For production use you may wish to adjust this for your +# environment. MAX_HEAP_SIZE is the total amount of memory dedicated +# to the Java heap; HEAP_NEWSIZE refers to the size of the young +# generation. Both MAX_HEAP_SIZE and HEAP_NEWSIZE should be either set +# or not (if you set one, set the other). +# +# The main trade-off for the young generation is that the larger it +# is, the longer GC pause times will be. The shorter it is, the more +# expensive GC will be (usually). +# +# The example HEAP_NEWSIZE assumes a modern 8-core+ machine for decent pause +# times. If in doubt, and if you do not particularly want to tweak, go with +# 100 MB per physical CPU core. + +#MAX_HEAP_SIZE="4G" +#HEAP_NEWSIZE="800M" + +if [ "x$MAX_HEAP_SIZE" = "x" ] && [ "x$HEAP_NEWSIZE" = "x" ]; then + calculate_heap_sizes +else + if [ "x$MAX_HEAP_SIZE" = "x" ] || [ "x$HEAP_NEWSIZE" = "x" ]; then + echo "please set or unset MAX_HEAP_SIZE and HEAP_NEWSIZE in pairs (see cassandra-env.sh)" + exit 1 + fi +fi + +# Specifies the default port over which Cassandra will be available for +# JMX connections. +JMX_PORT="@@jmx.port@@" + + +# Here we create the arguments that will get passed to the jvm when +# starting cassandra. + +JVM_EXTRA_OPTS="@@cassandra.ring.delay.property@@@@cassandra.ring.delay@@" +JVM_EXTRA_OPTS="$JVM_EXTRA_OPTS -Dpasswd.properties=@@rhq.cassandra.password.properties.file@@" +JVM_EXTRA_OPTS="$JVM_EXTRA_OPTS -Daccess.properties=@@rhq.cassandra.access.properties.file@@" + +# enable assertions. disabling this in production will give a modest +# performance benefit (around 5%). +JVM_OPTS="$JVM_OPTS -ea" + +# add the jamm javaagent +if [ "$JVM_VENDOR" != "OpenJDK" -o "$JVM_VERSION" > "1.6.0" ] \ + || [ "$JVM_VERSION" = "1.6.0" -a "$JVM_PATCH_VERSION" -ge 23 ] +then + JVM_OPTS="$JVM_OPTS -javaagent:$CASSANDRA_HOME/lib/jamm-0.2.5.jar" +fi + +# enable thread priorities, primarily so we can give periodic tasks +# a lower priority to avoid interfering with client workload +JVM_OPTS="$JVM_OPTS -XX:+UseThreadPriorities" +# allows lowering thread priority without being root. see +# http://tech.stolsvik.com/2010/01/linux-java-thread-priorities-workaround.htm... +JVM_OPTS="$JVM_OPTS -XX:ThreadPriorityPolicy=42" + +# min and max heap sizes should be set to the same value to avoid +# stop-the-world GC pauses during resize, and so that we can lock the +# heap in memory on startup to prevent any of it from being swapped +# out. +JVM_OPTS="$JVM_OPTS -Xms${MAX_HEAP_SIZE}" +JVM_OPTS="$JVM_OPTS -Xmx${MAX_HEAP_SIZE}" +JVM_OPTS="$JVM_OPTS -Xmn${HEAP_NEWSIZE}" +JVM_OPTS="$JVM_OPTS -XX:+HeapDumpOnOutOfMemoryError" + +# set jvm HeapDumpPath with CASSANDRA_HEAPDUMP_DIR +if [ "x$CASSANDRA_HEAPDUMP_DIR" != "x" ]; then + JVM_OPTS="$JVM_OPTS -XX:HeapDumpPath=$CASSANDRA_HEAPDUMP_DIR/cassandra-`date +%s`-pid$$.hprof" +fi + + +startswith() { [ "${1#$2}" != "$1" ]; } + +if [ "`uname`" = "Linux" ] ; then + # reduce the per-thread stack size to minimize the impact of Thrift + # thread-per-client. (Best practice is for client connections to + # be pooled anyway.) Only do so on Linux where it is known to be + # supported. + # u34 and greater need 180k + JVM_OPTS="$JVM_OPTS -Xss180k" +fi +echo "xss = $JVM_OPTS" + +# GC tuning options +JVM_OPTS="$JVM_OPTS -XX:+UseParNewGC" +JVM_OPTS="$JVM_OPTS -XX:+UseConcMarkSweepGC" +JVM_OPTS="$JVM_OPTS -XX:+CMSParallelRemarkEnabled" +JVM_OPTS="$JVM_OPTS -XX:SurvivorRatio=8" +JVM_OPTS="$JVM_OPTS -XX:MaxTenuringThreshold=1" +JVM_OPTS="$JVM_OPTS -XX:CMSInitiatingOccupancyFraction=75" +JVM_OPTS="$JVM_OPTS -XX:+UseCMSInitiatingOccupancyOnly" + +# GC logging options -- uncomment to enable +# JVM_OPTS="$JVM_OPTS -XX:+PrintGCDetails" +# JVM_OPTS="$JVM_OPTS -XX:+PrintGCDateStamps" +# JVM_OPTS="$JVM_OPTS -XX:+PrintHeapAtGC" +# JVM_OPTS="$JVM_OPTS -XX:+PrintTenuringDistribution" +# JVM_OPTS="$JVM_OPTS -XX:+PrintGCApplicationStoppedTime" +# JVM_OPTS="$JVM_OPTS -XX:+PrintPromotionFailure" +# JVM_OPTS="$JVM_OPTS -XX:PrintFLSStatistics=1" +# JVM_OPTS="$JVM_OPTS -Xloggc:/var/log/cassandra/gc-`date +%s`.log" + +# uncomment to have Cassandra JVM listen for remote debuggers/profilers on port 1414 +# JVM_OPTS="$JVM_OPTS -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1414" + +# Prefer binding to IPv4 network intefaces (when net.ipv6.bindv6only=1). See +# http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6342561 (short version: +# comment out this entry to enable IPv6 support). +JVM_OPTS="$JVM_OPTS -Djava.net.preferIPv4Stack=true" + +# jmx: metrics and administration interface +# +# add this if you're having trouble connecting: +# JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=<public name>" +# +# see +# https://blogs.oracle.com/jmxetc/entry/troubleshooting_connection_problems_in... +# for more on configuring JMX through firewalls, etc. (Short version: +# get it working with no firewall first.) +JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.port=$JMX_PORT" +JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.ssl=false" +JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.authenticate=false" +JVM_OPTS="$JVM_OPTS $JVM_EXTRA_OPTS" diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/cassandra.yaml b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/cassandra.yaml new file mode 100644 index 0000000..9a5d7fd --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/cassandra.yaml @@ -0,0 +1,645 @@ +# 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: @@cluster.name@@ + +# 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: @@rhq.cassandra.num_tokens@@ + +# 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, hints will be dropped. +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 +authenticator: @@rhq.cassandra.authenticator@@ + +# authorization backend, implementing IAUthorizer; used to limit access/provide permissions +authorizer: @@rhq.cassandra.authorizer@@ + +# 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: + - @@rhq.deploy.dir@@/@@data.dir@@ + +# commit log +commitlog_directory: @@rhq.deploy.dir@@/@@commitlog.dir@@ + +# 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: @@rhq.deploy.dir@@/@@saved.caches.dir@@ + +# 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: "@@seeds@@" + +# 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: 7000 + +# SSL port, for encrypted communication. Unused unless enabled in +# encryption_options +ssl_storage_port: 7001 + +# 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: @@listen.address@@ + +# 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 + + +# 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: @@rhq.cassandra.native_transport_port@@ +# 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: @@rhq.casandra.native_transport_max_threads@@ + + +# Whether to start the thrift rpc server. +start_rpc: true +# 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: @@rpc.address@@ +# 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: + +# 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 400 Mbps or 50 MB/s. +# stream_throughput_outbound_megabits_per_sec: 400 + +# How long the coordinator should wait for read operations to complete +read_request_timeout_in_ms: 10000 +# How long the coordinator should wait for seq or index scans to complete +range_request_timeout_in_ms: 10000 +# How long the coordinator should wait for writes to complete +write_request_timeout_in_ms: 10000 +# 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: 10000 + +# 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/JSSE... +# +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] + +# enable or disable client/server encryption. +client_encryption_options: + enabled: false + keystore: conf/.keystore + keystore_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: all diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/log4j-server.properties b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/log4j-server.properties new file mode 100644 index 0000000..e377c32 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/log4j-server.properties @@ -0,0 +1,45 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# for production, you should probably set pattern to %c instead of %l. +# (%l is slower.) + +# output messages into a rolling log file as well as stdout +log4j.rootLogger=@@logging.level@@,stdout,R + +# stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%5p %d{HH:mm:ss,SSS} %m%n + +# rolling log file +log4j.appender.R=org.apache.log4j.RollingFileAppender +log4j.appender.R.maxFileSize=20MB +log4j.appender.R.maxBackupIndex=50 +log4j.appender.R.layout=org.apache.log4j.PatternLayout +log4j.appender.R.layout.ConversionPattern=%5p [%t] %d{ISO8601} %F (line %L) %m%n +# Edit the next line to point to your logs directory +log4j.appender.R.File=@@rhq.deploy.dir@@/@@log.dir@@/system.log +log4j.appender.R.Threshold=@@logging.level@@ + +# Application logging options +#log4j.logger.org.apache.cassandra=DEBUG +#log4j.logger.org.apache.cassandra.db=DEBUG +#log4j.logger.org.apache.cassandra.service.StorageProxy=DEBUG + +# Adding this to avoid thrift logging disconnect errors. +log4j.logger.org.apache.thrift.server.TNonblockingServer=ERROR + diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/passwd.properties b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/passwd.properties new file mode 100644 index 0000000..e6c3d9b --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/conf/passwd.properties @@ -0,0 +1,23 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# This is a sample password file for SimpleAuthenticator. The format of +# this file is username=password. If -Dpasswd.mode=MD5 then the password +# is represented as an md5 digest, otherwise it is cleartext (keep this +# in mind when setting file mode and ownership). + +cassandra=cassandra +@@rhq.cassandra.username@@=@@rhq.cassandra.password@@ diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/lib/jna-3.4.1.jar b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/lib/jna-3.4.1.jar new file mode 100644 index 0000000..4e05a4a Binary files /dev/null and b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/lib/jna-3.4.1.jar differ diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/lib/platform-3.4.1.jar b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/lib/platform-3.4.1.jar new file mode 100644 index 0000000..8357d2e Binary files /dev/null and b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/cassandra/lib/platform-3.4.1.jar differ diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/deploy.xml b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/deploy.xml new file mode 100644 index 0000000..99644a5 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/resources/deploy.xml @@ -0,0 +1,226 @@ +<project name="rhq_cassandra_bundle" + default="main" + xmlns:rhq="antlib:org.rhq.bundle"> + <rhq:bundle name="${rhq.cassandra.bundle.name}" + version="${rhq.cassandra.bundle.version}" + description="A bundle for deploying RHQ Cassandra nodes."> + + <!-- + NOTE: the name attribute of an rhq:input-property does not support using a dash. + There is a convention where dashes are used in property names in rhq properties files + in the trailing part of a property name. If an rhq:input-property has a corresponding + property in cassandra.properties and contains a dash, the dash will be changed to an + underscore in this file. + --> + + <rhq:input-property name="cluster.name" + description="The name of the cluster. This is used to prevent machines in one logical cluster from joining another" + required="true" + defaultValue="rhqdev" + type="string"/> + + <rhq:input-property name="cluster.dir" + description="The directory in which Cassandra nodes will be installed" + required="true" + defaultValue="" + type="string"/> + + <rhq:input-property name="data.dir" + description="The directory where Cassandra should store data files. This should be a path relative to the base deployment directory." + required="true" + defaultValue="data" + type="string"/> + + <rhq:input-property name="commitlog.dir" + description="The directory where Cassandra stores its commit logs. This should be a path relative to the base deployment directory." + required="true" + defaultValue="commit_log" + type="string"/> + + <rhq:input-property name="saved.caches.dir" + description="The directory where Cassandra stores saved caches. This should be a path relative to the base deployment directory." + required="true" + defaultValue="saved_caches" + type="string"/> + + <rhq:input-property name="log.dir" + description="The directory where Cassandra stores log files. This should be a path relative to the base deployment directory." + required="false" + defaultValue="logs" + type="string"/> + + <rhq:input-property name="logging.level" + description="The log4j logging level to use." + required="false" + defaultValue="DEBUG" + type="string"/> + + <rhq:input-property name="hostname" + description="The host name of the node. This normally does not need to be set as Cassandra will resolve the host name/IP address. It needs to be set though for a local, development cluster running on a single machine." + required="true" + defaultValue="127.0.0.1" + type="string"/> + + <rhq:input-property name="seeds" + description="A comma-delimited list of IP addresses/host names that are deemed contact points. Cassandra nodes use this list of hosts to find each other and learn the topology of the ring. If you are running a local development cluster, be sure to have aliases set up for localhost." + required="false" + defaultValue="127.0.0.1" + type="string"/> + + <rhq:input-property name="rhq.cassandra.num_tokens" + description="Defines the number of tokens randomly assigned to a 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." + required="false" + defaultValue="256" + type="string"/> + + <rhq:input-property name="initial.token" + description="Each Cassandra node is assigned a unique token that determines what keys it is the first replica for. If you sort all nodes' token, the range of keys each is responsible for is (PreviousToken, MyToken], that is, from the previous token (exclusive) to the node's token (inclusive). The machine with the lowest Token gets both all keys less than that token, and all keys greater than the largest token; this is called a wrapping range." + required="false" + defaultValue="" + type="string"/> + + <rhq:input-property name="jmx.port" + description="The port over which Cassandra listens for JMX connections. Each node should be assigned a unique port." + required="false" + defaultValue="7200" + type="string"/> + + <rhq:input-property name="listen.address" + description="Address used for inter-node communication. Defaults to value of hostname property." + required="true" + defaultValue="" + type="string"/> + + <rhq:input-property name="rpc.address" + description="Address used for Thrift RPC client communication. Defaults to value of hostname property." + required="true" + defaultValue="" + type="string"/> + + <rhq:input-property name="cassandra.ring.delay.property" + required="false" + defaultValue="" + type="string"/> + + <rhq:input-property name="cassandra.ring.delay" + description="When a node initializes it contacts a seed and then sleeps for RING_DELAY (milliseconds) to learn about other nodes in the cluster. Cassandra uses a default value of 30 seconds." + required="false" + defaultValue="" + type="string"/> + + <rhq:input-property name="rhq.casandra.native_transport_max_threads" + description="The maximum number of threads handling native CQL requests." + required="false" + defaultValue="64" + type="integer"/> + + <rhq:input-property name="rhq.cassandra.native_transport_port" + description="The port for the CQL native transport to listen for clients on." + required="false" + defaultValue="9042" + type="integer"/> + + <rhq:input-property name="rhq.cassandra.authenticator" + description="A class that performs authentication. The value should be a fully qualified class name and implement IAuthenticator." + required="false" + defaultValue="org.rhq.cassandra.auth.SimpleAuthenticator" + type="string"/> + + <rhq:input-property name="rhq.cassandra.authorizer" + description="A class that performs authorization. Used to limit/provide permissions. The value should be a fully qualified class name and implement IAuthorizer." + required="false" + defaultValue="org.rhq.cassandra.auth.SimpleAuthorizer" + type="string"/> + + <rhq:input-property name="rhq.cassandra.password.properties.file" + description="The location of the password properties file used by SimpleAuthenticator. If a relative path is specified, its location is resolved relative to Cassandra's bin directory." + required="false" + defaultValue="./../conf/passwd.properties" + type="file"/> + + <rhq:input-property name="rhq.cassandra.access.properties.file" + description="The location of the authorization properties file used by SimpleAuthority. If a relative path is specified, its location is resolved relative to Cassandra's bin directory." + required="false" + defaultValue="./../conf/access.properties" + type="file"/> + + <rhq:input-property name="rhq.cassandra.username" + description="The username with which to authenticate requests to Cassandra." + required="true" + type="string"/> + + <rhq:input-property name="rhq.cassandra.password" + description="The password with which to authenticate requests to Cassandra." + required="true" + type="string"/> + + <rhq:deployment-unit name="cassandra" preinstallTarget="pre-install" postinstallTarget="post-install"> +<!-- + <rhq:file name="dbsetup.script" destinationFile="scripts/dbsetup.script" replace="true"/> +--> + <rhq:archive name="cassandra.zip"> + rhq:replace + <rhq:fileset dir="conf"> + <include name="cassandra.yaml"/> + </rhq:fileset> + <rhq:fileset dir="conf"> + <include name="cassandra-env.sh"/> + </rhq:fileset> + <rhq:fileset dir="conf"> + <include name="log4j-server.properties"/> + </rhq:fileset> + <rhq:fileset dir="conf"> + <include name="passwd.properties"/> + </rhq:fileset> +<!-- + <rhq:fileset dir="scripts"> + <include name="dbsetup.script"/> + </rhq:fileset> +--> + </rhq:replace> + </rhq:archive> + </rhq:deployment-unit> + </rhq:bundle> + + <target name="main"/> + + <target name="pre-install"> + <mkdir dir="${cluster.dir}"/> + </target> + + <target name="post-install"> + <property name="bin.dir" value="${rhq.deploy.dir}/bin"/> + + <mkdir dir="${rhq.deploy.dir}/${data.dir}"/> + <mkdir dir="${rhq.deploy.dir}/${commitlog.dir}"/> + <mkdir dir="${rhq.deploy.dir}/${saved.caches.dir}"/> + <mkdir dir="${rhq.deploy.dir}/${log.dir}"/> + + <chmod file="${bin.dir}/cassandra" perm="+x"/> + <chmod file="${bin.dir}/cqlsh" perm="+x"/> + <chmod file="${bin.dir}/cassandra-cli" perm="+x"/> + <chmod file="${bin.dir}/nodetool" perm="+x"/> + +<!-- + <exec dir="${bin.dir}" executable="cassandra" spawn="true" resolveexecutable="true"/> + + <script manager="javax" language="javascript"><![CDATA[ + if (project.getProperty("install.schema") == "true") { + java.lang.Thread.sleep(1000 * 10); + + exec = project.createTask("exec"); + args = exec.createArg(); + args.setLine("-f ../scripts/dbsetup.script"); + exec.setDir(java.io.File(project.getProperty("bin.dir"))); + exec.setExecutable("cassandra-cli"); + exec.setResolveExecutable(true); + exec.setError(java.io.File("/home/jsanda/cassandra.log")); + exec.setOutput(java.io.File("/home/jsanda/cassandra.log")); + + exec.execute(); + } + ]]></script> +--> + </target> + +</project> diff --git a/modules/common/cassandra-ccm/cassandra-ccm-testng/pom.xml b/modules/common/cassandra-ccm/cassandra-ccm-testng/pom.xml new file mode 100644 index 0000000..4cca8ed --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-testng/pom.xml @@ -0,0 +1,40 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd%22%3E + + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.rhq</groupId> + <artifactId>rhq-cassandra-ccm</artifactId> + <version>4.6.0-SNAPSHOT</version> + </parent> + + <artifactId>rhq-cassandra-ccm-testng</artifactId> + <name>RHQ Cassandra CCM TestNG</name> + + <dependencies> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>rhq-cassandra-ccm-core</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>rhq-cassandra-schema</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>org.testng</groupId> + <artifactId>testng</artifactId> + <version>${testng.version}</version> + </dependency> + + <dependency> + <groupId>net.java.dev.jna</groupId> + <artifactId>jna</artifactId> + <version>3.2.7</version> + </dependency> + </dependencies> +</project> diff --git a/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CCMTestNGListener.java b/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CCMTestNGListener.java new file mode 100644 index 0000000..0d6d26f --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CCMTestNGListener.java @@ -0,0 +1,153 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.StringWriter; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.IInvokedMethod; +import org.testng.IInvokedMethodListener; +import org.testng.ITestResult; + +import org.rhq.cassandra.schema.SchemaManager; +import org.rhq.core.util.stream.StreamUtil; + +/** + * @author John Sanda + */ +public class CCMTestNGListener implements IInvokedMethodListener { + + private final Log log = LogFactory.getLog(CCMTestNGListener.class); + + private CassandraClusterManager ccm; + + @Override + public void beforeInvocation(IInvokedMethod invokedMethod, ITestResult testResult) { + Method method = invokedMethod.getTestMethod().getConstructorOrMethod().getMethod(); + if (method.isAnnotationPresent(DeployCluster.class)) { + try { + deployCluster(method.getAnnotation(DeployCluster.class)); + } catch (CassandraException e) { + log.warn("Failed to deploy cluster", e); + } + } + } + + @Override + public void afterInvocation(IInvokedMethod invokedMethod, ITestResult testResult) { + Method method = invokedMethod.getTestMethod().getConstructorOrMethod().getMethod(); + if (method.isAnnotationPresent(ShutdownCluster.class)) { + try { + Boolean skipShutdown = Boolean.valueOf( + System.getProperty("rhq.cassandra.cluster.skip-shutdown", "false")); + if (!skipShutdown) { + shutdownCluster(); + } + } catch (Exception e) { + log.warn("An error occurred while shutting down the cluster", e); + } + } + } + + private void deployCluster(DeployCluster annotation) throws CassandraException { + File basedir = new File("target"); + File clusterDir = new File(basedir, "cassandra"); + + int numNodes = annotation.numNodes(); + DeploymentOptions deploymentOptions = new DeploymentOptions(); + deploymentOptions.setClusterDir(clusterDir.getAbsolutePath()); + deploymentOptions.setNumNodes(numNodes); + deploymentOptions.setUsername(annotation.username()); + deploymentOptions.setPassword(annotation.password()); + + ccm = new CassandraClusterManager(deploymentOptions); + List<File> nodeDirs = ccm.installCluster(); + ccm.startCluster(nodeDirs); + + ClusterInitService clusterInitService = new ClusterInitService(); + List<CassandraNode> cassandraHosts = getCassandraHosts(ccm.getHostNames()); + + if (annotation.waitForClusterToStart()) { + clusterInitService.waitForClusterToStart(cassandraHosts); + } + + if (annotation.waitForSchemaAgreement()) { + // TODO do not hard code cluster name + // I am ok with hard coding the cluster name for now as it is only required + // by the Hector API, and it is to be determined whether or not we will continue + // using Hector. If we wind up directly using the underlying Thrift API, there + // is no cluster name argument. + // + // jsanda + clusterInitService.waitForSchemaAgreement("rhq", cassandraHosts); + } + + SchemaManager schemaManager = new SchemaManager(annotation.username(), annotation.password(), + ccm.getHostNames().toArray(new String[] {})); + if (!schemaManager.schemaExists()) { + schemaManager.createSchema(); + } + schemaManager.updateSchema(); + schemaManager.shutdown(); + } + + private void shutdownCluster() throws Exception { + File basedir = new File("target"); + File clusterDir = new File(basedir, "cassandra"); + killNode(new File(clusterDir, "node0")); + killNode(new File(clusterDir, "node1")); + } + + private void killNode(File nodeDir) throws Exception { + long pid = getPid(nodeDir); + CLibrary.kill((int) pid, 9); + } + + private long getPid(File nodeDir) throws IOException { + File binDir = new File(nodeDir, "bin"); + StringWriter writer = new StringWriter(); + StreamUtil.copy(new FileReader(new File(binDir, "cassandra.pid")), writer); + + return Long.parseLong(writer.getBuffer().toString()); + } + + private List<CassandraNode> getCassandraHosts(List<String> hostNames) { + List<CassandraNode> cassandraHosts = new ArrayList<CassandraNode>(); + + for (String hostName : hostNames) { + cassandraHosts.add(new CassandraNode(hostName, 9160)); + } + return cassandraHosts; + } + +} diff --git a/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CLibrary.java b/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CLibrary.java new file mode 100644 index 0000000..9157b42 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CLibrary.java @@ -0,0 +1,47 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra; + +import com.sun.jna.Native; + +/** + * @author John Sanda + */ +public class CLibrary { + + static { + //try { + Native.register("c"); + //} catch () + } + + public static native int kill(int pid, int signal); + +// public static int killProcess(int pid, int signal) { +// +// } + +} diff --git a/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/DeployCluster.java b/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/DeployCluster.java new file mode 100644 index 0000000..78f3608 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/DeployCluster.java @@ -0,0 +1,70 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * boo! + * + * @author John Sanda + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD }) +public @interface DeployCluster { + + /** + * @return The number of nodes in the cluster. Defaults to two. + */ + int numNodes() default 2; + + /** + * @return A flag that specifies whether or not to wait for all cluster nodes to start. + * The approach that is currently used to determine whether or a node is started is to + * open a Thrift connection to that node. This attribute defaults to true. + */ + boolean waitForClusterToStart() default true; + + /** + * @return A flag that specifies whether or not to wait for schema agreement across the + * cluster. Defaults to true. + */ + boolean waitForSchemaAgreement() default true; + + /** + * @return The username with which to authenticate against Cassandra + */ + String username() default "rhqadmin"; + + /** + * @return The password with which to authenticate against Cassandra + */ + String password() default "rhqadmin"; + +} diff --git a/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/ShutdownCluster.java b/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/ShutdownCluster.java new file mode 100644 index 0000000..b2e32f4 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/ShutdownCluster.java @@ -0,0 +1,39 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author John Sanda + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD }) +public @interface ShutdownCluster { +} diff --git a/modules/common/cassandra-ccm/cassandra-ccm-testng/src/test/java/org/rhq/cassandra/common/BootstrapDeployerTest.java b/modules/common/cassandra-ccm/cassandra-ccm-testng/src/test/java/org/rhq/cassandra/common/BootstrapDeployerTest.java new file mode 100644 index 0000000..8cef4e7 --- /dev/null +++ b/modules/common/cassandra-ccm/cassandra-ccm-testng/src/test/java/org/rhq/cassandra/common/BootstrapDeployerTest.java @@ -0,0 +1,86 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra.common; + +import org.testng.annotations.Listeners; +import org.testng.annotations.Test; + +import org.rhq.cassandra.CCMTestNGListener; +import org.rhq.cassandra.CassandraException; +import org.rhq.cassandra.ShutdownCluster; + +/** + * @author John Sanda + */ +@Listeners({CCMTestNGListener.class}) +public class BootstrapDeployerTest { + + @Test + @ShutdownCluster + public void installSchema() throws CassandraException { +// File basedir = new File("target"); +// File clusterDir = new File(basedir, "cassandra"); +// int numNodes = 2; +// +// DeploymentOptions deploymentOptions = new DeploymentOptions(); +// try { +// deploymentOptions.setClusterDir(clusterDir.getAbsolutePath()); +// deploymentOptions.setRingDelay(1000L); +// deploymentOptions.load(); +// } catch (IOException e) { +// throw new CassandraException(e); +// } +// +// BootstrapDeployer deployer = new BootstrapDeployer(); +// deployer.setDeploymentOptions(deploymentOptions); +// deployer.deploy(); +// +// // first verify that the cluster has been installed +// File installedMarker = new File(clusterDir, ".installed"); +// assertTrue(installedMarker.exists(), "Cluster is not installed. The installer file marker " + +// installedMarker.getPath() + " does not exist."); +// +// List<CassandraHost> cassandraHosts = asList(new CassandraHost("127.0.0.1", 9160), +// new CassandraHost("127.0.0.2", 9160)); +// +// ClusterInitService clusterInitService = new ClusterInitService(); +// clusterInitService.waitForClusterToStart(cassandraHosts); +// clusterInitService.waitForSchemaAgreement("rhq", cassandraHosts); +// +// // now verify that the schema versions are the same on both nodes +// Cluster cluster = HFactory.getOrCreateCluster("test", "127.0.0.1"); +// Map<String, List<String>> schemaVersions = cluster.describeSchemaVersions(); +// +// // first make sure that we only have a single schema version +// assertEquals(schemaVersions.size(), 1, "There should only be one schema version."); +// +// // now make sure that each is on that version +// List<String> hosts = schemaVersions.values().iterator().next(); +// assertEquals(hosts.size(), numNodes, "The schema has not propagated to all hosts. The latest schema version " + +// "maps to " + hosts.size() + " should map to " + numNodes + " hosts"); + } + +} diff --git a/modules/common/cassandra-ccm/pom.xml b/modules/common/cassandra-ccm/pom.xml new file mode 100644 index 0000000..865b122 --- /dev/null +++ b/modules/common/cassandra-ccm/pom.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd%22%3E + <parent> + <artifactId>rhq-common-parent</artifactId> + <groupId>org.rhq</groupId> + <version>4.6.0-SNAPSHOT</version> + <relativePath>../pom.xml</relativePath> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>rhq-cassandra-ccm</artifactId> + <name>RHQ Cassandra CCM Parent</name> + <packaging>pom</packaging> + + <modules> + <module>cassandra-ccm-core</module> + <module>cassandra-ccm-cli</module> + <module>cassandra-ccm-testng</module> + </modules> +</project> diff --git a/modules/common/cassandra-common-itests/pom.xml b/modules/common/cassandra-common-itests/pom.xml deleted file mode 100644 index 85e500e..0000000 --- a/modules/common/cassandra-common-itests/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ -<!-- - ~ /* - ~ * RHQ Management Platform - ~ * Copyright (C) 2005-2012 Red Hat, Inc. - ~ * All rights reserved. - ~ * - ~ * This program is free software; you can redistribute it and/or modify - ~ * it under the terms of the GNU General Public License, version 2, as - ~ * published by the Free Software Foundation, and/or the GNU Lesser - ~ * General Public License, version 2.1, also as published by the Free - ~ * Software Foundation. - ~ * - ~ * This program is distributed in the hope that it will be useful, - ~ * but WITHOUT ANY WARRANTY; without even the implied warranty of - ~ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - ~ * GNU General Public License and the GNU Lesser General Public License - ~ * for more details. - ~ * - ~ * You should have received a copy of the GNU General Public License - ~ * and the GNU Lesser General Public License along with this program; - ~ * if not, write to the Free Software Foundation, Inc., - ~ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - ~ */ - --> - -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd%22%3E - - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.rhq</groupId> - <artifactId>rhq-common-parent</artifactId> - <version>4.6.0-SNAPSHOT</version> - </parent> - - <artifactId>rhq-cassandra-common-itests</artifactId> - <name>RHQ Cassandra Common Integration Tests</name> - - <dependencies> - <dependency> - <groupId>${project.groupId}</groupId> - <artifactId>rhq-cassandra-common</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>${project.groupId}</groupId> - <artifactId>rhq-cassandra-schema</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>org.testng</groupId> - <artifactId>testng</artifactId> - <version>${testng.version}</version> - </dependency> - - <dependency> - <groupId>net.java.dev.jna</groupId> - <artifactId>jna</artifactId> - <version>3.2.7</version> - </dependency> - </dependencies> -</project> diff --git a/modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/CCMTestNGListener.java b/modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/CCMTestNGListener.java deleted file mode 100644 index 0d6d26f..0000000 --- a/modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/CCMTestNGListener.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * - * * RHQ Management Platform - * * Copyright (C) 2005-2012 Red Hat, Inc. - * * All rights reserved. - * * - * * This program is free software; you can redistribute it and/or modify - * * it under the terms of the GNU General Public License, version 2, as - * * published by the Free Software Foundation, and/or the GNU Lesser - * * General Public License, version 2.1, also as published by the Free - * * Software Foundation. - * * - * * This program is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * * GNU General Public License and the GNU Lesser General Public License - * * for more details. - * * - * * You should have received a copy of the GNU General Public License - * * and the GNU Lesser General Public License along with this program; - * * if not, write to the Free Software Foundation, Inc., - * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package org.rhq.cassandra; - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.IInvokedMethod; -import org.testng.IInvokedMethodListener; -import org.testng.ITestResult; - -import org.rhq.cassandra.schema.SchemaManager; -import org.rhq.core.util.stream.StreamUtil; - -/** - * @author John Sanda - */ -public class CCMTestNGListener implements IInvokedMethodListener { - - private final Log log = LogFactory.getLog(CCMTestNGListener.class); - - private CassandraClusterManager ccm; - - @Override - public void beforeInvocation(IInvokedMethod invokedMethod, ITestResult testResult) { - Method method = invokedMethod.getTestMethod().getConstructorOrMethod().getMethod(); - if (method.isAnnotationPresent(DeployCluster.class)) { - try { - deployCluster(method.getAnnotation(DeployCluster.class)); - } catch (CassandraException e) { - log.warn("Failed to deploy cluster", e); - } - } - } - - @Override - public void afterInvocation(IInvokedMethod invokedMethod, ITestResult testResult) { - Method method = invokedMethod.getTestMethod().getConstructorOrMethod().getMethod(); - if (method.isAnnotationPresent(ShutdownCluster.class)) { - try { - Boolean skipShutdown = Boolean.valueOf( - System.getProperty("rhq.cassandra.cluster.skip-shutdown", "false")); - if (!skipShutdown) { - shutdownCluster(); - } - } catch (Exception e) { - log.warn("An error occurred while shutting down the cluster", e); - } - } - } - - private void deployCluster(DeployCluster annotation) throws CassandraException { - File basedir = new File("target"); - File clusterDir = new File(basedir, "cassandra"); - - int numNodes = annotation.numNodes(); - DeploymentOptions deploymentOptions = new DeploymentOptions(); - deploymentOptions.setClusterDir(clusterDir.getAbsolutePath()); - deploymentOptions.setNumNodes(numNodes); - deploymentOptions.setUsername(annotation.username()); - deploymentOptions.setPassword(annotation.password()); - - ccm = new CassandraClusterManager(deploymentOptions); - List<File> nodeDirs = ccm.installCluster(); - ccm.startCluster(nodeDirs); - - ClusterInitService clusterInitService = new ClusterInitService(); - List<CassandraNode> cassandraHosts = getCassandraHosts(ccm.getHostNames()); - - if (annotation.waitForClusterToStart()) { - clusterInitService.waitForClusterToStart(cassandraHosts); - } - - if (annotation.waitForSchemaAgreement()) { - // TODO do not hard code cluster name - // I am ok with hard coding the cluster name for now as it is only required - // by the Hector API, and it is to be determined whether or not we will continue - // using Hector. If we wind up directly using the underlying Thrift API, there - // is no cluster name argument. - // - // jsanda - clusterInitService.waitForSchemaAgreement("rhq", cassandraHosts); - } - - SchemaManager schemaManager = new SchemaManager(annotation.username(), annotation.password(), - ccm.getHostNames().toArray(new String[] {})); - if (!schemaManager.schemaExists()) { - schemaManager.createSchema(); - } - schemaManager.updateSchema(); - schemaManager.shutdown(); - } - - private void shutdownCluster() throws Exception { - File basedir = new File("target"); - File clusterDir = new File(basedir, "cassandra"); - killNode(new File(clusterDir, "node0")); - killNode(new File(clusterDir, "node1")); - } - - private void killNode(File nodeDir) throws Exception { - long pid = getPid(nodeDir); - CLibrary.kill((int) pid, 9); - } - - private long getPid(File nodeDir) throws IOException { - File binDir = new File(nodeDir, "bin"); - StringWriter writer = new StringWriter(); - StreamUtil.copy(new FileReader(new File(binDir, "cassandra.pid")), writer); - - return Long.parseLong(writer.getBuffer().toString()); - } - - private List<CassandraNode> getCassandraHosts(List<String> hostNames) { - List<CassandraNode> cassandraHosts = new ArrayList<CassandraNode>(); - - for (String hostName : hostNames) { - cassandraHosts.add(new CassandraNode(hostName, 9160)); - } - return cassandraHosts; - } - -} diff --git a/modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/CLibrary.java b/modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/CLibrary.java deleted file mode 100644 index 9157b42..0000000 --- a/modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/CLibrary.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * * RHQ Management Platform - * * Copyright (C) 2005-2012 Red Hat, Inc. - * * All rights reserved. - * * - * * This program is free software; you can redistribute it and/or modify - * * it under the terms of the GNU General Public License, version 2, as - * * published by the Free Software Foundation, and/or the GNU Lesser - * * General Public License, version 2.1, also as published by the Free - * * Software Foundation. - * * - * * This program is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * * GNU General Public License and the GNU Lesser General Public License - * * for more details. - * * - * * You should have received a copy of the GNU General Public License - * * and the GNU Lesser General Public License along with this program; - * * if not, write to the Free Software Foundation, Inc., - * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package org.rhq.cassandra; - -import com.sun.jna.Native; - -/** - * @author John Sanda - */ -public class CLibrary { - - static { - //try { - Native.register("c"); - //} catch () - } - - public static native int kill(int pid, int signal); - -// public static int killProcess(int pid, int signal) { -// -// } - -} diff --git a/modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/DeployCluster.java b/modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/DeployCluster.java deleted file mode 100644 index 78f3608..0000000 --- a/modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/DeployCluster.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * - * * RHQ Management Platform - * * Copyright (C) 2005-2012 Red Hat, Inc. - * * All rights reserved. - * * - * * This program is free software; you can redistribute it and/or modify - * * it under the terms of the GNU General Public License, version 2, as - * * published by the Free Software Foundation, and/or the GNU Lesser - * * General Public License, version 2.1, also as published by the Free - * * Software Foundation. - * * - * * This program is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * * GNU General Public License and the GNU Lesser General Public License - * * for more details. - * * - * * You should have received a copy of the GNU General Public License - * * and the GNU Lesser General Public License along with this program; - * * if not, write to the Free Software Foundation, Inc., - * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package org.rhq.cassandra; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * boo! - * - * @author John Sanda - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD }) -public @interface DeployCluster { - - /** - * @return The number of nodes in the cluster. Defaults to two. - */ - int numNodes() default 2; - - /** - * @return A flag that specifies whether or not to wait for all cluster nodes to start. - * The approach that is currently used to determine whether or a node is started is to - * open a Thrift connection to that node. This attribute defaults to true. - */ - boolean waitForClusterToStart() default true; - - /** - * @return A flag that specifies whether or not to wait for schema agreement across the - * cluster. Defaults to true. - */ - boolean waitForSchemaAgreement() default true; - - /** - * @return The username with which to authenticate against Cassandra - */ - String username() default "rhqadmin"; - - /** - * @return The password with which to authenticate against Cassandra - */ - String password() default "rhqadmin"; - -} diff --git a/modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/ShutdownCluster.java b/modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/ShutdownCluster.java deleted file mode 100644 index b2e32f4..0000000 --- a/modules/common/cassandra-common-itests/src/main/java/org/rhq/cassandra/ShutdownCluster.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * - * * RHQ Management Platform - * * Copyright (C) 2005-2012 Red Hat, Inc. - * * All rights reserved. - * * - * * This program is free software; you can redistribute it and/or modify - * * it under the terms of the GNU General Public License, version 2, as - * * published by the Free Software Foundation, and/or the GNU Lesser - * * General Public License, version 2.1, also as published by the Free - * * Software Foundation. - * * - * * This program is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * * GNU General Public License and the GNU Lesser General Public License - * * for more details. - * * - * * You should have received a copy of the GNU General Public License - * * and the GNU Lesser General Public License along with this program; - * * if not, write to the Free Software Foundation, Inc., - * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package org.rhq.cassandra; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * @author John Sanda - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD }) -public @interface ShutdownCluster { -} diff --git a/modules/common/cassandra-common-itests/src/test/java/org/rhq/cassandra/common/BootstrapDeployerTest.java b/modules/common/cassandra-common-itests/src/test/java/org/rhq/cassandra/common/BootstrapDeployerTest.java deleted file mode 100644 index 8cef4e7..0000000 --- a/modules/common/cassandra-common-itests/src/test/java/org/rhq/cassandra/common/BootstrapDeployerTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * - * * RHQ Management Platform - * * Copyright (C) 2005-2012 Red Hat, Inc. - * * All rights reserved. - * * - * * This program is free software; you can redistribute it and/or modify - * * it under the terms of the GNU General Public License, version 2, as - * * published by the Free Software Foundation, and/or the GNU Lesser - * * General Public License, version 2.1, also as published by the Free - * * Software Foundation. - * * - * * This program is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * * GNU General Public License and the GNU Lesser General Public License - * * for more details. - * * - * * You should have received a copy of the GNU General Public License - * * and the GNU Lesser General Public License along with this program; - * * if not, write to the Free Software Foundation, Inc., - * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package org.rhq.cassandra.common; - -import org.testng.annotations.Listeners; -import org.testng.annotations.Test; - -import org.rhq.cassandra.CCMTestNGListener; -import org.rhq.cassandra.CassandraException; -import org.rhq.cassandra.ShutdownCluster; - -/** - * @author John Sanda - */ -@Listeners({CCMTestNGListener.class}) -public class BootstrapDeployerTest { - - @Test - @ShutdownCluster - public void installSchema() throws CassandraException { -// File basedir = new File("target"); -// File clusterDir = new File(basedir, "cassandra"); -// int numNodes = 2; -// -// DeploymentOptions deploymentOptions = new DeploymentOptions(); -// try { -// deploymentOptions.setClusterDir(clusterDir.getAbsolutePath()); -// deploymentOptions.setRingDelay(1000L); -// deploymentOptions.load(); -// } catch (IOException e) { -// throw new CassandraException(e); -// } -// -// BootstrapDeployer deployer = new BootstrapDeployer(); -// deployer.setDeploymentOptions(deploymentOptions); -// deployer.deploy(); -// -// // first verify that the cluster has been installed -// File installedMarker = new File(clusterDir, ".installed"); -// assertTrue(installedMarker.exists(), "Cluster is not installed. The installer file marker " + -// installedMarker.getPath() + " does not exist."); -// -// List<CassandraHost> cassandraHosts = asList(new CassandraHost("127.0.0.1", 9160), -// new CassandraHost("127.0.0.2", 9160)); -// -// ClusterInitService clusterInitService = new ClusterInitService(); -// clusterInitService.waitForClusterToStart(cassandraHosts); -// clusterInitService.waitForSchemaAgreement("rhq", cassandraHosts); -// -// // now verify that the schema versions are the same on both nodes -// Cluster cluster = HFactory.getOrCreateCluster("test", "127.0.0.1"); -// Map<String, List<String>> schemaVersions = cluster.describeSchemaVersions(); -// -// // first make sure that we only have a single schema version -// assertEquals(schemaVersions.size(), 1, "There should only be one schema version."); -// -// // now make sure that each is on that version -// List<String> hosts = schemaVersions.values().iterator().next(); -// assertEquals(hosts.size(), numNodes, "The schema has not propagated to all hosts. The latest schema version " + -// "maps to " + hosts.size() + " should map to " + numNodes + " hosts"); - } - -} diff --git a/modules/common/cassandra-common/pom.xml b/modules/common/cassandra-common/pom.xml deleted file mode 100644 index 50e72d1..0000000 --- a/modules/common/cassandra-common/pom.xml +++ /dev/null @@ -1,372 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd%22%3E - - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.rhq</groupId> - <artifactId>rhq-common-parent</artifactId> - <version>4.6.0-SNAPSHOT</version> - </parent> - - <artifactId>rhq-cassandra-common</artifactId> - <name>RHQ Cassandra Common</name> - - <properties> - <cassandra.version>1.2.0-rc1</cassandra.version> - <local.repo>${settings.localRepository}</local.repo> - <moduleName>org.rhq.${project.artifactId}</moduleName> - <moduleDir>org/rhq/${project.artifactId}</moduleDir> - </properties> - - <dependencies> - <dependency> - <groupId>${project.groupId}</groupId> - <artifactId>rhq-ant-bundle-common</artifactId> - <version>${project.version}</version> - <exclusions> - <exclusion> - <groupId>org.liquibase</groupId> - <artifactId>liquibase-core</artifactId> - </exclusion> - </exclusions> - </dependency> - - <dependency> - <groupId>${project.groupId}</groupId> - <artifactId>rhq-core-plugin-api</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>org.apache.cassandra</groupId> - <artifactId>cassandra-thrift</artifactId> - <version>${cassandra.version}</version> - </dependency> - - <dependency> - <groupId>commons-cli</groupId> - <artifactId>commons-cli</artifactId> - <version>1.2</version> - <scope>provided</scope> - </dependency> - </dependencies> - - <build> - <resources> - <resource> - <directory>src/main/resources</directory> - <filtering>true</filtering> - </resource> - <resource> - <directory>src/main/cassandra/cql</directory> - </resource> - </resources> - - <filters> - <filter>src/main/resources/cassandra.properties</filter> - </filters> - - <plugins> - <plugin> - <artifactId>maven-antrun-plugin</artifactId> - <executions> - <execution> - <!-- - This execution is a place holder or stub to do some pre-processing before - packaging up the bundle. See the snappy-mac-workaround profile below for more - details. - --> - <id>setup-pkg</id> - </execution> - <execution> - <id>get-cassandra</id> - <phase>generate-resources</phase> - <goals> - <goal>run</goal> - </goals> - <configuration> - <target> - <property name="cassandra.download.dir" - value="${project.build.directory}/cassandra-download"/> - <mkdir dir="${cassandra.download.dir}"/> - <mkdir dir="${settings.localRepository}/org/apache/cassandra/apache-cassandra/${cassandra.version}"/> - <get src="http://repo1.maven.org/maven2/org/apache/cassandra/apache-cassandra/$%7Bcass..." - dest="${settings.localRepository}/org/apache/cassandra/apache-cassandra/${cassandra.version}/apache-cassandra-${cassandra.version}-bin.tar.gz" - skipexisting="true" - verbose="true"/> - <gunzip src="${settings.localRepository}/org/apache/cassandra/apache-cassandra/${cassandra.version}/apache-cassandra-${cassandra.version}-bin.tar.gz" - dest="${cassandra.download.dir}"/> - <untar src="${cassandra.download.dir}/apache-cassandra-${cassandra.version}-bin.tar" - dest="${cassandra.download.dir}"/> - <move file="${cassandra.download.dir}/apache-cassandra-${cassandra.version}" - tofile="${project.build.outputDirectory}/cassandra-${cassandra.version}"/> - <delete dir="${cassandra.download.dir}"/> - </target> - </configuration> - </execution> - <execution> - <id>create-cassandra-pkg</id> - <phase>prepare-package</phase> - <goals> - <goal>run</goal> - </goals> - <configuration> - <target> - <property name="cassandra.dir" - value="${project.build.outputDirectory}/cassandra-${cassandra.version}"/> - <property name="cassandra.distro.filename" value="cassandra.zip"/> - <property name="cassandra.distro.zip" - value="${project.build.outputDirectory}/${cassandra.distro.filename}"/> - <copy file="${settings.localRepository}/org/rhq/rhq-cassandra-auth/${project.version}/rhq-cassandra-auth-${project.version}.jar" - todir="${cassandra.dir}/lib"/> - <move file="${project.build.outputDirectory}/cassandra/conf" todir="${cassandra.dir}"/> - <move file="${project.build.outputDirectory}/cassandra/lib" todir="${cassandra.dir}"/> - <!--<move file="${project.build.outputDirectory}/passwd.properties" todir="${cassandra.dir}/conf"/>--> - <!--<move file="${project.build.outputDirectory}/access.properties" todir="${cassandra.dir}/conf"/>--> - <zip basedir="${cassandra.dir}" destfile="${cassandra.distro.zip}"/> - <delete dir="${cassandra.dir}"/> - <zip basedir="${project.build.outputDirectory}" - destfile="${project.build.outputDirectory}/cassandra-bundle.zip" - includes="${cassandra.distro.filename},deploy.xml"/> - <delete file="${project.build.outputDirectory}/deploy.xml"/> - <delete file="${project.build.outputDirectory}/cassandra}"/> - <delete file="${cassandra.distro.zip}"/> - </target> - </configuration> - </execution> - </executions> - </plugin> - - <plugin> - <artifactId>maven-dependency-plugin</artifactId> - <executions> - <execution> - <id>copy-deps</id> - <phase>prepare-package</phase> - <goals> - <goal>copy</goal> - </goals> - <configuration> - <outputDirectory>${project.build.directory}/dependencies</outputDirectory> - <artifactItems> - <artifactItem> - <groupId>${project.groupId}</groupId> - <artifactId>rhq-ant-bundle-common</artifactId> - </artifactItem> - <artifactItem> - <groupId>${project.groupId}</groupId> - <artifactId>rhq-core-util</artifactId> - <version>${project.version}</version> - </artifactItem> - <artifactItem> - <groupId>jdom</groupId> - <artifactId>jdom</artifactId> - <version>1.0</version> - </artifactItem> - <artifactItem> - <groupId>i18nlog</groupId> - <artifactId>i18nlog</artifactId> - <version>1.0.10</version> - </artifactItem> - <artifactItem> - <groupId>${project.groupId}</groupId> - <artifactId>rhq-core-native-system</artifactId> - <version>${project.version}</version> - </artifactItem> - <artifactItem> - <groupId>org.apache.ant</groupId> - <artifactId>ant</artifactId> - <version>1.8.0</version> - </artifactItem> - <artifactItem> - <groupId>org.apache.ant</groupId> - <artifactId>ant-launcher</artifactId> - <version>1.8.0</version> - </artifactItem> - <artifactItem> - <groupId>org.apache.ant</groupId> - <artifactId>ant-nodeps</artifactId> - <version>1.8.0</version> - </artifactItem> - <artifactItem> - <groupId>ant-contrib</groupId> - <artifactId>ant-contrib</artifactId> - <version>1.0b3</version> - </artifactItem> - <artifactItem> - <groupId>${project.groupId}</groupId> - <artifactId>rhq-core-plugin-api</artifactId> - </artifactItem> - <artifactItem> - <groupId>org.apache.cassandra</groupId> - <artifactId>cassandra-thrift</artifactId> - </artifactItem> - <artifactItem> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-api</artifactId> - <version>1.7.2</version> - </artifactItem> - <artifactItem> - <groupId>${project.groupId}</groupId> - <artifactId>rhq-core-domain</artifactId> - <version>${project.version}</version> - </artifactItem> - <artifactItem> - <groupId>commons-lang</groupId> - <artifactId>commons-lang</artifactId> - <version>2.4</version> - </artifactItem> - <artifactItem> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-api</artifactId> - <version>1.7.2</version> - </artifactItem> - <artifactItem> - <groupId>org.apache.thrift</groupId> - <artifactId>libthrift</artifactId> - <version>0.7.0</version> - </artifactItem> - <artifactItem> - <groupId>commons-codec</groupId> - <artifactId>commons-codec</artifactId> - <version>1.3</version> - </artifactItem> - </artifactItems> - </configuration> - </execution> - </executions> - </plugin> - - <plugin> - <artifactId>maven-assembly-plugin</artifactId> - <configuration> - <descriptors> - <descriptor>src/main/scripts/module-assembly.xml</descriptor> - </descriptors> - </configuration> - <executions> - <execution> - <id>module-assembly</id> - <phase>package</phase> - <goals> - <goal>single</goal> - </goals> - </execution> - </executions> - </plugin> - </plugins> - </build> - - <profiles> - <profile> - <id>dev</id> - <properties> - <rhq.rootDir>../../..</rhq.rootDir> - <rhq.containerDir>${rhq.rootDir}/${rhq.defaultDevContainerPath}</rhq.containerDir> - <rhq.deploymentDir>${rhq.containerDir}/${rhq.earLibDir}</rhq.deploymentDir> - </properties> - - <build> - <plugins> - <plugin> - <artifactId>maven-antrun-plugin</artifactId> - <executions> - <execution> - <id>deploy</id> - <phase>package</phase> - <configuration> - <target> - <mkdir dir="${rhq.deploymentDir}"/> - <property name="deployment.file" location="${rhq.deploymentDir}/${project.build.finalName}.jar"/> - <echo>*** Updating ${deployment.file}...</echo> - <jar destfile="${deployment.file}" basedir="${project.build.outputDirectory}"/> - </target> - </configuration> - <goals> - <goal>run</goal> - </goals> - </execution> - - <execution> - <id>undeploy</id> - <phase>clean</phase> - <configuration> - <target> - <property name="deployment.file" location="${rhq.deploymentDir}/${project.build.finalName}.jar"/> - <echo>*** Deleting ${deployment.file}...</echo> - <delete file="${deployment.file}"/> - </target> - </configuration> - <goals> - <goal>run</goal> - </goals> - </execution> - - </executions> - </plugin> - </plugins> - </build> - </profile> - - <!-- - Cassandra uses the snappy-java compression library, and it uses a native library that - is packaged in the snappy-java JAR. Running on Mac OS X with Java 7 will result in, - - NoClassDefFoundError Could not initialize class org.xerial.snappy.Snappy - - due to the file name extension that the Java 7 JVM looks for on Mac OS X. This issue - was logged and fixed under https://github.com/xerial/snappy-java/issues/6. Cassandra - however does not yet bundle a newer version of snappy-java. This profile is activated - when running on Mac OS X and replaces the packaged version of snappy-java with a newer - version so that snappy compression can still be used during development. Note that - this is **not** an issue when running on Java 6. - - - jsanda 10/03/2012 - --> - <profile> - <id>snappy-mac-workaround</id> - <activation> - <os> - <family>Mac</family> - </os> - </activation> - <build> - <plugins> - <plugin> - <artifactId>maven-antrun-plugin</artifactId> - <inherited>false</inherited> - <dependencies> - <dependency> - <groupId>org.xerial.snappy</groupId> - <artifactId>snappy-java</artifactId> - <version>1.0.5-M3</version> - </dependency> - </dependencies> - <executions> - <execution> - <id>setup-pkg-mac</id> - <phase>process-resources</phase> - <goals> - <goal>run</goal> - </goals> - <configuration> - <target> - <property name="cassandra.dir" - value="${project.build.outputDirectory}/cassandra-${cassandra.version}"/> - <property name="cassandra.lib.dir" value="${cassandra.dir}/lib"/> - <property name="snappy.jar.original" value="${cassandra.lib.dir}/snappy-java-1.0.4.1.jar"/> - <property name="snappy.jar.updated" - value="${local.repo}/org/xerial/snappy/snappy-java/1.0.5-M3/snappy-java-1.0.5-M3.jar"/> - <delete file="${snappy.jar.original}"/> - <copy file="${snappy.jar.updated}" todir="${cassandra.lib.dir}"/> - </target> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> - </profile> - </profiles> -</project> diff --git a/modules/common/cassandra-common/src/main/cassandra/cli/dbsetup.script b/modules/common/cassandra-common/src/main/cassandra/cli/dbsetup.script deleted file mode 100644 index 73bc2a7..0000000 --- a/modules/common/cassandra-common/src/main/cassandra/cli/dbsetup.script +++ /dev/null @@ -1,40 +0,0 @@ -create keyspace rhq - with placement_strategy = 'org.apache.cassandra.locator.SimpleStrategy' and - strategy_options = {replication_factor:1}; - -use rhq; - -create column family raw_metrics - with comparator = DateType and - default_validation_class = DoubleType and - key_validation_class = Int32Type; - -create column family one_hour_metric_data - with comparator = 'CompositeType(DateType, Int32Type)' and - default_validation_class = DoubleType and - key_validation_class = Int32Type; - -create column family six_hour_metric_data - with comparator = 'CompositeType(DateType, Int32Type)' and - default_validation_class = DoubleType and - key_validation_class = Int32Type; - -create column family twenty_four_hour_metric_data - with comparator = 'CompositeType(DateType, Int32Type)' and - default_validation_class = DoubleType and - key_validation_class = Int32Type; - -create column family metrics_work_queue - with comparator = 'CompositeType(DateType, Int32Type)' and - default_validation_class = Int32Type and - key_validation_class = UTF8Type; - -create column family resource_traits - with comparator = 'CompositeType(DateType, Int32Type, Int32Type, UTF8Type, UTF8Type)' and - default_validation_class = UTF8Type and - key_validation_class = Int32Type; - -create column family traits - with comparator = DateType and - default_validation_class = UTF8Type and - key_validation_class = Int32Type; diff --git a/modules/common/cassandra-common/src/main/cassandra/cql/create_keyspace.cql b/modules/common/cassandra-common/src/main/cassandra/cql/create_keyspace.cql deleted file mode 100644 index 9df13a0..0000000 --- a/modules/common/cassandra-common/src/main/cassandra/cql/create_keyspace.cql +++ /dev/null @@ -1 +0,0 @@ -CREATE KEYSPACE rhq WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}; diff --git a/modules/common/cassandra-common/src/main/cassandra/cql/dbsetup.cql b/modules/common/cassandra-common/src/main/cassandra/cql/dbsetup.cql deleted file mode 100644 index 189b35b..0000000 --- a/modules/common/cassandra-common/src/main/cassandra/cql/dbsetup.cql +++ /dev/null @@ -1,42 +0,0 @@ -CREATE KEYSPACE rhq WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}; - -USE rhq; - -CREATE TABLE raw_metrics ( - schedule_id int, - time timestamp, - value double, - PRIMARY KEY (schedule_id, time) -); - -CREATE TABLE one_hour_metrics ( - schedule_id int, - time timestamp, - type int, - value double, - PRIMARY KEY (schedule_id, time, type) -); - -CREATE TABLE six_hour_metrics ( - schedule_id int, - time timestamp, - type int, - value double, - PRIMARY KEY (schedule_id, time, type) -); - -CREATE TABLE twenty_four_hour_metrics ( - schedule_id int, - time timestamp, - type int, - value double, - PRIMARY KEY (schedule_id, time, type) -); - -CREATE TABLE metrics_index ( - bucket varchar, - time timestamp, - schedule_id int, - null_col boolean, - PRIMARY KEY (bucket, time, schedule_id) -); diff --git a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/BootstrapDeployer.java b/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/BootstrapDeployer.java deleted file mode 100644 index 73015c7..0000000 --- a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/BootstrapDeployer.java +++ /dev/null @@ -1,323 +0,0 @@ -/* - * - * * RHQ Management Platform - * * Copyright (C) 2005-2012 Red Hat, Inc. - * * All rights reserved. - * * - * * This program is free software; you can redistribute it and/or modify - * * it under the terms of the GNU General Public License, version 2, as - * * published by the Free Software Foundation, and/or the GNU Lesser - * * General Public License, version 2.1, also as published by the Free - * * Software Foundation. - * * - * * This program is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * * GNU General Public License and the GNU Lesser General Public License - * * for more details. - * * - * * You should have received a copy of the GNU General Public License - * * and the GNU Lesser General Public License along with this program; - * * if not, write to the Free Software Foundation, Inc., - * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package org.rhq.cassandra; - -import static java.util.Arrays.asList; -import static org.rhq.core.util.StringUtil.collectionToString; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.thrift.transport.TSocket; -import org.apache.thrift.transport.TTransportException; - -import org.rhq.bundle.ant.AntLauncher; -import org.rhq.core.pluginapi.util.ProcessExecutionUtility; -import org.rhq.core.system.OperatingSystemType; -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.StringUtil; -import org.rhq.core.util.ZipUtil; -import org.rhq.core.util.file.FileUtil; -import org.rhq.core.util.stream.StreamUtil; - -/** - * @author John Sanda - */ -public class BootstrapDeployer { - - private final Log log = LogFactory.getLog(BootstrapDeployer.class); - - private DeploymentOptions deploymentOptions; - - public void setDeploymentOptions(DeploymentOptions deploymentOptions) { - this.deploymentOptions = deploymentOptions; - } - - public String getCassandraHosts() { - StringBuilder hosts = new StringBuilder(); - for (int i = 0; i < deploymentOptions.getNumNodes(); ++i) { - hosts.append(getLocalIPAddress(i + 1)).append(":9160,"); - } - hosts.deleteCharAt(hosts.length() - 1); - return hosts.toString(); - } - - public List<File> deploy() throws CassandraException { - Set<String> ipAddresses = calculateLocalIPAddresses(deploymentOptions.getNumNodes()); - File clusterDir = new File(deploymentOptions.getClusterDir()); - File installedMarker = new File(clusterDir, ".installed"); - - if (isClusterInstalled()) { - return Collections.emptyList(); - } - - FileUtil.purge(clusterDir, false); - - File bundleZipeFile = null; - File bundleDir = null; - List<File> nodeDirs = new LinkedList<File>(); - - try { - deploymentOptions.load(); - bundleZipeFile = unpackBundleZipFile(); - bundleDir = unpackBundle(bundleZipeFile); - - for (int i = 0; i < deploymentOptions.getNumNodes(); ++i) { - Set<String> seeds = getSeeds(ipAddresses, i + 1); - int jmxPort = 7200 + i; - String address = getLocalIPAddress(i + 1); - File nodeBasedir = new File(clusterDir, "node" + i); - nodeDirs.add(nodeBasedir); - - Properties props = new Properties(); - props.put("cluster.name", "rhq"); - props.put("cluster.dir", clusterDir.getAbsolutePath()); - props.put("auto.bootstrap", deploymentOptions.isAutoDeploy()); - props.put("data.dir", "data"); - props.put("commitlog.dir", "commit_log"); - props.put("log.dir", "logs"); - props.put("saved.caches.dir", "saved_caches"); - props.put("hostname", address); - props.put("seeds", collectionToString(ipAddresses)); - props.put("jmx.port", Integer.toString(jmxPort)); - props.put("initial.token", generateToken(i, deploymentOptions.getNumNodes())); - props.put("rhq.deploy.dir", nodeBasedir.getAbsolutePath()); - props.put("rhq.deploy.id", i); - props.put("rhq.deploy.phase", "install"); - props.put("listen.address", address); - props.put("rpc.address", address); - props.put("logging.level", deploymentOptions.getLoggingLevel()); - props.put("rhq.cassandra.username", deploymentOptions.getUsername()); - props.put("rhq.cassandra.password", deploymentOptions.getPassword()); - - if (deploymentOptions.getRingDelay() != null) { - props.put("cassandra.ring.delay.property", "-Dcassandra.ring_delay_ms="); - props.put("cassandra.ring.delay", deploymentOptions.getRingDelay()); - } - - props.put("rhq.cassandra.node.num_tokens", deploymentOptions.getNumTokens()); - props.put("rhq.cassandra.authenticator", deploymentOptions.getAuthenticator()); - props.put("rhq.cassandra.authorizer", deploymentOptions.getAuthorizer()); - - doLocalDeploy(props, bundleDir); -// startNode(nodeBasedir); -// if (i == 0) { -// waitForNodeToStart(10, address); -// } - } - FileUtil.writeFile(new ByteArrayInputStream(new byte[] {0}), installedMarker); - } catch (IOException e) { - throw new CassandraException("Failed to deploy embedded cluster", e); - } finally { - if (bundleZipeFile != null) { - bundleZipeFile.delete(); - } - - if (bundleDir != null) { - FileUtil.purge(bundleDir, true); - } - } - - return nodeDirs; - } - - public static void main(String[] args) { - long start = System.currentTimeMillis(); - BootstrapDeployer deployer = new BootstrapDeployer(); - - DeploymentOptions deploymentOptions = new DeploymentOptions(); - try { - deploymentOptions.setNumNodes(2); - deploymentOptions.load(); - } catch (IOException e) { - throw new RuntimeException("Failed to load deployment options.", e); - } - deployer.setDeploymentOptions(deploymentOptions); - try { - deployer.deploy(); - PropertiesFileUpdate serverPropertiesUpdater = getServerProperties(); - - String[] hostNames = getHostNames(deployer.getCassandraHosts()); - serverPropertiesUpdater.update("rhq.cassandra.cluster.seeds", StringUtil.arrayToString(hostNames)); - - long end = System.currentTimeMillis(); - deployer.log.info("Finished installing embedded cluster in " + (end - start) + " ms"); - } catch (CassandraException e) { - throw new RuntimeException("A deployment error occurred.", e); - } catch (IOException e) { - throw new RuntimeException("An error occurred while trying to update RHQ server properties", e); - } - } - - private static PropertiesFileUpdate getServerProperties() { - String sysprop = System.getProperty("rhq.server.properties-file"); - if (sysprop == null) { - throw new RuntimeException("The required system property [rhq.server.properties] is not defined."); - } - - File file = new File(sysprop); - if (!(file.exists() && file.isFile())) { - throw new RuntimeException("System property [" + sysprop + "] points to in invalid file."); - } - - return new PropertiesFileUpdate(file.getAbsolutePath()); - } - - private static String[] getHostNames(String hosts) { - List<String> hostNames = new ArrayList<String>(); - for (String s : hosts.split(",")) { - String[] params = s.split(":"); - hostNames.add(params[0]); - } - return hostNames.toArray(new String[hostNames.size()]); - } - - private boolean isClusterInstalled() { - File clusterDir = new File(deploymentOptions.getClusterDir()); - File installedMarker = new File(clusterDir, ".installed"); - - if (installedMarker.exists()) { - return true; - } - return false; - } - - private void doLocalDeploy(Properties deployProps, File bundleDir) throws CassandraException { - AntLauncher launcher = new AntLauncher(); - try { - File recipeFile = new File(bundleDir, "deploy.xml"); - launcher.executeBundleDeployFile(recipeFile, deployProps, null); - } catch (Exception e) { - String msg = "Failed to execute local rhq cassandra bundle deployment"; - //logException(msg, e); - throw new CassandraException(msg, e); - } - } - - private void startNode(File basedir) { - File binDir = new File(basedir, "bin"); - File startScript; - SystemInfo systemInfo = SystemInfoFactory.createSystemInfo(); - - if (systemInfo.getOperatingSystemType() == OperatingSystemType.WINDOWS) { - startScript = new File(binDir, "cassandra.bat"); - } else { - startScript = new File(binDir, "cassandra"); - } - - ProcessExecution startScriptExe = ProcessExecutionUtility.createProcessExecution(startScript); - startScriptExe.setArguments(asList("-p", "cassandra.pid")); - - ProcessExecutionResults results = systemInfo.executeProcess(startScriptExe); - } - - private void waitForNodeToStart(int maxRetries, String host) throws CassandraException { - int port = 9160; - int timeout = 50; - for (int i = 0; i < maxRetries; ++i) { - TSocket socket = new TSocket(host, port, timeout); - try { - socket.open(); - return; - } catch (TTransportException e) { - try { - Thread.sleep(1000); - } catch (InterruptedException e1) { - } - } - } - Date timestamp = new Date(); - throw new CassandraException("[" + timestamp + "] Could not connect to " + host + " after " + maxRetries + - " tries"); - } - - private File unpackBundleZipFile() throws IOException { - InputStream bundleInputStream = getClass().getResourceAsStream("/cassandra-bundle.zip"); - File bundleZipFile = File.createTempFile("cassandra-bundle.zip", null); - StreamUtil.copy(bundleInputStream, new FileOutputStream(bundleZipFile)); - - return bundleZipFile; - } - - private File unpackBundle(File bundleZipFile) throws IOException { - File bundleDir = new File(System.getProperty("java.io.tmpdir"), "rhq-cassandra-bundle"); - bundleDir.mkdir(); - ZipUtil.unzipFile(bundleZipFile, bundleDir); - - return bundleDir; - } - - private Set<String> calculateLocalIPAddresses(int numNodes) { - Set<String> addresses = new HashSet<String>(); - for (int i = 1; i <= numNodes; ++i) { - addresses.add(getLocalIPAddress(i)); - } - return addresses; - } - - private String getLocalIPAddress(int i) { - return "127.0.0." + i; - } - - private String generateToken(int i, int numNodes) { - BigInteger num = new BigInteger("2").pow(127).divide(new BigInteger(Integer.toString(numNodes))); - return num.multiply(new BigInteger(Integer.toString(i))).toString(); - } - - private Set<String> getSeeds(Set<String> addresses, int i) { - Set<String> seeds = new HashSet<String>(); - String address = getLocalIPAddress(i); - - for (String nodeAddress : addresses) { - if (nodeAddress.equals(address)) { - continue; - } else { - seeds.add(nodeAddress); - } - } - - return seeds; - } - -} diff --git a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CLI.java b/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CLI.java deleted file mode 100644 index 9808662..0000000 --- a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CLI.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * - * * RHQ Management Platform - * * Copyright (C) 2005-2012 Red Hat, Inc. - * * All rights reserved. - * * - * * This program is free software; you can redistribute it and/or modify - * * it under the terms of the GNU General Public License, version 2, as - * * published by the Free Software Foundation, and/or the GNU Lesser - * * General Public License, version 2.1, also as published by the Free - * * Software Foundation. - * * - * * This program is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * * GNU General Public License and the GNU Lesser General Public License - * * for more details. - * * - * * You should have received a copy of the GNU General Public License - * * and the GNU Lesser General Public License along with this program; - * * if not, write to the Free Software Foundation, Inc., - * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package org.rhq.cassandra; - -import java.io.File; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.OptionBuilder; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.apache.commons.cli.PosixParser; - -/** - * @author John Sanda - */ -public class CLI { - - private Set<Option> supportedArgs = new HashSet<Option>(); - - private Option deployCommand; - - private Option shutdownCommand; - - private String deployDescription = "Creates an embedded cluster and then starts each node"; - - public CLI() { - deployCommand = OptionBuilder - .withArgName("[options]") - .hasOptionalArgs() - .withDescription(deployDescription) - .create("deploy"); - - shutdownCommand = OptionBuilder - .withArgName("[options]") - .hasOptionalArg() - .withDescription("Shuts down all of the cluster nodes.") - .create("shutdown"); - } - - public void printUsage() { - HelpFormatter helpFormatter = new HelpFormatter(); - String syntax = "rhq-ccm.sh <cmd> [options]"; - String header = "\nwhere <cmd> is one of:"; - - Options options = new Options().addOption(deployCommand).addOption(shutdownCommand); - - helpFormatter.setOptPrefix(""); - helpFormatter.printHelp(syntax, header, options, null); - } - - public void exec(String[] args) { - if (args.length == 0) { - printUsage(); - return; - } - - List<String> commands = new LinkedList<String>(); - for (String arg : args) { - if (arg.equals(deployCommand.getOpt()) || arg.equals(shutdownCommand.getOpt())) { - commands.add(arg); - } - } - - if (commands.size() != 1) { - printUsage(); - return; - } - - String cmd = commands.get(0); - - if (cmd.equals(deployCommand.getOpt())) { - deploy(getCommandLine(cmd, args)); - } - } - - public void deploy(String [] args) { - Options options = new Options() - .addOption("h", "help", false, "Show this message.") - .addOption("n", "num-nodes", true, "The number of nodes to install and configure. The top level or base " + - "directory for each node will be nodeN where N is the node number."); - - try { - CommandLineParser parser = new PosixParser(); - CommandLine cmdLine = parser.parse(options, args); - - if (cmdLine.hasOption("h")) { - printDeployUsage(options); - } else { - DeploymentOptions deploymentOptions = new DeploymentOptions(); - if (cmdLine.hasOption("n")) { - int numNodes = Integer.parseInt(cmdLine.getOptionValue("n")); - deploymentOptions.setNumNodes(numNodes); - } - - CassandraClusterManager ccm = new CassandraClusterManager(deploymentOptions); - List<File> nodeDirs = ccm.installCluster(); - ccm.startCluster(nodeDirs); - } - } catch (ParseException e) { - printDeployUsage(options); - } - } - - private void printDeployUsage(Options options) { - HelpFormatter helpFormatter = new HelpFormatter(); - String syntax = "rhq-ccm.sh deploy [options]"; - String header = "\n" + deployDescription + "\n\n"; - - helpFormatter.setNewLine("\n"); - helpFormatter.printHelp(syntax, header, options, null); - } - - public void shutdown() { - - } - - private String[] getCommandLine(String cmd, String[] args) { - String[] cmdLine = new String[args.length - 1]; - int i = 0; - for (String arg : args) { - if (arg.equals(cmd)) { - continue; - } - cmdLine[i++] = arg; - } - return cmdLine; - } - - public static void main(String[] args) { -// OptionGroup ccmArgs = new OptionGroup(); -// -// Option deploy = OptionBuilder -// .withArgName("[options]") -// .hasOptionalArgs() -// .withDescription("Creates an embedded cluster and then starts each node") -// .create("deploy"); -// -// Option shutdown = OptionBuilder -// .withArgName("[options]") -// .hasOptionalArg() -// .withDescription("Shuts down all of the cluster nodes.") -// .create("shutdown"); -// -// ccmArgs.addOption(deploy).addOption(shutdown); -// //ccmArgs.setRequired(true); -// -// CommandLineParser parser = new PosixParser(); -// Options options = new Options(); -// options.addOptionGroup(ccmArgs); -// -// try { -// CommandLine cmdLine = parser.parse(options, args); -// } catch (ParseException e) { -// e.printStackTrace(); -// } - CLI cli = new CLI(); - cli.exec(args); - } - -} diff --git a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraClusterManager.java b/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraClusterManager.java deleted file mode 100644 index 9a1a648..0000000 --- a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraClusterManager.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * - * * RHQ Management Platform - * * Copyright (C) 2005-2012 Red Hat, Inc. - * * All rights reserved. - * * - * * This program is free software; you can redistribute it and/or modify - * * it under the terms of the GNU General Public License, version 2, as - * * published by the Free Software Foundation, and/or the GNU Lesser - * * General Public License, version 2.1, also as published by the Free - * * Software Foundation. - * * - * * This program is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * * GNU General Public License and the GNU Lesser General Public License - * * for more details. - * * - * * You should have received a copy of the GNU General Public License - * * and the GNU Lesser General Public License along with this program; - * * if not, write to the Free Software Foundation, Inc., - * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package org.rhq.cassandra; - -import static java.util.Arrays.asList; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.OptionBuilder; -import org.apache.commons.cli.Options; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.rhq.core.pluginapi.util.ProcessExecutionUtility; -import org.rhq.core.system.OperatingSystemType; -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.StringUtil; - -/** - * @author John Sanda - */ -public class CassandraClusterManager { - - private final Log log = LogFactory.getLog(CassandraClusterManager.class); - - private DeploymentOptions deploymentOptions; - - public CassandraClusterManager() { - this(new DeploymentOptions()); - } - - public CassandraClusterManager(DeploymentOptions deploymentOptions) { - this.deploymentOptions = deploymentOptions; - try { - this.deploymentOptions.load(); - } catch (IOException e) { - log.error("Failed to load deployment options", e); - throw new IllegalStateException("An initialization error occurred.", e); - } - } - - public List<File> installCluster() { - if (log.isDebugEnabled()) { - log.debug("Installing embedded " + deploymentOptions.getNumNodes() + " node cluster to " + - deploymentOptions.getClusterDir()); - } else { - log.info("Installing embedded cluster"); - } - - BootstrapDeployer deployer = new BootstrapDeployer(); - deployer.setDeploymentOptions(deploymentOptions); - try { - return deployer.deploy(); - } catch (CassandraException e) { - String msg = "Failed to install cluster."; - log.error(msg, e); - throw new RuntimeException(msg, e); - } - } - - public void startCluster(List<File> nodeDirs) { - long start = System.currentTimeMillis(); - log.info("Starting embedded cluster"); - for (File dir : nodeDirs) { - ProcessExecutionResults results = startNode(dir); - if (results.getError() != null) { - log.warn("An unexpected error occurred while starting the node at " + dir, results.getError()); - } - } - long end = System.currentTimeMillis(); - log.info("Started embedded cluster in " + (end - start) + " ms"); - } - - private ProcessExecutionResults startNode(File basedir) { - if (log.isDebugEnabled()) { - log.debug("Starting node at " + basedir); - } - File binDir = new File(basedir, "bin"); - File startScript; - SystemInfo systemInfo = SystemInfoFactory.createSystemInfo(); - - if (systemInfo.getOperatingSystemType() == OperatingSystemType.WINDOWS) { - startScript = new File(binDir, "cassandra.bat"); - } else { - startScript = new File(binDir, "cassandra"); - } - - ProcessExecution startScriptExe = ProcessExecutionUtility.createProcessExecution(startScript); - startScriptExe.setArguments(asList("-p", "cassandra.pid")); - - ProcessExecutionResults results = systemInfo.executeProcess(startScriptExe); - if (log.isDebugEnabled()) { - log.debug(startScript + " returned with exit code [" + results.getExitCode() + "]"); - } - - return results; - } - - public void shutdownCluster() { - } - - public List<String> getHostNames() { - List<String> hosts = new ArrayList<String>(deploymentOptions.getNumNodes()); - for (int i = 0; i < deploymentOptions.getNumNodes(); ++i) { - hosts.add("127.0.0." + (i + 1)); - } - return hosts; - } - - public InputStream loadBundle() { - return null; - } - - public static void main(String[] args) { -// CommandLineParser parser = new PosixParser(); -// -// Options options = new Options(); -// -// OptionGroup optionGroup = new OptionGroup(); -// Option deploy = OptionBuilder -// .withArgName("[options]") -// .hasArgs() -// .withDescription("Creates an embedded cluster and then starts each node") -// .create("deploy"); -// -// Option shutdown = OptionBuilder -// .withArgName("[options]") -// .hasArgs() -// .withDescription("Shuts down all of the cluster nodes.") -// .create("shutdown"); -// -// optionGroup.addOption(deploy); -// optionGroup.addOption(shutdown); -// optionGroup.setRequired(true); -// -// options.addOptionGroup(optionGroup); -// -// try { -// CommandLine cmdLine = parser.parse(options, args, false); -// if (cmdLine.hasOption("h") && cmdLine.getArgList().isEmpty()) { -// printHelp(); -// return; -// } -// } catch (ParseException e) { -// printHelp(); -// return; -// } - - /////////////////////////////////////////////////////////////// - - CassandraClusterManager ccm = new CassandraClusterManager(); - List<File> nodeDirs = ccm.installCluster(); - ccm.startCluster(nodeDirs); - - PropertiesFileUpdate serverPropertiesUpdater = getServerProperties(); - try { - serverPropertiesUpdater.update("rhq.cassandra.cluster.seeds", - StringUtil.collectionToString(ccm.getHostNames())); - } catch (IOException e) { - throw new RuntimeException("An error occurred while trying to update RHQ server properties", e); - } - } - - private static void printHelp() { - HelpFormatter helpFormatter = new HelpFormatter(); - int width = 80; - String syntax = "rhq-ccm.sh <cmd> [options]"; - String header = "\nwhere <cmd> is one of:"; - - Option deploy = OptionBuilder - .withArgName("[options]") - .hasArgs() - .withDescription("Creates an embedded cluster and then starts each node") - .create("deploy"); - - Option shutdown = OptionBuilder - .withArgName("[options]") - .hasArgs() - .withDescription("Shuts down all of the cluster nodes.") - .create("shutdown"); - - - Options options = new Options().addOption(deploy).addOption(shutdown); - - helpFormatter.setOptPrefix(""); - helpFormatter.printHelp(syntax, header, options, null); - } - - private static PropertiesFileUpdate getServerProperties() { - String sysprop = System.getProperty("rhq.server.properties-file"); - if (sysprop == null) { - throw new RuntimeException("The required system property [rhq.server.properties] is not defined."); - } - - File file = new File(sysprop); - if (!(file.exists() && file.isFile())) { - throw new RuntimeException("System property [" + sysprop + "] points to in invalid file."); - } - - return new PropertiesFileUpdate(file.getAbsolutePath()); - } - -} diff --git a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraException.java b/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraException.java deleted file mode 100644 index 43259ac..0000000 --- a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraException.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * * RHQ Management Platform - * * Copyright (C) 2005-2012 Red Hat, Inc. - * * All rights reserved. - * * - * * This program is free software; you can redistribute it and/or modify - * * it under the terms of the GNU General Public License, version 2, as - * * published by the Free Software Foundation, and/or the GNU Lesser - * * General Public License, version 2.1, also as published by the Free - * * Software Foundation. - * * - * * This program is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * * GNU General Public License and the GNU Lesser General Public License - * * for more details. - * * - * * You should have received a copy of the GNU General Public License - * * and the GNU Lesser General Public License along with this program; - * * if not, write to the Free Software Foundation, Inc., - * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package org.rhq.cassandra; - -/** - * @author John Sanda - */ -public class CassandraException extends Exception { - public CassandraException() { - super(); - } - - public CassandraException(String message) { - super(message); - } - - public CassandraException(String message, Throwable cause) { - super(message, cause); - } - - public CassandraException(Throwable cause) { - super(cause); - } -} diff --git a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraNode.java b/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraNode.java deleted file mode 100644 index 6b1cd27..0000000 --- a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraNode.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * - * * RHQ Management Platform - * * Copyright (C) 2005-2012 Red Hat, Inc. - * * All rights reserved. - * * - * * This program is free software; you can redistribute it and/or modify - * * it under the terms of the GNU General Public License, version 2, as - * * published by the Free Software Foundation, and/or the GNU Lesser - * * General Public License, version 2.1, also as published by the Free - * * Software Foundation. - * * - * * This program is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * * GNU General Public License and the GNU Lesser General Public License - * * for more details. - * * - * * You should have received a copy of the GNU General Public License - * * and the GNU Lesser General Public License along with this program; - * * if not, write to the Free Software Foundation, Inc., - * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package org.rhq.cassandra; - -/** - * @author John Sanda - */ -public class CassandraNode { - - private String hostName; - - private int thriftPort; - - public CassandraNode(String hostName, int thriftPort) { - this.hostName = hostName; - this.thriftPort = thriftPort; - } - - public String getHostName() { - return hostName; - } - - public int getThriftPort() { - return thriftPort; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - CassandraNode that = (CassandraNode) o; - - if (thriftPort != that.thriftPort) return false; - if (!hostName.equals(that.hostName)) return false; - - return true; - } - - @Override - public int hashCode() { - int result = hostName.hashCode(); - result = 41 * result + thriftPort; - return result; - } - - @Override - public String toString() { - return "CassandraNode[hostName: " + hostName + ", thriftPort: " + thriftPort + "]"; - } -} diff --git a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/ClusterInitService.java b/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/ClusterInitService.java deleted file mode 100644 index fb9d011..0000000 --- a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/ClusterInitService.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * - * * RHQ Management Platform - * * Copyright (C) 2005-2012 Red Hat, Inc. - * * All rights reserved. - * * - * * This program is free software; you can redistribute it and/or modify - * * it under the terms of the GNU General Public License, version 2, as - * * published by the Free Software Foundation, and/or the GNU Lesser - * * General Public License, version 2.1, also as published by the Free - * * Software Foundation. - * * - * * This program is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * * GNU General Public License and the GNU Lesser General Public License - * * for more details. - * * - * * You should have received a copy of the GNU General Public License - * * and the GNU Lesser General Public License along with this program; - * * if not, write to the Free Software Foundation, Inc., - * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package org.rhq.cassandra; - -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; - -import org.apache.cassandra.thrift.Cassandra; -import org.apache.cassandra.thrift.InvalidRequestException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.thrift.TException; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.transport.TFramedTransport; -import org.apache.thrift.transport.TSocket; -import org.apache.thrift.transport.TTransportException; - -/** - * This class provides operations to ensure a cluster is initialized and in a consistent - * state. It does not offer functionality for initializing a cluster but rather to make - * sure that nodes have started up and are accepting client connections for example. - * - * @author John Sanda - */ -public class ClusterInitService { - - private final Log log = LogFactory.getLog(ClusterInitService.class); - - /** - * Attempts to establish a Thrift RPC connection to the hosts for the number specified. - * In other words, if there are four hosts and <code>numHosts</code> is two, this - * method will immediately return after making two successful connections. - * - * @param hosts The cluster nodes to which a connection should be made - * @param numHosts The number of hosts to which a successful connection has to be made - * before returning. - * @return true if connections are made to the number of specified hosts, false - * otherwise. - */ - public boolean ping(List<CassandraNode> hosts, int numHosts) { - long sleep = 100; - int timeout = 50; - int connections = 0; - - for (CassandraNode host : hosts) { - TSocket socket = new TSocket(host.getHostName(), host.getThriftPort(), timeout); - try { - socket.open(); - if (log.isDebugEnabled()) { - log.debug("Successfully connected to cassandra node [" + host + "]"); - } - ++connections; - socket.close(); - if (connections == numHosts) { - return true; - } - } catch (TTransportException e) { - String msg = "Unable to open thrift connection to cassandra node [" + host + "]"; - logException(msg, e); - } - try { - Thread.sleep(sleep); - } catch (InterruptedException e) { - } - } - - return false; - } - - /** - * This method attempts to establish a Thrift RPC connection to each host. If the - * connection fails, the host is retried after going through the other, remaining - * hosts. - * - * @param hosts The cluster nodes to which a connection should be made - */ - public void waitForClusterToStart(List<CassandraNode> hosts) { - waitForClusterToStart(hosts, hosts.size()); - } - - /** - * This method attempts to establish a Thrift RPC connection to each host for the - * number specified. In other words, if there are four hosts and <code>numHosts</code> - * is 2, this method will block only until it can connect to two of the hosts. If the - * connection fails, the host is retried after going through the other, remaining - * hosts. - * - * @param hosts The cluster nodes to which a connection should be made - * @param numHosts The number of hosts to which a successful connection has to be made - * before returning. - */ - public void waitForClusterToStart(List<CassandraNode> hosts, int numHosts) { - long sleep = 100; - int timeout = 50; - int connections = 0; - Queue<CassandraNode> queue = new LinkedList<CassandraNode>(hosts); - CassandraNode host = queue.poll(); - - while (host != null) { - TSocket socket = new TSocket(host.getHostName(), host.getThriftPort(), timeout); - try { - socket.open(); - if (log.isDebugEnabled()) { - log.debug("Successfully connected to cassandra node [" + host + "]"); - } - ++connections; - socket.close(); - if (connections == numHosts) { - return; - } - } catch (TTransportException e) { - queue.offer(host); - String msg = "Unable to open thrift connection to cassandra node [" + host + "]"; - logException(msg, e); - } - try { - Thread.sleep(sleep); - } catch (InterruptedException e) { - } - host = queue.poll(); - } - } - - /** - * Waits for the cluster to reach schema agreement. During cluster initialization - * before and while schema changes propagate throughout the cluster, there could be - * multiple schema versions found among nodes. Schema agreement is reached when there - * is a single schema version and all nodes are on that version. - * - * @param clusterName The cluster name used by underlying Hector APIs. - * @param hosts The cluster nodes - */ - public void waitForSchemaAgreement(String clusterName, List<CassandraNode> hosts) { - long sleep = 100L; - CassandraClient client = createClient(hosts.get(0)); - client.openConnection(); - boolean schemaInAgreement = false; - String schemaVersion = null; - - while (!schemaInAgreement) { - Map<String, List<String>> schemaVersions = null; - try { - schemaVersions = client.describe_schema_versions(); - } catch (InvalidRequestException e) { - throw new RuntimeException("Unable to get schema versions from " + hosts.get(0), e); - } catch (TException e) { - throw new RuntimeException("Unable to get schema versions from " + hosts.get(0), e); - } - if (schemaVersions.size() > 1) { - if (log.isInfoEnabled()) { - log.info("Schema agreement has not been reached. Found " + schemaVersions.size() + - " schema versions"); - } - if (log.isDebugEnabled()) { - log.debug("Found the following schema versions: " + schemaVersions.keySet()); - } - try { - Thread.sleep(sleep); - } catch (InterruptedException e) { - } - } else { - schemaVersion = schemaVersions.keySet().iterator().next(); - List<String> hostAddresses = schemaVersions.get(schemaVersion); - if (hostAddresses.size() == hosts.size()) { - schemaInAgreement = true; - } else { - if (log.isInfoEnabled()) { - log.info("Schema agreement has not been reached. Found one schema version but only " + - hostAddresses.size() + " of " + hosts.size() + " nodes at version [" + schemaVersion + "]"); - } - if (log.isDebugEnabled()) { - log.debug("Found the following nodes at schema version [" + schemaVersion + "]: " + - hostAddresses); - } - try { - Thread.sleep(sleep); - } catch (InterruptedException e) { - } - } - } - } - client.closeConnection(); - - if (log.isInfoEnabled()) { - log.info("Schema agreement has been reached at version [" + schemaVersion + "]"); - } - } - - private CassandraClient createClient(CassandraNode node) { - TSocket socket = new TSocket(node.getHostName(), node.getThriftPort()); - TFramedTransport transport = new TFramedTransport(socket); - TProtocol protocol = new TBinaryProtocol(transport); - - return new CassandraClient(socket, protocol, node); - } - - private void logException(String msg, Exception e) { - if (log.isDebugEnabled()) { - log.debug(msg, e); - } else if (log.isInfoEnabled()) { - log.info(msg + ": " + e.getMessage()); - } else { - log.warn(msg); - } - } - - private static class CassandraClient extends Cassandra.Client { - private TSocket socket; - private CassandraNode node; - - public CassandraClient(TSocket socket, TProtocol protocol, CassandraNode node) { - super(protocol); - this.socket = socket; - this.node = node; - } - - public void openConnection() { - try { - socket.open(); - } catch (TTransportException e) { - throw new RuntimeException("Could not open thrift connection to " + node, e); - } - } - - public void closeConnection() { - socket.close(); - } - } - -} diff --git a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/DeploymentOptions.java b/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/DeploymentOptions.java deleted file mode 100644 index 098b1b0..0000000 --- a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/DeploymentOptions.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * - * * RHQ Management Platform - * * Copyright (C) 2005-2012 Red Hat, Inc. - * * All rights reserved. - * * - * * This program is free software; you can redistribute it and/or modify - * * it under the terms of the GNU General Public License, version 2, as - * * published by the Free Software Foundation, and/or the GNU Lesser - * * General Public License, version 2.1, also as published by the Free - * * Software Foundation. - * * - * * This program is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * * GNU General Public License and the GNU Lesser General Public License - * * for more details. - * * - * * You should have received a copy of the GNU General Public License - * * and the GNU Lesser General Public License along with this program; - * * if not, write to the Free Software Foundation, Inc., - * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package org.rhq.cassandra; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * @author John Sanda - */ -public class DeploymentOptions { - - private final Log log = LogFactory.getLog(DeploymentOptions.class); - - private boolean loaded; - - private String bundleFileName; - private String bundleName; - private String bundleVersion; - private String clusterDir; - private Integer numNodes; - private Boolean autoDeploy; - private Boolean embedded; - private String loggingLevel; - private Long ringDelay; - private Integer numTokens; - private Integer nativeTransportPort; - private Integer nativeTransportMaxThreads; - private String username; - private String password; - private String authenticator; - private String authorizer; - - public DeploymentOptions() { - } - - public void load() throws IOException { - if (loaded) { - return; - } - InputStream stream = null; - try { - stream = getClass().getResourceAsStream("/cassandra.properties"); - Properties props = new Properties(); - props.load(stream); - - init(props); - loaded = true; - } catch (IOException e) { - log.warn("Unable to load deployment options from cassandra.properties."); - log.info("The following error occurred while trying to load options.", e); - throw e; - } finally { - if (stream != null) { - try { - stream.close(); - } catch (IOException e) { - String msg = "An error occurred while closing input stream on cassandra.properties"; - log.info(msg, e); - } - } - } - } - - private void init(Properties properties) { - setBundleFileName(properties.getProperty("rhq.cassandra.bundle.filename")); - setBundleName(properties.getProperty("rhq.cassandra.bundle.name")); - setBundleVersion(properties.getProperty("rhq.cassandra.bundle.version")); - setClusterDir(loadProperty("rhq.cassandra.cluster.dir", properties)); - setNumNodes(Integer.parseInt(loadProperty("rhq.cassandra.cluster.num-nodes", properties))); - setAutoDeploy(Boolean.valueOf(loadProperty("rhq.cassandra.cluster.auto-deploy", properties))); - setEmbedded(Boolean.valueOf(loadProperty("rhq.cassandra.cluster.is-embedded", properties))); - setLoggingLevel(loadProperty("rhq.cassandra.logging.level", properties)); - - String ringDelay = loadProperty("rhq.cassandra.ring.delay", properties); - if (ringDelay != null && !ringDelay.isEmpty()) { - setRingDelay(Long.valueOf(ringDelay)); - } - - setNumTokens(Integer.valueOf(loadProperty("rhq.cassandra.num-tokens", properties))); - setNativeTransportPort(Integer.valueOf(loadProperty("rhq.cassandra.native-transport-port", properties))); - setNativeTransportMaxThreads(Integer.valueOf(loadProperty("rhq.casandra.native-transport-max-threads", - properties))); - setUsername(loadProperty("rhq.cassandra.username", properties)); - setPassword(loadProperty("rhq.cassandra.password", properties)); - setAuthenticator(loadProperty("rhq.cassandra.authenticator", properties)); - setAuthorizer(loadProperty("rhq.cassandra.authorizer", properties)); - } - - private String loadProperty(String key, Properties properties) { - String value = System.getProperty(key); - if (value == null || value.isEmpty()) { - return properties.getProperty(key); - } - return value; - } - - public String getBundleFileName() { - return bundleFileName; - } - - public void setBundleFileName(String name) { - if (bundleFileName == null) { - bundleFileName = name; - } - } - - public String getBundleName() { - return bundleName; - } - - public void setBundleName(String name) { - if (bundleName == null) { - bundleName = name; - } - } - - public String getBundleVersion() { - return bundleVersion; - } - - public void setBundleVersion(String version) { - if (bundleVersion == null) { - bundleVersion = version; - } - } - - public String getClusterDir() { - return clusterDir; - } - - public void setClusterDir(String dir) { - if (clusterDir == null) { - clusterDir = dir; - } - } - - public int getNumNodes() { - return numNodes; - } - - public void setNumNodes(int numNodes) { - if (this.numNodes == null) { - this.numNodes = numNodes; - } - } - - public boolean isAutoDeploy() { - return autoDeploy; - } - - public void setAutoDeploy(boolean autoDeploy) { - if (this.autoDeploy == null) { - this.autoDeploy = autoDeploy; - } - } - - public boolean isEmbedded() { - return embedded; - } - - public void setEmbedded(boolean embedded) { - if (this.embedded == null) { - this.embedded = embedded; - } - } - - public String getLoggingLevel() { - return loggingLevel; - } - - public void setLoggingLevel(String loggingLevel) { - if (this.loggingLevel == null) { - this.loggingLevel = loggingLevel; - } - } - - public Long getRingDelay() { - return ringDelay; - } - - public void setRingDelay(Long ringDelay) { - if (this.ringDelay == null) { - this.ringDelay = ringDelay; - } - } - - public Integer getNumTokens() { - return numTokens; - } - - public void setNumTokens(int numTokens) { - if (this.numTokens == null) { - this.numTokens = numTokens; - } - } - - public Integer getNativeTransportPort() { - return nativeTransportPort; - } - - public void setNativeTransportPort(Integer port) { - if (nativeTransportPort == null) { - nativeTransportPort = port; - } - } - - public Integer getNativeTransportMaxThreads() { - return nativeTransportMaxThreads; - } - - public void setNativeTransportMaxThreads(int numThreads) { - if (nativeTransportMaxThreads == null) { - nativeTransportMaxThreads = numThreads; - } - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - if (this.username == null) { - this.username = username; - } - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - if (this.password == null) { - this.password = password; - } - } - - public String getAuthenticator() { - return authenticator; - } - - public void setAuthenticator(String authenticator) { - if (this.authenticator == null) { - this.authenticator = authenticator; - } - } - - public String getAuthorizer() { - return authorizer; - } - - public void setAuthorizer(String authorizer) { - if (this.authorizer == null) { - this.authorizer = authorizer; - } - } - -} diff --git a/modules/common/cassandra-common/src/main/resources/.DS_Store b/modules/common/cassandra-common/src/main/resources/.DS_Store deleted file mode 100644 index 856cdc6..0000000 Binary files a/modules/common/cassandra-common/src/main/resources/.DS_Store and /dev/null differ diff --git a/modules/common/cassandra-common/src/main/resources/cassandra.properties b/modules/common/cassandra-common/src/main/resources/cassandra.properties deleted file mode 100644 index fb844da..0000000 --- a/modules/common/cassandra-common/src/main/resources/cassandra.properties +++ /dev/null @@ -1,77 +0,0 @@ -# These properties are used for the Cassandra bundle deployment and for embedded cluster -# deployments. Properties that affect embedded cluster deployments are used only in -# development and test environments, not production environments. -cassandra.version=1.2.0-beta3 -rhq.cassandra.bundle.filename=/cassandra-bundle.zip -rhq.cassandra.bundle.name=RHQ Cassandra Bundle -rhq.cassandra.bundle.version=1.0 - -# The username with which to authenticate requests to Cassandra. -rhq.cassandra.username=rhqadmin - -# The password with which to authenticate requests to Cassandra. -rhq.cassandra.password=rhqadmin - -# When a node initializes it contacts a seed and then sleeps for RING_DELAY (milliseconds) -# to learn about other nodes in the cluster. This defaults to 30 seconds. Cassandra gets -# the value from the cassandra.ring_delay_ms system property -# rhq.cassandra.ring.delay - -# Defines the number of tokens randomly assigned to a 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. Tokens are randomly generated with the expectation of an even -# distribution. With that said, there can be some variation. Either increasing this value -# or increasing the number of nodes in the cluster will help even out the distribution. -rhq.cassandra.num-tokens=256 - -# A class that performs authentication. The value should be a fully qualified class name -# and implement IAuthenticator. -rhq.cassandra.authenticator=org.rhq.cassandra.auth.SimpleAuthenticator -#rhq.cassandra.authenticator=org.apache.cassandra.auth.AllowAllAuthenticator - -# A class that performs authorization. Used to limit/provide permissions. The value should -# be a fully qualified class name and implement IAuthorizer. -rhq.cassandra.authorizer=org.rhq.cassandra.auth.SimpleAuthorizer -#rhq.cassandra.authorizer=org.apache.cassandra.auth.AllowAllAuthorizer - -# The location of the password properties file used by SimpleAuthenticator. If a relative -# path is specified, its location is resolved relative to Cassandra's bin directory. -rhq.cassandra.password.properties.file=./../conf/passwd.properties - -# The location of the authorization properties file used by SimpleAuthority. If a relative -# path is specified, its location is resolved relative to Cassandra's bin directory. -rhq.cassandra.access.properties.file=./../conf/access.properties - -# The maximum number of threads handling native CQL requests. -rhq.casandra.native-transport-max-threads=64 - -# The port for the CQL native transport to listen for clients on. -rhq.cassandra.native-transport-port=9042 - -# The remaining properties pertain to cluster configuration and are only used in -# development and testing environments when an embedded cluster is used. These properties -# are also loaded into the container build (when the dev profile is active) in the -# rhq-container.build.xml script. If you add any properties below here that pertain to -# cluster configuration for an embedded cluster, please also update -# rhq-container.build.xml. This is done as a convenience for developers so that they can -# just update rhq-server.properties to change the cluster configuration. -# -# -# Accepts a value of true or false and specifies whether or not the cluster is embedded. -# Note that if this property is set to false, the other, remaining cluster configuration -# properties that are set will be ignored as they are only used with embedded clusters. -rhq.cassandra.cluster.is-embedded=true - -# The directory in which cluster nodes will be installed. -rhq.cassandra.cluster.dir=${rhq.rootDir}/cassandra - -# The number of nodes in the cluster. This specifies how many nodes to install and -# configure. The top level or base directory for each node will be nodeN where N is the -# node number. -rhq.cassandra.cluster.num-nodes=2 - -rhq.cassandra.cluster.auto-deploy=true - -# The log4j logging level to use on each node. -rhq.cassandra.logging.level=DEBUG diff --git a/modules/common/cassandra-common/src/main/resources/cassandra/conf/access.properties b/modules/common/cassandra-common/src/main/resources/cassandra/conf/access.properties deleted file mode 100644 index 4465450..0000000 --- a/modules/common/cassandra-common/src/main/resources/cassandra/conf/access.properties +++ /dev/null @@ -1,46 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# This is a sample access file for SimpleAuthority. The format of this file -# is KEYSPACE[.COLUMNFAMILY].PERMISSION=USERS, where: -# -# * KEYSPACE is the keyspace name. -# * COLUMNFAMILY is the column family name. -# * PERMISSION is one of <ro> or <rw> for read-only or read-write respectively. -# * USERS is a comma delimited list of users from passwd.properties. -# -# See below for example entries. - -# NOTE: This file contains potentially sensitive information, please keep -# this in mind when setting its mode and ownership. - -# The magical '<modify-keyspaces>' property lists users who can modify the -# list of keyspaces: all users will be able to view the list of keyspaces. -<modify-keyspaces>=cassandra - -# Access to Keyspace1 (add/remove column families, etc). -Keyspace1.<ro>=jsmith,Elvis Presley -Keyspace1.<rw>=dilbert - -# Access to Standard1 (keyspace Keyspace1) -#Keyspace1.Standard1.<rw>=jsmith,Elvis Presley,dilbert - -system.local.<ro>=rhqadmin -system.peers.<ro>=rhqadmin -system.schema_keyspaces.<ro>=rhqadmin -system.schema_columnfamilies.<ro>=rhqadmin -system.schema_columns.<ro>=rhqadmin -rhq.<rw>=rhqadmin diff --git a/modules/common/cassandra-common/src/main/resources/cassandra/conf/cassandra-env.sh b/modules/common/cassandra-common/src/main/resources/cassandra/conf/cassandra-env.sh deleted file mode 100644 index a80b05b..0000000 --- a/modules/common/cassandra-common/src/main/resources/cassandra/conf/cassandra-env.sh +++ /dev/null @@ -1,235 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -calculate_heap_sizes() -{ - case "`uname`" in - Linux) - system_memory_in_mb=`free -m | awk '/Mem:/ {print $2}'` - system_cpu_cores=`egrep -c 'processor([[:space:]]+):.*' /proc/cpuinfo` - ;; - FreeBSD) - system_memory_in_bytes=`sysctl hw.physmem | awk '{print $2}'` - system_memory_in_mb=`expr $system_memory_in_bytes / 1024 / 1024` - system_cpu_cores=`sysctl hw.ncpu | awk '{print $2}'` - ;; - SunOS) - system_memory_in_mb=`prtconf | awk '/Memory size:/ {print $3}'` - system_cpu_cores=`psrinfo | wc -l` - ;; - *) - # assume reasonable defaults for e.g. a modern desktop or - # cheap server - system_memory_in_mb="2048" - system_cpu_cores="2" - ;; - esac - - # some systems like the raspberry pi don't report cores, use at least 1 - if [ "$system_cpu_cores" -lt "1" ] - then - system_cpu_cores="1" - fi - - # set max heap size based on the following - # max(min(1/2 ram, 1024MB), min(1/4 ram, 8GB)) - # calculate 1/2 ram and cap to 1024MB - # calculate 1/4 ram and cap to 8192MB - # pick the max - half_system_memory_in_mb=`expr $system_memory_in_mb / 2` - quarter_system_memory_in_mb=`expr $half_system_memory_in_mb / 2` - if [ "$half_system_memory_in_mb" -gt "1024" ] - then - half_system_memory_in_mb="1024" - fi - if [ "$quarter_system_memory_in_mb" -gt "8192" ] - then - quarter_system_memory_in_mb="8192" - fi - if [ "$half_system_memory_in_mb" -gt "$quarter_system_memory_in_mb" ] - then - max_heap_size_in_mb="$half_system_memory_in_mb" - else - max_heap_size_in_mb="$quarter_system_memory_in_mb" - fi - MAX_HEAP_SIZE="${max_heap_size_in_mb}M" - - # Young gen: min(max_sensible_per_modern_cpu_core * num_cores, 1/4 * heap size) - max_sensible_yg_per_core_in_mb="100" - max_sensible_yg_in_mb=`expr $max_sensible_yg_per_core_in_mb "*" $system_cpu_cores` - - desired_yg_in_mb=`expr $max_heap_size_in_mb / 4` - - if [ "$desired_yg_in_mb" -gt "$max_sensible_yg_in_mb" ] - then - HEAP_NEWSIZE="${max_sensible_yg_in_mb}M" - else - HEAP_NEWSIZE="${desired_yg_in_mb}M" - fi -} - -# Determine the sort of JVM we'll be running on. - -java_ver_output=`"${JAVA:-java}" -version 2>&1` - -jvmver=`echo "$java_ver_output" | awk -F'"' 'NR==1 {print $2}'` -JVM_VERSION=${jvmver%_*} -JVM_PATCH_VERSION=${jvmver#*_} - -jvm=`echo "$java_ver_output" | awk 'NR==2 {print $1}'` -case "$jvm" in - OpenJDK) - JVM_VENDOR=OpenJDK - # this will be "64-Bit" or "32-Bit" - JVM_ARCH=`echo "$java_ver_output" | awk 'NR==3 {print $2}'` - ;; - "Java(TM)") - JVM_VENDOR=Oracle - # this will be "64-Bit" or "32-Bit" - JVM_ARCH=`echo "$java_ver_output" | awk 'NR==3 {print $3}'` - ;; - *) - # Help fill in other JVM values - JVM_VENDOR=other - JVM_ARCH=unknown - ;; -esac - - -# Override these to set the amount of memory to allocate to the JVM at -# start-up. For production use you may wish to adjust this for your -# environment. MAX_HEAP_SIZE is the total amount of memory dedicated -# to the Java heap; HEAP_NEWSIZE refers to the size of the young -# generation. Both MAX_HEAP_SIZE and HEAP_NEWSIZE should be either set -# or not (if you set one, set the other). -# -# The main trade-off for the young generation is that the larger it -# is, the longer GC pause times will be. The shorter it is, the more -# expensive GC will be (usually). -# -# The example HEAP_NEWSIZE assumes a modern 8-core+ machine for decent pause -# times. If in doubt, and if you do not particularly want to tweak, go with -# 100 MB per physical CPU core. - -#MAX_HEAP_SIZE="4G" -#HEAP_NEWSIZE="800M" - -if [ "x$MAX_HEAP_SIZE" = "x" ] && [ "x$HEAP_NEWSIZE" = "x" ]; then - calculate_heap_sizes -else - if [ "x$MAX_HEAP_SIZE" = "x" ] || [ "x$HEAP_NEWSIZE" = "x" ]; then - echo "please set or unset MAX_HEAP_SIZE and HEAP_NEWSIZE in pairs (see cassandra-env.sh)" - exit 1 - fi -fi - -# Specifies the default port over which Cassandra will be available for -# JMX connections. -JMX_PORT="@@jmx.port@@" - - -# Here we create the arguments that will get passed to the jvm when -# starting cassandra. - -JVM_EXTRA_OPTS="@@cassandra.ring.delay.property@@@@cassandra.ring.delay@@" -JVM_EXTRA_OPTS="$JVM_EXTRA_OPTS -Dpasswd.properties=@@rhq.cassandra.password.properties.file@@" -JVM_EXTRA_OPTS="$JVM_EXTRA_OPTS -Daccess.properties=@@rhq.cassandra.access.properties.file@@" - -# enable assertions. disabling this in production will give a modest -# performance benefit (around 5%). -JVM_OPTS="$JVM_OPTS -ea" - -# add the jamm javaagent -if [ "$JVM_VENDOR" != "OpenJDK" -o "$JVM_VERSION" > "1.6.0" ] \ - || [ "$JVM_VERSION" = "1.6.0" -a "$JVM_PATCH_VERSION" -ge 23 ] -then - JVM_OPTS="$JVM_OPTS -javaagent:$CASSANDRA_HOME/lib/jamm-0.2.5.jar" -fi - -# enable thread priorities, primarily so we can give periodic tasks -# a lower priority to avoid interfering with client workload -JVM_OPTS="$JVM_OPTS -XX:+UseThreadPriorities" -# allows lowering thread priority without being root. see -# http://tech.stolsvik.com/2010/01/linux-java-thread-priorities-workaround.htm... -JVM_OPTS="$JVM_OPTS -XX:ThreadPriorityPolicy=42" - -# min and max heap sizes should be set to the same value to avoid -# stop-the-world GC pauses during resize, and so that we can lock the -# heap in memory on startup to prevent any of it from being swapped -# out. -JVM_OPTS="$JVM_OPTS -Xms${MAX_HEAP_SIZE}" -JVM_OPTS="$JVM_OPTS -Xmx${MAX_HEAP_SIZE}" -JVM_OPTS="$JVM_OPTS -Xmn${HEAP_NEWSIZE}" -JVM_OPTS="$JVM_OPTS -XX:+HeapDumpOnOutOfMemoryError" - -# set jvm HeapDumpPath with CASSANDRA_HEAPDUMP_DIR -if [ "x$CASSANDRA_HEAPDUMP_DIR" != "x" ]; then - JVM_OPTS="$JVM_OPTS -XX:HeapDumpPath=$CASSANDRA_HEAPDUMP_DIR/cassandra-`date +%s`-pid$$.hprof" -fi - - -startswith() { [ "${1#$2}" != "$1" ]; } - -if [ "`uname`" = "Linux" ] ; then - # reduce the per-thread stack size to minimize the impact of Thrift - # thread-per-client. (Best practice is for client connections to - # be pooled anyway.) Only do so on Linux where it is known to be - # supported. - # u34 and greater need 180k - JVM_OPTS="$JVM_OPTS -Xss180k" -fi -echo "xss = $JVM_OPTS" - -# GC tuning options -JVM_OPTS="$JVM_OPTS -XX:+UseParNewGC" -JVM_OPTS="$JVM_OPTS -XX:+UseConcMarkSweepGC" -JVM_OPTS="$JVM_OPTS -XX:+CMSParallelRemarkEnabled" -JVM_OPTS="$JVM_OPTS -XX:SurvivorRatio=8" -JVM_OPTS="$JVM_OPTS -XX:MaxTenuringThreshold=1" -JVM_OPTS="$JVM_OPTS -XX:CMSInitiatingOccupancyFraction=75" -JVM_OPTS="$JVM_OPTS -XX:+UseCMSInitiatingOccupancyOnly" - -# GC logging options -- uncomment to enable -# JVM_OPTS="$JVM_OPTS -XX:+PrintGCDetails" -# JVM_OPTS="$JVM_OPTS -XX:+PrintGCDateStamps" -# JVM_OPTS="$JVM_OPTS -XX:+PrintHeapAtGC" -# JVM_OPTS="$JVM_OPTS -XX:+PrintTenuringDistribution" -# JVM_OPTS="$JVM_OPTS -XX:+PrintGCApplicationStoppedTime" -# JVM_OPTS="$JVM_OPTS -XX:+PrintPromotionFailure" -# JVM_OPTS="$JVM_OPTS -XX:PrintFLSStatistics=1" -# JVM_OPTS="$JVM_OPTS -Xloggc:/var/log/cassandra/gc-`date +%s`.log" - -# uncomment to have Cassandra JVM listen for remote debuggers/profilers on port 1414 -# JVM_OPTS="$JVM_OPTS -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1414" - -# Prefer binding to IPv4 network intefaces (when net.ipv6.bindv6only=1). See -# http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6342561 (short version: -# comment out this entry to enable IPv6 support). -JVM_OPTS="$JVM_OPTS -Djava.net.preferIPv4Stack=true" - -# jmx: metrics and administration interface -# -# add this if you're having trouble connecting: -# JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=<public name>" -# -# see -# https://blogs.oracle.com/jmxetc/entry/troubleshooting_connection_problems_in... -# for more on configuring JMX through firewalls, etc. (Short version: -# get it working with no firewall first.) -JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.port=$JMX_PORT" -JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.ssl=false" -JVM_OPTS="$JVM_OPTS -Dcom.sun.management.jmxremote.authenticate=false" -JVM_OPTS="$JVM_OPTS $JVM_EXTRA_OPTS" diff --git a/modules/common/cassandra-common/src/main/resources/cassandra/conf/cassandra.yaml b/modules/common/cassandra-common/src/main/resources/cassandra/conf/cassandra.yaml deleted file mode 100644 index 9a5d7fd..0000000 --- a/modules/common/cassandra-common/src/main/resources/cassandra/conf/cassandra.yaml +++ /dev/null @@ -1,645 +0,0 @@ -# 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: @@cluster.name@@ - -# 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: @@rhq.cassandra.num_tokens@@ - -# 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, hints will be dropped. -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 -authenticator: @@rhq.cassandra.authenticator@@ - -# authorization backend, implementing IAUthorizer; used to limit access/provide permissions -authorizer: @@rhq.cassandra.authorizer@@ - -# 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: - - @@rhq.deploy.dir@@/@@data.dir@@ - -# commit log -commitlog_directory: @@rhq.deploy.dir@@/@@commitlog.dir@@ - -# 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: @@rhq.deploy.dir@@/@@saved.caches.dir@@ - -# 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: "@@seeds@@" - -# 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: 7000 - -# SSL port, for encrypted communication. Unused unless enabled in -# encryption_options -ssl_storage_port: 7001 - -# 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: @@listen.address@@ - -# 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 - - -# 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: @@rhq.cassandra.native_transport_port@@ -# 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: @@rhq.casandra.native_transport_max_threads@@ - - -# Whether to start the thrift rpc server. -start_rpc: true -# 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: @@rpc.address@@ -# 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: - -# 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 400 Mbps or 50 MB/s. -# stream_throughput_outbound_megabits_per_sec: 400 - -# How long the coordinator should wait for read operations to complete -read_request_timeout_in_ms: 10000 -# How long the coordinator should wait for seq or index scans to complete -range_request_timeout_in_ms: 10000 -# How long the coordinator should wait for writes to complete -write_request_timeout_in_ms: 10000 -# 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: 10000 - -# 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/JSSE... -# -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] - -# enable or disable client/server encryption. -client_encryption_options: - enabled: false - keystore: conf/.keystore - keystore_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: all diff --git a/modules/common/cassandra-common/src/main/resources/cassandra/conf/log4j-server.properties b/modules/common/cassandra-common/src/main/resources/cassandra/conf/log4j-server.properties deleted file mode 100644 index e377c32..0000000 --- a/modules/common/cassandra-common/src/main/resources/cassandra/conf/log4j-server.properties +++ /dev/null @@ -1,45 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# for production, you should probably set pattern to %c instead of %l. -# (%l is slower.) - -# output messages into a rolling log file as well as stdout -log4j.rootLogger=@@logging.level@@,stdout,R - -# stdout -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%5p %d{HH:mm:ss,SSS} %m%n - -# rolling log file -log4j.appender.R=org.apache.log4j.RollingFileAppender -log4j.appender.R.maxFileSize=20MB -log4j.appender.R.maxBackupIndex=50 -log4j.appender.R.layout=org.apache.log4j.PatternLayout -log4j.appender.R.layout.ConversionPattern=%5p [%t] %d{ISO8601} %F (line %L) %m%n -# Edit the next line to point to your logs directory -log4j.appender.R.File=@@rhq.deploy.dir@@/@@log.dir@@/system.log -log4j.appender.R.Threshold=@@logging.level@@ - -# Application logging options -#log4j.logger.org.apache.cassandra=DEBUG -#log4j.logger.org.apache.cassandra.db=DEBUG -#log4j.logger.org.apache.cassandra.service.StorageProxy=DEBUG - -# Adding this to avoid thrift logging disconnect errors. -log4j.logger.org.apache.thrift.server.TNonblockingServer=ERROR - diff --git a/modules/common/cassandra-common/src/main/resources/cassandra/conf/passwd.properties b/modules/common/cassandra-common/src/main/resources/cassandra/conf/passwd.properties deleted file mode 100644 index e6c3d9b..0000000 --- a/modules/common/cassandra-common/src/main/resources/cassandra/conf/passwd.properties +++ /dev/null @@ -1,23 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This is a sample password file for SimpleAuthenticator. The format of -# this file is username=password. If -Dpasswd.mode=MD5 then the password -# is represented as an md5 digest, otherwise it is cleartext (keep this -# in mind when setting file mode and ownership). - -cassandra=cassandra -@@rhq.cassandra.username@@=@@rhq.cassandra.password@@ diff --git a/modules/common/cassandra-common/src/main/resources/cassandra/lib/jna-3.4.1.jar b/modules/common/cassandra-common/src/main/resources/cassandra/lib/jna-3.4.1.jar deleted file mode 100644 index 4e05a4a..0000000 Binary files a/modules/common/cassandra-common/src/main/resources/cassandra/lib/jna-3.4.1.jar and /dev/null differ diff --git a/modules/common/cassandra-common/src/main/resources/cassandra/lib/platform-3.4.1.jar b/modules/common/cassandra-common/src/main/resources/cassandra/lib/platform-3.4.1.jar deleted file mode 100644 index 8357d2e..0000000 Binary files a/modules/common/cassandra-common/src/main/resources/cassandra/lib/platform-3.4.1.jar and /dev/null differ diff --git a/modules/common/cassandra-common/src/main/resources/deploy.xml b/modules/common/cassandra-common/src/main/resources/deploy.xml deleted file mode 100644 index 99644a5..0000000 --- a/modules/common/cassandra-common/src/main/resources/deploy.xml +++ /dev/null @@ -1,226 +0,0 @@ -<project name="rhq_cassandra_bundle" - default="main" - xmlns:rhq="antlib:org.rhq.bundle"> - <rhq:bundle name="${rhq.cassandra.bundle.name}" - version="${rhq.cassandra.bundle.version}" - description="A bundle for deploying RHQ Cassandra nodes."> - - <!-- - NOTE: the name attribute of an rhq:input-property does not support using a dash. - There is a convention where dashes are used in property names in rhq properties files - in the trailing part of a property name. If an rhq:input-property has a corresponding - property in cassandra.properties and contains a dash, the dash will be changed to an - underscore in this file. - --> - - <rhq:input-property name="cluster.name" - description="The name of the cluster. This is used to prevent machines in one logical cluster from joining another" - required="true" - defaultValue="rhqdev" - type="string"/> - - <rhq:input-property name="cluster.dir" - description="The directory in which Cassandra nodes will be installed" - required="true" - defaultValue="" - type="string"/> - - <rhq:input-property name="data.dir" - description="The directory where Cassandra should store data files. This should be a path relative to the base deployment directory." - required="true" - defaultValue="data" - type="string"/> - - <rhq:input-property name="commitlog.dir" - description="The directory where Cassandra stores its commit logs. This should be a path relative to the base deployment directory." - required="true" - defaultValue="commit_log" - type="string"/> - - <rhq:input-property name="saved.caches.dir" - description="The directory where Cassandra stores saved caches. This should be a path relative to the base deployment directory." - required="true" - defaultValue="saved_caches" - type="string"/> - - <rhq:input-property name="log.dir" - description="The directory where Cassandra stores log files. This should be a path relative to the base deployment directory." - required="false" - defaultValue="logs" - type="string"/> - - <rhq:input-property name="logging.level" - description="The log4j logging level to use." - required="false" - defaultValue="DEBUG" - type="string"/> - - <rhq:input-property name="hostname" - description="The host name of the node. This normally does not need to be set as Cassandra will resolve the host name/IP address. It needs to be set though for a local, development cluster running on a single machine." - required="true" - defaultValue="127.0.0.1" - type="string"/> - - <rhq:input-property name="seeds" - description="A comma-delimited list of IP addresses/host names that are deemed contact points. Cassandra nodes use this list of hosts to find each other and learn the topology of the ring. If you are running a local development cluster, be sure to have aliases set up for localhost." - required="false" - defaultValue="127.0.0.1" - type="string"/> - - <rhq:input-property name="rhq.cassandra.num_tokens" - description="Defines the number of tokens randomly assigned to a 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." - required="false" - defaultValue="256" - type="string"/> - - <rhq:input-property name="initial.token" - description="Each Cassandra node is assigned a unique token that determines what keys it is the first replica for. If you sort all nodes' token, the range of keys each is responsible for is (PreviousToken, MyToken], that is, from the previous token (exclusive) to the node's token (inclusive). The machine with the lowest Token gets both all keys less than that token, and all keys greater than the largest token; this is called a wrapping range." - required="false" - defaultValue="" - type="string"/> - - <rhq:input-property name="jmx.port" - description="The port over which Cassandra listens for JMX connections. Each node should be assigned a unique port." - required="false" - defaultValue="7200" - type="string"/> - - <rhq:input-property name="listen.address" - description="Address used for inter-node communication. Defaults to value of hostname property." - required="true" - defaultValue="" - type="string"/> - - <rhq:input-property name="rpc.address" - description="Address used for Thrift RPC client communication. Defaults to value of hostname property." - required="true" - defaultValue="" - type="string"/> - - <rhq:input-property name="cassandra.ring.delay.property" - required="false" - defaultValue="" - type="string"/> - - <rhq:input-property name="cassandra.ring.delay" - description="When a node initializes it contacts a seed and then sleeps for RING_DELAY (milliseconds) to learn about other nodes in the cluster. Cassandra uses a default value of 30 seconds." - required="false" - defaultValue="" - type="string"/> - - <rhq:input-property name="rhq.casandra.native_transport_max_threads" - description="The maximum number of threads handling native CQL requests." - required="false" - defaultValue="64" - type="integer"/> - - <rhq:input-property name="rhq.cassandra.native_transport_port" - description="The port for the CQL native transport to listen for clients on." - required="false" - defaultValue="9042" - type="integer"/> - - <rhq:input-property name="rhq.cassandra.authenticator" - description="A class that performs authentication. The value should be a fully qualified class name and implement IAuthenticator." - required="false" - defaultValue="org.rhq.cassandra.auth.SimpleAuthenticator" - type="string"/> - - <rhq:input-property name="rhq.cassandra.authorizer" - description="A class that performs authorization. Used to limit/provide permissions. The value should be a fully qualified class name and implement IAuthorizer." - required="false" - defaultValue="org.rhq.cassandra.auth.SimpleAuthorizer" - type="string"/> - - <rhq:input-property name="rhq.cassandra.password.properties.file" - description="The location of the password properties file used by SimpleAuthenticator. If a relative path is specified, its location is resolved relative to Cassandra's bin directory." - required="false" - defaultValue="./../conf/passwd.properties" - type="file"/> - - <rhq:input-property name="rhq.cassandra.access.properties.file" - description="The location of the authorization properties file used by SimpleAuthority. If a relative path is specified, its location is resolved relative to Cassandra's bin directory." - required="false" - defaultValue="./../conf/access.properties" - type="file"/> - - <rhq:input-property name="rhq.cassandra.username" - description="The username with which to authenticate requests to Cassandra." - required="true" - type="string"/> - - <rhq:input-property name="rhq.cassandra.password" - description="The password with which to authenticate requests to Cassandra." - required="true" - type="string"/> - - <rhq:deployment-unit name="cassandra" preinstallTarget="pre-install" postinstallTarget="post-install"> -<!-- - <rhq:file name="dbsetup.script" destinationFile="scripts/dbsetup.script" replace="true"/> ---> - <rhq:archive name="cassandra.zip"> - rhq:replace - <rhq:fileset dir="conf"> - <include name="cassandra.yaml"/> - </rhq:fileset> - <rhq:fileset dir="conf"> - <include name="cassandra-env.sh"/> - </rhq:fileset> - <rhq:fileset dir="conf"> - <include name="log4j-server.properties"/> - </rhq:fileset> - <rhq:fileset dir="conf"> - <include name="passwd.properties"/> - </rhq:fileset> -<!-- - <rhq:fileset dir="scripts"> - <include name="dbsetup.script"/> - </rhq:fileset> ---> - </rhq:replace> - </rhq:archive> - </rhq:deployment-unit> - </rhq:bundle> - - <target name="main"/> - - <target name="pre-install"> - <mkdir dir="${cluster.dir}"/> - </target> - - <target name="post-install"> - <property name="bin.dir" value="${rhq.deploy.dir}/bin"/> - - <mkdir dir="${rhq.deploy.dir}/${data.dir}"/> - <mkdir dir="${rhq.deploy.dir}/${commitlog.dir}"/> - <mkdir dir="${rhq.deploy.dir}/${saved.caches.dir}"/> - <mkdir dir="${rhq.deploy.dir}/${log.dir}"/> - - <chmod file="${bin.dir}/cassandra" perm="+x"/> - <chmod file="${bin.dir}/cqlsh" perm="+x"/> - <chmod file="${bin.dir}/cassandra-cli" perm="+x"/> - <chmod file="${bin.dir}/nodetool" perm="+x"/> - -<!-- - <exec dir="${bin.dir}" executable="cassandra" spawn="true" resolveexecutable="true"/> - - <script manager="javax" language="javascript"><![CDATA[ - if (project.getProperty("install.schema") == "true") { - java.lang.Thread.sleep(1000 * 10); - - exec = project.createTask("exec"); - args = exec.createArg(); - args.setLine("-f ../scripts/dbsetup.script"); - exec.setDir(java.io.File(project.getProperty("bin.dir"))); - exec.setExecutable("cassandra-cli"); - exec.setResolveExecutable(true); - exec.setError(java.io.File("/home/jsanda/cassandra.log")); - exec.setOutput(java.io.File("/home/jsanda/cassandra.log")); - - exec.execute(); - } - ]]></script> ---> - </target> - -</project> diff --git a/modules/common/cassandra-common/src/main/resources/logging.properties b/modules/common/cassandra-common/src/main/resources/logging.properties deleted file mode 100644 index 3a4f2b6..0000000 --- a/modules/common/cassandra-common/src/main/resources/logging.properties +++ /dev/null @@ -1,27 +0,0 @@ -# Additional logger names to configure (root logger is always configured) -loggers=org.rhq - -# Root logger level -logger.level=${rhq.ccm.loglevel:DEBUG} -# Root logger handlers -logger.handlers=FILE,CONSOLE - -# Console handler configuration -handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler -handler.CONSOLE.properties=autoFlush -handler.CONSOLE.level=${rhq.ccm.loglevel:DEBUG} -handler.CONSOLE.autoFlush=true -handler.CONSOLE.formatter=PATTERN - -# File handler configuration -handler.FILE=org.jboss.logmanager.handlers.FileHandler -handler.FILE.level=${rhq.ccm.loglevel:DEBUG} -handler.FILE.properties=autoFlush,fileName -handler.FILE.autoFlush=true -handler.FILE.fileName=${rhq.ccm.logdir:.}/rhq-ccm.log -handler.FILE.formatter=PATTERN - -# Formatter pattern configuration -formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter -formatter.PATTERN.properties=pattern -formatter.PATTERN.pattern=%d{HH:mm:ss,SSS} %-5p [%c] %s%E%n diff --git a/modules/common/cassandra-common/src/main/resources/module/main/module.xml b/modules/common/cassandra-common/src/main/resources/module/main/module.xml deleted file mode 100644 index 4fdbea4..0000000 --- a/modules/common/cassandra-common/src/main/resources/module/main/module.xml +++ /dev/null @@ -1,36 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<module xmlns="urn:jboss:module:1.0" name="${moduleName}"> - <main-class name="org.rhq.cassandra.CLI"/> - - <resources> - <resource-root path="${project.build.finalName}.jar"/> - <resource-root path="rhq-ant-bundle-common-${project.version}.jar"/> - <resource-root path="rhq-core-util-${project.version}.jar"/> - <resource-root path="jdom-1.0.jar"/> - <resource-root path="i18nlog-1.0.10.jar"/> - <resource-root path="rhq-core-native-system-${project.version}.jar"/> - <resource-root path="ant-1.8.0.jar"/> - <resource-root path="ant-launcher-1.8.0.jar"/> - <resource-root path="ant-nodeps-1.8.0.jar"/> - <resource-root path="ant-contrib-1.0b3.jar"/> - <resource-root path="rhq-core-plugin-api-${project.version}.jar"/> - <resource-root path="cassandra-thrift-${cassandra.version}.jar"/> - <resource-root path="slf4j-api-1.7.2.jar"/> - <resource-root path="rhq-core-domain-${project.version}.jar"/> - <resource-root path="commons-lang-2.4.jar"/> - <resource-root path="slf4j-api-1.7.2.jar"/> - <resource-root path="libthrift-0.7.0.jar"/> - </resources> - - <dependencies> - <module name="com.sun.xml.bind"/> - <module name="javax.api"/> - <module name="org.apache.commons.logging"/> - <module name="org.apache.commons.cli"/> - <module name="org.apache.log4j"/> - <module name="javax.api"/> - <module name="org.jboss.logmanager" services="import"/> - <module name="org.jboss.logging"/> - </dependencies> -</module> \ No newline at end of file diff --git a/modules/common/cassandra-common/src/main/scripts/module-assembly.xml b/modules/common/cassandra-common/src/main/scripts/module-assembly.xml deleted file mode 100644 index 30dd591..0000000 --- a/modules/common/cassandra-common/src/main/scripts/module-assembly.xml +++ /dev/null @@ -1,37 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<assembly> - <id>module-assembly</id> - <formats> - <format>zip</format> - </formats> - <includeBaseDirectory>false</includeBaseDirectory> - <baseDirectory>${project.build.finalName}-module</baseDirectory> - <fileSets> - <fileSet> - <directory>${project.build.outputDirectory}/module</directory> - <outputDirectory>/org/rhq/${artifactId}</outputDirectory> - <includes> - <include>main/module.xml</include> - </includes> - <fileMode>0644</fileMode> - <directoryMode>0755</directoryMode> - </fileSet> - <fileSet> - <directory>${project.build.directory}</directory> - <outputDirectory>/org/rhq/${artifactId}/main</outputDirectory> - <includes> - <include>${project.build.finalName}.jar</include> - </includes> - <fileMode>0644</fileMode> - <directoryMode>0755</directoryMode> - </fileSet> - <fileSet> - <directory>${project.build.directory}/dependencies</directory> - <outputDirectory>/org/rhq/${artifactId}/main</outputDirectory> - <fileMode>0644</fileMode> - <directoryMode>0755</directoryMode> - </fileSet> - </fileSets> -</assembly> -
commit a376377c4412193d5dd76fc4fc7d5899ea5394be Author: John Sanda jsanda@redhat.com Date: Fri Dec 21 13:48:33 2012 -0500
initial commit for CLI which is the class that the rhq-ccm script now calls
diff --git a/modules/common/cassandra-common/pom.xml b/modules/common/cassandra-common/pom.xml index a3d1918..50e72d1 100644 --- a/modules/common/cassandra-common/pom.xml +++ b/modules/common/cassandra-common/pom.xml @@ -43,6 +43,13 @@ <artifactId>cassandra-thrift</artifactId> <version>${cassandra.version}</version> </dependency> + + <dependency> + <groupId>commons-cli</groupId> + <artifactId>commons-cli</artifactId> + <version>1.2</version> + <scope>provided</scope> + </dependency> </dependencies>
<build> diff --git a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CLI.java b/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CLI.java new file mode 100644 index 0000000..9808662 --- /dev/null +++ b/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CLI.java @@ -0,0 +1,190 @@ +/* + * + * * RHQ Management Platform + * * Copyright (C) 2005-2012 Red Hat, Inc. + * * All rights reserved. + * * + * * This program is free software; you can redistribute it and/or modify + * * it under the terms of the GNU General Public License, version 2, as + * * published by the Free Software Foundation, and/or the GNU Lesser + * * General Public License, version 2.1, also as published by the Free + * * Software Foundation. + * * + * * This program is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * * GNU General Public License and the GNU Lesser General Public License + * * for more details. + * * + * * You should have received a copy of the GNU General Public License + * * and the GNU Lesser General Public License along with this program; + * * if not, write to the Free Software Foundation, Inc., + * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +package org.rhq.cassandra; + +import java.io.File; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.OptionBuilder; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.apache.commons.cli.PosixParser; + +/** + * @author John Sanda + */ +public class CLI { + + private Set<Option> supportedArgs = new HashSet<Option>(); + + private Option deployCommand; + + private Option shutdownCommand; + + private String deployDescription = "Creates an embedded cluster and then starts each node"; + + public CLI() { + deployCommand = OptionBuilder + .withArgName("[options]") + .hasOptionalArgs() + .withDescription(deployDescription) + .create("deploy"); + + shutdownCommand = OptionBuilder + .withArgName("[options]") + .hasOptionalArg() + .withDescription("Shuts down all of the cluster nodes.") + .create("shutdown"); + } + + public void printUsage() { + HelpFormatter helpFormatter = new HelpFormatter(); + String syntax = "rhq-ccm.sh <cmd> [options]"; + String header = "\nwhere <cmd> is one of:"; + + Options options = new Options().addOption(deployCommand).addOption(shutdownCommand); + + helpFormatter.setOptPrefix(""); + helpFormatter.printHelp(syntax, header, options, null); + } + + public void exec(String[] args) { + if (args.length == 0) { + printUsage(); + return; + } + + List<String> commands = new LinkedList<String>(); + for (String arg : args) { + if (arg.equals(deployCommand.getOpt()) || arg.equals(shutdownCommand.getOpt())) { + commands.add(arg); + } + } + + if (commands.size() != 1) { + printUsage(); + return; + } + + String cmd = commands.get(0); + + if (cmd.equals(deployCommand.getOpt())) { + deploy(getCommandLine(cmd, args)); + } + } + + public void deploy(String [] args) { + Options options = new Options() + .addOption("h", "help", false, "Show this message.") + .addOption("n", "num-nodes", true, "The number of nodes to install and configure. The top level or base " + + "directory for each node will be nodeN where N is the node number."); + + try { + CommandLineParser parser = new PosixParser(); + CommandLine cmdLine = parser.parse(options, args); + + if (cmdLine.hasOption("h")) { + printDeployUsage(options); + } else { + DeploymentOptions deploymentOptions = new DeploymentOptions(); + if (cmdLine.hasOption("n")) { + int numNodes = Integer.parseInt(cmdLine.getOptionValue("n")); + deploymentOptions.setNumNodes(numNodes); + } + + CassandraClusterManager ccm = new CassandraClusterManager(deploymentOptions); + List<File> nodeDirs = ccm.installCluster(); + ccm.startCluster(nodeDirs); + } + } catch (ParseException e) { + printDeployUsage(options); + } + } + + private void printDeployUsage(Options options) { + HelpFormatter helpFormatter = new HelpFormatter(); + String syntax = "rhq-ccm.sh deploy [options]"; + String header = "\n" + deployDescription + "\n\n"; + + helpFormatter.setNewLine("\n"); + helpFormatter.printHelp(syntax, header, options, null); + } + + public void shutdown() { + + } + + private String[] getCommandLine(String cmd, String[] args) { + String[] cmdLine = new String[args.length - 1]; + int i = 0; + for (String arg : args) { + if (arg.equals(cmd)) { + continue; + } + cmdLine[i++] = arg; + } + return cmdLine; + } + + public static void main(String[] args) { +// OptionGroup ccmArgs = new OptionGroup(); +// +// Option deploy = OptionBuilder +// .withArgName("[options]") +// .hasOptionalArgs() +// .withDescription("Creates an embedded cluster and then starts each node") +// .create("deploy"); +// +// Option shutdown = OptionBuilder +// .withArgName("[options]") +// .hasOptionalArg() +// .withDescription("Shuts down all of the cluster nodes.") +// .create("shutdown"); +// +// ccmArgs.addOption(deploy).addOption(shutdown); +// //ccmArgs.setRequired(true); +// +// CommandLineParser parser = new PosixParser(); +// Options options = new Options(); +// options.addOptionGroup(ccmArgs); +// +// try { +// CommandLine cmdLine = parser.parse(options, args); +// } catch (ParseException e) { +// e.printStackTrace(); +// } + CLI cli = new CLI(); + cli.exec(args); + } + +} diff --git a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraClusterManager.java b/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraClusterManager.java index 6b6fd31..9a1a648 100644 --- a/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraClusterManager.java +++ b/modules/common/cassandra-common/src/main/java/org/rhq/cassandra/CassandraClusterManager.java @@ -33,6 +33,10 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.List;
+import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.OptionBuilder; +import org.apache.commons.cli.Options; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
@@ -141,6 +145,42 @@ public class CassandraClusterManager { }
public static void main(String[] args) { +// CommandLineParser parser = new PosixParser(); +// +// Options options = new Options(); +// +// OptionGroup optionGroup = new OptionGroup(); +// Option deploy = OptionBuilder +// .withArgName("[options]") +// .hasArgs() +// .withDescription("Creates an embedded cluster and then starts each node") +// .create("deploy"); +// +// Option shutdown = OptionBuilder +// .withArgName("[options]") +// .hasArgs() +// .withDescription("Shuts down all of the cluster nodes.") +// .create("shutdown"); +// +// optionGroup.addOption(deploy); +// optionGroup.addOption(shutdown); +// optionGroup.setRequired(true); +// +// options.addOptionGroup(optionGroup); +// +// try { +// CommandLine cmdLine = parser.parse(options, args, false); +// if (cmdLine.hasOption("h") && cmdLine.getArgList().isEmpty()) { +// printHelp(); +// return; +// } +// } catch (ParseException e) { +// printHelp(); +// return; +// } + + /////////////////////////////////////////////////////////////// + CassandraClusterManager ccm = new CassandraClusterManager(); List<File> nodeDirs = ccm.installCluster(); ccm.startCluster(nodeDirs); @@ -154,6 +194,31 @@ public class CassandraClusterManager { } }
+ private static void printHelp() { + HelpFormatter helpFormatter = new HelpFormatter(); + int width = 80; + String syntax = "rhq-ccm.sh <cmd> [options]"; + String header = "\nwhere <cmd> is one of:"; + + Option deploy = OptionBuilder + .withArgName("[options]") + .hasArgs() + .withDescription("Creates an embedded cluster and then starts each node") + .create("deploy"); + + Option shutdown = OptionBuilder + .withArgName("[options]") + .hasArgs() + .withDescription("Shuts down all of the cluster nodes.") + .create("shutdown"); + + + Options options = new Options().addOption(deploy).addOption(shutdown); + + helpFormatter.setOptPrefix(""); + helpFormatter.printHelp(syntax, header, options, null); + } + private static PropertiesFileUpdate getServerProperties() { String sysprop = System.getProperty("rhq.server.properties-file"); if (sysprop == null) { diff --git a/modules/common/cassandra-common/src/main/resources/module/main/module.xml b/modules/common/cassandra-common/src/main/resources/module/main/module.xml index 0f5af62..4fdbea4 100644 --- a/modules/common/cassandra-common/src/main/resources/module/main/module.xml +++ b/modules/common/cassandra-common/src/main/resources/module/main/module.xml @@ -1,7 +1,7 @@ <?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.0" name="${moduleName}"> - <main-class name="org.rhq.cassandra.CassandraClusterManager"/> + <main-class name="org.rhq.cassandra.CLI"/>
<resources> <resource-root path="${project.build.finalName}.jar"/> @@ -27,6 +27,7 @@ <module name="com.sun.xml.bind"/> <module name="javax.api"/> <module name="org.apache.commons.logging"/> + <module name="org.apache.commons.cli"/> <module name="org.apache.log4j"/> <module name="javax.api"/> <module name="org.jboss.logmanager" services="import"/>
rhq-commits@lists.fedorahosted.org