r/m vestigal avro code from 0.6. patch by jbellis

git-svn-id: https://svn.apache.org/repos/asf/cassandra/branches/cassandra-0.6@979500 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Jonathan Ellis 2010-07-27 02:48:30 +00:00
parent df8f1f3469
commit 982ac1e44f
11 changed files with 14 additions and 1191 deletions

View File

@ -35,7 +35,6 @@
<property name="interface.dir" value="${basedir}/interface"/>
<property name="interface.thrift.dir" value="${interface.dir}/thrift"/>
<property name="interface.thrift.gen-java" value="${interface.thrift.dir}/gen-java"/>
<property name="interface.avro.dir" value="${interface.dir}/avro/gen-java"/>
<property name="test.dir" value="${basedir}/test"/>
<property name="test.resources" value="${test.dir}/resources"/>
<property name="test.classes" value="${build.dir}/test/classes"/>
@ -98,7 +97,6 @@
<delete dir="${build.test.dir}" />
<delete dir="${build.classes}" />
<delete dir="${build.src.gen-java}" />
<delete dir="${interface.avro.dir}" />
</target>
<target depends="clean" name="cleanall"/>
@ -152,41 +150,6 @@
pattern="${build.dir.lib}/[type]s/[artifact]-[revision].[ext]" />
</target>
<!--
Generate avro code
-->
<target name="check-avro-generate">
<uptodate property="avroUpToDate"
srcfile="${interface.dir}/cassandra.avpr"
targetfile="${interface.avro.dir}/org/apache/cassandra/avro/Cassandra.java" />
<taskdef name="protocol"
classname="org.apache.avro.specific.ProtocolTask">
<classpath refid="cassandra.classpath" />
</taskdef>
<taskdef name="schema" classname="org.apache.avro.specific.SchemaTask">
<classpath refid="cassandra.classpath" />
</taskdef>
<taskdef name="paranamer"
classname="com.thoughtworks.paranamer.ant.ParanamerGeneratorTask">
<classpath refid="cassandra.classpath" />
</taskdef>
</target>
<target name="avro-generate" unless="avroUpToDate"
depends="init,check-avro-generate">
<echo>Generating avro code...</echo>
<protocol destdir="${interface.avro.dir}">
<fileset dir="${interface.dir}">
<include name="**/*.avpr" />
</fileset>
</protocol>
<schema destdir="${interface.avro.dir}">
<fileset dir="${interface.dir}">
<include name="**/*.avsc" />
</fileset>
</schema>
</target>
<!--
Generate thrift code
-->
@ -219,22 +182,18 @@
The build target builds all the .class files
-->
<target name="build"
depends="ivy-retrieve-build,avro-generate,build-subprojects,build-project"/>
depends="ivy-retrieve-build,build-subprojects,build-project"/>
<target name="build-subprojects"/>
<target name="codecoverage" depends="cobertura-instrument,test,cobertura-report"/>
<target depends="init,avro-generate,gen-cli-grammar" name="build-project">
<target depends="init,gen-cli-grammar" name="build-project">
<echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="${build.classes}">
<src path="${build.src}"/>
<src path="${build.src.gen-java}"/>
<src path="${interface.thrift.dir}/gen-java"/>
<src path="${interface.avro.dir}"/>
<classpath refid="cassandra.classpath"/>
</javac>
<paranamer sourceDirectory="${interface.avro.dir}"
outputDirectory="${build.classes}"/>
</target>
<!--
@ -323,7 +282,6 @@
<include name="**"/>
<exclude name="build/**" />
<exclude name="src/gen-java/**" />
<exclude name="interface/avro/**" />
<exclude name=".git/**" />
</tarfileset>
</tar>

Binary file not shown.

View File

@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed 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.

View File

@ -1,142 +0,0 @@
package org.apache.cassandra.avro;
/*
*
* 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.
*
*/
import java.util.Arrays;
import org.apache.avro.util.Utf8;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ColumnFamily;
import org.apache.cassandra.db.IColumn;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.MarshalException;
import static org.apache.cassandra.avro.ErrorFactory.newInvalidRequestException;
import static org.apache.cassandra.avro.RecordFactory.newColumnPath;
/**
* The Avro analogue to org.apache.cassandra.service.ThriftValidation
*/
public class AvroValidation {
// FIXME: could use method in ThriftValidation
static void validateKey(String key) throws InvalidRequestException
{
if (key.isEmpty())
throw newInvalidRequestException("Key may not be empty");
}
// FIXME: could use method in ThriftValidation
static void validateKeyspace(String keyspace) throws KeyspaceNotDefinedException
{
if (!DatabaseDescriptor.getTables().contains(keyspace))
throw new KeyspaceNotDefinedException(new Utf8("Keyspace " + keyspace + " does not exist in this schema."));
}
// FIXME: could use method in ThriftValidation
static String validateColumnFamily(String keyspace, String columnFamily) throws InvalidRequestException
{
if (columnFamily.isEmpty())
throw newInvalidRequestException("non-empty columnfamily is required");
String cfType = DatabaseDescriptor.getColumnFamilyType(keyspace, columnFamily);
if (cfType == null)
throw newInvalidRequestException("unconfigured columnfamily " + columnFamily);
return cfType;
}
static void validateColumnPath(String keyspace, ColumnPath cp) throws InvalidRequestException
{
validateKeyspace(keyspace);
String column_family = cp.column_family.toString();
String cfType = validateColumnFamily(keyspace, column_family);
byte[] column = null, super_column = null;
if (cp.super_column != null) super_column = cp.super_column.array();
if (cp.column != null) column = cp.column.array();
if (cfType.equals("Standard"))
{
if (super_column != null)
throw newInvalidRequestException("supercolumn parameter is invalid for standard CF " + column_family);
if (column == null)
throw newInvalidRequestException("column parameter is not optional for standard CF " + column_family);
}
else
{
if (super_column == null)
throw newInvalidRequestException("supercolumn parameter is not optional for super CF " + column_family);
}
if (column != null)
validateColumns(keyspace, column_family, super_column, Arrays.asList(column));
if (super_column != null)
validateColumns(keyspace, column_family, null, Arrays.asList(super_column));
}
// FIXME: could use method in ThriftValidation
static void validateColumns(String keyspace, String cfName, byte[] superColumnName, Iterable<byte[]> columnNames)
throws InvalidRequestException
{
if (superColumnName != null)
{
if (superColumnName.length > IColumn.MAX_NAME_LENGTH)
throw newInvalidRequestException("supercolumn name length must not be greater than " + IColumn.MAX_NAME_LENGTH);
if (superColumnName.length == 0)
throw newInvalidRequestException("supercolumn name must not be empty");
if (!DatabaseDescriptor.getColumnFamilyType(keyspace, cfName).equals("Super"))
throw newInvalidRequestException("supercolumn specified to ColumnFamily " + cfName + " containing normal columns");
}
AbstractType comparator = ColumnFamily.getComparatorFor(keyspace, cfName, superColumnName);
for (byte[] name : columnNames)
{
if (name.length > IColumn.MAX_NAME_LENGTH)
throw newInvalidRequestException("column name length must not be greater than " + IColumn.MAX_NAME_LENGTH);
if (name.length == 0)
throw newInvalidRequestException("column name must not be empty");
try
{
comparator.validate(name);
}
catch (MarshalException e)
{
throw newInvalidRequestException(e.getMessage());
}
}
}
static void validateColumnOrSuperColumn(String keyspace, String cfName, ColumnOrSuperColumn cosc)
throws InvalidRequestException
{
if (cosc.column != null)
AvroValidation.validateColumnPath(keyspace, newColumnPath(cfName, cosc.super_column.name, cosc.column.name));
if (cosc.super_column != null)
for (Column c : cosc.super_column.columns)
AvroValidation.validateColumnPath(keyspace, newColumnPath(cfName, cosc.super_column.name, c.name));
if ((cosc.column == null) && (cosc.super_column == null))
throw newInvalidRequestException("ColumnOrSuperColumn must have one or both of Column or SuperColumn");
}
}

View File

@ -1,168 +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.
*/
package org.apache.cassandra.avro;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import org.apache.avro.ipc.SocketServer;
import org.apache.avro.specific.SpecificResponder;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.CompactionManager;
import org.apache.cassandra.db.SystemTable;
import org.apache.cassandra.db.Table;
import org.apache.cassandra.db.commitlog.CommitLog;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
* The Avro analogue to org.apache.cassandra.service.CassandraDaemon.
*
*/
public class CassandraDaemon {
private static Logger logger = Logger.getLogger(CassandraDaemon.class);
private SocketServer server;
private InetAddress listenAddr;
private int listenPort;
private void setup() throws IOException
{
// log4j
String file = System.getProperty("storage-config") + File.separator + "log4j.properties";
PropertyConfigurator.configure(file);
listenPort = DatabaseDescriptor.getThriftPort();
listenAddr = DatabaseDescriptor.getThriftAddress();
/*
* If ThriftAddress was left completely unconfigured, then assume
* the same default as ListenAddress
*/
if (listenAddr == null)
listenAddr = FBUtilities.getLocalAddress();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
public void uncaughtException(Thread t, Throwable e)
{
logger.error("Fatal exception in thread " + t, e);
if (e instanceof OutOfMemoryError)
{
System.exit(100);
}
}
});
// check the system table for mismatched partitioner.
try
{
SystemTable.checkHealth();
}
catch (IOException e)
{
logger.error("Fatal exception during initialization", e);
System.exit(100);
}
// initialize keyspaces
for (String table : DatabaseDescriptor.getTables())
{
if (logger.isDebugEnabled())
logger.debug("opening keyspace " + table);
Table.open(table);
}
// replay the log if necessary and check for compaction candidates
CommitLog.recover();
CompactionManager.instance.checkAllColumnFamilies();
// start server internals
StorageService.instance.initServer();
}
/** hook for JSVC */
public void load(String[] arguments) throws IOException
{
setup();
}
/** hook for JSVC */
public void start() throws IOException
{
if (logger.isDebugEnabled())
logger.debug(String.format("Binding avro service to %s:%s", listenAddr, listenPort));
InetSocketAddress socketAddress = new InetSocketAddress(listenAddr, listenPort);
SpecificResponder responder = new SpecificResponder(Cassandra.class, new CassandraServer());
logger.info("Cassandra starting up...");
server = new SocketServer(responder, socketAddress);
}
/** hook for JSVC */
public void stop()
{
logger.info("Cassandra shutting down...");
server.close();
}
/** hook for JSVC */
public void destroy()
{
}
public static void main(String[] args) {
CassandraDaemon daemon = new CassandraDaemon();
String pidFile = System.getProperty("cassandra-pidfile");
try
{
daemon.setup();
if (pidFile != null)
{
new File(pidFile).deleteOnExit();
}
if (System.getProperty("cassandra-foreground") == null)
{
System.out.close();
System.err.close();
}
daemon.start();
}
catch (Throwable e)
{
String msg = "Exception encountered during startup.";
logger.error(msg, e);
// try to warn user on stdout too, if we haven't already detached
System.out.println(msg);
e.printStackTrace();
System.exit(3);
}
}
}

View File

@ -1,344 +0,0 @@
package org.apache.cassandra.avro;
/*
*
* 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.
*
*/
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.generic.GenericData;
import org.apache.avro.ipc.AvroRemoteException;
import org.apache.avro.util.Utf8;
import org.apache.cassandra.db.ColumnFamily;
import org.apache.cassandra.db.IColumn;
import org.apache.cassandra.db.ReadCommand;
import org.apache.cassandra.db.Row;
import org.apache.cassandra.db.RowMutation;
import org.apache.cassandra.db.SliceByNamesReadCommand;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.db.marshal.MarshalException;
import org.apache.cassandra.service.StorageProxy;
import org.apache.log4j.Logger;
import static org.apache.cassandra.avro.RecordFactory.*;
import static org.apache.cassandra.avro.ErrorFactory.*;
public class CassandraServer implements Cassandra {
private static Logger logger = Logger.getLogger(CassandraServer.class);
private final static GenericArray<Column> EMPTY_SUBCOLUMNS = new GenericData.Array<Column>(0, Schema.parse("{\"type\":\"array\",\"items\":" + Column.SCHEMA$ + "}"));
private final static Utf8 API_VERSION = new Utf8("0.0.0");
@Override
public ColumnOrSuperColumn get(Utf8 keyspace, Utf8 key, ColumnPath columnPath, ConsistencyLevel consistencyLevel)
throws AvroRemoteException, InvalidRequestException, NotFoundException, UnavailableException, TimedOutException {
if (logger.isDebugEnabled())
logger.debug("get");
ColumnOrSuperColumn column = multigetInternal(keyspace.toString(), Arrays.asList(key.toString()), columnPath, consistencyLevel).get(key.toString());
if ((column.column == null) && (column.super_column == null))
{
throw newNotFoundException("Path not found");
}
return column;
}
private Map<String, ColumnOrSuperColumn> multigetInternal(String keyspace, List<String> keys, ColumnPath cp, ConsistencyLevel level)
throws InvalidRequestException, UnavailableException, TimedOutException
{
AvroValidation.validateColumnPath(keyspace, cp);
// FIXME: This is repetitive.
byte[] column, super_column;
column = cp.column == null ? null : cp.column.array();
super_column = cp.super_column == null ? null : cp.super_column.array();
QueryPath path = new QueryPath(cp.column_family.toString(), column == null ? null : super_column);
List<byte[]> nameAsList = Arrays.asList(column == null ? super_column : column);
List<ReadCommand> commands = new ArrayList<ReadCommand>();
for (String key: keys)
{
AvroValidation.validateKey(key);
commands.add(new SliceByNamesReadCommand(keyspace, key, path, nameAsList));
}
Map<String, ColumnOrSuperColumn> columnFamiliesMap = new HashMap<String, ColumnOrSuperColumn>();
Map<String, Collection<IColumn>> columnsMap = multigetColumns(commands, level);
for (ReadCommand command: commands)
{
ColumnOrSuperColumn columnorsupercolumn;
Collection<IColumn> columns = columnsMap.get(command.key);
if (columns == null)
{
columnorsupercolumn = new ColumnOrSuperColumn();
}
else
{
assert columns.size() == 1;
IColumn col = columns.iterator().next();
if (col.isMarkedForDelete())
{
columnorsupercolumn = new ColumnOrSuperColumn();
}
else
{
columnorsupercolumn = col instanceof org.apache.cassandra.db.Column
? newColumnOrSuperColumn(newColumn(col.name(), col.value(), col.timestamp()))
: newColumnOrSuperColumn(newSuperColumn(col.name(), avronateSubColumns(col.getSubColumns())));
}
}
columnFamiliesMap.put(command.key, columnorsupercolumn);
}
return columnFamiliesMap;
}
private Map<String, Collection<IColumn>> multigetColumns(List<ReadCommand> commands, ConsistencyLevel level)
throws InvalidRequestException, UnavailableException, TimedOutException
{
Map<String, ColumnFamily> cfamilies = readColumnFamily(commands, level);
Map<String, Collection<IColumn>> columnFamiliesMap = new HashMap<String, Collection<IColumn>>();
for (ReadCommand command: commands)
{
ColumnFamily cfamily = cfamilies.get(command.key);
if (cfamily == null)
continue;
Collection<IColumn> columns = null;
if (command.queryPath.superColumnName != null)
{
IColumn column = cfamily.getColumn(command.queryPath.superColumnName);
if (column != null)
{
columns = column.getSubColumns();
}
}
else
{
columns = cfamily.getSortedColumns();
}
if (columns != null && columns.size() != 0)
{
columnFamiliesMap.put(command.key, columns);
}
}
return columnFamiliesMap;
}
protected Map<String, ColumnFamily> readColumnFamily(List<ReadCommand> commands, ConsistencyLevel consistency)
throws InvalidRequestException, UnavailableException, TimedOutException
{
// TODO - Support multiple column families per row, right now row only contains 1 column family
Map<String, ColumnFamily> columnFamilyKeyMap = new HashMap<String,ColumnFamily>();
if (consistency == ConsistencyLevel.ZERO)
throw newInvalidRequestException("Consistency level zero may not be applied to read operations");
List<Row> rows;
try
{
rows = StorageProxy.readProtocol(commands, thriftConsistencyLevel(consistency));
}
catch (TimeoutException e)
{
throw new TimedOutException();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
// FIXME: This suckage brought to you by StorageService and StorageProxy
// which throw Thrift exceptions directly.
catch (org.apache.cassandra.thrift.UnavailableException e)
{
throw new UnavailableException();
}
for (Row row: rows)
{
columnFamilyKeyMap.put(row.key, row.cf);
}
return columnFamilyKeyMap;
}
// Don't playa hate, avronate.
public GenericArray<Column> avronateSubColumns(Collection<IColumn> columns)
{
if (columns == null || columns.isEmpty())
return EMPTY_SUBCOLUMNS;
GenericData.Array<Column> avroColumns = new GenericData.Array<Column>(columns.size(), Column.SCHEMA$);
for (IColumn column : columns)
{
if (column.isMarkedForDelete())
continue;
Column avroColumn = newColumn(column.name(), column.value(), column.timestamp());
avroColumns.add(avroColumn);
}
return avroColumns;
}
@Override
public Void insert(Utf8 keyspace, Utf8 key, ColumnPath cp, ByteBuffer value, long timestamp, ConsistencyLevel consistencyLevel)
throws AvroRemoteException, InvalidRequestException, UnavailableException, TimedOutException
{
if (logger.isDebugEnabled())
logger.debug("insert");
// FIXME: This is repetitive.
byte[] column, super_column;
column = cp.column == null ? null : cp.column.array();
super_column = cp.super_column == null ? null : cp.super_column.array();
String column_family = cp.column_family.toString();
String keyspace_string = keyspace.toString();
AvroValidation.validateKey(keyspace_string);
AvroValidation.validateColumnPath(keyspace_string, cp);
RowMutation rm = new RowMutation(keyspace_string, key.toString());
try
{
rm.add(new QueryPath(column_family, super_column, column), value.array(), timestamp);
}
catch (MarshalException e)
{
throw newInvalidRequestException(e.getMessage());
}
doInsert(consistencyLevel, rm);
return null;
}
private void doInsert(ConsistencyLevel consistency, RowMutation rm) throws UnavailableException, TimedOutException
{
if (consistency != ConsistencyLevel.ZERO)
{
try
{
StorageProxy.mutateBlocking(Arrays.asList(rm), thriftConsistencyLevel(consistency));
}
catch (TimeoutException e)
{
throw new TimedOutException();
}
catch (org.apache.cassandra.thrift.UnavailableException thriftE)
{
throw new UnavailableException();
}
}
else
{
StorageProxy.mutate(Arrays.asList(rm));
}
}
@Override
public Void batch_insert(Utf8 keyspace, Utf8 key, Map<Utf8, GenericArray<ColumnOrSuperColumn>> cfmap, ConsistencyLevel consistency)
throws AvroRemoteException, InvalidRequestException, UnavailableException, TimedOutException
{
if (logger.isDebugEnabled())
logger.debug("batch_insert");
String keyString = key.toString();
String keyspaceString = keyspace.toString();
AvroValidation.validateKey(keyString);
for (Utf8 cfName : cfmap.keySet())
{
for (ColumnOrSuperColumn cosc : cfmap.get(cfName))
AvroValidation.validateColumnOrSuperColumn(keyspaceString, cfName.toString(), cosc);
}
doInsert(consistency, getRowMutation(keyspaceString, keyString, cfmap));
return null;
}
// FIXME: This is copypasta from o.a.c.db.RowMutation, (RowMutation.getRowMutation uses Thrift types directly).
private static RowMutation getRowMutation(String keyspace, String key, Map<Utf8, GenericArray<ColumnOrSuperColumn>> cfmap)
{
RowMutation rm = new RowMutation(keyspace, key.trim());
for (Map.Entry<Utf8, GenericArray<ColumnOrSuperColumn>> entry : cfmap.entrySet())
{
String cfName = entry.getKey().toString();
for (ColumnOrSuperColumn cosc : entry.getValue())
{
if (cosc.column == null)
{
assert cosc.super_column != null;
for (Column column : cosc.super_column.columns)
{
QueryPath path = new QueryPath(cfName, cosc.super_column.name.array(), column.name.array());
rm.add(path, column.value.array(), column.timestamp);
}
}
else
{
assert cosc.super_column == null;
QueryPath path = new QueryPath(cfName, null, cosc.column.name.array());
rm.add(path, cosc.column.value.array(), cosc.column.timestamp);
}
}
}
return rm;
}
private org.apache.cassandra.thrift.ConsistencyLevel thriftConsistencyLevel(ConsistencyLevel consistency)
{
switch (consistency)
{
case ZERO: return org.apache.cassandra.thrift.ConsistencyLevel.ZERO;
case ONE: return org.apache.cassandra.thrift.ConsistencyLevel.ONE;
case QUORUM: return org.apache.cassandra.thrift.ConsistencyLevel.QUORUM;
case DCQUORUM: return org.apache.cassandra.thrift.ConsistencyLevel.DCQUORUM;
case DCQUORUMSYNC: return org.apache.cassandra.thrift.ConsistencyLevel.DCQUORUMSYNC;
case ALL: return org.apache.cassandra.thrift.ConsistencyLevel.ALL;
}
return null;
}
@Override
public Utf8 get_api_version() throws AvroRemoteException
{
return API_VERSION;
}
}

View File

@ -1,34 +0,0 @@
package org.apache.cassandra.avro;
/*
*
* 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.
*
*/
import org.apache.avro.util.Utf8;
// XXX: This is an analogue to org.apache.cassandra.db.KeyspaceNotDefinedException
@SuppressWarnings("serial")
public class KeyspaceNotDefinedException extends InvalidRequestException {
public KeyspaceNotDefinedException(Utf8 why)
{
this.why = why;
}
}

View File

@ -1,129 +0,0 @@
package org.apache.cassandra.avro;
/*
*
* 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.
*
*/
import java.nio.ByteBuffer;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.util.Utf8;
class RecordFactory
{
static Column newColumn(ByteBuffer name, ByteBuffer value, long timestamp)
{
Column column = new Column();
column.name = name;
column.value = value;
column.timestamp = timestamp;
return column;
}
static Column newColumn(byte[] name, byte[] value, long timestamp)
{
return newColumn(ByteBuffer.wrap(name), ByteBuffer.wrap(value), timestamp);
}
static SuperColumn newSuperColumn(ByteBuffer name, GenericArray<Column> columns)
{
SuperColumn column = new SuperColumn();
column.name = name;
column.columns = columns;
return column;
}
static SuperColumn newSuperColumn(byte[] name, GenericArray<Column> columns)
{
return newSuperColumn(ByteBuffer.wrap(name), columns);
}
static ColumnOrSuperColumn newColumnOrSuperColumn(Column column)
{
ColumnOrSuperColumn col = new ColumnOrSuperColumn();
col.column = column;
return col;
}
static ColumnOrSuperColumn newColumnOrSuperColumn(SuperColumn superColumn)
{
ColumnOrSuperColumn column = new ColumnOrSuperColumn();
column.super_column = superColumn;
return column;
}
static ColumnPath newColumnPath(String cfName, ByteBuffer superColumn, ByteBuffer column)
{
ColumnPath cPath = new ColumnPath();
cPath.super_column = superColumn;
cPath.column = column;
return cPath;
}
}
class ErrorFactory
{
static InvalidRequestException newInvalidRequestException(Utf8 why)
{
InvalidRequestException exception = new InvalidRequestException();
exception.why = why;
return exception;
}
static InvalidRequestException newInvalidRequestException(String why)
{
return newInvalidRequestException(new Utf8(why));
}
static NotFoundException newNotFoundException(Utf8 why)
{
NotFoundException exception = new NotFoundException();
exception.why = why;
return exception;
}
static NotFoundException newNotFoundException(String why)
{
return newNotFoundException(new Utf8(why));
}
static TimedOutException newTimedOutException(Utf8 why)
{
TimedOutException exception = new TimedOutException();
exception.why = why;
return exception;
}
static TimedOutException newTimedOutException(String why)
{
return newTimedOutException(new Utf8(why));
}
static UnavailableException newUnavailableException(Utf8 why)
{
UnavailableException exception = new UnavailableException();
exception.why = why;
return exception;
}
static UnavailableException newUnavailableException(String why)
{
return newUnavailableException(new Utf8(why));
}
}

View File

@ -1,105 +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.
*/
package org.apache.cassandra.service;
import java.io.IOException;
import java.io.IOError;
import org.apache.cassandra.db.RowMutationMessage;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.utils.ExpiringMap;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.cache.ICacheExpungeHook;
import org.apache.log4j.Logger;
/*
* This class manages the read repairs . This is a singleton class
* it basically uses the cache table construct to schedule writes that have to be
* made for read repairs.
* A cachetable is created which wakes up every n milliseconds specified by
* expirationTimeInMillis and calls a global hook function on pending entries
* This function basically sends the message to the appropriate servers to update them
* with the latest changes.
*/
class ReadRepairManager
{
private static final Logger logger_ = Logger.getLogger(ReadRepairManager.class);
private static final long expirationTimeInMillis = 2000;
public static final ReadRepairManager instance = new ReadRepairManager();
/*
* This is the internal class which actually
* implements the global hook function called by the read repair manager
*/
static class ReadRepairPerformer implements ICacheExpungeHook<String, Message>
{
/*
* The hook function which takes the end point and the row mutation that
* needs to be sent to the end point in order
* to perform read repair.
*/
public void callMe(String target, Message message)
{
String[] pieces = FBUtilities.strip(target, ":");
InetAddress to = null;
try
{
to = InetAddress.getByName(pieces[0]);
}
catch (UnknownHostException e)
{
throw new RuntimeException(e);
}
MessagingService.instance.sendOneWay(message, to);
}
}
private ExpiringMap<String, Message> readRepairTable_ = new ExpiringMap<String, Message>(expirationTimeInMillis, new ReadRepairManager.ReadRepairPerformer());
protected ReadRepairManager()
{
}
/*
* Schedules a read repair.
* @param target endpoint on which the read repair should happen
* @param rowMutationMessage the row mutation message that has the repaired row.
*/
public void schedule(InetAddress target, RowMutationMessage rowMutationMessage)
{
try
{
Message message = rowMutationMessage.makeRowMutationMessage(StorageService.Verb.READ_REPAIR);
String key = target.getHostAddress() + ":" + message.getMessageId();
readRepairTable_.put(key, message);
}
catch (IOException ex)
{
throw new IOError(ex);
}
}
}

View File

@ -20,6 +20,7 @@ package org.apache.cassandra.service;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOError;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@ -33,6 +34,7 @@ import org.apache.cassandra.db.RowMutation;
import org.apache.cassandra.db.RowMutationMessage;
import java.net.InetAddress;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.config.DatabaseDescriptor;
@ -135,7 +137,16 @@ public class ReadResponseResolver implements IResponseResolver<Row>
RowMutation rowMutation = new RowMutation(table, key);
rowMutation.add(diffCf);
RowMutationMessage rowMutationMessage = new RowMutationMessage(rowMutation);
ReadRepairManager.instance.schedule(endPoints.get(i), rowMutationMessage);
Message repairMessage;
try
{
repairMessage = rowMutationMessage.makeRowMutationMessage(StorageService.Verb.READ_REPAIR);
}
catch (IOException e)
{
throw new IOError(e);
}
MessagingService.instance.sendOneWay(repairMessage, endPoints.get(i));
}
}

View File

@ -104,16 +104,11 @@ public class ExpiringMap<K, V>
{
hook.callMe(key, value);
}
else if (globalHook_ != null)
{
globalHook_.callMe(key, value);
}
}
expungedValues.clear();
}
}
private ICacheExpungeHook<K, V> globalHook_;
private Hashtable<K, CacheableObject> cache_;
private Map<K, ICacheExpungeHook<K, V>> hooks_;
private Timer timer_;
@ -142,18 +137,6 @@ public class ExpiringMap<K, V>
init(expiration);
}
/*
* Specify the TTL for objects in the cache
* in milliseconds and a global expunge hook. If
* a key has a key-specific hook installed invoke that
* instead.
*/
public ExpiringMap(long expiration, ICacheExpungeHook<K, V> global)
{
init(expiration);
globalHook_ = global;
}
public void shutdown()
{
timer_.cancel();
@ -202,11 +185,6 @@ public class ExpiringMap<K, V>
return cache_.containsKey(key);
}
public boolean containsValue(V value)
{
return cache_.containsValue(new CacheableObject(value));
}
public boolean isEmpty()
{
return cache_.isEmpty();