[2013.11.21 Comment]

현재 Cassandra standalone은 버그가 많아서 쓸 수 없다. 따로 Cassandra를 두어 테스트를 해야 한다.

Casandra unit이 잘 개발되길 조금 기다려야 한다. 


-------------------------



cassandra 2.0 java 유닛 테스트를 하려면 2가지 방법을 사용할 수 있다.


1. 테스트용 cassandra 를 local로 설치해 테스트하는 방법

2. cassandra 가 standalone 데몬으로 실행되고 unit test를 쉽게 할 수 있는 방법 (내가 선택한 방법)



1번은 전형적인 방법으로 많이들 쓰고 있다. DB 를 사용하는 dao 또는 batch에서는 transaction rollback 방식을 사용하거나 mock을 이용하는 방법으로 테스트를 진행하고 있다.  그런데 상당히 이런 작업이 불편하다. 개발 서버에 있는 내용과 테스트케이스가 다를 수 있고, 스키마도 다를 수 있다. 

그동안 상당히 귀찮았다. 


DB가 java daemonize되는 부분이 분명 존재하는 것이라 생각했는데, 마침 cassandra에서는 그런 것이 있었다. 

이름 하여 cassandra-uni 이라는 github프로젝트가 있다. 

https://github.com/jsevellec/cassandra-unit

cassandra 1.x대는 지원되고 있지만, cassandra 2.0도 지원계획을 가지고 있다. 

https://github.com/jsevellec/cassandra-unit/issues/70


cassandra 1.x는 잘 지원되니 큰 문제는 없으나 2.0은 현재 약간의 이슈가 있지만, 조금만 피해가면 잘 테스트가 가능하다. 

(아래 소스를 참조하면 된다. )


https://github.com/gibffe/cassyunit-2.0-test/tree/master



CQLDataLoader 가 잘 동작하지 않아서 수동으로 schema를 cql 파일을 로딩하지 못해서, hector나 astyanax 를 이용해서 schema 만드는 작업은 작업을 해야 할듯 하다. 아니면 좀더 잘 될 때까지 기다려야 한다. 

나머지는 잘동작되는 것 같다.  위의 github를 다운받아 조금 수정했다. 



pom.xml

<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">

<modelVersion>4.0.0</modelVersion>


<groupId>com.sulaco</groupId>

<artifactId>cassyunit-test</artifactId>

<version>0.0.1-SNAPSHOT</version>

<packaging>jar</packaging>


<name>cassyunit-test</name>


<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

</properties>


<repositories>

<repository>

<id>sonatype</id>

<url>http://oss.sonatype.org/content/repositories/snapshots</url>

</repository>

</repositories>


<build>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-compiler-plugin</artifactId>

<configuration>

<source>1.7</source>

<target>1.7</target>

</configuration>

</plugin>

</plugins>

</build>


<dependencies>

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-simple</artifactId>

<version>1.7.5</version>

<scope>compile</scope>

</dependency>


<dependency>

<groupId>org.cassandraunit</groupId>

<artifactId>cassandra-unit</artifactId>

<version>2.0.2.0-SNAPSHOT</version>

<scope>test</scope>

</dependency>


<dependency>

<groupId>org.yaml</groupId>

<artifactId>snakeyaml</artifactId>

<version>1.13</version>

<scope>test</scope>

</dependency>


<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.11</version>

<scope>test</scope>

</dependency>


<dependency>

<groupId>org.assertj</groupId>

<artifactId>assertj-core</artifactId>

<version>1.5.0</version>

<scope>test</scope>

</dependency>


<dependency>

<groupId>com.datastax.cassandra</groupId>

<artifactId>cassandra-driver-core</artifactId>

<version>2.0.0-beta1</version>

</dependency>

</dependencies>

</project>



cassandra.yaml - 기존에 실행되고 있는 cassandra 과 충돌나게 하지 않기 위해서 port 번호를 변경했다. 

# 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: 'cassy-1'


# This defines the number of tokens randomly assigned to this node on the ring

# The more tokens, relative to other nodes, the larger the proportion of data

# that this node will store. You probably want all nodes to have the same number

# of tokens assuming they have equal hardware capability.

#

# If you leave this unspecified, Cassandra will use the default of 1 token for legacy compatibility,

# and will use the initial_token as described below.

#

# Specifying initial_token will override this setting.

#

# If you already have a cluster with 1 token per node, and wish to migrate to

# multiple tokens per node, see http://wiki.apache.org/cassandra/Operations

num_tokens: 256


# initial_token allows you to specify tokens manually.  While you can use # it with

# vnodes (num_tokens > 1, above) -- in which case you should provide a

# comma-separated list -- it's primarily used when adding nodes # to legacy clusters

# that do not have vnodes enabled.

# initial_token:


# See http://wiki.apache.org/cassandra/HintedHandoff

hinted_handoff_enabled: true

# this defines the maximum amount of time a dead host will have hints

# generated.  After it has been dead this long, new hints for it will not be

# created until it has been seen alive and gone down again.

max_hint_window_in_ms: 10800000 # 3 hours

# Maximum throttle in KBs per second, per delivery thread.  This will be

# reduced proportionally to the number of nodes in the cluster.  (If there

# are two nodes in the cluster, each delivery thread will use the maximum

# rate; if there are three, each will throttle to half of the maximum,

# since we expect two nodes to be delivering hints simultaneously.)

hinted_handoff_throttle_in_kb: 1024

# Number of threads with which to deliver hints;

# Consider increasing this number when you have multi-dc deployments, since

# cross-dc handoff tends to be slower

max_hints_delivery_threads: 2


# The following setting populates the page cache on memtable flush and compaction

# WARNING: Enable this setting only when the whole node's data fits in memory.

# Defaults to: false

# populate_io_cache_on_flush: false


# Authentication backend, implementing IAuthenticator; used to identify users

# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthenticator,

# PasswordAuthenticator}.

#

# - AllowAllAuthenticator performs no checks - set it to disable authentication.

# - PasswordAuthenticator relies on username/password pairs to authenticate

#   users. It keeps usernames and hashed passwords in system_auth.credentials table.

#   Please increase system_auth keyspace replication factor if you use this authenticator.

authenticator: AllowAllAuthenticator


# Authorization backend, implementing IAuthorizer; used to limit access/provide permissions

# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthorizer,

# CassandraAuthorizer}.

#

# - AllowAllAuthorizer allows any action to any user - set it to disable authorization.

# - CassandraAuthorizer stores permissions in system_auth.permissions table. Please

#   increase system_auth keyspace replication factor if you use this authorizer.

authorizer: AllowAllAuthorizer


# Validity period for permissions cache (fetching permissions can be an

# expensive operation depending on the authorizer, CassandraAuthorizer is

# one example). Defaults to 2000, set to 0 to disable.

# Will be disabled automatically for AllowAllAuthorizer.

permissions_validity_in_ms: 2000


# The partitioner is responsible for distributing rows (by key) across

# nodes in the cluster.  Any IPartitioner may be used, including your

# own as long as it is on the classpath.  Out of the box, Cassandra

# provides org.apache.cassandra.dht.{Murmur3Partitioner, RandomPartitioner

# ByteOrderedPartitioner, OrderPreservingPartitioner (deprecated)}.

#

# - RandomPartitioner distributes rows across the cluster evenly by md5.

#   This is the default prior to 1.2 and is retained for compatibility.

# - Murmur3Partitioner is similar to RandomPartioner but uses Murmur3_128

#   Hash Function instead of md5.  When in doubt, this is the best option.

# - ByteOrderedPartitioner orders rows lexically by key bytes.  BOP allows

#   scanning rows in key order, but the ordering can generate hot spots

#   for sequential insertion workloads.

# - OrderPreservingPartitioner is an obsolete form of BOP, that stores

# - keys in a less-efficient format and only works with keys that are

#   UTF8-encoded Strings.

# - CollatingOPP collates 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.  Cassandra

# will spread data evenly across them, subject to the granularity of

# the configured compaction strategy.

data_file_directories:

    - target/embeddedCassandra/data


# commit log

commitlog_directory: target/embeddedCassandra/commitlog


# policy for data disk failures:

# stop: shut down gossip and Thrift, leaving the node effectively dead, but

#       can still be inspected 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 contain the entire row,

# 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

# save the key 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 off-heap memory allocator.  Affects storage engine metadata as

# well as caches.  Experiments show that JEMAlloc saves some memory

# than the native GCC allocator (i.e., JEMalloc is more

# fragmentation-resistant).

#

# Supported values are: NativeAllocator, JEMallocAllocator

#

# If you intend to use JEMallocAllocator you have to install JEMalloc as library and

# modify cassandra-env.sh as directed in the file.

#

# Defaults to NativeAllocator

# memory_allocator: NativeAllocator


# saved caches

saved_caches_directory: target/embeddedCassandra/saved_caches


# commitlog_sync may be either "periodic" or "batch."

# When in batch mode, Cassandra won't ack writes until the commit log

# has been fsynced to disk.  It will wait up to

# commitlog_sync_batch_window_in_ms milliseconds for other writes, before

# performing the sync.

#

# commitlog_sync: batch

# commitlog_sync_batch_window_in_ms: 50

#

# the other option is "periodic" where writes may be acked immediately

# and the CommitLog is simply synced every commitlog_sync_period_in_ms

# milliseconds.  By default this allows 1024*(CPU cores) pending

# entries on the commitlog queue.  If you are writing very large blobs,

# you should reduce that; 16*cores works reasonably well for 1MB blobs.

# It should be at least as large as the concurrent_writes setting.

commitlog_sync: periodic

commitlog_sync_period_in_ms: 10000

# commitlog_periodic_queue_size:


# The size of the individual commitlog file segments.  A commitlog

# segment may be archived, deleted, or recycled once all the data

# in it (potentially from each columnfamily in the system) has been

# flushed to sstables.

#

# The default size is 32, which is almost always fine, but if you are

# archiving commitlog segments (see commitlog_archiving.properties),

# then you probably want a finer granularity of archiving; 8 or 16 MB

# is reasonable.

commitlog_segment_size_in_mb: 32


# any class that implements the SeedProvider interface and has a

# constructor that takes a Map<String, String> of parameters will do.

seed_provider:

    # Addresses of hosts that are deemed contact points.

    # Cassandra nodes use this list of hosts to find each other and learn

    # the topology of the ring.  You must change this if you are running

    # multiple nodes!

    - class_name: org.apache.cassandra.locator.SimpleSeedProvider

      parameters:

          # seeds is actually a comma-delimited list of addresses.

          # Ex: "<ip1>,<ip2>,<ip3>"

          - seeds: "127.0.0.1"


# 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 sstable-reading buffers.  Defaults to

# the smaller of 1/4 of heap or 512MB.

# file_cache_size_in_mb: 512


# Total memory to use for memtablesCassandra 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 SSDs; not

# necessarily on platters.

trickle_fsync: false

trickle_fsync_interval_in_kb: 10240


# TCP port, for commands and data

storage_port: 7500


# SSL port, for encrypted communication.  Unused unless enabled in

# encryption_options

ssl_storage_port: 7501


# Address to bind to and tell other Cassandra nodes to connect to. You

# _must_ change this if you want multiple nodes to be able to

# communicate!

#

# Leaving it blank leaves it up to InetAddress.getLocalHost(). This

# will always do the Right Thing _if_ the node is properly configured

# (hostname, name resolution, etc), and the Right Thing is to use the

# address associated with the hostname (it might not be).

#

# Setting this to 0.0.0.0 is always wrong.

listen_address: 127.0.0.1


# Address to broadcast to other Cassandra nodes

# Leaving this blank will set it to the same value as listen_address

# broadcast_address: 1.2.3.4


# Internode authentication backend, implementing IInternodeAuthenticator;

# used to allow/disallow connections from peer nodes.

# internode_authenticator: org.apache.cassandra.auth.AllowAllInternodeAuthenticator


# Whether to start the native transport server.

# 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: 9542

# The maximum threads for handling requests when the native transport is used.

# This is similar to rpc_max_threads though the default differs slightly (and

# there is no native_transport_min_threads, idle threads will always be stopped

# after 30 seconds).

# native_transport_max_threads: 128


# Whether to start the thrift rpc server.

start_rpc: true


# The address to bind the Thrift RPC service and native transport

# server -- clients connect here.

#

# Leaving this blank has the same effect it does for ListenAddress,

# (i.e. it will be based on the configured hostname of the node).

#

# Note that unlike ListenAddress above, it is allowed to specify 0.0.0.0

# here if you want to listen on all interfaces, but that will break clients

# that rely on node auto-discovery.

rpc_address: localhost

# port for Thrift to listen for clients on

rpc_port: 9560


# enable or disable keepalive on rpc connections

rpc_keepalive: true


# Cassandra provides two 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, 180KB 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: hsha


# 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 provides no protection against clients overwhelming the server. You are

# encouraged to set a maximum that makes sense for you in production, but do keep in mind that

# rpc_max_threads represents the maximum number of client requests this server may execute concurrently.

#

# rpc_min_threads: 16

# rpc_max_threads: 2048


# uncomment to set socket buffer sizes on rpc connections

# rpc_send_buff_size_in_bytes:

# rpc_recv_buff_size_in_bytes:


# Uncomment to set socket buffer size for internode communication

# Note that when setting this, the buffer size is limited by net.core.wmem_max

# and when not setting it it is defined by net.ipv4.tcp_wmem

# See:

# /proc/sys/net/core/wmem_max

# /proc/sys/net/core/rmem_max

# /proc/sys/net/ipv4/tcp_wmem

# /proc/sys/net/ipv4/tcp_wmem

# and: man tcp

# internode_send_buff_size_in_bytes:

# internode_recv_buff_size_in_bytes:


# Frame size for thrift (maximum message length).

thrift_framed_transport_size_in_mb: 15


# 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


# When executing a scan, within or across a partition, we need to keep the

# tombstones seen in memory so we can return them to the coordinator, which

# will use them to make sure other replicas also know about the deleted rows.

# With workloads that generate a lot of tombstones, this can cause performance

# problems and even exaust the server heap.

# (http://www.datastax.com/dev/blog/cassandra-anti-patterns-queues-and-queue-like-datasets)

# Adjust the thresholds here if you understand the dangers and want to

# scan more tombstones anyway.  These thresholds may also be adjusted at runtime

# using the StorageService mbean.

tombstone_warn_threshold: 1000

tombstone_failure_threshold: 100000


# Add column indexes to a row after its contents reach this size.

# Increase if your column values are large, or if you have a very large

# number of columns.  The competing causes are, Cassandra has to

# deserialize this much of the row to read a single column, so you want

# it to be small - at least if you do many partial-row reads - but all

# the index data is read for each access, so you don't want to generate

# that wastefully either.

column_index_size_in_kb: 64


# Size limit for rows being compacted in memory.  Larger rows will spill

# over to disk and use a slower two-pass compaction process.  A message

# will be logged specifying the row key.

in_memory_compaction_limit_in_mb: 64


# Number of simultaneous compactions to allow, NOT including

# validation "compactions" for anti-entropy repair.  Simultaneous

# compactions can help preserve read performance in a mixed read/write

# workload, by mitigating the tendency of small sstables to accumulate

# during a single long running compactions. The default is usually

# fine and if you experience problems with compaction running too

# slowly or too fast, you should look at

# compaction_throughput_mb_per_sec first.

#

# concurrent_compactors defaults to the number of cores.

# Uncomment to make compaction mono-threaded, the pre-0.8 default.

#concurrent_compactors: 1


# Multi-threaded compaction. When enabled, each compaction will use

# up to one thread per core, plus one thread per sstable being merged.

# This is usually only useful for SSD-based hardware: otherwise,

# your concern is usually to get compaction to do LESS i/o (see:

# compaction_throughput_mb_per_sec), not more.

multithreaded_compaction: false


# Throttles compaction to the given total throughput across the entire

# system. The faster you insert data, the faster you need to compact in

# order to keep the sstable count down, but in general, setting this to

# 16 to 32 times the rate you are inserting data is more than sufficient.

# Setting this to 0 disables throttling. Note that this account for all types

# of compaction, including validation compaction.

compaction_throughput_mb_per_sec: 16


# Track cached row keys during compaction, and re-cache their new

# positions in the compacted sstable.  Disable if you use really large

# key caches.

compaction_preheat_key_cache: true


# Throttles all outbound streaming file transfers on this node to the

# given total throughput in Mbps. This is necessary because Cassandra does

# mostly sequential IO when streaming data during bootstrap or repair, which

# can lead to saturating the network connection and degrading rpc performance.

# When unset, the default is 200 Mbps or 25 MB/s.

# stream_throughput_outbound_megabits_per_sec: 200


# How long the coordinator should wait for read operations to complete

read_request_timeout_in_ms: 5000

# 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: 2000

# How long a coordinator should continue to retry a CAS operation

# that contends with other proposals for the same row

cas_contention_timeout_in_ms: 1000

# How long the coordinator should wait for truncates to complete

# (This can be much longer, because unless auto_snapshot is disabled

# we need to flush first so we can snapshot before removing the data.)

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, replicas will assume that requests

# were forwarded to them instantly by the coordinator, which means that

# under overload conditions we will waste that much extra time processing

# already-timed-out requests.

#

# 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 identifier based on which to perform

# the request scheduling. Currently the only valid option is keyspace.

# request_scheduler_id: keyspace


# 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/JSSERefGuide.html#CreateKeystore

#

server_encryption_options:

    internode_encryption: none

    keystore: conf/.keystore

    keystore_password: cassandra

    truststore: conf/.truststore

    truststore_password: cassandra

    # More advanced defaults below:

    # protocol: TLS

    # algorithm: SunX509

    # store_type: JKS

    # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA]

    # require_client_auth: false


# enable or disable client/server encryption.

client_encryption_options:

    enabled: false

    keystore: conf/.keystore

    keystore_password: cassandra

    # require_client_auth: false

    # Set trustore and truststore_password if require_client_auth is true

    # truststore: conf/.truststore

    # truststore_password: cassandra

    # More advanced defaults below:

    # protocol: TLS

    # algorithm: SunX509

    # store_type: JKS

    # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA]


# internode_compression controls whether traffic between nodes is

# compressed.

# can be:  all  - all traffic is compressed

#          dc   - traffic between different datacenters is compressed

#          none - nothing is compressed.

internode_compression: all


# Enable or disable tcp_nodelay for inter-dc communication.

# Disabling it will result in larger (but fewer) network packets being sent,

# reducing overhead from the TCP protocol itself, at the cost of increasing

# latency if you block for cross-datacenter responses.

inter_dc_tcp_nodelay: false


# Enable or disable kernel page cache preheating from contents of the key cache after compaction.

# When enabled it would preheat only first "page" (4KB) of each row to optimize

# for sequential access. Note: This could be harmful for fat rows, see CASSANDRA-4937

# for further details on that topic.

preheat_kernel_page_cache: false


SimpleClient.java

package pl.allegro.cassy.datastax;


import com.datastax.driver.core.Cluster;

import com.datastax.driver.core.Host;

import com.datastax.driver.core.Metadata;

import com.datastax.driver.core.Session;

import pl.allegro.cassy.Client;


public class SimpleClient implements Client {


    private Cluster cluster;


    private Session session;



    @Override

    public Session connect(String cassandraHost, int cassandraPort, String keyspaceName) {

        cluster = Cluster.builder()

                         .withPort(cassandraPort)

                         .addContactPoint(cassandraHost)

                         .build();


        session = cluster.connect(keyspaceName);

        printMetaData();


        return session;

    }


    @Override

    public void disconnect() {

        if (this.cluster != null) {

            this.cluster.shutdown();

            this.cluster = null;

        }

    }


    @Override

    public Cluster getConnection() {

        return this.cluster;

    }


    private void printMetaData() {

        Metadata metadata = cluster.getMetadata();


        System.out.printf("Connected to cluster %s\n", metadata.getClusterName());


        // iterate all hosts in the cluster

        for (Host host : metadata.getAllHosts()) {

            System.out.printf("Datacenter: %s; Host: %s; Rack: %s\n", host.getDatacenter(),

                                                                      host.getAddress(),

                                                                      host.getRack()

            );

        }

    }

}


Client.java

package pl.allegro.cassy;


import com.datastax.driver.core.Cluster;

import com.datastax.driver.core.Session;


public interface Client {


    public Session connect(String cassandraHost, int cassandraPort, String keyspaceName);


    public void disconnect();


    public Cluster getConnection();



}





import org.cassandraunit.utils.EmbeddedCassandraServerHelper;

import org.junit.Assert;

import org.junit.BeforeClass;

import org.junit.Test;


import pl.allegro.cassy.Client;

import pl.allegro.cassy.datastax.SimpleClient;


import com.datastax.driver.core.Session;


public class T {

    @BeforeClass

    public static void setup() throws Exception {

        EmbeddedCassandraServerHelper.startEmbeddedCassandra("cassandra.yaml");


        // issue!

        //CQLDataLoader loader = new CQLDataLoader("127.0.0.1", 9560);

        // loader.load(new ClassPathCQLDataSet("data.cql"));

    }


    @Test

    public void connect() {

        System.out.println("-- connect");

        Session session = null;

        Client client = new SimpleClient();

        session = client.connect("127.0.0.1", 9542, "system");

        

        Assert.assertNotNull(session);

        System.out.println("   session name : " + session.getCluster().getClusterName());

        System.out.println("   session connect timeout: " + session.getCluster().getConfiguration().getSocketOptions().getConnectTimeoutMillis());

    }


    @Test

    public void disconnect() {

    System.out.println("-- disconnect ");

        Client client = new SimpleClient();

        client.connect("127.0.0.1", 9542, "system");

        client.disconnect();

    }

}





테스트 결과는 다음과 같다. junit 테스트는 모두 작동 완료했다. 


SLF4J: Class path contains multiple SLF4J bindings.

SLF4J: Found binding in [jar:file:/Users/knight/.m2/repository/org/slf4j/slf4j-simple/1.7.5/slf4j-simple-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]

SLF4J: Found binding in [jar:file:/Users/knight/.m2/repository/org/slf4j/slf4j-log4j12/1.6.1/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]

SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.

SLF4J: Actual binding is of type [org.slf4j.impl.SimpleLoggerFactory]

[main] INFO org.apache.cassandra.config.YamlConfigurationLoader - Loading settings from file:/Users/knight/git/cassyunit-2.0-test/target/embeddedCassandra/cassandra.yaml

[main] INFO org.apache.cassandra.config.DatabaseDescriptor - Data files directories: [target/embeddedCassandra/data]

[main] INFO org.apache.cassandra.config.DatabaseDescriptor - Commit log directory: target/embeddedCassandra/commitlog

[main] INFO org.apache.cassandra.config.DatabaseDescriptor - DiskAccessMode 'auto' determined to be mmap, indexAccessMode is mmap

[main] INFO org.apache.cassandra.config.DatabaseDescriptor - disk_failure_policy is stop

[main] INFO org.apache.cassandra.config.DatabaseDescriptor - Global memtable threshold is enabled at 219MB

[main] INFO org.apache.cassandra.config.DatabaseDescriptor - Not using multi-threaded compaction

[pool-1-thread-1] INFO org.apache.cassandra.service.CassandraDaemon - JVM vendor/version: Java HotSpot(TM) 64-Bit Server VM/1.7.0_11

[pool-1-thread-1] INFO org.apache.cassandra.service.CassandraDaemon - Heap size: 61997056/920911872

[pool-1-thread-1] INFO org.apache.cassandra.service.CassandraDaemon - Classpath: /Users/knight/git/cassyunit-2.0-test/target/test-classes:/Users/knight/git/cassyunit-2.0-test/target/classes:/Users/knight/.m2/repository/javax/validation/validation-api/1.0.0.GA/validation-api-1.0.0.GA.jar:/Users/knight/.m2/repository/javax/xml/bind/jaxb-api/2.2.3/jaxb-api-2.2.3.jar:/Users/knight/.m2/repository/javax/xml/stream/stax-api/1.0-2/stax-api-1.0-2.jar:/Users/knight/.m2/repository/javax/activation/activation/1.1/activation-1.1.jar:/Users/knight/.m2/repository/org/slf4j/slf4j-simple/1.7.5/slf4j-simple-1.7.5.jar:/Users/knight/.m2/repository/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar:/Users/knight/.m2/repository/org/cassandraunit/cassandra-unit/2.0.2.0-SNAPSHOT/cassandra-unit-2.0.2.0-SNAPSHOT.jar:/Users/knight/.m2/repository/com/datastax/cassandra/cassandra-driver-core/2.0.0-rc1/cassandra-driver-core-2.0.0-rc1.jar:/Users/knight/.m2/repository/io/netty/netty/3.7.0.Final/netty-3.7.0.Final.jar:/Users/knight/.m2/repository/com/google/guava/guava/15.0/guava-15.0.jar:/Users/knight/.m2/repository/org/codehaus/jackson/jackson-mapper-asl/1.9.13/jackson-mapper-asl-1.9.13.jar:/Users/knight/.m2/repository/com/codahale/metrics/metrics-core/3.0.1/metrics-core-3.0.1.jar:/Users/knight/.m2/repository/junit/junit/4.11/junit-4.11.jar:/Users/knight/.m2/repository/org/hamcrest/hamcrest-all/1.1/hamcrest-all-1.1.jar:/Users/knight/.m2/repository/org/apache/cassandra/cassandra-all/2.0.2/cassandra-all-2.0.2.jar:/Users/knight/.m2/repository/org/xerial/snappy/snappy-java/1.0.5/snappy-java-1.0.5.jar:/Users/knight/.m2/repository/net/jpountz/lz4/lz4/1.2.0/lz4-1.2.0.jar:/Users/knight/.m2/repository/com/ning/compress-lzf/0.8.4/compress-lzf-0.8.4.jar:/Users/knight/.m2/repository/commons-cli/commons-cli/1.2/commons-cli-1.2.jar:/Users/knight/.m2/repository/commons-codec/commons-codec/1.2/commons-codec-1.2.jar:/Users/knight/.m2/repository/org/apache/commons/commons-lang3/3.1/commons-lang3-3.1.jar:/Users/knight/.m2/repository/com/googlecode/concurrentlinkedhashmap/concurrentlinkedhashmap-lru/1.3/concurrentlinkedhashmap-lru-1.3.jar:/Users/knight/.m2/repository/org/antlr/antlr/3.2/antlr-3.2.jar:/Users/knight/.m2/repository/org/antlr/antlr-runtime/3.2/antlr-runtime-3.2.jar:/Users/knight/.m2/repository/org/antlr/stringtemplate/3.2/stringtemplate-3.2.jar:/Users/knight/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7.jar:/Users/knight/.m2/repository/org/codehaus/jackson/jackson-core-asl/1.9.2/jackson-core-asl-1.9.2.jar:/Users/knight/.m2/repository/jline/jline/1.0/jline-1.0.jar:/Users/knight/.m2/repository/com/googlecode/json-simple/json-simple/1.1/json-simple-1.1.jar:/Users/knight/.m2/repository/com/github/stephenc/high-scale-lib/high-scale-lib/1.1.2/high-scale-lib-1.1.2.jar:/Users/knight/.m2/repository/org/yaml/snakeyaml/1.13/snakeyaml-1.13.jar:/Users/knight/.m2/repository/edu/stanford/ppl/snaptree/0.1/snaptree-0.1.jar:/Users/knight/.m2/repository/org/mindrot/jbcrypt/0.3m/jbcrypt-0.3m.jar:/Users/knight/.m2/repository/com/yammer/metrics/metrics-core/2.2.0/metrics-core-2.2.0.jar:/Users/knight/.m2/repository/com/addthis/metrics/reporter-config/2.1.0/reporter-config-2.1.0.jar:/Users/knight/.m2/repository/org/hibernate/hibernate-validator/4.3.0.Final/hibernate-validator-4.3.0.Final.jar:/Users/knight/.m2/repository/org/jboss/logging/jboss-logging/3.1.0.CR2/jboss-logging-3.1.0.CR2.jar:/Users/knight/.m2/repository/com/thinkaurelius/thrift/thrift-server/0.3.2/thrift-server-0.3.2.jar:/Users/knight/.m2/repository/com/lmax/disruptor/3.0.1/disruptor-3.0.1.jar:/Users/knight/.m2/repository/org/apache/thrift/libthrift/0.9.1/libthrift-0.9.1.jar:/Users/knight/.m2/repository/org/apache/httpcomponents/httpclient/4.2.5/httpclient-4.2.5.jar:/Users/knight/.m2/repository/org/apache/httpcomponents/httpcore/4.2.4/httpcore-4.2.4.jar:/Users/knight/.m2/repository/org/apache/cassandra/cassandra-thrift/2.0.2/cassandra-thrift-2.0.2.jar:/Users/knight/.m2/repository/com/github/stephenc/jamm/0.2.5/jamm-0.2.5.jar:/Users/knight/.m2/repository/org/jboss/netty/netty/3.2.9.Final/netty-3.2.9.Final.jar:/Users/knight/.m2/repository/org/slf4j/slf4j-log4j12/1.6.1/slf4j-log4j12-1.6.1.jar:/Users/knight/.m2/repository/log4j/log4j/1.2.16/log4j-1.2.16.jar:/Users/knight/.m2/repository/com/sun/xml/bind/jaxb-impl/2.2.4-1/jaxb-impl-2.2.4-1.jar:/Users/knight/.m2/repository/org/hectorclient/hector-core/1.1-4/hector-core-1.1-4.jar:/Users/knight/.m2/repository/commons-lang/commons-lang/2.6/commons-lang-2.6.jar:/Users/knight/.m2/repository/commons-pool/commons-pool/1.5.3/commons-pool-1.5.3.jar:/Users/knight/.m2/repository/com/github/stephenc/eaio-uuid/uuid/3.2.0/uuid-3.2.0.jar:/Users/knight/.m2/repository/com/ecyrd/speed4j/speed4j/0.9/speed4j-0.9.jar:/Users/knight/.m2/repository/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar:/Users/knight/springsource/sts-3.4.0.RELEASE/configuration/org.eclipse.osgi/bundles/402/1/.cp/:/Users/knight/springsource/sts-3.4.0.RELEASE/configuration/org.eclipse.osgi/bundles/401/1/.cp/

[pool-1-thread-1] INFO org.apache.cassandra.utils.CLibrary - JNA not found. Native methods will be disabled.

[pool-1-thread-1] INFO org.apache.cassandra.service.CacheService - Initializing key cache with capacity of 2 MBs.

[pool-1-thread-1] INFO org.apache.cassandra.service.CacheService - Scheduling key cache save to each 14400 seconds (going to save all keys).

[pool-1-thread-1] INFO org.apache.cassandra.service.CacheService - Initializing row cache with capacity of 0 MBs

[pool-1-thread-1] INFO org.apache.cassandra.service.CacheService - Scheduling row cache save to each 0 seconds (going to save all keys).

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.schema_triggers

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.compaction_history

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.batchlog

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.sstable_activity

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.peer_events

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.compactions_in_progress

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.hints

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.schema_keyspaces

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.range_xfers

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.schema_columnfamilies

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.NodeIdInfo

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.paxos

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.schema_columns

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.IndexInfo

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.peers

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system.local

[pool-1-thread-1] INFO org.apache.cassandra.config.DatabaseDescriptor - Couldn't detect any schema definitions in local storage.

[pool-1-thread-1] INFO org.apache.cassandra.config.DatabaseDescriptor - To create keyspaces and column families, see 'help create' in cqlsh.

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Enqueuing flush of Memtable-local@1745669410(144/1440 serialized/live bytes, 6 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Writing Memtable-local@1745669410(144/1440 serialized/live bytes, 6 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Completed flushing target/embeddedCassandra/data/system/local/system-local-jb-1-Data.db (174 bytes) for commitlog position ReplayPosition(segmentId=1384769522823, position=412)

[pool-1-thread-1] INFO org.apache.cassandra.db.commitlog.CommitLog - Replaying target/embeddedCassandra/commitlog/CommitLog-3-1384769522822.log

[pool-1-thread-1] INFO org.apache.cassandra.db.commitlog.CommitLogReplayer - Replaying target/embeddedCassandra/commitlog/CommitLog-3-1384769522822.log

[pool-1-thread-1] INFO org.apache.cassandra.db.commitlog.CommitLogReplayer - Finished reading target/embeddedCassandra/commitlog/CommitLog-3-1384769522822.log

[pool-1-thread-1] INFO org.apache.cassandra.db.commitlog.CommitLog - Log replay complete, 0 replayed mutations

[pool-1-thread-1] INFO org.apache.cassandra.service.StorageService - Cassandra version: 2.0.2

[pool-1-thread-1] INFO org.apache.cassandra.service.StorageService - Thrift API version: 19.38.0

[pool-1-thread-1] INFO org.apache.cassandra.service.StorageService - CQL supported versions: 2.0.0,3.1.1 (default: 3.1.1)

[pool-1-thread-1] INFO org.apache.cassandra.service.StorageService - Loading persisted ring state

[pool-1-thread-1] WARN org.apache.cassandra.db.SystemKeyspace - No host ID found, created 8bdf9e5f-3493-4b52-83ff-4b0b12554c1c (Note: This should happen exactly once per node).

[pool-1-thread-1] INFO org.apache.cassandra.service.StorageService - Starting up server gossip

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Enqueuing flush of Memtable-local@1612558095(320/3200 serialized/live bytes, 12 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Writing Memtable-local@1612558095(320/3200 serialized/live bytes, 12 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Completed flushing target/embeddedCassandra/data/system/local/system-local-jb-2-Data.db (301 bytes) for commitlog position ReplayPosition(segmentId=1384769522823, position=82225)

[pool-1-thread-1] INFO org.apache.cassandra.net.MessagingService - Starting Messaging Service on port 7500

[pool-1-thread-1] INFO org.apache.cassandra.service.StorageService - Generated random tokens. tokens are [-7897495258110946089, -993618140451193622, -741769360282693962, -7365786459655180195, -6996710276778530694, -1805677852708217721, 1173945514353441977, 5838205476682460320, 4281992790760632189, 2419231774471446648, -1166694029847650386, 7262343478793891428, 2423383570357751226, 2116311952626479630, 2155358960048433342, -1834274706856210316, 2687645334969923521, -4638162304885887759, -8091952146158016939, -771155582672544265, 6508501330104885054, -90021061479948672, -970802962310490309, 3658320502290076717, -9016857001732700721, 5850596101715799811, -5816647359882856006, 9024293304198565969, 6392520850732929306, 559089783979280006, 8099155292590458437, -6271948727393445324, 7385052247510557871, -6204171235250648610, -5242026646477551348, 524232974521637404, -2750762283863900828, 2673970317916605471, -3517618708956987990, -2559651028284195467, -5365623817531883925, 1896887247352164763, -254922145894196814, 7148505448955709054, 5455783798975863066, -7905743912886185926, -6913990237302467512, -3900083263238480014, -300191716008264302, 5993436098806299193, -1375986188848960027, -7601519015111664207, -2664437913274766533, 5893592981009676813, 293043419218964469, 8659122455041574771, -141736725893861802, -197100985567820575, 6494910323686262055, 1369222166653577587, -901613166521293950, 7735113709881832752, -5488043932175239119, -6104445712563488485, 1325804735841036092, 2768039918136391990, 3007262876838902265, 9169852366190971443, -8223834675697609811, 828238590501297958, 5017023631689620585, -8868822128780155513, -2444048423001132195, -9163742028306194768, 565900915313702358, -3703350178808181121, -8773976004206028814, 3052852523418293888, -2022179219475515661, 9188732132359748067, 1737820293356112590, 3765918105761241412, 519833407594445560, 5146368331470882714, 2831562007524108108, 5463943589420270988, -5688775091959849715, -1281699718016081471, 6455227726713184128, -1996506638604254698, 704624523657793214, -3037612302558591207, 5024072307681718667, -7266673853770330853, 4242471679611020159, 4956638230402718818, -2362773410941766983, -3981993887863635605, 1557999930878030676, 2463910867318332315, 5369587287570977748, 2469291184722093792, 5916806701316154023, 7558765883469563887, -5422506410380679618, -4225476447154517484, -2650458316641898633, 8511690844999204614, 6536068411116972446, 5546376054407093839, -8946544327604168816, 2748162759792467365, 5368324584492585790, -6031932692066687628, -3667730604010674766, 1153775044181340284, 5092676636153396688, 3021524714754838582, 5321345290946985538, -5983799511060445032, 8958938536391748596, 2312186152666380265, -2241142629934566023, 424702417853746392, -831516986220828184, -8877486524979488104, -7081990162539352833, 885940789545590172, 7313791096238456419, -7471092678943978078, -4486569438179523191, -3392848442139904779, -232380745752110954, 3670571989087625663, 1371267986474029102, 8050466031038065584, -2669056432623234320, 7047995051947828540, -1127278145044095210, -5084991884110266512, -6985701253681661559, 5086749927138490856, -7655670214200876893, -2178591702579170601, -998279180117886112, 5715122411890225087, -5621665586658079456, 7024553038400483474, 1649431723222167031, -1576062719392646313, 3740794267997377733, 6016125052250013341, 1421740322127805419, 2925758069764057582, -8099554026529040208, -240621446974348012, 43108829771781180, 1155045055138286872, 2558277703144832410, -3955485961286090200, 9151457387027004416, -8514643314886697782, 2690655293592479872, -8589755388701167407, -3986294404020955080, -4428326991833971904, -5179706026140210367, 4163440319054215180, -6964157234782005438, 5985303829708487918, 2910359288798234326, 4310369204703870467, -7170991954851418171, 3905555449347845182, -6535039815683472112, 7227536772511147725, -3596078704480759994, 7955947048754694122, -2201544570292534796, 6327035662361745398, 2119232967185821477, -4312204980467488616, -948307019540001527, 95973398253982969, -3818691759247143921, -2878589428638084863, -6432678153824136629, -7848450127604349949, -7930991838782710923, 8148241022209731614, -8221357459178038818, 2381281788685989489, -4926863107303466703, 8557362949934966113, 4456199168021863081, -1300148220769384831, -1292792255664381526, 7175676531965857695, 6234476973744963615, 5192510229338295509, 2544496751577163319, 963098149512324057, -2809805077844872419, 1429179268284480463, -3314419216276692839, 8059672370583251981, -8930169656969335624, -8593378848393845099, 3257187957561045798, -6434129975042123952, 7380410784313701833, -7978996550271630411, 7674946001097203094, 3885927966587556534, -8827632249055872288, 5976660820898290023, 7933850666550013612, 1509934050780416155, 4695538661043795074, 6259369823698750307, -6083411833191744858, 5344161221116991513, -3200529027137048960, 8549409082522883515, -2899435703831967011, -4941569445391403078, 4167261943141531355, 2261894256113385002, -4702756518974544549, 428149618493437793, -6715557104799451720, -7118311070443632199, 4090852646575516292, 2219249805620514712, 5919947735376317944, -8468587022004416840, -1130797596200210995, 693066955998225080, -4882854129587709381, 5587243421286460433, -7803542878084798028, -8406503715768141379, -4568930399575760023, 8480910328410055651, 3775431410073062474, 6197839568383366976, -4689368830782225873, -4843051495780306207, 7408360421939436522, 2949916053542854722, 4656781539546967727, 2064909635358889288, 6930938933995468822, 4857184730863785088, 6373094938167720835, 9157351208706347855]

[pool-1-thread-1] INFO org.apache.cassandra.service.MigrationManager - Create new Keyspace: system_traces, rep strategy:SimpleStrategy{org.apache.cassandra.config.CFMetaData@16d63f65[cfId=c5e99f16-8677-3914-b17e-960613512345,ksName=system_traces,cfName=sessions,cfType=Standard,comparator=org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.ColumnToCollectionType(706172616d6574657273:org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.UTF8Type))),comment=traced sessions,readRepairChance=0.0,dclocalReadRepairChance=0.0,replicateOnWrite=true,gcGraceSeconds=0,defaultValidator=org.apache.cassandra.db.marshal.BytesType,keyValidator=org.apache.cassandra.db.marshal.UUIDType,minCompactionThreshold=4,maxCompactionThreshold=32,column_metadata={java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]=ColumnDefinition{name=73657373696f6e5f6964, validator=org.apache.cassandra.db.marshal.UUIDType, type=PARTITION_KEY, componentIndex=null, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=8 cap=8]=ColumnDefinition{name=6475726174696f6e, validator=org.apache.cassandra.db.marshal.Int32Type, type=REGULAR, componentIndex=0, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]=ColumnDefinition{name=706172616d6574657273, validator=org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.UTF8Type), type=REGULAR, componentIndex=0, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]=ColumnDefinition{name=737461727465645f6174, validator=org.apache.cassandra.db.marshal.TimestampType, type=REGULAR, componentIndex=0, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=7 cap=7]=ColumnDefinition{name=72657175657374, validator=org.apache.cassandra.db.marshal.UTF8Type, type=REGULAR, componentIndex=0, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=11 cap=11]=ColumnDefinition{name=636f6f7264696e61746f72, validator=org.apache.cassandra.db.marshal.InetAddressType, type=REGULAR, componentIndex=0, indexName=null, indexType=null}},compactionStrategyClass=class org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy,compactionStrategyOptions={},compressionOptions={sstable_compression=org.apache.cassandra.io.compress.LZ4Compressor},bloomFilterFpChance=0.01,memtable_flush_period_in_ms=0,caching=KEYS_ONLY,defaultTimeToLive=0,speculative_retry=99.0PERCENTILE,indexInterval=128,populateIoCacheOnFlush=false,droppedColumns={},triggers={}], org.apache.cassandra.config.CFMetaData@3d80023a[cfId=8826e8e9-e16a-3728-8753-3bc1fc713c25,ksName=system_traces,cfName=events,cfType=Standard,comparator=org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.TimeUUIDType,org.apache.cassandra.db.marshal.UTF8Type),comment=,readRepairChance=0.0,dclocalReadRepairChance=0.0,replicateOnWrite=true,gcGraceSeconds=0,defaultValidator=org.apache.cassandra.db.marshal.BytesType,keyValidator=org.apache.cassandra.db.marshal.UUIDType,minCompactionThreshold=4,maxCompactionThreshold=32,column_metadata={java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]=ColumnDefinition{name=73657373696f6e5f6964, validator=org.apache.cassandra.db.marshal.UUIDType, type=PARTITION_KEY, componentIndex=null, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=6 cap=6]=ColumnDefinition{name=736f75726365, validator=org.apache.cassandra.db.marshal.InetAddressType, type=REGULAR, componentIndex=1, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=6 cap=6]=ColumnDefinition{name=746872656164, validator=org.apache.cassandra.db.marshal.UTF8Type, type=REGULAR, componentIndex=1, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=8 cap=8]=ColumnDefinition{name=6163746976697479, validator=org.apache.cassandra.db.marshal.UTF8Type, type=REGULAR, componentIndex=1, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=14 cap=14]=ColumnDefinition{name=736f757263655f656c6170736564, validator=org.apache.cassandra.db.marshal.Int32Type, type=REGULAR, componentIndex=1, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=8 cap=8]=ColumnDefinition{name=6576656e745f6964, validator=org.apache.cassandra.db.marshal.TimeUUIDType, type=CLUSTERING_KEY, componentIndex=0, indexName=null, indexType=null}},compactionStrategyClass=class org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy,compactionStrategyOptions={},compressionOptions={sstable_compression=org.apache.cassandra.io.compress.LZ4Compressor},bloomFilterFpChance=0.01,memtable_flush_period_in_ms=0,caching=KEYS_ONLY,defaultTimeToLive=0,speculative_retry=99.0PERCENTILE,indexInterval=128,populateIoCacheOnFlush=false,droppedColumns={},triggers={}]}, strategy_options: {replication_factor=2}, durable_writes: true

[MigrationStage:1] INFO org.apache.cassandra.db.ColumnFamilyStore - Enqueuing flush of Memtable-schema_keyspaces@645015487(251/2510 serialized/live bytes, 7 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Writing Memtable-schema_keyspaces@645015487(251/2510 serialized/live bytes, 7 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Completed flushing target/embeddedCassandra/data/system/schema_keyspaces/system-schema_keyspaces-jb-1-Data.db (216 bytes) for commitlog position ReplayPosition(segmentId=1384769522823, position=90960)

[MigrationStage:1] INFO org.apache.cassandra.db.ColumnFamilyStore - Enqueuing flush of Memtable-schema_columnfamilies@1026641493(28865/288650 serialized/live bytes, 451 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Writing Memtable-schema_columnfamilies@1026641493(28865/288650 serialized/live bytes, 451 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Completed flushing target/embeddedCassandra/data/system/schema_columnfamilies/system-schema_columnfamilies-jb-1-Data.db (5716 bytes) for commitlog position ReplayPosition(segmentId=1384769522823, position=90960)

[MigrationStage:1] INFO org.apache.cassandra.db.ColumnFamilyStore - Enqueuing flush of Memtable-schema_columns@440702060(51047/510470 serialized/live bytes, 848 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Writing Memtable-schema_columns@440702060(51047/510470 serialized/live bytes, 848 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Completed flushing target/embeddedCassandra/data/system/schema_columns/system-schema_columns-jb-1-Data.db (10107 bytes) for commitlog position ReplayPosition(segmentId=1384769522823, position=90960)

[MigrationStage:1] INFO org.apache.cassandra.db.DefsTables - Loading org.apache.cassandra.config.CFMetaData@213fdeca[cfId=c5e99f16-8677-3914-b17e-960613512345,ksName=system_traces,cfName=sessions,cfType=Standard,comparator=org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.ColumnToCollectionType(706172616d6574657273:org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.UTF8Type))),comment=traced sessions,readRepairChance=0.0,dclocalReadRepairChance=0.0,replicateOnWrite=true,gcGraceSeconds=0,defaultValidator=org.apache.cassandra.db.marshal.BytesType,keyValidator=org.apache.cassandra.db.marshal.UUIDType,minCompactionThreshold=4,maxCompactionThreshold=32,column_metadata={java.nio.HeapByteBuffer[pos=0 lim=8 cap=8]=ColumnDefinition{name=6475726174696f6e, validator=org.apache.cassandra.db.marshal.Int32Type, type=REGULAR, componentIndex=0, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]=ColumnDefinition{name=73657373696f6e5f6964, validator=org.apache.cassandra.db.marshal.UUIDType, type=PARTITION_KEY, componentIndex=null, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]=ColumnDefinition{name=706172616d6574657273, validator=org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.UTF8Type), type=REGULAR, componentIndex=0, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]=ColumnDefinition{name=737461727465645f6174, validator=org.apache.cassandra.db.marshal.TimestampType, type=REGULAR, componentIndex=0, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=7 cap=7]=ColumnDefinition{name=72657175657374, validator=org.apache.cassandra.db.marshal.UTF8Type, type=REGULAR, componentIndex=0, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=11 cap=11]=ColumnDefinition{name=636f6f7264696e61746f72, validator=org.apache.cassandra.db.marshal.InetAddressType, type=REGULAR, componentIndex=0, indexName=null, indexType=null}},compactionStrategyClass=class org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy,compactionStrategyOptions={},compressionOptions={sstable_compression=org.apache.cassandra.io.compress.LZ4Compressor},bloomFilterFpChance=0.01,memtable_flush_period_in_ms=0,caching=KEYS_ONLY,defaultTimeToLive=0,speculative_retry=99.0PERCENTILE,indexInterval=128,populateIoCacheOnFlush=false,droppedColumns={},triggers={}]

[MigrationStage:1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system_traces.sessions

[MigrationStage:1] INFO org.apache.cassandra.db.DefsTables - Loading org.apache.cassandra.config.CFMetaData@26d6221b[cfId=8826e8e9-e16a-3728-8753-3bc1fc713c25,ksName=system_traces,cfName=events,cfType=Standard,comparator=org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.TimeUUIDType,org.apache.cassandra.db.marshal.UTF8Type),comment=,readRepairChance=0.0,dclocalReadRepairChance=0.0,replicateOnWrite=true,gcGraceSeconds=0,defaultValidator=org.apache.cassandra.db.marshal.BytesType,keyValidator=org.apache.cassandra.db.marshal.UUIDType,minCompactionThreshold=4,maxCompactionThreshold=32,column_metadata={java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]=ColumnDefinition{name=73657373696f6e5f6964, validator=org.apache.cassandra.db.marshal.UUIDType, type=PARTITION_KEY, componentIndex=null, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=6 cap=6]=ColumnDefinition{name=736f75726365, validator=org.apache.cassandra.db.marshal.InetAddressType, type=REGULAR, componentIndex=1, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=6 cap=6]=ColumnDefinition{name=746872656164, validator=org.apache.cassandra.db.marshal.UTF8Type, type=REGULAR, componentIndex=1, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=8 cap=8]=ColumnDefinition{name=6163746976697479, validator=org.apache.cassandra.db.marshal.UTF8Type, type=REGULAR, componentIndex=1, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=14 cap=14]=ColumnDefinition{name=736f757263655f656c6170736564, validator=org.apache.cassandra.db.marshal.Int32Type, type=REGULAR, componentIndex=1, indexName=null, indexType=null}, java.nio.HeapByteBuffer[pos=0 lim=8 cap=8]=ColumnDefinition{name=6576656e745f6964, validator=org.apache.cassandra.db.marshal.TimeUUIDType, type=CLUSTERING_KEY, componentIndex=0, indexName=null, indexType=null}},compactionStrategyClass=class org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy,compactionStrategyOptions={},compressionOptions={sstable_compression=org.apache.cassandra.io.compress.LZ4Compressor},bloomFilterFpChance=0.01,memtable_flush_period_in_ms=0,caching=KEYS_ONLY,defaultTimeToLive=0,speculative_retry=99.0PERCENTILE,indexInterval=128,populateIoCacheOnFlush=false,droppedColumns={},triggers={}]

[MigrationStage:1] INFO org.apache.cassandra.db.ColumnFamilyStore - Initializing system_traces.events

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Enqueuing flush of Memtable-local@878259848(84/840 serialized/live bytes, 6 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Writing Memtable-local@878259848(84/840 serialized/live bytes, 6 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Completed flushing target/embeddedCassandra/data/system/local/system-local-jb-3-Data.db (110 bytes) for commitlog position ReplayPosition(segmentId=1384769522823, position=91219)

[pool-1-thread-1] INFO org.apache.cassandra.db.ColumnFamilyStore - Enqueuing flush of Memtable-local@1337654277(10082/100820 serialized/live bytes, 257 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Writing Memtable-local@1337654277(10082/100820 serialized/live bytes, 257 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Completed flushing target/embeddedCassandra/data/system/local/system-local-jb-4-Data.db (5245 bytes) for commitlog position ReplayPosition(segmentId=1384769522823, position=103202)

[CompactionExecutor:2] INFO org.apache.cassandra.db.compaction.CompactionTask - Compacting [SSTableReader(path='target/embeddedCassandra/data/system/local/system-local-jb-3-Data.db'), SSTableReader(path='target/embeddedCassandra/data/system/local/system-local-jb-1-Data.db'), SSTableReader(path='target/embeddedCassandra/data/system/local/system-local-jb-4-Data.db'), SSTableReader(path='target/embeddedCassandra/data/system/local/system-local-jb-2-Data.db')]

[CompactionExecutor:2] INFO org.apache.cassandra.db.ColumnFamilyStore - Enqueuing flush of Memtable-compaction_history@1701650929(388/3880 serialized/live bytes, 10 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Writing Memtable-compaction_history@1701650929(388/3880 serialized/live bytes, 10 ops)

[FlushWriter:1] INFO org.apache.cassandra.db.Memtable - Completed flushing target/embeddedCassandra/data/system/compaction_history/system-compaction_history-jb-1-Data.db (255 bytes) for commitlog position ReplayPosition(segmentId=1384769522823, position=103783)

[CompactionExecutor:2] INFO org.apache.cassandra.db.compaction.CompactionTask - Compacted 4 sstables to [target/embeddedCassandra/data/system/local/system-local-jb-5,].  5,830 bytes to 5,671 (~97% of original) in 39ms = 0.138674MB/s.  4 total rows, 1 unique.  Row merge counts were {1:0, 2:0, 3:0, 4:1, }

[pool-1-thread-1] INFO org.apache.cassandra.service.StorageService - Node /127.0.0.1 state jump to normal

[pool-1-thread-1] INFO org.apache.cassandra.service.StorageService - Startup completed! Now serving reads.

[pool-1-thread-1] INFO org.apache.cassandra.transport.Server - Starting listening for CQL clients on localhost/127.0.0.1:9542...

[pool-1-thread-1] INFO org.apache.cassandra.thrift.ThriftServer - Using TFramedTransport with a max frame size of 15728640 bytes.

[pool-1-thread-1] INFO org.apache.cassandra.thrift.ThriftServer - Binding thrift service to localhost/127.0.0.1:9560

[pool-1-thread-1] WARN com.thinkaurelius.thrift.TDisruptorServer - Off-heap allocation couldn't be used as JNA is not present in classpath or broken, using on-heap instead.

[pool-1-thread-1] INFO org.apache.cassandra.thrift.THsHaDisruptorServer - Starting up org.apache.cassandra.thrift.THsHaDisruptorServer@198ec596

[pool-1-thread-1] INFO org.apache.cassandra.thrift.TServerCustomFactory - Using custom half-sync/half-async thrift server on localhost : 9560

[Thread-2] INFO org.apache.cassandra.thrift.ThriftServer - Listening for thrift clients...

-- disconnect 

Connected to cluster cassy-1

Datacenter: datacenter1; Host: /127.0.0.1; Rack: rack1

-- connect

Connected to cluster cassy-1

Datacenter: datacenter1; Host: /127.0.0.1; Rack: rack1

   session : cluster2

   session connect timeout: 5000

[StorageServiceShutdownHook] INFO org.apache.cassandra.thrift.ThriftServer - Stop listening to thrift clients

[StorageServiceShutdownHook] INFO org.apache.cassandra.transport.Server - Stop listening for CQL clients

[StorageServiceShutdownHook] INFO org.apache.cassandra.gms.Gossiper - Announcing shutdown

[StorageServiceShutdownHook] INFO org.apache.cassandra.net.MessagingService - Waiting for messaging service to quiesce

[ACCEPT-/127.0.0.1] INFO org.apache.cassandra.net.MessagingService - MessagingService shutting down server thread.


로그보면 cassandra 2.0.2로 실행된 것을 볼 수 있다.  기타 버전은 참고할 수 있다. 


[pool-1-thread-1] INFO org.apache.cassandra.service.StorageService - Cassandra version: 2.0.2

[pool-1-thread-1] INFO org.apache.cassandra.service.StorageService - Thrift API version: 19.38.0

[pool-1-thread-1] INFO org.apache.cassandra.service.StorageService - CQL supported versions: 2.0.0,3.1.1 (default: 3.1.1)

[pool-1-thread-1] INFO org.apache.cassandra.service.StorageService - Loading persisted ring state


Posted by '김용환'
,


mysql의 show tables, show databases와 같은 기능은 다음과 같다. 




1.  show databases;


cqlsh:os_ui> select * from system.schema_keyspaces;


 keyspace_name | durable_writes | strategy_class                                       | strategy_options

---------------+----------------+------------------------------------------------------+----------------------------

         os_ui |           True |          org.apache.cassandra.locator.SimpleStrategy | {"replication_factor":"1"}




 

2.  show tables;

 

 cqlsh:os_ui> select * from system.schema_columnfamilies;


 keyspace_name | columnfamily_name       | bloom_filter_fp_chance | caching   | column_aliases                       | comment                             | compaction_strategy_class                                       | compaction_strategy_options | comparator                                                                                                                                                                                                                                                                                                                                                                                          | compression_parameters                                                   | default_time_to_live | default_validator                         | dropped_columns | gc_grace_seconds | index_interval | key_aliases                                        | key_validator                                                                                                                                                              | local_read_repair_chance | max_compaction_threshold | memtable_flush_period_in_ms | min_compaction_threshold | populate_io_cache_on_flush | read_repair_chance | replicate_on_write | speculative_retry | subcomparator | type     | value_alias

---------------+-------------------------+------------------------+-----------+--------------------------------------+-------------------------------------+-----------------------------------------------------------------+-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------+----------------------+-------------------------------------------+-----------------+------------------+----------------+----------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------+--------------------------+-----------------------------+--------------------------+----------------------------+--------------------+--------------------+-------------------+---------------+----------+-------------

         os_ui |            cpu_util_pct |                   0.01 | KEYS_ONLY |                               ["ts"] |                                     | org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy |                          {} |                                                                                                                                                                                                                                                               org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.TimestampType,org.apache.cassandra.db.marshal.UTF8Type) | {"sstable_compression":"org.apache.cassandra.io.compress.LZ4Compressor"} |                    0 | org.apache.cassandra.db.marshal.BytesType |            null |           864000 |            128 |                                           ["guid"] |                                                                                                                                   org.apache.cassandra.db.marshal.UTF8Type |                        0 |                       32 |                           0 |                        4 |                      False |                0.1 |               True |    99.0PERCENTILE |          null | Standard |        null

         

         

         

         






Posted by '김용환'
,


cassandra 2.0.1 에서 중복된 list 값을 insert시 replace가 안되고 append되는 이슈가 있었다.

그러나. cassandra 2.0.2에서는 insert시 append(add) 가 아닌 replace가 된다.

원래 스펙상 insert 는 replace이다. 


http://cassandra.apache.org/doc/cql3/CQL.html#collections

Writing list data is accomplished with a JSON-style syntax. To write a record using INSERT, specify the entire list as a JSON array.

 Note: An INSERT will always replace the entire list


테스트 


cqlsh> CREATE KEYSPACE ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};

cqlsh>  USE ks;

cqlsh:ks> CREATE TABLE test (k int PRIMARY KEY, l list<int>);

cqlsh:ks> INSERT INTO test (k, l) VALUES (0, [0, 1]);

cqlsh:ks> INSERT INTO test (k, l) VALUES (0, [3, 4]);

cqlsh:ks> SELECT * FROM test;


 k | l

---+--------

 0 | [3, 4]


(1 rows)

Posted by '김용환'
,


http://cassandra.apache.org/doc/cql3/CQL.html#types



typeconstants supporteddescription
asciistringsASCII character string
bigintintegers64-bit signed long
blobblobsArbitrary bytes (no validation)
booleanbooleanstrue or false
counterintegersCounter column (64-bit signed value). See Counters for details
decimalintegers, floatsVariable-precision decimal
doubleintegers64-bit IEEE-754 floating point
floatintegers, floats32-bit IEEE-754 floating point
inetstringsAn IP address. It can be either 4 bytes long (IPv4) or 16 bytes long (IPv6). There is no inet constant, IP address should be inputed as strings
intintegers32-bit signed int
textstringsUTF8 encoded string
timestampintegers, stringsA timestamp. Strings constant are allow to input timestamps as dates, see Working with dates below for more information.
timeuuiduuidsType 1 UUID. This is generally used as a “conflict-free” timestamp. Also see the functions on Timeuuid
uuiduuidsType 1 or type 4 UUID
varcharstringsUTF8 encoded string
varintintegersArbitrary-precision integer



* text와 varchar는 같다. aliasing 차이. 




그리고, list, set, map을 기본적으로 지원한다. 

<collection-type> ::= list '<' <native-type> '>'
                    | set  '<' <native-type> '>'
                    | map  '<' <native-type> ',' <native-type> '>'

map 테스트

* 특이사항 : 없는 요소를 update하면 insert가 된다. 



cqlsh:userkeyspace> CREATE TABLE users (

                ...     id text PRIMARY KEY,

                ...     given text,

                ...     surname text,

                ...     favs map<text, text>   // A map of text keys, and text values

                ... );

cqlsh:userkeyspace> INSERT INTO users (id, given, surname, favs)

                ...            VALUES ('jsmith', 'John', 'Smith', { 'fruit' : 'apple', 'band' : 'Beatles' })

                ... ;

cqlsh:userkeyspace> select * from users;


 id     | favs                                  | given | surname

--------+---------------------------------------+-------+---------

 jsmith | {'band': 'Beatles', 'fruit': 'apple'}John |   Smith


(1 rows)


cqlsh:userkeyspace> UPDATE users SET favs['author'] = 'Ed Poe' WHERE id = 'jsmith'

                ... ;

cqlsh:userkeyspace> select * from users;


 id     | favs                                                      | given | surname

--------+-----------------------------------------------------------+-------+---------

 jsmith | {'author': 'Ed Poe', 'band': 'Beatles', 'fruit': 'apple'}John |   Smith


(1 rows)


cqlsh:userkeyspace> UPDATE users SET favs = favs +  { 'movie' : 'Cassablanca' } WHERE id = 'jsmith'

                ... ;

cqlsh:userkeyspace> select * from users;


 id     | favs                                                                              | given | surname

--------+-----------------------------------------------------------------------------------+-------+---------

 jsmith | {'author': 'Ed Poe', 'band': 'Beatles', 'fruit': 'apple', 'movie': 'Cassablanca'}John |   Smith


(1 rows)


cqlsh:userkeyspace> UPDATE users USING TTL 10 SET favs['color'] = 'green' WHERE id = 'jsmith'

                ... ;

cqlsh:userkeyspace> select * from users;


 id     | favs                                                                                                | given | surname

--------+-----------------------------------------------------------------------------------------------------+-------+---------

 jsmith | {'author': 'Ed Poe', 'band': 'Beatles', 'color': 'green', 'fruit': 'apple', 'movie': 'Cassablanca'}John |   Smith


(1 rows)


cqlsh:userkeyspace> select * from users;


 id     | favs                                                                              | given | surname

--------+-----------------------------------------------------------------------------------+-------+---------

 jsmith | {'author': 'Ed Poe', 'band': 'Beatles', 'fruit': 'apple', 'movie': 'Cassablanca'}John |   Smith


(1 rows)


cqlsh:userkeyspace> DELETE favs['author'] FROM users WHERE id = 'jsmith';

cqlsh:userkeyspace> select * from users;


 id     | favs                                                          | given | surname

--------+---------------------------------------------------------------+-------+---------

 jsmith | {'band': 'Beatles', 'fruit': 'apple', 'movie': 'Cassablanca'}John |   Smith


(1 rows)




set 지원

* 특이사항 delete query는 사용하지 않는다. update만 사용.


cqlsh:userkeyspace> CREATE TABLE images (

                ...     name text PRIMARY KEY,

                ...     owner text,

                ...     date timestamp,

                ...     tags set<text>

                ... );

cqlsh:userkeyspace> INSERT INTO images (name, owner, date, tags)

                ...             VALUES ('cat.jpg', 'jsmith', 'now', { 'kitten', 'cat', 'pet' });

cqlsh:userkeyspace> select * from images;


 name    | date                     | owner  | tags

---------+--------------------------+--------+--------------------------

 cat.jpg | 2013-11-13 15:50:17+0900 | jsmith | {'cat', 'kitten', 'pet'}


(1 rows)


cqlsh:userkeyspace> UPDATE images SET tags = tags + { 'cute', 'cuddly' } WHERE name = 'cat.jpg';

cqlsh:userkeyspace> select * from images;


 name    | date                     | owner  | tags

---------+--------------------------+--------+--------------------------------------------

 cat.jpg | 2013-11-13 15:50:17+0900 | jsmith | {'cat', 'cuddly', 'cute', 'kitten', 'pet'}


(1 rows)


cqlsh:userkeyspace> UPDATE images SET tags = tags - { 'lame' } WHERE name = 'cat.jpg';

cqlsh:userkeyspace> select * from images;


 name    | date                     | owner  | tags

---------+--------------------------+--------+--------------------------------------------

 cat.jpg | 2013-11-13 15:50:17+0900 | jsmith | {'cat', 'cuddly', 'cute', 'kitten', 'pet'}


(1 rows)




list에서 삭제할때 update문이 아닌 delete문을 사용하면 hang이 되므로 유의해야 한다.


cqlsh:userkeyspace> delete tags['cuddly'] from images where id = 'cat.jpg';

(hang)



위의 부분은 아파치 지라에 신고했고, 2.0.3 부터는 문제가 없을 예정이다. 

https://issues.apache.org/jira/browse/CASSANDRA-6341




list 이용

* 주의 사항 

It should be noted that append and prepend are not idempotent operations. This means that if during an append or a prepend the operation timeout, it is not always safe to retry the operation (as this could result in the record appended or prepended twice).

Lists also provides the following operation: setting an element by its position in the list, removing an element by its position in the list and remove all the occurrence of a given value in the list. However, and contrarily to all the other collection operations, these three operations induce an internal read before the update, and will thus typically have slower performance characteristics.



cqlsh:userkeyspace> CREATE TABLE plays (

                ...     id text PRIMARY KEY,

                ...     game text,

                ...     players int,

                ...     scores list<int>

                ... )

                ... ;

cqlsh:userkeyspace> UPDATE plays SET players = 5, scores = scores + [ 14, 21 ] WHERE id = '123-afde';

cqlsh:userkeyspace> select * from plays;


 id       | game | players | scores

----------+------+---------+----------

 123-afde | null |       5 | [14, 21]


(1 rows)


cqlsh:userkeyspace> UPDATE plays SET players = 5, scores = [ 12 ] + scores WHERE id = '123-afde';

cqlsh:userkeyspace> select * from plays;


 id       | game | players | scores

----------+------+---------+--------------

 123-afde | null |       5 | [12, 14, 21]


(1 rows)


cqlsh:userkeyspace> UPDATE plays SET scores[1] = 7 WHERE id = '123-afde'; 

cqlsh:userkeyspace> select * from plays;


 id       | game | players | scores

----------+------+---------+-------------

 123-afde | null |       5 | [12, 7, 21]


(1 rows)


cqlsh:userkeyspace> DELETE scores[1] FROM plays WHERE id = '123-afde';  

cqlsh:userkeyspace> select * from plays;


 id       | game | players | scores

----------+------+---------+----------

 123-afde | null |       5 | [12, 21]


(1 rows)


cqlsh:userkeyspace> UPDATE plays SET scores = scores - [ 12, 21 ] WHERE id = '123-afde';

cqlsh:userkeyspace> select * from plays;


 id       | game | players | scores

----------+------+---------+--------

 123-afde | null |       5 |   null


(1 rows)



Posted by '김용환'
,


 localhost에서 clustering구성시 사용하는 스크립트 소스이다. 


https://github.com/pcmanus/ccm


예제)


ccm populate -n 3

ccm start

ccm node1 ring
ccm node2 flush


Posted by '김용환'
,

cassandra - select cql 문서

nosql 2013. 11. 13. 15:33


cassandra 2.0이 채용한 cql 3의 select 문을 살펴본다. 


http://cassandra.apache.org/doc/cql3/CQL.html#selectStmt


특징적인 것은 order by, limit이 제공된다. 

join와 sub query, group by, cursor는 제공이 안된다. 




Posted by '김용환'
,

cassandra 2.0에서 데이터 저장시 ttl(time to live)를 쉽게 지정할 수 있다.

단위는 초(second)이다.  expire time를 사용할 시 유용하다. 


10초 뒤에 데이터는 사라진다.


insert cpu_util_pct (time, ts, pct) values (now(), now(), 50.5) USING TTL 10;



Posted by '김용환'
,


timeuuid나 timestamp를 range로 검색하려면 다음의 Rule을 써야 한다.

primary key의 첫번째 인자가 되면 안된다. 즉 secondary index여야 한다.



primary key 첫번째 인자가 timestamp이면 , in, eq외에는 쓸 수 없다.


cqlsh:userkeyspace> select percentage from mem_physical where time>'2011-02-03';
Bad Request: Only EQ and IN relation are supported on the partition key (unless you use the token() function)




secondary index로 써야 timestamp 쿼리를 쓸 수 있다.



create table mem_physical (
    time text, // sharding 또는 addition data
    ts timestamp,
    pct double,
    total int,
    used int,
    PRIMARY KEY (time, ts, pct, total, used)
);


cqlsh:userkeyspace> insert into mem_physical (timeString, time, percentage, total, used) values ('2011-02-03+0000', '2011-02-03+0000', 50.5, 100, 40);
cqlsh:userkeyspace> insert into mem_physical (timeString, time, percentage, total, used) values ('2011-02-03+0000', '2011-02-02+0000', 50.5, 100, 40);



cqlsh:userkeyspace> select * from mem_physical where time > 1231252312307 ALLOW FILTERING;

 timestring          | time                     | percentage | total | used
---------------------+--------------------------+------------+-------+------

....


(2) rows



timeuuid대신 timestamp를 사용중이다. ebay에서는 timestamp대신 timeuuid를 사용하라고 권고하고 있다. 그러나 timeuuid를 쓰기 번거로운 부분이 있었다. 단순히 long 값인 timestamp 로 단순히 query하기에는 좋은 모델이라 timeuuid대신 timestamp를 쓰고 있다. 



참고로 timeuuid의 장점은 select시 dateOf나 unixTimestampOf fuctiion을 사용할 수 있다는 점이다. 표준화된 포맷으로 다양하게 쓸 수 있다. 


cqlsh:userkeyspace> select canon_key, t, dateOf(t), unixTimestampOf(t) from test_t  ;


 canon_key | t                                    | dateOf(t)                | unixTimestampOf(t)

-----------+--------------------------------------+--------------------------+--------------------

         k | 6366bfe0-4a89-11e3-b040-6b48c21c33af | 2013-11-11 13:26:08+0900 |      1384143968990




그러나 아래와 같은 timestamp 값 또는 int값으로 비교하는 것은 허용이 되지 않는다. TimeUUID를 이용해야 한다. 


select canon_key, t, dateOf(t), unixTimestampOf(t) from test_t  where unixTimestampOf(t) > 1384143968990;







'nosql' 카테고리의 다른 글

cassandra - select cql 문서  (0) 2013.11.13
cassandra 2.0 - 데이터 저장시 TTL 지정  (0) 2013.11.11
cassandra 시간정보 저장  (0) 2013.11.11
cassandra 2.0 - copy  (0) 2013.11.08
facebook 분석툴 (dw엔진) fresto 소스 공개  (0) 2013.11.08
Posted by '김용환'
,

cassandra 시간정보 저장

nosql 2013. 11. 11. 13:43


cassandra 에서 시간 정보를 저장할 때, 3가지 type으로 저장가능하다. 


1. uuid

2. timeuuid

3. timestamp



uuid에서 나온 것이 timeuuid 이다. uuid (timeuuid)의 큰 장점은 표준 uuid 라는 점, dateOf나 unixTimestampOf function을 cql에서 사용할 수 있다. 반면, timestamp에서는 이를 쓸 수 없다. timeuuid 는 처음부터 time으로 sorting이 가능하다. time uuid type으로 comparator type을 지정할 수 있다.


timeuuid는 mac address 기반이다.. 따라서 time stamp를 쓸지 timeuuid를 쓸지 고민해야 한다. 




http://www.datastax.com/documentation/cql/3.0/webhelp/index.html#cql/cql_reference/cql_data_types_c.html?pagename=docs&version=1.2&file=cql_cli/cql_data_types


timestampintegers, stringsDate plus time, encoded as 8 bytes since epoch
uuiduuidsA UUID in standard UUID format
timeuuiduuidsType 1 UUID only (CQL 3)




http://www.datastax.com/documentation/cql/3.0/webhelp/index.html#cql/cql_reference/cql_lexicon_c.html#reference_ds_rgn_xy5_yj  


  • uuid

    32 hex digits, 0-9 or a-f, which are case-insensitive, separated by dashes, -, after the 8th, 12th, 16th, and 20th digits. For example: 01234567-0123-0123-0123-0123456789ab

  • timeuuid

    Uses the time in 100 nanosecond intervals since 00:00:00.00 UTC (60 bits), a clock sequence number for prevention of duplicates (14 bits), plus the IEEE 801 MAC address (48 bits) to generate a unique identifier. For example: d2177dd0-eaa2-11de-a572-001b779c76e3




http://stackoverflow.com/questions/17945677/cassandra-uuid-vs-timeuuid-benefits-and-disadvantages



UUID and TIMEUUID are stored the same way in Cassandra, and they only really represent two different sorting implementations.

TIMEUUID columns are sorted by their time components first, and then by their raw bytes, whereasUUID columns are sorted by their version first, then if both are version 1 by their time component, and finally by their raw bytes. Curiosly the time component sorting implementations are duplicated betweenUUIDType and TimeUUIDType in the Cassandra code, except for different formatting.

I think of the UUID vs. TIMEUUID question primarily as documentation: if you choose TIMEUUIDyou're saying that you're storing things in chronological order, and that these things can occur at the same time, so a simple timestamp isn't enough. Using UUID says that you don't care about order (even if in practice the columns will be ordered by time if you put version 1 UUIDs in them), you just want to make sure that things have unique IDs.

Even if using NOW() to generate UUID values is convenient, it's also very surprising to other people reading your code.

It probably does not matter much in the grand scheme of things, but sorting non-version 1 UUIDs is a bit faster than version 1, so if you have a UUID column and generate the UUIDs yourself, go for another version.



http://wiki.apache.org/cassandra/FAQ#working_with_timeuuid_in_java




http://svn.apache.org/repos/asf/cassandra/trunk/src/java/org/apache/cassandra/db/marshal/TimeUUIDType.java





http://www.datastax.com/docs/0.8/dml/using_cli

[default@demo] CREATE COLUMN FAMILY blog_entry
WITH comparator = TimeUUIDType
AND key_validation_class=UTF8Type 

AND default_validation_class = UTF8Type;



Posted by '김용환'
,

cassandra 2.0 - copy

nosql 2013. 11. 8. 15:35


기존의 db를 사용했던 사람이라면 db의 테이블로부터 csv로 export 하는 기능을 많이 활용한다.  cassandra 2.0의 cql copy 명령어를 이용하면 export/import 기능을 사용할 수 있다. 


cassandra 2.0에 copy statement를 사용할 수 있다.

http://www.datastax.com/documentation/cql/3.1/webhelp/index.html#cql/cql_reference/copy_r.html






cqlsh:userkeyspace> describe table cf33


CREATE TABLE cf33 (

  key text,

  name text,

  number text,

  PRIMARY KEY (key)

) WITH

  bloom_filter_fp_chance=0.010000 AND

  caching='KEYS_ONLY' AND

  comment='' AND

  dclocal_read_repair_chance=0.000000 AND

  gc_grace_seconds=864000 AND

  index_interval=128 AND

  read_repair_chance=0.100000 AND

  replicate_on_write='true' AND

  populate_io_cache_on_flush='false' AND

  default_time_to_live=0 AND

  speculative_retry='NONE' AND

  memtable_flush_period_in_ms=0 AND

  compaction={'class': 'SizeTieredCompactionStrategy'} AND

  compression={'sstable_compression': 'LZ4Compressor'};


CREATE INDEX name ON cf33 (name);


cqlsh:userkeyspace> select * from cf33;


 key  | name | number

------+------+--------

 row1 | John |      2


(1 rows)


cqlsh:userkeyspace> copy cf33 to 'cf33.csv';

1 rows exported in 0.008 seconds.

cqlsh:userkeyspace> truncate cf33;

cqlsh:userkeyspace> select * from cf33;


(0 rows)



cqlsh:userkeyspace> copy cf33(key, name,number) from 'cf33.csv';

1 rows imported in 0.034 seconds.

cqlsh:userkeyspace> select * from cf33;


 key  | name | number

------+------+--------

 row1 | John |      2


(1 rows)





Posted by '김용환'
,