[rhq] Branch 'feature/cassandra-backend' - modules/core modules/enterprise
by snegrea
modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1D.java | 4
modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1H.java | 4
modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric6H.java | 4
modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumericAggregateInterface.java | 45 +++
modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/DataMigrator.java | 150 +++++-----
5 files changed, 141 insertions(+), 66 deletions(-)
New commits:
commit 4c932c2c765aef27d333852f469286dbb50825aa
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Thu Dec 27 17:49:40 2012 -0600
Update data migrator to use interfaces to compact the code and also make the process configurable.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1D.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1D.java
index 35c958b..e36f136 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1D.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1D.java
@@ -43,7 +43,9 @@ import javax.persistence.Table;
@NamedQuery(name = MeasurementDataNumeric1D.QUERY_FIND_ALL, query = "SELECT m From MeasurementDataNumeric1D m"),
@NamedQuery(name = MeasurementDataNumeric1D.QUERY_DELETE_ALL, query = "DELETE FROM MeasurementDataNumeric1D m ") })
@Table(name = "RHQ_MEASUREMENT_DATA_NUM_1D")
-public class MeasurementDataNumeric1D extends MeasurementData implements Serializable {
+public class MeasurementDataNumeric1D extends MeasurementData implements Serializable,
+ MeasurementDataNumericAggregateInterface {
+
private static final long serialVersionUID = 1L;
public static final String GET_NUM_AGGREGATE = "MeasurementDataNumeric1D.getNumAggregate";
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1H.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1H.java
index 6766293..ad43580 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1H.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1H.java
@@ -41,7 +41,9 @@ import javax.persistence.Table;
@NamedQuery(name = MeasurementDataNumeric1H.QUERY_FIND_ALL, query = "SELECT m From MeasurementDataNumeric1H m"),
@NamedQuery(name = MeasurementDataNumeric1H.QUERY_DELETE_ALL, query = "DELETE FROM MeasurementDataNumeric1D m ") })
@Table(name = "RHQ_MEASUREMENT_DATA_NUM_1H")
-public class MeasurementDataNumeric1H extends MeasurementData implements Serializable {
+public class MeasurementDataNumeric1H extends MeasurementData implements Serializable,
+ MeasurementDataNumericAggregateInterface {
+
private static final long serialVersionUID = 1L;
public static final String GET_MAX_TIMESTAMP = "MeasurementDataNumeric1H.getMaxTimestamp";
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric6H.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric6H.java
index 75f3aed..3cb718c 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric6H.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric6H.java
@@ -43,7 +43,9 @@ import javax.persistence.Table;
@NamedQuery(name = MeasurementDataNumeric6H.QUERY_FIND_ALL, query = "SELECT m From MeasurementDataNumeric6H m"),
@NamedQuery(name = MeasurementDataNumeric6H.QUERY_DELETE_ALL, query = "DELETE FROM MeasurementDataNumeric6H m ") })
@Table(name = "RHQ_MEASUREMENT_DATA_NUM_6H")
-public class MeasurementDataNumeric6H extends MeasurementData implements Serializable {
+public class MeasurementDataNumeric6H extends MeasurementData implements Serializable,
+ MeasurementDataNumericAggregateInterface {
+
private static final long serialVersionUID = 1L;
public static final String GET_NUM_AGGREGATE = "MeasurementDataNumeric6H.getNumAggregate";
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumericAggregateInterface.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumericAggregateInterface.java
new file mode 100644
index 0000000..d4a0484
--- /dev/null
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumericAggregateInterface.java
@@ -0,0 +1,45 @@
+/*
+ *
+ * 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.core.domain.measurement;
+
+/**
+ * Transition interface for data migration between SQL and Cassandra
+ *
+ * @author Stefan Negrea
+ */
+@Deprecated
+public interface MeasurementDataNumericAggregateInterface {
+
+ public int getScheduleId();
+
+ public long getTimestamp();
+
+ public Object getValue();
+
+ public Double getMin();
+
+ public Double getMax();
+
+}
diff --git a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/DataMigrator.java b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/DataMigrator.java
index c783f93..b5c1f6c 100644
--- a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/DataMigrator.java
+++ b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/DataMigrator.java
@@ -34,6 +34,7 @@ import com.datastax.driver.core.exceptions.NoHostAvailableException;
import org.rhq.core.domain.measurement.MeasurementDataNumeric1D;
import org.rhq.core.domain.measurement.MeasurementDataNumeric1H;
import org.rhq.core.domain.measurement.MeasurementDataNumeric6H;
+import org.rhq.core.domain.measurement.MeasurementDataNumericAggregateInterface;
/**
* @author Stefan Negrea
@@ -41,76 +42,120 @@ import org.rhq.core.domain.measurement.MeasurementDataNumeric6H;
*/
public class DataMigrator {
+ private static final int MAX_RECORDS_TO_MIGRATE = 1000;
+
private final EntityManager entityManager;
+ private final Session session;
- private Session session;
+ private boolean deleteDataImmediatelyAfterMigration;
+ private boolean deleteAllDataAtTheEndOfMigration;
+ private boolean runRawDataMigration;
+ private boolean run1HAggregateDataMigration;
+ private boolean run6HAggregateDataMigration;
+ private boolean run1DAggregateDataMigration;
public DataMigrator(EntityManager entityManager, Session session) {
this.entityManager = entityManager;
this.session = session;
+
+ this.deleteDataImmediatelyAfterMigration = true;
+ this.deleteAllDataAtTheEndOfMigration = false;
+ this.runRawDataMigration = true;
+ this.run1HAggregateDataMigration = true;
+ this.run6HAggregateDataMigration = true;
+ this.run1DAggregateDataMigration = true;
}
- public void migrateData() {
+ public void run1HAggregateDataMigration(boolean value) {
+ this.run1HAggregateDataMigration = value;
+ }
- migrateRawData();
- migrateOneHourData();
- migrateSixHourData();
- migrateTwentyFourHourData();
+ public void run6HAggregateDataMigration(boolean value) {
+ this.run6HAggregateDataMigration = value;
+ }
- clearAllData();
+ public void run1DAggregateDataMigration(boolean value) {
+ this.run1DAggregateDataMigration = value;
}
- private void migrateRawData() {
+ public void deleteDataImmediatelyAfterMigration(boolean value) {
+ this.deleteDataImmediatelyAfterMigration = value;
+ this.deleteAllDataAtTheEndOfMigration = !value;
+ }
+ public void deleteAllDataAtTheEndOfMigration(boolean value) {
+ this.deleteAllDataAtTheEndOfMigration = value;
+ this.deleteDataImmediatelyAfterMigration = !value;
}
- @SuppressWarnings("unchecked")
- private void migrateOneHourData() {
- Query q = this.entityManager.createNamedQuery(MeasurementDataNumeric1H.QUERY_FIND_ALL);
- List<MeasurementDataNumeric1H> existingData = q.getResultList();
+ public void migrateData() {
+ if (runRawDataMigration) {
+ migrateRawData();
+ }
- try {
- PreparedStatement statement = createPreparedStatement(MetricsTable.ONE_HOUR);
+ if (run1HAggregateDataMigration) {
+ migrateAggregatedMetricsData(MeasurementDataNumeric1H.QUERY_FIND_ALL, MetricsTable.ONE_HOUR);
+ }
- for (MeasurementDataNumeric1H measurement : existingData) {
- insertData(statement, measurement.getScheduleId(), measurement.getMin(), measurement.getMax(),
- Double.parseDouble(measurement.getValue().toString()), measurement.getTimestamp());
- }
- } catch (NoHostAvailableException e) {
- throw new CQLException(e);
+ if (run6HAggregateDataMigration) {
+ migrateAggregatedMetricsData(MeasurementDataNumeric6H.QUERY_FIND_ALL, MetricsTable.SIX_HOUR);
+ }
+
+ if (run1DAggregateDataMigration) {
+ migrateAggregatedMetricsData(MeasurementDataNumeric1D.QUERY_FIND_ALL, MetricsTable.TWENTY_FOUR_HOUR);
+ }
+
+ if (deleteAllDataAtTheEndOfMigration) {
+ this.clearAllData();
}
}
+ private void migrateRawData() {
+ //possibly need to add raw SQL code here because data is split among several tables
+ }
+
@SuppressWarnings("unchecked")
- private void migrateSixHourData() {
- Query q = this.entityManager.createNamedQuery(MeasurementDataNumeric6H.QUERY_FIND_ALL);
- List<MeasurementDataNumeric6H> existingData = q.getResultList();
+ private void migrateAggregatedMetricsData(String query, MetricsTable metricsTable) {
+ List<MeasurementDataNumericAggregateInterface> existingData = null;
- try {
- PreparedStatement statement = createPreparedStatement(MetricsTable.SIX_HOUR);
+ while (true) {
+ Query q = this.entityManager.createNamedQuery(query);
+ q.setMaxResults(MAX_RECORDS_TO_MIGRATE);
+ existingData = (List<MeasurementDataNumericAggregateInterface>) q.getResultList();
- for (MeasurementDataNumeric6H measurement : existingData) {
- insertData(statement, measurement.getScheduleId(), measurement.getMin(), measurement.getMax(),
- Double.parseDouble(measurement.getValue().toString()), measurement.getTimestamp());
+ if (existingData.size() == 0) {
+ break;
}
- } catch (NoHostAvailableException e) {
- throw new CQLException(e);
- }
- }
- private void migrateTwentyFourHourData() {
- Query q = this.entityManager.createNamedQuery(MeasurementDataNumeric1D.QUERY_FIND_ALL);
- List<MeasurementDataNumeric1D> existingData = q.getResultList();
+ try {
+ String cql = "INSERT INTO " + metricsTable
+ + " (schedule_id, time, type, value) VALUES (?, ?, ?, ?) USING TTL " + metricsTable.getTTL();
+ PreparedStatement statement = session.prepare(cql);
+
+ for (MeasurementDataNumericAggregateInterface measurement : existingData) {
- try {
- PreparedStatement statement = createPreparedStatement(MetricsTable.TWENTY_FOUR_HOUR);
+ BoundStatement boundStatement = statement.bind(measurement.getScheduleId(),
+ new Date(measurement.getTimestamp()), AggregateType.MIN.ordinal(), measurement.getMin());
+ session.execute(boundStatement);
- for (MeasurementDataNumeric1D measurement : existingData) {
- insertData(statement, measurement.getScheduleId(), measurement.getMin(), measurement.getMax(),
- Double.parseDouble(measurement.getValue().toString()), measurement.getTimestamp());
+ boundStatement = statement.bind(measurement.getScheduleId(), new Date(measurement.getTimestamp()),
+ AggregateType.MAX.ordinal(), measurement.getMax());
+ session.execute(boundStatement);
+
+ boundStatement = statement.bind(measurement.getScheduleId(), new Date(measurement.getTimestamp()),
+ AggregateType.AVG.ordinal(), Double.parseDouble(measurement.getValue().toString()));
+ session.execute(boundStatement);
+ }
+ } catch (NoHostAvailableException e) {
+ throw new CQLException(e);
+ }
+
+ if (this.deleteDataImmediatelyAfterMigration) {
+ for (Object entity : existingData) {
+ this.entityManager.remove(entity);
+ }
+ this.entityManager.flush();
}
- } catch (NoHostAvailableException e) {
- throw new CQLException(e);
}
}
@@ -124,25 +169,4 @@ public class DataMigrator {
q = this.entityManager.createNamedQuery(MeasurementDataNumeric1D.QUERY_DELETE_ALL);
q.executeUpdate();
}
-
- private PreparedStatement createPreparedStatement(MetricsTable metricsTable) throws NoHostAvailableException {
- String cql = "INSERT INTO " + metricsTable + " (schedule_id, time, type, value) VALUES (?, ?, ?, ?) USING TTL "
- + metricsTable.getTTL();
- PreparedStatement statement = session.prepare(cql);
- return statement;
- }
-
- private void insertData(PreparedStatement statement, int scheduleId, double min, double max, double average,
- long timestamp)
- throws NoHostAvailableException {
- BoundStatement boundStatement = statement.bind(scheduleId, new Date(timestamp), AggregateType.MIN.ordinal(),
- min);
- session.execute(boundStatement);
-
- boundStatement = statement.bind(scheduleId, new Date(timestamp), AggregateType.MAX.ordinal(), max);
- session.execute(boundStatement);
-
- boundStatement = statement.bind(scheduleId, new Date(timestamp), AggregateType.AVG.ordinal(), average);
- session.execute(boundStatement);
- }
}
10 years, 11 months
[rhq] Branch 'feature/cassandra-backend' - modules/enterprise
by snegrea
modules/enterprise/server/server-metrics/pom.xml | 15
modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricBaselineCalculator.java | 95 ----
modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsBaselineCalculator.java | 95 ++++
modules/enterprise/server/server-metrics/src/test/java/org/rhq/server/metrics/ArithmeticMeanCalculatorTest.java | 93 ++++
modules/enterprise/server/server-metrics/src/test/java/org/rhq/server/metrics/MetricsBaselineCalculatorTest.java | 228 ++++++++++
5 files changed, 431 insertions(+), 95 deletions(-)
New commits:
commit 8f96d812511fc82bf6a57300ffed918b457792b3
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Wed Dec 26 13:33:02 2012 -0600
Add unit tests for the metrics baseline calculation and arithmetic mean calculator.
Also, min and max of a baseline are now zero if the average calculation succeeds but data is purged from the db before min and max queries.
diff --git a/modules/enterprise/server/server-metrics/pom.xml b/modules/enterprise/server/server-metrics/pom.xml
index 0e5b43a..ef9524b 100644
--- a/modules/enterprise/server/server-metrics/pom.xml
+++ b/modules/enterprise/server/server-metrics/pom.xml
@@ -121,6 +121,21 @@
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.1</version>
</dependency>
+
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-module-testng</artifactId>
+ <version>${powermock.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-api-mockito</artifactId>
+ <version>${powermock.version}</version>
+ <scope>test</scope>
+ </dependency>
+
</dependencies>
<build>
diff --git a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricBaselineCalculator.java b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricBaselineCalculator.java
deleted file mode 100644
index c3322e8..0000000
--- a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricBaselineCalculator.java
+++ /dev/null
@@ -1,95 +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.server.metrics;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.datastax.driver.core.Session;
-
-import org.rhq.core.domain.measurement.MeasurementBaseline;
-import org.rhq.core.domain.util.PageOrdering;
-
-/**
- * @author Stefan Negrea
- */
-public class MetricBaselineCalculator {
-
- private MetricsDAO metricsDAO;
-
- public MetricBaselineCalculator(Session session) {
- this.metricsDAO = new MetricsDAO(session);
- }
-
- public List<MeasurementBaseline> calculateBaselines(List<Integer> scheduleIds, long startTime, long endTime) {
- List<MeasurementBaseline> calculatedBaselines = new ArrayList<MeasurementBaseline>();
-
- MeasurementBaseline measurementBaseline;
- for (Integer scheduleId : scheduleIds) {
- measurementBaseline = this.calculateBaseline(scheduleId, startTime, endTime);
- if (measurementBaseline != null) {
- calculatedBaselines.add(measurementBaseline);
- }
- }
-
- return calculatedBaselines;
- }
-
- private MeasurementBaseline calculateBaseline(Integer scheduleId, long startTime, long endTime) {
- List<AggregatedNumericMetric> metrics = this.metricsDAO.findAggregateMetrics(MetricsTable.ONE_HOUR, scheduleId, startTime, endTime);
-
- if (metrics.size() != 0) {
- ArithmeticMeanCalculator mean = new ArithmeticMeanCalculator();
-
- for (AggregatedNumericMetric entry : metrics) {
- mean.add(entry.getAvg());
- }
-
- double min = Double.MIN_VALUE;
- List<Double> results = this.metricsDAO.findAggregateSimpleMetric(MetricsTable.ONE_HOUR, AggregateType.MIN,
- scheduleId, startTime, endTime, PageOrdering.ASC, 1);
- if(results.size() != 0){
- min = results.get(0);
- }
-
- double max = Double.MAX_VALUE;
- results = this.metricsDAO.findAggregateSimpleMetric(MetricsTable.ONE_HOUR, AggregateType.MAX, scheduleId,
- startTime, endTime, PageOrdering.DESC, 1);
- if (results.size() != 0) {
- max = results.get(0);
- }
-
- MeasurementBaseline baseline = new MeasurementBaseline();
- baseline.setMax(max);
- baseline.setMin(min);
- baseline.setMean(mean.getArithmeticMean());
- baseline.setScheduleId(scheduleId);
-
- return baseline;
- }
-
- return null;
- }
-}
diff --git a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsBaselineCalculator.java b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsBaselineCalculator.java
new file mode 100644
index 0000000..3ce6f5d
--- /dev/null
+++ b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsBaselineCalculator.java
@@ -0,0 +1,95 @@
+/*
+ *
+ * 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.server.metrics;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.datastax.driver.core.Session;
+
+import org.rhq.core.domain.measurement.MeasurementBaseline;
+import org.rhq.core.domain.util.PageOrdering;
+
+/**
+ * @author Stefan Negrea
+ */
+public class MetricsBaselineCalculator {
+
+ private MetricsDAO metricsDAO;
+
+ public MetricsBaselineCalculator(Session session) {
+ this.metricsDAO = new MetricsDAO(session);
+ }
+
+ public List<MeasurementBaseline> calculateBaselines(List<Integer> scheduleIds, long startTime, long endTime) {
+ List<MeasurementBaseline> calculatedBaselines = new ArrayList<MeasurementBaseline>();
+
+ MeasurementBaseline measurementBaseline;
+ for (Integer scheduleId : scheduleIds) {
+ measurementBaseline = this.calculateBaseline(scheduleId, startTime, endTime);
+ if (measurementBaseline != null) {
+ calculatedBaselines.add(measurementBaseline);
+ }
+ }
+
+ return calculatedBaselines;
+ }
+
+ private MeasurementBaseline calculateBaseline(Integer scheduleId, long startTime, long endTime) {
+ List<AggregatedNumericMetric> metrics = this.metricsDAO.findAggregateMetrics(MetricsTable.ONE_HOUR, scheduleId, startTime, endTime);
+
+ if (metrics.size() != 0) {
+ ArithmeticMeanCalculator mean = new ArithmeticMeanCalculator();
+
+ for (AggregatedNumericMetric entry : metrics) {
+ mean.add(entry.getAvg());
+ }
+
+ double min = 0;
+ List<Double> results = this.metricsDAO.findAggregateSimpleMetric(MetricsTable.ONE_HOUR, AggregateType.MIN,
+ scheduleId, startTime, endTime, PageOrdering.ASC, 1);
+ if(results.size() != 0){
+ min = results.get(0);
+ }
+
+ double max = 0;
+ results = this.metricsDAO.findAggregateSimpleMetric(MetricsTable.ONE_HOUR, AggregateType.MAX, scheduleId,
+ startTime, endTime, PageOrdering.DESC, 1);
+ if (results.size() != 0) {
+ max = results.get(0);
+ }
+
+ MeasurementBaseline baseline = new MeasurementBaseline();
+ baseline.setMax(max);
+ baseline.setMin(min);
+ baseline.setMean(mean.getArithmeticMean());
+ baseline.setScheduleId(scheduleId);
+
+ return baseline;
+ }
+
+ return null;
+ }
+}
diff --git a/modules/enterprise/server/server-metrics/src/test/java/org/rhq/server/metrics/ArithmeticMeanCalculatorTest.java b/modules/enterprise/server/server-metrics/src/test/java/org/rhq/server/metrics/ArithmeticMeanCalculatorTest.java
new file mode 100644
index 0000000..2b9653a
--- /dev/null
+++ b/modules/enterprise/server/server-metrics/src/test/java/org/rhq/server/metrics/ArithmeticMeanCalculatorTest.java
@@ -0,0 +1,93 @@
+/*
+ * RHQ Management Platform
+ * Copyright 2011, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+package org.rhq.server.metrics;
+
+import java.util.Random;
+
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+/**
+ * @author Stefan Negrea
+ *
+ */
+public class ArithmeticMeanCalculatorTest {
+
+ private static final double TEST_PRECISION = Math.pow(10, -10);
+
+ @Test
+ public void simpleTest() {
+ ArithmeticMeanCalculator objectUnderTest = new ArithmeticMeanCalculator();
+
+ objectUnderTest.add(1);
+ objectUnderTest.add(2);
+ objectUnderTest.add(3);
+ objectUnderTest.add(4);
+ objectUnderTest.add(5);
+ objectUnderTest.add(6);
+
+ Assert.assertEquals(objectUnderTest.getArithmeticMean(), 3.5);
+ }
+
+ @Test
+ public void simpleResetTest() {
+ ArithmeticMeanCalculator objectUnderTest = new ArithmeticMeanCalculator();
+
+ objectUnderTest.add(1);
+ objectUnderTest.add(2);
+ objectUnderTest.add(3);
+ objectUnderTest.add(4);
+ objectUnderTest.add(5);
+ objectUnderTest.add(6);
+ objectUnderTest.add(7);
+ objectUnderTest.add(8);
+
+ Assert.assertEquals(objectUnderTest.getArithmeticMean(), 4.5, TEST_PRECISION);
+
+ objectUnderTest.reset();
+ objectUnderTest.add(1);
+ objectUnderTest.add(2);
+ objectUnderTest.add(3);
+
+ Assert.assertEquals(objectUnderTest.getArithmeticMean(), 2.0, TEST_PRECISION);
+ }
+
+ @Test
+ public void randomNumberWithResetTest() {
+ ArithmeticMeanCalculator objectUnderTest = new ArithmeticMeanCalculator();
+
+ Random random = new Random(1243);
+
+ for (int j = 0; j < 5; j++) {
+ double sum = 0;
+ objectUnderTest.reset();
+
+ for (int i = 0; i < 123; i++) {
+ double randomNumber = random.nextDouble() * 100;
+ objectUnderTest.add(randomNumber);
+ sum += randomNumber;
+ }
+
+ Assert.assertEquals(objectUnderTest.getArithmeticMean(), sum / 123, TEST_PRECISION);
+ }
+ }
+
+}
diff --git a/modules/enterprise/server/server-metrics/src/test/java/org/rhq/server/metrics/MetricsBaselineCalculatorTest.java b/modules/enterprise/server/server-metrics/src/test/java/org/rhq/server/metrics/MetricsBaselineCalculatorTest.java
new file mode 100644
index 0000000..669b8bf
--- /dev/null
+++ b/modules/enterprise/server/server-metrics/src/test/java/org/rhq/server/metrics/MetricsBaselineCalculatorTest.java
@@ -0,0 +1,228 @@
+/*
+ * RHQ Management Platform
+ * Copyright 2011, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+package org.rhq.server.metrics;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Random;
+
+import com.datastax.driver.core.Session;
+
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.testng.PowerMockObjectFactory;
+import org.testng.Assert;
+import org.testng.IObjectFactory;
+import org.testng.annotations.ObjectFactory;
+import org.testng.annotations.Test;
+
+import org.rhq.core.domain.measurement.MeasurementBaseline;
+import org.rhq.core.domain.util.PageOrdering;
+
+/**
+ * @author Stefan Negrea
+ *
+ */
+@PrepareForTest({ MetricsBaselineCalculator.class })
+public class MetricsBaselineCalculatorTest {
+
+ private static final double TEST_PRECISION = Math.pow(10, -10);
+
+ @ObjectFactory
+ public IObjectFactory getObjectFactory() {
+ return new PowerMockObjectFactory();
+ }
+
+ @Test
+ public void noCalculationTest() throws Exception {
+
+ //tell the method story as it happens: mock dependencies and configure
+ //those dependencies to get the method under test to completion.
+ Session mockSession = mock(Session.class);
+ MetricsDAO mockMetricsDAO = mock(MetricsDAO.class);
+ PowerMockito.whenNew(MetricsDAO.class).withParameterTypes(Session.class).withArguments(eq(mockSession))
+ .thenReturn(mockMetricsDAO);
+
+ when(mockMetricsDAO.findAggregateMetrics(eq(MetricsTable.ONE_HOUR), eq(1), eq(0), eq(1))).thenReturn(
+ new ArrayList<AggregatedNumericMetric>());
+
+ //create object to test and inject required dependencies
+ MetricsBaselineCalculator objectUnderTest = new MetricsBaselineCalculator(mockSession);
+
+ //run code under test
+ List<MeasurementBaseline> result = objectUnderTest.calculateBaselines(Arrays.asList(0), 0, 1);
+
+ //verify the results (Assert and mock verification)
+ Assert.assertEquals(result.size(), 0);
+ verify(mockMetricsDAO, times(1)).findAggregateMetrics(eq(MetricsTable.ONE_HOUR), any(Integer.class),
+ any(Integer.class), any(Integer.class));
+ verifyNoMoreInteractions(mockMetricsDAO);
+ }
+
+ @Test
+ public void randomDataTest() throws Exception {
+ //generate random data
+ Random random = new Random();
+ List<AggregatedNumericMetric> randomData = new ArrayList<AggregatedNumericMetric>();
+
+ for (int i = 0; i < 123; i++) {
+ AggregatedNumericMetric randomMetric = new AggregatedNumericMetric();
+ randomMetric.setAvg(random.nextDouble() * 1000);
+ randomData.add(randomMetric);
+ }
+
+ double average = 0;
+ for (AggregatedNumericMetric metric : randomData) {
+ average += metric.getAvg();
+ }
+ average = average / 123;
+
+ double expectedMax = 99999;
+ double expectedMin = 1.1111;
+ int expectedScheduleId= 567;
+ long expectedStartTime = 135;
+ long expectedEndTime = 246;
+ long beforeComputeTime = System.currentTimeMillis();
+
+ //tell the method story as it happens: mock dependencies and configure
+ //those dependencies to get the method under test to completion.
+ Session mockSession = mock(Session.class);
+ MetricsDAO mockMetricsDAO = mock(MetricsDAO.class);
+ PowerMockito.whenNew(MetricsDAO.class).withParameterTypes(Session.class).withArguments(eq(mockSession))
+ .thenReturn(mockMetricsDAO);
+
+ when(
+ mockMetricsDAO.findAggregateMetrics(eq(MetricsTable.ONE_HOUR), eq(expectedScheduleId),
+ eq(expectedStartTime), eq(expectedEndTime))).thenReturn(randomData);
+
+ when(
+ mockMetricsDAO.findAggregateSimpleMetric(eq(MetricsTable.ONE_HOUR), eq(AggregateType.MIN),
+ eq(expectedScheduleId), eq(expectedStartTime), eq(expectedEndTime), eq(PageOrdering.ASC), eq(1)))
+ .thenReturn(Arrays.asList(expectedMin));
+
+ when(
+ mockMetricsDAO.findAggregateSimpleMetric(eq(MetricsTable.ONE_HOUR), eq(AggregateType.MAX),
+ eq(expectedScheduleId), eq(expectedStartTime), eq(expectedEndTime), eq(PageOrdering.DESC), eq(1)))
+ .thenReturn(Arrays.asList(expectedMax));
+
+ //create object to test and inject required dependencies
+ MetricsBaselineCalculator objectUnderTest = new MetricsBaselineCalculator(mockSession);
+
+ //run code under test
+ List<MeasurementBaseline> result = objectUnderTest.calculateBaselines(Arrays.asList(expectedScheduleId),
+ expectedStartTime, expectedEndTime);
+
+ //verify the results (Assert and mock verification)
+ Assert.assertEquals(result.size(), 1);
+
+ MeasurementBaseline baselineResult = result.get(0);
+ Assert.assertEquals(baselineResult.getMean(), average, TEST_PRECISION);
+ Assert.assertEquals(baselineResult.getMax(), expectedMax, TEST_PRECISION);
+ Assert.assertEquals(baselineResult.getMin(), expectedMin, TEST_PRECISION);
+ Assert.assertEquals(baselineResult.getScheduleId(), expectedScheduleId);
+ if (baselineResult.getComputeTime().getTime() >= System.currentTimeMillis()) {
+ Assert.fail("Back compute time, the computation was forward dated.");
+ }
+ if (baselineResult.getComputeTime().getTime() <= beforeComputeTime) {
+ Assert.fail("Back compute time, the computation was backdated.");
+ }
+
+ verify(mockMetricsDAO, times(1)).findAggregateMetrics(eq(MetricsTable.ONE_HOUR), eq(expectedScheduleId),
+ eq(expectedStartTime), eq(expectedEndTime));
+ verify(mockMetricsDAO, times(1)).findAggregateSimpleMetric(eq(MetricsTable.ONE_HOUR), eq(AggregateType.MIN),
+ eq(expectedScheduleId), eq(expectedStartTime), eq(expectedEndTime), eq(PageOrdering.ASC), eq(1));
+ verify(mockMetricsDAO, times(1)).findAggregateSimpleMetric(eq(MetricsTable.ONE_HOUR), eq(AggregateType.MAX),
+ eq(expectedScheduleId), eq(expectedStartTime), eq(expectedEndTime), eq(PageOrdering.DESC), eq(1));
+
+ verifyNoMoreInteractions(mockMetricsDAO);
+ }
+
+ @Test
+ public void noMinMaxDataTest() throws Exception {
+ //generate random data
+ Random random = new Random();
+ List<AggregatedNumericMetric> randomData = new ArrayList<AggregatedNumericMetric>();
+
+ for (int i = 0; i < 123; i++) {
+ AggregatedNumericMetric randomMetric = new AggregatedNumericMetric();
+ randomMetric.setAvg(random.nextDouble() * 1000);
+ randomData.add(randomMetric);
+ }
+
+ double average = 0;
+ for (AggregatedNumericMetric metric : randomData) {
+ average += metric.getAvg();
+ }
+ average = average / 123;
+
+ double expectedMinMax = 0;
+ int expectedScheduleId = 567;
+ long expectedStartTime = 135;
+ long expectedEndTime = 246;
+
+ //tell the method story as it happens: mock dependencies and configure
+ //those dependencies to get the method under test to completion.
+ Session mockSession = mock(Session.class);
+ MetricsDAO mockMetricsDAO = mock(MetricsDAO.class);
+ PowerMockito.whenNew(MetricsDAO.class).withParameterTypes(Session.class).withArguments(eq(mockSession))
+ .thenReturn(mockMetricsDAO);
+
+ when(
+ mockMetricsDAO.findAggregateMetrics(eq(MetricsTable.ONE_HOUR), eq(expectedScheduleId),
+ eq(expectedStartTime), eq(expectedEndTime))).thenReturn(randomData);
+
+
+ //create object to test and inject required dependencies
+ MetricsBaselineCalculator objectUnderTest = new MetricsBaselineCalculator(mockSession);
+
+ //run code under test
+ List<MeasurementBaseline> result = objectUnderTest.calculateBaselines(Arrays.asList(expectedScheduleId),
+ expectedStartTime, expectedEndTime);
+
+ //verify the results (Assert and mock verification)
+ Assert.assertEquals(result.size(), 1);
+
+ MeasurementBaseline baselineResult = result.get(0);
+ Assert.assertEquals(baselineResult.getMean(), average, TEST_PRECISION);
+ Assert.assertEquals(baselineResult.getMax(), expectedMinMax, TEST_PRECISION);
+ Assert.assertEquals(baselineResult.getMin(), expectedMinMax, TEST_PRECISION);
+ Assert.assertEquals(baselineResult.getScheduleId(), expectedScheduleId);
+
+ verify(mockMetricsDAO, times(1)).findAggregateMetrics(eq(MetricsTable.ONE_HOUR), eq(expectedScheduleId),
+ eq(expectedStartTime), eq(expectedEndTime));
+ verify(mockMetricsDAO, times(1)).findAggregateSimpleMetric(eq(MetricsTable.ONE_HOUR), eq(AggregateType.MIN),
+ eq(expectedScheduleId), eq(expectedStartTime), eq(expectedEndTime), eq(PageOrdering.ASC), eq(1));
+ verify(mockMetricsDAO, times(1)).findAggregateSimpleMetric(eq(MetricsTable.ONE_HOUR), eq(AggregateType.MAX),
+ eq(expectedScheduleId), eq(expectedStartTime), eq(expectedEndTime), eq(PageOrdering.DESC), eq(1));
+
+ verifyNoMoreInteractions(mockMetricsDAO);
+ }
+
+}
10 years, 11 months
[rhq] Branch 'tsegismont/as7plugin-httpclient' - .classpath modules/core modules/plugins
by Thomas Segismont
.classpath | 4
modules/core/arquillian-integration/container/pom.xml | 22 +++++
modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/util/SigarInstaller.java | 42 +++++++---
modules/core/arquillian-integration/container/src/main/resources/maven-properties.properties | 4
modules/plugins/jboss-as-7/pom.xml | 8 -
5 files changed, 65 insertions(+), 15 deletions(-)
New commits:
commit afa006e24139c5badef4ac89ac22e0d6ce4e2280
Author: Thomas Segismont <tsegismo(a)redhat.com>
Date: Mon Dec 24 16:28:01 2012 +0100
Integation tests: make rid of SigarInstaller hard coded Sigar version
diff --git a/.classpath b/.classpath
index 2b8098f..e6e9eaf 100644
--- a/.classpath
+++ b/.classpath
@@ -169,9 +169,11 @@
<classpathentry kind="src" path="modules/helpers/rtfilter/src/main/java"/>
<classpathentry kind="src" path="modules/core/plugin-container-itest/src/test/java"/>
<classpathentry kind="src" path="modules/core/plugin-test-util/src/main/java"/>
- <classpathentry kind="src" path="modules/core/arquillian-integration/container/src/test/java"/>
<classpathentry kind="src" path="modules/core/arquillian-integration/archive/src/main/java"/>
<classpathentry kind="src" path="modules/core/arquillian-integration/container/src/main/java"/>
+ <classpathentry kind="src" path="modules/core/arquillian-integration/container/src/main/resources"/>
+ <classpathentry kind="src" path="modules/core/arquillian-integration/container/src/test/java"/>
+ <classpathentry kind="src" path="modules/core/arquillian-integration/container/src/test/resources"/>
<classpathentry kind="src" path="modules/test-utils/src/main/java"/>
<classpathentry kind="src" path="modules/integration-tests/mod_cluster-plugin-test/src/test/java"/>
<classpathentry kind="src" path="etc/samples/skeleton-plugin/src/main/java"/>
diff --git a/modules/core/arquillian-integration/container/pom.xml b/modules/core/arquillian-integration/container/pom.xml
index f01d018..2a397ab 100644
--- a/modules/core/arquillian-integration/container/pom.xml
+++ b/modules/core/arquillian-integration/container/pom.xml
@@ -20,6 +20,28 @@
<name>RHQ Arquillian Plugin Container</name>
<description>RHQ Embedded Agent Plugin Container integration for Arquillian</description>
+ <build>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>maven-properties.properties</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>false</filtering>
+ <includes>
+ <include>**/*</include>
+ </includes>
+ <excludes>
+ <exclude>maven-properties.properties</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ </build>
+
<!-- Dependencies -->
<dependencies>
diff --git a/modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/util/SigarInstaller.java b/modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/util/SigarInstaller.java
index 97b6df8..cad7f7d 100644
--- a/modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/util/SigarInstaller.java
+++ b/modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/util/SigarInstaller.java
@@ -21,7 +21,9 @@ package org.rhq.test.arquillian.impl.util;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
+import java.io.InputStream;
import java.util.Collection;
+import java.util.Properties;
import java.util.UUID;
import org.apache.commons.logging.Log;
@@ -56,18 +58,40 @@ public class SigarInstaller {
}
private void init() {
+
MavenDependencyResolver mavenDependencyResolver = DependencyResolvers.use(MavenDependencyResolver.class);
- // artifact specifier format is "<groupId>:<artifactId>[:<extension>[:<classifier>]][:<version >]"
- Collection<JavaArchive> sigars = mavenDependencyResolver
- .loadMetadataFromPom("pom.xml")
- .goOffline()
- // TODO (ips, 05/02/12): Figure out how to make this work without hard-coding the version.
- .artifact("org.hyperic:sigar-dist:zip:1.6.5.132-3")
- .resolveAs(JavaArchive.class);
+ // Read the desired properties from the Maven filtered resource file
+ Properties pomProperties = new Properties();
+ InputStream propertyFileInputStream = getClass().getClassLoader().getResourceAsStream(
+ "maven-properties.properties");
+ try {
+ pomProperties.load(propertyFileInputStream);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ } finally {
+ if (propertyFileInputStream != null) {
+ try {
+ propertyFileInputStream.close();
+ } catch (IOException ignore) {
+ }
+ }
+ }
+
+ String sigarVersion = pomProperties.getProperty("sigar.version");
+ if (sigarVersion == null) {
+ throw new RuntimeException("Could not read Sigar version from the properties file");
+ }
+
+ // Artifact specifier format is "<groupId>:<artifactId>[:<extension>[:<classifier>]][:<version >]"
+ String sigarArtifactCoordinates = "org.hyperic:sigar-dist:zip:" + sigarVersion;
+
+ Collection<JavaArchive> sigars = mavenDependencyResolver.loadMetadataFromPom("pom.xml").goOffline()
+ .artifact(sigarArtifactCoordinates).resolveAs(JavaArchive.class);
- if (sigars.size() > 1) {
- LOG.warn("More than 1 org.hyperic:sigar-dist artifact found in the current POM: " + sigars);
+ // The previous search can only find a single artifact (fully qualified)
+ if (sigars.size() != 1) {
+ throw new RuntimeException(sigarArtifactCoordinates + " search resolved to more than 1 artifact");
}
sigarDistArtifact = sigars.iterator().next();
diff --git a/modules/core/arquillian-integration/container/src/main/resources/maven-properties.properties b/modules/core/arquillian-integration/container/src/main/resources/maven-properties.properties
new file mode 100644
index 0000000..0eb80b4
--- /dev/null
+++ b/modules/core/arquillian-integration/container/src/main/resources/maven-properties.properties
@@ -0,0 +1,4 @@
+#This file helps test classes to load properties coming from Maven POM
+#It is filtered during the process-resources phase of a Maven build
+#Add the properties you need here
+sigar.version=${sigar.version}
\ No newline at end of file
diff --git a/modules/plugins/jboss-as-7/pom.xml b/modules/plugins/jboss-as-7/pom.xml
index 14ef20f..bee2bbb 100644
--- a/modules/plugins/jboss-as-7/pom.xml
+++ b/modules/plugins/jboss-as-7/pom.xml
@@ -330,12 +330,10 @@
<target>
<!-- Set as7.zipfile name before download -->
<property name="as7.zipfile" location="${java.io.tmpdir}/jboss-as7-${as7.version}.zip"/>
- <!-- Defensive clean -->
- <delete file="${as7.zipfile}" quiet="true" />
<!-- Defensive clean (jboss7.home is a POM property) -->
<delete dir="${jboss7.home}" quiet="true"/>
- <!-- Download as7 dist -->
- <get src="${as7.url}" dest="${as7.zipfile}" verbose="true"/>
+ <!-- Download as7 dist if not already present -->
+ <get src="${as7.url}" dest="${as7.zipfile}" usetimestamp="true" verbose="true" />
<!-- Unzip as7 dist to jboss7.home -->
<unzip src="${as7.zipfile}" dest="${jboss7.home}">
<!-- cutdirsmapper available since ANT 1.8.2. See http://ant.apache.org/manual/Types/mapper.html -->
@@ -367,7 +365,7 @@
</goals>
<configuration>
<target>
- <delete dir="${jboss7.home}" verbose="true"/>
+ <delete dir="${jboss7.home}" />
</target>
</configuration>
</execution>
10 years, 11 months
[rhq] Branch 'tsegismont/as7plugin-httpclient' - .classpath modules/plugins pom.xml
by Thomas Segismont
.classpath | 5 ++---
modules/plugins/jboss-as-7/pom.xml | 29 ++++++++++++++++-------------
pom.xml | 6 +++---
3 files changed, 21 insertions(+), 19 deletions(-)
New commits:
commit ea483e9ef52459aab8df12fd808627f4d5f9a0d2
Author: Thomas SEGISMONT <tsegismo(a)redhat.com>
Date: Sun Dec 23 14:54:29 2012 +0100
Make as7 integration test launch generic
diff --git a/.classpath b/.classpath
index f493247..2b8098f 100644
--- a/.classpath
+++ b/.classpath
@@ -194,8 +194,7 @@
<classpathentry exported="true" kind="var" path="M2_REPO/jboss/jboss-remoting/2.2.2.SP8/jboss-remoting-2.2.2.SP8.jar"/>
<classpathentry exported="true" kind="var" path="M2_REPO/oswego-concurrent/concurrent/1.3.4/concurrent-1.3.4.jar"/>
<classpathentry exported="true" kind="var" path="M2_REPO/rss4j/rss4j/0.92-on.2/rss4j-0.92-on.2.jar"/>
- <classpathentry exported="true" kind="var" path="M2_REPO/org/apache/ant/ant/1.8.0/ant-1.8.0.jar" sourcepath="M2_REPO/org/apache/ant/ant/1.8.0/ant-1.8.0-sources.jar"/>
- <classpathentry exported="true" kind="var" path="M2_REPO/org/apache/ant/ant-nodeps/1.8.0/ant-nodeps-1.8.0.jar"/>
+ <classpathentry exported="true" kind="var" path="M2_REPO/org/apache/ant/ant/1.8.2/ant-1.8.2.jar" sourcepath="M2_REPO/org/apache/ant/ant/1.8.0/ant-1.8.0-sources.jar"/>
<classpathentry exported="true" kind="var" path="M2_REPO/javax/servlet/servlet-api/2.4/servlet-api-2.4.jar"/>
<classpathentry exported="true" kind="var" path="M2_REPO/struts/struts/1.2.9/struts-1.2.9.jar"/>
<classpathentry exported="true" kind="var" path="M2_REPO/javax/servlet/jsp-api/2.0/jsp-api-2.0.jar"/>
@@ -220,7 +219,7 @@
<classpathentry exported="true" kind="var" path="M2_REPO/javax/xml/bind/jsr173_api/1.0/jsr173_api-1.0.jar"/>
<classpathentry exported="true" kind="var" path="M2_REPO/jboss/jbpm/3.1.1/jbpm-3.1.1.jar"/>
<classpathentry exported="true" kind="var" path="M2_REPO/org/jetbrains/annotations/7.0.2/annotations-7.0.2.jar"/>
- <classpathentry exported="true" kind="var" path="M2_REPO/org/apache/ant/ant-launcher/1.8.0/ant-launcher-1.8.0.jar"/>
+ <classpathentry exported="true" kind="var" path="M2_REPO/org/apache/ant/ant-launcher/1.8.2/ant-launcher-1.8.2.jar"/>
<classpathentry exported="true" kind="var" path="M2_REPO/cglib/cglib-nodep/2.1_3/cglib-nodep-2.1_3.jar"/>
<classpathentry exported="true" kind="var" path="M2_REPO/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar" sourcepath="/M2_REPO/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1-sources.jar"/>
<classpathentry exported="true" kind="var" path="M2_REPO/commons-lang/commons-lang/2.4/commons-lang-2.4.jar"/>
diff --git a/modules/plugins/jboss-as-7/pom.xml b/modules/plugins/jboss-as-7/pom.xml
index 6c9a833..14ef20f 100644
--- a/modules/plugins/jboss-as-7/pom.xml
+++ b/modules/plugins/jboss-as-7/pom.xml
@@ -328,19 +328,22 @@
</goals>
<configuration>
<target>
- <condition property="as7.product" value="eap" else="as">
- <matches pattern="^6\." string="${as7.version}"/>
- </condition>
- <property name="as7.zipfile"
- location="${java.io.tmpdir}/jboss-${as7.product}-${as7.version}.zip"/>
- <delete file="${as7.zipfile}"/>
- <get src="${as7.url}" dest="${as7.zipfile}" usetimestamp="true" verbose="true"/>
- <unzip src="${as7.zipfile}" dest="${java.io.tmpdir}"/>
- <!-- What was this supposed to do? Right now, it'd delete the AS7 deployment we just unzipped. -->
- <!-- <delete dir="${jboss7.home}" verbose="true"/> -->
- <move file="${java.io.tmpdir}/jboss-eap-6.0"
- tofile="${jboss7.home}" failonerror="false"/>
-
+ <!-- Set as7.zipfile name before download -->
+ <property name="as7.zipfile" location="${java.io.tmpdir}/jboss-as7-${as7.version}.zip"/>
+ <!-- Defensive clean -->
+ <delete file="${as7.zipfile}" quiet="true" />
+ <!-- Defensive clean (jboss7.home is a POM property) -->
+ <delete dir="${jboss7.home}" quiet="true"/>
+ <!-- Download as7 dist -->
+ <get src="${as7.url}" dest="${as7.zipfile}" verbose="true"/>
+ <!-- Unzip as7 dist to jboss7.home -->
+ <unzip src="${as7.zipfile}" dest="${jboss7.home}">
+ <!-- cutdirsmapper available since ANT 1.8.2. See http://ant.apache.org/manual/Types/mapper.html -->
+ <!-- All as7 dist zip files have a top level directory in their hierarchy -->
+ <!-- Sometimes this top level directory is not even named like the zip file (e.g. snapshot dists) -->
+ <!-- So we use the cutdirsmapper to extract as7 files straight to as7.home -->
+ <cutdirsmapper dirs="1"/>
+ </unzip>
<chmod perm="u+rx">
<fileset dir="${jboss7.home}/bin" includes="*.sh"/>
</chmod>
diff --git a/pom.xml b/pom.xml
index a1184e1..ae8ca49 100644
--- a/pom.xml
+++ b/pom.xml
@@ -680,11 +680,11 @@
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<dependencies>
- <!-- This includes all the "optional" tasks. -->
+ <!-- Standard ANT dist (no more "nodeps" since 1.8.2) -->
<dependency>
<groupId>org.apache.ant</groupId>
- <artifactId>ant-nodeps</artifactId>
- <version>1.8.1</version>
+ <artifactId>ant</artifactId>
+ <version>1.8.2</version>
</dependency>
<!-- This includes the <if> task, and a bunch of other handy tasks. -->
10 years, 11 months
[rhq] Branch 'refs/tags/RHQ_4_4_0_JON312CI' - 4 commits - modules/core modules/enterprise
by rhqci
modules/core/domain/intentional-api-changes-since-4.4.0.JON311GA.xml | 10 ++
modules/enterprise/agent/src/etc/rhq-agent.sh | 13 ++
modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java | 46 +++++++---
3 files changed, 57 insertions(+), 12 deletions(-)
New commits:
commit b17bd0074707cf101dcca638832734a1de2bbb6e
Author: Lukas Krejci <lkrejci(a)redhat.com>
Date: Thu Dec 20 00:18:51 2012 +0100
[BZ 880795] - The upgraded Augeas library no longer contains the file
"libaugeas.so", which causes the default native library lookup mechanisms
to fail. Standard ld should be able to find the .so.x.y files, too,
but the presence of java.library.path system property seems to be causing
this not to kick in during the library loading as done by the JVM.
To work around this problem, we need to instruct JNA to have a "backup
plan" in case the standard lookup mechanisms fail. This can be done using
the "jna.platform.library.path" system property, which instructs JNA to use
that path to look up libraries if everything else fails (and do the .so.x.y
resolution on its own).
We set this variable to the same value as we override LD_LIBRARY_PATH to
so that JNA library loading and native (as in system-wide) library loading
works the same for the agent process. This way we can load the JNA
libraries using the .so.x.y resolution the same way as the system resolves
the native libraries using stadard ld mechanisms in spite of there being
the java.library.path variable set (which is needed by SIGAR).
(cherry picked from commit e437f5771c4b79ce570ad24cb3c545078d9a944a)
diff --git a/modules/enterprise/agent/src/etc/rhq-agent.sh b/modules/enterprise/agent/src/etc/rhq-agent.sh
index e80581d..b3ee8a7 100755
--- a/modules/enterprise/agent/src/etc/rhq-agent.sh
+++ b/modules/enterprise/agent/src/etc/rhq-agent.sh
@@ -212,7 +212,9 @@ fi
debug_msg "RHQ_AGENT_CMDLINE_OPTS: $RHQ_AGENT_CMDLINE_OPTS"
# ----------------------------------------------------------------------
-# Prepare LD_LIBRARY_PATH to include libraries shipped with the agent
+# Prepare LD_LIBRARY_PATH to include libraries shipped with the agent and
+# prepare jna.platform.library.path for JNA to be able to load augeas from our
+# custom location.
# ----------------------------------------------------------------------
if [ -n "$_LINUX" ]; then
@@ -230,6 +232,13 @@ if [ -n "$_LINUX" ]; then
fi
fi
export LD_LIBRARY_PATH
+
+ # We need to force our custom library path as the "system" look up path to
+ # JNA. Without this, the lookup of .so.x.y versions wouldn't work.
+ # We also need to keep the LD_LIBRARY_PATH in place so that the default
+ # system lookup works for libfa, which libaugeas depends on.
+ _JNA_LIBRARY_PATH="\"-Djna.platform.library.path=${LD_LIBRARY_PATH}\""
+
debug_msg "LD_LIBRARY_PATH: $LD_LIBRARY_PATH"
fi
@@ -265,7 +274,7 @@ if [ -z "$RHQ_AGENT_MAINCLASS" ]; then
fi
# Build the command line that starts the VM
-CMD="\"${RHQ_AGENT_JAVA_EXE_FILE_PATH}\" ${_JAVA_ENDORSED_DIRS_OPT} ${_JAVA_LIBRARY_PATH_OPT} ${RHQ_AGENT_JAVA_OPTS} ${RHQ_AGENT_ADDITIONAL_JAVA_OPTS} ${_LOG_CONFIG} -cp \"${CLASSPATH}\" ${RHQ_AGENT_MAINCLASS} ${RHQ_AGENT_CMDLINE_OPTS}"
+CMD="\"${RHQ_AGENT_JAVA_EXE_FILE_PATH}\" ${_JAVA_ENDORSED_DIRS_OPT} ${_JAVA_LIBRARY_PATH_OPT} ${_JNA_LIBRARY_PATH} ${RHQ_AGENT_JAVA_OPTS} ${RHQ_AGENT_ADDITIONAL_JAVA_OPTS} ${_LOG_CONFIG} -cp \"${CLASSPATH}\" ${RHQ_AGENT_MAINCLASS} ${RHQ_AGENT_CMDLINE_OPTS}"
debug_msg "Executing the agent with this command line:"
debug_msg "$CMD"
commit 8623993dd46785e359383c0cc54dc51c168d0c96
Author: John Sanda <jsanda(a)redhat.com>
Date: Wed Dec 19 10:00:20 2012 -0500
fixing a few issues with test failures
Test clean was failing because we were not purging the resource from the db.
The uuid constant in the test class did not match the one actually used.
When setting the uuid, Resource pads it out to 36 characters.
The other issue involves dealing with decimal precision. I have added a
function to use up to 4 decimal places.
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java
index cbbbdaf..b40efbe 100644
--- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java
+++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java
@@ -31,10 +31,14 @@ import static org.rhq.core.domain.measurement.NumericType.DYNAMIC;
import static org.rhq.core.domain.resource.ResourceCategory.SERVER;
import static org.rhq.test.AssertUtils.assertPropertiesMatch;
+import java.math.BigDecimal;
+import java.math.MathContext;
+import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
+import java.text.DecimalFormat;
import java.util.Collections;
import java.util.List;
@@ -91,7 +95,7 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test {
private final String RESOURCE_NAME = getClass().getName() + "_NAME";
- private final String RESOURCE_UUID = getClass().getSimpleName() + "_UUID";
+ private final String RESOURCE_UUID = "MeasurementDataManagerBeanTest_UUID ";
private ResourceType resourceType;
@@ -114,7 +118,7 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test {
insertDummyReport();
}
- @AfterMethod
+ @AfterMethod(alwaysRun = true)
public void tearDown() {
purgeDB();
}
@@ -146,17 +150,17 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test {
assertEquals("Expected to get back 60 data points.", buckets.getNumDataPoints(), actualData.size());
MeasurementDataNumericHighLowComposite expectedBucket0Data = new MeasurementDataNumericHighLowComposite(
- buckets.get(0), (1.1 + 2.2 + 3.3) / 3, 3.3, 1.1);
+ buckets.get(0), divide(1.1 + 2.2 + 3.3, 3), 3.3, 1.1);
MeasurementDataNumericHighLowComposite expectedBucket59Data = new MeasurementDataNumericHighLowComposite(
- buckets.get(59), (4.4 + 5.5 + 6.6) / 3, 6.6, 4.4);
+ buckets.get(59), divide(4.4 + 5.5 + 6.6, 3), 6.6, 4.4);
MeasurementDataNumericHighLowComposite expectedBucket29Data = new MeasurementDataNumericHighLowComposite(
buckets.get(29), Double.NaN, Double.NaN, Double.NaN);
- assertPropertiesMatch("The data for bucket 0 does not match the expected values.", expectedBucket0Data,
+ assertMeasurementDataMatches("The data for bucket 0 does not match the expected values.", expectedBucket0Data,
actualData.get(0));
- assertPropertiesMatch("The data for bucket 59 does not match the expected values.", expectedBucket59Data,
+ assertMeasurementDataMatches("The data for bucket 59 does not match the expected values.", expectedBucket59Data,
actualData.get(59));
- assertPropertiesMatch("The data for bucket 29 does not match the expected values.", expectedBucket29Data,
+ assertMeasurementDataMatches("The data for bucket 29 does not match the expected values.", expectedBucket29Data,
actualData.get(29));
}
@@ -191,16 +195,38 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test {
assertEquals("Expected to get back 60 data points.", buckets.getNumDataPoints(), actualData.size());
MeasurementDataNumericHighLowComposite expectedBucket0Data = new MeasurementDataNumericHighLowComposite(
- buckets.get(0), (2.0 + 5.0 + 3.0) / 3, 6.0, 1.0);
+ buckets.get(0), divide(2.0 + 5.0 + 3.0, 3), 6.0, 1.0);
MeasurementDataNumericHighLowComposite expectedBucket59Data = new MeasurementDataNumericHighLowComposite(
- buckets.get(59), (5.0 + 5.0 + 3.0) / 3, 9.0, 2.0);
+ buckets.get(59), divide(5.0 + 5.0 + 3.0, 3), 9.0, 2.0);
- assertPropertiesMatch("The data for bucket 0 does not match the expected values.", expectedBucket0Data,
+ assertMeasurementDataMatches("The data for bucket 0 does not match the expected values.", expectedBucket0Data,
actualData.get(0));
assertPropertiesMatch("The data for bucket 59 does not match the expected values.", expectedBucket59Data,
actualData.get(59));
}
+ private void assertMeasurementDataMatches(String msg, MeasurementDataNumericHighLowComposite expected,
+ MeasurementDataNumericHighLowComposite actual) {
+
+ if (Double.isNaN(expected.getValue())) {
+ assertPropertiesMatch(msg, expected, actual);
+ } else {
+ assertPropertiesMatch(msg, expected, actual, "value");
+
+ DecimalFormat df = new DecimalFormat("#########0.0000");
+ MathContext context = new MathContext(16, RoundingMode.CEILING);
+ BigDecimal expectedValue = new BigDecimal(df.format(expected.getValue()), context);
+ BigDecimal actualValue = new BigDecimal(df.format(actual.getValue()), context);
+
+ assertEquals(msg + " - The average value does not match.", expectedValue, actualValue);
+ }
+ }
+
+ private double divide(double dividend, int divisor) {
+ return new BigDecimal(Double.toString(dividend)).divide(new BigDecimal(Integer.toString(divisor)),
+ MathContext.DECIMAL64).doubleValue();
+ }
+
private void createInventory() throws Exception {
purgeDB();
executeInTransaction(new TransactionCallback() {
@@ -287,7 +313,6 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test {
.setParameter("key", RESOURCE_KEY)
.setParameter("uuid", RESOURCE_UUID)
.executeUpdate();
- em.flush();
}
private void deleteMeasurementSchedules(EntityManager em) {
commit 0ecbebbf556353cd4b5aadef7e9e62e9a09ffcc0
Author: John Sanda <jsanda(a)redhat.com>
Date: Tue Dec 18 10:29:17 2012 -0500
trying to resolve oracle test failure
We are hitting a constraint violation when attemtping to delete the agent
record, even though we have already executed a statement to delete the
resource. Adding call to EntityManager.flush after deleting the resource to
ensure that the resource deletion is performed prior to deleting the agent.
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java
index 96a72ed..cbbbdaf 100644
--- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java
+++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java
@@ -287,6 +287,7 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test {
.setParameter("key", RESOURCE_KEY)
.setParameter("uuid", RESOURCE_UUID)
.executeUpdate();
+ em.flush();
}
private void deleteMeasurementSchedules(EntityManager em) {
commit 17ea914e821eb2ec331c8fe454e5793bb4b2f856
Author: Simeon Pinder <spinder(a)fulliautomatix.conchfritter.com>
Date: Mon Dec 17 14:00:37 2012 -0500
[BZ 878661] add justification for reverting unintentional api changes.
diff --git a/modules/core/domain/intentional-api-changes-since-4.4.0.JON311GA.xml b/modules/core/domain/intentional-api-changes-since-4.4.0.JON311GA.xml
new file mode 100644
index 0000000..427b809
--- /dev/null
+++ b/modules/core/domain/intentional-api-changes-since-4.4.0.JON311GA.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0"?>
+<differences>
+ <difference>
+ <className>org/rhq/core/domain/configuration/definition/PropertyDefinitionMap</className>
+ <differenceType>7006</differenceType><!-- return type changed -->
+ <method>java.util.List getPropertyDefinitions()</method>
+ <to>java.util.Map</to>
+ <justification>[BZ 878661] reverting unintentional api changes.</justification>
+ </difference>
+</differences>
10 years, 11 months
[rhq] Branch 'feature/cassandra-backend' - 3 commits - modules/enterprise
by snegrea
modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/ArithmeticMeanCalculator.java | 44 ++
modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/Buckets.java | 7
modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricBaselineCalculator.java | 28 +
modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsDAO.java | 151 +++++-----
modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsServer.java | 21 -
modules/enterprise/server/server-metrics/src/test/java/org/rhq/server/metrics/MetricsServerTest.java | 7
6 files changed, 157 insertions(+), 101 deletions(-)
New commits:
commit 3ecbfcab546406684dbbe49a840a6e9bc26a0a57
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Fri Dec 21 17:39:45 2012 -0600
Update existing average calculations to use the rolling algorithm to prevent overflow. Move the initial implementation to the test class to check for rolling algorithm correctness.
diff --git a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/Buckets.java b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/Buckets.java
index bcac61a..db96b80 100644
--- a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/Buckets.java
+++ b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/Buckets.java
@@ -38,7 +38,7 @@ public class Buckets {
// end time is exclusive
private long endTime;
- private double sum;
+ private ArithmeticMeanCalculator mean;
private double max;
private double min;
private int count;
@@ -46,6 +46,7 @@ public class Buckets {
public Bucket(long startTime, long endTime) {
this.startTime = startTime;
this.endTime = endTime;
+ this.mean = new ArithmeticMeanCalculator();
}
public long getStartTime() {
@@ -57,7 +58,7 @@ public class Buckets {
}
public Bucket insert(double value) {
- sum += value;
+ mean.add(value);
if (count == 0) {
min = value;
max = value;
@@ -74,7 +75,7 @@ public class Buckets {
if (count == 0) {
return Double.NaN;
}
- return MetricsServer.divide(sum, count);
+ return mean.getArithmeticMean();
}
public double getMax() {
diff --git a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsServer.java b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsServer.java
index 33c6a13..0c5f329 100644
--- a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsServer.java
+++ b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsServer.java
@@ -27,8 +27,6 @@ package org.rhq.server.metrics;
import static org.rhq.core.domain.util.PageOrdering.DESC;
-import java.math.BigDecimal;
-import java.math.MathContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -265,8 +263,8 @@ public class MetricsServer {
private AggregatedNumericMetric calculateAggregatedRaw(List<RawNumericMetric> rawMetrics, long timestamp) {
double min = Double.NaN;
double max = min;
- double sum = 0;
int count = 0;
+ ArithmeticMeanCalculator mean = new ArithmeticMeanCalculator();
double value;
for (RawNumericMetric metric : rawMetrics) {
@@ -280,14 +278,13 @@ public class MetricsServer {
} else if (value > max) {
max = value;
}
- sum += value;
+ mean.add(value);
++count;
}
- double avg = divide(sum, count);
// We let the caller handle setting the schedule id because in some cases we do
// not care about it.
- return new AggregatedNumericMetric(0, avg, min, max, timestamp);
+ return new AggregatedNumericMetric(0, mean.getArithmeticMean(), min, max, timestamp);
}
private List<AggregatedNumericMetric> calculateAggregates(MetricsTable fromColumnFamily,
@@ -322,8 +319,8 @@ public class MetricsServer {
private AggregatedNumericMetric calculateAggregate(List<AggregatedNumericMetric> metrics, long timestamp) {
double min = Double.NaN;
double max = min;
- double sum = 0;
int count = 0;
+ ArithmeticMeanCalculator mean = new ArithmeticMeanCalculator();
for (AggregatedNumericMetric metric : metrics) {
if (count == 0) {
@@ -335,14 +332,13 @@ public class MetricsServer {
} else if (metric.getMax() > max) {
max = metric.getMax();
}
- sum += metric.getAvg();
+ mean.add(metric.getAvg());
++count;
}
- double avg = divide(sum, count);
// We let the caller handle setting the schedule id because in some cases we do
// not care about it.
- return new AggregatedNumericMetric(0, avg, min, max, timestamp);
+ return new AggregatedNumericMetric(0, mean.getArithmeticMean(), min, max, timestamp);
}
private MetricsTable getTable(DateTime begin) {
@@ -386,11 +382,6 @@ public class MetricsServer {
// public void addCallTimeData(Set<CallTimeData> callTimeDatas) {
// }
- static double divide(double dividend, int divisor) {
- return new BigDecimal(Double.toString(dividend)).divide(new BigDecimal(Integer.toString(divisor)),
- MathContext.DECIMAL64).doubleValue();
- }
-
protected DateTime getCurrentHour() {
DateTime now = new DateTime();
return now.hourOfDay().roundFloorCopy();
diff --git a/modules/enterprise/server/server-metrics/src/test/java/org/rhq/server/metrics/MetricsServerTest.java b/modules/enterprise/server/server-metrics/src/test/java/org/rhq/server/metrics/MetricsServerTest.java
index ca6dd95..2c76e45 100644
--- a/modules/enterprise/server/server-metrics/src/test/java/org/rhq/server/metrics/MetricsServerTest.java
+++ b/modules/enterprise/server/server-metrics/src/test/java/org/rhq/server/metrics/MetricsServerTest.java
@@ -27,12 +27,13 @@ package org.rhq.server.metrics;
import static java.util.Arrays.asList;
import static org.joda.time.DateTime.now;
-import static org.rhq.server.metrics.MetricsServer.divide;
import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder;
import static org.rhq.test.AssertUtils.assertPropertiesMatch;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
+import java.math.BigDecimal;
+import java.math.MathContext;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -757,4 +758,8 @@ public class MetricsServerTest extends CassandraIntegrationTest {
assertEquals(index.size(), 0, "Expected metrics index for " + table + " to be empty but found " + index);
}
+ static double divide(double dividend, int divisor) {
+ return new BigDecimal(Double.toString(dividend)).divide(new BigDecimal(Integer.toString(divisor)),
+ MathContext.DECIMAL64).doubleValue();
+ }
}
commit b0134d8673127e0023e37d06bb2c443e9e701d66
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Fri Dec 21 17:23:09 2012 -0600
Improve baseline calculation performance by quering for raw min and max. Also updated the average algorithm to use rolling calculations to prevent overflows (due to addition).
diff --git a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/ArithmeticMeanCalculator.java b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/ArithmeticMeanCalculator.java
new file mode 100644
index 0000000..dfba260
--- /dev/null
+++ b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/ArithmeticMeanCalculator.java
@@ -0,0 +1,44 @@
+/*
+ * RHQ Management Platform
+ * Copyright 2011, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+package org.rhq.server.metrics;
+
+/**
+ * @author Stefan Negrea
+ *
+ */
+public class ArithmeticMeanCalculator {
+ private int iterations = 0;
+ private double arithmeticMean = 0;
+
+ public void add(double value) {
+ iterations++;
+ arithmeticMean = arithmeticMean + (value - arithmeticMean) / iterations;
+ }
+
+ public double getArithmeticMean() {
+ return arithmeticMean;
+ }
+
+ public void reset() {
+ iterations = 0;
+ arithmeticMean = 0;
+ }
+}
diff --git a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricBaselineCalculator.java b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricBaselineCalculator.java
index b8a97c2..c3322e8 100644
--- a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricBaselineCalculator.java
+++ b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricBaselineCalculator.java
@@ -30,6 +30,7 @@ import java.util.List;
import com.datastax.driver.core.Session;
import org.rhq.core.domain.measurement.MeasurementBaseline;
+import org.rhq.core.domain.util.PageOrdering;
/**
* @author Stefan Negrea
@@ -57,30 +58,33 @@ public class MetricBaselineCalculator {
}
private MeasurementBaseline calculateBaseline(Integer scheduleId, long startTime, long endTime) {
-
List<AggregatedNumericMetric> metrics = this.metricsDAO.findAggregateMetrics(MetricsTable.ONE_HOUR, scheduleId, startTime, endTime);
if (metrics.size() != 0) {
- double min = metrics.get(0).getMin();
- double max = metrics.get(0).getMax();
- double average = 0;
+ ArithmeticMeanCalculator mean = new ArithmeticMeanCalculator();
for (AggregatedNumericMetric entry : metrics) {
- if (entry.getMax() > max) {
- max = entry.getMax();
- } else if (entry.getMin() < min) {
- min = entry.getMin();
- }
+ mean.add(entry.getAvg());
+ }
- average += entry.getAvg();
+ double min = Double.MIN_VALUE;
+ List<Double> results = this.metricsDAO.findAggregateSimpleMetric(MetricsTable.ONE_HOUR, AggregateType.MIN,
+ scheduleId, startTime, endTime, PageOrdering.ASC, 1);
+ if(results.size() != 0){
+ min = results.get(0);
}
- average = average / (double) metrics.size();
+ double max = Double.MAX_VALUE;
+ results = this.metricsDAO.findAggregateSimpleMetric(MetricsTable.ONE_HOUR, AggregateType.MAX, scheduleId,
+ startTime, endTime, PageOrdering.DESC, 1);
+ if (results.size() != 0) {
+ max = results.get(0);
+ }
MeasurementBaseline baseline = new MeasurementBaseline();
baseline.setMax(max);
baseline.setMin(min);
- baseline.setMean(average);
+ baseline.setMean(mean.getArithmeticMean());
baseline.setScheduleId(scheduleId);
return baseline;
commit 2ed670d98a66143923a9af78db5e41b823cbfc25
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Fri Dec 21 17:17:43 2012 -0600
Update metrics dao to use prepared statements as much as possible with the current driver.
diff --git a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsDAO.java b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsDAO.java
index dfdfd14..8d4855b 100644
--- a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsDAO.java
+++ b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/MetricsDAO.java
@@ -25,10 +25,6 @@
package org.rhq.server.metrics;
-import static com.datastax.driver.core.utils.querybuilder.Clause.eq;
-import static com.datastax.driver.core.utils.querybuilder.Clause.gte;
-import static com.datastax.driver.core.utils.querybuilder.Clause.lt;
-import static com.datastax.driver.core.utils.querybuilder.QueryBuilder.select;
import static org.rhq.core.util.StringUtil.listToString;
import java.util.ArrayList;
@@ -59,10 +55,20 @@ public class MetricsDAO {
//
// jsanda
+ private static final String RAW_METRICS_SIMPLE_QUERY =
+ "SELECT schedule_id, time, value " +
+ "FROM " + MetricsTable.RAW + " " +
+ "WHERE schedule_id = ? ORDER by time";
+
private static final String RAW_METRICS_QUERY =
"SELECT schedule_id, time, value " +
"FROM " + MetricsTable.RAW + " " +
- "WHERE schedule_id = ? AND time >= ? AND time < ?";
+ "WHERE schedule_id = ? AND time >= ? AND time < ? ORDER BY time";
+
+ private static final String RAW_METRICS_SCHEDULE_LIST_QUERY =
+ "SELECT schedule_id, time, value " +
+ "FROM " + MetricsTable.RAW + " " +
+ "WHERE schedule_id IN (?) AND time >= ? AND time < ? ORDER BY time";
private static final String RAW_METRICS_WITH_METADATA_QUERY =
"SELECT schedule_id, time, value, ttl(value), writetime(value) " +
@@ -88,22 +94,19 @@ public class MetricsDAO {
this.session = session;
}
- public void setSession(Session session) {
- this.session = session;
- }
-
public Set<MeasurementDataNumeric> insertRawMetrics(Set<MeasurementDataNumeric> dataSet, int ttl) {
- Set<MeasurementDataNumeric> insertedMetrics = new HashSet<MeasurementDataNumeric>();
- String sql = "INSERT INTO raw_metrics (schedule_id, time, value) VALUES (?, ?, ?) " +
- "USING TTL " + ttl;
try {
- PreparedStatement statement = session.prepare(sql);
+ String cql = "INSERT INTO raw_metrics (schedule_id, time, value) VALUES (?, ?, ?) " + "USING TTL " + ttl;
+ PreparedStatement statement = session.prepare(cql);
+
+ Set<MeasurementDataNumeric> insertedMetrics = new HashSet<MeasurementDataNumeric>();
for (MeasurementDataNumeric data : dataSet) {
BoundStatement boundStatement = statement.bind(data.getScheduleId(), new Date(data.getTimestamp()),
data.getValue());
session.execute(boundStatement);
insertedMetrics.add(data);
}
+
return insertedMetrics;
} catch (NoHostAvailableException e) {
throw new CQLException(e);
@@ -133,6 +136,7 @@ public class MetricsDAO {
updates.add(metric);
}
+
return updates;
} catch (NoHostAvailableException e) {
throw new CQLException(e);
@@ -141,17 +145,16 @@ public class MetricsDAO {
public List<RawNumericMetric> findRawMetrics(int scheduleId, long startTime, long endTime) {
try {
- List<RawNumericMetric> metrics = new ArrayList<RawNumericMetric>();
-
- String cql = "SELECT schedule_id, time, value FROM " + MetricsTable.RAW + " WHERE schedule_id = "
- + scheduleId + " AND time >= " + startTime + " AND time < " + endTime
- + " ORDER BY time";
+ PreparedStatement statement = session.prepare(RAW_METRICS_QUERY);
+ BoundStatement boundStatement = statement.bind(scheduleId, new Date(startTime), new Date(endTime));
+ ResultSet resultSet = session.execute(boundStatement);
- ResultSet resultSet = session.execute(cql);
+ List<RawNumericMetric> metrics = new ArrayList<RawNumericMetric>();
ResultSetMapper<RawNumericMetric> resultSetMapper = new RawNumericMetricMapper();
for (Row row : resultSet) {
metrics.add(resultSetMapper.map(row));
}
+
return metrics;
} catch (NoHostAvailableException e) {
throw new CQLException(e);
@@ -160,16 +163,15 @@ public class MetricsDAO {
public List<RawNumericMetric> findRawMetrics(int scheduleId, PageOrdering ordering, int limit) {
try {
- List<RawNumericMetric> metrics = new ArrayList<RawNumericMetric>();
-
- String cql = "SELECT schedule_id, time, value FROM " + MetricsTable.RAW + " WHERE schedule_id = " +
- scheduleId + " ORDER BY time " + ordering;
-
+ String cql = RAW_METRICS_SIMPLE_QUERY + " " + ordering;
if (limit > 0) {
cql += " LIMIT " + limit;
}
+ PreparedStatement statement = session.prepare(cql);
+ BoundStatement boundStatement = statement.bind(scheduleId);
+ ResultSet resultSet = session.execute(boundStatement);
- ResultSet resultSet = session.execute(cql);
+ List<RawNumericMetric> metrics = new ArrayList<RawNumericMetric>();
ResultSetMapper<RawNumericMetric> resultSetMapper = new RawNumericMetricMapper();
for (Row row : resultSet) {
metrics.add(resultSetMapper.map(row));
@@ -188,15 +190,10 @@ public class MetricsDAO {
}
try {
- ResultSet resultSet = session.execute(
- select("schedule_id", "time", "value", "ttl(value), writetime(value)")
- .from(MetricsTable.RAW.toString())
- .where(
- eq("schedule_id", scheduleId),
- gte("time", new Date(startTime)),
- lt("time", new Date(endTime)))
- .getQueryString()
- );
+ PreparedStatement statement = session.prepare(RAW_METRICS_WITH_METADATA_QUERY);
+ BoundStatement boundStatement = statement.bind(scheduleId, new Date(startTime), new Date(endTime));
+ ResultSet resultSet = session.execute(boundStatement);
+
List<RawNumericMetric> metrics = new ArrayList<RawNumericMetric>();
ResultSetMapper<RawNumericMetric> resultSetMapper = new RawNumericMetricMapper(true);
for (Row row : resultSet) {
@@ -214,25 +211,14 @@ public class MetricsDAO {
// I was not able to get the below query working by directly binding the List
// object. From a quick glance at the driver code, it looks like it might not
// yet be properly supported in which case we need to report a bug.
- //
// jsanda
-// String cql = "SELECT schedule_id, time, value FROM " + RAW_METRICS_TABLE +
-// " WHERE schedule_id IN (?) AND time >= ? AND time < ? ORDER BY time";
-// PreparedStatement statement = session.prepare(cql);
-// BoundStatement boundStatement = statement.bind(scheduleIds, startTime.toDate(), endTime.toDate());
-// ResultSet resultSet = session.execute(boundStatement);
-// String cql =
-// select("schedule_id", "time", "value")
-// .from(RAW_METRICS_TABLE)
-// .where(
-// in("schedule_id", listToString(scheduleIds)),
-// gte("time", startTime.toDate()),
-// lt("time", endTime.toDate()))
-// .getQueryString();
-
- String cql = "SELECT schedule_id, time, value FROM " + MetricsTable.RAW + " WHERE schedule_id IN (" +
- listToString(scheduleIds) + ") AND time >= " + startTime + " AND time <= " + endTime;
+ //PreparedStatement statement = session.prepare(RAW_METRICS_SCHEDULE_LIST_QUERY);
+ //BoundStatement boundStatement = statement.bind(scheduleIds, startTime, endTime);
+ //ResultSet resultSet = session.execute(boundStatement);
+
+ String cql = "SELECT schedule_id, time, value FROM " + MetricsTable.RAW + " WHERE schedule_id IN ("
+ + listToString(scheduleIds) + ") AND time >= " + startTime + " AND time <= " + endTime;
ResultSet resultSet = session.execute(cql);
List<RawNumericMetric> metrics = new ArrayList<RawNumericMetric>();
@@ -240,6 +226,7 @@ public class MetricsDAO {
for (Row row : resultSet) {
metrics.add(resultSetMapper.map(row));
}
+
return metrics;
} catch (NoHostAvailableException e) {
throw new CQLException(e);
@@ -251,12 +238,14 @@ public class MetricsDAO {
String cql =
"SELECT schedule_id, time, type, value " +
"FROM " + table + " " +
- "WHERE schedule_id = " + scheduleId + " " +
+ "WHERE schedule_id = ? " +
"ORDER BY time, type";
+ PreparedStatement statement = session.prepare(cql);
+ BoundStatement boundStatement = statement.bind(scheduleId);
+ ResultSet resultSet = session.execute(boundStatement);
+
List<AggregatedNumericMetric> metrics = new ArrayList<AggregatedNumericMetric>();
ResultSetMapper<AggregatedNumericMetric> resultSetMapper = new AggregateMetricMapper();
- ResultSet resultSet = session.execute(cql);
-
while (!resultSet.isExhausted()) {
metrics.add(resultSetMapper.map(resultSet.fetchOne(), resultSet.fetchOne(), resultSet.fetchOne()));
}
@@ -274,12 +263,13 @@ public class MetricsDAO {
String cql =
"SELECT schedule_id, time, type, value " +
"FROM " + table + " " +
- "WHERE schedule_id = "
- + scheduleId + " AND time >= " + startTime + " AND time < " + endTime;
+ "WHERE schedule_id = ? AND time >= ? AND time < ?";
+ PreparedStatement statement = session.prepare(cql);
+ BoundStatement boundStatement = statement.bind(scheduleId, new Date(startTime), new Date(endTime));
+ ResultSet resultSet = session.execute(boundStatement);
+
List<AggregatedNumericMetric> metrics = new ArrayList<AggregatedNumericMetric>();
ResultSetMapper<AggregatedNumericMetric> resultSetMapper = new AggregateMetricMapper();
- ResultSet resultSet = session.execute(cql);
-
while (!resultSet.isExhausted()) {
metrics.add(resultSetMapper.map(resultSet.fetchOne(), resultSet.fetchOne(), resultSet.fetchOne()));
}
@@ -290,18 +280,38 @@ public class MetricsDAO {
}
}
+ public List<Double> findAggregateSimpleMetric(MetricsTable table, AggregateType type, int scheduleId,
+ long startTime, long endTime, PageOrdering ordering, int limit) {
+ try {
+ String cql = "SELECT schedule_id, time, type, value " + "FROM " + table + " "
+ + "WHERE schedule_id = ? AND time >= ? AND time < ? AND type = ? "
+ + "ORDER BY value " + ordering + " LIMIT " + limit;
+ PreparedStatement statement = session.prepare(cql);
+ BoundStatement boundStatement = statement.bind(scheduleId, new Date(startTime), new Date(endTime),
+ type.ordinal());
+ ResultSet resultSet = session.execute(boundStatement);
+
+ List<Double> metrics = new ArrayList<Double>();
+ while (!resultSet.isExhausted()) {
+ metrics.add(resultSet.fetchOne().getDouble(3));
+ }
+
+ return metrics;
+ } catch (NoHostAvailableException e) {
+ throw new CQLException(e);
+ }
+ }
+
public List<AggregatedNumericMetric> findAggregateMetrics(MetricsTable table, List<Integer> scheduleIds,
long startTime, long endTime) {
try {
String cql =
- "SELECT schedule_id, time, type, value " +
- "FROM " + table + " " +
- "WHERE schedule_id IN ("
- + listToString(scheduleIds) + ") AND time >= " + startTime + " AND time < " + endTime;
- List<AggregatedNumericMetric> metrics = new ArrayList<AggregatedNumericMetric>();
- ResultSetMapper<AggregatedNumericMetric> resultSetMapper = new AggregateMetricMapper();
+ "SELECT schedule_id, time, type, value FROM " + table + " " +
+ "WHERE schedule_id IN (" + listToString(scheduleIds) + ") AND time >= " + startTime + " AND time < " + endTime;
ResultSet resultSet = session.execute(cql);
+ List<AggregatedNumericMetric> metrics = new ArrayList<AggregatedNumericMetric>();
+ ResultSetMapper<AggregatedNumericMetric> resultSetMapper = new AggregateMetricMapper();
while (!resultSet.isExhausted()) {
metrics.add(resultSetMapper.map(resultSet.fetchOne(), resultSet.fetchOne(), resultSet.fetchOne()));
}
@@ -312,19 +322,20 @@ public class MetricsDAO {
}
}
- List<AggregatedNumericMetric> findAggregateMetricsWithMetadata(MetricsTable table, int scheduleId,
+ public List<AggregatedNumericMetric> findAggregateMetricsWithMetadata(MetricsTable table, int scheduleId,
long startTime, long endTime) {
try {
String cql =
"SELECT schedule_id, time, type, value, ttl(value), writetime(value) " +
"FROM " + table + " " +
- "WHERE schedule_id = " + scheduleId + " AND time >= " + startTime +
- " AND time < " + endTime;
+ "WHERE schedule_id = ? AND time >= ? AND time < ?";
+ PreparedStatement statement = session.prepare(cql);
+ BoundStatement boundStatement = statement.bind(scheduleId, new Date(startTime), new Date(endTime));
+ ResultSet resultSet = session.execute(boundStatement);
+
List<AggregatedNumericMetric> metrics = new ArrayList<AggregatedNumericMetric>();
ResultSetMapper<AggregatedNumericMetric> resultSetMapper = new AggregateMetricMapper(true);
- ResultSet resultSet = session.execute(cql);
-
while (!resultSet.isExhausted()) {
metrics.add(resultSetMapper.map(resultSet.fetchOne(), resultSet.fetchOne(), resultSet.fetchOne()));
}
@@ -340,9 +351,9 @@ public class MetricsDAO {
PreparedStatement statement = session.prepare(METRICS_INDEX_QUERY);
BoundStatement boundStatement = statement.bind(table.toString());
ResultSet resultSet = session.execute(boundStatement);
+
List<MetricsIndexEntry> indexEntries = new ArrayList<MetricsIndexEntry>();
ResultSetMapper<MetricsIndexEntry> resultSetMapper = new MetricsIndexResultSetMapper(table);
-
for (Row row : resultSet) {
indexEntries.add(resultSetMapper.map(row));
}
10 years, 11 months
[rhq] 4 commits - modules/common modules/enterprise
by mazz
modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java | 71 +++++-
modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/WebJBossASClient.java | 14 +
modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/Installer.java | 28 ++
modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerService.java | 15 +
modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java | 52 ++++
modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java | 116 +++++-----
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CustomJaasDeploymentService.java | 2
7 files changed, 228 insertions(+), 70 deletions(-)
New commits:
commit 45a58220880d1a0b4749af319d8065936f734a57
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Fri Dec 21 17:36:27 2012 -0500
can't just reload at the end, need to restart - our Mbeans don't go away on just a reload, so we must restart
diff --git a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java
index 4b5e4b8..4ff3e4c 100644
--- a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java
+++ b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java
@@ -569,9 +569,9 @@ public class InstallerServiceImpl implements InstallerService {
// create a keystore whose cert has a CN of this server's public endpoint address
ServerInstallUtil.setupWebConnectors(mcc, appServerConfigDir, serverProperties);
- // now reload out of admin mode to pick up the changes
+ // now restart - don't just reload, some of our stuff won't restart properly if we just reload
coreClient = new CoreJBossASClient(mcc);
- coreClient.reload(false);
+ coreClient.restart();
} finally {
safeClose(mcc);
}
commit 3d9d1ece7431fe738e08655edbe46649be9559c5
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Fri Dec 21 17:04:03 2012 -0500
add code to update SecureIdentity security domain credentials
add code to remove web connector
skip adding default mgmt user if it already exists
add installer --reconfig feature to update AS7 settings based on new rhq-server.properties settings
diff --git a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java
index 0b4597c..e101de3 100644
--- a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java
+++ b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java
@@ -106,6 +106,53 @@ public class SecurityDomainJBossASClient extends JBossASClient {
}
/**
+ * Given the name of an existing security domain that uses the SecureIdentity authentication method,
+ * this updates that domain with the new credentials. Use this to change credentials if you don't
+ * want to use expressions as the username or password entry (in some cases you can't, see the JIRA
+ * https://issues.jboss.org/browse/AS7-5177 for more info).
+ *
+ * @param securityDomainName the name of the security domain whose credentials are to change
+ * @param username the new username to be associated with the security domain
+ * @param password the new value of the password to store in the configuration (e.g. the obfuscated password itself)
+ *
+ * @throws Exception if failed to update security domain
+ */
+ public void updateSecureIdentitySecurityDomainCredentials(String securityDomainName, String username,
+ String password) throws Exception {
+
+ Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_SECURITY, SECURITY_DOMAIN, securityDomainName,
+ AUTHENTICATION, CLASSIC);
+
+ ModelNode loginModule = new ModelNode();
+ loginModule.get(CODE).set("SecureIdentity");
+ loginModule.get(FLAG).set("required");
+ ModelNode moduleOptions = loginModule.get(MODULE_OPTIONS);
+ moduleOptions.setEmptyList();
+ // TODO: we really want to use addExpression (e.g. ${rhq.server.database.user-name})
+ // for username and password so rhq-server.properties can be used to set these.
+ // However, AS7.1 doesn't support this yet - see https://issues.jboss.org/browse/AS7-5177
+ moduleOptions.add(USERNAME, username);
+ moduleOptions.add(PASSWORD, password);
+
+ // login modules attribute must be a list - we only have one item in it, the loginModule
+ ModelNode loginModuleList = new ModelNode();
+ loginModuleList.setEmptyList();
+ loginModuleList.add(loginModule);
+
+ final ModelNode op = createRequest(WRITE_ATTRIBUTE, addr);
+ op.get(NAME).set(LOGIN_MODULES);
+ op.get(VALUE).set(loginModuleList);
+
+ ModelNode results = execute(op);
+ if (!isSuccess(results)) {
+ throw new FailureException(results, "Failed to update credentials for security domain ["
+ + securityDomainName + "]");
+ }
+
+ return;
+ }
+
+ /**
* Create a new security domain using the database server authentication method.
* This is used when you want to directly authenticate against a db entry.
*
diff --git a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/WebJBossASClient.java b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/WebJBossASClient.java
index f1d030d..b67c376 100644
--- a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/WebJBossASClient.java
+++ b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/WebJBossASClient.java
@@ -85,6 +85,20 @@ public class WebJBossASClient extends JBossASClient {
}
/**
+ * Removes the given web connector.
+ *
+ * @param doomedConnectorName the name of the web connector to remove.
+ * @throws Exception
+ */
+ public void removeConnector(String doomedConnectorName) throws Exception {
+ final Address address = Address.root().add(SUBSYSTEM, SUBSYSTEM_WEB, CONNECTOR, doomedConnectorName);
+ if (isConnector(doomedConnectorName)) {
+ remove(address);
+ }
+ return;
+ }
+
+ /**
* Add a new web connector, which may be a secure SSL connector (HTTPS) or not (HTTP).
*
* @param name
diff --git a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/Installer.java b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/Installer.java
index 0c8876b..6d0c159 100644
--- a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/Installer.java
+++ b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/Installer.java
@@ -47,7 +47,7 @@ public class Installer {
private InstallerConfiguration installerConfig;
private enum WhatToDo {
- DISPLAY_USAGE, DO_NOTHING, TEST, SETUPDB, LIST_SERVERS, INSTALL
+ DISPLAY_USAGE, DO_NOTHING, RECONFIGURE, TEST, SETUPDB, LIST_SERVERS, INSTALL
}
public static void main(String[] args) {
@@ -109,6 +109,18 @@ public class Installer {
}
continue;
}
+ case RECONFIGURE: {
+ try {
+ final InstallerService installerService = new InstallerServiceImpl(installerConfig);
+ final HashMap<String, String> serverProperties = installerService.getServerProperties();
+ installerService.reconfigure(serverProperties);
+ LOG.info("Reconfiguration is complete.");
+ } catch (Exception e) {
+ LOG.error(ThrowableUtil.getAllMessages(e));
+ System.exit(EXIT_CODE_INSTALLATION_ERROR);
+ }
+ continue;
+ }
case INSTALL: {
try {
final InstallerService installerService = new InstallerServiceImpl(installerConfig);
@@ -145,24 +157,27 @@ public class Installer {
usage.append("\t--test, -t: test the validity of the server properties (install not performed)").append("\n");
usage.append("\t--listservers, -l: show list of known installed servers (install not performed)").append("\n");
usage.append("\t--setupdb, -b: only perform database schema creation or update").append("\n");
+ usage.append("\t--reconfig, -r: resets some configuration settings in an installed server").append("\n");
usage.append("\t--dbpassword, -d: encodes a DB password for rhq-server.properties (install not performed)")
.append("\n");
LOG.info(usage);
}
private WhatToDo[] processArguments(String[] args) throws Exception {
- String sopts = "-:HD:h:p:d:blt";
+ String sopts = "-:HD:h:p:d:blrt";
LongOpt[] lopts = { new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'H'),
new LongOpt("host", LongOpt.REQUIRED_ARGUMENT, null, 'h'),
new LongOpt("port", LongOpt.REQUIRED_ARGUMENT, null, 'p'),
new LongOpt("dbpassword", LongOpt.REQUIRED_ARGUMENT, null, 'd'),
new LongOpt("setupdb", LongOpt.NO_ARGUMENT, null, 'b'),
new LongOpt("listservers", LongOpt.NO_ARGUMENT, null, 'l'),
+ new LongOpt("reconfig", LongOpt.NO_ARGUMENT, null, 'r'),
new LongOpt("test", LongOpt.NO_ARGUMENT, null, 't') };
boolean test = false;
boolean listservers = false;
boolean setupdb = false;
+ boolean reconfig = false;
String dbpassword = null;
Getopt getopt = new Getopt("installer", args, sopts, lopts);
@@ -243,6 +258,11 @@ public class Installer {
break; // don't return, we need to allow more args to be processed, like -p or -h
}
+ case 'r': {
+ reconfig = true;
+ break; // don't return, we need to allow more args to be processed, like -p or -h
+ }
+
case 't': {
test = true;
break; // don't return, we need to allow more args to be processed, like -p or -h
@@ -257,6 +277,10 @@ public class Installer {
return new WhatToDo[] { WhatToDo.DO_NOTHING };
}
+ if (reconfig) {
+ return new WhatToDo[] { WhatToDo.RECONFIGURE };
+ }
+
if (test || setupdb || listservers) {
ArrayList<WhatToDo> whatToDo = new ArrayList<WhatToDo>();
if (test) {
diff --git a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerService.java b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerService.java
index 6eff4b7..9ee3c27 100644
--- a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerService.java
+++ b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerService.java
@@ -121,6 +121,21 @@ public interface InstallerService {
String existingSchemaOption) throws Exception;
/**
+ * This will take server properties and reconfigure an already-installed server
+ * with those values if the settings were previously hardcoded to old values (as opposed to being
+ * set to expressions that allow them to be overridden with system property settings).
+ * Note that is function is here only to workaround various bugs in AS7
+ * that force us to not be able to use expressions in certain app server subsystem attribute
+ * settings - see https://issues.jboss.org/browse/AS7-6120. Once this issues are fixed, this
+ * method will go away.
+ *
+ * @param serverProperties the new server properties
+ * @throws Exception
+ */
+ @Deprecated
+ void reconfigure(HashMap<String, String> serverProperties) throws Exception;
+
+ /**
* Returns a list of all registered servers in the database.
*
* @param connectionUrl
diff --git a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java
index bff75f0..4b5e4b8 100644
--- a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java
+++ b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java
@@ -249,7 +249,10 @@ public class InstallerServiceImpl implements InstallerService {
ServerInstallUtil.configureDeploymentScanner(mcc);
// create a keystore whose cert has a CN of this server's public endpoint address
- ServerInstallUtil.prepareWebConnectors(mcc, serverDetails, appServerConfigDir, serverProperties);
+ File keystoreFile = ServerInstallUtil.createKeystore(serverDetails, appServerConfigDir);
+
+ // make sure all necessary web connectors are configured
+ ServerInstallUtil.setupWebConnectors(mcc, appServerConfigDir, serverProperties);
} finally {
safeClose(mcc);
}
@@ -529,6 +532,51 @@ public class InstallerServiceImpl implements InstallerService {
return map;
}
+ // This is here only to help users workaround https://issues.jboss.org/browse/AS7-6120.
+ // It will go away once all the issues with expression support in AS7 are fixed.
+ // Notice in this method we only reconfigure some things - only the subsystems/services
+ // that didn't support expressions in their attributes are reconfigured here since it
+ // is those whose values are hardcoded and we must alter to pick up changes to
+ // rhq-server.properties. All other services can pick up the property value changes
+ // make to rhq-server.properties on restart (since rhq-server.properties are system
+ // properties set in the AS7 instance via -P option to AS7).
+ @Override
+ public void reconfigure(HashMap<String, String> serverProperties) throws Exception {
+
+ // make sure we can connect using our configuration
+ testModelControllerClient(serverProperties);
+
+ String appServerConfigDir = getAppServerConfigDir();
+ ModelControllerClient mcc = null;
+
+ try {
+ // first, put the server in admin-only mode so we can start changing things around
+ mcc = getModelControllerClient();
+ CoreJBossASClient coreClient = new CoreJBossASClient(mcc);
+ coreClient.reload(true);
+
+ // not sure if we have to, but see if we need to wait for the reload to finish
+ testModelControllerClient(30);
+
+ mcc = getModelControllerClient(); // get a new controller
+
+ // create the security domain needed by the datasources
+ ServerInstallUtil.createDatasourceSecurityDomain(mcc, serverProperties);
+
+ // setup the email service
+ ServerInstallUtil.setupMailService(mcc, serverProperties);
+
+ // create a keystore whose cert has a CN of this server's public endpoint address
+ ServerInstallUtil.setupWebConnectors(mcc, appServerConfigDir, serverProperties);
+
+ // now reload out of admin mode to pick up the changes
+ coreClient = new CoreJBossASClient(mcc);
+ coreClient.reload(false);
+ } finally {
+ safeClose(mcc);
+ }
+ }
+
/**
* Makes sure the data is at least in the correct format (booleans are true/false, integers are valid numbers).
*
diff --git a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java
index 85dedf9..baa81da 100644
--- a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java
+++ b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java
@@ -64,6 +64,7 @@ import org.rhq.core.db.DbUtil;
import org.rhq.core.db.OracleDatabaseType;
import org.rhq.core.db.PostgresqlDatabaseType;
import org.rhq.core.db.setup.DBSetup;
+import org.rhq.core.util.PropertiesFileUpdate;
import org.rhq.core.util.exception.ThrowableUtil;
import org.rhq.core.util.stream.StreamUtil;
import org.rhq.enterprise.communications.util.SecurityUtil;
@@ -142,6 +143,7 @@ public class ServerInstallUtil {
private static final String JMS_DRIFT_FILE_QUEUE = "DriftFileQueue";
private static final String RHQ_CACHE_CONTAINER = "rhq";
private static final String RHQ_CACHE = "rhqCache";
+ private static final String RHQ_MGMT_USER = "rhqadmin";
/**
* Configure the deployment scanner to get ready to deploy the application.
@@ -245,10 +247,12 @@ public class ServerInstallUtil {
final SecurityDomainJBossASClient client = new SecurityDomainJBossASClient(mcc);
final String securityDomain = RHQ_DS_SECURITY_DOMAIN;
if (!client.isSecurityDomain(securityDomain)) {
- client.createNewSecureIdentitySecurityDomainRequest(securityDomain, dbUsername, obfuscatedPassword);
+ client.createNewSecureIdentitySecurityDomain(securityDomain, dbUsername, obfuscatedPassword);
LOG.info("Security domain [" + securityDomain + "] created");
} else {
LOG.info("Security domain [" + securityDomain + "] already exists, skipping the creation request");
+ client.updateSecureIdentitySecurityDomainCredentials(securityDomain, dbUsername, obfuscatedPassword);
+ LOG.info("Credentials have been updated for security domain [" + securityDomain + "]");
}
}
@@ -318,6 +322,7 @@ public class ServerInstallUtil {
LOG.info("JMS Queue [" + queueName + "] already exists, skipping the creation request");
}
+ return;
}
/**
@@ -333,7 +338,8 @@ public class ServerInstallUtil {
final SecurityDomainJBossASClient client = new SecurityDomainJBossASClient(mcc);
final String securityDomain = RHQ_REST_SECURITY_DOMAIN;
if (!client.isSecurityDomain(securityDomain)) {
- client.createNewDatabaseServerSecurityDomainRequest(securityDomain, "java:jboss/datasources/RHQDS",
+ String dsJndiName = "java:jboss/datasources/" + RHQ_DATASOURCE_NAME_XA;
+ client.createNewDatabaseServerSecurityDomain(securityDomain, dsJndiName,
"SELECT PASSWORD FROM RHQ_PRINCIPAL WHERE principal=?",
"SELECT 'all', 'Roles' FROM RHQ_PRINCIPAL WHERE principal=?", null, null);
LOG.info("Security domain [" + securityDomain + "] created");
@@ -1170,16 +1176,12 @@ public class ServerInstallUtil {
* Ensures our web connectors are configured properly.
*
* @param mcc the AS client
- * @param serverDetails details of the server being installed
* @param configDirStr location of a configuration directory where the keystore is to be stored
* @param serverProperties the full set of server properties
* @throws Exception
*/
- public static void prepareWebConnectors(ModelControllerClient mcc, ServerDetails serverDetails, String configDirStr,
- HashMap<String, String> serverProperties) throws Exception {
-
- // first create our keystore
- File keystoreFile = createKeystore(serverDetails, configDirStr);
+ public static void setupWebConnectors(ModelControllerClient mcc, String configDirStr,
+ HashMap<String, String> serverProperties) throws Exception {
// out of box, we always get a non-secure connector (called "http")...
final String connectorName = "http";
@@ -1190,46 +1192,45 @@ public class ServerInstallUtil {
WebJBossASClient client = new WebJBossASClient(mcc);
- if (!client.isConnector(sslConnectorName)) {
- LOG.info("Creating https connector...");
-
- SSLConfiguration ssl = new SSLConfiguration();
-
- // truststore
- ssl.setCaCertificateFile(getAbsoluteFileLocation("rhq.server.tomcat.security.truststore.file",
- serverProperties, configDirStr)); // this cannot be an expression - AS7 doesn't support that now
- ssl.setCaCertificationPassword(buildExpression("rhq.server.tomcat.security.truststore.password",
- serverProperties, false));
- ssl.setTruststoreType(buildExpression("rhq.server.tomcat.security.truststore.type", serverProperties, false));
-
- // keystore
- ssl.setCertificateKeyFile(getAbsoluteFileLocation("rhq.server.tomcat.security.keystore.file",
- serverProperties, configDirStr)); // this cannot be an expression - AS7 doesn't support that now
- ssl.setPassword(buildExpression("rhq.server.tomcat.security.keystore.password", serverProperties, false));
- ssl.setKeyAlias(buildExpression("rhq.server.tomcat.security.keystore.alias", serverProperties, false));
- ssl.setKeystoreType(buildExpression("rhq.server.tomcat.security.keystore.type", serverProperties, false));
-
- // SSL protocol config
- ssl.setProtocol(buildExpression("rhq.server.tomcat.security.secure-socket-protocol", serverProperties,
- false));
- ssl.setVerifyClient(buildExpression("rhq.server.tomcat.security.client-auth-mode", serverProperties,
- false));
-
- // note: there doesn't appear to be a way for AS7 to support algorithm, like SunX509 or IbmX509
- // so I think it just uses the JVM's default. This means "rhq.server.tomcat.security.algorithm" is unused
-
- ConnectorConfiguration connector = new ConnectorConfiguration();
- connector.setMaxConnections(buildExpression("rhq.server.startup.web.max-connections", serverProperties,
- false));
- connector.setScheme("https");
- connector.setSocketBinding("https");
- connector.setSslConfiguration(ssl);
-
- // create it now
- client.addConnector("https", connector);
-
- LOG.info("https connector created.");
- }
+ // because some of the connector attributes do not (yet) support expressions, let's remove any existing
+ // connector we may have created before and create it again with our current attribute values.
+ client.removeConnector(sslConnectorName);
+
+ LOG.info("Creating https connector...");
+
+ SSLConfiguration ssl = new SSLConfiguration();
+
+ // truststore
+ ssl.setCaCertificateFile(getAbsoluteFileLocation("rhq.server.tomcat.security.truststore.file",
+ serverProperties, configDirStr)); // this cannot be an expression - AS7 doesn't support that now
+ ssl.setCaCertificationPassword(buildExpression("rhq.server.tomcat.security.truststore.password",
+ serverProperties, false));
+ ssl.setTruststoreType(buildExpression("rhq.server.tomcat.security.truststore.type", serverProperties, false));
+
+ // keystore
+ ssl.setCertificateKeyFile(getAbsoluteFileLocation("rhq.server.tomcat.security.keystore.file", serverProperties,
+ configDirStr)); // this cannot be an expression - AS7 doesn't support that now
+ ssl.setPassword(buildExpression("rhq.server.tomcat.security.keystore.password", serverProperties, false));
+ ssl.setKeyAlias(buildExpression("rhq.server.tomcat.security.keystore.alias", serverProperties, false));
+ ssl.setKeystoreType(buildExpression("rhq.server.tomcat.security.keystore.type", serverProperties, false));
+
+ // SSL protocol config
+ ssl.setProtocol(buildExpression("rhq.server.tomcat.security.secure-socket-protocol", serverProperties, false));
+ ssl.setVerifyClient(buildExpression("rhq.server.tomcat.security.client-auth-mode", serverProperties, false));
+
+ // note: there doesn't appear to be a way for AS7 to support algorithm, like SunX509 or IbmX509
+ // so I think it just uses the JVM's default. This means "rhq.server.tomcat.security.algorithm" is unused
+
+ ConnectorConfiguration connector = new ConnectorConfiguration();
+ connector.setMaxConnections(buildExpression("rhq.server.startup.web.max-connections", serverProperties, false));
+ connector.setScheme("https");
+ connector.setSocketBinding("https");
+ connector.setSslConfiguration(ssl);
+
+ // create it now
+ client.addConnector("https", connector);
+
+ LOG.info("https connector created.");
if (client.isConnector(connectorName)) {
client.changeConnector(connectorName, "redirect-port",
@@ -1310,7 +1311,7 @@ public class ServerInstallUtil {
* @param configDirStr location of a configuration directory where the keystore is to be stored
* @return where the keystore file should be created (if an error occurs, this file won't exist)
*/
- private static File createKeystore(ServerDetails serverDetails, String configDirStr) {
+ public static File createKeystore(ServerDetails serverDetails, String configDirStr) {
File confDir = new File(configDirStr);
File keystore = new File(confDir, "rhq.keystore");
File keystoreBackup = new File(confDir, "rhq.keystore.backup");
@@ -1361,20 +1362,31 @@ public class ServerInstallUtil {
// Add the default admin user, or if for some reason this file does not exist, just log the issue
if (mgmtUsers.exists()) {
+ try {
+ PropertiesFileUpdate mgmtUsersPropFile = new PropertiesFileUpdate(mgmtUsers.getAbsolutePath());
+ Properties existingUsers = mgmtUsersPropFile.loadExistingProperties();
+ if (existingUsers.containsKey(RHQ_MGMT_USER)) {
+ LOG.info("There is already a mgmt user named [" + RHQ_MGMT_USER + "], will not create another");
+ return;
+ }
+ } catch (Exception e) {
+ LOG.warn("Cannot determine if mgmt user exists in [" + mgmtUsers + "]; will try to create it anyway", e);
+ }
+
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mgmtUsers, true);
- fos.write("\nrhqadmin=35c160c1f841a889d4cda53f0bfc94b6\n".getBytes());
+ fos.write(("\n" + RHQ_MGMT_USER + "=35c160c1f841a889d4cda53f0bfc94b6\n").getBytes());
} catch (Exception e) {
- LOG.warn("Could not create default management user in file: [" + mgmtUsers.getPath() + "] : ", e);
+ LOG.warn("Could not create default management user in file: [" + mgmtUsers + "] : ", e);
} finally {
StreamUtil.safeClose(fos);
}
} else {
- LOG.warn("Could not create default management user. Could not find file: [" + mgmtUsers.getPath() + "]");
+ LOG.warn("Could not create default management user. Could not find file: [" + mgmtUsers + "]");
}
}
commit 97919b228645970a82f44a4e3dd6951843911900
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Fri Dec 21 16:57:33 2012 -0500
rename the methods by removing "Request" - these don't create the requests, they actually do the thing itself.
JBossASClient and its subclasses have createXYZRequest static methods, but they only create the ModelNode requests, but they don't submit them for execution.
That's the difference - if you see a method called "createXYZRequest", it returns a ModelNode for the caller to manipulate and later submit for execution.
If the method does the execution itself, don't append "Request" to its name to avoid confusion.
diff --git a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java
index 48aede8..0b4597c 100644
--- a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java
+++ b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java
@@ -66,9 +66,8 @@ public class SecurityDomainJBossASClient extends JBossASClient {
}
/**
- * Convenience method that builds a request which can create a new security-domain
- * using the SecureIdentity authentication method. This is used when you want
- * to obfuscate a database password in the configuration.
+ * Create a new security domain using the SecureIdentity authentication method.
+ * This is used when you want to obfuscate a database password in the configuration.
*
* @param securityDomainName the name of the new security domain
* @param username the username associated with the security domain
@@ -76,7 +75,7 @@ public class SecurityDomainJBossASClient extends JBossASClient {
*
* @throws Exception if failed to create security domain
*/
- public void createNewSecureIdentitySecurityDomainRequest(String securityDomainName, String username, String password)
+ public void createNewSecureIdentitySecurityDomain(String securityDomainName, String username, String password)
throws Exception {
Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_SECURITY, SECURITY_DOMAIN, securityDomainName);
@@ -107,9 +106,8 @@ public class SecurityDomainJBossASClient extends JBossASClient {
}
/**
- * Convenience method that builds a request which can create a new security domain
- * using the database server authentication method. This is used when you want to directly
- * authenticate against a db entry.
+ * Create a new security domain using the database server authentication method.
+ * This is used when you want to directly authenticate against a db entry.
*
* @param securityDomainName the name of the new security domain
* @param dsJndiName the jndi name for the datasource to query against
@@ -119,7 +117,7 @@ public class SecurityDomainJBossASClient extends JBossASClient {
* @param hashEncoding if null defaults to "base64"
* @throws Exception if failed to create security domain
*/
- public void createNewDatabaseServerSecurityDomainRequest(String securityDomainName, String dsJndiName,
+ public void createNewDatabaseServerSecurityDomain(String securityDomainName, String dsJndiName,
String principalsQuery, String rolesQuery, String hashAlgorithm, String hashEncoding) throws Exception {
Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_SECURITY, SECURITY_DOMAIN, securityDomainName);
@@ -156,7 +154,7 @@ public class SecurityDomainJBossASClient extends JBossASClient {
* @param securityDomainName the name of the new security domain
* @throws Exception if failed to remove the security domain
*/
- public void removeSecurityDomainRequest(String securityDomainName) throws Exception {
+ public void removeSecurityDomain(String securityDomainName) throws Exception {
// If not there just return
if (!isSecurityDomain(securityDomainName)) {
@@ -175,19 +173,19 @@ public class SecurityDomainJBossASClient extends JBossASClient {
}
/**
- * Convenience method that builds a request to create a new security domain including one or
- * more login modules. The security domain will be replaced if it exists.
+ * Creates a new security domain including one or more login modules.
+ * The security domain will be replaced if it exists.
*
* @param securityDomainName the name of the new security domain
* @param loginModules an array of login modules to place in the security domain. They are ordered top-down in the
* same index order of the array.
* @throws Exception if failed to create security domain
*/
- public void createNewSecurityDomainRequest(String securityDomainName, LoginModuleRequest... loginModules)
+ public void createNewSecurityDomain(String securityDomainName, LoginModuleRequest... loginModules)
throws Exception {
if (isSecurityDomain(securityDomainName)) {
- removeSecurityDomainRequest(securityDomainName);
+ removeSecurityDomain(securityDomainName);
}
Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_SECURITY, SECURITY_DOMAIN, securityDomainName);
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CustomJaasDeploymentService.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CustomJaasDeploymentService.java
index 582de5e..2d6c35d 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CustomJaasDeploymentService.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CustomJaasDeploymentService.java
@@ -167,7 +167,7 @@ public class CustomJaasDeploymentService implements CustomJaasDeploymentServiceM
loginModules.add(ldapLoginModule);
}
- client.createNewSecurityDomainRequest(RHQ_USER_SECURITY_DOMAIN,
+ client.createNewSecurityDomain(RHQ_USER_SECURITY_DOMAIN,
loginModules.toArray(new LoginModuleRequest[loginModules.size()]));
log.info("Security domain [" + RHQ_USER_SECURITY_DOMAIN + "] created with login modules " + loginModules);
commit e70c5793b4a4c6ed4ab1bf29a62ece1da80cd1b3
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Fri Dec 21 14:07:35 2012 -0500
trivial change to comment (this line of code doesn't deploy the ear)
diff --git a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java
index 7006601..bff75f0 100644
--- a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java
+++ b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java
@@ -254,7 +254,7 @@ public class InstallerServiceImpl implements InstallerService {
safeClose(mcc);
}
- // now create our deployment services and our main EAR
+ // now create our deployment services
deployServices(serverProperties);
// deploy the main EAR app startup module extension
10 years, 11 months
[rhq] Branch 'feature/cassandra-backend' - 3 commits - modules/common modules/enterprise pom.xml
by John Sanda
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(a)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(a)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">
+
+ <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">
+
+ <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/${cas..."
+ 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(a)@"
+
+
+# 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(a)@"
+JVM_EXTRA_OPTS="$JVM_EXTRA_OPTS -Dpasswd.properties=@@rhq.cassandra.password.properties.file(a)@"
+JVM_EXTRA_OPTS="$JVM_EXTRA_OPTS -Daccess.properties=@@rhq.cassandra.access.properties.file(a)@"
+
+# 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....
+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...
+# 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(a)@
+
+# 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(a)@
+
+# 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(a)@
+
+# authorization backend, implementing IAUthorizer; used to limit access/provide permissions
+authorizer: @@rhq.cassandra.authorizer(a)@
+
+# 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(a)@
+
+# commit log
+commitlog_directory: @@rhq.deploy.dir@@/@@commitlog.dir(a)@
+
+# 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(a)@
+
+# 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(a)@
+
+# 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(a)@
+# 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(a)@
+
+
+# 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(a)@
+# 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/J...
+#
+server_encryption_options:
+ internode_encryption: none
+ keystore: conf/.keystore
+ keystore_password: cassandra
+ truststore: conf/.truststore
+ truststore_password: cassandra
+ # More advanced defaults below:
+ # protocol: TLS
+ # algorithm: SunX509
+ # store_type: JKS
+ # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA]
+
+# 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@(a),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@(a)/system.log
+log4j.appender.R.Threshold=@@logging.level(a)@
+
+# 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(a)@
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">
+
+ <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
+ */
+(a)Retention(RetentionPolicy.RUNTIME)
+(a)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
+ */
+(a)Retention(RetentionPolicy.RUNTIME)
+(a)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
+ */
+(a)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">
+ <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">
-
- <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
- */
-(a)Retention(RetentionPolicy.RUNTIME)
-(a)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
- */
-(a)Retention(RetentionPolicy.RUNTIME)
-(a)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
- */
-(a)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">
-
- <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/${cas..."
- 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(a)@"
-
-
-# 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(a)@"
-JVM_EXTRA_OPTS="$JVM_EXTRA_OPTS -Dpasswd.properties=@@rhq.cassandra.password.properties.file(a)@"
-JVM_EXTRA_OPTS="$JVM_EXTRA_OPTS -Daccess.properties=@@rhq.cassandra.access.properties.file(a)@"
-
-# 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....
-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...
-# 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(a)@
-
-# 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(a)@
-
-# 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(a)@
-
-# authorization backend, implementing IAUthorizer; used to limit access/provide permissions
-authorizer: @@rhq.cassandra.authorizer(a)@
-
-# 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(a)@
-
-# commit log
-commitlog_directory: @@rhq.deploy.dir@@/@@commitlog.dir(a)@
-
-# 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(a)@
-
-# 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(a)@
-
-# 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(a)@
-# 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(a)@
-
-
-# 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(a)@
-# 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/J...
-#
-server_encryption_options:
- internode_encryption: none
- keystore: conf/.keystore
- keystore_password: cassandra
- truststore: conf/.truststore
- truststore_password: cassandra
- # More advanced defaults below:
- # protocol: TLS
- # algorithm: SunX509
- # store_type: JKS
- # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA]
-
-# 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@(a),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@(a)/system.log
-log4j.appender.R.Threshold=@@logging.level(a)@
-
-# 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(a)@
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(a)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"/>
10 years, 11 months
[rhq] modules/common
by Jay Shaughnessy
modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/JBossASClient.java | 1 -
1 file changed, 1 deletion(-)
New commits:
commit 79e0b1b8baf09811d46580d800a788e9d66f05e5
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Fri Dec 21 15:18:52 2012 -0500
fix merge issue
diff --git a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/JBossASClient.java b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/JBossASClient.java
index 343cc25..9e51248 100644
--- a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/JBossASClient.java
+++ b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/JBossASClient.java
@@ -58,7 +58,6 @@ public class JBossASClient {
public static final String REMOVE = "remove";
public static final String SYSTEM_PROPERTY = "system-property";
public static final String PERSISTENT = "persistent"; // used by some operations to persist their effects
- public static final String REMOVE = "remove";
private ModelControllerClient client;
10 years, 11 months
[rhq] 2 commits - modules/common modules/enterprise
by Jay Shaughnessy
modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/JBossASClient.java | 1
modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java | 121 +++++++---
modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml | 2
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CustomJaasDeploymentService.java | 55 ++--
4 files changed, 131 insertions(+), 48 deletions(-)
New commits:
commit 00ec08dead23cdf5fb8238d106f8561f93c33247
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Fri Dec 21 15:03:05 2012 -0500
In dev mode we try and run the installer automatically for the dev, if it
hasn't been run already. We do this in the "background" so we use the
same window (the /B option). Change it to suppress output (> nul) so it
doesn't interfere with the actual server startup. And change it to
suppress input (< nul) so it doesn't hang waiting for "Terminate Batch Job (Y/N)"
when it completes.
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 0be2e6f..0c30da9 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
@@ -611,7 +611,7 @@ rhq.sync.endpoint-address=false
<replace file="${project.build.outputDirectory}/bin/rhq-server.bat">
<replacefilter>
<replacetoken>rem START SERVER</replacetoken>
- <replacevalue><![CDATA[start /B %RHQ_SERVER_HOME%\bin\rhq-autoinstall.bat]]></replacevalue>
+ <replacevalue><![CDATA[start /B %RHQ_SERVER_HOME%\bin\rhq-autoinstall.bat < nul > nul]]></replacevalue>
</replacefilter>
</replace>
</target>
commit 839b84fde562548edca1e4ac36324e5f0e0c0860
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Fri Dec 21 14:48:15 2012 -0500
LDAP support in RHQ-on-AS7
- fix up the client API to support:
- removal/replacement of the existing security domain for RHQ logins
- allow for multiple login-modules for a single security domain
- fix up the CustomJaasDeploymentService to play with the new API to be able to
add or remove the ldap support based on whether it is enabled.
diff --git a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/JBossASClient.java b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/JBossASClient.java
index a4f47a0..343cc25 100644
--- a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/JBossASClient.java
+++ b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/JBossASClient.java
@@ -55,6 +55,7 @@ public class JBossASClient {
public static final String READ_RESOURCE = "read-resource";
public static final String WRITE_ATTRIBUTE = "write-attribute";
public static final String ADD = "add";
+ public static final String REMOVE = "remove";
public static final String SYSTEM_PROPERTY = "system-property";
public static final String PERSISTENT = "persistent"; // used by some operations to persist their effects
public static final String REMOVE = "remove";
diff --git a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java
index 043e8f8..48aede8 100644
--- a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java
+++ b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/SecurityDomainJBossASClient.java
@@ -20,6 +20,8 @@ package org.rhq.common.jbossas.client.controller;
import java.util.Map;
+import javax.security.auth.login.AppConfigurationEntry;
+
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;
@@ -148,45 +150,77 @@ public class SecurityDomainJBossASClient extends JBossASClient {
}
/**
- * Convenience method that builds a request which can create a new security domain
- * using the database server authentication method. This is used when you want to directly
- * authenticate against a db entry.
+ * Convenience method that removes a security domain by name. Useful when changing the characteristics of the
+ * login modules.
*
* @param securityDomainName the name of the new security domain
- * @param loginModuleFQCN fully qualified class name to be set as the login-module "code".
- * @param moduleOptionProperties map of propName->propValue mappings to to bet as module options
+ * @throws Exception if failed to remove the security domain
+ */
+ public void removeSecurityDomainRequest(String securityDomainName) throws Exception {
+
+ // If not there just return
+ if (!isSecurityDomain(securityDomainName)) {
+ return;
+ }
+
+ final Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_SECURITY, SECURITY_DOMAIN, securityDomainName);
+ ModelNode removeSecurityDomainNode = createRequest(REMOVE, addr);
+
+ final ModelNode results = execute(removeSecurityDomainNode);
+ if (!isSuccess(results)) {
+ throw new FailureException(results, "Failed to remove security domain [" + securityDomainName + "]");
+ }
+
+ return;
+ }
+
+ /**
+ * Convenience method that builds a request to create a new security domain including one or
+ * more login modules. The security domain will be replaced if it exists.
+ *
+ * @param securityDomainName the name of the new security domain
+ * @param loginModules an array of login modules to place in the security domain. They are ordered top-down in the
+ * same index order of the array.
* @throws Exception if failed to create security domain
*/
- public void createNewCustomSecurityDomainRequest(String securityDomainName, String loginModuleFQCN,
- Map<String, String> moduleOptionProperties) throws Exception {
+ public void createNewSecurityDomainRequest(String securityDomainName, LoginModuleRequest... loginModules)
+ throws Exception {
+
+ if (isSecurityDomain(securityDomainName)) {
+ removeSecurityDomainRequest(securityDomainName);
+ }
Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_SECURITY, SECURITY_DOMAIN, securityDomainName);
- ModelNode addTopNode = null;
- // If necessary create the security domain, otherwise just add the loginModule
- if (!isSecurityDomain(securityDomainName)) {
- addTopNode = createRequest(ADD, addr);
- addTopNode.get(CACHE_TYPE).set("default");
- }
+ ModelNode addTopNode = createRequest(ADD, addr);
+ addTopNode.get(CACHE_TYPE).set("default");
ModelNode addAuthNode = createRequest(ADD, addr.clone().add(AUTHENTICATION, CLASSIC));
ModelNode loginModulesNode = addAuthNode.get(LOGIN_MODULES);
- ModelNode loginModule = new ModelNode();
- loginModule.get(CODE).set(loginModuleFQCN);
- loginModule.get(FLAG).set("required");
- ModelNode moduleOptions = loginModule.get(MODULE_OPTIONS);
- moduleOptions.setEmptyList();
- if (null != moduleOptionProperties) {
- for (String key : moduleOptionProperties.keySet()) {
- moduleOptions.add(key, moduleOptionProperties.get(key));
+ ModelNode[] loginModuleNodes = new ModelNode[loginModules.length];
+
+ for (int i = 0, len = loginModules.length; i < len; ++i) {
+ ModelNode loginModule = new ModelNode();
+ loginModule.get(CODE).set(loginModules[i].getLoginModuleFQCN());
+ loginModule.get(FLAG).set(loginModules[i].getFlagString());
+ ModelNode moduleOptions = loginModule.get(MODULE_OPTIONS);
+ moduleOptions.setEmptyList();
+
+ Map<String, String> moduleOptionProperties = loginModules[i].getModuleOptionProperties();
+ if (null != moduleOptionProperties) {
+ for (String key : moduleOptionProperties.keySet()) {
+ String value = moduleOptionProperties.get(key);
+ if (null != value) {
+ moduleOptions.add(key, value);
+ }
+ }
}
- }
- loginModulesNode.add(loginModule);
+ loginModulesNode.add(loginModule);
+ }
- ModelNode batch = (null != addTopNode) ? createBatchRequest(addTopNode, addAuthNode)
- : createBatchRequest(addAuthNode);
+ ModelNode batch = createBatchRequest(addTopNode, addAuthNode);
ModelNode results = execute(batch);
if (!isSuccess(results)) {
throw new FailureException(results, "Failed to create security domain [" + securityDomainName + "]");
@@ -195,4 +229,41 @@ public class SecurityDomainJBossASClient extends JBossASClient {
return;
}
+ /** Immutable helper */
+ public static class LoginModuleRequest {
+ private AppConfigurationEntry entry;
+
+ /**
+ * @param loginModuleFQCN fully qualified class name to be set as the login-module "code".
+ * @param flag constant, one of required|requisite|sufficient|optional
+ * @param moduleOptionProperties map of propName->propValue mappings to to bet as module options
+ */
+ public LoginModuleRequest(String loginModuleFQCN, AppConfigurationEntry.LoginModuleControlFlag flag,
+ Map<String, String> moduleOptionProperties) {
+
+ this.entry = new AppConfigurationEntry(loginModuleFQCN, flag, moduleOptionProperties);
+ }
+
+ public String getLoginModuleFQCN() {
+ return entry.getLoginModuleName();
+ }
+
+ public AppConfigurationEntry.LoginModuleControlFlag getFlag() {
+ return entry.getControlFlag();
+ }
+
+ public String getFlagString() {
+ return entry.getControlFlag().toString().split(" ")[1];
+ }
+
+ public Map<String, String> getModuleOptionProperties() {
+ return (Map<String, String>) entry.getOptions();
+ }
+
+ @Override
+ public String toString() {
+ return "LoginModuleRequest [loginModuleFQCN=" + getLoginModuleFQCN() + ", flag=" + getFlag()
+ + ", moduleOptionProperties=" + getModuleOptionProperties() + "]";
+ }
+ }
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CustomJaasDeploymentService.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CustomJaasDeploymentService.java
index ddd0815..582de5e 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CustomJaasDeploymentService.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CustomJaasDeploymentService.java
@@ -18,7 +18,9 @@
*/
package org.rhq.enterprise.server.core;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Properties;
@@ -29,6 +31,7 @@ import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
+import javax.security.auth.login.AppConfigurationEntry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -36,6 +39,7 @@ import org.apache.commons.logging.LogFactory;
import org.jboss.as.controller.client.ModelControllerClient;
import org.rhq.common.jbossas.client.controller.SecurityDomainJBossASClient;
+import org.rhq.common.jbossas.client.controller.SecurityDomainJBossASClient.LoginModuleRequest;
import org.rhq.core.domain.common.composite.SystemSetting;
import org.rhq.enterprise.server.RHQConstants;
import org.rhq.enterprise.server.core.jaas.JDBCLoginModule;
@@ -101,26 +105,30 @@ public class CustomJaasDeploymentService implements CustomJaasDeploymentServiceM
public void postDeregister() {
}
+ /**
+ * Will register the necessary JAAS login Modules. The RHQ_USER_SECURITY_DOMAIN will be created, or recreated
+ * if it already exists. This allows us to add/remove ldap support as it is enabled or disabled.
+ *
+ * @param systemConfig
+ * @throws Exception
+ */
private void registerJaasModules(Properties systemConfig) throws Exception {
ModelControllerClient mcc = null;
try {
mcc = ManagementService.getClient();
final SecurityDomainJBossASClient client = new SecurityDomainJBossASClient(mcc);
- final String securityDomain = RHQ_USER_SECURITY_DOMAIN;
- if (client.isSecurityDomain(securityDomain)) {
- log.info("Security domain [" + securityDomain + "] already exists, skipping the creation request");
- return;
+ if (client.isSecurityDomain(RHQ_USER_SECURITY_DOMAIN)) {
+ log.info("Security domain [" + RHQ_USER_SECURITY_DOMAIN + "] already exists, it will be replaced.");
}
- // Always register the RHQ user JDBC login module, this checks the pricipal against the RHQ DB
- Map<String, String> moduleOptionProperties = getJdbcOptions(systemConfig);
- String code = JDBCLoginModule.class.getName();
+ List<LoginModuleRequest> loginModules = new ArrayList<LoginModuleRequest>(3);
- client.createNewCustomSecurityDomainRequest(securityDomain, code, moduleOptionProperties);
- log.info("Security domain [" + securityDomain + "] created");
- log.info("Security domain login module [" + securityDomain + ":" + code + "] created");
+ // Always register the RHQ user JDBC login module, this checks the principal against the RHQ DB
+ LoginModuleRequest jdbcLoginModule = new LoginModuleRequest(JDBCLoginModule.class.getName(),
+ AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT, getJdbcOptions(systemConfig));
+ loginModules.add(jdbcLoginModule);
// Optionally register two more login modules for LDAP support. The first ensures
// we don't have a DB principal (if we do then the JDBC login module is sufficient.
@@ -130,16 +138,15 @@ public class CustomJaasDeploymentService implements CustomJaasDeploymentServiceM
if (isLdapAuthenticationEnabled) {
// this is a "gatekeeper" that only allows us to go to LDAP if there is no principal in the DB
- moduleOptionProperties = getJdbcOptions(systemConfig);
- code = JDBCPrincipalCheckLoginModule.class.getName();
-
- client.createNewCustomSecurityDomainRequest(securityDomain, code, moduleOptionProperties);
- log.info("Security domain login module [" + securityDomain + ":" + code + "] created");
+ LoginModuleRequest jdbcPrincipalCheckLoginModule = new LoginModuleRequest(
+ JDBCPrincipalCheckLoginModule.class.getName(),
+ AppConfigurationEntry.LoginModuleControlFlag.REQUISITE, getJdbcOptions(systemConfig));
+ loginModules.add(jdbcPrincipalCheckLoginModule);
- // this is the LDAP module that checks the LDAP for auth
- moduleOptionProperties = getLdapOptions(systemConfig);
+ // this is the LDAP module that checks the LDAP for auth
+ Map<String, String> ldapModuleOptionProperties = getLdapOptions(systemConfig);
try {
- validateLdapOptions(moduleOptionProperties);
+ validateLdapOptions(ldapModuleOptionProperties);
} catch (NamingException e) {
String descriptiveMessage = null;
@@ -155,11 +162,15 @@ public class CustomJaasDeploymentService implements CustomJaasDeploymentServiceM
}
// Enable the login module even if the LDAP properties have issues
- code = LdapLoginModule.class.getName();
-
- client.createNewCustomSecurityDomainRequest(securityDomain, code, moduleOptionProperties);
- log.info("Security domain login module [" + securityDomain + ":" + code + "] created");
+ LoginModuleRequest ldapLoginModule = new LoginModuleRequest(LdapLoginModule.class.getName(),
+ AppConfigurationEntry.LoginModuleControlFlag.REQUISITE, ldapModuleOptionProperties);
+ loginModules.add(ldapLoginModule);
}
+
+ client.createNewSecurityDomainRequest(RHQ_USER_SECURITY_DOMAIN,
+ loginModules.toArray(new LoginModuleRequest[loginModules.size()]));
+ log.info("Security domain [" + RHQ_USER_SECURITY_DOMAIN + "] created with login modules " + loginModules);
+
} catch (Exception e) {
throw new Exception("Error registering RHQ JAAS modules", e);
} finally {
10 years, 11 months