diff --git a/.travis.yml b/.travis.yml index f1fff4b..b485e21 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,32 +1,33 @@ dist: xenial sudo: false language: python python: - "2.7" - "3.5" - "3.6" - "3.7" - "pypy2.7-6.0" - "pypy3.5" env: - CASS_DRIVER_NO_CYTHON=1 addons: apt: packages: - build-essential - python-dev - pypy-dev - libc-ares-dev - libev4 - libev-dev install: - - pip install tox-travis lz4 + - pip install tox-travis + - if [[ $TRAVIS_PYTHON_VERSION != pypy3.5 ]]; then pip install lz4; fi script: - tox - tox -e gevent_loop - tox -e eventlet_loop diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 0ac2aeb..d2d577c 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,1494 +1,1678 @@ +3.25.0 +====== +March 18, 2021 + +Features +-------- +* Ensure the driver can connect when invalid peer hosts are in system.peers (PYTHON-1260) +* Implement protocol v5 checksumming (PYTHON-1258) +* Fix the default cqlengine connection mechanism to work with Astra (PYTHON-1265) + +Bug Fixes +--------- +* Asyncore race condition cause logging exception on shutdown (PYTHON-1266) +* Update list of reserved keywords (PYTHON-1269) + +Others +------ +* Drop Python 3.4 support (PYTHON-1220) +* Update security documentation and examples to use PROTOCOL_TLS (PYTHON-1264) + +3.24.0 +====== +June 18, 2020 + +Features +-------- +* Make geomet an optional dependency at runtime (PYTHON-1237) +* Add use_default_tempdir cloud config options (PYTHON-1245) +* Tcp flow control for libevreactor (PYTHON-1248) + +Bug Fixes +--------- +* Unable to connect to a cloud cluster using Ubuntu 20.04 (PYTHON-1238) +* PlainTextAuthProvider fails with unicode chars and Python3 (PYTHON-1241) +* [GRAPH] Graph execution profiles consistency level are not set to LOCAL_QUORUM with a cloud cluster (PYTHON-1240) +* [GRAPH] Can't write data in a Boolean field using the Fluent API (PYTHON-1239) +* [GRAPH] Fix elementMap() result deserialization (PYTHON-1233) + +Others +------ +* Bump geomet dependency version to 0.2 (PYTHON-1243) +* Bump gremlinpython dependency version to 3.4.6 (PYTHON-1212) +* Improve fluent graph documentation for core graphs (PYTHON-1244) + +3.23.0 +====== +April 6, 2020 + +Features +-------- +* Transient Replication Support (PYTHON-1207) +* Support system.peers_v2 and port discovery for C* 4.0 (PYTHON-700) + +Bug Fixes +--------- +* Asyncore logging exception on shutdown (PYTHON-1228) + +3.22.0 +====== +February 26, 2020 + +Features +-------- + +* Add all() function to the ResultSet API (PYTHON-1203) +* Parse new schema metadata in NGDG and generate table edges CQL syntax (PYTHON-996) +* Add GraphSON3 support (PYTHON-788) +* Use GraphSON3 as default for Native graphs (PYTHON-1004) +* Add Tuple and UDT types for native graph (PYTHON-1005) +* Add Duration type for native graph (PYTHON-1000) +* Add gx:ByteBuffer graphson type support for Blob field (PYTHON-1027) +* Enable Paging Through DSE Driver for Gremlin Traversals (PYTHON-1045) +* Provide numerical wrappers to ensure proper graphson schema definition (PYTHON-1051) +* Resolve the row_factory automatically for native graphs (PYTHON-1056) +* Add g:TraversalMetrics/g:Metrics graph deserializers (PYTHON-1057) +* Add g:BulkSet graph deserializers (PYTHON-1060) +* Update Graph Engine names and the way to create a Classic/Native Graph (PYTHON-1090) +* Update Native to Core Graph Engine +* Add graphson3 and native graph support (PYTHON-1039) +* Enable Paging Through DSE Driver for Gremlin Traversals (PYTHON-1045) +* Expose filter predicates for cql collections (PYTHON-1019) +* Add g:TraversalMetrics/Metrics deserializers (PYTHON-1057) +* Make graph metadata handling more robust (PYTHON-1204) + +Bug Fixes +--------- +* Make sure to only query the native_transport_address column with DSE (PYTHON-1205) + +3.21.0 +====== +January 15, 2020 + +Features +-------- +* Unified driver: merge core and DSE drivers into a single package (PYTHON-1130) +* Add Python 3.8 support (PYTHON-1189) +* Allow passing ssl context for Twisted (PYTHON-1161) +* Ssl context and cloud support for Eventlet (PYTHON-1162) +* Cloud Twisted support (PYTHON-1163) +* Add additional_write_policy and read_repair to system schema parsing (PYTHON-1048) +* Flexible version parsing (PYTHON-1174) +* Support NULL in collection deserializer (PYTHON-1123) +* [GRAPH] Ability to execute Fluent Graph queries asynchronously (PYTHON-1129) + +Bug Fixes +--------- +* Handle prepared id mismatch when repreparing on the fly (PYTHON-1124) +* re-raising the CQLEngineException will fail on Python 3 (PYTHON-1166) +* asyncio message chunks can be processed discontinuously (PYTHON-1185) +* Reconnect attempts persist after downed node removed from peers (PYTHON-1181) +* Connection fails to validate ssl certificate hostname when SSLContext.check_hostname is set (PYTHON-1186) +* ResponseFuture._set_result crashes on connection error when used with PrepareMessage (PYTHON-1187) +* Insights fail to serialize the startup message when the SSL Context is from PyOpenSSL (PYTHON-1192) + +Others +------ +* The driver has a new dependency: geomet. It comes from the dse-driver unification and + is used to support DSE geo types. +* Remove *read_repair_chance table options (PYTHON-1140) +* Avoid warnings about unspecified load balancing policy when connecting to a cloud cluster (PYTHON-1177) +* Add new DSE CQL keywords (PYTHON-1122) +* Publish binary wheel distributions (PYTHON-1013) + +Deprecations +------------ + +* DSELoadBalancingPolicy will be removed in the next major, consider using + the DefaultLoadBalancingPolicy. + +Merged from dse-driver: + +Features +-------- + +* Insights integration (PYTHON-1047) +* Graph execution profiles should preserve their graph_source when graph_options is overridden (PYTHON-1021) +* Add NodeSync metadata (PYTHON-799) +* Add new NodeSync failure values (PYTHON-934) +* DETERMINISTIC and MONOTONIC Clauses for Functions and Aggregates (PYTHON-955) +* GraphOptions should show a warning for unknown parameters (PYTHON-819) +* DSE protocol version 2 and continous paging backpressure (PYTHON-798) +* GraphSON2 Serialization/Deserialization Support (PYTHON-775) +* Add graph-results payload option for GraphSON format (PYTHON-773) +* Create an AuthProvider for the DSE transitional mode (PYTHON-831) +* Implement serializers for the Graph String API (PYTHON-778) +* Provide deserializers for GraphSON types (PYTHON-782) +* Add Graph DurationType support (PYTHON-607) +* Support DSE DateRange type (PYTHON-668) +* RLAC CQL output for materialized views (PYTHON-682) +* Add Geom Types wkt deserializer +* DSE Graph Client timeouts in custom payload (PYTHON-589) +* Make DSEGSSAPIAuthProvider accept principal name (PYTHON-574) +* Add config profiles to DSE graph execution (PYTHON-570) +* DSE Driver version checking (PYTHON-568) +* Distinct default timeout for graph queries (PYTHON-477) +* Graph result parsing for known types (PYTHON-479,487) +* Distinct read/write CL for graph execution (PYTHON-509) +* Target graph analytics query to spark master when available (PYTHON-510) + +Bug Fixes +--------- + +* Continuous paging sessions raise RuntimeError when results are not entirely consumed (PYTHON-1054) +* GraphSON Property deserializer should return a dict instead of a set (PYTHON-1033) +* ResponseFuture.has_more_pages may hold the wrong value (PYTHON-946) +* DETERMINISTIC clause in AGGREGATE misplaced in CQL generation (PYTHON-963) +* graph module import cause a DLL issue on Windows due to its cythonizing failure (PYTHON-900) +* Update date serialization to isoformat in graph (PYTHON-805) +* DateRange Parse Error (PYTHON-729) +* MontonicTimestampGenerator.__init__ ignores class defaults (PYTHON-728) +* metadata.get_host returning None unexpectedly (PYTHON-709) +* Sockets associated with sessions not getting cleaned up on session.shutdown() (PYTHON-673) +* Resolve FQDN from ip address and use that as host passed to SASLClient (PYTHON-566) +* Geospatial type implementations don't handle 'EMPTY' values. (PYTHON-481) +* Correctly handle other types in geo type equality (PYTHON-508) + +Other +----- +* Add tests around cqlengine and continuous paging (PYTHON-872) +* Add an abstract GraphStatement to handle different graph statements (PYTHON-789) +* Write documentation examples for DSE 2.0 features (PYTHON-732) +* DSE_V1 protocol should not include all of protocol v5 (PYTHON-694) + 3.20.2 ====== November 19, 2019 Bug Fixes --------- * Fix import error for old python installation without SSLContext (PYTHON-1183) 3.20.1 ====== November 6, 2019 Bug Fixes --------- * ValueError: too many values to unpack (expected 2)" when there are two dashes in server version number (PYTHON-1172) 3.20.0 ====== October 28, 2019 Features -------- -* DataStax Apollo Support (PYTHON-1074) +* DataStax Astra Support (PYTHON-1074) * Use 4.0 schema parser in 4 alpha and snapshot builds (PYTHON-1158) Bug Fixes --------- * Connection setup methods prevent using ExecutionProfile in cqlengine (PYTHON-1009) * Driver deadlock if all connections dropped by heartbeat whilst request in flight and request times out (PYTHON-1044) * Exception when use pk__token__gt filter In python 3.7 (PYTHON-1121) 3.19.0 ====== August 26, 2019 Features -------- * Add Python 3.7 support (PYTHON-1016) * Future-proof Mapping imports (PYTHON-1023) * Include param values in cqlengine logging (PYTHON-1105) * NTS Token Replica Map Generation is slow (PYTHON-622) Bug Fixes --------- * as_cql_query UDF/UDA parameters incorrectly includes "frozen" if arguments are collections (PYTHON-1031) * cqlengine does not currently support combining TTL and TIMESTAMP on INSERT (PYTHON-1093) * Fix incorrect metadata for compact counter tables (PYTHON-1100) * Call ConnectionException with correct kwargs (PYTHON-1117) * Can't connect to clusters built from source because version parsing doesn't handle 'x.y-SNAPSHOT' (PYTHON-1118) * Discovered node doesn´t honor the configured Cluster port on connection (PYTHON-1127) +* Exception when use pk__token__gt filter In python 3.7 (PYTHON-1121) Other ----- * Remove invalid warning in set_session when we initialize a default connection (PYTHON-1104) * Set the proper default ExecutionProfile.row_factory value (PYTHON-1119) 3.18.0 ====== May 27, 2019 Features -------- * Abstract Host Connection information (PYTHON-1079) * Improve version parsing to support a non-integer 4th component (PYTHON-1091) * Expose on_request_error method in the RetryPolicy (PYTHON-1064) * Add jitter to ExponentialReconnectionPolicy (PYTHON-1065) Bug Fixes --------- * Fix error when preparing queries with beta protocol v5 (PYTHON-1081) * Accept legacy empty strings as column names (PYTHON-1082) * Let util.SortedSet handle uncomparable elements (PYTHON-1087) 3.17.1 ====== May 2, 2019 Bug Fixes --------- * Socket errors EAGAIN/EWOULDBLOCK are not handled properly and cause timeouts (PYTHON-1089) 3.17.0 ====== February 19, 2019 Features -------- * Send driver name and version in startup message (PYTHON-1068) * Add Cluster ssl_context option to enable SSL (PYTHON-995) * Allow encrypted private keys for 2-way SSL cluster connections (PYTHON-995) * Introduce new method ConsistencyLevel.is_serial (PYTHON-1067) * Add Session.get_execution_profile (PYTHON-932) * Add host kwarg to Session.execute/execute_async APIs to send a query to a specific node (PYTHON-993) Bug Fixes --------- * NoHostAvailable when all hosts are up and connectable (PYTHON-891) * Serial consistency level is not used (PYTHON-1007) Other ----- * Fail faster on incorrect lz4 import (PYTHON-1042) * Bump Cython dependency version to 0.29 (PYTHON-1036) * Expand Driver SSL Documentation (PYTHON-740) Deprecations ------------ * Using Cluster.ssl_options to enable SSL is deprecated and will be removed in the next major release, use ssl_context. * DowngradingConsistencyRetryPolicy is deprecated and will be removed in the next major release. (PYTHON-937) 3.16.0 ====== November 12, 2018 Bug Fixes --------- * Improve and fix socket error-catching code in nonblocking-socket reactors (PYTHON-1024) * Non-ASCII characters in schema break CQL string generation (PYTHON-1008) * Fix OSS driver's virtual table support against DSE 6.0.X and future server releases (PYTHON-1020) * ResultSet.one() fails if the row_factory is using a generator (PYTHON-1026) * Log profile name on attempt to create existing profile (PYTHON-944) * Cluster instantiation fails if any contact points' hostname resolution fails (PYTHON-895) Other ----- * Fix tests when RF is not maintained if we decomission a node (PYTHON-1017) * Fix wrong use of ResultSet indexing (PYTHON-1015) 3.15.1 ====== September 6, 2018 Bug Fixes --------- * C* 4.0 schema-parsing logic breaks running against DSE 6.0.X (PYTHON-1018) 3.15.0 ====== August 30, 2018 Features -------- * Parse Virtual Keyspace Metadata (PYTHON-992) Bug Fixes --------- * Tokenmap.get_replicas returns the wrong value if token coincides with the end of the range (PYTHON-978) * Python Driver fails with "more than 255 arguments" python exception when > 255 columns specified in query response (PYTHON-893) * Hang in integration.standard.test_cluster.ClusterTests.test_set_keyspace_twice (PYTHON-998) * Asyncore reactors should use a global variable instead of a class variable for the event loop (PYTHON-697) Other ----- * Use global variable for libev loops so it can be subclassed (PYTHON-973) * Update SchemaParser for V4 (PYTHON-1006) * Bump Cython dependency version to 0.28 (PYTHON-1012) 3.14.0 ====== April 17, 2018 Features -------- * Add one() function to the ResultSet API (PYTHON-947) * Create an utility function to fetch concurrently many keys from the same replica (PYTHON-647) * Allow filter queries with fields that have an index managed outside of cqlengine (PYTHON-966) * Twisted SSL Support (PYTHON-343) * Support IS NOT NULL operator in cqlengine (PYTHON-968) Other ----- * Fix Broken Links in Docs (PYTHON-916) * Reevaluate MONKEY_PATCH_LOOP in test codebase (PYTHON-903) * Remove CASS_SERVER_VERSION and replace it for CASSANDRA_VERSION in tests (PYTHON-910) * Refactor CASSANDRA_VERSION to a some kind of version object (PYTHON-915) * Log warning when driver configures an authenticator, but server does not request authentication (PYTHON-940) * Warn users when using the deprecated Session.default_consistency_level (PYTHON-953) * Add DSE smoke test to OSS driver tests (PYTHON-894) * Document long compilation times and workarounds (PYTHON-868) * Improve error for batch WriteTimeouts (PYTHON-941) * Deprecate ResultSet indexing (PYTHON-945) 3.13.0 ====== January 30, 2018 Features -------- * cqlengine: LIKE filter operator (PYTHON-512) * Support cassandra.query.BatchType with cqlengine BatchQuery (PYTHON-888) Bug Fixes --------- * AttributeError: 'NoneType' object has no attribute 'add_timer' (PYTHON-862) * Support retry_policy in PreparedStatement (PYTHON-861) * __del__ method in Session is throwing an exception (PYTHON-813) * LZ4 import issue with recent versions (PYTHON-897) * ResponseFuture._connection can be None when returning request_id (PYTHON-853) * ResultSet.was_applied doesn't support batch with LWT statements (PYTHON-848) Other ----- * cqlengine: avoid warning when unregistering connection on shutdown (PYTHON-865) * Fix DeprecationWarning of log.warn (PYTHON-846) * Fix example_mapper.py for python3 (PYTHON-860) * Possible deadlock on cassandra.concurrent.execute_concurrent (PYTHON-768) * Add some known deprecated warnings for 4.x (PYTHON-877) * Remove copyright dates from copyright notices (PYTHON-863) * Remove "Experimental" tag from execution profiles documentation (PYTHON-840) * request_timer metrics descriptions are slightly incorrect (PYTHON-885) * Remove "Experimental" tag from cqlengine connections documentation (PYTHON-892) * Set in documentation default consistency for operations is LOCAL_ONE (PYTHON-901) 3.12.0 ====== November 6, 2017 Features -------- * Send keyspace in QUERY, PREPARE, and BATCH messages (PYTHON-678) * Add IPv4Address/IPv6Address support for inet types (PYTHON-751) * WriteType.CDC and VIEW missing (PYTHON-794) * Warn on Cluster init if contact points are specified but LBP isn't (legacy mode) (PYTHON-812) * Warn on Cluster init if contact points are specified but LBP isn't (exection profile mode) (PYTHON-838) * Include hash of result set metadata in prepared stmt id (PYTHON-808) * Add NO_COMPACT startup option (PYTHON-839) * Add new exception type for CDC (PYTHON-837) * Allow 0ms in ConstantSpeculativeExecutionPolicy (PYTHON-836) * Add asyncio reactor (PYTHON-507) Bug Fixes --------- * Both _set_final_exception/result called for the same ResponseFuture (PYTHON-630) * Use of DCAwareRoundRobinPolicy raises NoHostAvailable exception (PYTHON-781) * Not create two sessions by default in CQLEngine (PYTHON-814) * Bug when subclassing AyncoreConnection (PYTHON-827) * Error at cleanup when closing the asyncore connections (PYTHON-829) * Fix sites where `sessions` can change during iteration (PYTHON-793) * cqlengine: allow min_length=0 for Ascii and Text column types (PYTHON-735) * Rare exception when "sys.exit(0)" after query timeouts (PYTHON-752) * Dont set the session keyspace when preparing statements (PYTHON-843) * Use of DCAwareRoundRobinPolicy raises NoHostAvailable exception (PYTHON-781) Other ------ * Remove DeprecationWarning when using WhiteListRoundRobinPolicy (PYTHON-810) * Bump Cython dependency version to 0.27 (PYTHON-833) 3.11.0 ====== July 24, 2017 Features -------- * Add idle_heartbeat_timeout cluster option to tune how long to wait for heartbeat responses. (PYTHON-762) * Add HostFilterPolicy (PYTHON-761) Bug Fixes --------- * is_idempotent flag is not propagated from PreparedStatement to BoundStatement (PYTHON-736) * Fix asyncore hang on exit (PYTHON-767) * Driver takes several minutes to remove a bad host from session (PYTHON-762) * Installation doesn't always fall back to no cython in Windows (PYTHON-763) * Avoid to replace a connection that is supposed to shutdown (PYTHON-772) * request_ids may not be returned to the pool (PYTHON-739) * Fix murmur3 on big-endian systems (PYTHON-653) * Ensure unused connections are closed if a Session is deleted by the GC (PYTHON-774) * Fix .values_list by using db names internally (cqlengine) (PYTHON-785) Other ----- * Bump Cython dependency version to 0.25.2 (PYTHON-754) * Fix DeprecationWarning when using lz4 (PYTHON-769) * Deprecate WhiteListRoundRobinPolicy (PYTHON-759) * Improve upgrade guide for materializing pages (PYTHON-464) * Documentation for time/date specifies timestamp inupt as microseconds (PYTHON-717) * Point to DSA Slack, not IRC, in docs index 3.10.0 ====== May 24, 2017 Features -------- * Add Duration type to cqlengine (PYTHON-750) * Community PR review: Raise error on primary key update only if its value changed (PYTHON-705) * get_query_trace() contract is ambiguous (PYTHON-196) Bug Fixes --------- * Queries using speculative execution policy timeout prematurely (PYTHON-755) * Fix `map` where results are not consumed (PYTHON-749) * Driver fails to encode Duration's with large values (PYTHON-747) * UDT values are not updated correctly in CQLEngine (PYTHON-743) * UDT types are not validated in CQLEngine (PYTHON-742) * to_python is not implemented for types columns.Type and columns.Date in CQLEngine (PYTHON-741) * Clients spin infinitely trying to connect to a host that is drained (PYTHON-734) * Resulset.get_query_trace returns empty trace sometimes (PYTHON-730) * Memory grows and doesn't get removed (PYTHON-720) * Fix RuntimeError caused by change dict size during iteration (PYTHON-708) * fix ExponentialReconnectionPolicy may throw OverflowError problem (PYTHON-707) * Avoid using nonexistent prepared statement in ResponseFuture (PYTHON-706) Other ----- * Update README (PYTHON-746) * Test python versions 3.5 and 3.6 (PYTHON-737) * Docs Warning About Prepare "select *" (PYTHON-626) * Increase Coverage in CqlEngine Test Suite (PYTHON-505) * Example SSL connection code does not verify server certificates (PYTHON-469) 3.9.0 ===== Features -------- * cqlengine: remove elements by key from a map (PYTHON-688) Bug Fixes --------- * improve error handling when connecting to non-existent keyspace (PYTHON-665) * Sockets associated with sessions not getting cleaned up on session.shutdown() (PYTHON-673) * rare flake on integration.standard.test_cluster.ClusterTests.test_clone_shared_lbp (PYTHON-727) * MontonicTimestampGenerator.__init__ ignores class defaults (PYTHON-728) * race where callback or errback for request may not be called (PYTHON-733) * cqlengine: model.update() should not update columns with a default value that hasn't changed (PYTHON-657) * cqlengine: field value manager's explicit flag is True when queried back from cassandra (PYTHON-719) Other ----- * Connection not closed in example_mapper (PYTHON-723) * Remove mention of pre-2.0 C* versions from OSS 3.0+ docs (PYTHON-710) 3.8.1 ===== March 16, 2017 Bug Fixes --------- * implement __le__/__ge__/__ne__ on some custom types (PYTHON-714) * Fix bug in eventlet and gevent reactors that could cause hangs (PYTHON-721) * Fix DecimalType regression (PYTHON-724) 3.8.0 ===== Features -------- * Quote index names in metadata CQL generation (PYTHON-616) * On column deserialization failure, keep error message consistent between python and cython (PYTHON-631) * TokenAwarePolicy always sends requests to the same replica for a given key (PYTHON-643) * Added cql types to result set (PYTHON-648) * Add __len__ to BatchStatement (PYTHON-650) * Duration Type for Cassandra (PYTHON-655) * Send flags with PREPARE message in v5 (PYTHON-684) Bug Fixes --------- * Potential Timing issue if application exits prior to session pool initialization (PYTHON-636) * "Host X.X.X.X has been marked down" without any exceptions (PYTHON-640) * NoHostAvailable or OperationTimedOut when using execute_concurrent with a generator that inserts into more than one table (PYTHON-642) * ResponseFuture creates Timers and don't cancel them even when result is received which leads to memory leaks (PYTHON-644) * Driver cannot connect to Cassandra version > 3 (PYTHON-646) * Unable to import model using UserType without setuping connection since 3.7 (PYTHON-649) * Don't prepare queries on ignored hosts on_up (PYTHON-669) * Sockets associated with sessions not getting cleaned up on session.shutdown() (PYTHON-673) * Make client timestamps strictly monotonic (PYTHON-676) * cassandra.cqlengine.connection.register_connection broken when hosts=None (PYTHON-692) Other ----- * Create a cqlengine doc section explaining None semantics (PYTHON-623) * Resolve warnings in documentation generation (PYTHON-645) * Cython dependency (PYTHON-686) * Drop Support for Python 2.6 (PYTHON-690) 3.7.1 ===== October 26, 2016 Bug Fixes --------- * Cython upgrade has broken stable version of cassandra-driver (PYTHON-656) 3.7.0 ===== September 13, 2016 Features -------- * Add v5 protocol failure map (PYTHON-619) * Don't return from initial connect on first error (PYTHON-617) * Indicate failed column when deserialization fails (PYTHON-361) * Let Cluster.refresh_nodes force a token map rebuild (PYTHON-349) * Refresh UDTs after "keyspace updated" event with v1/v2 protocol (PYTHON-106) * EC2 Address Resolver (PYTHON-198) * Speculative query retries (PYTHON-218) * Expose paging state in API (PYTHON-200) * Don't mark host down while one connection is active (PYTHON-498) * Query request size information (PYTHON-284) * Avoid quadratic ring processing with invalid replication factors (PYTHON-379) * Improve Connection/Pool creation concurrency on startup (PYTHON-82) * Add beta version native protocol flag (PYTHON-614) * cqlengine: Connections: support of multiple keyspaces and sessions (PYTHON-613) Bug Fixes --------- * Race when adding a pool while setting keyspace (PYTHON-628) * Update results_metadata when prepared statement is reprepared (PYTHON-621) * CQL Export for Thrift Tables (PYTHON-213) * cqlengine: default value not applied to UserDefinedType (PYTHON-606) * cqlengine: columns are no longer hashable (PYTHON-618) * cqlengine: remove clustering keys from where clause when deleting only static columns (PYTHON-608) 3.6.0 ===== August 1, 2016 Features -------- * Handle null values in NumpyProtocolHandler (PYTHON-553) * Collect greplin scales stats per cluster (PYTHON-561) * Update mock unit test dependency requirement (PYTHON-591) * Handle Missing CompositeType metadata following C* upgrade (PYTHON-562) * Improve Host.is_up state for HostDistance.IGNORED hosts (PYTHON-551) * Utilize v2 protocol's ability to skip result set metadata for prepared statement execution (PYTHON-71) * Return from Cluster.connect() when first contact point connection(pool) is opened (PYTHON-105) * cqlengine: Add ContextQuery to allow cqlengine models to switch the keyspace context easily (PYTHON-598) * Standardize Validation between Ascii and Text types in Cqlengine (PYTHON-609) Bug Fixes --------- * Fix geventreactor with SSL support (PYTHON-600) * Don't downgrade protocol version if explicitly set (PYTHON-537) * Nonexistent contact point tries to connect indefinitely (PYTHON-549) * Execute_concurrent can exceed max recursion depth in failure mode (PYTHON-585) * Libev loop shutdown race (PYTHON-578) * Include aliases in DCT type string (PYTHON-579) * cqlengine: Comparison operators for Columns (PYTHON-595) * cqlengine: disentangle default_time_to_live table option from model query default TTL (PYTHON-538) * cqlengine: pk__token column name issue with the equality operator (PYTHON-584) * cqlengine: Fix "__in" filtering operator converts True to string "True" automatically (PYTHON-596) * cqlengine: Avoid LWTExceptions when updating columns that are part of the condition (PYTHON-580) * cqlengine: Cannot execute a query when the filter contains all columns (PYTHON-599) * cqlengine: routing key computation issue when a primary key column is overriden by model inheritance (PYTHON-576) 3.5.0 ===== June 27, 2016 Features -------- * Optional Execution Profiles for the core driver (PYTHON-569) * API to get the host metadata associated with the control connection node (PYTHON-583) * Expose CDC option in table metadata CQL (PYTHON-593) Bug Fixes --------- * Clean up Asyncore socket map when fork is detected (PYTHON-577) * cqlengine: QuerySet only() is not respected when there are deferred fields (PYTHON-560) 3.4.1 ===== May 26, 2016 Bug Fixes --------- * Gevent connection closes on IO timeout (PYTHON-573) * "dictionary changed size during iteration" with Python 3 (PYTHON-572) 3.4.0 ===== May 24, 2016 Features -------- * Include DSE version and workload in Host data (PYTHON-555) * Add a context manager to Cluster and Session (PYTHON-521) * Better Error Message for Unsupported Protocol Version (PYTHON-157) * Make the error message explicitly state when an error comes from the server (PYTHON-412) * Short Circuit meta refresh on topo change if NEW_NODE already exists (PYTHON-557) * Show warning when the wrong config is passed to SimpleStatement (PYTHON-219) * Return namedtuple result pairs from execute_concurrent (PYTHON-362) * BatchStatement should enforce batch size limit in a better way (PYTHON-151) * Validate min/max request thresholds for connection pool scaling (PYTHON-220) * Handle or warn about multiple hosts with the same rpc_address (PYTHON-365) * Write docs around working with datetime and timezones (PYTHON-394) Bug Fixes --------- * High CPU utilization when using asyncore event loop (PYTHON-239) * Fix CQL Export for non-ASCII Identifiers (PYTHON-447) * Make stress scripts Python 2.6 compatible (PYTHON-434) * UnicodeDecodeError when unicode characters in key in BOP (PYTHON-559) * WhiteListRoundRobinPolicy should resolve hosts (PYTHON-565) * Cluster and Session do not GC after leaving scope (PYTHON-135) * Don't wait for schema agreement on ignored nodes (PYTHON-531) * Reprepare on_up with many clients causes node overload (PYTHON-556) * None inserted into host map when control connection node is decommissioned (PYTHON-548) * weakref.ref does not accept keyword arguments (github #585) 3.3.0 ===== May 2, 2016 Features -------- * Add an AddressTranslator interface (PYTHON-69) * New Retry Policy Decision - try next host (PYTHON-285) * Don't mark host down on timeout (PYTHON-286) * SSL hostname verification (PYTHON-296) * Add C* version to metadata or cluster objects (PYTHON-301) * Options to Disable Schema, Token Metadata Processing (PYTHON-327) * Expose listen_address of node we get ring information from (PYTHON-332) * Use A-record with multiple IPs for contact points (PYTHON-415) * Custom consistency level for populating query traces (PYTHON-435) * Normalize Server Exception Types (PYTHON-443) * Propagate exception message when DDL schema agreement fails (PYTHON-444) * Specialized exceptions for metadata refresh methods failure (PYTHON-527) Bug Fixes --------- * Resolve contact point hostnames to avoid duplicate hosts (PYTHON-103) * GeventConnection stalls requests when read is a multiple of the input buffer size (PYTHON-429) * named_tuple_factory breaks with duplicate "cleaned" col names (PYTHON-467) * Connection leak if Cluster.shutdown() happens during reconnection (PYTHON-482) * HostConnection.borrow_connection does not block when all request ids are used (PYTHON-514) * Empty field not being handled by the NumpyProtocolHandler (PYTHON-550) 3.2.2 ===== April 19, 2016 * Fix counter save-after-no-update (PYTHON-547) 3.2.1 ===== April 13, 2016 * Introduced an update to allow deserializer compilation with recently released Cython 0.24 (PYTHON-542) 3.2.0 ===== April 12, 2016 Features -------- * cqlengine: Warn on sync_schema type mismatch (PYTHON-260) * cqlengine: Automatically defer fields with the '=' operator (and immutable values) in select queries (PYTHON-520) * cqlengine: support non-equal conditions for LWT (PYTHON-528) * cqlengine: sync_table should validate the primary key composition (PYTHON-532) * cqlengine: token-aware routing for mapper statements (PYTHON-535) Bug Fixes --------- * Deleting a column in a lightweight transaction raises a SyntaxException #325 (PYTHON-249) * cqlengine: make Token function works with named tables/columns #86 (PYTHON-272) * comparing models with datetime fields fail #79 (PYTHON-273) * cython date deserializer integer math should be aligned with CPython (PYTHON-480) * db_field is not always respected with UpdateStatement (PYTHON-530) * Sync_table fails on column.Set with secondary index (PYTHON-533) 3.1.1 ===== March 14, 2016 Bug Fixes --------- * cqlengine: Fix performance issue related to additional "COUNT" queries (PYTHON-522) 3.1.0 ===== March 10, 2016 Features -------- * Pass name of server auth class to AuthProvider (PYTHON-454) * Surface schema agreed flag for DDL statements (PYTHON-458) * Automatically convert float and int to Decimal on serialization (PYTHON-468) * Eventlet Reactor IO improvement (PYTHON-495) * Make pure Python ProtocolHandler available even when Cython is present (PYTHON-501) * Optional Cython deserializer for bytes as bytearray (PYTHON-503) * Add Session.default_serial_consistency_level (github #510) * cqlengine: Expose prior state information via cqlengine LWTException (github #343, PYTHON-336) * cqlengine: Collection datatype "contains" operators support (Cassandra 2.1) #278 (PYTHON-258) * cqlengine: Add DISTINCT query operator (PYTHON-266) * cqlengine: Tuple cqlengine api (PYTHON-306) * cqlengine: Add support for UPDATE/DELETE ... IF EXISTS statements (PYTHON-432) * cqlengine: Allow nested container types (PYTHON-478) * cqlengine: Add ability to set query's fetch_size and limit (PYTHON-323) * cqlengine: Internalize default keyspace from successive set_session (PYTHON-486) * cqlengine: Warn when Model.create() on Counters (to be deprecated) (PYTHON-333) Bug Fixes --------- * Bus error (alignment issues) when running cython on some ARM platforms (PYTHON-450) * Overflow when decoding large collections (cython) (PYTHON-459) * Timer heap comparison issue with Python 3 (github #466) * Cython deserializer date overflow at 2^31 - 1 (PYTHON-452) * Decode error encountered when cython deserializing large map results (PYTHON-459) * Don't require Cython for build if compiler or Python header not present (PYTHON-471) * Unorderable types in task scheduling with Python 3 (h(PYTHON-473) * cqlengine: Fix crash when updating a UDT column with a None value (github #467) * cqlengine: Race condition in ..connection.execute with lazy_connect (PYTHON-310) * cqlengine: doesn't support case sensitive column family names (PYTHON-337) * cqlengine: UserDefinedType mandatory in create or update (PYTHON-344) * cqlengine: db_field breaks UserType (PYTHON-346) * cqlengine: UDT badly quoted (PYTHON-347) * cqlengine: Use of db_field on primary key prevents querying except while tracing. (PYTHON-351) * cqlengine: DateType.deserialize being called with one argument vs two (PYTHON-354) * cqlengine: Querying without setting up connection now throws AttributeError and not CQLEngineException (PYTHON-395) * cqlengine: BatchQuery multiple time executing execute statements. (PYTHON-445) * cqlengine: Better error for management functions when no connection set (PYTHON-451) * cqlengine: Handle None values for UDT attributes in cqlengine (PYTHON-470) * cqlengine: Fix inserting None for model save (PYTHON-475) * cqlengine: EQ doesn't map to a QueryOperator (setup race condition) (PYTHON-476) * cqlengine: class.MultipleObjectsReturned has DoesNotExist as base class (PYTHON-489) * cqlengine: Typo in cqlengine UserType __len__ breaks attribute assignment (PYTHON-502) Other ----- * cqlengine: a major improvement on queryset has been introduced. It is a lot more efficient to iterate large datasets: the rows are now fetched on demand using the driver pagination. * cqlengine: the queryset len() and count() behaviors have changed. It now executes a "SELECT COUNT(*)" of the query rather than returning the size of the internal result_cache (loaded rows). On large queryset, you might want to avoid using them due to the performance cost. Note that trying to access objects using list index/slicing with negative indices also requires a count to be executed. 3.0.0 ===== November 24, 2015 Features -------- * Support datetime.date objects as a DateType (PYTHON-212) * Add Cluster.update_view_metadata (PYTHON-407) * QueryTrace option to populate partial trace sessions (PYTHON-438) * Attach column names to ResultSet (PYTHON-439) * Change default consistency level to LOCAL_ONE Bug Fixes --------- * Properly SerDes nested collections when protocol_version < 3 (PYTHON-215) * Evict UDTs from UserType cache on change (PYTHON-226) * Make sure query strings are always encoded UTF-8 (PYTHON-334) * Track previous value of columns at instantiation in CQLengine (PYTHON-348) * UDT CQL encoding does not work for unicode values (PYTHON-353) * NetworkTopologyStrategy#make_token_replica_map does not account for multiple racks in a DC (PYTHON-378) * Cython integer overflow on decimal type deserialization (PYTHON-433) * Query trace: if session hasn't been logged, query trace can throw exception (PYTHON-442) 3.0.0rc1 ======== November 9, 2015 Features -------- * Process Modernized Schema Tables for Cassandra 3.0 (PYTHON-276, PYTHON-408, PYTHON-400, PYTHON-422) * Remove deprecated features (PYTHON-292) * Don't assign trace data to Statements (PYTHON-318) * Normalize results return (PYTHON-368) * Process Materialized View Metadata/Events (PYTHON-371) * Remove blist as soft dependency (PYTHON-385) * Change default consistency level to LOCAL_QUORUM (PYTHON-416) * Normalize CQL query/export in metadata model (PYTHON-405) Bug Fixes --------- * Implementation of named arguments bind is non-pythonic (PYTHON-178) * CQL encoding is incorrect for NaN and Infinity floats (PYTHON-282) * Protocol downgrade issue with C* 2.0.x, 2.1.x, and python3, with non-default logging (PYTHON-409) * ValueError when accessing usertype with non-alphanumeric field names (PYTHON-413) * NumpyProtocolHandler does not play well with PagedResult (PYTHON-430) 2.7.2 ===== September 14, 2015 Bug Fixes --------- * Resolve CQL export error for UDF with zero parameters (PYTHON-392) * Remove futures dep. for Python 3 (PYTHON-393) * Avoid Python closure in cdef (supports earlier Cython compiler) (PYTHON-396) * Unit test runtime issues (PYTHON-397,398) 2.7.1 ===== August 25, 2015 Bug Fixes --------- * Explicitly include extension source files in Manifest 2.7.0 ===== August 25, 2015 Cython is introduced, providing compiled extensions for core modules, and extensions for optimized results deserialization. Features -------- * General Performance Improvements for Throughput (PYTHON-283) * Improve synchronous request performance with Timers (PYTHON-108) * Enable C Extensions for PyPy Runtime (PYTHON-357) * Refactor SerDes functionality for pluggable interface (PYTHON-313) * Cython SerDes Extension (PYTHON-377) * Accept iterators/generators for execute_concurrent() (PYTHON-123) * cythonize existing modules (PYTHON-342) * Pure Python murmur3 implementation (PYTHON-363) * Make driver tolerant of inconsistent metadata (PYTHON-370) Bug Fixes --------- * Drop Events out-of-order Cause KeyError on Processing (PYTHON-358) * DowngradingConsistencyRetryPolicy doesn't check response count on write timeouts (PYTHON-338) * Blocking connect does not use connect_timeout (PYTHON-381) * Properly protect partition key in CQL export (PYTHON-375) * Trigger error callbacks on timeout (PYTHON-294) 2.6.0 ===== July 20, 2015 Bug Fixes --------- * Output proper CQL for compact tables with no clustering columns (PYTHON-360) 2.6.0c2 ======= June 24, 2015 Features -------- * Automatic Protocol Version Downgrade (PYTHON-240) * cqlengine Python 2.6 compatibility (PYTHON-288) * Double-dollar string quote UDF body (PYTHON-345) * Set models.DEFAULT_KEYSPACE when calling set_session (github #352) Bug Fixes --------- * Avoid stall while connecting to mixed version cluster (PYTHON-303) * Make SSL work with AsyncoreConnection in python 2.6.9 (PYTHON-322) * Fix Murmur3Token.from_key() on Windows (PYTHON-331) * Fix cqlengine TimeUUID rounding error for Windows (PYTHON-341) * Avoid invalid compaction options in CQL export for non-SizeTiered (PYTHON-352) 2.6.0c1 ======= June 4, 2015 This release adds support for Cassandra 2.2 features, including version 4 of the native protocol. Features -------- * Default load balancing policy to TokenAware(DCAware) (PYTHON-160) * Configuration option for connection timeout (PYTHON-206) * Support User Defined Function and Aggregate metadata in C* 2.2 (PYTHON-211) * Surface request client in QueryTrace for C* 2.2+ (PYTHON-235) * Implement new request failure messages in protocol v4+ (PYTHON-238) * Metadata model now maps index meta by index name (PYTHON-241) * Support new types in C* 2.2: date, time, smallint, tinyint (PYTHON-245, 295) * cqle: add Double column type and remove Float overload (PYTHON-246) * Use partition key column information in prepared response for protocol v4+ (PYTHON-277) * Support message custom payloads in protocol v4+ (PYTHON-280, PYTHON-329) * Deprecate refresh_schema and replace with functions for specific entities (PYTHON-291) * Save trace id even when trace complete times out (PYTHON-302) * Warn when registering client UDT class for protocol < v3 (PYTHON-305) * Support client warnings returned with messages in protocol v4+ (PYTHON-315) * Ability to distinguish between NULL and UNSET values in protocol v4+ (PYTHON-317) * Expose CQL keywords in API (PYTHON-324) Bug Fixes --------- * IPv6 address support on Windows (PYTHON-20) * Convert exceptions during automatic re-preparation to nice exceptions (PYTHON-207) * cqle: Quote keywords properly in table management functions (PYTHON-244) * Don't default to GeventConnection when gevent is loaded, but not monkey-patched (PYTHON-289) * Pass dynamic host from SaslAuthProvider to SaslAuthenticator (PYTHON-300) * Make protocol read_inet work for Windows (PYTHON-309) * cqle: Correct encoding for nested types (PYTHON-311) * Update list of CQL keywords used quoting identifiers (PYTHON-319) * Make ConstantReconnectionPolicy work with infinite retries (github #327, PYTHON-325) * Accept UUIDs with uppercase hex as valid in cqlengine (github #335) 2.5.1 ===== April 23, 2015 Bug Fixes --------- * Fix thread safety in DC-aware load balancing policy (PYTHON-297) * Fix race condition in node/token rebuild (PYTHON-298) * Set and send serial consistency parameter (PYTHON-299) 2.5.0 ===== March 30, 2015 Features -------- * Integrated cqlengine object mapping package * Utility functions for converting timeuuids and datetime (PYTHON-99) * Schema metadata fetch window randomized, config options added (PYTHON-202) * Support for new Date and Time Cassandra types (PYTHON-190) Bug Fixes --------- * Fix index target for collection indexes (full(), keys()) (PYTHON-222) * Thread exception during GIL cleanup (PYTHON-229) * Workaround for rounding anomaly in datetime.utcfromtime (Python 3.4) (PYTHON-230) * Normalize text serialization for lookup in OrderedMap (PYTHON-231) * Support reading CompositeType data (PYTHON-234) * Preserve float precision in CQL encoding (PYTHON-243) 2.1.4 ===== January 26, 2015 Features -------- * SaslAuthenticator for Kerberos support (PYTHON-109) * Heartbeat for network device keepalive and detecting failures on idle connections (PYTHON-197) * Support nested, frozen collections for Cassandra 2.1.3+ (PYTHON-186) * Schema agreement wait bypass config, new call for synchronous schema refresh (PYTHON-205) * Add eventlet connection support (PYTHON-194) Bug Fixes --------- * Schema meta fix for complex thrift tables (PYTHON-191) * Support for 'unknown' replica placement strategies in schema meta (PYTHON-192) * Resolve stream ID leak on set_keyspace (PYTHON-195) * Remove implicit timestamp scaling on serialization of numeric timestamps (PYTHON-204) * Resolve stream id collision when using SASL auth (PYTHON-210) * Correct unhexlify usage for user defined type meta in Python3 (PYTHON-208) 2.1.3 ===== December 16, 2014 Features -------- * INFO-level log confirmation that a connection was opened to a node that was marked up (PYTHON-116) * Avoid connecting to peer with incomplete metadata (PYTHON-163) * Add SSL support to gevent reactor (PYTHON-174) * Use control connection timeout in wait for schema agreement (PYTHON-175) * Better consistency level representation in unavailable+timeout exceptions (PYTHON-180) * Update schema metadata processing to accommodate coming schema modernization (PYTHON-185) Bug Fixes --------- * Support large negative timestamps on Windows (PYTHON-119) * Fix schema agreement for clusters with peer rpc_addres 0.0.0.0 (PYTHON-166) * Retain table metadata following keyspace meta refresh (PYTHON-173) * Use a timeout when preparing a statement for all nodes (PYTHON-179) * Make TokenAware routing tolerant of statements with no keyspace (PYTHON-181) * Update add_collback to store/invoke multiple callbacks (PYTHON-182) * Correct routing key encoding for composite keys (PYTHON-184) * Include compression option in schema export string when disabled (PYTHON-187) 2.1.2 ===== October 16, 2014 Features -------- * Allow DCAwareRoundRobinPolicy to be constructed without a local_dc, defaulting instead to the DC of a contact_point (PYTHON-126) * Set routing key in BatchStatement.add() if none specified in batch (PYTHON-148) * Improved feedback on ValueError using named_tuple_factory with invalid column names (PYTHON-122) Bug Fixes --------- * Make execute_concurrent compatible with Python 2.6 (PYTHON-159) * Handle Unauthorized message on schema_triggers query (PYTHON-155) * Pure Python sorted set in support of UDTs nested in collections (PYTON-167) * Support CUSTOM index metadata and string export (PYTHON-165) 2.1.1 ===== September 11, 2014 Features -------- * Detect triggers and include them in CQL queries generated to recreate the schema (github-189) * Support IPv6 addresses (PYTHON-144) (note: basic functionality added; Windows platform not addressed (PYTHON-20)) Bug Fixes --------- * Fix NetworkTopologyStrategy.export_for_schema (PYTHON-120) * Keep timeout for paged results (PYTHON-150) Other ----- * Add frozen<> type modifier to UDTs and tuples to handle CASSANDRA-7857 2.1.0 ===== August 7, 2014 Bug Fixes --------- * Correctly serialize and deserialize null values in tuples and user-defined types (PYTHON-110) * Include additional header and lib dirs, allowing libevwrapper to build against Homebrew and Mac Ports installs of libev (PYTHON-112 and 804dea3) 2.1.0c1 ======= July 25, 2014 Bug Fixes --------- * Properly specify UDTs for columns in CREATE TABLE statements * Avoid moving retries to a new host when using request ID zero (PYTHON-88) * Don't ignore fetch_size arguments to Statement constructors (github-151) * Allow disabling automatic paging on a per-statement basis when it's enabled by default for the session (PYTHON-93) * Raise ValueError when tuple query parameters for prepared statements have extra items (PYTHON-98) * Correctly encode nested tuples and UDTs for non-prepared statements (PYTHON-100) * Raise TypeError when a string is used for contact_points (github #164) * Include User Defined Types in KeyspaceMetadata.export_as_string() (PYTHON-96) Other ----- * Return list collection columns as python lists instead of tuples now that tuples are a specific Cassandra type 2.1.0b1 ======= July 11, 2014 This release adds support for Cassandra 2.1 features, including version 3 of the native protocol. Features -------- * When using the v3 protocol, only one connection is opened per-host, and throughput is improved due to reduced pooling overhead and lock contention. * Support for user-defined types (Cassandra 2.1+) * Support for tuple type in (limited usage Cassandra 2.0.9, full usage in Cassandra 2.1) * Protocol-level client-side timestamps (see Session.use_client_timestamp) * Overridable type encoding for non-prepared statements (see Session.encoders) * Configurable serial consistency levels for batch statements * Use io.BytesIO for reduced CPU consumption (github #143) * Support Twisted as a reactor. Note that a Twisted-compatible API is not exposed (so no Deferreds), this is just a reactor implementation. (github #135, PYTHON-8) Bug Fixes --------- * Fix references to xrange that do not go through "six" in libevreactor and geventreactor (github #138) * Make BoundStatements inherit fetch_size from their parent PreparedStatement (PYTHON-80) * Clear reactor state in child process after forking to prevent errors with multiprocessing when the parent process has connected a Cluster before forking (github #141) * Don't share prepared statement lock across Cluster instances * Format CompositeType and DynamicCompositeType columns correctly in CREATE TABLE statements. * Fix cassandra.concurrent behavior when dealing with automatic paging (PYTHON-81) * Properly defunct connections after protocol errors * Avoid UnicodeDecodeError when query string is unicode (PYTHON-76) * Correctly capture dclocal_read_repair_chance for tables and use it when generating CREATE TABLE statements (PYTHON-84) * Avoid race condition with AsyncoreConnection that may cause messages to fail to be written until a new message is pushed * Make sure cluster.metadata.partitioner and cluster.metadata.token_map are populated when all nodes in the cluster are included in the contact points (PYTHON-90) * Make Murmur3 hash match Cassandra's hash for all values (PYTHON-89, github #147) * Don't attempt to reconnect to hosts that should be ignored (according to the load balancing policy) when a notification is received that the host is down. * Add CAS WriteType, avoiding KeyError on CAS write timeout (PYTHON-91) 2.0.2 ===== June 10, 2014 Bug Fixes --------- * Add six to requirements.txt * Avoid KeyError during schema refresh when a keyspace is dropped and TokenAwarePolicy is not in use * Avoid registering multiple atexit cleanup functions when the asyncore event loop is restarted multiple times * Delay initialization of reactors in order to avoid problems with shared state when using multiprocessing (PYTHON-60) * Add python-six to debian dependencies, move python-blist to recommends * Fix memory leak when libev connections are created and destroyed (github #93) * Ensure token map is rebuilt when hosts are removed from the cluster 2.0.1 ===== May 28, 2014 Bug Fixes --------- * Fix check for Cluster.is_shutdown in in @run_in_executor decorator 2.0.0 ===== May 28, 2014 Features -------- * Make libev C extension Python3-compatible (PYTHON-70) * Support v2 protocol authentication (PYTHON-73, github #125) Bug Fixes --------- * Fix murmur3 C extension compilation under Python3.4 (github #124) Merged From 1.x --------------- Features ^^^^^^^^ * Add Session.default_consistency_level (PYTHON-14) Bug Fixes ^^^^^^^^^ * Don't strip trailing underscores from column names when using the named_tuple_factory (PYTHON-56) * Ensure replication factors are ints for NetworkTopologyStrategy to avoid TypeErrors (github #120) * Pass WriteType instance to RetryPolicy.on_write_timeout() instead of the string name of the write type. This caused write timeout errors to always be rethrown instead of retrying. (github #123) * Avoid submitting tasks to the ThreadPoolExecutor after shutdown. With retries enabled, this could cause Cluster.shutdown() to hang under some circumstances. * Fix unintended rebuild of token replica map when keyspaces are discovered (on startup), added, or updated and TokenAwarePolicy is not in use. * Avoid rebuilding token metadata when cluster topology has not actually changed * Avoid preparing queries for hosts that should be ignored (such as remote hosts when using the DCAwareRoundRobinPolicy) (PYTHON-75) Other ^^^^^ * Add 1 second timeout to join() call on event loop thread during interpreter shutdown. This can help to prevent the process from hanging during shutdown. 2.0.0b1 ======= May 6, 2014 Upgrading from 1.x ------------------ Cluster.shutdown() should always be called when you are done with a Cluster instance. If it is not called, there are no guarantees that the driver will not hang. However, if you *do* have a reproduceable case where Cluster.shutdown() is not called and the driver hangs, please report it so that we can attempt to fix it. If you're using the 2.0 driver against Cassandra 1.2, you will need to set your protocol version to 1. For example: cluster = Cluster(..., protocol_version=1) Features -------- * Support v2 of Cassandra's native protocol, which includes the following new features: automatic query paging support, protocol-level batch statements, and lightweight transactions * Support for Python 3.3 and 3.4 * Allow a default query timeout to be set per-Session Bug Fixes --------- * Avoid errors during interpreter shutdown (the driver attempts to cleanup daemonized worker threads before interpreter shutdown) Deprecations ------------ The following functions have moved from cassandra.decoder to cassandra.query. The original functions have been left in place with a DeprecationWarning for now: * cassandra.decoder.tuple_factory has moved to cassandra.query.tuple_factory * cassandra.decoder.named_tuple_factory has moved to cassandra.query.named_tuple_factory * cassandra.decoder.dict_factory has moved to cassandra.query.dict_factory * cassandra.decoder.ordered_dict_factory has moved to cassandra.query.ordered_dict_factory Exceptions that were in cassandra.decoder have been moved to cassandra.protocol. If you handle any of these exceptions, you must adjust the code accordingly. 1.1.2 ===== May 8, 2014 Features -------- * Allow a specific compression type to be requested for communications with Cassandra and prefer lz4 if available Bug Fixes --------- * Update token metadata (for TokenAware calculations) when a node is removed from the ring * Fix file handle leak with gevent reactor due to blocking Greenlet kills when closing excess connections * Avoid handling a node coming up multiple times due to a reconnection attempt succeeding close to the same time that an UP notification is pushed * Fix duplicate node-up handling, which could result in multiple reconnectors being started as well as the executor threads becoming deadlocked, preventing future node up or node down handling from being executed. * Handle exhausted ReconnectionPolicy schedule correctly Other ----- * Don't log at ERROR when a connection is closed during the startup communications * Mke scales, blist optional dependencies 1.1.1 ===== April 16, 2014 Bug Fixes --------- * Fix unconditional import of nose in setup.py (github #111) 1.1.0 ===== April 16, 2014 Features -------- * Gevent is now supported through monkey-patching the stdlib (PYTHON-7, github issue #46) * Support static columns in schemas, which are available starting in Cassandra 2.1. (github issue #91) * Add debian packaging (github issue #101) * Add utility methods for easy concurrent execution of statements. See the new cassandra.concurrent module. (github issue #7) Bug Fixes --------- * Correctly supply compaction and compression parameters in CREATE statements for tables when working with Cassandra 2.0+ * Lowercase boolean literals when generating schemas * Ignore SSL_ERROR_WANT_READ and SSL_ERROR_WANT_WRITE socket errors. Previously, these resulted in the connection being defuncted, but they can safely be ignored by the driver. * Don't reconnect the control connection every time Cluster.connect() is called * Avoid race condition that could leave ResponseFuture callbacks uncalled if the callback was added outside of the event loop thread (github issue #95) * Properly escape keyspace name in Session.set_keyspace(). Previously, the keyspace name was quoted, but any quotes in the string were not escaped. * Avoid adding hosts to the load balancing policy before their datacenter and rack information has been set, if possible. * Avoid KeyError when updating metadata after droping a table (github issues #97, #98) * Use tuples instead of sets for DCAwareLoadBalancingPolicy to ensure equal distribution of requests Other ----- * Don't ignore column names when parsing typestrings. This is needed for user-defined type support. (github issue #90) * Better error message when libevwrapper is not found * Only try to import scales when metrics are enabled (github issue #92) * Cut down on the number of queries executing when a new Cluster connects and when the control connection has to reconnect (github issue #104, PYTHON-59) * Issue warning log when schema versions do not match 1.0.2 ===== March 4, 2014 Bug Fixes --------- * With asyncorereactor, correctly handle EAGAIN/EWOULDBLOCK when the message from Cassandra is a multiple of the read buffer size. Previously, if no more data became available to read on the socket, the message would never be processed, resulting in an OperationTimedOut error. * Double quote keyspace, table and column names that require them (those using uppercase characters or keywords) when generating CREATE statements through KeyspaceMetadata and TableMetadata. * Decode TimestampType as DateType. (Cassandra replaced DateType with TimestampType to fix sorting of pre-unix epoch dates in CASSANDRA-5723.) * Handle latest table options when parsing the schema and generating CREATE statements. * Avoid 'Set changed size during iteration' during query plan generation when hosts go up or down Other ----- * Remove ignored ``tracing_enabled`` parameter for ``SimpleStatement``. The correct way to trace a query is by setting the ``trace`` argument to ``True`` in ``Session.execute()`` and ``Session.execute_async()``. * Raise TypeError instead of cassandra.query.InvalidParameterTypeError when a parameter for a prepared statement has the wrong type; remove cassandra.query.InvalidParameterTypeError. * More consistent type checking for query parameters * Add option to a return special object for empty string values for non-string columns 1.0.1 ===== Feb 19, 2014 Bug Fixes --------- * Include table indexes in ``KeyspaceMetadata.export_as_string()`` * Fix broken token awareness on ByteOrderedPartitioner * Always close socket when defuncting error'ed connections to avoid a potential file descriptor leak * Handle "custom" types (such as the replaced DateType) correctly * With libevreactor, correctly handle EAGAIN/EWOULDBLOCK when the message from Cassandra is a multiple of the read buffer size. Previously, if no more data became available to read on the socket, the message would never be processed, resulting in an OperationTimedOut error. * Don't break tracing when a Session's row_factory is not the default namedtuple_factory. * Handle data that is already utf8-encoded for UTF8Type values * Fix token-aware routing for tokens that fall before the first node token in the ring and tokens that exactly match a node's token * Tolerate null source_elapsed values for Trace events. These may not be set when events complete after the main operation has already completed. Other ----- * Skip sending OPTIONS message on connection creation if compression is disabled or not available and a CQL version has not been explicitly set * Add details about errors and the last queried host to ``OperationTimedOut`` 1.0.0 Final =========== Jan 29, 2014 Bug Fixes --------- * Prevent leak of Scheduler thread (even with proper shutdown) * Correctly handle ignored hosts, which are common with the DCAwareRoundRobinPolicy * Hold strong reference to prepared statement while executing it to avoid garbage collection * Add NullHandler logging handler to the cassandra package to avoid warnings about there being no configured logger * Fix bad handling of nodes that have been removed from the cluster * Properly escape string types within cql collections * Handle setting the same keyspace twice in a row * Avoid race condition during schema agreement checks that could result in schema update queries returning before all nodes had seen the change * Preserve millisecond-level precision in datetimes when performing inserts with simple (non-prepared) statements * Properly defunct connections when libev reports an error by setting errno instead of simply logging the error * Fix endless hanging of some requests when using the libev reactor * Always start a reconnection process when we fail to connect to a newly bootstrapped node * Generators map to CQL lists, not key sequences * Always defunct connections when an internal operation fails * Correctly break from handle_write() if nothing was sent (asyncore reactor only) * Avoid potential double-erroring of callbacks when a connection becomes defunct Features -------- * Add default query timeout to ``Session`` * Add timeout parameter to ``Session.execute()`` * Add ``WhiteListRoundRobinPolicy`` as a load balancing policy option * Support for consistency level ``LOCAL_ONE`` * Make the backoff for fetching traces exponentially increasing and configurable Other ----- * Raise Exception if ``TokenAwarePolicy`` is used against a cluster using the ``Murmur3Partitioner`` if the murmur3 C extension has not been compiled * Add encoder mapping for ``OrderedDict`` * Use timeouts on all control connection queries * Benchmark improvements, including command line options and eay multithreading support * Reduced lock contention when using the asyncore reactor * Warn when non-datetimes are used for 'timestamp' column values in prepared statements * Add requirements.txt and test-requirements.txt * TravisCI integration for running unit tests against Python 2.6, Python 2.7, and PyPy 1.0.0b7 ======= Nov 12, 2013 This release makes many stability improvements, especially around prepared statements and node failure handling. In particular, several cases where a request would never be completed (and as a result, leave the application hanging) have been resolved. Features -------- * Add `timeout` kwarg to ``ResponseFuture.result()`` * Create connection pools to all hosts in parallel when initializing new Sesssions. Bug Fixes --------- * Properly set exception on ResponseFuture when a query fails against all hosts * Improved cleanup and reconnection efforts when reconnection fails on a node that has recently come up * Use correct consistency level when retrying failed operations against a different host. (An invalid consistency level was being used, causing the retry to fail.) * Better error messages for failed ``Session.prepare()`` opertaions * Prepare new statements against all hosts in parallel (formerly sequential) * Fix failure to save the new current keyspace on connections. (This could cause problems for prepared statements and lead to extra operations to continuously re-set the keyspace.) * Avoid sharing ``LoadBalancingPolicies`` across ``Cluster`` instances. (When a second ``Cluster`` was connected, it effectively mark nodes down for the first ``Cluster``.) * Better handling of failures during the re-preparation sequence for unrecognized prepared statements * Throttle trashing of underutilized connections to avoid trashing newly created connections * Fix race condition which could result in trashed connections being closed before the last operations had completed * Avoid preparing statements on the event loop thread (which could lead to deadlock) * Correctly mark up non-contact point nodes discovered by the control connection. (This lead to prepared statements not being prepared against those hosts, generating extra traffic later when the statements were executed and unrecognized.) * Correctly handle large messages through libev * Add timeout to schema agreement check queries * More complete (and less contended) locking around manipulation of the pending message deque for libev connections Other ----- * Prepare statements in batches of 10. (When many prepared statements are in use, this allows the driver to start utilizing nodes that were restarted more quickly.) * Better debug logging around connection management * Don't retain unreferenced prepared statements in the local cache. (If many different prepared statements were created, this would increase memory usage and greatly increase the amount of time required to begin utilizing a node that was added or marked up.) 1.0.0b6 ======= Oct 22, 2013 Bug Fixes --------- * Use lazy string formatting when logging * Avoid several deadlock scenarios, especially when nodes go down * Avoid trashing newly created connections due to insufficient traffic * Gracefully handle un-handled Exceptions when erroring callbacks Other ----- * Node state listeners (which are called when a node is added, removed, goes down, or comes up) should now be registered through Cluster.register_listener() instead of through a host's HealthMonitor (which has been removed) 1.0.0b5 ======== Oct 10, 2013 Features -------- * SSL support Bug Fixes --------- * Avoid KeyError when building replica map for NetworkTopologyStrategy * Work around python bug which causes deadlock when a thread imports the utf8 module * Handle no blist library, which is not compatible with pypy * Avoid deadlock triggered by a keyspace being set on a connection (which may happen automatically for new connections) Other ----- * Switch packaging from Distribute to setuptools, improved C extension support * Use PEP 386 compliant beta and post-release versions 1.0.0-beta4 =========== Sep 24, 2013 Features -------- * Handle new blob syntax in Cassandra 2.0 by accepting bytearray objects for blob values * Add cql_version kwarg to Cluster.__init__ Bug Fixes --------- * Fix KeyError when building token map with NetworkTopologyStrategy keyspaces (this prevented a Cluster from successfully connecting at all). * Don't lose default consitency level from parent PreparedStatement when creating BoundStatements 1.0.0-beta3 =========== Sep 20, 2013 Features -------- * Support for LZ4 compression (Cassandra 2.0+) * Token-aware routing will now utilize all replicas for a query instead of just the first replica Bug Fixes --------- * Fix libev include path for CentOS * Fix varint packing of the value 0 * Correctly pack unicode values * Don't attempt to return failed connections to the pool when a final result is set * Fix bad iteration of connection credentials * Use blist's orderedset for set collections and OrderedDict for map collections so that Cassandra's ordering is preserved * Fix connection failure on Windows due to unavailability of inet_pton and inet_ntop. (Note that IPv6 inet_address values are still not supported on Windows.) * Boolean constants shouldn't be surrounded by single quotes * Avoid a potential loss of precision on float constants due to string formatting * Actually utilize non-standard ports set on Cluster objects * Fix export of schema as a set of CQL queries Other ----- * Use cStringIO for connection buffer for better performance * Add __repr__ method for Statement classes * Raise InvalidTypeParameterError when parameters of the wrong type are used with statements * Make all tests compatible with Python 2.6 * Add 1s timeout for opening new connections 1.0.0-beta2 =========== Aug 19, 2013 Bug Fixes --------- * Fix pip packaging 1.0.0-beta ========== Aug 16, 2013 Initial release diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..abb6092 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,675 @@ +#!groovy +/* + +There are multiple combinations to test the python driver. + +Test Profiles: + + Full: Execute all unit and integration tests, including long tests. + Standard: Execute unit and integration tests. + Smoke Tests: Execute a small subset of tests. + EVENT_LOOP: Execute a small subset of tests selected to test EVENT_LOOPs. + +Matrix Types: + + Full: All server versions, python runtimes tested with and without Cython. + Develop: Smaller matrix for dev purpose. + Cassandra: All cassandra server versions. + Dse: All dse server versions. + +Parameters: + + EVENT_LOOP: 'LIBEV' (Default), 'GEVENT', 'EVENTLET', 'ASYNCIO', 'ASYNCORE', 'TWISTED' + CYTHON: Default, 'True', 'False' + +*/ + +@Library('dsdrivers-pipeline-lib@develop') +import com.datastax.jenkins.drivers.python.Slack + +slack = new Slack() + +// Define our predefined matrices +matrices = [ + "FULL": [ + "SERVER": ['2.1', '2.2', '3.0', '3.11', '4.0', 'dse-5.0', 'dse-5.1', 'dse-6.0', 'dse-6.7', 'dse-6.8'], + "RUNTIME": ['2.7.18', '3.5.9', '3.6.10', '3.7.7', '3.8.3'], + "CYTHON": ["True", "False"] + ], + "DEVELOP": [ + "SERVER": ['2.1', '3.11', 'dse-6.8'], + "RUNTIME": ['2.7.18', '3.6.10'], + "CYTHON": ["True", "False"] + ], + "CASSANDRA": [ + "SERVER": ['2.1', '2.2', '3.0', '3.11', '4.0'], + "RUNTIME": ['2.7.18', '3.5.9', '3.6.10', '3.7.7', '3.8.3'], + "CYTHON": ["True", "False"] + ], + "DSE": [ + "SERVER": ['dse-5.0', 'dse-5.1', 'dse-6.0', 'dse-6.7', 'dse-6.8'], + "RUNTIME": ['2.7.18', '3.5.9', '3.6.10', '3.7.7', '3.8.3'], + "CYTHON": ["True", "False"] + ] +] + +def getBuildContext() { + /* + Based on schedule, parameters and branch name, configure the build context and env vars. + */ + + def driver_display_name = 'Cassandra Python Driver' + if (env.GIT_URL.contains('riptano/python-driver')) { + driver_display_name = 'private ' + driver_display_name + } else if (env.GIT_URL.contains('python-dse-driver')) { + driver_display_name = 'DSE Python Driver' + } + + def git_sha = "${env.GIT_COMMIT.take(7)}" + def github_project_url = "https://${GIT_URL.replaceFirst(/(git@|http:\/\/|https:\/\/)/, '').replace(':', '/').replace('.git', '')}" + def github_branch_url = "${github_project_url}/tree/${env.BRANCH_NAME}" + def github_commit_url = "${github_project_url}/commit/${env.GIT_COMMIT}" + + def profile = "${params.PROFILE}" + def EVENT_LOOP = "${params.EVENT_LOOP.toLowerCase()}" + matrixType = "FULL" + developBranchPattern = ~"((dev|long)-)?python-.*" + + if (developBranchPattern.matcher(env.BRANCH_NAME).matches()) { + matrixType = "DEVELOP" + if (env.BRANCH_NAME.contains("long")) { + profile = "FULL" + } + } + + // Check if parameters were set explicitly + if (params.MATRIX != "DEFAULT") { + matrixType = params.MATRIX + } + + matrix = matrices[matrixType].clone() + if (params.CYTHON != "DEFAULT") { + matrix["CYTHON"] = [params.CYTHON] + } + + if (params.SERVER_VERSION != "DEFAULT") { + matrix["SERVER"] = [params.SERVER_VERSION] + } + + if (params.PYTHON_VERSION != "DEFAULT") { + matrix["RUNTIME"] = [params.PYTHON_VERSION] + } + + if (params.CI_SCHEDULE == "WEEKNIGHTS") { + matrix["SERVER"] = params.CI_SCHEDULE_SERVER_VERSION.split(' ') + matrix["RUNTIME"] = params.CI_SCHEDULE_PYTHON_VERSION.split(' ') + } + + context = [ + vars: [ + "PROFILE=${profile}", + "EVENT_LOOP=${EVENT_LOOP}", + "DRIVER_DISPLAY_NAME=${driver_display_name}", "GIT_SHA=${git_sha}", "GITHUB_PROJECT_URL=${github_project_url}", + "GITHUB_BRANCH_URL=${github_branch_url}", "GITHUB_COMMIT_URL=${github_commit_url}" + ], + matrix: matrix + ] + + return context +} + +def buildAndTest(context) { + initializeEnvironment() + installDriverAndCompileExtensions() + + try { + executeTests() + } finally { + junit testResults: '*_results.xml' + } +} + +def getMatrixBuilds(buildContext) { + def tasks = [:] + matrix = buildContext.matrix + + matrix["SERVER"].each { serverVersion -> + matrix["RUNTIME"].each { runtimeVersion -> + matrix["CYTHON"].each { cythonFlag -> + def taskVars = [ + "CASSANDRA_VERSION=${serverVersion}", + "PYTHON_VERSION=${runtimeVersion}", + "CYTHON_ENABLED=${cythonFlag}" + ] + def cythonDesc = cythonFlag == "True" ? ", Cython": "" + tasks["${serverVersion}, py${runtimeVersion}${cythonDesc}"] = { + node("${OS_VERSION}") { + checkout scm + + withEnv(taskVars) { + buildAndTest(context) + } + } + } + } + } + } + return tasks +} + +def initializeEnvironment() { + sh label: 'Initialize the environment', script: '''#!/bin/bash -lex + pyenv global ${PYTHON_VERSION} + sudo apt-get install socat + pip install --upgrade pip + pip install -U setuptools + pip install ${HOME}/ccm + ''' + + // Determine if server version is Apache CassandraⓇ or DataStax Enterprise + if (env.CASSANDRA_VERSION.split('-')[0] == 'dse') { + sh label: 'Install DataStax Enterprise requirements', script: '''#!/bin/bash -lex + pip install -r test-datastax-requirements.txt + ''' + } else { + sh label: 'Install Apache CassandraⓇ requirements', script: '''#!/bin/bash -lex + pip install -r test-requirements.txt + ''' + + sh label: 'Uninstall the geomet dependency since it is not required for Cassandra', script: '''#!/bin/bash -lex + pip uninstall -y geomet + ''' + } + + sh label: 'Install unit test modules', script: '''#!/bin/bash -lex + pip install nose-ignore-docstring nose-exclude service_identity + ''' + + if (env.CYTHON_ENABLED == 'True') { + sh label: 'Install cython modules', script: '''#!/bin/bash -lex + pip install cython numpy + ''' + } + + sh label: 'Download Apache CassandraⓇ or DataStax Enterprise', script: '''#!/bin/bash -lex + . ${CCM_ENVIRONMENT_SHELL} ${CASSANDRA_VERSION} + ''' + + sh label: 'Display Python and environment information', script: '''#!/bin/bash -le + # Load CCM environment variables + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + python --version + pip --version + pip freeze + printenv | sort + ''' +} + +def installDriverAndCompileExtensions() { + if (env.CYTHON_ENABLED == 'True') { + sh label: 'Install the driver and compile with C extensions with Cython', script: '''#!/bin/bash -lex + python setup.py build_ext --inplace + ''' + } else { + sh label: 'Install the driver and compile with C extensions without Cython', script: '''#!/bin/bash -lex + python setup.py build_ext --inplace --no-cython + ''' + } +} + +def executeStandardTests() { + + sh label: 'Execute unit tests', script: '''#!/bin/bash -lex + # Load CCM environment variables + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP=${EVENT_LOOP} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=unit_results.xml tests/unit/ || true + EVENT_LOOP=eventlet VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=unit_eventlet_results.xml tests/unit/io/test_eventletreactor.py || true + EVENT_LOOP=gevent VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=unit_gevent_results.xml tests/unit/io/test_geventreactor.py || true + ''' + + sh label: 'Execute Simulacron integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variables + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + SIMULACRON_JAR="${HOME}/simulacron.jar" + SIMULACRON_JAR=${SIMULACRON_JAR} EVENT_LOOP=${EVENT_LOOP} CASSANDRA_DIR=${CCM_INSTALL_DIR} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --exclude test_backpressure.py --xunit-file=simulacron_results.xml tests/integration/simulacron/ || true + + # Run backpressure tests separately to avoid memory issue + SIMULACRON_JAR=${SIMULACRON_JAR} EVENT_LOOP=${EVENT_LOOP} CASSANDRA_DIR=${CCM_INSTALL_DIR} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --exclude test_backpressure.py --xunit-file=simulacron_backpressure_1_results.xml tests/integration/simulacron/test_backpressure.py:TCPBackpressureTests.test_paused_connections || true + SIMULACRON_JAR=${SIMULACRON_JAR} EVENT_LOOP=${EVENT_LOOP} CASSANDRA_DIR=${CCM_INSTALL_DIR} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --exclude test_backpressure.py --xunit-file=simulacron_backpressure_2_results.xml tests/integration/simulacron/test_backpressure.py:TCPBackpressureTests.test_queued_requests_timeout || true + SIMULACRON_JAR=${SIMULACRON_JAR} EVENT_LOOP=${EVENT_LOOP} CASSANDRA_DIR=${CCM_INSTALL_DIR} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --exclude test_backpressure.py --xunit-file=simulacron_backpressure_3_results.xml tests/integration/simulacron/test_backpressure.py:TCPBackpressureTests.test_cluster_busy || true + SIMULACRON_JAR=${SIMULACRON_JAR} EVENT_LOOP=${EVENT_LOOP} CASSANDRA_DIR=${CCM_INSTALL_DIR} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --exclude test_backpressure.py --xunit-file=simulacron_backpressure_4_results.xml tests/integration/simulacron/test_backpressure.py:TCPBackpressureTests.test_node_busy || true + ''' + + sh label: 'Execute CQL engine integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variables + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP=${EVENT_LOOP} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=cqle_results.xml tests/integration/cqlengine/ || true + ''' + + sh label: 'Execute Apache CassandraⓇ integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variables + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP=${EVENT_LOOP} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=standard_results.xml tests/integration/standard/ || true + ''' + + if (env.CASSANDRA_VERSION.split('-')[0] == 'dse' && env.CASSANDRA_VERSION.split('-')[1] != '4.8') { + sh label: 'Execute DataStax Enterprise integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variable + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP=${EVENT_LOOP} CASSANDRA_DIR=${CCM_INSTALL_DIR} DSE_VERSION=${DSE_VERSION} ADS_HOME="${HOME}/" VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=dse_results.xml tests/integration/advanced/ || true + ''' + } + + sh label: 'Execute DataStax Constellation integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variable + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP=${EVENT_LOOP} CLOUD_PROXY_PATH="${HOME}/proxy/" CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=advanced_results.xml tests/integration/cloud/ || true + ''' + + if (env.PROFILE == 'FULL') { + sh label: 'Execute long running integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variable + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP=${EVENT_LOOP} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --exclude-dir=tests/integration/long/upgrade --with-ignore-docstrings --with-xunit --xunit-file=long_results.xml tests/integration/long/ || true + ''' + } +} + +def executeDseSmokeTests() { + sh label: 'Execute profile DataStax Enterprise smoke test integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variable + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP=${EVENT_LOOP} CCM_ARGS="${CCM_ARGS}" CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} DSE_VERSION=${DSE_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=standard_results.xml tests/integration/standard/test_dse.py || true + ''' +} + +def executeEventLoopTests() { + sh label: 'Execute profile event loop manager integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variable + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP_TESTS=( + "tests/integration/standard/test_cluster.py" + "tests/integration/standard/test_concurrent.py" + "tests/integration/standard/test_connection.py" + "tests/integration/standard/test_control_connection.py" + "tests/integration/standard/test_metrics.py" + "tests/integration/standard/test_query.py" + "tests/integration/simulacron/test_endpoint.py" + "tests/integration/long/test_ssl.py" + ) + EVENT_LOOP=${EVENT_LOOP} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=standard_results.xml ${EVENT_LOOP_TESTS[@]} || true + ''' +} + +def executeTests() { + switch(env.PROFILE) { + case 'DSE-SMOKE-TEST': + executeDseSmokeTests() + break + case 'EVENT_LOOP': + executeEventLoopTests() + break + default: + executeStandardTests() + break + } +} + + +// TODO move this in the shared lib +def getDriverMetricType() { + metric_type = 'oss' + if (env.GIT_URL.contains('riptano/python-driver')) { + metric_type = 'oss-private' + } else if (env.GIT_URL.contains('python-dse-driver')) { + metric_type = 'dse' + } + return metric_type +} + +def submitCIMetrics(buildType) { + long durationMs = currentBuild.duration + long durationSec = durationMs / 1000 + long nowSec = (currentBuild.startTimeInMillis + durationMs) / 1000 + def branchNameNoPeriods = env.BRANCH_NAME.replaceAll('\\.', '_') + metric_type = getDriverMetricType() + def durationMetric = "okr.ci.python.${metric_type}.${buildType}.${branchNameNoPeriods} ${durationSec} ${nowSec}" + + timeout(time: 1, unit: 'MINUTES') { + withCredentials([string(credentialsId: 'lab-grafana-address', variable: 'LAB_GRAFANA_ADDRESS'), + string(credentialsId: 'lab-grafana-port', variable: 'LAB_GRAFANA_PORT')]) { + withEnv(["DURATION_METRIC=${durationMetric}"]) { + sh label: 'Send runtime metrics to labgrafana', script: '''#!/bin/bash -lex + echo "${DURATION_METRIC}" | nc -q 5 ${LAB_GRAFANA_ADDRESS} ${LAB_GRAFANA_PORT} + ''' + } + } + } +} + +def describeBuild(buildContext) { + script { + def runtimes = buildContext.matrix["RUNTIME"] + def serverVersions = buildContext.matrix["SERVER"] + def numBuilds = runtimes.size() * serverVersions.size() * buildContext.matrix["CYTHON"].size() + currentBuild.displayName = "${env.PROFILE} (${env.EVENT_LOOP} | ${numBuilds} builds)" + currentBuild.description = "${env.PROFILE} build testing servers (${serverVersions.join(', ')}) against Python (${runtimes.join(', ')}) using ${env.EVENT_LOOP} event loop manager" + } +} + +def scheduleTriggerJobName = "drivers/python/oss/master/disabled" + +pipeline { + agent none + + // Global pipeline timeout + options { + timeout(time: 10, unit: 'HOURS') // TODO timeout should be per build + buildDiscarder(logRotator(artifactNumToKeepStr: '10', // Keep only the last 10 artifacts + numToKeepStr: '50')) // Keep only the last 50 build records + } + + parameters { + choice( + name: 'ADHOC_BUILD_TYPE', + choices: ['BUILD', 'BUILD-AND-EXECUTE-TESTS'], + description: '''

Perform a adhoc build operation

+ + + + + + + + + + + + + + + +
ChoiceDescription
BUILDPerforms a Per-Commit build
BUILD-AND-EXECUTE-TESTSPerforms a build and executes the integration and unit tests
''') + choice( + name: 'PROFILE', + choices: ['STANDARD', 'FULL', 'DSE-SMOKE-TEST', 'EVENT_LOOP'], + description: '''

Profile to utilize for scheduled or adhoc builds

+ + + + + + + + + + + + + + + + + + + + + + + +
ChoiceDescription
STANDARDExecute the standard tests for the driver
FULLExecute all tests for the driver, including long tests.
DSE-SMOKE-TESTExecute only the DataStax Enterprise smoke tests
EVENT_LOOPExecute only the event loop tests for the specified event loop manager (see: EVENT_LOOP)
''') + choice( + name: 'MATRIX', + choices: ['DEFAULT', 'FULL', 'DEVELOP', 'CASSANDRA', 'DSE'], + description: '''

The matrix for the build.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
ChoiceDescription
DEFAULTDefault to the build context.
FULLAll server versions, python runtimes tested with and without Cython.
DEVELOPSmaller matrix for dev purpose.
CASSANDRAAll cassandra server versions.
DSEAll dse server versions.
''') + choice( + name: 'PYTHON_VERSION', + choices: ['DEFAULT', '2.7.18', '3.5.9', '3.6.10', '3.7.7', '3.8.3'], + description: 'Python runtime version. Default to the build context.') + choice( + name: 'SERVER_VERSION', + choices: ['DEFAULT', + '2.1', // Legacy Apache CassandraⓇ + '2.2', // Legacy Apache CassandraⓇ + '3.0', // Previous Apache CassandraⓇ + '3.11', // Current Apache CassandraⓇ + '4.0', // Development Apache CassandraⓇ + 'dse-5.0', // Long Term Support DataStax Enterprise + 'dse-5.1', // Legacy DataStax Enterprise + 'dse-6.0', // Previous DataStax Enterprise + 'dse-6.7', // Previous DataStax Enterprise + 'dse-6.8', // Current DataStax Enterprise + ], + description: '''Apache CassandraⓇ and DataStax Enterprise server version to use for adhoc BUILD-AND-EXECUTE-TESTS ONLY! + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ChoiceDescription
DEFAULTDefault to the build context.
2.1Apache CassandraⓇ; v2.1.x
2.2Apache CassandarⓇ; v2.2.x
3.0Apache CassandraⓇ v3.0.x
3.11Apache CassandraⓇ v3.11.x
4.0Apache CassandraⓇ v4.x (CURRENTLY UNDER DEVELOPMENT)
dse-5.0DataStax Enterprise v5.0.x (Long Term Support)
dse-5.1DataStax Enterprise v5.1.x
dse-6.0DataStax Enterprise v6.0.x
dse-6.7DataStax Enterprise v6.7.x
dse-6.8DataStax Enterprise v6.8.x (CURRENTLY UNDER DEVELOPMENT)
''') + choice( + name: 'CYTHON', + choices: ['DEFAULT', 'True', 'False'], + description: '''

Flag to determine if Cython should be enabled

+ + + + + + + + + + + + + + + + + + + +
ChoiceDescription
DefaultDefault to the build context.
TrueEnable Cython
FalseDisable Cython
''') + choice( + name: 'EVENT_LOOP', + choices: ['LIBEV', 'GEVENT', 'EVENTLET', 'ASYNCIO', 'ASYNCORE', 'TWISTED'], + description: '''

Event loop manager to utilize for scheduled or adhoc builds

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ChoiceDescription
LIBEVA full-featured and high-performance event loop that is loosely modeled after libevent, but without its limitations and bugs
GEVENTA co-routine -based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libev or libuv event loop
EVENTLETA concurrent networking library for Python that allows you to change how you run your code, not how you write it
ASYNCIOA library to write concurrent code using the async/await syntax
ASYNCOREA module provides the basic infrastructure for writing asynchronous socket service clients and servers
TWISTEDAn event-driven networking engine written in Python and licensed under the open source MIT license
''') + choice( + name: 'CI_SCHEDULE', + choices: ['DO-NOT-CHANGE-THIS-SELECTION', 'WEEKNIGHTS', 'WEEKENDS'], + description: 'CI testing schedule to execute periodically scheduled builds and tests of the driver (DO NOT CHANGE THIS SELECTION)') + string( + name: 'CI_SCHEDULE_PYTHON_VERSION', + defaultValue: 'DO-NOT-CHANGE-THIS-SELECTION', + description: 'CI testing python version to utilize for scheduled test runs of the driver (DO NOT CHANGE THIS SELECTION)') + string( + name: 'CI_SCHEDULE_SERVER_VERSION', + defaultValue: 'DO-NOT-CHANGE-THIS-SELECTION', + description: 'CI testing server version to utilize for scheduled test runs of the driver (DO NOT CHANGE THIS SELECTION)') + } + + triggers { + parameterizedCron((scheduleTriggerJobName == env.JOB_NAME) ? """ + # Every weeknight (Monday - Friday) around 4:00 AM + # These schedules will run with and without Cython enabled for Python v2.7.18 and v3.5.9 + H 4 * * 1-5 %CI_SCHEDULE=WEEKNIGHTS;EVENT_LOOP=LIBEV;CI_SCHEDULE_PYTHON_VERSION=2.7.18 3.5.9;CI_SCHEDULE_SERVER_VERSION=2.2 3.11 dse-5.1 dse-6.0 dse-6.7 + """ : "") + } + + environment { + OS_VERSION = 'ubuntu/bionic64/python-driver' + CCM_ENVIRONMENT_SHELL = '/usr/local/bin/ccm_environment.sh' + CCM_MAX_HEAP_SIZE = '1536M' + } + + stages { + stage ('Build and Test') { + agent { + // // If I removed this agent block, GIT_URL and GIT_COMMIT aren't set. + // // However, this trigger an additional checkout + label "master" + } + when { + beforeAgent true + allOf { + not { buildingTag() } + } + } + + steps { + script { + context = getBuildContext() + withEnv(context.vars) { + describeBuild(context) + slack.notifyChannel() + + // build and test all builds + parallel getMatrixBuilds(context) + + // send the metrics + submitCIMetrics('commit') + slack.notifyChannel(currentBuild.currentResult) + } + } + } + } + + } +} diff --git a/Jenkinsfile.bak b/Jenkinsfile.bak new file mode 100644 index 0000000..87b2080 --- /dev/null +++ b/Jenkinsfile.bak @@ -0,0 +1,873 @@ +#!groovy + +def initializeEnvironment() { + env.DRIVER_DISPLAY_NAME = 'Cassandra Python Driver' + env.DRIVER_METRIC_TYPE = 'oss' + if (env.GIT_URL.contains('riptano/python-driver')) { + env.DRIVER_DISPLAY_NAME = 'private ' + env.DRIVER_DISPLAY_NAME + env.DRIVER_METRIC_TYPE = 'oss-private' + } else if (env.GIT_URL.contains('python-dse-driver')) { + env.DRIVER_DISPLAY_NAME = 'DSE Python Driver' + env.DRIVER_METRIC_TYPE = 'dse' + } + + env.GIT_SHA = "${env.GIT_COMMIT.take(7)}" + env.GITHUB_PROJECT_URL = "https://${GIT_URL.replaceFirst(/(git@|http:\/\/|https:\/\/)/, '').replace(':', '/').replace('.git', '')}" + env.GITHUB_BRANCH_URL = "${GITHUB_PROJECT_URL}/tree/${env.BRANCH_NAME}" + env.GITHUB_COMMIT_URL = "${GITHUB_PROJECT_URL}/commit/${env.GIT_COMMIT}" + + sh label: 'Assign Python global environment', script: '''#!/bin/bash -lex + pyenv global ${PYTHON_VERSION} + ''' + + sh label: 'Install socat; required for unix socket tests', script: '''#!/bin/bash -lex + sudo apt-get install socat + ''' + + sh label: 'Install the latest setuptools', script: '''#!/bin/bash -lex + pip install --upgrade pip + pip install -U setuptools + ''' + + sh label: 'Install CCM', script: '''#!/bin/bash -lex + pip install ${HOME}/ccm + ''' + + // Determine if server version is Apache Cassandra� or DataStax Enterprise + if (env.CASSANDRA_VERSION.split('-')[0] == 'dse') { + sh label: 'Install DataStax Enterprise requirements', script: '''#!/bin/bash -lex + pip install -r test-datastax-requirements.txt + ''' + } else { + sh label: 'Install Apache CassandraⓇ requirements', script: '''#!/bin/bash -lex + pip install -r test-requirements.txt + ''' + + sh label: 'Uninstall the geomet dependency since it is not required for Cassandra', script: '''#!/bin/bash -lex + pip uninstall -y geomet + ''' + + } + + sh label: 'Install unit test modules', script: '''#!/bin/bash -lex + pip install nose-ignore-docstring nose-exclude service_identity + ''' + + if (env.CYTHON_ENABLED == 'True') { + sh label: 'Install cython modules', script: '''#!/bin/bash -lex + pip install cython numpy + ''' + } + + sh label: 'Download Apache CassandraⓇ or DataStax Enterprise', script: '''#!/bin/bash -lex + . ${CCM_ENVIRONMENT_SHELL} ${CASSANDRA_VERSION} + ''' + + sh label: 'Display Python and environment information', script: '''#!/bin/bash -le + # Load CCM environment variables + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + python --version + pip --version + printenv | sort + ''' +} + +def installDriverAndCompileExtensions() { + if (env.CYTHON_ENABLED == 'True') { + sh label: 'Install the driver and compile with C extensions with Cython', script: '''#!/bin/bash -lex + python setup.py build_ext --inplace + ''' + } else { + sh label: 'Install the driver and compile with C extensions without Cython', script: '''#!/bin/bash -lex + python setup.py build_ext --inplace --no-cython + ''' + } +} + +def executeStandardTests() { + + sh label: 'Execute unit tests', script: '''#!/bin/bash -lex + # Load CCM environment variables + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=unit_results.xml tests/unit/ || true + EVENT_LOOP_MANAGER=eventlet VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=unit_eventlet_results.xml tests/unit/io/test_eventletreactor.py || true + EVENT_LOOP_MANAGER=gevent VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=unit_gevent_results.xml tests/unit/io/test_geventreactor.py || true + ''' + + sh label: 'Execute Simulacron integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variables + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + SIMULACRON_JAR="${HOME}/simulacron.jar" + SIMULACRON_JAR=${SIMULACRON_JAR} EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} CASSANDRA_DIR=${CCM_INSTALL_DIR} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --exclude test_backpressure.py --xunit-file=simulacron_results.xml tests/integration/simulacron/ || true + + # Run backpressure tests separately to avoid memory issue + SIMULACRON_JAR=${SIMULACRON_JAR} EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} CASSANDRA_DIR=${CCM_INSTALL_DIR} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --exclude test_backpressure.py --xunit-file=simulacron_backpressure_1_results.xml tests/integration/simulacron/test_backpressure.py:TCPBackpressureTests.test_paused_connections || true + SIMULACRON_JAR=${SIMULACRON_JAR} EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} CASSANDRA_DIR=${CCM_INSTALL_DIR} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --exclude test_backpressure.py --xunit-file=simulacron_backpressure_2_results.xml tests/integration/simulacron/test_backpressure.py:TCPBackpressureTests.test_queued_requests_timeout || true + SIMULACRON_JAR=${SIMULACRON_JAR} EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} CASSANDRA_DIR=${CCM_INSTALL_DIR} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --exclude test_backpressure.py --xunit-file=simulacron_backpressure_3_results.xml tests/integration/simulacron/test_backpressure.py:TCPBackpressureTests.test_cluster_busy || true + SIMULACRON_JAR=${SIMULACRON_JAR} EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} CASSANDRA_DIR=${CCM_INSTALL_DIR} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --exclude test_backpressure.py --xunit-file=simulacron_backpressure_4_results.xml tests/integration/simulacron/test_backpressure.py:TCPBackpressureTests.test_node_busy || true + ''' + + sh label: 'Execute CQL engine integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variables + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=cqle_results.xml tests/integration/cqlengine/ || true + ''' + + sh label: 'Execute Apache CassandraⓇ integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variables + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=standard_results.xml tests/integration/standard/ || true + ''' + + if (env.CASSANDRA_VERSION.split('-')[0] == 'dse' && env.CASSANDRA_VERSION.split('-')[1] != '4.8') { + sh label: 'Execute DataStax Enterprise integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variable + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} CASSANDRA_DIR=${CCM_INSTALL_DIR} DSE_VERSION=${DSE_VERSION} ADS_HOME="${HOME}/" VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=dse_results.xml tests/integration/advanced/ || true + ''' + } + + sh label: 'Execute DataStax Constellation integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variable + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} CLOUD_PROXY_PATH="${HOME}/proxy/" CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=advanced_results.xml tests/integration/cloud/ || true + ''' + + if (env.EXECUTE_LONG_TESTS == 'True') { + sh label: 'Execute long running integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variable + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --exclude-dir=tests/integration/long/upgrade --with-ignore-docstrings --with-xunit --xunit-file=long_results.xml tests/integration/long/ || true + ''' + } +} + +def executeDseSmokeTests() { + sh label: 'Execute profile DataStax Enterprise smoke test integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variable + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} CCM_ARGS="${CCM_ARGS}" CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} DSE_VERSION=${DSE_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=standard_results.xml tests/integration/standard/test_dse.py || true + ''' +} + +def executeEventLoopTests() { + sh label: 'Execute profile event loop manager integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variable + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP_TESTS=( + "tests/integration/standard/test_cluster.py" + "tests/integration/standard/test_concurrent.py" + "tests/integration/standard/test_connection.py" + "tests/integration/standard/test_control_connection.py" + "tests/integration/standard/test_metrics.py" + "tests/integration/standard/test_query.py" + "tests/integration/simulacron/test_endpoint.py" + "tests/integration/long/test_ssl.py" + ) + EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} CCM_ARGS="${CCM_ARGS}" DSE_VERSION=${DSE_VERSION} CASSANDRA_VERSION=${CCM_CASSANDRA_VERSION} MAPPED_CASSANDRA_VERSION=${MAPPED_CASSANDRA_VERSION} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=standard_results.xml ${EVENT_LOOP_TESTS[@]} || true + ''' +} + +def executeUpgradeTests() { + sh label: 'Execute profile upgrade integration tests', script: '''#!/bin/bash -lex + # Load CCM environment variable + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + EVENT_LOOP_MANAGER=${EVENT_LOOP_MANAGER} VERIFY_CYTHON=${CYTHON_ENABLED} nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=upgrade_results.xml tests/integration/upgrade || true + ''' +} + +def executeTests() { + switch(params.PROFILE) { + case 'DSE-SMOKE-TEST': + executeDseSmokeTests() + break + case 'EVENT-LOOP': + executeEventLoopTests() + break + case 'UPGRADE': + executeUpgradeTests() + break + default: + executeStandardTests() + break + } +} + +def notifySlack(status = 'started') { + // Set the global pipeline scoped environment (this is above each matrix) + env.BUILD_STATED_SLACK_NOTIFIED = 'true' + + def buildType = 'Commit' + if (params.CI_SCHEDULE != 'DO-NOT-CHANGE-THIS-SELECTION') { + buildType = "${params.CI_SCHEDULE.toLowerCase().capitalize()}" + } + + def color = 'good' // Green + if (status.equalsIgnoreCase('aborted')) { + color = '808080' // Grey + } else if (status.equalsIgnoreCase('unstable')) { + color = 'warning' // Orange + } else if (status.equalsIgnoreCase('failed')) { + color = 'danger' // Red + } + + def message = """Build ${status} for ${env.DRIVER_DISPLAY_NAME} [${buildType}] +<${env.GITHUB_BRANCH_URL}|${env.BRANCH_NAME}> - <${env.RUN_DISPLAY_URL}|#${env.BUILD_NUMBER}> - <${env.GITHUB_COMMIT_URL}|${env.GIT_SHA}>""" + if (params.CI_SCHEDULE != 'DO-NOT-CHANGE-THIS-SELECTION') { + message += " - ${params.CI_SCHEDULE_PYTHON_VERSION} - ${params.EVENT_LOOP_MANAGER}" + } + if (!status.equalsIgnoreCase('Started')) { + message += """ +${status} after ${currentBuild.durationString - ' and counting'}""" + } + + slackSend color: "${color}", + channel: "#python-driver-dev-bots", + message: "${message}" +} + +def submitCIMetrics(buildType) { + long durationMs = currentBuild.duration + long durationSec = durationMs / 1000 + long nowSec = (currentBuild.startTimeInMillis + durationMs) / 1000 + def branchNameNoPeriods = env.BRANCH_NAME.replaceAll('\\.', '_') + def durationMetric = "okr.ci.python.${env.DRIVER_METRIC_TYPE}.${buildType}.${branchNameNoPeriods} ${durationSec} ${nowSec}" + + timeout(time: 1, unit: 'MINUTES') { + withCredentials([string(credentialsId: 'lab-grafana-address', variable: 'LAB_GRAFANA_ADDRESS'), + string(credentialsId: 'lab-grafana-port', variable: 'LAB_GRAFANA_PORT')]) { + withEnv(["DURATION_METRIC=${durationMetric}"]) { + sh label: 'Send runtime metrics to labgrafana', script: '''#!/bin/bash -lex + echo "${DURATION_METRIC}" | nc -q 5 ${LAB_GRAFANA_ADDRESS} ${LAB_GRAFANA_PORT} + ''' + } + } + } +} + +def describePerCommitStage() { + script { + def type = 'standard' + def serverDescription = 'current Apache CassandaraⓇ and supported DataStax Enterprise versions' + if (env.BRANCH_NAME ==~ /long-python.*/) { + type = 'long' + } else if (env.BRANCH_NAME ==~ /dev-python.*/) { + type = 'dev' + } + + currentBuild.displayName = "Per-Commit (${env.EVENT_LOOP_MANAGER} | ${type.capitalize()})" + currentBuild.description = "Per-Commit build and ${type} testing of ${serverDescription} against Python v2.7.18 and v3.5.9 using ${env.EVENT_LOOP_MANAGER} event loop manager" + } + + sh label: 'Describe the python environment', script: '''#!/bin/bash -lex + python -V + pip freeze + ''' +} + +def describeScheduledTestingStage() { + script { + def type = params.CI_SCHEDULE.toLowerCase().capitalize() + def displayName = "${type} schedule (${env.EVENT_LOOP_MANAGER}" + if (env.CYTHON_ENABLED == 'True') { + displayName += " | Cython" + } + if (params.PROFILE != 'NONE') { + displayName += " | ${params.PROFILE}" + } + displayName += ")" + currentBuild.displayName = displayName + + def serverVersionDescription = "${params.CI_SCHEDULE_SERVER_VERSION.replaceAll(' ', ', ')} server version(s) in the matrix" + def pythonVersionDescription = "${params.CI_SCHEDULE_PYTHON_VERSION.replaceAll(' ', ', ')} Python version(s) in the matrix" + def description = "${type} scheduled testing using ${env.EVENT_LOOP_MANAGER} event loop manager" + if (env.CYTHON_ENABLED == 'True') { + description += ", with Cython enabled" + } + if (params.PROFILE != 'NONE') { + description += ", ${params.PROFILE} profile" + } + description += ", ${serverVersionDescription}, and ${pythonVersionDescription}" + currentBuild.description = description + } +} + +def describeAdhocTestingStage() { + script { + def serverType = params.ADHOC_BUILD_AND_EXECUTE_TESTS_SERVER_VERSION.split('-')[0] + def serverDisplayName = 'Apache CassandaraⓇ' + def serverVersion = " v${serverType}" + if (serverType == 'ALL') { + serverDisplayName = "all ${serverDisplayName} and DataStax Enterprise server versions" + serverVersion = '' + } else { + try { + serverVersion = " v${env.ADHOC_BUILD_AND_EXECUTE_TESTS_SERVER_VERSION.split('-')[1]}" + } catch (e) { + ;; // no-op + } + if (serverType == 'dse') { + serverDisplayName = 'DataStax Enterprise' + } + } + def displayName = "${params.ADHOC_BUILD_AND_EXECUTE_TESTS_SERVER_VERSION} for v${params.ADHOC_BUILD_AND_EXECUTE_TESTS_PYTHON_VERSION} (${env.EVENT_LOOP_MANAGER}" + if (env.CYTHON_ENABLED == 'True') { + displayName += " | Cython" + } + if (params.PROFILE != 'NONE') { + displayName += " | ${params.PROFILE}" + } + displayName += ")" + currentBuild.displayName = displayName + + def description = "Testing ${serverDisplayName} ${serverVersion} using ${env.EVENT_LOOP_MANAGER} against Python ${params.ADHOC_BUILD_AND_EXECUTE_TESTS_PYTHON_VERSION}" + if (env.CYTHON_ENABLED == 'True') { + description += ", with Cython" + } + if (params.PROFILE == 'NONE') { + if (params.EXECUTE_LONG_TESTS) { + description += ", with" + } else { + description += ", without" + } + description += " long tests executed" + } else { + description += ", ${params.PROFILE} profile" + } + currentBuild.description = description + } +} + +def branchPatternCron = ~"(master)" +def riptanoPatternCron = ~"(riptano)" + +pipeline { + agent none + + // Global pipeline timeout + options { + timeout(time: 10, unit: 'HOURS') + buildDiscarder(logRotator(artifactNumToKeepStr: '10', // Keep only the last 10 artifacts + numToKeepStr: '50')) // Keep only the last 50 build records + } + + parameters { + choice( + name: 'ADHOC_BUILD_TYPE', + choices: ['BUILD', 'BUILD-AND-EXECUTE-TESTS'], + description: '''

Perform a adhoc build operation

+ + + + + + + + + + + + + + + +
ChoiceDescription
BUILDPerforms a Per-Commit build
BUILD-AND-EXECUTE-TESTSPerforms a build and executes the integration and unit tests
''') + choice( + name: 'ADHOC_BUILD_AND_EXECUTE_TESTS_PYTHON_VERSION', + choices: ['2.7.18', '3.4.10', '3.5.9', '3.6.10', '3.7.7', '3.8.3'], + description: 'Python version to use for adhoc BUILD-AND-EXECUTE-TESTS ONLY!') + choice( + name: 'ADHOC_BUILD_AND_EXECUTE_TESTS_SERVER_VERSION', + choices: ['2.1', // Legacy Apache CassandraⓇ + '2.2', // Legacy Apache CassandraⓇ + '3.0', // Previous Apache CassandraⓇ + '3.11', // Current Apache CassandraⓇ + '4.0', // Development Apache CassandraⓇ + 'dse-5.0', // Long Term Support DataStax Enterprise + 'dse-5.1', // Legacy DataStax Enterprise + 'dse-6.0', // Previous DataStax Enterprise + 'dse-6.7', // Previous DataStax Enterprise + 'dse-6.8', // Current DataStax Enterprise + 'ALL'], + description: '''Apache CassandraⓇ and DataStax Enterprise server version to use for adhoc BUILD-AND-EXECUTE-TESTS ONLY! + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ChoiceDescription
2.1Apache CassandaraⓇ; v2.1.x
2.2Apache CassandarⓇ; v2.2.x
3.0Apache CassandaraⓇ v3.0.x
3.11Apache CassandaraⓇ v3.11.x
4.0Apache CassandaraⓇ v4.x (CURRENTLY UNDER DEVELOPMENT)
dse-5.0DataStax Enterprise v5.0.x (Long Term Support)
dse-5.1DataStax Enterprise v5.1.x
dse-6.0DataStax Enterprise v6.0.x
dse-6.7DataStax Enterprise v6.7.x
dse-6.8DataStax Enterprise v6.8.x (CURRENTLY UNDER DEVELOPMENT)
''') + booleanParam( + name: 'CYTHON', + defaultValue: false, + description: 'Flag to determine if Cython should be enabled for scheduled or adhoc builds') + booleanParam( + name: 'EXECUTE_LONG_TESTS', + defaultValue: false, + description: 'Flag to determine if long integration tests should be executed for scheduled or adhoc builds') + choice( + name: 'EVENT_LOOP_MANAGER', + choices: ['LIBEV', 'GEVENT', 'EVENTLET', 'ASYNCIO', 'ASYNCORE', 'TWISTED'], + description: '''

Event loop manager to utilize for scheduled or adhoc builds

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ChoiceDescription
LIBEVA full-featured and high-performance event loop that is loosely modeled after libevent, but without its limitations and bugs
GEVENTA co-routine -based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libev or libuv event loop
EVENTLETA concurrent networking library for Python that allows you to change how you run your code, not how you write it
ASYNCIOA library to write concurrent code using the async/await syntax
ASYNCOREA module provides the basic infrastructure for writing asynchronous socket service clients and servers
TWISTEDAn event-driven networking engine written in Python and licensed under the open source MIT license
''') + choice( + name: 'PROFILE', + choices: ['NONE', 'DSE-SMOKE-TEST', 'EVENT-LOOP', 'UPGRADE'], + description: '''

Profile to utilize for scheduled or adhoc builds

+ + + + + + + + + + + + + + + + + + + + + + + +
ChoiceDescription
NONEExecute the standard tests for the driver
DSE-SMOKE-TESTExecute only the DataStax Enterprise smoke tests
EVENT-LOOPExecute only the event loop tests for the specified event loop manager (see: EVENT_LOOP_MANAGER)
UPGRADEExecute only the upgrade tests
''') + choice( + name: 'CI_SCHEDULE', + choices: ['DO-NOT-CHANGE-THIS-SELECTION', 'WEEKNIGHTS', 'WEEKENDS'], + description: 'CI testing schedule to execute periodically scheduled builds and tests of the driver (DO NOT CHANGE THIS SELECTION)') + string( + name: 'CI_SCHEDULE_PYTHON_VERSION', + defaultValue: 'DO-NOT-CHANGE-THIS-SELECTION', + description: 'CI testing python version to utilize for scheduled test runs of the driver (DO NOT CHANGE THIS SELECTION)') + string( + name: 'CI_SCHEDULE_SERVER_VERSION', + defaultValue: 'DO-NOT-CHANGE-THIS-SELECTION', + description: 'CI testing server version to utilize for scheduled test runs of the driver (DO NOT CHANGE THIS SELECTION)') + } + + triggers { + parameterizedCron((branchPatternCron.matcher(env.BRANCH_NAME).matches() && !riptanoPatternCron.matcher(GIT_URL).find()) ? """ + # Every weeknight (Monday - Friday) around 4:00 AM + # These schedules will run with and without Cython enabled for Python v2.7.18 and v3.5.9 + H 4 * * 1-5 %CI_SCHEDULE=WEEKNIGHTS;EVENT_LOOP_MANAGER=LIBEV;CI_SCHEDULE_PYTHON_VERSION=2.7.18;CI_SCHEDULE_SERVER_VERSION=2.2 3.11 dse-5.1 dse-6.0 dse-6.7 + H 4 * * 1-5 %CI_SCHEDULE=WEEKNIGHTS;EVENT_LOOP_MANAGER=LIBEV;CI_SCHEDULE_PYTHON_VERSION=3.5.9;CI_SCHEDULE_SERVER_VERSION=2.2 3.11 dse-5.1 dse-6.0 dse-6.7 + + # Every Saturday around 12:00, 4:00 and 8:00 PM + # These schedules are for weekly libev event manager runs with and without Cython for most of the Python versions (excludes v3.5.9.x) + H 12 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=LIBEV;CI_SCHEDULE_PYTHON_VERSION=2.7.18;CI_SCHEDULE_SERVER_VERSION=2.1 3.0 dse-5.1 dse-6.0 dse-6.7 + H 12 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=LIBEV;CI_SCHEDULE_PYTHON_VERSION=3.4.10;CI_SCHEDULE_SERVER_VERSION=2.1 3.0 dse-5.1 dse-6.0 dse-6.7 + H 12 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=LIBEV;CI_SCHEDULE_PYTHON_VERSION=3.6.10;CI_SCHEDULE_SERVER_VERSION=2.1 3.0 dse-5.1 dse-6.0 dse-6.7 + H 12 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=LIBEV;CI_SCHEDULE_PYTHON_VERSION=3.7.7;CI_SCHEDULE_SERVER_VERSION=2.1 3.0 dse-5.1 dse-6.0 dse-6.7 + H 12 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=LIBEV;CI_SCHEDULE_PYTHON_VERSION=3.8.3;CI_SCHEDULE_SERVER_VERSION=2.1 3.0 dse-5.1 dse-6.0 dse-6.7 + # These schedules are for weekly gevent event manager event loop only runs with and without Cython for most of the Python versions (excludes v3.4.10.x) + H 16 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=GEVENT;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=2.7.18;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 16 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=GEVENT;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.5.9;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 16 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=GEVENT;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.6.10;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 16 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=GEVENT;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.7.7;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 16 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=GEVENT;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.8.3;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + # These schedules are for weekly eventlet event manager event loop only runs with and without Cython for most of the Python versions (excludes v3.4.10.x) + H 20 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=EVENTLET;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=2.7.18;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 20 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=EVENTLET;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.5.9;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 20 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=EVENTLET;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.6.10;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 20 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=EVENTLET;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.7.7;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 20 * * 6 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=EVENTLET;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.8.3;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + + # Every Sunday around 12:00 and 4:00 AM + # These schedules are for weekly asyncore event manager event loop only runs with and without Cython for most of the Python versions (excludes v3.4.10.x) + H 0 * * 7 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=ASYNCORE;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=2.7.18;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 0 * * 7 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=ASYNCORE;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.5.9;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 0 * * 7 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=ASYNCORE;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.6.10;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 0 * * 7 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=ASYNCORE;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.7.7;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 0 * * 7 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=ASYNCORE;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.8.3;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + # These schedules are for weekly twisted event manager event loop only runs with and without Cython for most of the Python versions (excludes v3.4.10.x) + H 4 * * 7 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=TWISTED;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=2.7.18;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 4 * * 7 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=TWISTED;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.5.9;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 4 * * 7 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=TWISTED;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.6.10;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 4 * * 7 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=TWISTED;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.7.7;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + H 4 * * 7 %CI_SCHEDULE=WEEKENDS;EVENT_LOOP_MANAGER=TWISTED;PROFILE=EVENT-LOOP;CI_SCHEDULE_PYTHON_VERSION=3.8.3;CI_SCHEDULE_SERVER_VERSION=2.1 2.2 3.0 3.11 dse-5.1 dse-6.0 dse-6.7 + """ : "") + } + + environment { + OS_VERSION = 'ubuntu/bionic64/python-driver' + CYTHON_ENABLED = "${params.CYTHON ? 'True' : 'False'}" + EVENT_LOOP_MANAGER = "${params.EVENT_LOOP_MANAGER.toLowerCase()}" + EXECUTE_LONG_TESTS = "${params.EXECUTE_LONG_TESTS ? 'True' : 'False'}" + CCM_ENVIRONMENT_SHELL = '/usr/local/bin/ccm_environment.sh' + CCM_MAX_HEAP_SIZE = '1536M' + } + + stages { + stage ('Per-Commit') { + options { + timeout(time: 2, unit: 'HOURS') + } + when { + beforeAgent true + branch pattern: '((dev|long)-)?python-.*', comparator: 'REGEXP' + allOf { + expression { params.ADHOC_BUILD_TYPE == 'BUILD' } + expression { params.CI_SCHEDULE == 'DO-NOT-CHANGE-THIS-SELECTION' } + not { buildingTag() } + } + } + + matrix { + axes { + axis { + name 'CASSANDRA_VERSION' + values '3.11', // Current Apache Cassandra + 'dse-6.8' // Current DataStax Enterprise + } + axis { + name 'PYTHON_VERSION' + values '2.7.18', '3.5.9' + } + axis { + name 'CYTHON_ENABLED' + values 'False' + } + } + + agent { + label "${OS_VERSION}" + } + + stages { + stage('Initialize-Environment') { + steps { + initializeEnvironment() + script { + if (env.BUILD_STATED_SLACK_NOTIFIED != 'true') { + notifySlack() + } + } + } + } + stage('Describe-Build') { + steps { + describePerCommitStage() + } + } + stage('Install-Driver-And-Compile-Extensions') { + steps { + installDriverAndCompileExtensions() + } + } + stage('Execute-Tests') { + steps { + + script { + if (env.BRANCH_NAME ==~ /long-python.*/) { + withEnv(["EXECUTE_LONG_TESTS=True"]) { + executeTests() + } + } + else { + executeTests() + } + } + } + post { + always { + junit testResults: '*_results.xml' + } + } + } + } + } + post { + always { + node('master') { + submitCIMetrics('commit') + } + } + aborted { + notifySlack('aborted') + } + success { + notifySlack('completed') + } + unstable { + notifySlack('unstable') + } + failure { + notifySlack('FAILED') + } + } + } + + stage ('Scheduled-Testing') { + when { + beforeAgent true + allOf { + expression { params.ADHOC_BUILD_TYPE == 'BUILD' } + expression { params.CI_SCHEDULE != 'DO-NOT-CHANGE-THIS-SELECTION' } + not { buildingTag() } + } + } + matrix { + axes { + axis { + name 'CASSANDRA_VERSION' + values '2.1', // Legacy Apache Cassandra + '2.2', // Legacy Apache Cassandra + '3.0', // Previous Apache Cassandra + '3.11', // Current Apache Cassandra + 'dse-5.1', // Legacy DataStax Enterprise + 'dse-6.0', // Previous DataStax Enterprise + 'dse-6.7' // Current DataStax Enterprise + } + axis { + name 'CYTHON_ENABLED' + values 'True', 'False' + } + } + when { + beforeAgent true + allOf { + expression { return params.CI_SCHEDULE_SERVER_VERSION.split(' ').any { it =~ /(ALL|${env.CASSANDRA_VERSION})/ } } + } + } + + environment { + PYTHON_VERSION = "${params.CI_SCHEDULE_PYTHON_VERSION}" + } + agent { + label "${OS_VERSION}" + } + + stages { + stage('Initialize-Environment') { + steps { + initializeEnvironment() + script { + if (env.BUILD_STATED_SLACK_NOTIFIED != 'true') { + notifySlack() + } + } + } + } + stage('Describe-Build') { + steps { + describeScheduledTestingStage() + } + } + stage('Install-Driver-And-Compile-Extensions') { + steps { + installDriverAndCompileExtensions() + } + } + stage('Execute-Tests') { + steps { + executeTests() + } + post { + always { + junit testResults: '*_results.xml' + } + } + } + } + } + post { + aborted { + notifySlack('aborted') + } + success { + notifySlack('completed') + } + unstable { + notifySlack('unstable') + } + failure { + notifySlack('FAILED') + } + } + } + + + stage('Adhoc-Testing') { + when { + beforeAgent true + allOf { + expression { params.ADHOC_BUILD_TYPE == 'BUILD-AND-EXECUTE-TESTS' } + not { buildingTag() } + } + } + + environment { + CYTHON_ENABLED = "${params.CYTHON ? 'True' : 'False'}" + PYTHON_VERSION = "${params.ADHOC_BUILD_AND_EXECUTE_TESTS_PYTHON_VERSION}" + } + + matrix { + axes { + axis { + name 'CASSANDRA_VERSION' + values '2.1', // Legacy Apache Cassandra + '2.2', // Legacy Apache Cassandra + '3.0', // Previous Apache Cassandra + '3.11', // Current Apache Cassandra + '4.0', // Development Apache Cassandra + 'dse-5.0', // Long Term Support DataStax Enterprise + 'dse-5.1', // Legacy DataStax Enterprise + 'dse-6.0', // Previous DataStax Enterprise + 'dse-6.7', // Current DataStax Enterprise + 'dse-6.8' // Development DataStax Enterprise + } + } + when { + beforeAgent true + allOf { + expression { params.ADHOC_BUILD_AND_EXECUTE_TESTS_SERVER_VERSION ==~ /(ALL|${env.CASSANDRA_VERSION})/ } + } + } + + agent { + label "${OS_VERSION}" + } + + stages { + stage('Describe-Build') { + steps { + describeAdhocTestingStage() + } + } + stage('Initialize-Environment') { + steps { + initializeEnvironment() + } + } + stage('Install-Driver-And-Compile-Extensions') { + steps { + installDriverAndCompileExtensions() + } + } + stage('Execute-Tests') { + steps { + executeTests() + } + post { + always { + junit testResults: '*_results.xml' + } + } + } + } + } + } + } +} diff --git a/README-dev.rst b/README-dev.rst index c10aed2..85a722c 100644 --- a/README-dev.rst +++ b/README-dev.rst @@ -1,171 +1,251 @@ Releasing ========= * Run the tests and ensure they all pass * Update CHANGELOG.rst - * Check for any missing entries * Add today's date to the release section * Update the version in ``cassandra/__init__.py`` - * For beta releases, use a version like ``(2, 1, '0b1')`` * For release candidates, use a version like ``(2, 1, '0rc1')`` * When in doubt, follow PEP 440 versioning * Add the new version in ``docs.yaml`` - * Commit the changelog and version changes, e.g. ``git commit -m'version 1.0.0'`` * Tag the release. For example: ``git tag -a 1.0.0 -m 'version 1.0.0'`` * Push the tag and new ``master``: ``git push origin 1.0.0 ; git push origin master`` -* Upload the package to pypi:: +* Update the `python-driver` submodule of `python-driver-wheels`, + commit then push. This will trigger TravisCI and the wheels building. +* For a GA release, upload the package to pypi:: + + # Clean the working directory + python setup.py clean + rm dist/* - python setup.py register - python setup.py sdist upload + # Build the source distribution + python setup.py sdist + + # Download all wheels from the jfrog repository and copy them in + # the dist/ directory + cp /path/to/wheels/*.whl dist/ + + # Upload all files + twine upload dist/* * On pypi, make the latest GA the only visible version * Update the docs (see below) * Append a 'postN' string to the version tuple in ``cassandra/__init__.py`` so that it looks like ``(x, y, z, 'postN')`` * After a beta or rc release, this should look like ``(2, 1, '0b1', 'post0')`` +* After the release has been tagged, add a section to docs.yaml with the new tag ref:: + + versions: + - name: + ref: + * Commit and push * Update 'cassandra-test' branch to reflect new release * this is typically a matter of merging or rebasing onto master * test and push updated branch to origin * Update the JIRA versions: https://datastax-oss.atlassian.net/plugins/servlet/project-config/PYTHON/versions * add release dates and set version as "released" * Make an announcement on the mailing list Building the Docs ================= Sphinx is required to build the docs. You probably want to install through apt, if possible:: sudo apt-get install python-sphinx pip may also work:: sudo pip install -U Sphinx To build the docs, run:: python setup.py doc Upload the Docs ================= This is deprecated. The docs is now only published on https://docs.datastax.com. To upload the docs, checkout the ``gh-pages`` branch and copy the entire contents all of ``docs/_build/X.Y.Z/*`` into the root of the ``gh-pages`` branch and then push that branch to github. For example:: git checkout 1.0.0 python setup.py doc git checkout gh-pages cp -R docs/_build/1.0.0/* . git add --update # add modified files # Also make sure to add any new documentation files! git commit -m 'Update docs (version 1.0.0)' git push origin gh-pages If docs build includes errors, those errors may not show up in the next build unless you have changed the files with errors. It's good to occassionally clear the build directory and build from scratch:: rm -rf docs/_build/* -Running the Tests -================= -In order for the extensions to be built and used in the test, run:: +Documentor +========== +We now also use another tool called Documentor with Sphinx source to build docs. +This gives us versioned docs with nice integrated search. This is a private tool +of DataStax. - nosetests +Dependencies +------------ +Sphinx +~~~~~~ +Installed as described above -You can run a specific test module or package like so:: +Documentor +~~~~~~~~~~ +Clone and setup Documentor as specified in `the project `_. +This tool assumes Ruby, bundler, and npm are present. - nosetests -w tests/unit/ +Building +-------- +The setup script expects documentor to be in the system path. You can either add it permanently or run with something +like this:: -You can run a specific test method like so:: + PATH=$PATH:/bin python setup.py doc - nosetests -w tests/unit/test_connection.py:ConnectionTest.test_bad_protocol_version +The docs will not display properly just browsing the filesystem in a browser. To view the docs as they would be in most +web servers, use the SimpleHTTPServer module:: -Seeing Test Logs in Real Time ------------------------------ -Sometimes it's useful to output logs for the tests as they run:: + cd docs/_build/ + python -m SimpleHTTPServer - nosetests -w tests/unit/ --nocapture --nologcapture +Then, browse to `localhost:8000 `_. -Use tee to capture logs and see them on your terminal:: +Tests +===== - nosetests -w tests/unit/ --nocapture --nologcapture 2>&1 | tee test.log +Running Unit Tests +------------------ +Unit tests can be run like so:: -Specifying a Cassandra Version for Integration Tests ----------------------------------------------------- -You can specify a cassandra version with the ``CASSANDRA_VERSION`` environment variable:: + nosetests -w tests/unit/ + +You can run a specific test method like so:: + + nosetests -w tests/unit/test_connection.py:ConnectionTest.test_bad_protocol_version + +Running Integration Tests +------------------------- +In order to run integration tests, you must specify a version to run using the ``CASSANDRA_VERSION`` or ``DSE_VERSION`` environment variable:: CASSANDRA_VERSION=2.0.9 nosetests -w tests/integration/standard -You can also specify a cassandra directory (to test unreleased versions):: +Or you can specify a cassandra directory (to test unreleased versions):: - CASSANDRA_DIR=/home/thobbs/cassandra nosetests -w tests/integration/standard + CASSANDRA_DIR=/home/thobbs/cassandra nosetests -w tests/integration/standard/ Specifying the usage of an already running Cassandra cluster ----------------------------------------------------- -The test will start the appropriate Cassandra clusters when necessary but if you don't want this to happen because a Cassandra cluster is already running the flag ``USE_CASS_EXTERNAL`` can be used, for example: +------------------------------------------------------------ +The test will start the appropriate Cassandra clusters when necessary but if you don't want this to happen because a Cassandra cluster is already running the flag ``USE_CASS_EXTERNAL`` can be used, for example:: - USE_CASS_EXTERNAL=1 python setup.py nosetests -w tests/integration/standard + USE_CASS_EXTERNAL=1 CASSANDRA_VERSION=2.0.9 nosetests -w tests/integration/standard Specify a Protocol Version for Tests ------------------------------------ The protocol version defaults to 1 for cassandra 1.2 and 2 otherwise. You can explicitly set it with the ``PROTOCOL_VERSION`` environment variable:: PROTOCOL_VERSION=3 nosetests -w tests/integration/standard +Seeing Test Logs in Real Time +----------------------------- +Sometimes it's useful to output logs for the tests as they run:: + + nosetests -w tests/unit/ --nocapture --nologcapture + +Use tee to capture logs and see them on your terminal:: + + nosetests -w tests/unit/ --nocapture --nologcapture 2>&1 | tee test.log + Testing Multiple Python Versions -------------------------------- -If you want to test all of python 2.7, 3.4, 3.5, 3.6 and pypy, use tox (this is what +If you want to test all of python 2.7, 3.5, 3.6, 3.7, and pypy, use tox (this is what TravisCI runs):: tox -By default, tox only runs the unit tests because I haven't put in the effort -to get the integration tests to run on TravicCI. However, the integration -tests should work locally. To run them, edit the following line in tox.ini:: - - commands = {envpython} setup.py build_ext --inplace nosetests --verbosity=2 tests/unit/ - -and change ``tests/unit/`` to ``tests/``. +By default, tox only runs the unit tests. Running the Benchmarks ====================== There needs to be a version of cassandra running locally so before running the benchmarks, if ccm is installed: ccm create benchmark_cluster -v 3.0.1 -n 1 -s To run the benchmarks, pick one of the files under the ``benchmarks/`` dir and run it:: python benchmarks/future_batches.py There are a few options. Use ``--help`` to see them all:: python benchmarks/future_batches.py --help Packaging for Cassandra ======================= A source distribution is included in Cassandra, which uses the driver internally for ``cqlsh``. To package a released version, checkout the tag and build a source zip archive:: python setup.py sdist --formats=zip If packaging a pre-release (untagged) version, it is useful to include a commit hash in the archive name to specify the built version:: python setup.py egg_info -b-`git rev-parse --short HEAD` sdist --formats=zip The file (``dist/cassandra-driver-.zip``) is packaged with Cassandra in ``cassandra/lib/cassandra-driver-internal-only*zip``. + +Releasing an EAP +================ + +An EAP release is only uploaded on a private server and it is not published on pypi. + +* Clean the environment:: + + python setup.py clean + +* Package the source distribution:: + + python setup.py sdist + +* Test the source distribution:: + + pip install dist/cassandra-driver-.tar.gz + +* Upload the package on the EAP download server. +* Build the documentation:: + + python setup.py doc + +* Upload the docs on the EAP download server. + +Adding a New Python Runtime Support +=================================== + +* Add the new python version to our jenkins image: + https://github.com/riptano/openstack-jenkins-drivers/ + +* Add the new python version in job-creator: + https://github.com/riptano/job-creator/ + +* Run the tests and ensure they all pass + * also test all event loops + +* Update the wheels building repo to support that version: + https://github.com/riptano/python-dse-driver-wheels diff --git a/README.rst b/README.rst index b98463c..7c5bf1e 100644 --- a/README.rst +++ b/README.rst @@ -1,89 +1,87 @@ -DataStax Python Driver for Apache Cassandra -=========================================== +DataStax Driver for Apache Cassandra +==================================== -.. image:: https://travis-ci.org/datastax/python-driver.png?branch=master - :target: https://travis-ci.org/datastax/python-driver +.. image:: https://travis-ci.com/datastax/python-driver.png?branch=master + :target: https://travis-ci.com/github/datastax/python-driver -A modern, `feature-rich `_ and highly-tunable Python client library for Apache Cassandra (2.1+) using exclusively Cassandra's binary protocol and Cassandra Query Language v3. +A modern, `feature-rich `_ and highly-tunable Python client library for Apache Cassandra (2.1+) and +DataStax Enterprise (4.7+) using exclusively Cassandra's binary protocol and Cassandra Query Language v3. -The driver supports Python 2.7, 3.4, 3.5, 3.6 and 3.7. - -If you require compatibility with DataStax Enterprise, use the `DataStax Enterprise Python Driver `_. +The driver supports Python 2.7, 3.5, 3.6, 3.7 and 3.8. **Note:** DataStax products do not support big-endian systems. -Feedback Requested ------------------- -**Help us focus our efforts!** Provide your input on the `Platform and Runtime Survey `_ (we kept it short). - Features -------- * `Synchronous `_ and `Asynchronous `_ APIs * `Simple, Prepared, and Batch statements `_ * Asynchronous IO, parallel execution, request pipelining * `Connection pooling `_ * Automatic node discovery * `Automatic reconnection `_ * Configurable `load balancing `_ and `retry policies `_ * `Concurrent execution utilities `_ * `Object mapper `_ -* `Connecting to DataStax Apollo database (cloud) `_ +* `Connecting to DataStax Astra database (cloud) `_ +* DSE Graph execution API +* DSE Geometric type serialization +* DSE PlainText and GSSAPI authentication Installation ------------ Installation through pip is recommended:: $ pip install cassandra-driver For more complete installation instructions, see the `installation guide `_. Documentation ------------- The documentation can be found online `here `_. A couple of links for getting up to speed: * `Installation `_ * `Getting started guide `_ * `API docs `_ * `Performance tips `_ Object Mapper ------------- cqlengine (originally developed by Blake Eggleston and Jon Haddad, with contributions from the community) is now maintained as an integral part of this package. Refer to `documentation here `_. Contributing ------------ See `CONTRIBUTING.md `_. Reporting Problems ------------------ Please report any bugs and make any feature requests on the `JIRA `_ issue tracker. If you would like to contribute, please feel free to open a pull request. Getting Help ------------ Your best options for getting help with the driver are the `mailing list `_ -and the ``#datastax-drivers`` channel in the `DataStax Academy Slack `_. +and the `DataStax Community `_. License ------- Copyright DataStax, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. diff --git a/appveyor/appveyor.ps1 b/appveyor/appveyor.ps1 index cc1e6aa..5f6840e 100644 --- a/appveyor/appveyor.ps1 +++ b/appveyor/appveyor.ps1 @@ -1,80 +1,80 @@ $env:JAVA_HOME="C:\Program Files\Java\jdk1.8.0" $env:PATH="$($env:JAVA_HOME)\bin;$($env:PATH)" $env:CCM_PATH="C:\Users\appveyor\ccm" $env:CASSANDRA_VERSION=$env:cassandra_version $env:EVENT_LOOP_MANAGER="asyncore" $env:SIMULACRON_JAR="C:\Users\appveyor\simulacron-standalone-0.7.0.jar" python --version python -c "import platform; print(platform.architecture())" # Install Ant Start-Process cinst -ArgumentList @("-y","ant") -Wait -NoNewWindow # Workaround for ccm, link ant.exe -> ant.bat If (!(Test-Path C:\ProgramData\chocolatey\bin\ant.bat)) { cmd /c mklink C:\ProgramData\chocolatey\bin\ant.bat C:\ProgramData\chocolatey\bin\ant.exe } $jce_indicator = "$target\README.txt" # Install Java Cryptographic Extensions, needed for SSL. If (!(Test-Path $jce_indicator)) { $zip = "C:\Users\appveyor\jce_policy-$($env:java_version).zip" $target = "$($env:JAVA_HOME)\jre\lib\security" # If this file doesn't exist we know JCE hasn't been installed. $url = "https://www.dropbox.com/s/po4308hlwulpvep/UnlimitedJCEPolicyJDK7.zip?dl=1" $extract_folder = "UnlimitedJCEPolicy" If ($env:java_version -eq "1.8.0") { $url = "https://www.dropbox.com/s/al1e6e92cjdv7m7/jce_policy-8.zip?dl=1" $extract_folder = "UnlimitedJCEPolicyJDK8" } # Download zip to staging area if it doesn't exist, we do this because # we extract it to the directory based on the platform and we want to cache # this file so it can apply to all platforms. if(!(Test-Path $zip)) { (new-object System.Net.WebClient).DownloadFile($url, $zip) } Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::ExtractToDirectory($zip, $target) $jcePolicyDir = "$target\$extract_folder" Move-Item $jcePolicyDir\* $target\ -force Remove-Item $jcePolicyDir } # Download simulacron $simulacron_url = "https://github.com/datastax/simulacron/releases/download/0.7.0/simulacron-standalone-0.7.0.jar" $simulacron_jar = $env:SIMULACRON_JAR if(!(Test-Path $simulacron_jar)) { (new-object System.Net.WebClient).DownloadFile($simulacron_url, $simulacron_jar) } # Install Python Dependencies for CCM. Start-Process python -ArgumentList "-m pip install psutil pyYaml six numpy" -Wait -NoNewWindow # Clone ccm from git and use master. If (!(Test-Path $env:CCM_PATH)) { - Start-Process git -ArgumentList "clone https://github.com/pcmanus/ccm.git $($env:CCM_PATH)" -Wait -NoNewWindow + Start-Process git -ArgumentList "clone -b cassandra-test https://github.com/pcmanus/ccm.git $($env:CCM_PATH)" -Wait -NoNewWindow } # Copy ccm -> ccm.py so windows knows to run it. If (!(Test-Path $env:CCM_PATH\ccm.py)) { Copy-Item "$env:CCM_PATH\ccm" "$env:CCM_PATH\ccm.py" } $env:PYTHONPATH="$($env:CCM_PATH);$($env:PYTHONPATH)" $env:PATH="$($env:CCM_PATH);$($env:PATH)" # Predownload cassandra version for CCM if it isn't already downloaded. # This is necessary because otherwise ccm fails If (!(Test-Path C:\Users\appveyor\.ccm\repository\$env:cassandra_version)) { Start-Process python -ArgumentList "$($env:CCM_PATH)\ccm.py create -v $($env:cassandra_version) -n 1 predownload" -Wait -NoNewWindow echo "Checking status of download" python $env:CCM_PATH\ccm.py status Start-Process python -ArgumentList "$($env:CCM_PATH)\ccm.py remove predownload" -Wait -NoNewWindow echo "Downloaded version $env:cassandra_version" } Start-Process python -ArgumentList "-m pip install -r test-requirements.txt" -Wait -NoNewWindow Start-Process python -ArgumentList "-m pip install nose-ignore-docstring" -Wait -NoNewWindow diff --git a/build.yaml b/build.yaml.bak similarity index 68% rename from build.yaml rename to build.yaml.bak index 335de1e..100c865 100644 --- a/build.yaml +++ b/build.yaml.bak @@ -1,255 +1,264 @@ schedules: nightly_master: schedule: nightly + disable_pull_requests: true branches: include: [master] env_vars: | EVENT_LOOP_MANAGER='libev' matrix: exclude: - - python: [3.4, 3.6, 3.7] - - cassandra: ['2.1', '3.0', 'test-dse'] + - python: [3.6, 3.7, 3.8] + - cassandra: ['2.1', '3.0', '4.0', 'test-dse'] commit_long_test: schedule: per_commit disable_pull_requests: true branches: include: [/long-python.*/] env_vars: | EVENT_LOOP_MANAGER='libev' matrix: exclude: - - python: [3.4, 3.6, 3.7] + - python: [3.6, 3.7, 3.8] - cassandra: ['2.1', '3.0', 'test-dse'] commit_branches: schedule: per_commit disable_pull_requests: true branches: include: [/python.*/] env_vars: | EVENT_LOOP_MANAGER='libev' EXCLUDE_LONG=1 matrix: exclude: - - python: [3.4, 3.6, 3.7] + - python: [3.6, 3.7, 3.8] - cassandra: ['2.1', '3.0', 'test-dse'] commit_branches_dev: schedule: per_commit disable_pull_requests: true branches: include: [/dev-python.*/] env_vars: | EVENT_LOOP_MANAGER='libev' EXCLUDE_LONG=1 matrix: exclude: - - python: [2.7, 3.4, 3.6, 3.7] - - cassandra: ['2.0', '2.1', '2.2', '3.0', 'test-dse'] + - python: [2.7, 3.7, 3.6, 3.8] + - cassandra: ['2.0', '2.1', '2.2', '3.0', '4.0', 'test-dse', 'dse-4.8', 'dse-5.0', 'dse-6.0', 'dse-6.8'] release_test: schedule: per_commit disable_pull_requests: true branches: include: [/release-.+/] env_vars: | EVENT_LOOP_MANAGER='libev' weekly_master: schedule: 0 10 * * 6 disable_pull_requests: true branches: include: [master] env_vars: | EVENT_LOOP_MANAGER='libev' matrix: exclude: - python: [3.5] - cassandra: ['2.2', '3.1'] weekly_gevent: schedule: 0 14 * * 6 disable_pull_requests: true branches: include: [master] env_vars: | EVENT_LOOP_MANAGER='gevent' JUST_EVENT_LOOP=1 - matrix: - exclude: - - python: [3.4] weekly_eventlet: schedule: 0 18 * * 6 disable_pull_requests: true branches: include: [master] env_vars: | EVENT_LOOP_MANAGER='eventlet' JUST_EVENT_LOOP=1 - matrix: - exclude: - - python: [3.4] weekly_asyncio: schedule: 0 22 * * 6 disable_pull_requests: true branches: include: [master] env_vars: | EVENT_LOOP_MANAGER='asyncio' JUST_EVENT_LOOP=1 matrix: exclude: - python: [2.7] weekly_async: schedule: 0 10 * * 7 disable_pull_requests: true branches: include: [master] env_vars: | EVENT_LOOP_MANAGER='asyncore' JUST_EVENT_LOOP=1 - matrix: - exclude: - - python: [3.4] weekly_twister: schedule: 0 14 * * 7 disable_pull_requests: true branches: include: [master] env_vars: | EVENT_LOOP_MANAGER='twisted' JUST_EVENT_LOOP=1 - matrix: - exclude: - - python: [3.4] upgrade_tests: schedule: adhoc branches: include: [master, python-546] env_vars: | EVENT_LOOP_MANAGER='libev' JUST_UPGRADE=True matrix: exclude: - - python: [3.4, 3.6, 3.7] - - cassandra: ['2.0', '2.1', '2.2', '3.0', 'test-dse'] + - python: [3.6, 3.7, 3.8] + - cassandra: ['2.0', '2.1', '2.2', '3.0', '4.0', 'test-dse'] python: - 2.7 - - 3.4 - 3.5 - 3.6 - 3.7 + - 3.8 os: - ubuntu/bionic64/python-driver cassandra: - '2.1' - '2.2' - '3.0' - '3.11' - - 'test-dse' + - '4.0' + - 'dse-4.8' + - 'dse-5.0' + - 'dse-5.1' + - 'dse-6.0' + - 'dse-6.7' + - 'dse-6.8.0' env: CYTHON: - CYTHON - NO_CYTHON build: - script: | export JAVA_HOME=$CCM_JAVA_HOME export PATH=$JAVA_HOME/bin:$PATH export PYTHONPATH="" + export CCM_MAX_HEAP_SIZE=1024M # Required for unix socket tests sudo apt-get install socat # Install latest setuptools pip install --upgrade pip pip install -U setuptools - pip install git+ssh://git@github.com/riptano/ccm-private.git + pip install git+ssh://git@github.com/riptano/ccm-private.git@cassandra-7544-native-ports-with-dse-fix + + #pip install $HOME/ccm + + if [ -n "$CCM_IS_DSE" ]; then + pip install -r test-datastax-requirements.txt + else + pip install -r test-requirements.txt + fi - pip install -r test-requirements.txt pip install nose-ignore-docstring pip install nose-exclude pip install service_identity FORCE_CYTHON=False if [[ $CYTHON == 'CYTHON' ]]; then FORCE_CYTHON=True pip install cython pip install numpy # Install the driver & compile C extensions python setup.py build_ext --inplace else # Install the driver & compile C extensions with no cython python setup.py build_ext --inplace --no-cython fi echo "JUST_UPGRADE: $JUST_UPGRADE" if [[ $JUST_UPGRADE == 'True' ]]; then EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=upgrade_results.xml tests/integration/upgrade || true exit 0 fi - if [[ $CCM_IS_DSE == 'true' ]]; then - # We only use a DSE version for unreleased DSE versions, so we only need to run the smoke tests here - echo "CCM_IS_DSE: $CCM_IS_DSE" + if [[ $JUST_SMOKE == 'true' ]]; then + # When we ONLY want to run the smoke tests + echo "JUST_SMOKE: $JUST_SMOKE" echo "==========RUNNING SMOKE TESTS===========" EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CCM_ARGS="$CCM_ARGS" CASSANDRA_VERSION=$CCM_CASSANDRA_VERSION DSE_VERSION='6.7.0' MAPPED_CASSANDRA_VERSION=$MAPPED_CASSANDRA_VERSION VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=standard_results.xml tests/integration/standard/test_dse.py || true exit 0 fi # Run the unit tests, this is not done in travis because # it takes too much time for the whole matrix to build with cython if [[ $CYTHON == 'CYTHON' ]]; then EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER VERIFY_CYTHON=1 nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=unit_results.xml tests/unit/ || true EVENT_LOOP_MANAGER=eventlet VERIFY_CYTHON=1 nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=unit_eventlet_results.xml tests/unit/io/test_eventletreactor.py || true EVENT_LOOP_MANAGER=gevent VERIFY_CYTHON=1 nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=unit_gevent_results.xml tests/unit/io/test_geventreactor.py || true fi if [ -n "$JUST_EVENT_LOOP" ]; then echo "Running integration event loop subset with $EVENT_LOOP_MANAGER" EVENT_LOOP_TESTS=( "tests/integration/standard/test_cluster.py" "tests/integration/standard/test_concurrent.py" "tests/integration/standard/test_connection.py" "tests/integration/standard/test_control_connection.py" "tests/integration/standard/test_metrics.py" "tests/integration/standard/test_query.py" "tests/integration/simulacron/test_endpoint.py" + "tests/integration/long/test_ssl.py" ) - EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CCM_ARGS="$CCM_ARGS" CASSANDRA_VERSION=$CCM_CASSANDRA_VERSION MAPPED_CASSANDRA_VERSION=$MAPPED_CASSANDRA_VERSION VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=standard_results.xml ${EVENT_LOOP_TESTS[@]} || true + EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CCM_ARGS="$CCM_ARGS" DSE_VERSION=$DSE_VERSION CASSANDRA_VERSION=$CCM_CASSANDRA_VERSION MAPPED_CASSANDRA_VERSION=$MAPPED_CASSANDRA_VERSION VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=standard_results.xml ${EVENT_LOOP_TESTS[@]} || true exit 0 fi echo "Running with event loop manager: $EVENT_LOOP_MANAGER" echo "==========RUNNING SIMULACRON TESTS==========" SIMULACRON_JAR="$HOME/simulacron.jar" - SIMULACRON_JAR=$SIMULACRON_JAR EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CASSANDRA_DIR=$CCM_INSTALL_DIR CCM_ARGS="$CCM_ARGS" DSE_VERSION=$CCM_CASSANDRA_VERSION MAPPED_CASSANDRA_VERSION=$MAPPED_CASSANDRA_VERSION VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=simulacron_results.xml tests/integration/simulacron/ || true + SIMULACRON_JAR=$SIMULACRON_JAR EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CASSANDRA_DIR=$CCM_INSTALL_DIR CCM_ARGS="$CCM_ARGS" DSE_VERSION=$DSE_VERSION CASSANDRA_VERSION=$CCM_CASSANDRA_VERSION MAPPED_CASSANDRA_VERSION=$MAPPED_CASSANDRA_VERSION VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=simulacron_results.xml tests/integration/simulacron/ || true echo "Running with event loop manager: $EVENT_LOOP_MANAGER" echo "==========RUNNING CQLENGINE TESTS==========" - EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CCM_ARGS="$CCM_ARGS" CASSANDRA_VERSION=$CCM_CASSANDRA_VERSION MAPPED_CASSANDRA_VERSION=$MAPPED_CASSANDRA_VERSION VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=cqle_results.xml tests/integration/cqlengine/ || true + EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CCM_ARGS="$CCM_ARGS" DSE_VERSION=$DSE_VERSION CASSANDRA_VERSION=$CCM_CASSANDRA_VERSION MAPPED_CASSANDRA_VERSION=$MAPPED_CASSANDRA_VERSION VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=cqle_results.xml tests/integration/cqlengine/ || true echo "==========RUNNING INTEGRATION TESTS==========" - EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CCM_ARGS="$CCM_ARGS" CASSANDRA_VERSION=$CCM_CASSANDRA_VERSION MAPPED_CASSANDRA_VERSION=$MAPPED_CASSANDRA_VERSION VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=standard_results.xml tests/integration/standard/ || true + EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CCM_ARGS="$CCM_ARGS" DSE_VERSION=$DSE_VERSION CASSANDRA_VERSION=$CCM_CASSANDRA_VERSION MAPPED_CASSANDRA_VERSION=$MAPPED_CASSANDRA_VERSION VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=standard_results.xml tests/integration/standard/ || true + + if [ -n "$DSE_VERSION" ] && ! [[ $DSE_VERSION == "4.8"* ]]; then + echo "==========RUNNING DSE INTEGRATION TESTS==========" + EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CASSANDRA_DIR=$CCM_INSTALL_DIR DSE_VERSION=$DSE_VERSION ADS_HOME=$HOME/ VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=dse_results.xml tests/integration/advanced/ || true + fi - echo "==========RUNNING ADVANCED AND CLOUD TESTS==========" - EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CLOUD_PROXY_PATH="$HOME/proxy/" CASSANDRA_VERSION=$CCM_CASSANDRA_VERSION MAPPED_CASSANDRA_VERSION=$MAPPED_CASSANDRA_VERSION VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=advanced_results.xml tests/integration/advanced/ || true + echo "==========RUNNING CLOUD TESTS==========" + EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CLOUD_PROXY_PATH="$HOME/proxy/" CASSANDRA_VERSION=$CCM_CASSANDRA_VERSION MAPPED_CASSANDRA_VERSION=$MAPPED_CASSANDRA_VERSION VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --with-ignore-docstrings --with-xunit --xunit-file=advanced_results.xml tests/integration/cloud/ || true if [ -z "$EXCLUDE_LONG" ]; then echo "==========RUNNING LONG INTEGRATION TESTS==========" - EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CCM_ARGS="$CCM_ARGS" CASSANDRA_VERSION=$CCM_CASSANDRA_VERSION MAPPED_CASSANDRA_VERSION=$MAPPED_CASSANDRA_VERSION VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --exclude-dir=tests/integration/long/upgrade --with-ignore-docstrings --with-xunit --xunit-file=long_results.xml tests/integration/long/ || true + EVENT_LOOP_MANAGER=$EVENT_LOOP_MANAGER CCM_ARGS="$CCM_ARGS" DSE_VERSION=$DSE_VERSION CASSANDRA_VERSION=$CCM_CASSANDRA_VERSION MAPPED_CASSANDRA_VERSION=$MAPPED_CASSANDRA_VERSION VERIFY_CYTHON=$FORCE_CYTHON nosetests -s -v --logging-format="[%(levelname)s] %(asctime)s %(thread)d: %(message)s" --exclude-dir=tests/integration/long/upgrade --with-ignore-docstrings --with-xunit --xunit-file=long_results.xml tests/integration/long/ || true fi - xunit: - "*_results.xml" diff --git a/cassandra/__init__.py b/cassandra/__init__.py index 38aef2f..5739d5d 100644 --- a/cassandra/__init__.py +++ b/cassandra/__init__.py @@ -1,703 +1,730 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger('cassandra').addHandler(NullHandler()) -__version_info__ = (3, 20, 2) +__version_info__ = (3, 25, 0) __version__ = '.'.join(map(str, __version_info__)) class ConsistencyLevel(object): """ Spcifies how many replicas must respond for an operation to be considered a success. By default, ``ONE`` is used for all operations. """ ANY = 0 """ Only requires that one replica receives the write *or* the coordinator stores a hint to replay later. Valid only for writes. """ ONE = 1 """ Only one replica needs to respond to consider the operation a success """ TWO = 2 """ Two replicas must respond to consider the operation a success """ THREE = 3 """ Three replicas must respond to consider the operation a success """ QUORUM = 4 """ ``ceil(RF/2)`` replicas must respond to consider the operation a success """ ALL = 5 """ All replicas must respond to consider the operation a success """ LOCAL_QUORUM = 6 """ Requires a quorum of replicas in the local datacenter """ EACH_QUORUM = 7 """ Requires a quorum of replicas in each datacenter """ SERIAL = 8 """ For conditional inserts/updates that utilize Cassandra's lightweight transactions, this requires consensus among all replicas for the modified data. """ LOCAL_SERIAL = 9 """ Like :attr:`~ConsistencyLevel.SERIAL`, but only requires consensus among replicas in the local datacenter. """ LOCAL_ONE = 10 """ Sends a request only to replicas in the local datacenter and waits for one response. """ @staticmethod def is_serial(cl): return cl == ConsistencyLevel.SERIAL or cl == ConsistencyLevel.LOCAL_SERIAL ConsistencyLevel.value_to_name = { ConsistencyLevel.ANY: 'ANY', ConsistencyLevel.ONE: 'ONE', ConsistencyLevel.TWO: 'TWO', ConsistencyLevel.THREE: 'THREE', ConsistencyLevel.QUORUM: 'QUORUM', ConsistencyLevel.ALL: 'ALL', ConsistencyLevel.LOCAL_QUORUM: 'LOCAL_QUORUM', ConsistencyLevel.EACH_QUORUM: 'EACH_QUORUM', ConsistencyLevel.SERIAL: 'SERIAL', ConsistencyLevel.LOCAL_SERIAL: 'LOCAL_SERIAL', ConsistencyLevel.LOCAL_ONE: 'LOCAL_ONE' } ConsistencyLevel.name_to_value = { 'ANY': ConsistencyLevel.ANY, 'ONE': ConsistencyLevel.ONE, 'TWO': ConsistencyLevel.TWO, 'THREE': ConsistencyLevel.THREE, 'QUORUM': ConsistencyLevel.QUORUM, 'ALL': ConsistencyLevel.ALL, 'LOCAL_QUORUM': ConsistencyLevel.LOCAL_QUORUM, 'EACH_QUORUM': ConsistencyLevel.EACH_QUORUM, 'SERIAL': ConsistencyLevel.SERIAL, 'LOCAL_SERIAL': ConsistencyLevel.LOCAL_SERIAL, 'LOCAL_ONE': ConsistencyLevel.LOCAL_ONE } def consistency_value_to_name(value): return ConsistencyLevel.value_to_name[value] if value is not None else "Not Set" class ProtocolVersion(object): """ Defines native protocol versions supported by this driver. """ V1 = 1 """ v1, supported in Cassandra 1.2-->2.2 """ V2 = 2 """ v2, supported in Cassandra 2.0-->2.2; added support for lightweight transactions, batch operations, and automatic query paging. """ V3 = 3 """ v3, supported in Cassandra 2.1-->3.x+; added support for protocol-level client-side timestamps (see :attr:`.Session.use_client_timestamp`), serial consistency levels for :class:`~.BatchStatement`, and an improved connection pool. """ V4 = 4 """ v4, supported in Cassandra 2.2-->3.x+; added a number of new types, server warnings, new failure messages, and custom payloads. Details in the `project docs `_ """ V5 = 5 """ - v5, in beta from 3.x+ + v5, in beta from 3.x+. Finalised in 4.0-beta5 """ - SUPPORTED_VERSIONS = (V5, V4, V3, V2, V1) + V6 = 6 + """ + v6, in beta from 4.0-beta5 + """ + + DSE_V1 = 0x41 + """ + DSE private protocol v1, supported in DSE 5.1+ + """ + + DSE_V2 = 0x42 + """ + DSE private protocol v2, supported in DSE 6.0+ + """ + + SUPPORTED_VERSIONS = (DSE_V2, DSE_V1, V6, V5, V4, V3, V2, V1) """ A tuple of all supported protocol versions """ - BETA_VERSIONS = (V5,) + BETA_VERSIONS = (V6,) """ A tuple of all beta protocol versions """ MIN_SUPPORTED = min(SUPPORTED_VERSIONS) """ Minimum protocol version supported by this driver. """ MAX_SUPPORTED = max(SUPPORTED_VERSIONS) """ - Maximum protocol versioni supported by this driver. + Maximum protocol version supported by this driver. """ @classmethod def get_lower_supported(cls, previous_version): """ Return the lower supported protocol version. Beta versions are omitted. """ try: version = next(v for v in sorted(ProtocolVersion.SUPPORTED_VERSIONS, reverse=True) if v not in ProtocolVersion.BETA_VERSIONS and v < previous_version) except StopIteration: version = 0 return version @classmethod def uses_int_query_flags(cls, version): return version >= cls.V5 @classmethod def uses_prepare_flags(cls, version): - return version >= cls.V5 + return version >= cls.V5 and version != cls.DSE_V1 @classmethod def uses_prepared_metadata(cls, version): - return version >= cls.V5 + return version >= cls.V5 and version != cls.DSE_V1 @classmethod def uses_error_code_map(cls, version): return version >= cls.V5 @classmethod def uses_keyspace_flag(cls, version): - return version >= cls.V5 + return version >= cls.V5 and version != cls.DSE_V1 + + @classmethod + def has_continuous_paging_support(cls, version): + return version >= cls.DSE_V1 + + @classmethod + def has_continuous_paging_next_pages(cls, version): + return version >= cls.DSE_V2 + + @classmethod + def has_checksumming_support(cls, version): + return cls.V5 <= version < cls.DSE_V1 class WriteType(object): """ For usage with :class:`.RetryPolicy`, this describe a type of write operation. """ SIMPLE = 0 """ A write to a single partition key. Such writes are guaranteed to be atomic and isolated. """ BATCH = 1 """ A write to multiple partition keys that used the distributed batch log to ensure atomicity. """ UNLOGGED_BATCH = 2 """ A write to multiple partition keys that did not use the distributed batch log. Atomicity for such writes is not guaranteed. """ COUNTER = 3 """ A counter write (for one or multiple partition keys). Such writes should not be replayed in order to avoid overcount. """ BATCH_LOG = 4 """ The initial write to the distributed batch log that Cassandra performs internally before a BATCH write. """ CAS = 5 """ A lighweight-transaction write, such as "DELETE ... IF EXISTS". """ VIEW = 6 """ This WriteType is only seen in results for requests that were unable to complete MV operations. """ CDC = 7 """ This WriteType is only seen in results for requests that were unable to complete CDC operations. """ WriteType.name_to_value = { 'SIMPLE': WriteType.SIMPLE, 'BATCH': WriteType.BATCH, 'UNLOGGED_BATCH': WriteType.UNLOGGED_BATCH, 'COUNTER': WriteType.COUNTER, 'BATCH_LOG': WriteType.BATCH_LOG, 'CAS': WriteType.CAS, 'VIEW': WriteType.VIEW, 'CDC': WriteType.CDC } WriteType.value_to_name = {v: k for k, v in WriteType.name_to_value.items()} class SchemaChangeType(object): DROPPED = 'DROPPED' CREATED = 'CREATED' UPDATED = 'UPDATED' class SchemaTargetType(object): KEYSPACE = 'KEYSPACE' TABLE = 'TABLE' TYPE = 'TYPE' FUNCTION = 'FUNCTION' AGGREGATE = 'AGGREGATE' class SignatureDescriptor(object): def __init__(self, name, argument_types): self.name = name self.argument_types = argument_types @property def signature(self): """ function signature string in the form 'name([type0[,type1[...]]])' can be used to uniquely identify overloaded function names within a keyspace """ return self.format_signature(self.name, self.argument_types) @staticmethod def format_signature(name, argument_types): return "%s(%s)" % (name, ','.join(t for t in argument_types)) def __repr__(self): return "%s(%s, %s)" % (self.__class__.__name__, self.name, self.argument_types) class UserFunctionDescriptor(SignatureDescriptor): """ Describes a User function by name and argument signature """ name = None """ name of the function """ argument_types = None """ Ordered list of CQL argument type names comprising the type signature """ class UserAggregateDescriptor(SignatureDescriptor): """ Describes a User aggregate function by name and argument signature """ name = None """ name of the aggregate """ argument_types = None """ Ordered list of CQL argument type names comprising the type signature """ class DriverException(Exception): """ Base for all exceptions explicitly raised by the driver. """ pass class RequestExecutionException(DriverException): """ Base for request execution exceptions returned from the server. """ pass class Unavailable(RequestExecutionException): """ There were not enough live replicas to satisfy the requested consistency level, so the coordinator node immediately failed the request without forwarding it to any replicas. """ consistency = None """ The requested :class:`ConsistencyLevel` """ required_replicas = None """ The number of replicas that needed to be live to complete the operation """ alive_replicas = None """ The number of replicas that were actually alive """ def __init__(self, summary_message, consistency=None, required_replicas=None, alive_replicas=None): self.consistency = consistency self.required_replicas = required_replicas self.alive_replicas = alive_replicas Exception.__init__(self, summary_message + ' info=' + repr({'consistency': consistency_value_to_name(consistency), 'required_replicas': required_replicas, 'alive_replicas': alive_replicas})) class Timeout(RequestExecutionException): """ Replicas failed to respond to the coordinator node before timing out. """ consistency = None """ The requested :class:`ConsistencyLevel` """ required_responses = None """ The number of required replica responses """ received_responses = None """ The number of replicas that responded before the coordinator timed out the operation """ def __init__(self, summary_message, consistency=None, required_responses=None, received_responses=None, **kwargs): self.consistency = consistency self.required_responses = required_responses self.received_responses = received_responses if "write_type" in kwargs: kwargs["write_type"] = WriteType.value_to_name[kwargs["write_type"]] info = {'consistency': consistency_value_to_name(consistency), 'required_responses': required_responses, 'received_responses': received_responses} info.update(kwargs) Exception.__init__(self, summary_message + ' info=' + repr(info)) class ReadTimeout(Timeout): """ A subclass of :exc:`Timeout` for read operations. This indicates that the replicas failed to respond to the coordinator node before the configured timeout. This timeout is configured in ``cassandra.yaml`` with the ``read_request_timeout_in_ms`` and ``range_request_timeout_in_ms`` options. """ data_retrieved = None """ A boolean indicating whether the requested data was retrieved by the coordinator from any replicas before it timed out the operation """ def __init__(self, message, data_retrieved=None, **kwargs): Timeout.__init__(self, message, **kwargs) self.data_retrieved = data_retrieved class WriteTimeout(Timeout): """ A subclass of :exc:`Timeout` for write operations. This indicates that the replicas failed to respond to the coordinator node before the configured timeout. This timeout is configured in ``cassandra.yaml`` with the ``write_request_timeout_in_ms`` option. """ write_type = None """ The type of write operation, enum on :class:`~cassandra.policies.WriteType` """ def __init__(self, message, write_type=None, **kwargs): kwargs["write_type"] = write_type Timeout.__init__(self, message, **kwargs) self.write_type = write_type class CDCWriteFailure(RequestExecutionException): """ Hit limit on data in CDC folder, writes are rejected """ def __init__(self, message): Exception.__init__(self, message) class CoordinationFailure(RequestExecutionException): """ Replicas sent a failure to the coordinator. """ consistency = None """ The requested :class:`ConsistencyLevel` """ required_responses = None """ The number of required replica responses """ received_responses = None """ The number of replicas that responded before the coordinator timed out the operation """ failures = None """ The number of replicas that sent a failure message """ error_code_map = None """ A map of inet addresses to error codes representing replicas that sent a failure message. Only set when `protocol_version` is 5 or higher. """ def __init__(self, summary_message, consistency=None, required_responses=None, received_responses=None, failures=None, error_code_map=None): self.consistency = consistency self.required_responses = required_responses self.received_responses = received_responses self.failures = failures self.error_code_map = error_code_map info_dict = { 'consistency': consistency_value_to_name(consistency), 'required_responses': required_responses, 'received_responses': received_responses, 'failures': failures } if error_code_map is not None: # make error codes look like "0x002a" formatted_map = dict((addr, '0x%04x' % err_code) for (addr, err_code) in error_code_map.items()) info_dict['error_code_map'] = formatted_map Exception.__init__(self, summary_message + ' info=' + repr(info_dict)) class ReadFailure(CoordinationFailure): """ A subclass of :exc:`CoordinationFailure` for read operations. This indicates that the replicas sent a failure message to the coordinator. """ data_retrieved = None """ A boolean indicating whether the requested data was retrieved by the coordinator from any replicas before it timed out the operation """ def __init__(self, message, data_retrieved=None, **kwargs): CoordinationFailure.__init__(self, message, **kwargs) self.data_retrieved = data_retrieved class WriteFailure(CoordinationFailure): """ A subclass of :exc:`CoordinationFailure` for write operations. This indicates that the replicas sent a failure message to the coordinator. """ write_type = None """ The type of write operation, enum on :class:`~cassandra.policies.WriteType` """ def __init__(self, message, write_type=None, **kwargs): CoordinationFailure.__init__(self, message, **kwargs) self.write_type = write_type class FunctionFailure(RequestExecutionException): """ User Defined Function failed during execution """ keyspace = None """ Keyspace of the function """ function = None """ Name of the function """ arg_types = None """ List of argument type names of the function """ def __init__(self, summary_message, keyspace, function, arg_types): self.keyspace = keyspace self.function = function self.arg_types = arg_types Exception.__init__(self, summary_message) class RequestValidationException(DriverException): """ Server request validation failed """ pass class ConfigurationException(RequestValidationException): """ Server indicated request errro due to current configuration """ pass class AlreadyExists(ConfigurationException): """ An attempt was made to create a keyspace or table that already exists. """ keyspace = None """ The name of the keyspace that already exists, or, if an attempt was made to create a new table, the keyspace that the table is in. """ table = None """ The name of the table that already exists, or, if an attempt was make to create a keyspace, :const:`None`. """ def __init__(self, keyspace=None, table=None): if table: message = "Table '%s.%s' already exists" % (keyspace, table) else: message = "Keyspace '%s' already exists" % (keyspace,) Exception.__init__(self, message) self.keyspace = keyspace self.table = table class InvalidRequest(RequestValidationException): """ A query was made that was invalid for some reason, such as trying to set the keyspace for a connection to a nonexistent keyspace. """ pass class Unauthorized(RequestValidationException): """ The current user is not authorized to perform the requested operation. """ pass class AuthenticationFailed(DriverException): """ Failed to authenticate. """ pass class OperationTimedOut(DriverException): """ The operation took longer than the specified (client-side) timeout to complete. This is not an error generated by Cassandra, only the driver. """ errors = None """ A dict of errors keyed by the :class:`~.Host` against which they occurred. """ last_host = None """ The last :class:`~.Host` this operation was attempted against. """ def __init__(self, errors=None, last_host=None): self.errors = errors self.last_host = last_host message = "errors=%s, last_host=%s" % (self.errors, self.last_host) Exception.__init__(self, message) class UnsupportedOperation(DriverException): """ An attempt was made to use a feature that is not supported by the selected protocol version. See :attr:`Cluster.protocol_version` for more details. """ pass class UnresolvableContactPoints(DriverException): """ The driver was unable to resolve any provided hostnames. Note that this is *not* raised when a :class:`.Cluster` is created with no contact points, only when lookup fails for all hosts """ pass diff --git a/cassandra/auth.py b/cassandra/auth.py index 1d94817..3d2f751 100644 --- a/cassandra/auth.py +++ b/cassandra/auth.py @@ -1,182 +1,309 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and +# limitations under the License. + +import socket +import logging + +try: + import kerberos + _have_kerberos = True +except ImportError: + _have_kerberos = False + +try: + from puresasl.client import SASLClient + _have_puresasl = True +except ImportError: + _have_puresasl = False + try: from puresasl.client import SASLClient except ImportError: SASLClient = None +import six + +log = logging.getLogger(__name__) + +# Custom payload keys related to DSE Unified Auth +_proxy_execute_key = 'ProxyExecute' + + class AuthProvider(object): """ An abstract class that defines the interface that will be used for creating :class:`~.Authenticator` instances when opening new connections to Cassandra. .. versionadded:: 2.0.0 """ def new_authenticator(self, host): """ Implementations of this class should return a new instance of :class:`~.Authenticator` or one of its subclasses. """ raise NotImplementedError() class Authenticator(object): """ An abstract class that handles SASL authentication with Cassandra servers. Each time a new connection is created and the server requires authentication, a new instance of this class will be created by the corresponding :class:`~.AuthProvider` to handler that authentication. The lifecycle of the new :class:`~.Authenticator` will the be: 1) The :meth:`~.initial_response()` method will be called. The return value will be sent to the server to initiate the handshake. 2) The server will respond to each client response by either issuing a challenge or indicating that the authentication is complete (successful or not). If a new challenge is issued, :meth:`~.evaluate_challenge()` will be called to produce a response that will be sent to the server. This challenge/response negotiation will continue until the server responds that authentication is successful (or an :exc:`~.AuthenticationFailed` is raised). 3) When the server indicates that authentication is successful, :meth:`~.on_authentication_success` will be called a token string that that the server may optionally have sent. The exact nature of the negotiation between the client and server is specific to the authentication mechanism configured server-side. .. versionadded:: 2.0.0 """ server_authenticator_class = None """ Set during the connection AUTHENTICATE phase """ def initial_response(self): """ Returns an message to send to the server to initiate the SASL handshake. :const:`None` may be returned to send an empty message. """ return None def evaluate_challenge(self, challenge): """ Called when the server sends a challenge message. Generally, this method should return :const:`None` when authentication is complete from a client perspective. Otherwise, a string should be returned. """ raise NotImplementedError() def on_authentication_success(self, token): """ Called when the server indicates that authentication was successful. Depending on the authentication mechanism, `token` may be :const:`None` or a string. """ pass class PlainTextAuthProvider(AuthProvider): """ An :class:`~.AuthProvider` that works with Cassandra's PasswordAuthenticator. Example usage:: from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider auth_provider = PlainTextAuthProvider( username='cassandra', password='cassandra') cluster = Cluster(auth_provider=auth_provider) .. versionadded:: 2.0.0 """ def __init__(self, username, password): self.username = username self.password = password def new_authenticator(self, host): return PlainTextAuthenticator(self.username, self.password) -class PlainTextAuthenticator(Authenticator): +class TransitionalModePlainTextAuthProvider(object): """ - An :class:`~.Authenticator` that works with Cassandra's PasswordAuthenticator. + An :class:`~.AuthProvider` that works with DSE TransitionalModePlainTextAuthenticator. - .. versionadded:: 2.0.0 - """ + Example usage:: - def __init__(self, username, password): - self.username = username - self.password = password + from cassandra.cluster import Cluster + from cassandra.auth import TransitionalModePlainTextAuthProvider - def initial_response(self): - return "\x00%s\x00%s" % (self.username, self.password) + auth_provider = TransitionalModePlainTextAuthProvider() + cluster = Cluster(auth_provider=auth_provider) - def evaluate_challenge(self, challenge): - return None + .. warning:: TransitionalModePlainTextAuthProvider will be removed in cassandra-driver + 4.0. The transitional mode will be handled internally without the need + of any auth provider. + """ + + def __init__(self): + # TODO remove next major + log.warning("TransitionalModePlainTextAuthProvider will be removed in cassandra-driver " + "4.0. The transitional mode will be handled internally without the need " + "of any auth provider.") + + def new_authenticator(self, host): + return TransitionalModePlainTextAuthenticator() class SaslAuthProvider(AuthProvider): """ An :class:`~.AuthProvider` supporting general SASL auth mechanisms Suitable for GSSAPI or other SASL mechanisms Example usage:: from cassandra.cluster import Cluster from cassandra.auth import SaslAuthProvider sasl_kwargs = {'service': 'something', 'mechanism': 'GSSAPI', 'qops': 'auth'.split(',')} auth_provider = SaslAuthProvider(**sasl_kwargs) cluster = Cluster(auth_provider=auth_provider) .. versionadded:: 2.1.4 """ def __init__(self, **sasl_kwargs): if SASLClient is None: raise ImportError('The puresasl library has not been installed') if 'host' in sasl_kwargs: raise ValueError("kwargs should not contain 'host' since it is passed dynamically to new_authenticator") self.sasl_kwargs = sasl_kwargs def new_authenticator(self, host): return SaslAuthenticator(host, **self.sasl_kwargs) class SaslAuthenticator(Authenticator): """ A pass-through :class:`~.Authenticator` using the third party package 'pure-sasl' for authentication .. versionadded:: 2.1.4 """ def __init__(self, host, service, mechanism='GSSAPI', **sasl_kwargs): if SASLClient is None: raise ImportError('The puresasl library has not been installed') self.sasl = SASLClient(host, service, mechanism, **sasl_kwargs) def initial_response(self): return self.sasl.process() def evaluate_challenge(self, challenge): return self.sasl.process(challenge) + +# TODO remove me next major +DSEPlainTextAuthProvider = PlainTextAuthProvider + + +class DSEGSSAPIAuthProvider(AuthProvider): + """ + Auth provider for GSS API authentication. Works with legacy `KerberosAuthenticator` + or `DseAuthenticator` if `kerberos` scheme is enabled. + """ + def __init__(self, service='dse', qops=('auth',), resolve_host_name=True, **properties): + """ + :param service: name of the service + :param qops: iterable of "Quality of Protection" allowed; see ``puresasl.QOP`` + :param resolve_host_name: boolean flag indicating whether the authenticator should reverse-lookup an FQDN when + creating a new authenticator. Default is ``True``, which will resolve, or return the numeric address if there is no PTR + record. Setting ``False`` creates the authenticator with the numeric address known by Cassandra + :param properties: additional keyword properties to pass for the ``puresasl.mechanisms.GSSAPIMechanism`` class. + Presently, 'principal' (user) is the only one referenced in the ``pure-sasl`` implementation + """ + if not _have_puresasl: + raise ImportError('The puresasl library has not been installed') + if not _have_kerberos: + raise ImportError('The kerberos library has not been installed') + self.service = service + self.qops = qops + self.resolve_host_name = resolve_host_name + self.properties = properties + + def new_authenticator(self, host): + if self.resolve_host_name: + host = socket.getnameinfo((host, 0), 0)[0] + return GSSAPIAuthenticator(host, self.service, self.qops, self.properties) + + +class BaseDSEAuthenticator(Authenticator): + def get_mechanism(self): + raise NotImplementedError("get_mechanism not implemented") + + def get_initial_challenge(self): + raise NotImplementedError("get_initial_challenge not implemented") + + def initial_response(self): + if self.server_authenticator_class == "com.datastax.bdp.cassandra.auth.DseAuthenticator": + return self.get_mechanism() + else: + return self.evaluate_challenge(self.get_initial_challenge()) + + +class PlainTextAuthenticator(BaseDSEAuthenticator): + + def __init__(self, username, password): + self.username = username + self.password = password + + def get_mechanism(self): + return six.b("PLAIN") + + def get_initial_challenge(self): + return six.b("PLAIN-START") + + def evaluate_challenge(self, challenge): + if challenge == six.b('PLAIN-START'): + data = "\x00%s\x00%s" % (self.username, self.password) + return data if six.PY2 else data.encode() + raise Exception('Did not receive a valid challenge response from server') + + +class TransitionalModePlainTextAuthenticator(PlainTextAuthenticator): + """ + Authenticator that accounts for DSE authentication is configured with transitional mode. + """ + + def __init__(self): + super(TransitionalModePlainTextAuthenticator, self).__init__('', '') + + +class GSSAPIAuthenticator(BaseDSEAuthenticator): + def __init__(self, host, service, qops, properties): + properties = properties or {} + self.sasl = SASLClient(host, service, 'GSSAPI', qops=qops, **properties) + + def get_mechanism(self): + return six.b("GSSAPI") + + def get_initial_challenge(self): + return six.b("GSSAPI-START") + + def evaluate_challenge(self, challenge): + if challenge == six.b('GSSAPI-START'): + return self.sasl.process() + else: + return self.sasl.process(challenge) diff --git a/cassandra/cluster.py b/cassandra/cluster.py index 8fcbe33..7e101af 100644 --- a/cassandra/cluster.py +++ b/cassandra/cluster.py @@ -1,4651 +1,5257 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This module houses the main classes you will interact with, :class:`.Cluster` and :class:`.Session`. """ from __future__ import absolute_import import atexit +from binascii import hexlify from collections import defaultdict from concurrent.futures import ThreadPoolExecutor, FIRST_COMPLETED, wait as wait_futures from copy import copy from functools import partial, wraps -from itertools import groupby, count +from itertools import groupby, count, chain +import json import logging from warnings import warn from random import random import six from six.moves import filter, range, queue as Queue import socket import sys import time from threading import Lock, RLock, Thread, Event +import uuid import weakref from weakref import WeakValueDictionary -try: - from weakref import WeakSet -except ImportError: - from cassandra.util import WeakSet # NOQA from cassandra import (ConsistencyLevel, AuthenticationFailed, OperationTimedOut, UnsupportedOperation, SchemaTargetType, DriverException, ProtocolVersion, UnresolvableContactPoints) -from cassandra.auth import PlainTextAuthProvider +from cassandra.auth import _proxy_execute_key, PlainTextAuthProvider from cassandra.connection import (ConnectionException, ConnectionShutdown, ConnectionHeartbeat, ProtocolVersionUnsupported, EndPoint, DefaultEndPoint, DefaultEndPointFactory, - SniEndPointFactory) + ContinuousPagingState, SniEndPointFactory, ConnectionBusy) from cassandra.cqltypes import UserType from cassandra.encoder import Encoder from cassandra.protocol import (QueryMessage, ResultMessage, ErrorMessage, ReadTimeoutErrorMessage, WriteTimeoutErrorMessage, UnavailableErrorMessage, OverloadedErrorMessage, PrepareMessage, ExecuteMessage, PreparedQueryNotFound, IsBootstrappingErrorMessage, TruncateError, ServerError, BatchMessage, RESULT_KIND_PREPARED, RESULT_KIND_SET_KEYSPACE, RESULT_KIND_ROWS, - RESULT_KIND_SCHEMA_CHANGE, ProtocolHandler) -from cassandra.metadata import Metadata, protect_name, murmur3 + RESULT_KIND_SCHEMA_CHANGE, ProtocolHandler, + RESULT_KIND_VOID, ProtocolException) +from cassandra.metadata import Metadata, protect_name, murmur3, _NodeInfo from cassandra.policies import (TokenAwarePolicy, DCAwareRoundRobinPolicy, SimpleConvictionPolicy, ExponentialReconnectionPolicy, HostDistance, RetryPolicy, IdentityTranslator, NoSpeculativeExecutionPlan, - NoSpeculativeExecutionPolicy) + NoSpeculativeExecutionPolicy, DefaultLoadBalancingPolicy, + NeverRetryPolicy) from cassandra.pool import (Host, _ReconnectionHandler, _HostReconnectionHandler, HostConnectionPool, HostConnection, NoConnectionsAvailable) from cassandra.query import (SimpleStatement, PreparedStatement, BoundStatement, BatchStatement, bind_params, QueryTrace, TraceUnavailable, - named_tuple_factory, dict_factory, tuple_factory, FETCH_SIZE_UNSET) + named_tuple_factory, dict_factory, tuple_factory, FETCH_SIZE_UNSET, + HostTargetingStatement) +from cassandra.marshal import int64_pack from cassandra.timestamps import MonotonicTimestampGenerator from cassandra.compat import Mapping +from cassandra.util import _resolve_contact_points_to_string_map, Version + +from cassandra.datastax.insights.reporter import MonitorReporter +from cassandra.datastax.insights.util import version_supports_insights + +from cassandra.datastax.graph import (graph_object_row_factory, GraphOptions, GraphSON1Serializer, + GraphProtocol, GraphSON2Serializer, GraphStatement, SimpleGraphStatement, + graph_graphson2_row_factory, graph_graphson3_row_factory, + GraphSON3Serializer) +from cassandra.datastax.graph.query import _request_timeout_key, _GraphSONContextRowFactory from cassandra.datastax import cloud as dscloud +try: + from cassandra.io.twistedreactor import TwistedConnection +except ImportError: + TwistedConnection = None + +try: + from cassandra.io.eventletreactor import EventletConnection +except ImportError: + EventletConnection = None + +try: + from weakref import WeakSet +except ImportError: + from cassandra.util import WeakSet # NOQA + +if six.PY3: + long = int def _is_eventlet_monkey_patched(): if 'eventlet.patcher' not in sys.modules: return False import eventlet.patcher return eventlet.patcher.is_monkey_patched('socket') def _is_gevent_monkey_patched(): if 'gevent.monkey' not in sys.modules: return False import gevent.socket return socket.socket is gevent.socket.socket # default to gevent when we are monkey patched with gevent, eventlet when # monkey patched with eventlet, otherwise if libev is available, use that as # the default because it's fastest. Otherwise, use asyncore. if _is_gevent_monkey_patched(): from cassandra.io.geventreactor import GeventConnection as DefaultConnection elif _is_eventlet_monkey_patched(): from cassandra.io.eventletreactor import EventletConnection as DefaultConnection else: try: from cassandra.io.libevreactor import LibevConnection as DefaultConnection # NOQA except ImportError: from cassandra.io.asyncorereactor import AsyncoreConnection as DefaultConnection # NOQA # Forces load of utf8 encoding module to avoid deadlock that occurs # if code that is being imported tries to import the module in a seperate # thread. # See http://bugs.python.org/issue10923 "".encode('utf8') log = logging.getLogger(__name__) DEFAULT_MIN_REQUESTS = 5 DEFAULT_MAX_REQUESTS = 100 DEFAULT_MIN_CONNECTIONS_PER_LOCAL_HOST = 2 DEFAULT_MAX_CONNECTIONS_PER_LOCAL_HOST = 8 DEFAULT_MIN_CONNECTIONS_PER_REMOTE_HOST = 1 DEFAULT_MAX_CONNECTIONS_PER_REMOTE_HOST = 2 +_GRAPH_PAGING_MIN_DSE_VERSION = Version('6.8.0') _NOT_SET = object() class NoHostAvailable(Exception): """ Raised when an operation is attempted but all connections are busy, defunct, closed, or resulted in errors when used. """ errors = None """ A map of the form ``{ip: exception}`` which details the particular Exception that was caught for each host the operation was attempted against. """ def __init__(self, message, errors): Exception.__init__(self, message, errors) self.errors = errors def _future_completed(future): """ Helper for run_in_executor() """ exc = future.exception() if exc: log.debug("Failed to run task on executor", exc_info=exc) def run_in_executor(f): """ A decorator to run the given method in the ThreadPoolExecutor. """ @wraps(f) def new_f(self, *args, **kwargs): if self.is_shutdown: return try: future = self.executor.submit(f, self, *args, **kwargs) future.add_done_callback(_future_completed) except Exception: log.exception("Failed to submit task to executor") return new_f _clusters_for_shutdown = set() def _register_cluster_shutdown(cluster): _clusters_for_shutdown.add(cluster) def _discard_cluster_shutdown(cluster): _clusters_for_shutdown.discard(cluster) def _shutdown_clusters(): clusters = _clusters_for_shutdown.copy() # copy because shutdown modifies the global set "discard" for cluster in clusters: cluster.shutdown() atexit.register(_shutdown_clusters) def default_lbp_factory(): if murmur3 is not None: return TokenAwarePolicy(DCAwareRoundRobinPolicy()) return DCAwareRoundRobinPolicy() +class ContinuousPagingOptions(object): + + class PagingUnit(object): + BYTES = 1 + ROWS = 2 + + page_unit = None + """ + Value of PagingUnit. Default is PagingUnit.ROWS. + + Units refer to the :attr:`~.Statement.fetch_size` or :attr:`~.Session.default_fetch_size`. + """ + + max_pages = None + """ + Max number of pages to send + """ + + max_pages_per_second = None + """ + Max rate at which to send pages + """ + + max_queue_size = None + """ + The maximum queue size for caching pages, only honored for protocol version DSE_V2 and higher, + by default it is 4 and it must be at least 2. + """ + + def __init__(self, page_unit=PagingUnit.ROWS, max_pages=0, max_pages_per_second=0, max_queue_size=4): + self.page_unit = page_unit + self.max_pages = max_pages + self.max_pages_per_second = max_pages_per_second + if max_queue_size < 2: + raise ValueError('ContinuousPagingOptions.max_queue_size must be 2 or greater') + self.max_queue_size = max_queue_size + + def page_unit_bytes(self): + return self.page_unit == ContinuousPagingOptions.PagingUnit.BYTES + + def _addrinfo_or_none(contact_point, port): """ A helper function that wraps socket.getaddrinfo and returns None when it fails to, e.g. resolve one of the hostnames. Used to address PYTHON-895. """ try: return socket.getaddrinfo(contact_point, port, socket.AF_UNSPEC, socket.SOCK_STREAM) except socket.gaierror: log.debug('Could not resolve hostname "{}" ' 'with port {}'.format(contact_point, port)) return None -def _resolve_contact_points(contact_points, port): - resolved = tuple(_addrinfo_or_none(p, port) - for p in contact_points) - - if resolved and all((x is None for x in resolved)): - raise UnresolvableContactPoints(contact_points, port) - - resolved = tuple(r for r in resolved if r is not None) - - return [endpoint[4][0] - for addrinfo in resolved - for endpoint in addrinfo] +def _execution_profile_to_string(name): + default_profiles = { + EXEC_PROFILE_DEFAULT: 'EXEC_PROFILE_DEFAULT', + EXEC_PROFILE_GRAPH_DEFAULT: 'EXEC_PROFILE_GRAPH_DEFAULT', + EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT: 'EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT', + EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT: 'EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT', + } + if name in default_profiles: + return default_profiles[name] -def _execution_profile_to_string(name): - if name is EXEC_PROFILE_DEFAULT: - return 'EXEC_PROFILE_DEFAULT' return '"%s"' % (name,) class ExecutionProfile(object): load_balancing_policy = None """ An instance of :class:`.policies.LoadBalancingPolicy` or one of its subclasses. Used in determining host distance for establishing connections, and routing requests. Defaults to ``TokenAwarePolicy(DCAwareRoundRobinPolicy())`` if not specified """ retry_policy = None """ An instance of :class:`.policies.RetryPolicy` instance used when :class:`.Statement` objects do not have a :attr:`~.Statement.retry_policy` explicitly set. Defaults to :class:`.RetryPolicy` if not specified """ consistency_level = ConsistencyLevel.LOCAL_ONE """ :class:`.ConsistencyLevel` used when not specified on a :class:`.Statement`. """ serial_consistency_level = None """ Serial :class:`.ConsistencyLevel` used when not specified on a :class:`.Statement` (for LWT conditional statements). """ request_timeout = 10.0 """ Request timeout used when not overridden in :meth:`.Session.execute` """ row_factory = staticmethod(named_tuple_factory) """ A callable to format results, accepting ``(colnames, rows)`` where ``colnames`` is a list of column names, and ``rows`` is a list of tuples, with each tuple representing a row of parsed values. Some example implementations: - :func:`cassandra.query.tuple_factory` - return a result row as a tuple - :func:`cassandra.query.named_tuple_factory` - return a result row as a named tuple - :func:`cassandra.query.dict_factory` - return a result row as a dict - :func:`cassandra.query.ordered_dict_factory` - return a result row as an OrderedDict """ speculative_execution_policy = None """ An instance of :class:`.policies.SpeculativeExecutionPolicy` Defaults to :class:`.NoSpeculativeExecutionPolicy` if not specified """ - # indicates if set explicitly or uses default values + continuous_paging_options = None + """ + *Note:* This feature is implemented to facilitate server integration testing. It is not intended for general use in the Python driver. + See :attr:`.Statement.fetch_size` or :attr:`Session.default_fetch_size` for configuring normal paging. + + When set, requests will use DSE's continuous paging, which streams multiple pages without + intermediate requests. + + This has the potential to materialize all results in memory at once if the consumer cannot keep up. Use options + to constrain page size and rate. + + This is only available for DSE clusters. + """ + + # indicates if lbp was set explicitly or uses default values _load_balancing_policy_explicit = False _consistency_level_explicit = False def __init__(self, load_balancing_policy=_NOT_SET, retry_policy=None, consistency_level=_NOT_SET, serial_consistency_level=None, - request_timeout=10.0, row_factory=named_tuple_factory, speculative_execution_policy=None): + request_timeout=10.0, row_factory=named_tuple_factory, speculative_execution_policy=None, + continuous_paging_options=None): if load_balancing_policy is _NOT_SET: self._load_balancing_policy_explicit = False self.load_balancing_policy = default_lbp_factory() else: self._load_balancing_policy_explicit = True self.load_balancing_policy = load_balancing_policy if consistency_level is _NOT_SET: self._consistency_level_explicit = False self.consistency_level = ConsistencyLevel.LOCAL_ONE else: self._consistency_level_explicit = True self.consistency_level = consistency_level self.retry_policy = retry_policy or RetryPolicy() if (serial_consistency_level is not None and not ConsistencyLevel.is_serial(serial_consistency_level)): raise ValueError("serial_consistency_level must be either " "ConsistencyLevel.SERIAL " "or ConsistencyLevel.LOCAL_SERIAL.") self.serial_consistency_level = serial_consistency_level self.request_timeout = request_timeout self.row_factory = row_factory self.speculative_execution_policy = speculative_execution_policy or NoSpeculativeExecutionPolicy() + self.continuous_paging_options = continuous_paging_options + + +class GraphExecutionProfile(ExecutionProfile): + graph_options = None + """ + :class:`.GraphOptions` to use with this execution + + Default options for graph queries, initialized as follows by default:: + + GraphOptions(graph_language=b'gremlin-groovy') + + See cassandra.graph.GraphOptions + """ + + def __init__(self, load_balancing_policy=_NOT_SET, retry_policy=None, + consistency_level=_NOT_SET, serial_consistency_level=None, + request_timeout=30.0, row_factory=None, + graph_options=None, continuous_paging_options=_NOT_SET): + """ + Default execution profile for graph execution. + + See :class:`.ExecutionProfile` for base attributes. Note that if not explicitly set, + the row_factory and graph_options.graph_protocol are resolved during the query execution. + These options will resolve to graph_graphson3_row_factory and GraphProtocol.GRAPHSON_3_0 + for the core graph engine (DSE 6.8+), otherwise graph_object_row_factory and GraphProtocol.GRAPHSON_1_0 + + In addition to default parameters shown in the signature, this profile also defaults ``retry_policy`` to + :class:`cassandra.policies.NeverRetryPolicy`. + """ + retry_policy = retry_policy or NeverRetryPolicy() + super(GraphExecutionProfile, self).__init__(load_balancing_policy, retry_policy, consistency_level, + serial_consistency_level, request_timeout, row_factory, + continuous_paging_options=continuous_paging_options) + self.graph_options = graph_options or GraphOptions(graph_source=b'g', + graph_language=b'gremlin-groovy') + + +class GraphAnalyticsExecutionProfile(GraphExecutionProfile): + + def __init__(self, load_balancing_policy=None, retry_policy=None, + consistency_level=_NOT_SET, serial_consistency_level=None, + request_timeout=3600. * 24. * 7., row_factory=None, + graph_options=None): + """ + Execution profile with timeout and load balancing appropriate for graph analytics queries. + + See also :class:`~.GraphExecutionPolicy`. + + In addition to default parameters shown in the signature, this profile also defaults ``retry_policy`` to + :class:`cassandra.policies.NeverRetryPolicy`, and ``load_balancing_policy`` to one that targets the current Spark + master. + + Note: The graph_options.graph_source is set automatically to b'a' (analytics) + when using GraphAnalyticsExecutionProfile. This is mandatory to target analytics nodes. + """ + load_balancing_policy = load_balancing_policy or DefaultLoadBalancingPolicy(default_lbp_factory()) + graph_options = graph_options or GraphOptions(graph_language=b'gremlin-groovy') + super(GraphAnalyticsExecutionProfile, self).__init__(load_balancing_policy, retry_policy, consistency_level, + serial_consistency_level, request_timeout, row_factory, + graph_options) + # ensure the graph_source is analytics, since this is the purpose of the GraphAnalyticsExecutionProfile + self.graph_options.set_source_analytics() class ProfileManager(object): def __init__(self): self.profiles = dict() def _profiles_without_explicit_lbps(self): names = (profile_name for profile_name, profile in self.profiles.items() if not profile._load_balancing_policy_explicit) return tuple( 'EXEC_PROFILE_DEFAULT' if n is EXEC_PROFILE_DEFAULT else n for n in names ) def distance(self, host): distances = set(p.load_balancing_policy.distance(host) for p in self.profiles.values()) return HostDistance.LOCAL if HostDistance.LOCAL in distances else \ HostDistance.REMOTE if HostDistance.REMOTE in distances else \ HostDistance.IGNORED def populate(self, cluster, hosts): for p in self.profiles.values(): p.load_balancing_policy.populate(cluster, hosts) def check_supported(self): for p in self.profiles.values(): p.load_balancing_policy.check_supported() def on_up(self, host): for p in self.profiles.values(): p.load_balancing_policy.on_up(host) def on_down(self, host): for p in self.profiles.values(): p.load_balancing_policy.on_down(host) def on_add(self, host): for p in self.profiles.values(): p.load_balancing_policy.on_add(host) def on_remove(self, host): for p in self.profiles.values(): p.load_balancing_policy.on_remove(host) @property def default(self): """ internal-only; no checks are done because this entry is populated on cluster init """ return self.profiles[EXEC_PROFILE_DEFAULT] EXEC_PROFILE_DEFAULT = object() """ Key for the ``Cluster`` default execution profile, used when no other profile is selected in ``Session.execute(execution_profile)``. Use this as the key in ``Cluster(execution_profiles)`` to override the default profile. """ +EXEC_PROFILE_GRAPH_DEFAULT = object() +""" +Key for the default graph execution profile, used when no other profile is selected in +``Session.execute_graph(execution_profile)``. + +Use this as the key in :doc:`Cluster(execution_profiles) ` +to override the default graph profile. +""" + +EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT = object() +""" +Key for the default graph system execution profile. This can be used for graph statements using the DSE graph +system API. + +Selected using ``Session.execute_graph(execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT)``. +""" + +EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT = object() +""" +Key for the default graph analytics execution profile. This can be used for graph statements intended to +use Spark/analytics as the traversal source. + +Selected using ``Session.execute_graph(execution_profile=EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT)``. +""" + class _ConfigMode(object): UNCOMMITTED = 0 LEGACY = 1 PROFILES = 2 class Cluster(object): """ The main class to use when interacting with a Cassandra cluster. Typically, one instance of this class will be created for each separate Cassandra cluster that your application interacts with. Example usage:: >>> from cassandra.cluster import Cluster >>> cluster = Cluster(['192.168.1.1', '192.168.1.2']) >>> session = cluster.connect() >>> session.execute("CREATE KEYSPACE ...") >>> ... >>> cluster.shutdown() ``Cluster`` and ``Session`` also provide context management functions which implicitly handle shutdown when leaving scope. """ contact_points = ['127.0.0.1'] """ The list of contact points to try connecting for cluster discovery. A - contact point can be a string (ip, hostname) or a + contact point can be a string (ip or hostname), a tuple (ip/hostname, port) or a :class:`.connection.EndPoint` instance. Defaults to loopback interface. Note: When using :class:`.DCAwareLoadBalancingPolicy` with no explicit local_dc set (as is the default), the DC is chosen from an arbitrary host in contact_points. In this case, contact_points should contain only nodes from a single, local DC. Note: In the next major version, if you specify contact points, you will also be required to also explicitly specify a load-balancing policy. This change will help prevent cases where users had hard-to-debug issues surrounding unintuitive default load-balancing policy behavior. """ # tracks if contact_points was set explicitly or with default values _contact_points_explicit = None port = 9042 """ The server-side port to open connections to. Defaults to 9042. """ cql_version = None """ If a specific version of CQL should be used, this may be set to that string version. Otherwise, the highest CQL version supported by the server will be automatically used. """ - protocol_version = ProtocolVersion.V4 + protocol_version = ProtocolVersion.DSE_V2 """ The maximum version of the native protocol to use. See :class:`.ProtocolVersion` for more information about versions. If not set in the constructor, the driver will automatically downgrade version based on a negotiation with the server, but it is most efficient to set this to the maximum supported by your version of Cassandra. Setting this will also prevent conflicting versions negotiated if your cluster is upgraded. """ allow_beta_protocol_version = False no_compact = False """ Setting true injects a flag in all messages that makes the server accept and use "beta" protocol version. Used for testing new protocol features incrementally before the new version is complete. """ compression = True """ Controls compression for communications between the driver and Cassandra. If left as the default of :const:`True`, either lz4 or snappy compression may be used, depending on what is supported by both the driver and Cassandra. If both are fully supported, lz4 will be preferred. You may also set this to 'snappy' or 'lz4' to request that specific compression type. Setting this to :const:`False` disables compression. """ _auth_provider = None _auth_provider_callable = None @property def auth_provider(self): """ When :attr:`~.Cluster.protocol_version` is 2 or higher, this should be an instance of a subclass of :class:`~cassandra.auth.AuthProvider`, such as :class:`~.PlainTextAuthProvider`. When :attr:`~.Cluster.protocol_version` is 1, this should be a function that accepts one argument, the IP address of a node, and returns a dict of credentials for that node. When not using authentication, this should be left as :const:`None`. """ return self._auth_provider @auth_provider.setter # noqa def auth_provider(self, value): if not value: self._auth_provider = value return try: self._auth_provider_callable = value.new_authenticator except AttributeError: if self.protocol_version > 1: raise TypeError("auth_provider must implement the cassandra.auth.AuthProvider " "interface when protocol_version >= 2") elif not callable(value): raise TypeError("auth_provider must be callable when protocol_version == 1") self._auth_provider_callable = value self._auth_provider = value _load_balancing_policy = None @property def load_balancing_policy(self): """ An instance of :class:`.policies.LoadBalancingPolicy` or one of its subclasses. .. versionchanged:: 2.6.0 Defaults to :class:`~.TokenAwarePolicy` (:class:`~.DCAwareRoundRobinPolicy`). when using CPython (where the murmur3 extension is available). :class:`~.DCAwareRoundRobinPolicy` otherwise. Default local DC will be chosen from contact points. **Please see** :class:`~.DCAwareRoundRobinPolicy` **for a discussion on default behavior with respect to DC locality and remote nodes.** """ return self._load_balancing_policy @load_balancing_policy.setter def load_balancing_policy(self, lbp): if self._config_mode == _ConfigMode.PROFILES: raise ValueError("Cannot set Cluster.load_balancing_policy while using Configuration Profiles. Set this in a profile instead.") self._load_balancing_policy = lbp self._config_mode = _ConfigMode.LEGACY @property def _default_load_balancing_policy(self): return self.profile_manager.default.load_balancing_policy reconnection_policy = ExponentialReconnectionPolicy(1.0, 600.0) """ An instance of :class:`.policies.ReconnectionPolicy`. Defaults to an instance of :class:`.ExponentialReconnectionPolicy` with a base delay of one second and a max delay of ten minutes. """ _default_retry_policy = RetryPolicy() @property def default_retry_policy(self): """ A default :class:`.policies.RetryPolicy` instance to use for all :class:`.Statement` objects which do not have a :attr:`~.Statement.retry_policy` explicitly set. """ return self._default_retry_policy @default_retry_policy.setter def default_retry_policy(self, policy): if self._config_mode == _ConfigMode.PROFILES: raise ValueError("Cannot set Cluster.default_retry_policy while using Configuration Profiles. Set this in a profile instead.") self._default_retry_policy = policy self._config_mode = _ConfigMode.LEGACY conviction_policy_factory = SimpleConvictionPolicy """ A factory function which creates instances of :class:`.policies.ConvictionPolicy`. Defaults to :class:`.policies.SimpleConvictionPolicy`. """ address_translator = IdentityTranslator() """ :class:`.policies.AddressTranslator` instance to be used in translating server node addresses to driver connection addresses. """ connect_to_remote_hosts = True """ If left as :const:`True`, hosts that are considered :attr:`~.HostDistance.REMOTE` by the :attr:`~.Cluster.load_balancing_policy` will have a connection opened to them. Otherwise, they will not have a connection opened to them. Note that the default load balancing policy ignores remote hosts by default. .. versionadded:: 2.1.0 """ metrics_enabled = False """ Whether or not metric collection is enabled. If enabled, :attr:`.metrics` will be an instance of :class:`~cassandra.metrics.Metrics`. """ metrics = None """ An instance of :class:`cassandra.metrics.Metrics` if :attr:`.metrics_enabled` is :const:`True`, else :const:`None`. """ ssl_options = None """ Using ssl_options without ssl_context is deprecated and will be removed in the next major release. An optional dict which will be used as kwargs for ``ssl.SSLContext.wrap_socket`` (or ``ssl.wrap_socket()`` if used without ssl_context) when new sockets are created. This should be used when client encryption is enabled in Cassandra. The following documentation only applies when ssl_options is used without ssl_context. By default, a ``ca_certs`` value should be supplied (the value should be a string pointing to the location of the CA certs file), and you probably - want to specify ``ssl_version`` as ``ssl.PROTOCOL_TLSv1`` to match + want to specify ``ssl_version`` as ``ssl.PROTOCOL_TLS`` to match Cassandra's default protocol. .. versionchanged:: 3.3.0 In addition to ``wrap_socket`` kwargs, clients may also specify ``'check_hostname': True`` to verify the cert hostname as outlined in RFC 2818 and RFC 6125. Note that this requires the certificate to be transferred, so should almost always require the option ``'cert_reqs': ssl.CERT_REQUIRED``. Note also that this functionality was not built into Python standard library until (2.7.9, 3.2). To enable this mechanism in earlier versions, patch ``ssl.match_hostname`` with a custom or `back-ported function `_. """ ssl_context = None """ An optional ``ssl.SSLContext`` instance which will be used when new sockets are created. This should be used when client encryption is enabled in Cassandra. ``wrap_socket`` options can be set using :attr:`~Cluster.ssl_options`. ssl_options will be used as kwargs for ``ssl.SSLContext.wrap_socket``. .. versionadded:: 3.17.0 """ sockopts = None """ An optional list of tuples which will be used as arguments to ``socket.setsockopt()`` for all created sockets. Note: some drivers find setting TCPNODELAY beneficial in the context of their execution model. It was not found generally beneficial for this driver. To try with your own workload, set ``sockopts = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]`` """ max_schema_agreement_wait = 10 """ The maximum duration (in seconds) that the driver will wait for schema agreement across the cluster. Defaults to ten seconds. If set <= 0, the driver will bypass schema agreement waits altogether. """ metadata = None """ An instance of :class:`cassandra.metadata.Metadata`. """ connection_class = DefaultConnection """ This determines what event loop system will be used for managing I/O with Cassandra. These are the current options: * :class:`cassandra.io.asyncorereactor.AsyncoreConnection` * :class:`cassandra.io.libevreactor.LibevConnection` * :class:`cassandra.io.eventletreactor.EventletConnection` (requires monkey-patching - see doc for details) * :class:`cassandra.io.geventreactor.GeventConnection` (requires monkey-patching - see doc for details) * :class:`cassandra.io.twistedreactor.TwistedConnection` * EXPERIMENTAL: :class:`cassandra.io.asyncioreactor.AsyncioConnection` By default, ``AsyncoreConnection`` will be used, which uses the ``asyncore`` module in the Python standard library. If ``libev`` is installed, ``LibevConnection`` will be used instead. If ``gevent`` or ``eventlet`` monkey-patching is detected, the corresponding connection class will be used automatically. ``AsyncioConnection``, which uses the ``asyncio`` module in the Python standard library, is also available, but currently experimental. Note that it requires ``asyncio`` features that were only introduced in the 3.4 line in 3.4.6, and in the 3.5 line in 3.5.1. """ control_connection_timeout = 2.0 """ A timeout, in seconds, for queries made by the control connection, such as querying the current schema and information about nodes in the cluster. If set to :const:`None`, there will be no timeout for these queries. """ idle_heartbeat_interval = 30 """ Interval, in seconds, on which to heartbeat idle connections. This helps keep connections open through network devices that expire idle connections. It also helps discover bad connections early in low-traffic scenarios. Setting to zero disables heartbeats. """ idle_heartbeat_timeout = 30 """ Timeout, in seconds, on which the heartbeat wait for idle connection responses. Lowering this value can help to discover bad connections earlier. """ schema_event_refresh_window = 2 """ Window, in seconds, within which a schema component will be refreshed after receiving a schema_change event. The driver delays a random amount of time in the range [0.0, window) before executing the refresh. This serves two purposes: 1.) Spread the refresh for deployments with large fanout from C* to client tier, preventing a 'thundering herd' problem with many clients refreshing simultaneously. 2.) Remove redundant refreshes. Redundant events arriving within the delay period are discarded, and only one refresh is executed. Setting this to zero will execute refreshes immediately. Setting this negative will disable schema refreshes in response to push events (refreshes will still occur in response to schema change responses to DDL statements executed by Sessions of this Cluster). """ topology_event_refresh_window = 10 """ Window, in seconds, within which the node and token list will be refreshed after receiving a topology_change event. Setting this to zero will execute refreshes immediately. Setting this negative will disable node refreshes in response to push events. See :attr:`.schema_event_refresh_window` for discussion of rationale """ status_event_refresh_window = 2 """ Window, in seconds, within which the driver will start the reconnect after receiving a status_change event. Setting this to zero will connect immediately. This is primarily used to avoid 'thundering herd' in deployments with large fanout from cluster to clients. When nodes come up, clients attempt to reprepare prepared statements (depending on :attr:`.reprepare_on_up`), and establish connection pools. This can cause a rush of connections and queries if not mitigated with this factor. """ prepare_on_all_hosts = True """ Specifies whether statements should be prepared on all hosts, or just one. This can reasonably be disabled on long-running applications with numerous clients preparing statements on startup, where a randomized initial condition of the load balancing policy can be expected to distribute prepares from different clients across the cluster. """ reprepare_on_up = True """ Specifies whether all known prepared statements should be prepared on a node when it comes up. May be used to avoid overwhelming a node on return, or if it is supposed that the node was only marked down due to network. If statements are not reprepared, they are prepared on the first execution, causing an extra roundtrip for one or more client requests. """ connect_timeout = 5 """ Timeout, in seconds, for creating new connections. This timeout covers the entire connection negotiation, including TCP establishment, options passing, and authentication. """ timestamp_generator = None """ An object, shared between all sessions created by this cluster instance, that generates timestamps when client-side timestamp generation is enabled. By default, each :class:`Cluster` uses a new :class:`~.MonotonicTimestampGenerator`. Applications can set this value for custom timestamp behavior. See the documentation for :meth:`Session.timestamp_generator`. """ + monitor_reporting_enabled = True + """ + A boolean indicating if monitor reporting, which sends gathered data to + Insights when running against DSE 6.8 and higher. + """ + + monitor_reporting_interval = 30 + """ + A boolean indicating if monitor reporting, which sends gathered data to + Insights when running against DSE 6.8 and higher. + """ + + client_id = None + """ + A UUID that uniquely identifies this Cluster object to Insights. This will + be generated automatically unless the user provides one. + """ + + application_name = '' + """ + A string identifying this application to Insights. + """ + + application_version = '' + """ + A string identifiying this application's version to Insights + """ + cloud = None """ A dict of the cloud configuration. Example:: { # path to the secure connect bundle - 'secure_connect_bundle': '/path/to/secure-connect-dbname.zip' + 'secure_connect_bundle': '/path/to/secure-connect-dbname.zip', + + # optional config options + 'use_default_tempdir': True # use the system temp dir for the zip extraction } The zip file will be temporarily extracted in the same directory to load the configuration and certificates. """ @property def schema_metadata_enabled(self): """ Flag indicating whether internal schema metadata is updated. When disabled, the driver does not populate Cluster.metadata.keyspaces on connect, or on schema change events. This can be used to speed initial connection, and reduce load on client and server during operation. Turning this off gives away token aware request routing, and programmatic inspection of the metadata model. """ return self.control_connection._schema_meta_enabled @schema_metadata_enabled.setter def schema_metadata_enabled(self, enabled): self.control_connection._schema_meta_enabled = bool(enabled) @property def token_metadata_enabled(self): """ Flag indicating whether internal token metadata is updated. When disabled, the driver does not query node token information on connect, or on topology change events. This can be used to speed initial connection, and reduce load on client and server during operation. It is most useful in large clusters using vnodes, where the token map can be expensive to compute. Turning this off gives away token aware request routing, and programmatic inspection of the token ring. """ return self.control_connection._token_meta_enabled @token_metadata_enabled.setter def token_metadata_enabled(self, enabled): self.control_connection._token_meta_enabled = bool(enabled) endpoint_factory = None """ An :class:`~.connection.EndPointFactory` instance to use internally when creating a socket connection to a node. You can ignore this unless you need a special connection mechanism. """ profile_manager = None _config_mode = _ConfigMode.UNCOMMITTED sessions = None control_connection = None scheduler = None executor = None is_shutdown = False _is_setup = False _prepared_statements = None _prepared_statement_lock = None _idle_heartbeat = None _protocol_version_explicit = False _discount_down_events = True _user_types = None """ A map of {keyspace: {type_name: UserType}} """ _listeners = None _listener_lock = None def __init__(self, contact_points=_NOT_SET, port=9042, compression=True, auth_provider=None, load_balancing_policy=None, reconnection_policy=None, default_retry_policy=None, conviction_policy_factory=None, metrics_enabled=False, connection_class=None, ssl_options=None, sockopts=None, cql_version=None, protocol_version=_NOT_SET, executor_threads=2, max_schema_agreement_wait=10, control_connection_timeout=2.0, idle_heartbeat_interval=30, schema_event_refresh_window=2, topology_event_refresh_window=10, connect_timeout=5, schema_metadata_enabled=True, token_metadata_enabled=True, address_translator=None, status_event_refresh_window=2, prepare_on_all_hosts=True, reprepare_on_up=True, execution_profiles=None, allow_beta_protocol_version=False, timestamp_generator=None, idle_heartbeat_timeout=30, no_compact=False, ssl_context=None, endpoint_factory=None, + application_name=None, + application_version=None, + monitor_reporting_enabled=True, + monitor_reporting_interval=30, + client_id=None, cloud=None): """ ``executor_threads`` defines the number of threads in a pool for handling asynchronous tasks such as extablishing connection pools or refreshing metadata. Any of the mutable Cluster attributes may be set as keyword arguments to the constructor. """ + if connection_class is not None: + self.connection_class = connection_class if cloud is not None: + self.cloud = cloud if contact_points is not _NOT_SET or endpoint_factory or ssl_context or ssl_options: raise ValueError("contact_points, endpoint_factory, ssl_context, and ssl_options " "cannot be specified with a cloud configuration") - cloud_config = dscloud.get_cloud_config(cloud) + uses_twisted = TwistedConnection and issubclass(self.connection_class, TwistedConnection) + uses_eventlet = EventletConnection and issubclass(self.connection_class, EventletConnection) + cloud_config = dscloud.get_cloud_config(cloud, create_pyopenssl_context=uses_twisted or uses_eventlet) ssl_context = cloud_config.ssl_context ssl_options = {'check_hostname': True} if (auth_provider is None and cloud_config.username and cloud_config.password): auth_provider = PlainTextAuthProvider(cloud_config.username, cloud_config.password) endpoint_factory = SniEndPointFactory(cloud_config.sni_host, cloud_config.sni_port) contact_points = [ endpoint_factory.create_from_sni(host_id) for host_id in cloud_config.host_ids ] if contact_points is not None: if contact_points is _NOT_SET: self._contact_points_explicit = False contact_points = ['127.0.0.1'] else: self._contact_points_explicit = True if isinstance(contact_points, six.string_types): raise TypeError("contact_points should not be a string, it should be a sequence (e.g. list) of strings") if None in contact_points: raise ValueError("contact_points should not contain None (it can resolve to localhost)") self.contact_points = contact_points self.port = port self.endpoint_factory = endpoint_factory or DefaultEndPointFactory(port=self.port) self.endpoint_factory.configure(self) - raw_contact_points = [cp for cp in self.contact_points if not isinstance(cp, EndPoint)] + raw_contact_points = [] + for cp in [cp for cp in self.contact_points if not isinstance(cp, EndPoint)]: + raw_contact_points.append(cp if isinstance(cp, tuple) else (cp, port)) + self.endpoints_resolved = [cp for cp in self.contact_points if isinstance(cp, EndPoint)] + self._endpoint_map_for_insights = {repr(ep): '{ip}:{port}'.format(ip=ep.address, port=ep.port) + for ep in self.endpoints_resolved} + + strs_resolved_map = _resolve_contact_points_to_string_map(raw_contact_points) + self.endpoints_resolved.extend(list(chain( + *[ + [DefaultEndPoint(ip, port) for ip, port in xs if ip is not None] + for xs in strs_resolved_map.values() if xs is not None + ] + ))) - try: - self.endpoints_resolved += [DefaultEndPoint(address, self.port) - for address in _resolve_contact_points(raw_contact_points, self.port)] - except UnresolvableContactPoints: - # rethrow if no EndPoint was provided - if not self.endpoints_resolved: - raise + self._endpoint_map_for_insights.update( + {key: ['{ip}:{port}'.format(ip=ip, port=port) for ip, port in value] + for key, value in strs_resolved_map.items() if value is not None} + ) + + if contact_points and (not self.endpoints_resolved): + # only want to raise here if the user specified CPs but resolution failed + raise UnresolvableContactPoints(self._endpoint_map_for_insights) self.compression = compression if protocol_version is not _NOT_SET: self.protocol_version = protocol_version self._protocol_version_explicit = True self.allow_beta_protocol_version = allow_beta_protocol_version self.no_compact = no_compact self.auth_provider = auth_provider if load_balancing_policy is not None: if isinstance(load_balancing_policy, type): raise TypeError("load_balancing_policy should not be a class, it should be an instance of that class") self.load_balancing_policy = load_balancing_policy else: self._load_balancing_policy = default_lbp_factory() # set internal attribute to avoid committing to legacy config mode if reconnection_policy is not None: if isinstance(reconnection_policy, type): raise TypeError("reconnection_policy should not be a class, it should be an instance of that class") self.reconnection_policy = reconnection_policy if default_retry_policy is not None: if isinstance(default_retry_policy, type): raise TypeError("default_retry_policy should not be a class, it should be an instance of that class") self.default_retry_policy = default_retry_policy if conviction_policy_factory is not None: if not callable(conviction_policy_factory): raise ValueError("conviction_policy_factory must be callable") self.conviction_policy_factory = conviction_policy_factory if address_translator is not None: if isinstance(address_translator, type): raise TypeError("address_translator should not be a class, it should be an instance of that class") self.address_translator = address_translator - if connection_class is not None: - self.connection_class = connection_class - if timestamp_generator is not None: if not callable(timestamp_generator): raise ValueError("timestamp_generator must be callable") self.timestamp_generator = timestamp_generator else: self.timestamp_generator = MonotonicTimestampGenerator() self.profile_manager = ProfileManager() self.profile_manager.profiles[EXEC_PROFILE_DEFAULT] = ExecutionProfile( self.load_balancing_policy, self.default_retry_policy, request_timeout=Session._default_timeout, row_factory=Session._row_factory ) + # legacy mode if either of these is not default if load_balancing_policy or default_retry_policy: if execution_profiles: raise ValueError("Clusters constructed with execution_profiles should not specify legacy parameters " "load_balancing_policy or default_retry_policy. Configure this in a profile instead.") self._config_mode = _ConfigMode.LEGACY warn("Legacy execution parameters will be removed in 4.0. Consider using " "execution profiles.", DeprecationWarning) else: + profiles = self.profile_manager.profiles if execution_profiles: - self.profile_manager.profiles.update(execution_profiles) + profiles.update(execution_profiles) self._config_mode = _ConfigMode.PROFILES - if self._contact_points_explicit: + lbp = DefaultLoadBalancingPolicy(self.profile_manager.default.load_balancing_policy) + profiles.setdefault(EXEC_PROFILE_GRAPH_DEFAULT, GraphExecutionProfile(load_balancing_policy=lbp)) + profiles.setdefault(EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT, + GraphExecutionProfile(load_balancing_policy=lbp, request_timeout=60. * 3.)) + profiles.setdefault(EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT, + GraphAnalyticsExecutionProfile(load_balancing_policy=lbp)) + + if self._contact_points_explicit and not self.cloud: # avoid this warning for cloud users. if self._config_mode is _ConfigMode.PROFILES: default_lbp_profiles = self.profile_manager._profiles_without_explicit_lbps() if default_lbp_profiles: log.warning( 'Cluster.__init__ called with contact_points ' 'specified, but load-balancing policies are not ' 'specified in some ExecutionProfiles. In the next ' 'major version, this will raise an error; please ' 'specify a load-balancing policy. ' '(contact_points = {cp}, ' 'EPs without explicit LBPs = {eps})' ''.format(cp=contact_points, eps=default_lbp_profiles)) else: if load_balancing_policy is None: log.warning( 'Cluster.__init__ called with contact_points ' 'specified, but no load_balancing_policy. In the next ' 'major version, this will raise an error; please ' 'specify a load-balancing policy. ' '(contact_points = {cp}, lbp = {lbp})' ''.format(cp=contact_points, lbp=load_balancing_policy)) self.metrics_enabled = metrics_enabled if ssl_options and not ssl_context: warn('Using ssl_options without ssl_context is ' 'deprecated and will result in an error in ' 'the next major release. Please use ssl_context ' 'to prepare for that release.', DeprecationWarning) self.ssl_options = ssl_options self.ssl_context = ssl_context self.sockopts = sockopts self.cql_version = cql_version self.max_schema_agreement_wait = max_schema_agreement_wait self.control_connection_timeout = control_connection_timeout self.idle_heartbeat_interval = idle_heartbeat_interval self.idle_heartbeat_timeout = idle_heartbeat_timeout self.schema_event_refresh_window = schema_event_refresh_window self.topology_event_refresh_window = topology_event_refresh_window self.status_event_refresh_window = status_event_refresh_window self.connect_timeout = connect_timeout self.prepare_on_all_hosts = prepare_on_all_hosts self.reprepare_on_up = reprepare_on_up + self.monitor_reporting_enabled = monitor_reporting_enabled + self.monitor_reporting_interval = monitor_reporting_interval self._listeners = set() self._listener_lock = Lock() # let Session objects be GC'ed (and shutdown) when the user no longer # holds a reference. self.sessions = WeakSet() self.metadata = Metadata() self.control_connection = None self._prepared_statements = WeakValueDictionary() self._prepared_statement_lock = Lock() self._user_types = defaultdict(dict) self._min_requests_per_connection = { HostDistance.LOCAL: DEFAULT_MIN_REQUESTS, HostDistance.REMOTE: DEFAULT_MIN_REQUESTS } self._max_requests_per_connection = { HostDistance.LOCAL: DEFAULT_MAX_REQUESTS, HostDistance.REMOTE: DEFAULT_MAX_REQUESTS } self._core_connections_per_host = { HostDistance.LOCAL: DEFAULT_MIN_CONNECTIONS_PER_LOCAL_HOST, HostDistance.REMOTE: DEFAULT_MIN_CONNECTIONS_PER_REMOTE_HOST } self._max_connections_per_host = { HostDistance.LOCAL: DEFAULT_MAX_CONNECTIONS_PER_LOCAL_HOST, HostDistance.REMOTE: DEFAULT_MAX_CONNECTIONS_PER_REMOTE_HOST } self.executor = self._create_thread_pool_executor(max_workers=executor_threads) self.scheduler = _Scheduler(self.executor) self._lock = RLock() if self.metrics_enabled: from cassandra.metrics import Metrics self.metrics = Metrics(weakref.proxy(self)) self.control_connection = ControlConnection( self, self.control_connection_timeout, self.schema_event_refresh_window, self.topology_event_refresh_window, self.status_event_refresh_window, schema_metadata_enabled, token_metadata_enabled) + if client_id is None: + self.client_id = uuid.uuid4() + if application_name is not None: + self.application_name = application_name + if application_version is not None: + self.application_version = application_version + def _create_thread_pool_executor(self, **kwargs): """ Create a ThreadPoolExecutor for the cluster. In most cases, the built-in `concurrent.futures.ThreadPoolExecutor` is used. - Python 3.7 and Eventlet cause the `concurrent.futures.ThreadPoolExecutor` + Python 3.7+ and Eventlet cause the `concurrent.futures.ThreadPoolExecutor` to hang indefinitely. In that case, the user needs to have the `futurist` package so we can use the `futurist.GreenThreadPoolExecutor` class instead. :param kwargs: All keyword args are passed to the ThreadPoolExecutor constructor. :return: A ThreadPoolExecutor instance. """ tpe_class = ThreadPoolExecutor if sys.version_info[0] >= 3 and sys.version_info[1] >= 7: try: from cassandra.io.eventletreactor import EventletConnection is_eventlet = issubclass(self.connection_class, EventletConnection) except: # Eventlet is not available or can't be detected return tpe_class(**kwargs) if is_eventlet: try: from futurist import GreenThreadPoolExecutor tpe_class = GreenThreadPoolExecutor except ImportError: # futurist is not available raise ImportError( - ("Python 3.7 and Eventlet cause the `concurrent.futures.ThreadPoolExecutor` " + ("Python 3.7+ and Eventlet cause the `concurrent.futures.ThreadPoolExecutor` " "to hang indefinitely. If you want to use the Eventlet reactor, you " "need to install the `futurist` package to allow the driver to use " "the GreenThreadPoolExecutor. See https://github.com/eventlet/eventlet/issues/508 " "for more details.")) return tpe_class(**kwargs) def register_user_type(self, keyspace, user_type, klass): """ Registers a class to use to represent a particular user-defined type. Query parameters for this user-defined type will be assumed to be instances of `klass`. Result sets for this user-defined type will be instances of `klass`. If no class is registered for a user-defined type, a namedtuple will be used for result sets, and non-prepared statements may not encode parameters for this type correctly. `keyspace` is the name of the keyspace that the UDT is defined in. `user_type` is the string name of the UDT to register the mapping for. `klass` should be a class with attributes whose names match the fields of the user-defined type. The constructor must accepts kwargs for each of the fields in the UDT. This method should only be called after the type has been created within Cassandra. Example:: cluster = Cluster(protocol_version=3) session = cluster.connect() session.set_keyspace('mykeyspace') session.execute("CREATE TYPE address (street text, zipcode int)") session.execute("CREATE TABLE users (id int PRIMARY KEY, location address)") # create a class to map to the "address" UDT class Address(object): def __init__(self, street, zipcode): self.street = street self.zipcode = zipcode cluster.register_user_type('mykeyspace', 'address', Address) # insert a row using an instance of Address session.execute("INSERT INTO users (id, location) VALUES (%s, %s)", (0, Address("123 Main St.", 78723))) # results will include Address instances results = session.execute("SELECT * FROM users") row = results[0] print row.id, row.location.street, row.location.zipcode """ if self.protocol_version < 3: log.warning("User Type serialization is only supported in native protocol version 3+ (%d in use). " "CQL encoding for simple statements will still work, but named tuples will " "be returned when reading type %s.%s.", self.protocol_version, keyspace, user_type) self._user_types[keyspace][user_type] = klass for session in tuple(self.sessions): session.user_type_registered(keyspace, user_type, klass) UserType.evict_udt_class(keyspace, user_type) def add_execution_profile(self, name, profile, pool_wait_timeout=5): """ Adds an :class:`.ExecutionProfile` to the cluster. This makes it available for use by ``name`` in :meth:`.Session.execute` and :meth:`.Session.execute_async`. This method will raise if the profile already exists. Normally profiles will be injected at cluster initialization via ``Cluster(execution_profiles)``. This method provides a way of adding them dynamically. Adding a new profile updates the connection pools according to the specified ``load_balancing_policy``. By default, this method will wait up to five seconds for the pool creation to complete, so the profile can be used immediately upon return. This behavior can be controlled using ``pool_wait_timeout`` (see `concurrent.futures.wait `_ for timeout semantics). """ if not isinstance(profile, ExecutionProfile): raise TypeError("profile must be an instance of ExecutionProfile") if self._config_mode == _ConfigMode.LEGACY: raise ValueError("Cannot add execution profiles when legacy parameters are set explicitly.") if name in self.profile_manager.profiles: raise ValueError("Profile {} already exists".format(name)) contact_points_but_no_lbp = ( self._contact_points_explicit and not profile._load_balancing_policy_explicit) if contact_points_but_no_lbp: log.warning( 'Tried to add an ExecutionProfile with name {name}. ' '{self} was explicitly configured with contact_points, but ' '{ep} was not explicitly configured with a ' 'load_balancing_policy. In the next major version, trying to ' 'add an ExecutionProfile without an explicitly configured LBP ' 'to a cluster with explicitly configured contact_points will ' 'raise an exception; please specify a load-balancing policy ' 'in the ExecutionProfile.' ''.format(name=_execution_profile_to_string(name), self=self, ep=profile)) self.profile_manager.profiles[name] = profile profile.load_balancing_policy.populate(self, self.metadata.all_hosts()) # on_up after populate allows things like DCA LBP to choose default local dc for host in filter(lambda h: h.is_up, self.metadata.all_hosts()): profile.load_balancing_policy.on_up(host) futures = set() for session in tuple(self.sessions): self._set_default_dbaas_consistency(session) futures.update(session.update_created_pools()) _, not_done = wait_futures(futures, pool_wait_timeout) if not_done: raise OperationTimedOut("Failed to create all new connection pools in the %ss timeout.") def get_min_requests_per_connection(self, host_distance): return self._min_requests_per_connection[host_distance] def set_min_requests_per_connection(self, host_distance, min_requests): """ Sets a threshold for concurrent requests per connection, below which connections will be considered for disposal (down to core connections; see :meth:`~Cluster.set_core_connections_per_host`). Pertains to connection pool management in protocol versions {1,2}. """ if self.protocol_version >= 3: raise UnsupportedOperation( "Cluster.set_min_requests_per_connection() only has an effect " "when using protocol_version 1 or 2.") if min_requests < 0 or min_requests > 126 or \ min_requests >= self._max_requests_per_connection[host_distance]: raise ValueError("min_requests must be 0-126 and less than the max_requests for this host_distance (%d)" % (self._min_requests_per_connection[host_distance],)) self._min_requests_per_connection[host_distance] = min_requests def get_max_requests_per_connection(self, host_distance): return self._max_requests_per_connection[host_distance] def set_max_requests_per_connection(self, host_distance, max_requests): """ Sets a threshold for concurrent requests per connection, above which new connections will be created to a host (up to max connections; see :meth:`~Cluster.set_max_connections_per_host`). Pertains to connection pool management in protocol versions {1,2}. """ if self.protocol_version >= 3: raise UnsupportedOperation( "Cluster.set_max_requests_per_connection() only has an effect " "when using protocol_version 1 or 2.") if max_requests < 1 or max_requests > 127 or \ max_requests <= self._min_requests_per_connection[host_distance]: raise ValueError("max_requests must be 1-127 and greater than the min_requests for this host_distance (%d)" % (self._min_requests_per_connection[host_distance],)) self._max_requests_per_connection[host_distance] = max_requests def get_core_connections_per_host(self, host_distance): """ Gets the minimum number of connections per Session that will be opened for each host with :class:`~.HostDistance` equal to `host_distance`. The default is 2 for :attr:`~HostDistance.LOCAL` and 1 for :attr:`~HostDistance.REMOTE`. This property is ignored if :attr:`~.Cluster.protocol_version` is 3 or higher. """ return self._core_connections_per_host[host_distance] def set_core_connections_per_host(self, host_distance, core_connections): """ Sets the minimum number of connections per Session that will be opened for each host with :class:`~.HostDistance` equal to `host_distance`. The default is 2 for :attr:`~HostDistance.LOCAL` and 1 for :attr:`~HostDistance.REMOTE`. Protocol version 1 and 2 are limited in the number of concurrent requests they can send per connection. The driver implements connection pooling to support higher levels of concurrency. If :attr:`~.Cluster.protocol_version` is set to 3 or higher, this is not supported (there is always one connection per host, unless the host is remote and :attr:`connect_to_remote_hosts` is :const:`False`) - and using this will result in an :exc:`~.UnsupporteOperation`. + and using this will result in an :exc:`~.UnsupportedOperation`. """ if self.protocol_version >= 3: raise UnsupportedOperation( "Cluster.set_core_connections_per_host() only has an effect " "when using protocol_version 1 or 2.") old = self._core_connections_per_host[host_distance] self._core_connections_per_host[host_distance] = core_connections if old < core_connections: self._ensure_core_connections() def get_max_connections_per_host(self, host_distance): """ Gets the maximum number of connections per Session that will be opened for each host with :class:`~.HostDistance` equal to `host_distance`. The default is 8 for :attr:`~HostDistance.LOCAL` and 2 for :attr:`~HostDistance.REMOTE`. This property is ignored if :attr:`~.Cluster.protocol_version` is 3 or higher. """ return self._max_connections_per_host[host_distance] def set_max_connections_per_host(self, host_distance, max_connections): """ Sets the maximum number of connections per Session that will be opened for each host with :class:`~.HostDistance` equal to `host_distance`. The default is 2 for :attr:`~HostDistance.LOCAL` and 1 for :attr:`~HostDistance.REMOTE`. If :attr:`~.Cluster.protocol_version` is set to 3 or higher, this is not supported (there is always one connection per host, unless the host is remote and :attr:`connect_to_remote_hosts` is :const:`False`) - and using this will result in an :exc:`~.UnsupporteOperation`. + and using this will result in an :exc:`~.UnsupportedOperation`. """ if self.protocol_version >= 3: raise UnsupportedOperation( "Cluster.set_max_connections_per_host() only has an effect " "when using protocol_version 1 or 2.") self._max_connections_per_host[host_distance] = max_connections def connection_factory(self, endpoint, *args, **kwargs): """ Called to create a new connection with proper configuration. Intended for internal use only. """ kwargs = self._make_connection_kwargs(endpoint, kwargs) return self.connection_class.factory(endpoint, self.connect_timeout, *args, **kwargs) def _make_connection_factory(self, host, *args, **kwargs): kwargs = self._make_connection_kwargs(host.endpoint, kwargs) return partial(self.connection_class.factory, host.endpoint, self.connect_timeout, *args, **kwargs) def _make_connection_kwargs(self, endpoint, kwargs_dict): if self._auth_provider_callable: kwargs_dict.setdefault('authenticator', self._auth_provider_callable(endpoint.address)) kwargs_dict.setdefault('port', self.port) kwargs_dict.setdefault('compression', self.compression) kwargs_dict.setdefault('sockopts', self.sockopts) kwargs_dict.setdefault('ssl_options', self.ssl_options) kwargs_dict.setdefault('ssl_context', self.ssl_context) kwargs_dict.setdefault('cql_version', self.cql_version) kwargs_dict.setdefault('protocol_version', self.protocol_version) kwargs_dict.setdefault('user_type_map', self._user_types) kwargs_dict.setdefault('allow_beta_protocol_version', self.allow_beta_protocol_version) kwargs_dict.setdefault('no_compact', self.no_compact) return kwargs_dict def protocol_downgrade(self, host_endpoint, previous_version): if self._protocol_version_explicit: raise DriverException("ProtocolError returned from server while using explicitly set client protocol_version %d" % (previous_version,)) - new_version = ProtocolVersion.get_lower_supported(previous_version) if new_version < ProtocolVersion.MIN_SUPPORTED: raise DriverException( "Cannot downgrade protocol version below minimum supported version: %d" % (ProtocolVersion.MIN_SUPPORTED,)) log.warning("Downgrading core protocol version from %d to %d for %s. " "To avoid this, it is best practice to explicitly set Cluster(protocol_version) to the version supported by your cluster. " "http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.protocol_version", self.protocol_version, new_version, host_endpoint) self.protocol_version = new_version def connect(self, keyspace=None, wait_for_all_pools=False): """ Creates and returns a new :class:`~.Session` object. If `keyspace` is specified, that keyspace will be the default keyspace for operations on the ``Session``. `wait_for_all_pools` specifies whether this call should wait for all connection pools to be established or attempted. Default is `False`, which means it will return when the first successful connection is established. Remaining pools are added asynchronously. """ with self._lock: if self.is_shutdown: raise DriverException("Cluster is already shut down") if not self._is_setup: log.debug("Connecting to cluster, contact points: %s; protocol version: %s", self.contact_points, self.protocol_version) self.connection_class.initialize_reactor() _register_cluster_shutdown(self) for endpoint in self.endpoints_resolved: host, new = self.add_host(endpoint, signal=False) if new: host.set_up() for listener in self.listeners: listener.on_add(host) self.profile_manager.populate( weakref.proxy(self), self.metadata.all_hosts()) self.load_balancing_policy.populate( weakref.proxy(self), self.metadata.all_hosts() ) try: self.control_connection.connect() # we set all contact points up for connecting, but we won't infer state after this for endpoint in self.endpoints_resolved: h = self.metadata.get_host(endpoint) if h and self.profile_manager.distance(h) == HostDistance.IGNORED: h.is_up = None log.debug("Control connection created") except Exception: log.exception("Control connection failed to connect, " "shutting down Cluster:") self.shutdown() raise self.profile_manager.check_supported() # todo: rename this method if self.idle_heartbeat_interval: self._idle_heartbeat = ConnectionHeartbeat( self.idle_heartbeat_interval, self.get_connection_holders, timeout=self.idle_heartbeat_timeout ) self._is_setup = True session = self._new_session(keyspace) if wait_for_all_pools: wait_futures(session._initial_connect_futures) self._set_default_dbaas_consistency(session) return session def _set_default_dbaas_consistency(self, session): if session.cluster.metadata.dbaas: for profile in self.profile_manager.profiles.values(): if not profile._consistency_level_explicit: profile.consistency_level = ConsistencyLevel.LOCAL_QUORUM session._default_consistency_level = ConsistencyLevel.LOCAL_QUORUM def get_connection_holders(self): holders = [] for s in tuple(self.sessions): holders.extend(s.get_pools()) holders.append(self.control_connection) return holders def shutdown(self): """ Closes all sessions and connection associated with this Cluster. To ensure all connections are properly closed, **you should always call shutdown() on a Cluster instance when you are done with it**. Once shutdown, a Cluster should not be used for any purpose. """ with self._lock: if self.is_shutdown: return else: self.is_shutdown = True if self._idle_heartbeat: self._idle_heartbeat.stop() self.scheduler.shutdown() self.control_connection.shutdown() for session in tuple(self.sessions): session.shutdown() self.executor.shutdown() _discard_cluster_shutdown(self) def __enter__(self): return self def __exit__(self, *args): self.shutdown() def _new_session(self, keyspace): session = Session(self, self.metadata.all_hosts(), keyspace) self._session_register_user_types(session) self.sessions.add(session) return session def _session_register_user_types(self, session): for keyspace, type_map in six.iteritems(self._user_types): for udt_name, klass in six.iteritems(type_map): session.user_type_registered(keyspace, udt_name, klass) def _cleanup_failed_on_up_handling(self, host): self.profile_manager.on_down(host) self.control_connection.on_down(host) for session in tuple(self.sessions): session.remove_pool(host) self._start_reconnector(host, is_host_addition=False) def _on_up_future_completed(self, host, futures, results, lock, finished_future): with lock: futures.discard(finished_future) try: results.append(finished_future.result()) except Exception as exc: results.append(exc) if futures: return try: # all futures have completed at this point for exc in [f for f in results if isinstance(f, Exception)]: log.error("Unexpected failure while marking node %s up:", host, exc_info=exc) self._cleanup_failed_on_up_handling(host) return if not all(results): log.debug("Connection pool could not be created, not marking node %s up", host) self._cleanup_failed_on_up_handling(host) return log.info("Connection pools established for node %s", host) # mark the host as up and notify all listeners host.set_up() for listener in self.listeners: listener.on_up(host) finally: with host.lock: host._currently_handling_node_up = False # see if there are any pools to add or remove now that the host is marked up for session in tuple(self.sessions): session.update_created_pools() def on_up(self, host): """ Intended for internal use only. """ if self.is_shutdown: return log.debug("Waiting to acquire lock for handling up status of node %s", host) with host.lock: if host._currently_handling_node_up: log.debug("Another thread is already handling up status of node %s", host) return if host.is_up: log.debug("Host %s was already marked up", host) return host._currently_handling_node_up = True log.debug("Starting to handle up status of node %s", host) have_future = False futures = set() try: log.info("Host %s may be up; will prepare queries and open connection pool", host) reconnector = host.get_and_set_reconnection_handler(None) if reconnector: log.debug("Now that host %s is up, cancelling the reconnection handler", host) reconnector.cancel() if self.profile_manager.distance(host) != HostDistance.IGNORED: self._prepare_all_queries(host) log.debug("Done preparing all queries for host %s, ", host) for session in tuple(self.sessions): session.remove_pool(host) log.debug("Signalling to load balancing policies that host %s is up", host) self.profile_manager.on_up(host) log.debug("Signalling to control connection that host %s is up", host) self.control_connection.on_up(host) log.debug("Attempting to open new connection pools for host %s", host) futures_lock = Lock() futures_results = [] callback = partial(self._on_up_future_completed, host, futures, futures_results, futures_lock) for session in tuple(self.sessions): future = session.add_or_renew_pool(host, is_host_addition=False) if future is not None: have_future = True future.add_done_callback(callback) futures.add(future) except Exception: log.exception("Unexpected failure handling node %s being marked up:", host) for future in futures: future.cancel() self._cleanup_failed_on_up_handling(host) with host.lock: host._currently_handling_node_up = False raise else: if not have_future: with host.lock: host.set_up() host._currently_handling_node_up = False # for testing purposes return futures def _start_reconnector(self, host, is_host_addition): if self.profile_manager.distance(host) == HostDistance.IGNORED: return schedule = self.reconnection_policy.new_schedule() # in order to not hold references to this Cluster open and prevent # proper shutdown when the program ends, we'll just make a closure # of the current Cluster attributes to create new Connections with conn_factory = self._make_connection_factory(host) reconnector = _HostReconnectionHandler( host, conn_factory, is_host_addition, self.on_add, self.on_up, self.scheduler, schedule, host.get_and_set_reconnection_handler, new_handler=None) old_reconnector = host.get_and_set_reconnection_handler(reconnector) if old_reconnector: log.debug("Old host reconnector found for %s, cancelling", host) old_reconnector.cancel() log.debug("Starting reconnector for host %s", host) reconnector.start() @run_in_executor def on_down(self, host, is_host_addition, expect_host_to_be_down=False): """ Intended for internal use only. """ if self.is_shutdown: return with host.lock: was_up = host.is_up # ignore down signals if we have open pools to the host # this is to avoid closing pools when a control connection host became isolated if self._discount_down_events and self.profile_manager.distance(host) != HostDistance.IGNORED: connected = False for session in tuple(self.sessions): pool_states = session.get_pool_state() pool_state = pool_states.get(host) if pool_state: connected |= pool_state['open_count'] > 0 if connected: return host.set_down() if (not was_up and not expect_host_to_be_down) or host.is_currently_reconnecting(): return log.warning("Host %s has been marked down", host) self.profile_manager.on_down(host) self.control_connection.on_down(host) for session in tuple(self.sessions): session.on_down(host) for listener in self.listeners: listener.on_down(host) self._start_reconnector(host, is_host_addition) def on_add(self, host, refresh_nodes=True): if self.is_shutdown: return log.debug("Handling new host %r and notifying listeners", host) distance = self.profile_manager.distance(host) if distance != HostDistance.IGNORED: self._prepare_all_queries(host) log.debug("Done preparing queries for new host %r", host) self.profile_manager.on_add(host) self.control_connection.on_add(host, refresh_nodes) if distance == HostDistance.IGNORED: log.debug("Not adding connection pool for new host %r because the " "load balancing policy has marked it as IGNORED", host) self._finalize_add(host, set_up=False) return futures_lock = Lock() futures_results = [] futures = set() def future_completed(future): with futures_lock: futures.discard(future) try: futures_results.append(future.result()) except Exception as exc: futures_results.append(exc) if futures: return log.debug('All futures have completed for added host %s', host) for exc in [f for f in futures_results if isinstance(f, Exception)]: log.error("Unexpected failure while adding node %s, will not mark up:", host, exc_info=exc) return if not all(futures_results): log.warning("Connection pool could not be created, not marking node %s up", host) return self._finalize_add(host) have_future = False for session in tuple(self.sessions): future = session.add_or_renew_pool(host, is_host_addition=True) if future is not None: have_future = True futures.add(future) future.add_done_callback(future_completed) if not have_future: self._finalize_add(host) def _finalize_add(self, host, set_up=True): if set_up: host.set_up() for listener in self.listeners: listener.on_add(host) # see if there are any pools to add or remove now that the host is marked up for session in tuple(self.sessions): session.update_created_pools() def on_remove(self, host): if self.is_shutdown: return log.debug("Removing host %s", host) host.set_down() self.profile_manager.on_remove(host) for session in tuple(self.sessions): session.on_remove(host) for listener in self.listeners: listener.on_remove(host) self.control_connection.on_remove(host) + reconnection_handler = host.get_and_set_reconnection_handler(None) + if reconnection_handler: + reconnection_handler.cancel() + def signal_connection_failure(self, host, connection_exc, is_host_addition, expect_host_to_be_down=False): is_down = host.signal_connection_failure(connection_exc) if is_down: self.on_down(host, is_host_addition, expect_host_to_be_down) return is_down def add_host(self, endpoint, datacenter=None, rack=None, signal=True, refresh_nodes=True): """ Called when adding initial contact points and when the control connection subsequently discovers a new node. Returns a Host instance, and a flag indicating whether it was new in the metadata. Intended for internal use only. """ host, new = self.metadata.add_or_return_host(Host(endpoint, self.conviction_policy_factory, datacenter, rack)) if new and signal: log.info("New Cassandra host %r discovered", host) self.on_add(host, refresh_nodes) return host, new def remove_host(self, host): """ Called when the control connection observes that a node has left the ring. Intended for internal use only. """ if host and self.metadata.remove_host(host): log.info("Cassandra host %s removed", host) self.on_remove(host) def register_listener(self, listener): """ Adds a :class:`cassandra.policies.HostStateListener` subclass instance to the list of listeners to be notified when a host is added, removed, marked up, or marked down. """ with self._listener_lock: self._listeners.add(listener) def unregister_listener(self, listener): """ Removes a registered listener. """ with self._listener_lock: self._listeners.remove(listener) @property def listeners(self): with self._listener_lock: return self._listeners.copy() def _ensure_core_connections(self): """ If any host has fewer than the configured number of core connections open, attempt to open connections until that number is met. """ for session in tuple(self.sessions): for pool in tuple(session._pools.values()): pool.ensure_core_connections() @staticmethod def _validate_refresh_schema(keyspace, table, usertype, function, aggregate): if any((table, usertype, function, aggregate)): if not keyspace: raise ValueError("keyspace is required to refresh specific sub-entity {table, usertype, function, aggregate}") if sum(1 for e in (table, usertype, function) if e) > 1: raise ValueError("{table, usertype, function, aggregate} are mutually exclusive") @staticmethod def _target_type_from_refresh_args(keyspace, table, usertype, function, aggregate): if aggregate: return SchemaTargetType.AGGREGATE elif function: return SchemaTargetType.FUNCTION elif usertype: return SchemaTargetType.TYPE elif table: return SchemaTargetType.TABLE elif keyspace: return SchemaTargetType.KEYSPACE return None def get_control_connection_host(self): """ Returns the control connection host metadata. """ connection = self.control_connection._connection endpoint = connection.endpoint if connection else None return self.metadata.get_host(endpoint) if endpoint else None def refresh_schema_metadata(self, max_schema_agreement_wait=None): """ Synchronously refresh all schema metadata. By default, the timeout for this operation is governed by :attr:`~.Cluster.max_schema_agreement_wait` and :attr:`~.Cluster.control_connection_timeout`. Passing max_schema_agreement_wait here overrides :attr:`~.Cluster.max_schema_agreement_wait`. Setting max_schema_agreement_wait <= 0 will bypass schema agreement and refresh schema immediately. An Exception is raised if schema refresh fails for any reason. """ if not self.control_connection.refresh_schema(schema_agreement_wait=max_schema_agreement_wait, force=True): raise DriverException("Schema metadata was not refreshed. See log for details.") def refresh_keyspace_metadata(self, keyspace, max_schema_agreement_wait=None): """ Synchronously refresh keyspace metadata. This applies to keyspace-level information such as replication and durability settings. It does not refresh tables, types, etc. contained in the keyspace. See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior """ if not self.control_connection.refresh_schema(target_type=SchemaTargetType.KEYSPACE, keyspace=keyspace, schema_agreement_wait=max_schema_agreement_wait, force=True): raise DriverException("Keyspace metadata was not refreshed. See log for details.") def refresh_table_metadata(self, keyspace, table, max_schema_agreement_wait=None): """ Synchronously refresh table metadata. This applies to a table, and any triggers or indexes attached to the table. See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior """ if not self.control_connection.refresh_schema(target_type=SchemaTargetType.TABLE, keyspace=keyspace, table=table, schema_agreement_wait=max_schema_agreement_wait, force=True): raise DriverException("Table metadata was not refreshed. See log for details.") def refresh_materialized_view_metadata(self, keyspace, view, max_schema_agreement_wait=None): """ Synchronously refresh materialized view metadata. See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior """ if not self.control_connection.refresh_schema(target_type=SchemaTargetType.TABLE, keyspace=keyspace, table=view, schema_agreement_wait=max_schema_agreement_wait, force=True): raise DriverException("View metadata was not refreshed. See log for details.") def refresh_user_type_metadata(self, keyspace, user_type, max_schema_agreement_wait=None): """ Synchronously refresh user defined type metadata. See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior """ if not self.control_connection.refresh_schema(target_type=SchemaTargetType.TYPE, keyspace=keyspace, type=user_type, schema_agreement_wait=max_schema_agreement_wait, force=True): raise DriverException("User Type metadata was not refreshed. See log for details.") def refresh_user_function_metadata(self, keyspace, function, max_schema_agreement_wait=None): """ Synchronously refresh user defined function metadata. ``function`` is a :class:`cassandra.UserFunctionDescriptor`. See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior """ if not self.control_connection.refresh_schema(target_type=SchemaTargetType.FUNCTION, keyspace=keyspace, function=function, schema_agreement_wait=max_schema_agreement_wait, force=True): raise DriverException("User Function metadata was not refreshed. See log for details.") def refresh_user_aggregate_metadata(self, keyspace, aggregate, max_schema_agreement_wait=None): """ Synchronously refresh user defined aggregate metadata. ``aggregate`` is a :class:`cassandra.UserAggregateDescriptor`. See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior """ if not self.control_connection.refresh_schema(target_type=SchemaTargetType.AGGREGATE, keyspace=keyspace, aggregate=aggregate, schema_agreement_wait=max_schema_agreement_wait, force=True): raise DriverException("User Aggregate metadata was not refreshed. See log for details.") def refresh_nodes(self, force_token_rebuild=False): """ Synchronously refresh the node list and token metadata `force_token_rebuild` can be used to rebuild the token map metadata, even if no new nodes are discovered. An Exception is raised if node refresh fails for any reason. """ if not self.control_connection.refresh_node_list_and_token_map(force_token_rebuild): raise DriverException("Node list was not refreshed. See log for details.") def set_meta_refresh_enabled(self, enabled): """ *Deprecated:* set :attr:`~.Cluster.schema_metadata_enabled` :attr:`~.Cluster.token_metadata_enabled` instead Sets a flag to enable (True) or disable (False) all metadata refresh queries. This applies to both schema and node topology. Disabling this is useful to minimize refreshes during multiple changes. Meta refresh must be enabled for the driver to become aware of any cluster topology changes or schema updates. """ warn("Cluster.set_meta_refresh_enabled is deprecated and will be removed in 4.0. Set " "Cluster.schema_metadata_enabled and Cluster.token_metadata_enabled instead.", DeprecationWarning) self.schema_metadata_enabled = enabled self.token_metadata_enabled = enabled @classmethod def _send_chunks(cls, connection, host, chunks, set_keyspace=False): for ks_chunk in chunks: messages = [PrepareMessage(query=s.query_string, keyspace=s.keyspace if set_keyspace else None) for s in ks_chunk] # TODO: make this timeout configurable somehow? responses = connection.wait_for_responses(*messages, timeout=5.0, fail_on_error=False) for success, response in responses: if not success: log.debug("Got unexpected response when preparing " "statement on host %s: %r", host, response) def _prepare_all_queries(self, host): if not self._prepared_statements or not self.reprepare_on_up: return log.debug("Preparing all known prepared statements against host %s", host) connection = None try: connection = self.connection_factory(host.endpoint) statements = list(self._prepared_statements.values()) if ProtocolVersion.uses_keyspace_flag(self.protocol_version): # V5 protocol and higher, no need to set the keyspace chunks = [] for i in range(0, len(statements), 10): chunks.append(statements[i:i + 10]) self._send_chunks(connection, host, chunks, True) else: for keyspace, ks_statements in groupby(statements, lambda s: s.keyspace): if keyspace is not None: connection.set_keyspace_blocking(keyspace) # prepare 10 statements at a time ks_statements = list(ks_statements) chunks = [] for i in range(0, len(ks_statements), 10): chunks.append(ks_statements[i:i + 10]) self._send_chunks(connection, host, chunks) log.debug("Done preparing all known prepared statements against host %s", host) except OperationTimedOut as timeout: log.warning("Timed out trying to prepare all statements on host %s: %s", host, timeout) except (ConnectionException, socket.error) as exc: log.warning("Error trying to prepare all statements on host %s: %r", host, exc) except Exception: log.exception("Error trying to prepare all statements on host %s", host) finally: if connection: connection.close() def add_prepared(self, query_id, prepared_statement): with self._prepared_statement_lock: self._prepared_statements[query_id] = prepared_statement class Session(object): """ A collection of connection pools for each host in the cluster. Instances of this class should not be created directly, only using :meth:`.Cluster.connect()`. Queries and statements can be executed through ``Session`` instances using the :meth:`~.Session.execute()` and :meth:`~.Session.execute_async()` methods. Example usage:: >>> session = cluster.connect() >>> session.set_keyspace("mykeyspace") >>> session.execute("SELECT * FROM mycf") """ cluster = None hosts = None keyspace = None is_shutdown = False + session_id = None + _monitor_reporter = None _row_factory = staticmethod(named_tuple_factory) @property def row_factory(self): """ The format to return row results in. By default, each returned row will be a named tuple. You can alternatively use any of the following: - :func:`cassandra.query.tuple_factory` - return a result row as a tuple - :func:`cassandra.query.named_tuple_factory` - return a result row as a named tuple - :func:`cassandra.query.dict_factory` - return a result row as a dict - :func:`cassandra.query.ordered_dict_factory` - return a result row as an OrderedDict """ return self._row_factory @row_factory.setter def row_factory(self, rf): self._validate_set_legacy_config('row_factory', rf) _default_timeout = 10.0 @property def default_timeout(self): """ A default timeout, measured in seconds, for queries executed through :meth:`.execute()` or :meth:`.execute_async()`. This default may be overridden with the `timeout` parameter for either of those methods. Setting this to :const:`None` will cause no timeouts to be set by default. Please see :meth:`.ResponseFuture.result` for details on the scope and effect of this timeout. .. versionadded:: 2.0.0 """ return self._default_timeout @default_timeout.setter def default_timeout(self, timeout): self._validate_set_legacy_config('default_timeout', timeout) _default_consistency_level = ConsistencyLevel.LOCAL_ONE @property def default_consistency_level(self): """ *Deprecated:* use execution profiles instead The default :class:`~ConsistencyLevel` for operations executed through this session. This default may be overridden by setting the :attr:`~.Statement.consistency_level` on individual statements. .. versionadded:: 1.2.0 .. versionchanged:: 3.0.0 default changed from ONE to LOCAL_ONE """ return self._default_consistency_level @default_consistency_level.setter def default_consistency_level(self, cl): """ *Deprecated:* use execution profiles instead """ warn("Setting the consistency level at the session level will be removed in 4.0. Consider using " "execution profiles and setting the desired consitency level to the EXEC_PROFILE_DEFAULT profile." , DeprecationWarning) self._validate_set_legacy_config('default_consistency_level', cl) _default_serial_consistency_level = None @property def default_serial_consistency_level(self): """ The default :class:`~ConsistencyLevel` for serial phase of conditional updates executed through this session. This default may be overridden by setting the :attr:`~.Statement.serial_consistency_level` on individual statements. Only valid for ``protocol_version >= 2``. """ return self._default_serial_consistency_level @default_serial_consistency_level.setter def default_serial_consistency_level(self, cl): if (cl is not None and not ConsistencyLevel.is_serial(cl)): raise ValueError("default_serial_consistency_level must be either " "ConsistencyLevel.SERIAL " "or ConsistencyLevel.LOCAL_SERIAL.") self._validate_set_legacy_config('default_serial_consistency_level', cl) max_trace_wait = 2.0 """ The maximum amount of time (in seconds) the driver will wait for trace details to be populated server-side for a query before giving up. If the `trace` parameter for :meth:`~.execute()` or :meth:`~.execute_async()` is :const:`True`, the driver will repeatedly attempt to fetch trace details for the query (using exponential backoff) until this limit is hit. If the limit is passed, an error will be logged and the :attr:`.Statement.trace` will be left as :const:`None`. """ default_fetch_size = 5000 """ By default, this many rows will be fetched at a time. Setting this to :const:`None` will disable automatic paging for large query results. The fetch size can be also specified per-query through :attr:`.Statement.fetch_size`. This only takes effect when protocol version 2 or higher is used. See :attr:`.Cluster.protocol_version` for details. .. versionadded:: 2.0.0 """ use_client_timestamp = True """ When using protocol version 3 or higher, write timestamps may be supplied client-side at the protocol level. (Normally they are generated server-side by the coordinator node.) Note that timestamps specified within a CQL query will override this timestamp. .. versionadded:: 2.1.0 """ timestamp_generator = None """ When :attr:`use_client_timestamp` is set, sessions call this object and use the result as the timestamp. (Note that timestamps specified within a CQL query will override this timestamp.) By default, a new :class:`~.MonotonicTimestampGenerator` is created for each :class:`Cluster` instance. Applications can set this value for custom timestamp behavior. For example, an application could share a timestamp generator across :class:`Cluster` objects to guarantee that the application will use unique, increasing timestamps across clusters, or set it to to ``lambda: int(time.time() * 1e6)`` if losing records over clock inconsistencies is acceptable for the application. Custom :attr:`timestamp_generator` s should be callable, and calling them should return an integer representing microseconds since some point in time, typically UNIX epoch. .. versionadded:: 3.8.0 """ encoder = None """ A :class:`~cassandra.encoder.Encoder` instance that will be used when formatting query parameters for non-prepared statements. This is not used for prepared statements (because prepared statements give the driver more information about what CQL types are expected, allowing it to accept a wider range of python types). The encoder uses a mapping from python types to encoder methods (for specific CQL types). This mapping can be be modified by users as they see fit. Methods of :class:`~cassandra.encoder.Encoder` should be used for mapping values if possible, because they take precautions to avoid injections and properly sanitize data. Example:: cluster = Cluster() session = cluster.connect("mykeyspace") session.encoder.mapping[tuple] = session.encoder.cql_encode_tuple session.execute("CREATE TABLE mytable (k int PRIMARY KEY, col tuple)") session.execute("INSERT INTO mytable (k, col) VALUES (%s, %s)", [0, (123, 'abc')]) .. versionadded:: 2.1.0 """ client_protocol_handler = ProtocolHandler """ Specifies a protocol handler that will be used for client-initiated requests (i.e. no internal driver requests). This can be used to override or extend features such as message or type ser/des. The default pure python implementation is :class:`cassandra.protocol.ProtocolHandler`. When compiled with Cython, there are also built-in faster alternatives. See :ref:`faster_deser` """ + session_id = None + """ + A UUID that uniquely identifies this Session to Insights. This will be + generated automatically. + """ + _lock = None _pools = None _profile_manager = None _metrics = None _request_init_callbacks = None + _graph_paging_available = False def __init__(self, cluster, hosts, keyspace=None): self.cluster = cluster self.hosts = hosts self.keyspace = keyspace self._lock = RLock() self._pools = {} self._profile_manager = cluster.profile_manager self._metrics = cluster.metrics self._request_init_callbacks = [] self._protocol_version = self.cluster.protocol_version self.encoder = Encoder() # create connection pools in parallel self._initial_connect_futures = set() for host in hosts: future = self.add_or_renew_pool(host, is_host_addition=False) if future: self._initial_connect_futures.add(future) futures = wait_futures(self._initial_connect_futures, return_when=FIRST_COMPLETED) while futures.not_done and not any(f.result() for f in futures.done): futures = wait_futures(futures.not_done, return_when=FIRST_COMPLETED) if not any(f.result() for f in self._initial_connect_futures): msg = "Unable to connect to any servers" if self.keyspace: msg += " using keyspace '%s'" % self.keyspace raise NoHostAvailable(msg, [h.address for h in hosts]) + self.session_id = uuid.uuid4() + self._graph_paging_available = self._check_graph_paging_available() + + if self.cluster.monitor_reporting_enabled: + cc_host = self.cluster.get_control_connection_host() + valid_insights_version = (cc_host and version_supports_insights(cc_host.dse_version)) + if valid_insights_version: + self._monitor_reporter = MonitorReporter( + interval_sec=self.cluster.monitor_reporting_interval, + session=self, + ) + else: + if cc_host: + log.debug('Not starting MonitorReporter thread for Insights; ' + 'not supported by server version {v} on ' + 'ControlConnection host {c}'.format(v=cc_host.release_version, c=cc_host)) + + log.debug('Started Session with client_id {} and session_id {}'.format(self.cluster.client_id, + self.session_id)) + def execute(self, query, parameters=None, timeout=_NOT_SET, trace=False, custom_payload=None, execution_profile=EXEC_PROFILE_DEFAULT, - paging_state=None, host=None): + paging_state=None, host=None, execute_as=None): """ Execute the given query and synchronously wait for the response. If an error is encountered while executing the query, an Exception will be raised. `query` may be a query string or an instance of :class:`cassandra.query.Statement`. `parameters` may be a sequence or dict of parameters to bind. If a sequence is used, ``%s`` should be used the placeholder for each argument. If a dict is used, ``%(name)s`` style placeholders must be used. `timeout` should specify a floating-point timeout (in seconds) after which an :exc:`.OperationTimedOut` exception will be raised if the query - has not completed. If not set, the timeout defaults to - :attr:`~.Session.default_timeout`. If set to :const:`None`, there is - no timeout. Please see :meth:`.ResponseFuture.result` for details on + has not completed. If not set, the timeout defaults to the request_timeout of the selected ``execution_profile``. + If set to :const:`None`, there is no timeout. Please see :meth:`.ResponseFuture.result` for details on the scope and effect of this timeout. If `trace` is set to :const:`True`, the query will be sent with tracing enabled. The trace details can be obtained using the returned :class:`.ResultSet` object. `custom_payload` is a :ref:`custom_payload` dict to be passed to the server. If `query` is a Statement with its own custom_payload. The message payload will be a union of the two, with the values specified here taking precedence. `execution_profile` is the execution profile to use for this request. It can be a key to a profile configured via :meth:`Cluster.add_execution_profile` or an instance (from :meth:`Session.execution_profile_clone_update`, for example `paging_state` is an optional paging state, reused from a previous :class:`ResultSet`. `host` is the :class:`cassandra.pool.Host` that should handle the query. If the host specified is down or not yet connected, the query will fail with :class:`NoHostAvailable`. Using this is discouraged except in a few cases, e.g., querying node-local tables and applying schema changes. + + `execute_as` the user that will be used on the server to execute the request. This is only available + on a DSE cluster. """ - return self.execute_async(query, parameters, trace, custom_payload, - timeout, execution_profile, paging_state, host).result() + + return self.execute_async(query, parameters, trace, custom_payload, timeout, execution_profile, paging_state, host, execute_as).result() def execute_async(self, query, parameters=None, trace=False, custom_payload=None, timeout=_NOT_SET, execution_profile=EXEC_PROFILE_DEFAULT, - paging_state=None, host=None): + paging_state=None, host=None, execute_as=None): """ Execute the given query and return a :class:`~.ResponseFuture` object which callbacks may be attached to for asynchronous response delivery. You may also call :meth:`~.ResponseFuture.result()` on the :class:`.ResponseFuture` to synchronously block for results at any time. See :meth:`Session.execute` for parameter definitions. Example usage:: >>> session = cluster.connect() >>> future = session.execute_async("SELECT * FROM mycf") >>> def log_results(results): ... for row in results: ... log.info("Results: %s", row) >>> def log_error(exc): >>> log.error("Operation failed: %s", exc) >>> future.add_callbacks(log_results, log_error) Async execution with blocking wait for results:: >>> future = session.execute_async("SELECT * FROM mycf") >>> # do other stuff... >>> try: ... results = future.result() ... except Exception: ... log.exception("Operation failed:") """ + custom_payload = custom_payload if custom_payload else {} + if execute_as: + custom_payload[_proxy_execute_key] = six.b(execute_as) + future = self._create_response_future( query, parameters, trace, custom_payload, timeout, execution_profile, paging_state, host) future._protocol_handler = self.client_protocol_handler self._on_request(future) future.send_request() return future + def execute_graph(self, query, parameters=None, trace=False, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT, execute_as=None): + """ + Executes a Gremlin query string or GraphStatement synchronously, + and returns a ResultSet from this execution. + + `parameters` is dict of named parameters to bind. The values must be + JSON-serializable. + + `execution_profile`: Selects an execution profile for the request. + + `execute_as` the user that will be used on the server to execute the request. + """ + return self.execute_graph_async(query, parameters, trace, execution_profile, execute_as).result() + + def execute_graph_async(self, query, parameters=None, trace=False, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT, execute_as=None): + """ + Execute the graph query and return a :class:`ResponseFuture` + object which callbacks may be attached to for asynchronous response delivery. You may also call ``ResponseFuture.result()`` to synchronously block for + results at any time. + """ + if self.cluster._config_mode is _ConfigMode.LEGACY: + raise ValueError(("Cannot execute graph queries using Cluster legacy parameters. " + "Consider using Execution profiles: " + "https://docs.datastax.com/en/developer/python-driver/latest/execution_profiles/#execution-profiles")) + + if not isinstance(query, GraphStatement): + query = SimpleGraphStatement(query) + + # Clone and look up instance here so we can resolve and apply the extended attributes + execution_profile = self.execution_profile_clone_update(execution_profile) + + if not hasattr(execution_profile, 'graph_options'): + raise ValueError( + "Execution profile for graph queries must derive from GraphExecutionProfile, and provide graph_options") + + self._resolve_execution_profile_options(execution_profile) + + # make sure the graphson context row factory is binded to this cluster + try: + if issubclass(execution_profile.row_factory, _GraphSONContextRowFactory): + execution_profile.row_factory = execution_profile.row_factory(self.cluster) + except TypeError: + # issubclass might fail if arg1 is an instance + pass + + # set graph paging if needed + self._maybe_set_graph_paging(execution_profile) + + graph_parameters = None + if parameters: + graph_parameters = self._transform_params(parameters, graph_options=execution_profile.graph_options) + + custom_payload = execution_profile.graph_options.get_options_map() + if execute_as: + custom_payload[_proxy_execute_key] = six.b(execute_as) + custom_payload[_request_timeout_key] = int64_pack(long(execution_profile.request_timeout * 1000)) + + future = self._create_response_future(query, parameters=None, trace=trace, custom_payload=custom_payload, + timeout=_NOT_SET, execution_profile=execution_profile) + + future.message.query_params = graph_parameters + future._protocol_handler = self.client_protocol_handler + + if execution_profile.graph_options.is_analytics_source and \ + isinstance(execution_profile.load_balancing_policy, DefaultLoadBalancingPolicy): + self._target_analytics_master(future) + else: + future.send_request() + return future + + def _maybe_set_graph_paging(self, execution_profile): + graph_paging = execution_profile.continuous_paging_options + if execution_profile.continuous_paging_options is _NOT_SET: + graph_paging = ContinuousPagingOptions() if self._graph_paging_available else None + + execution_profile.continuous_paging_options = graph_paging + + def _check_graph_paging_available(self): + """Verify if we can enable graph paging. This executed only once when the session is created.""" + + if not ProtocolVersion.has_continuous_paging_next_pages(self._protocol_version): + return False + + for host in self.cluster.metadata.all_hosts(): + if host.dse_version is None: + return False + + version = Version(host.dse_version) + if version < _GRAPH_PAGING_MIN_DSE_VERSION: + return False + + return True + + def _resolve_execution_profile_options(self, execution_profile): + """ + Determine the GraphSON protocol and row factory for a graph query. This is useful + to configure automatically the execution profile when executing a query on a + core graph. + + If `graph_protocol` is not explicitly specified, the following rules apply: + - Default to GraphProtocol.GRAPHSON_1_0, or GRAPHSON_2_0 if the `graph_language` is not gremlin-groovy. + - If `graph_options.graph_name` is specified and is a Core graph, set GraphSON_3_0. + If `row_factory` is not explicitly specified, the following rules apply: + - Default to graph_object_row_factory. + - If `graph_options.graph_name` is specified and is a Core graph, set graph_graphson3_row_factory. + """ + if execution_profile.graph_options.graph_protocol is not None and \ + execution_profile.row_factory is not None: + return + + graph_options = execution_profile.graph_options + + is_core_graph = False + if graph_options.graph_name: + # graph_options.graph_name is bytes ... + name = graph_options.graph_name.decode('utf-8') + if name in self.cluster.metadata.keyspaces: + ks_metadata = self.cluster.metadata.keyspaces[name] + if ks_metadata.graph_engine == 'Core': + is_core_graph = True + + if is_core_graph: + graph_protocol = GraphProtocol.GRAPHSON_3_0 + row_factory = graph_graphson3_row_factory + else: + if graph_options.graph_language == GraphOptions.DEFAULT_GRAPH_LANGUAGE: + graph_protocol = GraphOptions.DEFAULT_GRAPH_PROTOCOL + row_factory = graph_object_row_factory + else: + # if not gremlin-groovy, GraphSON_2_0 + graph_protocol = GraphProtocol.GRAPHSON_2_0 + row_factory = graph_graphson2_row_factory + + # Only apply if not set explicitly + if graph_options.graph_protocol is None: + graph_options.graph_protocol = graph_protocol + if execution_profile.row_factory is None: + execution_profile.row_factory = row_factory + + def _transform_params(self, parameters, graph_options): + if not isinstance(parameters, dict): + raise ValueError('The parameters must be a dictionary. Unnamed parameters are not allowed.') + + # Serialize python types to graphson + serializer = GraphSON1Serializer + if graph_options.graph_protocol == GraphProtocol.GRAPHSON_2_0: + serializer = GraphSON2Serializer() + elif graph_options.graph_protocol == GraphProtocol.GRAPHSON_3_0: + # only required for core graphs + context = { + 'cluster': self.cluster, + 'graph_name': graph_options.graph_name.decode('utf-8') if graph_options.graph_name else None + } + serializer = GraphSON3Serializer(context) + + serialized_parameters = serializer.serialize(parameters) + return [json.dumps(serialized_parameters).encode('utf-8')] + + def _target_analytics_master(self, future): + future._start_timer() + master_query_future = self._create_response_future("CALL DseClientTool.getAnalyticsGraphServer()", + parameters=None, trace=False, + custom_payload=None, timeout=future.timeout) + master_query_future.row_factory = tuple_factory + master_query_future.send_request() + + cb = self._on_analytics_master_result + args = (master_query_future, future) + master_query_future.add_callbacks(callback=cb, callback_args=args, errback=cb, errback_args=args) + + def _on_analytics_master_result(self, response, master_future, query_future): + try: + row = master_future.result()[0] + addr = row[0]['location'] + delimiter_index = addr.rfind(':') # assumes : - not robust, but that's what is being provided + if delimiter_index > 0: + addr = addr[:delimiter_index] + targeted_query = HostTargetingStatement(query_future.query, addr) + query_future.query_plan = query_future._load_balancer.make_query_plan(self.keyspace, targeted_query) + except Exception: + log.debug("Failed querying analytics master (request might not be routed optimally). " + "Make sure the session is connecting to a graph analytics datacenter.", exc_info=True) + + self.submit(query_future.send_request) + def _create_response_future(self, query, parameters, trace, custom_payload, timeout, execution_profile=EXEC_PROFILE_DEFAULT, paging_state=None, host=None): """ Returns the ResponseFuture before calling send_request() on it """ prepared_statement = None if isinstance(query, six.string_types): query = SimpleStatement(query) elif isinstance(query, PreparedStatement): query = query.bind(parameters) if self.cluster._config_mode == _ConfigMode.LEGACY: if execution_profile is not EXEC_PROFILE_DEFAULT: raise ValueError("Cannot specify execution_profile while using legacy parameters.") if timeout is _NOT_SET: timeout = self.default_timeout cl = query.consistency_level if query.consistency_level is not None else self.default_consistency_level serial_cl = query.serial_consistency_level if query.serial_consistency_level is not None else self.default_serial_consistency_level retry_policy = query.retry_policy or self.cluster.default_retry_policy row_factory = self.row_factory load_balancing_policy = self.cluster.load_balancing_policy spec_exec_policy = None + continuous_paging_options = None else: execution_profile = self._maybe_get_execution_profile(execution_profile) if timeout is _NOT_SET: timeout = execution_profile.request_timeout cl = query.consistency_level if query.consistency_level is not None else execution_profile.consistency_level serial_cl = query.serial_consistency_level if query.serial_consistency_level is not None else execution_profile.serial_consistency_level + continuous_paging_options = execution_profile.continuous_paging_options retry_policy = query.retry_policy or execution_profile.retry_policy row_factory = execution_profile.row_factory load_balancing_policy = execution_profile.load_balancing_policy spec_exec_policy = execution_profile.speculative_execution_policy fetch_size = query.fetch_size if fetch_size is FETCH_SIZE_UNSET and self._protocol_version >= 2: fetch_size = self.default_fetch_size elif self._protocol_version == 1: fetch_size = None start_time = time.time() if self._protocol_version >= 3 and self.use_client_timestamp: timestamp = self.cluster.timestamp_generator() else: timestamp = None + supports_continuous_paging_state = ( + ProtocolVersion.has_continuous_paging_next_pages(self._protocol_version) + ) + if continuous_paging_options and supports_continuous_paging_state: + continuous_paging_state = ContinuousPagingState(continuous_paging_options.max_queue_size) + else: + continuous_paging_state = None + if isinstance(query, SimpleStatement): query_string = query.query_string statement_keyspace = query.keyspace if ProtocolVersion.uses_keyspace_flag(self._protocol_version) else None if parameters: query_string = bind_params(query_string, parameters, self.encoder) message = QueryMessage( query_string, cl, serial_cl, - fetch_size, timestamp=timestamp, - keyspace=statement_keyspace) + fetch_size, paging_state, timestamp, + continuous_paging_options, statement_keyspace) elif isinstance(query, BoundStatement): prepared_statement = query.prepared_statement message = ExecuteMessage( prepared_statement.query_id, query.values, cl, - serial_cl, fetch_size, - timestamp=timestamp, skip_meta=bool(prepared_statement.result_metadata), + serial_cl, fetch_size, paging_state, timestamp, + skip_meta=bool(prepared_statement.result_metadata), + continuous_paging_options=continuous_paging_options, result_metadata_id=prepared_statement.result_metadata_id) elif isinstance(query, BatchStatement): if self._protocol_version < 2: raise UnsupportedOperation( "BatchStatement execution is only supported with protocol version " "2 or higher (supported in Cassandra 2.0 and higher). Consider " "setting Cluster.protocol_version to 2 to support this operation.") statement_keyspace = query.keyspace if ProtocolVersion.uses_keyspace_flag(self._protocol_version) else None message = BatchMessage( query.batch_type, query._statements_and_parameters, cl, serial_cl, timestamp, statement_keyspace) + elif isinstance(query, GraphStatement): + # the statement_keyspace is not aplicable to GraphStatement + message = QueryMessage(query.query, cl, serial_cl, fetch_size, + paging_state, timestamp, + continuous_paging_options) message.tracing = trace - message.update_custom_payload(query.custom_payload) message.update_custom_payload(custom_payload) message.allow_beta_protocol_version = self.cluster.allow_beta_protocol_version - message.paging_state = paging_state spec_exec_plan = spec_exec_policy.new_plan(query.keyspace or self.keyspace, query) if query.is_idempotent and spec_exec_policy else None return ResponseFuture( self, message, query, timeout, metrics=self._metrics, prepared_statement=prepared_statement, retry_policy=retry_policy, row_factory=row_factory, load_balancer=load_balancing_policy, start_time=start_time, speculative_execution_plan=spec_exec_plan, - host=host) + continuous_paging_state=continuous_paging_state, host=host) def get_execution_profile(self, name): """ Returns the execution profile associated with the provided ``name``. :param name: The name (or key) of the execution profile. """ profiles = self.cluster.profile_manager.profiles try: return profiles[name] except KeyError: eps = [_execution_profile_to_string(ep) for ep in profiles.keys()] raise ValueError("Invalid execution_profile: %s; valid profiles are: %s." % ( _execution_profile_to_string(name), ', '.join(eps))) def _maybe_get_execution_profile(self, ep): return ep if isinstance(ep, ExecutionProfile) else self.get_execution_profile(ep) def execution_profile_clone_update(self, ep, **kwargs): """ Returns a clone of the ``ep`` profile. ``kwargs`` can be specified to update attributes of the returned profile. This is a shallow clone, so any objects referenced by the profile are shared. This means Load Balancing Policy is maintained by inclusion in the active profiles. It also means updating any other rich objects will be seen by the active profile. In cases where this is not desirable, be sure to replace the instance instead of manipulating the shared object. """ clone = copy(self._maybe_get_execution_profile(ep)) for attr, value in kwargs.items(): setattr(clone, attr, value) return clone def add_request_init_listener(self, fn, *args, **kwargs): """ Adds a callback with arguments to be called when any request is created. It will be invoked as `fn(response_future, *args, **kwargs)` after each client request is created, and before the request is sent. This can be used to create extensions by adding result callbacks to the response future. `response_future` is the :class:`.ResponseFuture` for the request. Note that the init callback is done on the client thread creating the request, so you may need to consider synchronization if you have multiple threads. Any callbacks added to the response future will be executed on the event loop thread, so the normal advice about minimizing cycles and avoiding blocking apply (see Note in :meth:`.ResponseFuture.add_callbacks`. See `this example `_ in the source tree for an example. """ self._request_init_callbacks.append((fn, args, kwargs)) def remove_request_init_listener(self, fn, *args, **kwargs): """ Removes a callback and arguments from the list. See :meth:`.Session.add_request_init_listener`. """ self._request_init_callbacks.remove((fn, args, kwargs)) def _on_request(self, response_future): for fn, args, kwargs in self._request_init_callbacks: fn(response_future, *args, **kwargs) def prepare(self, query, custom_payload=None, keyspace=None): """ Prepares a query string, returning a :class:`~cassandra.query.PreparedStatement` instance which can be used as follows:: >>> session = cluster.connect("mykeyspace") >>> query = "INSERT INTO users (id, name, age) VALUES (?, ?, ?)" >>> prepared = session.prepare(query) >>> session.execute(prepared, (user.id, user.name, user.age)) Or you may bind values to the prepared statement ahead of time:: >>> prepared = session.prepare(query) >>> bound_stmt = prepared.bind((user.id, user.name, user.age)) >>> session.execute(bound_stmt) Of course, prepared statements may (and should) be reused:: >>> prepared = session.prepare(query) >>> for user in users: ... bound = prepared.bind((user.id, user.name, user.age)) ... session.execute(bound) Alternatively, if :attr:`~.Cluster.protocol_version` is 5 or higher (requires Cassandra 4.0+), the keyspace can be specified as a parameter. This will allow you to avoid specifying the keyspace in the query without specifying a keyspace in :meth:`~.Cluster.connect`. It even will let you prepare and use statements against a keyspace other than the one originally specified on connection: >>> analyticskeyspace_prepared = session.prepare( ... "INSERT INTO user_activity id, last_activity VALUES (?, ?)", ... keyspace="analyticskeyspace") # note the different keyspace **Important**: PreparedStatements should be prepared only once. Preparing the same query more than once will likely affect performance. `custom_payload` is a key value map to be passed along with the prepare message. See :ref:`custom_payload`. """ message = PrepareMessage(query=query, keyspace=keyspace) future = ResponseFuture(self, message, query=None, timeout=self.default_timeout) try: future.send_request() - query_id, bind_metadata, pk_indexes, result_metadata, result_metadata_id = future.result() + response = future.result().one() except Exception: log.exception("Error preparing query:") raise prepared_keyspace = keyspace if keyspace else None prepared_statement = PreparedStatement.from_message( - query_id, bind_metadata, pk_indexes, self.cluster.metadata, query, self.keyspace, - self._protocol_version, result_metadata, result_metadata_id) + response.query_id, response.bind_metadata, response.pk_indexes, self.cluster.metadata, query, prepared_keyspace, + self._protocol_version, response.column_metadata, response.result_metadata_id) prepared_statement.custom_payload = future.custom_payload - self.cluster.add_prepared(query_id, prepared_statement) + self.cluster.add_prepared(response.query_id, prepared_statement) if self.cluster.prepare_on_all_hosts: host = future._current_host try: self.prepare_on_all_hosts(prepared_statement.query_string, host, prepared_keyspace) except Exception: log.exception("Error preparing query on all hosts:") return prepared_statement def prepare_on_all_hosts(self, query, excluded_host, keyspace=None): """ Prepare the given query on all hosts, excluding ``excluded_host``. Intended for internal use only. """ futures = [] for host in tuple(self._pools.keys()): if host != excluded_host and host.is_up: future = ResponseFuture(self, PrepareMessage(query=query, keyspace=keyspace), None, self.default_timeout) # we don't care about errors preparing against specific hosts, # since we can always prepare them as needed when the prepared # statement is used. Just log errors and continue on. try: request_id = future._query(host) except Exception: log.exception("Error preparing query for host %s:", host) continue if request_id is None: # the error has already been logged by ResponsFuture log.debug("Failed to prepare query for host %s: %r", host, future._errors.get(host)) continue futures.append((host, future)) for host, future in futures: try: future.result() except Exception: log.exception("Error preparing query for host %s:", host) def shutdown(self): """ Close all connections. ``Session`` instances should not be used for any purpose after being shutdown. """ with self._lock: if self.is_shutdown: return else: self.is_shutdown = True # PYTHON-673. If shutdown was called shortly after session init, avoid # a race by cancelling any initial connection attempts haven't started, # then blocking on any that have. for future in self._initial_connect_futures: future.cancel() wait_futures(self._initial_connect_futures) + if self._monitor_reporter: + self._monitor_reporter.stop() + for pool in tuple(self._pools.values()): pool.shutdown() def __enter__(self): return self def __exit__(self, *args): self.shutdown() def __del__(self): try: # Ensure all connections are closed, in case the Session object is deleted by the GC self.shutdown() except: # Ignore all errors. Shutdown errors can be caught by the user # when cluster.shutdown() is called explicitly. pass def add_or_renew_pool(self, host, is_host_addition): """ For internal use only. """ distance = self._profile_manager.distance(host) if distance == HostDistance.IGNORED: return None def run_add_or_renew_pool(): try: if self._protocol_version >= 3: new_pool = HostConnection(host, distance, self) else: # TODO remove host pool again ??? new_pool = HostConnectionPool(host, distance, self) except AuthenticationFailed as auth_exc: conn_exc = ConnectionException(str(auth_exc), endpoint=host) self.cluster.signal_connection_failure(host, conn_exc, is_host_addition) return False except Exception as conn_exc: log.warning("Failed to create connection pool for new host %s:", host, exc_info=conn_exc) # the host itself will still be marked down, so we need to pass # a special flag to make sure the reconnector is created self.cluster.signal_connection_failure( host, conn_exc, is_host_addition, expect_host_to_be_down=True) return False previous = self._pools.get(host) with self._lock: while new_pool._keyspace != self.keyspace: self._lock.release() set_keyspace_event = Event() errors_returned = [] def callback(pool, errors): errors_returned.extend(errors) set_keyspace_event.set() new_pool._set_keyspace_for_all_conns(self.keyspace, callback) set_keyspace_event.wait(self.cluster.connect_timeout) if not set_keyspace_event.is_set() or errors_returned: log.warning("Failed setting keyspace for pool after keyspace changed during connect: %s", errors_returned) self.cluster.on_down(host, is_host_addition) new_pool.shutdown() self._lock.acquire() return False self._lock.acquire() self._pools[host] = new_pool log.debug("Added pool for host %s to session", host) if previous: previous.shutdown() return True return self.submit(run_add_or_renew_pool) def remove_pool(self, host): pool = self._pools.pop(host, None) if pool: log.debug("Removed connection pool for %r", host) return self.submit(pool.shutdown) else: return None def update_created_pools(self): """ When the set of live nodes change, the loadbalancer will change its mind on host distances. It might change it on the node that came/left but also on other nodes (for instance, if a node dies, another previously ignored node may be now considered). This method ensures that all hosts for which a pool should exist have one, and hosts that shouldn't don't. For internal use only. """ futures = set() for host in self.cluster.metadata.all_hosts(): distance = self._profile_manager.distance(host) pool = self._pools.get(host) future = None if not pool or pool.is_shutdown: # we don't eagerly set is_up on previously ignored hosts. None is included here # to allow us to attempt connections to hosts that have gone from ignored to something # else. if distance != HostDistance.IGNORED and host.is_up in (True, None): future = self.add_or_renew_pool(host, False) elif distance != pool.host_distance: # the distance has changed if distance == HostDistance.IGNORED: future = self.remove_pool(host) else: pool.host_distance = distance if future: futures.add(future) return futures def on_down(self, host): """ Called by the parent Cluster instance when a node is marked down. Only intended for internal use. """ future = self.remove_pool(host) if future: future.add_done_callback(lambda f: self.update_created_pools()) def on_remove(self, host): """ Internal """ self.on_down(host) def set_keyspace(self, keyspace): """ Set the default keyspace for all queries made through this Session. This operation blocks until complete. """ self.execute('USE %s' % (protect_name(keyspace),)) def _set_keyspace_for_all_pools(self, keyspace, callback): """ Asynchronously sets the keyspace on all pools. When all pools have set all of their connections, `callback` will be called with a dictionary of all errors that occurred, keyed by the `Host` that they occurred against. """ with self._lock: self.keyspace = keyspace remaining_callbacks = set(self._pools.values()) errors = {} if not remaining_callbacks: callback(errors) return def pool_finished_setting_keyspace(pool, host_errors): remaining_callbacks.remove(pool) if host_errors: errors[pool.host] = host_errors if not remaining_callbacks: callback(host_errors) for pool in tuple(self._pools.values()): pool._set_keyspace_for_all_conns(keyspace, pool_finished_setting_keyspace) def user_type_registered(self, keyspace, user_type, klass): """ Called by the parent Cluster instance when the user registers a new mapping from a user-defined type to a class. Intended for internal use only. """ try: ks_meta = self.cluster.metadata.keyspaces[keyspace] except KeyError: raise UserTypeDoesNotExist( 'Keyspace %s does not exist or has not been discovered by the driver' % (keyspace,)) try: type_meta = ks_meta.user_types[user_type] except KeyError: raise UserTypeDoesNotExist( 'User type %s does not exist in keyspace %s' % (user_type, keyspace)) field_names = type_meta.field_names if six.PY2: # go from unicode to string to avoid decode errors from implicit # decode when formatting non-ascii values field_names = [fn.encode('utf-8') for fn in field_names] def encode(val): return '{ %s }' % ' , '.join('%s : %s' % ( field_name, self.encoder.cql_encode_all_types(getattr(val, field_name, None)) ) for field_name in field_names) self.encoder.mapping[klass] = encode def submit(self, fn, *args, **kwargs): """ Internal """ if not self.is_shutdown: return self.cluster.executor.submit(fn, *args, **kwargs) def get_pool_state(self): return dict((host, pool.get_state()) for host, pool in tuple(self._pools.items())) def get_pools(self): return self._pools.values() def _validate_set_legacy_config(self, attr_name, value): if self.cluster._config_mode == _ConfigMode.PROFILES: raise ValueError("Cannot set Session.%s while using Configuration Profiles. Set this in a profile instead." % (attr_name,)) setattr(self, '_' + attr_name, value) self.cluster._config_mode = _ConfigMode.LEGACY class UserTypeDoesNotExist(Exception): """ An attempt was made to use a user-defined type that does not exist. .. versionadded:: 2.1.0 """ pass class _ControlReconnectionHandler(_ReconnectionHandler): """ Internal """ def __init__(self, control_connection, *args, **kwargs): _ReconnectionHandler.__init__(self, *args, **kwargs) self.control_connection = weakref.proxy(control_connection) def try_reconnect(self): return self.control_connection._reconnect_internal() def on_reconnection(self, connection): self.control_connection._set_new_connection(connection) def on_exception(self, exc, next_delay): # TODO only overridden to add logging, so add logging if isinstance(exc, AuthenticationFailed): return False else: log.debug("Error trying to reconnect control connection: %r", exc) return True def _watch_callback(obj_weakref, method_name, *args, **kwargs): """ A callback handler for the ControlConnection that tolerates weak references. """ obj = obj_weakref() if obj is None: return getattr(obj, method_name)(*args, **kwargs) def _clear_watcher(conn, expiring_weakref): """ Called when the ControlConnection object is about to be finalized. This clears watchers on the underlying Connection object. """ try: conn.control_conn_disposed() except ReferenceError: pass class ControlConnection(object): """ Internal """ _SELECT_PEERS = "SELECT * FROM system.peers" - _SELECT_PEERS_NO_TOKENS = "SELECT host_id, peer, data_center, rack, rpc_address, release_version, schema_version FROM system.peers" + _SELECT_PEERS_NO_TOKENS_TEMPLATE = "SELECT host_id, peer, data_center, rack, rpc_address, {nt_col_name}, release_version, schema_version FROM system.peers" _SELECT_LOCAL = "SELECT * FROM system.local WHERE key='local'" _SELECT_LOCAL_NO_TOKENS = "SELECT host_id, cluster_name, data_center, rack, partitioner, release_version, schema_version FROM system.local WHERE key='local'" # Used only when token_metadata_enabled is set to False _SELECT_LOCAL_NO_TOKENS_RPC_ADDRESS = "SELECT rpc_address FROM system.local WHERE key='local'" - _SELECT_SCHEMA_PEERS = "SELECT peer, host_id, rpc_address, schema_version FROM system.peers" + _SELECT_SCHEMA_PEERS_TEMPLATE = "SELECT peer, host_id, {nt_col_name}, schema_version FROM system.peers" _SELECT_SCHEMA_LOCAL = "SELECT schema_version FROM system.local WHERE key='local'" + _SELECT_PEERS_V2 = "SELECT * FROM system.peers_v2" + _SELECT_PEERS_NO_TOKENS_V2 = "SELECT host_id, peer, peer_port, data_center, rack, native_address, native_port, release_version, schema_version FROM system.peers_v2" + _SELECT_SCHEMA_PEERS_V2 = "SELECT host_id, peer, peer_port, native_address, native_port, schema_version FROM system.peers_v2" + + _MINIMUM_NATIVE_ADDRESS_DSE_VERSION = Version("6.0.0") + + class PeersQueryType(object): + """internal Enum for _peers_query""" + PEERS = 0 + PEERS_SCHEMA = 1 + _is_shutdown = False _timeout = None _protocol_version = None _schema_event_refresh_window = None _topology_event_refresh_window = None _status_event_refresh_window = None _schema_meta_enabled = True _token_meta_enabled = True + _uses_peers_v2 = True + # for testing purposes _time = time def __init__(self, cluster, timeout, schema_event_refresh_window, topology_event_refresh_window, status_event_refresh_window, schema_meta_enabled=True, token_meta_enabled=True): # use a weak reference to allow the Cluster instance to be GC'ed (and # shutdown) since implementing __del__ disables the cycle detector self._cluster = weakref.proxy(cluster) self._connection = None self._timeout = timeout self._schema_event_refresh_window = schema_event_refresh_window self._topology_event_refresh_window = topology_event_refresh_window self._status_event_refresh_window = status_event_refresh_window self._schema_meta_enabled = schema_meta_enabled self._token_meta_enabled = token_meta_enabled self._lock = RLock() self._schema_agreement_lock = Lock() self._reconnection_handler = None self._reconnection_lock = RLock() self._event_schedule_times = {} def connect(self): if self._is_shutdown: return self._protocol_version = self._cluster.protocol_version self._set_new_connection(self._reconnect_internal()) - self._cluster.metadata.dbaas = self._connection._product_type == dscloud.PRODUCT_APOLLO + self._cluster.metadata.dbaas = self._connection._product_type == dscloud.DATASTAX_CLOUD_PRODUCT_TYPE def _set_new_connection(self, conn): """ Replace existing connection (if there is one) and close it. """ with self._lock: old = self._connection self._connection = conn if old: log.debug("[control connection] Closing old connection %r, replacing with %r", old, conn) old.close() def _reconnect_internal(self): """ Tries to connect to each host in the query plan until one succeeds or every attempt fails. If successful, a new Connection will be returned. Otherwise, :exc:`NoHostAvailable` will be raised with an "errors" arg that is a dict mapping host addresses to the exception that was raised when an attempt was made to open a connection to that host. """ errors = {} lbp = ( self._cluster.load_balancing_policy if self._cluster._config_mode == _ConfigMode.LEGACY else self._cluster._default_load_balancing_policy ) for host in lbp.make_query_plan(): try: return self._try_connect(host) except ConnectionException as exc: errors[str(host.endpoint)] = exc log.warning("[control connection] Error connecting to %s:", host, exc_info=True) self._cluster.signal_connection_failure(host, exc, is_host_addition=False) except Exception as exc: errors[str(host.endpoint)] = exc log.warning("[control connection] Error connecting to %s:", host, exc_info=True) if self._is_shutdown: raise DriverException("[control connection] Reconnection in progress during shutdown") raise NoHostAvailable("Unable to connect to any servers", errors) def _try_connect(self, host): """ Creates a new Connection, registers for pushed events, and refreshes node/token and schema metadata. """ log.debug("[control connection] Opening new connection to %s", host) while True: try: connection = self._cluster.connection_factory(host.endpoint, is_control_connection=True) if self._is_shutdown: connection.close() raise DriverException("Reconnecting during shutdown") break except ProtocolVersionUnsupported as e: self._cluster.protocol_downgrade(host.endpoint, e.startup_version) + except ProtocolException as e: + # protocol v5 is out of beta in C* >=4.0-beta5 and is now the default driver + # protocol version. If the protocol version was not explicitly specified, + # and that the server raises a beta protocol error, we should downgrade. + if not self._cluster._protocol_version_explicit and e.is_beta_protocol_error: + self._cluster.protocol_downgrade(host.endpoint, self._cluster.protocol_version) + else: + raise log.debug("[control connection] Established new connection %r, " "registering watchers and refreshing schema and topology", connection) # use weak references in both directions # _clear_watcher will be called when this ControlConnection is about to be finalized # _watch_callback will get the actual callback from the Connection and relay it to # this object (after a dereferencing a weakref) self_weakref = weakref.ref(self, partial(_clear_watcher, weakref.proxy(connection))) try: connection.register_watchers({ "TOPOLOGY_CHANGE": partial(_watch_callback, self_weakref, '_handle_topology_change'), "STATUS_CHANGE": partial(_watch_callback, self_weakref, '_handle_status_change'), "SCHEMA_CHANGE": partial(_watch_callback, self_weakref, '_handle_schema_change') }, register_timeout=self._timeout) - sel_peers = self._SELECT_PEERS if self._token_meta_enabled else self._SELECT_PEERS_NO_TOKENS + sel_peers = self._get_peers_query(self.PeersQueryType.PEERS, connection) sel_local = self._SELECT_LOCAL if self._token_meta_enabled else self._SELECT_LOCAL_NO_TOKENS peers_query = QueryMessage(query=sel_peers, consistency_level=ConsistencyLevel.ONE) local_query = QueryMessage(query=sel_local, consistency_level=ConsistencyLevel.ONE) - shared_results = connection.wait_for_responses( - peers_query, local_query, timeout=self._timeout) + (peers_success, peers_result), (local_success, local_result) = connection.wait_for_responses( + peers_query, local_query, timeout=self._timeout, fail_on_error=False) + + if not local_success: + raise local_result + + if not peers_success: + # error with the peers v2 query, fallback to peers v1 + self._uses_peers_v2 = False + sel_peers = self._get_peers_query(self.PeersQueryType.PEERS, connection) + peers_query = QueryMessage(query=sel_peers, consistency_level=ConsistencyLevel.ONE) + peers_result = connection.wait_for_response( + peers_query, timeout=self._timeout) + shared_results = (peers_result, local_result) self._refresh_node_list_and_token_map(connection, preloaded_results=shared_results) self._refresh_schema(connection, preloaded_results=shared_results, schema_agreement_wait=-1) except Exception: connection.close() raise return connection def reconnect(self): if self._is_shutdown: return self._submit(self._reconnect) def _reconnect(self): log.debug("[control connection] Attempting to reconnect") try: self._set_new_connection(self._reconnect_internal()) except NoHostAvailable: # make a retry schedule (which includes backoff) schedule = self._cluster.reconnection_policy.new_schedule() with self._reconnection_lock: # cancel existing reconnection attempts if self._reconnection_handler: self._reconnection_handler.cancel() # when a connection is successfully made, _set_new_connection # will be called with the new connection and then our # _reconnection_handler will be cleared out self._reconnection_handler = _ControlReconnectionHandler( self, self._cluster.scheduler, schedule, self._get_and_set_reconnection_handler, new_handler=None) self._reconnection_handler.start() except Exception: log.debug("[control connection] error reconnecting", exc_info=True) raise def _get_and_set_reconnection_handler(self, new_handler): """ Called by the _ControlReconnectionHandler when a new connection is successfully created. Clears out the _reconnection_handler on this ControlConnection. """ with self._reconnection_lock: old = self._reconnection_handler self._reconnection_handler = new_handler return old def _submit(self, *args, **kwargs): try: if not self._cluster.is_shutdown: return self._cluster.executor.submit(*args, **kwargs) except ReferenceError: pass return None def shutdown(self): # stop trying to reconnect (if we are) with self._reconnection_lock: if self._reconnection_handler: self._reconnection_handler.cancel() with self._lock: if self._is_shutdown: return else: self._is_shutdown = True log.debug("Shutting down control connection") if self._connection: self._connection.close() self._connection = None def refresh_schema(self, force=False, **kwargs): try: if self._connection: return self._refresh_schema(self._connection, force=force, **kwargs) except ReferenceError: pass # our weak reference to the Cluster is no good except Exception: log.debug("[control connection] Error refreshing schema", exc_info=True) self._signal_error() return False def _refresh_schema(self, connection, preloaded_results=None, schema_agreement_wait=None, force=False, **kwargs): if self._cluster.is_shutdown: return False agreed = self.wait_for_schema_agreement(connection, preloaded_results=preloaded_results, wait_time=schema_agreement_wait) if not self._schema_meta_enabled and not force: log.debug("[control connection] Skipping schema refresh because schema metadata is disabled") return False if not agreed: log.debug("Skipping schema refresh due to lack of schema agreement") return False self._cluster.metadata.refresh(connection, self._timeout, **kwargs) return True def refresh_node_list_and_token_map(self, force_token_rebuild=False): try: if self._connection: self._refresh_node_list_and_token_map(self._connection, force_token_rebuild=force_token_rebuild) return True except ReferenceError: pass # our weak reference to the Cluster is no good except Exception: log.debug("[control connection] Error refreshing node list and token map", exc_info=True) self._signal_error() return False def _refresh_node_list_and_token_map(self, connection, preloaded_results=None, force_token_rebuild=False): - if preloaded_results: log.debug("[control connection] Refreshing node list and token map using preloaded results") peers_result = preloaded_results[0] local_result = preloaded_results[1] else: cl = ConsistencyLevel.ONE + sel_peers = self._get_peers_query(self.PeersQueryType.PEERS, connection) if not self._token_meta_enabled: log.debug("[control connection] Refreshing node list without token map") - sel_peers = self._SELECT_PEERS_NO_TOKENS sel_local = self._SELECT_LOCAL_NO_TOKENS else: log.debug("[control connection] Refreshing node list and token map") - sel_peers = self._SELECT_PEERS sel_local = self._SELECT_LOCAL peers_query = QueryMessage(query=sel_peers, consistency_level=cl) local_query = QueryMessage(query=sel_local, consistency_level=cl) peers_result, local_result = connection.wait_for_responses( peers_query, local_query, timeout=self._timeout) - peers_result = dict_factory(*peers_result.results) + peers_result = dict_factory(peers_result.column_names, peers_result.parsed_rows) partitioner = None token_map = {} found_hosts = set() - if local_result.results: + if local_result.parsed_rows: found_hosts.add(connection.endpoint) - local_rows = dict_factory(*(local_result.results)) + local_rows = dict_factory(local_result.column_names, local_result.parsed_rows) local_row = local_rows[0] cluster_name = local_row["cluster_name"] self._cluster.metadata.cluster_name = cluster_name partitioner = local_row.get("partitioner") tokens = local_row.get("tokens") host = self._cluster.metadata.get_host(connection.endpoint) if host: datacenter = local_row.get("data_center") rack = local_row.get("rack") self._update_location_info(host, datacenter, rack) host.host_id = local_row.get("host_id") host.listen_address = local_row.get("listen_address") - host.broadcast_address = local_row.get("broadcast_address") + host.listen_port = local_row.get("listen_port") + host.broadcast_address = _NodeInfo.get_broadcast_address(local_row) + host.broadcast_port = _NodeInfo.get_broadcast_port(local_row) - host.broadcast_rpc_address = self._address_from_row(local_row) + host.broadcast_rpc_address = _NodeInfo.get_broadcast_rpc_address(local_row) + host.broadcast_rpc_port = _NodeInfo.get_broadcast_rpc_port(local_row) if host.broadcast_rpc_address is None: if self._token_meta_enabled: # local rpc_address is not available, use the connection endpoint host.broadcast_rpc_address = connection.endpoint.address + host.broadcast_rpc_port = connection.endpoint.port else: # local rpc_address has not been queried yet, try to fetch it # separately, which might fail because C* < 2.1.6 doesn't have rpc_address # in system.local. See CASSANDRA-9436. local_rpc_address_query = QueryMessage(query=self._SELECT_LOCAL_NO_TOKENS_RPC_ADDRESS, consistency_level=ConsistencyLevel.ONE) success, local_rpc_address_result = connection.wait_for_response( local_rpc_address_query, timeout=self._timeout, fail_on_error=False) if success: - row = dict_factory(*local_rpc_address_result.results) - host.broadcast_rpc_address = row[0]['rpc_address'] + row = dict_factory( + local_rpc_address_result.column_names, + local_rpc_address_result.parsed_rows) + host.broadcast_rpc_address = _NodeInfo.get_broadcast_rpc_address(row[0]) + host.broadcast_rpc_port = _NodeInfo.get_broadcast_rpc_port(row[0]) else: host.broadcast_rpc_address = connection.endpoint.address + host.broadcast_rpc_port = connection.endpoint.port host.release_version = local_row.get("release_version") host.dse_version = local_row.get("dse_version") host.dse_workload = local_row.get("workload") + host.dse_workloads = local_row.get("workloads") if partitioner and tokens: token_map[host] = tokens # Check metadata.partitioner to see if we haven't built anything yet. If # every node in the cluster was in the contact points, we won't discover # any new nodes, so we need this additional check. (See PYTHON-90) should_rebuild_token_map = force_token_rebuild or self._cluster.metadata.partitioner is None for row in peers_result: + if not self._is_valid_peer(row): + log.warning( + "Found an invalid row for peer (%s). Ignoring host." % + _NodeInfo.get_broadcast_rpc_address(row)) + continue + endpoint = self._cluster.endpoint_factory.create(row) - tokens = row.get("tokens", None) - if 'tokens' in row and not tokens: # it was selected, but empty - log.warning("Excluding host (%s) with no tokens in system.peers table of %s." % (endpoint, connection.endpoint)) - continue if endpoint in found_hosts: log.warning("Found multiple hosts with the same endpoint (%s). Excluding peer %s", endpoint, row.get("peer")) continue found_hosts.add(endpoint) host = self._cluster.metadata.get_host(endpoint) datacenter = row.get("data_center") rack = row.get("rack") if host is None: log.debug("[control connection] Found new host to connect to: %s", endpoint) host, _ = self._cluster.add_host(endpoint, datacenter, rack, signal=True, refresh_nodes=False) should_rebuild_token_map = True else: should_rebuild_token_map |= self._update_location_info(host, datacenter, rack) host.host_id = row.get("host_id") - host.broadcast_address = row.get("peer") - host.broadcast_rpc_address = self._address_from_row(row) + host.broadcast_address = _NodeInfo.get_broadcast_address(row) + host.broadcast_port = _NodeInfo.get_broadcast_port(row) + host.broadcast_rpc_address = _NodeInfo.get_broadcast_rpc_address(row) + host.broadcast_rpc_port = _NodeInfo.get_broadcast_rpc_port(row) host.release_version = row.get("release_version") host.dse_version = row.get("dse_version") host.dse_workload = row.get("workload") + host.dse_workloads = row.get("workloads") - if partitioner and tokens: + tokens = row.get("tokens", None) + if partitioner and tokens and self._token_meta_enabled: token_map[host] = tokens for old_host in self._cluster.metadata.all_hosts(): if old_host.endpoint.address != connection.endpoint and old_host.endpoint not in found_hosts: should_rebuild_token_map = True log.debug("[control connection] Removing host not found in peers metadata: %r", old_host) self._cluster.remove_host(old_host) log.debug("[control connection] Finished fetching ring info") if partitioner and should_rebuild_token_map: log.debug("[control connection] Rebuilding token map due to topology changes") self._cluster.metadata.rebuild_token_map(partitioner, token_map) + @staticmethod + def _is_valid_peer(row): + return bool(_NodeInfo.get_broadcast_rpc_address(row) and row.get("host_id") and + row.get("data_center") and row.get("rack") and + ('tokens' not in row or row.get('tokens'))) + def _update_location_info(self, host, datacenter, rack): if host.datacenter == datacenter and host.rack == rack: return False # If the dc/rack information changes, we need to update the load balancing policy. # For that, we remove and re-add the node against the policy. Not the most elegant, and assumes # that the policy will update correctly, but in practice this should work. self._cluster.profile_manager.on_down(host) host.set_location_info(datacenter, rack) self._cluster.profile_manager.on_up(host) return True def _delay_for_event_type(self, event_type, delay_window): # this serves to order processing correlated events (received within the window) # the window and randomization still have the desired effect of skew across client instances next_time = self._event_schedule_times.get(event_type, 0) now = self._time.time() if now <= next_time: this_time = next_time + 0.01 delay = this_time - now else: delay = random() * delay_window this_time = now + delay self._event_schedule_times[event_type] = this_time return delay def _refresh_nodes_if_not_up(self, host): """ Used to mitigate refreshes for nodes that are already known. Some versions of the server send superfluous NEW_NODE messages in addition to UP events. """ if not host or not host.is_up: self.refresh_node_list_and_token_map() def _handle_topology_change(self, event): change_type = event["change_type"] - host = self._cluster.metadata.get_host(event["address"][0]) + addr, port = event["address"] + host = self._cluster.metadata.get_host(addr, port) if change_type == "NEW_NODE" or change_type == "MOVED_NODE": if self._topology_event_refresh_window >= 0: delay = self._delay_for_event_type('topology_change', self._topology_event_refresh_window) self._cluster.scheduler.schedule_unique(delay, self._refresh_nodes_if_not_up, host) elif change_type == "REMOVED_NODE": self._cluster.scheduler.schedule_unique(0, self._cluster.remove_host, host) def _handle_status_change(self, event): change_type = event["change_type"] - host = self._cluster.metadata.get_host(event["address"][0]) + addr, port = event["address"] + host = self._cluster.metadata.get_host(addr, port) if change_type == "UP": delay = self._delay_for_event_type('status_change', self._status_event_refresh_window) if host is None: # this is the first time we've seen the node self._cluster.scheduler.schedule_unique(delay, self.refresh_node_list_and_token_map) else: self._cluster.scheduler.schedule_unique(delay, self._cluster.on_up, host) elif change_type == "DOWN": # Note that there is a slight risk we can receive the event late and thus # mark the host down even though we already had reconnected successfully. # But it is unlikely, and don't have too much consequence since we'll try reconnecting # right away, so we favor the detection to make the Host.is_up more accurate. if host is not None: # this will be run by the scheduler self._cluster.on_down(host, is_host_addition=False) def _handle_schema_change(self, event): if self._schema_event_refresh_window < 0: return delay = self._delay_for_event_type('schema_change', self._schema_event_refresh_window) self._cluster.scheduler.schedule_unique(delay, self.refresh_schema, **event) def wait_for_schema_agreement(self, connection=None, preloaded_results=None, wait_time=None): total_timeout = wait_time if wait_time is not None else self._cluster.max_schema_agreement_wait if total_timeout <= 0: return True # Each schema change typically generates two schema refreshes, one # from the response type and one from the pushed notification. Holding # a lock is just a simple way to cut down on the number of schema queries # we'll make. with self._schema_agreement_lock: if self._is_shutdown: return if not connection: connection = self._connection if preloaded_results: log.debug("[control connection] Attempting to use preloaded results for schema agreement") peers_result = preloaded_results[0] local_result = preloaded_results[1] schema_mismatches = self._get_schema_mismatches(peers_result, local_result, connection.endpoint) if schema_mismatches is None: return True log.debug("[control connection] Waiting for schema agreement") start = self._time.time() elapsed = 0 cl = ConsistencyLevel.ONE schema_mismatches = None + select_peers_query = self._get_peers_query(self.PeersQueryType.PEERS_SCHEMA, connection) + while elapsed < total_timeout: - peers_query = QueryMessage(query=self._SELECT_SCHEMA_PEERS, consistency_level=cl) + peers_query = QueryMessage(query=select_peers_query, consistency_level=cl) local_query = QueryMessage(query=self._SELECT_SCHEMA_LOCAL, consistency_level=cl) try: timeout = min(self._timeout, total_timeout - elapsed) peers_result, local_result = connection.wait_for_responses( peers_query, local_query, timeout=timeout) except OperationTimedOut as timeout: log.debug("[control connection] Timed out waiting for " "response during schema agreement check: %s", timeout) elapsed = self._time.time() - start continue except ConnectionShutdown: if self._is_shutdown: log.debug("[control connection] Aborting wait for schema match due to shutdown") return None else: raise schema_mismatches = self._get_schema_mismatches(peers_result, local_result, connection.endpoint) if schema_mismatches is None: return True log.debug("[control connection] Schemas mismatched, trying again") self._time.sleep(0.2) elapsed = self._time.time() - start log.warning("Node %s is reporting a schema disagreement: %s", connection.endpoint, schema_mismatches) return False def _get_schema_mismatches(self, peers_result, local_result, local_address): - peers_result = dict_factory(*peers_result.results) + peers_result = dict_factory(peers_result.column_names, peers_result.parsed_rows) versions = defaultdict(set) - if local_result.results: - local_row = dict_factory(*local_result.results)[0] + if local_result.parsed_rows: + local_row = dict_factory(local_result.column_names, local_result.parsed_rows)[0] if local_row.get("schema_version"): versions[local_row.get("schema_version")].add(local_address) for row in peers_result: schema_ver = row.get('schema_version') if not schema_ver: continue endpoint = self._cluster.endpoint_factory.create(row) peer = self._cluster.metadata.get_host(endpoint) if peer and peer.is_up is not False: versions[schema_ver].add(endpoint) if len(versions) == 1: log.debug("[control connection] Schemas match") return None return dict((version, list(nodes)) for version, nodes in six.iteritems(versions)) - def _address_from_row(self, row): + def _get_peers_query(self, peers_query_type, connection=None): """ - Parse the broadcast rpc address from a row and return it untranslated. + Determine the peers query to use. + + :param peers_query_type: Should be one of PeersQueryType enum. + + If _uses_peers_v2 is True, return the proper peers_v2 query (no templating). + Else, apply the logic below to choose the peers v1 address column name: + + Given a connection: + + - find the server product version running on the connection's host, + - use that to choose the column name for the transport address (see APOLLO-1130), and + - use that column name in the provided peers query template. """ - addr = None - if "rpc_address" in row: - addr = row.get("rpc_address") # peers and local - if "native_transport_address" in row: - addr = row.get("native_transport_address") - if not addr or addr in ["0.0.0.0", "::"]: - addr = row.get("peer") + if peers_query_type not in (self.PeersQueryType.PEERS, self.PeersQueryType.PEERS_SCHEMA): + raise ValueError("Invalid peers query type: %s" % peers_query_type) + + if self._uses_peers_v2: + if peers_query_type == self.PeersQueryType.PEERS: + query = self._SELECT_PEERS_V2 if self._token_meta_enabled else self._SELECT_PEERS_NO_TOKENS_V2 + else: + query = self._SELECT_SCHEMA_PEERS_V2 + else: + if peers_query_type == self.PeersQueryType.PEERS and self._token_meta_enabled: + query = self._SELECT_PEERS + else: + query_template = (self._SELECT_SCHEMA_PEERS_TEMPLATE + if peers_query_type == self.PeersQueryType.PEERS_SCHEMA + else self._SELECT_PEERS_NO_TOKENS_TEMPLATE) + + host_release_version = self._cluster.metadata.get_host(connection.endpoint).release_version + host_dse_version = self._cluster.metadata.get_host(connection.endpoint).dse_version + uses_native_address_query = ( + host_dse_version and Version(host_dse_version) >= self._MINIMUM_NATIVE_ADDRESS_DSE_VERSION) + + if uses_native_address_query: + query = query_template.format(nt_col_name="native_transport_address") + elif host_release_version: + query = query_template.format(nt_col_name="rpc_address") + else: + query = self._SELECT_PEERS + + return query - return addr - def _signal_error(self): with self._lock: if self._is_shutdown: return # try just signaling the cluster, as this will trigger a reconnect # as part of marking the host down if self._connection and self._connection.is_defunct: host = self._cluster.metadata.get_host(self._connection.endpoint) # host may be None if it's already been removed, but that indicates # that errors have already been reported, so we're fine if host: self._cluster.signal_connection_failure( host, self._connection.last_error, is_host_addition=False) return # if the connection is not defunct or the host already left, reconnect # manually self.reconnect() def on_up(self, host): pass def on_down(self, host): conn = self._connection if conn and conn.endpoint == host.endpoint and \ self._reconnection_handler is None: log.debug("[control connection] Control connection host (%s) is " "considered down, starting reconnection", host) # this will result in a task being submitted to the executor to reconnect self.reconnect() def on_add(self, host, refresh_nodes=True): if refresh_nodes: self.refresh_node_list_and_token_map(force_token_rebuild=True) def on_remove(self, host): c = self._connection if c and c.endpoint == host.endpoint: log.debug("[control connection] Control connection host (%s) is being removed. Reconnecting", host) # refresh will be done on reconnect self.reconnect() else: self.refresh_node_list_and_token_map(force_token_rebuild=True) def get_connections(self): c = getattr(self, '_connection', None) return [c] if c else [] def return_connection(self, connection): if connection is self._connection and (connection.is_defunct or connection.is_closed): self.reconnect() def _stop_scheduler(scheduler, thread): try: if not scheduler.is_shutdown: scheduler.shutdown() except ReferenceError: pass thread.join() class _Scheduler(Thread): _queue = None _scheduled_tasks = None _executor = None is_shutdown = False def __init__(self, executor): self._queue = Queue.PriorityQueue() self._scheduled_tasks = set() self._count = count() self._executor = executor Thread.__init__(self, name="Task Scheduler") self.daemon = True self.start() def shutdown(self): try: log.debug("Shutting down Cluster Scheduler") except AttributeError: # this can happen on interpreter shutdown pass self.is_shutdown = True self._queue.put_nowait((0, 0, None)) self.join() def schedule(self, delay, fn, *args, **kwargs): self._insert_task(delay, (fn, args, tuple(kwargs.items()))) def schedule_unique(self, delay, fn, *args, **kwargs): task = (fn, args, tuple(kwargs.items())) if task not in self._scheduled_tasks: self._insert_task(delay, task) else: log.debug("Ignoring schedule_unique for already-scheduled task: %r", task) def _insert_task(self, delay, task): if not self.is_shutdown: run_at = time.time() + delay self._scheduled_tasks.add(task) self._queue.put_nowait((run_at, next(self._count), task)) else: log.debug("Ignoring scheduled task after shutdown: %r", task) def run(self): while True: if self.is_shutdown: return try: while True: run_at, i, task = self._queue.get(block=True, timeout=None) if self.is_shutdown: if task: log.debug("Not executing scheduled task due to Scheduler shutdown") return if run_at <= time.time(): self._scheduled_tasks.discard(task) fn, args, kwargs = task kwargs = dict(kwargs) future = self._executor.submit(fn, *args, **kwargs) future.add_done_callback(self._log_if_failed) else: self._queue.put_nowait((run_at, i, task)) break except Queue.Empty: pass time.sleep(0.1) def _log_if_failed(self, future): exc = future.exception() if exc: log.warning( "An internally scheduled tasked failed with an unhandled exception:", exc_info=exc) def refresh_schema_and_set_result(control_conn, response_future, connection, **kwargs): try: log.debug("Refreshing schema in response to schema change. " "%s", kwargs) response_future.is_schema_agreed = control_conn._refresh_schema(connection, **kwargs) except Exception: log.exception("Exception refreshing schema in response to schema change:") response_future.session.submit(control_conn.refresh_schema, **kwargs) finally: response_future._set_final_result(None) class ResponseFuture(object): """ An asynchronous response delivery mechanism that is returned from calls to :meth:`.Session.execute_async()`. There are two ways for results to be delivered: - Synchronously, by calling :meth:`.result()` - Asynchronously, by attaching callback and errback functions via :meth:`.add_callback()`, :meth:`.add_errback()`, and :meth:`.add_callbacks()`. """ query = None """ The :class:`~.Statement` instance that is being executed through this :class:`.ResponseFuture`. """ is_schema_agreed = True """ For DDL requests, this may be set ``False`` if the schema agreement poll after the response fails. Always ``True`` for non-DDL requests. """ request_encoded_size = None """ Size of the request message sent """ coordinator_host = None """ - The host from which we recieved a response + The host from which we received a response """ attempted_hosts = None """ A list of hosts tried, including all speculative executions, retries, and pages """ session = None row_factory = None message = None default_timeout = None _retry_policy = None _profile_manager = None _req_id = None _final_result = _NOT_SET _col_names = None _col_types = None _final_exception = None _query_traces = None _callbacks = None _errbacks = None _current_host = None _connection = None _query_retries = 0 _start_time = None _metrics = None _paging_state = None _custom_payload = None _warnings = None _timer = None _protocol_handler = ProtocolHandler _spec_execution_plan = NoSpeculativeExecutionPlan() + _continuous_paging_options = None + _continuous_paging_session = None _host = None _warned_timeout = False def __init__(self, session, message, query, timeout, metrics=None, prepared_statement=None, retry_policy=RetryPolicy(), row_factory=None, load_balancer=None, start_time=None, - speculative_execution_plan=None, host=None): + speculative_execution_plan=None, continuous_paging_state=None, host=None): self.session = session # TODO: normalize handling of retry policy and row factory self.row_factory = row_factory or session.row_factory self._load_balancer = load_balancer or session.cluster._default_load_balancing_policy self.message = message self.query = query self.timeout = timeout self._retry_policy = retry_policy self._metrics = metrics self.prepared_statement = prepared_statement self._callback_lock = Lock() self._start_time = start_time or time.time() self._host = host self._spec_execution_plan = speculative_execution_plan or self._spec_execution_plan self._make_query_plan() self._event = Event() self._errors = {} self._callbacks = [] self._errbacks = [] self.attempted_hosts = [] self._start_timer() + self._continuous_paging_state = continuous_paging_state @property def _time_remaining(self): if self.timeout is None: return None return (self._start_time + self.timeout) - time.time() def _start_timer(self): if self._timer is None: spec_delay = self._spec_execution_plan.next_execution(self._current_host) if spec_delay >= 0: if self._time_remaining is None or self._time_remaining > spec_delay: self._timer = self.session.cluster.connection_class.create_timer(spec_delay, self._on_speculative_execute) return if self._time_remaining is not None: self._timer = self.session.cluster.connection_class.create_timer(self._time_remaining, self._on_timeout) def _cancel_timer(self): if self._timer: self._timer.cancel() def _on_timeout(self, _attempts=0): """ Called when the request associated with this ResponseFuture times out. This function may reschedule itself. The ``_attempts`` parameter tracks the number of times this has happened. This parameter should only be set in those cases, where ``_on_timeout`` reschedules itself. """ # PYTHON-853: for short timeouts, we sometimes race with our __init__ if self._connection is None and _attempts < 3: self._timer = self.session.cluster.connection_class.create_timer( 0.01, partial(self._on_timeout, _attempts=_attempts + 1) ) return if self._connection is not None: try: self._connection._requests.pop(self._req_id) # PYTHON-1044 # This request might have been removed from the connection after the latter was defunct by heartbeat. # We should still raise OperationTimedOut to reject the future so that the main event thread will not # wait for it endlessly except KeyError: key = "Connection defunct by heartbeat" errors = {key: "Client request timeout. See Session.execute[_async](timeout)"} self._set_final_exception(OperationTimedOut(errors, self._current_host)) return pool = self.session._pools.get(self._current_host) if pool and not pool.is_shutdown: with self._connection.lock: self._connection.request_ids.append(self._req_id) pool.return_connection(self._connection) errors = self._errors if not errors: if self.is_schema_agreed: key = str(self._current_host.endpoint) if self._current_host else 'no host queried before timeout' errors = {key: "Client request timeout. See Session.execute[_async](timeout)"} else: connection = self.session.cluster.control_connection._connection host = str(connection.endpoint) if connection else 'unknown' errors = {host: "Request timed out while waiting for schema agreement. See Session.execute[_async](timeout) and Cluster.max_schema_agreement_wait."} self._set_final_exception(OperationTimedOut(errors, self._current_host)) def _on_speculative_execute(self): self._timer = None if not self._event.is_set(): # PYTHON-836, the speculative queries must be after # the query is sent from the main thread, otherwise the # query from the main thread may raise NoHostAvailable # if the _query_plan has been exhausted by the specualtive queries. # This also prevents a race condition accessing the iterator. # We reschedule this call until the main thread has succeeded # making a query if not self.attempted_hosts: self._timer = self.session.cluster.connection_class.create_timer(0.01, self._on_speculative_execute) return if self._time_remaining is not None: if self._time_remaining <= 0: self._on_timeout() return self.send_request(error_no_hosts=False) self._start_timer() def _make_query_plan(self): # set the query_plan according to the load balancing policy, # or to the explicit host target if set if self._host: # returning a single value effectively disables retries self.query_plan = [self._host] else: # convert the list/generator/etc to an iterator so that subsequent # calls to send_request (which retries may do) will resume where # they last left off self.query_plan = iter(self._load_balancer.make_query_plan(self.session.keyspace, self.query)) def send_request(self, error_no_hosts=True): """ Internal """ # query_plan is an iterator, so this will resume where we last left # off if send_request() is called multiple times for host in self.query_plan: req_id = self._query(host) if req_id is not None: self._req_id = req_id return True if self.timeout is not None and time.time() - self._start_time > self.timeout: self._on_timeout() return True - if error_no_hosts: self._set_final_exception(NoHostAvailable( "Unable to complete the operation against any hosts", self._errors)) return False def _query(self, host, message=None, cb=None): if message is None: message = self.message pool = self.session._pools.get(host) if not pool: self._errors[host] = ConnectionException("Host has been marked down or removed") return None elif pool.is_shutdown: self._errors[host] = ConnectionException("Pool is shutdown") return None self._current_host = host connection = None try: # TODO get connectTimeout from cluster settings connection, request_id = pool.borrow_connection(timeout=2.0) self._connection = connection result_meta = self.prepared_statement.result_metadata if self.prepared_statement else [] if cb is None: cb = partial(self._set_result, host, connection, pool) self.request_encoded_size = connection.send_msg(message, request_id, cb=cb, encoder=self._protocol_handler.encode_message, decoder=self._protocol_handler.decode_message, result_metadata=result_meta) self.attempted_hosts.append(host) return request_id except NoConnectionsAvailable as exc: log.debug("All connections for host %s are at capacity, moving to the next host", host) self._errors[host] = exc - return None + except ConnectionBusy as exc: + log.debug("Connection for host %s is busy, moving to the next host", host) + self._errors[host] = exc except Exception as exc: log.debug("Error querying host %s", host, exc_info=True) self._errors[host] = exc if self._metrics is not None: self._metrics.on_connection_error() if connection: pool.return_connection(connection) - return None + + return None @property def has_more_pages(self): """ Returns :const:`True` if there are more pages left in the query results, :const:`False` otherwise. This should only be checked after the first page has been returned. .. versionadded:: 2.0.0 """ return self._paging_state is not None @property def warnings(self): """ Warnings returned from the server, if any. This will only be set for protocol_version 4+. Warnings may be returned for such things as oversized batches, or too many tombstones in slice queries. Ensure the future is complete before trying to access this property (call :meth:`.result()`, or after callback is invoked). Otherwise it may throw if the response has not been received. """ # TODO: When timers are introduced, just make this wait if not self._event.is_set(): raise DriverException("warnings cannot be retrieved before ResponseFuture is finalized") return self._warnings @property def custom_payload(self): """ The custom payload returned from the server, if any. This will only be set by Cassandra servers implementing a custom QueryHandler, and only for protocol_version 4+. Ensure the future is complete before trying to access this property (call :meth:`.result()`, or after callback is invoked). Otherwise it may throw if the response has not been received. :return: :ref:`custom_payload`. """ # TODO: When timers are introduced, just make this wait if not self._event.is_set(): raise DriverException("custom_payload cannot be retrieved before ResponseFuture is finalized") return self._custom_payload def start_fetching_next_page(self): """ If there are more pages left in the query result, this asynchronously starts fetching the next page. If there are no pages left, :exc:`.QueryExhausted` is raised. Also see :attr:`.has_more_pages`. This should only be called after the first page has been returned. .. versionadded:: 2.0.0 """ if not self._paging_state: raise QueryExhausted() self._make_query_plan() self.message.paging_state = self._paging_state self._event.clear() self._final_result = _NOT_SET self._final_exception = None self._start_timer() self.send_request() def _reprepare(self, prepare_message, host, connection, pool): cb = partial(self.session.submit, self._execute_after_prepare, host, connection, pool) request_id = self._query(host, prepare_message, cb=cb) if request_id is None: # try to submit the original prepared statement on some other host self.send_request() def _set_result(self, host, connection, pool, response): try: self.coordinator_host = host if pool: pool.return_connection(connection) trace_id = getattr(response, 'trace_id', None) if trace_id: if not self._query_traces: self._query_traces = [] self._query_traces.append(QueryTrace(trace_id, self.session)) self._warnings = getattr(response, 'warnings', None) self._custom_payload = getattr(response, 'custom_payload', None) if isinstance(response, ResultMessage): if response.kind == RESULT_KIND_SET_KEYSPACE: session = getattr(self, 'session', None) # since we're running on the event loop thread, we need to # use a non-blocking method for setting the keyspace on # all connections in this session, otherwise the event # loop thread will deadlock waiting for keyspaces to be # set. This uses a callback chain which ends with # self._set_keyspace_completed() being called in the # event loop thread. if session: session._set_keyspace_for_all_pools( - response.results, self._set_keyspace_completed) + response.new_keyspace, self._set_keyspace_completed) elif response.kind == RESULT_KIND_SCHEMA_CHANGE: # refresh the schema before responding, but do it in another # thread instead of the event loop thread self.is_schema_agreed = False self.session.submit( refresh_schema_and_set_result, self.session.cluster.control_connection, - self, connection, **response.results) + self, connection, **response.schema_change_event) + elif response.kind == RESULT_KIND_ROWS: + self._paging_state = response.paging_state + self._col_names = response.column_names + self._col_types = response.column_types + if getattr(self.message, 'continuous_paging_options', None): + self._handle_continuous_paging_first_response(connection, response) + else: + self._set_final_result(self.row_factory(response.column_names, response.parsed_rows)) + elif response.kind == RESULT_KIND_VOID: + self._set_final_result(None) else: - results = getattr(response, 'results', None) - if results is not None and response.kind == RESULT_KIND_ROWS: - self._paging_state = response.paging_state - self._col_types = response.col_types - self._col_names = results[0] - results = self.row_factory(*results) - self._set_final_result(results) + self._set_final_result(response) elif isinstance(response, ErrorMessage): retry_policy = self._retry_policy if isinstance(response, ReadTimeoutErrorMessage): if self._metrics is not None: self._metrics.on_read_timeout() retry = retry_policy.on_read_timeout( self.query, retry_num=self._query_retries, **response.info) elif isinstance(response, WriteTimeoutErrorMessage): if self._metrics is not None: self._metrics.on_write_timeout() retry = retry_policy.on_write_timeout( self.query, retry_num=self._query_retries, **response.info) elif isinstance(response, UnavailableErrorMessage): if self._metrics is not None: self._metrics.on_unavailable() retry = retry_policy.on_unavailable( self.query, retry_num=self._query_retries, **response.info) elif isinstance(response, (OverloadedErrorMessage, IsBootstrappingErrorMessage, TruncateError, ServerError)): log.warning("Host %s error: %s.", host, response.summary) if self._metrics is not None: self._metrics.on_other_error() + cl = getattr(self.message, 'consistency_level', None) retry = retry_policy.on_request_error( - self.query, self.message.consistency_level, error=response, + self.query, cl, error=response, retry_num=self._query_retries) elif isinstance(response, PreparedQueryNotFound): if self.prepared_statement: query_id = self.prepared_statement.query_id assert query_id == response.info, \ "Got different query ID in server response (%s) than we " \ "had before (%s)" % (response.info, query_id) else: query_id = response.info try: prepared_statement = self.session.cluster._prepared_statements[query_id] except KeyError: if not self.prepared_statement: log.error("Tried to execute unknown prepared statement: id=%s", query_id.encode('hex')) self._set_final_exception(response) return else: prepared_statement = self.prepared_statement self.session.cluster._prepared_statements[query_id] = prepared_statement current_keyspace = self._connection.keyspace prepared_keyspace = prepared_statement.keyspace if not ProtocolVersion.uses_keyspace_flag(self.session.cluster.protocol_version) \ and prepared_keyspace and current_keyspace != prepared_keyspace: self._set_final_exception( ValueError("The Session's current keyspace (%s) does " "not match the keyspace the statement was " "prepared with (%s)" % (current_keyspace, prepared_keyspace))) return log.debug("Re-preparing unrecognized prepared statement against host %s: %s", host, prepared_statement.query_string) prepared_keyspace = prepared_statement.keyspace \ if ProtocolVersion.uses_keyspace_flag(self.session.cluster.protocol_version) else None prepare_message = PrepareMessage(query=prepared_statement.query_string, keyspace=prepared_keyspace) # since this might block, run on the executor to avoid hanging # the event loop thread self.session.submit(self._reprepare, prepare_message, host, connection, pool) return else: if hasattr(response, 'to_exception'): self._set_final_exception(response.to_exception()) else: self._set_final_exception(response) return self._handle_retry_decision(retry, response, host) elif isinstance(response, ConnectionException): if self._metrics is not None: self._metrics.on_connection_error() if not isinstance(response, ConnectionShutdown): self._connection.defunct(response) + cl = getattr(self.message, 'consistency_level', None) retry = self._retry_policy.on_request_error( - self.query, self.message.consistency_level, error=response, - retry_num=self._query_retries) + self.query, cl, error=response, retry_num=self._query_retries) self._handle_retry_decision(retry, response, host) elif isinstance(response, Exception): if hasattr(response, 'to_exception'): self._set_final_exception(response.to_exception()) else: self._set_final_exception(response) else: # we got some other kind of response message msg = "Got unexpected message: %r" % (response,) exc = ConnectionException(msg, host) self._cancel_timer() self._connection.defunct(exc) self._set_final_exception(exc) except Exception as exc: # almost certainly caused by a bug, but we need to set something here log.exception("Unexpected exception while handling result in ResponseFuture:") self._set_final_exception(exc) + def _handle_continuous_paging_first_response(self, connection, response): + self._continuous_paging_session = connection.new_continuous_paging_session(response.stream_id, + self._protocol_handler.decode_message, + self.row_factory, + self._continuous_paging_state) + self._continuous_paging_session.on_message(response) + self._set_final_result(self._continuous_paging_session.results()) + def _set_keyspace_completed(self, errors): if not errors: self._set_final_result(None) else: self._set_final_exception(ConnectionException( "Failed to set keyspace on all hosts: %s" % (errors,))) def _execute_after_prepare(self, host, connection, pool, response): """ Handle the response to our attempt to prepare a statement. If it succeeded, run the original query again against the same host. """ if pool: pool.return_connection(connection) if self._final_exception: return if isinstance(response, ResultMessage): if response.kind == RESULT_KIND_PREPARED: if self.prepared_statement: - # result metadata is the only thing that could have - # changed from an alter - (_, _, _, - self.prepared_statement.result_metadata, - new_metadata_id) = response.results + if self.prepared_statement.query_id != response.query_id: + self._set_final_exception(DriverException( + "ID mismatch while trying to reprepare (expected {expected}, got {got}). " + "This prepared statement won't work anymore. " + "This usually happens when you run a 'USE...' " + "query after the statement was prepared.".format( + expected=hexlify(self.prepared_statement.query_id), got=hexlify(response.query_id) + ) + )) + self.prepared_statement.result_metadata = response.column_metadata + new_metadata_id = response.result_metadata_id if new_metadata_id is not None: self.prepared_statement.result_metadata_id = new_metadata_id # use self._query to re-use the same host and # at the same time properly borrow the connection request_id = self._query(host) if request_id is None: # this host errored out, move on to the next self.send_request() else: self._set_final_exception(ConnectionException( "Got unexpected response when preparing statement " "on host %s: %s" % (host, response))) elif isinstance(response, ErrorMessage): if hasattr(response, 'to_exception'): self._set_final_exception(response.to_exception()) else: self._set_final_exception(response) elif isinstance(response, ConnectionException): log.debug("Connection error when preparing statement on host %s: %s", host, response) # try again on a different host, preparing again if necessary self._errors[host] = response self.send_request() else: self._set_final_exception(ConnectionException( "Got unexpected response type when preparing " "statement on host %s: %s" % (host, response))) def _set_final_result(self, response): self._cancel_timer() if self._metrics is not None: self._metrics.request_timer.addValue(time.time() - self._start_time) with self._callback_lock: self._final_result = response # save off current callbacks inside lock for execution outside it # -- prevents case where _final_result is set, then a callback is # added and executed on the spot, then executed again as a # registered callback to_call = tuple( partial(fn, response, *args, **kwargs) for (fn, args, kwargs) in self._callbacks ) self._event.set() # apply each callback for callback_partial in to_call: callback_partial() def _set_final_exception(self, response): self._cancel_timer() if self._metrics is not None: self._metrics.request_timer.addValue(time.time() - self._start_time) with self._callback_lock: self._final_exception = response # save off current errbacks inside lock for execution outside it -- # prevents case where _final_exception is set, then an errback is # added and executed on the spot, then executed again as a # registered errback to_call = tuple( partial(fn, response, *args, **kwargs) for (fn, args, kwargs) in self._errbacks ) self._event.set() # apply each callback for callback_partial in to_call: callback_partial() def _handle_retry_decision(self, retry_decision, response, host): def exception_from_response(response): if hasattr(response, 'to_exception'): return response.to_exception() else: return response retry_type, consistency = retry_decision if retry_type in (RetryPolicy.RETRY, RetryPolicy.RETRY_NEXT_HOST): self._query_retries += 1 reuse = retry_type == RetryPolicy.RETRY self._retry(reuse, consistency, host) elif retry_type is RetryPolicy.RETHROW: self._set_final_exception(exception_from_response(response)) else: # IGNORE if self._metrics is not None: self._metrics.on_ignore() self._set_final_result(None) self._errors[host] = exception_from_response(response) def _retry(self, reuse_connection, consistency_level, host): if self._final_exception: # the connection probably broke while we were waiting # to retry the operation return if self._metrics is not None: self._metrics.on_retry() if consistency_level is not None: self.message.consistency_level = consistency_level # don't retry on the event loop thread self.session.submit(self._retry_task, reuse_connection, host) def _retry_task(self, reuse_connection, host): if self._final_exception: # the connection probably broke while we were waiting # to retry the operation return if reuse_connection and self._query(host) is not None: return # otherwise, move onto another host self.send_request() def result(self): """ Return the final result or raise an Exception if errors were encountered. If the final result or error has not been set yet, this method will block until it is set, or the timeout set for the request expires. Timeout is specified in the Session request execution functions. If the timeout is exceeded, an :exc:`cassandra.OperationTimedOut` will be raised. This is a client-side timeout. For more information about server-side coordinator timeouts, see :class:`.policies.RetryPolicy`. Example usage:: >>> future = session.execute_async("SELECT * FROM mycf") >>> # do other stuff... >>> try: ... rows = future.result() ... for row in rows: ... ... # process results ... except Exception: ... log.exception("Operation failed:") """ self._event.wait() if self._final_result is not _NOT_SET: return ResultSet(self, self._final_result) else: raise self._final_exception def get_query_trace_ids(self): """ Returns the trace session ids for this future, if tracing was enabled (does not fetch trace data). """ return [trace.trace_id for trace in self._query_traces] def get_query_trace(self, max_wait=None, query_cl=ConsistencyLevel.LOCAL_ONE): """ Fetches and returns the query trace of the last response, or `None` if tracing was not enabled. Note that this may raise an exception if there are problems retrieving the trace details from Cassandra. If the trace is not available after `max_wait`, :exc:`cassandra.query.TraceUnavailable` will be raised. If the ResponseFuture is not done (async execution) and you try to retrieve the trace, :exc:`cassandra.query.TraceUnavailable` will be raised. `query_cl` is the consistency level used to poll the trace tables. """ if self._final_result is _NOT_SET and self._final_exception is None: raise TraceUnavailable( "Trace information was not available. The ResponseFuture is not done.") if self._query_traces: return self._get_query_trace(len(self._query_traces) - 1, max_wait, query_cl) def get_all_query_traces(self, max_wait_per=None, query_cl=ConsistencyLevel.LOCAL_ONE): """ Fetches and returns the query traces for all query pages, if tracing was enabled. See note in :meth:`~.get_query_trace` regarding possible exceptions. """ if self._query_traces: return [self._get_query_trace(i, max_wait_per, query_cl) for i in range(len(self._query_traces))] return [] def _get_query_trace(self, i, max_wait, query_cl): trace = self._query_traces[i] if not trace.events: trace.populate(max_wait=max_wait, query_cl=query_cl) return trace def add_callback(self, fn, *args, **kwargs): """ Attaches a callback function to be called when the final results arrive. By default, `fn` will be called with the results as the first and only argument. If `*args` or `**kwargs` are supplied, they will be passed through as additional positional or keyword arguments to `fn`. If an error is hit while executing the operation, a callback attached here will not be called. Use :meth:`.add_errback()` or :meth:`add_callbacks()` if you wish to handle that case. If the final result has already been seen when this method is called, the callback will be called immediately (before this method returns). Note: in the case that the result is not available when the callback is added, the callback is executed by IO event thread. This means that the callback should not block or attempt further synchronous requests, because no further IO will be processed until the callback returns. **Important**: if the callback you attach results in an exception being raised, **the exception will be ignored**, so please ensure your callback handles all error cases that you care about. Usage example:: >>> session = cluster.connect("mykeyspace") >>> def handle_results(rows, start_time, should_log=False): ... if should_log: ... log.info("Total time: %f", time.time() - start_time) ... ... >>> future = session.execute_async("SELECT * FROM users") >>> future.add_callback(handle_results, time.time(), should_log=True) """ run_now = False with self._callback_lock: # Always add fn to self._callbacks, even when we're about to # execute it, to prevent races with functions like # start_fetching_next_page that reset _final_result self._callbacks.append((fn, args, kwargs)) if self._final_result is not _NOT_SET: run_now = True if run_now: fn(self._final_result, *args, **kwargs) return self def add_errback(self, fn, *args, **kwargs): """ Like :meth:`.add_callback()`, but handles error cases. An Exception instance will be passed as the first positional argument to `fn`. """ run_now = False with self._callback_lock: # Always add fn to self._errbacks, even when we're about to execute # it, to prevent races with functions like start_fetching_next_page # that reset _final_exception self._errbacks.append((fn, args, kwargs)) if self._final_exception: run_now = True if run_now: fn(self._final_exception, *args, **kwargs) return self def add_callbacks(self, callback, errback, callback_args=(), callback_kwargs=None, errback_args=(), errback_kwargs=None): """ A convenient combination of :meth:`.add_callback()` and :meth:`.add_errback()`. Example usage:: >>> session = cluster.connect() >>> query = "SELECT * FROM mycf" >>> future = session.execute_async(query) >>> def log_results(results, level='debug'): ... for row in results: ... log.log(level, "Result: %s", row) >>> def log_error(exc, query): ... log.error("Query '%s' failed: %s", query, exc) >>> future.add_callbacks( ... callback=log_results, callback_kwargs={'level': 'info'}, ... errback=log_error, errback_args=(query,)) """ self.add_callback(callback, *callback_args, **(callback_kwargs or {})) self.add_errback(errback, *errback_args, **(errback_kwargs or {})) def clear_callbacks(self): with self._callback_lock: self._callbacks = [] self._errbacks = [] def __str__(self): result = "(no result yet)" if self._final_result is _NOT_SET else self._final_result return "" \ % (self.query, self._req_id, result, self._final_exception, self.coordinator_host) __repr__ = __str__ class QueryExhausted(Exception): """ Raised when :meth:`.ResponseFuture.start_fetching_next_page()` is called and there are no more pages. You can check :attr:`.ResponseFuture.has_more_pages` before calling to avoid this. .. versionadded:: 2.0.0 """ pass class ResultSet(object): """ An iterator over the rows from a query result. Also supplies basic equality and indexing methods for backward-compatability. These methods materialize the entire result set (loading all pages), and should only be used if the total result size is understood. Warnings are emitted when paged results are materialized in this fashion. You can treat this as a normal iterator over rows:: >>> from cassandra.query import SimpleStatement >>> statement = SimpleStatement("SELECT * FROM users", fetch_size=10) >>> for user_row in session.execute(statement): ... process_user(user_row) Whenever there are no more rows in the current page, the next page will be fetched transparently. However, note that it *is* possible for an :class:`Exception` to be raised while fetching the next page, just like you might see on a normal call to ``session.execute()``. """ def __init__(self, response_future, initial_response): self.response_future = response_future self.column_names = response_future._col_names self.column_types = response_future._col_types self._set_current_rows(initial_response) self._page_iter = None self._list_mode = False @property def has_more_pages(self): """ True if the last response indicated more pages; False otherwise """ return self.response_future.has_more_pages @property def current_rows(self): """ The list of current page rows. May be empty if the result was empty, or this is the last page. """ return self._current_rows or [] + def all(self): + """ + Returns all the remaining rows as a list. This is basically + a convenient shortcut to `list(result_set)`. + + This function is not recommended for queries that return a large number of elements. + """ + return list(self) + def one(self): """ Return a single row of the results or None if empty. This is basically a shortcut to `result_set.current_rows[0]` and should only be used when you know a query returns a single row. Consider using an iterator if the ResultSet contains more than one row. """ row = None if self._current_rows: try: row = self._current_rows[0] except TypeError: # generator object is not subscriptable, PYTHON-1026 row = next(iter(self._current_rows)) return row def __iter__(self): if self._list_mode: return iter(self._current_rows) self._page_iter = iter(self._current_rows) return self def next(self): try: return next(self._page_iter) except StopIteration: if not self.response_future.has_more_pages: if not self._list_mode: self._current_rows = [] raise - self.fetch_next_page() - self._page_iter = iter(self._current_rows) + if not self.response_future._continuous_paging_session: + self.fetch_next_page() + self._page_iter = iter(self._current_rows) return next(self._page_iter) __next__ = next def fetch_next_page(self): """ Manually, synchronously fetch the next page. Supplied for manually retrieving pages and inspecting :meth:`~.current_page`. It is not necessary to call this when iterating through results; paging happens implicitly in iteration. """ if self.response_future.has_more_pages: self.response_future.start_fetching_next_page() result = self.response_future.result() self._current_rows = result._current_rows # ResultSet has already _set_current_rows to the appropriate form else: self._current_rows = [] def _set_current_rows(self, result): if isinstance(result, Mapping): self._current_rows = [result] if result else [] return try: iter(result) # can't check directly for generator types because cython generators are different self._current_rows = result except TypeError: self._current_rows = [result] if result else [] def _fetch_all(self): self._current_rows = list(self) self._page_iter = None def _enter_list_mode(self, operator): if self._list_mode: return if self._page_iter: raise RuntimeError("Cannot use %s when results have been iterated." % operator) if self.response_future.has_more_pages: log.warning("Using %s on paged results causes entire result set to be materialized.", operator) self._fetch_all() # done regardless of paging status in case the row factory produces a generator self._list_mode = True def __eq__(self, other): self._enter_list_mode("equality operator") return self._current_rows == other def __getitem__(self, i): if i == 0: warn("ResultSet indexing support will be removed in 4.0. Consider using " "ResultSet.one() to get a single row.", DeprecationWarning) self._enter_list_mode("index operator") return self._current_rows[i] def __nonzero__(self): return bool(self._current_rows) __bool__ = __nonzero__ def get_query_trace(self, max_wait_sec=None): """ Gets the last query trace from the associated future. See :meth:`.ResponseFuture.get_query_trace` for details. """ return self.response_future.get_query_trace(max_wait_sec) def get_all_query_traces(self, max_wait_sec_per=None): """ Gets all query traces from the associated future. See :meth:`.ResponseFuture.get_all_query_traces` for details. """ return self.response_future.get_all_query_traces(max_wait_sec_per) + def cancel_continuous_paging(self): + try: + self.response_future._continuous_paging_session.cancel() + except AttributeError: + raise DriverException("Attempted to cancel paging with no active session. This is only for requests with ContinuousdPagingOptions.") + @property def was_applied(self): """ For LWT results, returns whether the transaction was applied. Result is indeterminate if called on a result that was not an LWT request or on a :class:`.query.BatchStatement` containing LWT. In the latter case either all the batch succeeds or fails. Only valid when one of the of the internal row factories is in use. """ if self.response_future.row_factory not in (named_tuple_factory, dict_factory, tuple_factory): raise RuntimeError("Cannot determine LWT result with row factory %s" % (self.response_future.row_factory,)) is_batch_statement = isinstance(self.response_future.query, BatchStatement) if is_batch_statement and (not self.column_names or self.column_names[0] != "[applied]"): raise RuntimeError("No LWT were present in the BatchStatement") if not is_batch_statement and len(self.current_rows) != 1: raise RuntimeError("LWT result should have exactly one row. This has %d." % (len(self.current_rows))) row = self.current_rows[0] if isinstance(row, tuple): return row[0] else: return row['[applied]'] @property def paging_state(self): """ Server paging state of the query. Can be `None` if the query was not paged. The driver treats paging state as opaque, but it may contain primary key data, so applications may want to avoid sending this to untrusted parties. """ return self.response_future._paging_state diff --git a/cassandra/connection.py b/cassandra/connection.py index ba08ae2..0d8a50e 100644 --- a/cassandra/connection.py +++ b/cassandra/connection.py @@ -1,1418 +1,1765 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import # to enable import io from stdlib from collections import defaultdict, deque import errno from functools import wraps, partial, total_ordering from heapq import heappush, heappop import io import logging import six from six.moves import range import socket import struct import sys -from threading import Thread, Event, RLock +from threading import Thread, Event, RLock, Condition import time +import ssl +import weakref -try: - import ssl -except ImportError: - ssl = None # NOQA if 'gevent.monkey' in sys.modules: from gevent.queue import Queue, Empty else: from six.moves.queue import Queue, Empty # noqa from cassandra import ConsistencyLevel, AuthenticationFailed, OperationTimedOut, ProtocolVersion from cassandra.marshal import int32_pack from cassandra.protocol import (ReadyMessage, AuthenticateMessage, OptionsMessage, StartupMessage, ErrorMessage, CredentialsMessage, QueryMessage, ResultMessage, ProtocolHandler, InvalidRequestException, SupportedMessage, AuthResponseMessage, AuthChallengeMessage, AuthSuccessMessage, ProtocolException, - RegisterMessage) + RegisterMessage, ReviseRequestMessage) +from cassandra.segment import SegmentCodec, CrcException from cassandra.util import OrderedDict log = logging.getLogger(__name__) +segment_codec_no_compression = SegmentCodec() +segment_codec_lz4 = None + # We use an ordered dictionary and specifically add lz4 before # snappy so that lz4 will be preferred. Changing the order of this # will change the compression preferences for the driver. locally_supported_compressions = OrderedDict() try: import lz4 except ImportError: pass else: # The compress and decompress functions we need were moved from the lz4 to # the lz4.block namespace, so we try both here. try: from lz4 import block as lz4_block except ImportError: lz4_block = lz4 try: lz4_block.compress lz4_block.decompress except AttributeError: raise ImportError( 'lz4 not imported correctly. Imported object should have ' '.compress and and .decompress attributes but does not. ' 'Please file a bug report on JIRA. (Imported object was ' '{lz4_block})'.format(lz4_block=repr(lz4_block)) ) # Cassandra writes the uncompressed message length in big endian order, # but the lz4 lib requires little endian order, so we wrap these # functions to handle that def lz4_compress(byts): # write length in big-endian instead of little-endian return int32_pack(len(byts)) + lz4_block.compress(byts)[4:] def lz4_decompress(byts): # flip from big-endian to little-endian return lz4_block.decompress(byts[3::-1] + byts[4:]) locally_supported_compressions['lz4'] = (lz4_compress, lz4_decompress) + segment_codec_lz4 = SegmentCodec(lz4_compress, lz4_decompress) try: import snappy except ImportError: pass else: # work around apparently buggy snappy decompress def decompress(byts): if byts == '\x00': return '' return snappy.decompress(byts) locally_supported_compressions['snappy'] = (snappy.compress, decompress) DRIVER_NAME, DRIVER_VERSION = 'DataStax Python Driver', sys.modules['cassandra'].__version__ PROTOCOL_VERSION_MASK = 0x7f HEADER_DIRECTION_FROM_CLIENT = 0x00 HEADER_DIRECTION_TO_CLIENT = 0x80 HEADER_DIRECTION_MASK = 0x80 frame_header_v1_v2 = struct.Struct('>BbBi') frame_header_v3 = struct.Struct('>BhBi') class EndPoint(object): """ Represents the information to connect to a cassandra node. """ @property def address(self): """ The IP address of the node. This is the RPC address the driver uses when connecting to the node """ raise NotImplementedError() @property def port(self): """ The port of the node. """ raise NotImplementedError() @property def ssl_options(self): """ SSL options specific to this endpoint. """ return None @property def socket_family(self): """ The socket family of the endpoint. """ return socket.AF_UNSPEC def resolve(self): """ Resolve the endpoint to an address/port. This is called only on socket connection. """ raise NotImplementedError() class EndPointFactory(object): cluster = None def configure(self, cluster): """ This is called by the cluster during its initialization. """ self.cluster = cluster return self def create(self, row): """ Create an EndPoint from a system.peers row. """ raise NotImplementedError() @total_ordering class DefaultEndPoint(EndPoint): """ Default EndPoint implementation, basically just an address and port. """ def __init__(self, address, port=9042): self._address = address self._port = port @property def address(self): return self._address @property def port(self): return self._port def resolve(self): return self._address, self._port def __eq__(self, other): return isinstance(other, DefaultEndPoint) and \ self.address == other.address and self.port == other.port def __hash__(self): return hash((self.address, self.port)) def __lt__(self, other): return (self.address, self.port) < (other.address, other.port) def __str__(self): return str("%s:%d" % (self.address, self.port)) def __repr__(self): return "<%s: %s:%d>" % (self.__class__.__name__, self.address, self.port) class DefaultEndPointFactory(EndPointFactory): port = None """ - If set, force all endpoints to use this port. + If no port is discovered in the row, this is the default port + used for endpoint creation. """ def __init__(self, port=None): self.port = port def create(self, row): - addr = None - if "rpc_address" in row: - addr = row.get("rpc_address") - if "native_transport_address" in row: - addr = row.get("native_transport_address") - if not addr or addr in ["0.0.0.0", "::"]: - addr = row.get("peer") + # TODO next major... move this class so we don't need this kind of hack + from cassandra.metadata import _NodeInfo + addr = _NodeInfo.get_broadcast_rpc_address(row) + port = _NodeInfo.get_broadcast_rpc_port(row) + if port is None: + port = self.port if self.port else 9042 # create the endpoint with the translated address + # TODO next major, create a TranslatedEndPoint type return DefaultEndPoint( self.cluster.address_translator.translate(addr), - self.port if self.port is not None else 9042) + port) @total_ordering class SniEndPoint(EndPoint): """SNI Proxy EndPoint implementation.""" def __init__(self, proxy_address, server_name, port=9042): self._proxy_address = proxy_address self._index = 0 self._resolved_address = None # resolved address self._port = port self._server_name = server_name self._ssl_options = {'server_hostname': server_name} @property def address(self): return self._proxy_address @property def port(self): return self._port @property def ssl_options(self): return self._ssl_options def resolve(self): try: resolved_addresses = socket.getaddrinfo(self._proxy_address, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM) except socket.gaierror: log.debug('Could not resolve sni proxy hostname "%s" ' 'with port %d' % (self._proxy_address, self._port)) raise # round-robin pick self._resolved_address = sorted(addr[4][0] for addr in resolved_addresses)[self._index % len(resolved_addresses)] self._index += 1 return self._resolved_address, self._port def __eq__(self, other): return (isinstance(other, SniEndPoint) and self.address == other.address and self.port == other.port and self._server_name == other._server_name) def __hash__(self): return hash((self.address, self.port, self._server_name)) def __lt__(self, other): return ((self.address, self.port, self._server_name) < (other.address, other.port, self._server_name)) def __str__(self): return str("%s:%d:%s" % (self.address, self.port, self._server_name)) def __repr__(self): return "<%s: %s:%d:%s>" % (self.__class__.__name__, self.address, self.port, self._server_name) class SniEndPointFactory(EndPointFactory): def __init__(self, proxy_address, port): self._proxy_address = proxy_address self._port = port def create(self, row): host_id = row.get("host_id") if host_id is None: raise ValueError("No host_id to create the SniEndPoint") return SniEndPoint(self._proxy_address, str(host_id), self._port) def create_from_sni(self, sni): return SniEndPoint(self._proxy_address, sni, self._port) @total_ordering class UnixSocketEndPoint(EndPoint): """ Unix Socket EndPoint implementation. """ def __init__(self, unix_socket_path): self._unix_socket_path = unix_socket_path @property def address(self): return self._unix_socket_path @property def port(self): return None @property def socket_family(self): return socket.AF_UNIX def resolve(self): return self.address, None def __eq__(self, other): return (isinstance(other, UnixSocketEndPoint) and self._unix_socket_path == other._unix_socket_path) def __hash__(self): return hash(self._unix_socket_path) def __lt__(self, other): return self._unix_socket_path < other._unix_socket_path def __str__(self): return str("%s" % (self._unix_socket_path,)) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self._unix_socket_path) class _Frame(object): def __init__(self, version, flags, stream, opcode, body_offset, end_pos): self.version = version self.flags = flags self.stream = stream self.opcode = opcode self.body_offset = body_offset self.end_pos = end_pos def __eq__(self, other): # facilitates testing if isinstance(other, _Frame): return (self.version == other.version and self.flags == other.flags and self.stream == other.stream and self.opcode == other.opcode and self.body_offset == other.body_offset and self.end_pos == other.end_pos) return NotImplemented def __str__(self): return "ver({0}); flags({1:04b}); stream({2}); op({3}); offset({4}); len({5})".format(self.version, self.flags, self.stream, self.opcode, self.body_offset, self.end_pos - self.body_offset) NONBLOCKING = (errno.EAGAIN, errno.EWOULDBLOCK) class ConnectionException(Exception): """ An unrecoverable error was hit when attempting to use a connection, or the connection was already closed or defunct. """ def __init__(self, message, endpoint=None): Exception.__init__(self, message) self.endpoint = endpoint @property def host(self): return self.endpoint.address class ConnectionShutdown(ConnectionException): """ Raised when a connection has been marked as defunct or has been closed. """ pass class ProtocolVersionUnsupported(ConnectionException): """ Server rejected startup message due to unsupported protocol version """ def __init__(self, endpoint, startup_version): msg = "Unsupported protocol version on %s: %d" % (endpoint, startup_version) super(ProtocolVersionUnsupported, self).__init__(msg, endpoint) self.startup_version = startup_version class ConnectionBusy(Exception): """ An attempt was made to send a message through a :class:`.Connection` that was already at the max number of in-flight operations. """ pass class ProtocolError(Exception): """ Communication did not match the protocol that this driver expects. """ pass +class CrcMismatchException(ConnectionException): + pass + + +class ContinuousPagingState(object): + """ + A class for specifying continuous paging state, only supported starting with DSE_V2. + """ + + num_pages_requested = None + """ + How many pages we have already requested + """ + + num_pages_received = None + """ + How many pages we have already received + """ + + max_queue_size = None + """ + The max queue size chosen by the user via the options + """ + + def __init__(self, max_queue_size): + self.num_pages_requested = max_queue_size # the initial query requests max_queue_size + self.num_pages_received = 0 + self.max_queue_size = max_queue_size + + +class ContinuousPagingSession(object): + def __init__(self, stream_id, decoder, row_factory, connection, state): + self.stream_id = stream_id + self.decoder = decoder + self.row_factory = row_factory + self.connection = connection + self._condition = Condition() + self._stop = False + self._page_queue = deque() + self._state = state + self.released = False + + def on_message(self, result): + if isinstance(result, ResultMessage): + self.on_page(result) + elif isinstance(result, ErrorMessage): + self.on_error(result) + + def on_page(self, result): + with self._condition: + if self._state: + self._state.num_pages_received += 1 + self._page_queue.appendleft((result.column_names, result.parsed_rows, None)) + self._stop |= result.continuous_paging_last + self._condition.notify() + + if result.continuous_paging_last: + self.released = True + + def on_error(self, error): + if isinstance(error, ErrorMessage): + error = error.to_exception() + + log.debug("Got error %s for session %s", error, self.stream_id) + + with self._condition: + self._page_queue.appendleft((None, None, error)) + self._stop = True + self._condition.notify() + + self.released = True + + def results(self): + try: + self._condition.acquire() + while True: + while not self._page_queue and not self._stop: + self._condition.wait(timeout=5) + while self._page_queue: + names, rows, err = self._page_queue.pop() + if err: + raise err + self.maybe_request_more() + self._condition.release() + for row in self.row_factory(names, rows): + yield row + self._condition.acquire() + if self._stop: + break + finally: + try: + self._condition.release() + except RuntimeError: + # This exception happens if the CP results are not entirely consumed + # and the session is terminated by the runtime. See PYTHON-1054 + pass + + def maybe_request_more(self): + if not self._state: + return + + max_queue_size = self._state.max_queue_size + num_in_flight = self._state.num_pages_requested - self._state.num_pages_received + space_in_queue = max_queue_size - len(self._page_queue) - num_in_flight + log.debug("Session %s from %s, space in CP queue: %s, requested: %s, received: %s, num_in_flight: %s", + self.stream_id, self.connection.host, space_in_queue, self._state.num_pages_requested, + self._state.num_pages_received, num_in_flight) + + if space_in_queue >= max_queue_size / 2: + self.update_next_pages(space_in_queue) + + def update_next_pages(self, num_next_pages): + try: + self._state.num_pages_requested += num_next_pages + log.debug("Updating backpressure for session %s from %s", self.stream_id, self.connection.host) + with self.connection.lock: + self.connection.send_msg(ReviseRequestMessage(ReviseRequestMessage.RevisionType.PAGING_BACKPRESSURE, + self.stream_id, + next_pages=num_next_pages), + self.connection.get_request_id(), + self._on_backpressure_response) + except ConnectionShutdown as ex: + log.debug("Failed to update backpressure for session %s from %s, connection is shutdown", + self.stream_id, self.connection.host) + self.on_error(ex) + + def _on_backpressure_response(self, response): + if isinstance(response, ResultMessage): + log.debug("Paging session %s backpressure updated.", self.stream_id) + else: + log.error("Failed updating backpressure for session %s from %s: %s", self.stream_id, self.connection.host, + response.to_exception() if hasattr(response, 'to_exception') else response) + self.on_error(response) + + def cancel(self): + try: + log.debug("Canceling paging session %s from %s", self.stream_id, self.connection.host) + with self.connection.lock: + self.connection.send_msg(ReviseRequestMessage(ReviseRequestMessage.RevisionType.PAGING_CANCEL, + self.stream_id), + self.connection.get_request_id(), + self._on_cancel_response) + except ConnectionShutdown: + log.debug("Failed to cancel session %s from %s, connection is shutdown", + self.stream_id, self.connection.host) + + with self._condition: + self._stop = True + self._condition.notify() + + def _on_cancel_response(self, response): + if isinstance(response, ResultMessage): + log.debug("Paging session %s canceled.", self.stream_id) + else: + log.error("Failed canceling streaming session %s from %s: %s", self.stream_id, self.connection.host, + response.to_exception() if hasattr(response, 'to_exception') else response) + self.released = True + + def defunct_on_error(f): @wraps(f) def wrapper(self, *args, **kwargs): try: return f(self, *args, **kwargs) except Exception as exc: self.defunct(exc) return wrapper DEFAULT_CQL_VERSION = '3.0.0' if six.PY3: def int_from_buf_item(i): return i else: int_from_buf_item = ord +class _ConnectionIOBuffer(object): + """ + Abstraction class to ease the use of the different connection io buffers. With + protocol V5 and checksumming, the data is read, validated and copied to another + cql frame buffer. + """ + _io_buffer = None + _cql_frame_buffer = None + _connection = None + _segment_consumed = False + + def __init__(self, connection): + self._io_buffer = io.BytesIO() + self._connection = weakref.proxy(connection) + + @property + def io_buffer(self): + return self._io_buffer + + @property + def cql_frame_buffer(self): + return self._cql_frame_buffer if self.is_checksumming_enabled else \ + self._io_buffer + + def set_checksumming_buffer(self): + self.reset_io_buffer() + self._cql_frame_buffer = io.BytesIO() + + @property + def is_checksumming_enabled(self): + return self._connection._is_checksumming_enabled + + @property + def has_consumed_segment(self): + return self._segment_consumed; + + def readable_io_bytes(self): + return self.io_buffer.tell() + + def readable_cql_frame_bytes(self): + return self.cql_frame_buffer.tell() + + def reset_io_buffer(self): + self._io_buffer = io.BytesIO(self._io_buffer.read()) + self._io_buffer.seek(0, 2) # 2 == SEEK_END + + def reset_cql_frame_buffer(self): + if self.is_checksumming_enabled: + self._cql_frame_buffer = io.BytesIO(self._cql_frame_buffer.read()) + self._cql_frame_buffer.seek(0, 2) # 2 == SEEK_END + else: + self.reset_io_buffer() + + class Connection(object): CALLBACK_ERR_THREAD_THRESHOLD = 100 in_buffer_size = 4096 out_buffer_size = 4096 cql_version = None no_compact = False protocol_version = ProtocolVersion.MAX_SUPPORTED keyspace = None compression = True + _compression_type = None compressor = None decompressor = None endpoint = None ssl_options = None ssl_context = None last_error = None # The current number of operations that are in flight. More precisely, # the number of request IDs that are currently in use. in_flight = 0 # Max concurrent requests allowed per connection. This is set optimistically high, allowing # all request ids to be used in protocol version 3+. Normally concurrency would be controlled # at a higher level by the application or concurrent.execute_concurrent. This attribute # is for lower-level integrations that want some upper bound without reimplementing. max_in_flight = 2 ** 15 # A set of available request IDs. When using the v3 protocol or higher, # this will not initially include all request IDs in order to save memory, # but the set will grow if it is exhausted. request_ids = None # Tracks the highest used request ID in order to help with growing the # request_ids set highest_request_id = 0 is_defunct = False is_closed = False lock = None user_type_map = None msg_received = False is_unsupported_proto_version = False is_control_connection = False signaled_error = False # used for flagging at the pool level allow_beta_protocol_version = False - _iobuf = None _current_frame = None _socket = None _socket_impl = socket _ssl_impl = ssl _check_hostname = False _product_type = None + _is_checksumming_enabled = False + + @property + def _iobuf(self): + # backward compatibility, to avoid any change in the reactors + return self._io_buffer.io_buffer + def __init__(self, host='127.0.0.1', port=9042, authenticator=None, ssl_options=None, sockopts=None, compression=True, cql_version=None, protocol_version=ProtocolVersion.MAX_SUPPORTED, is_control_connection=False, user_type_map=None, connect_timeout=None, allow_beta_protocol_version=False, no_compact=False, ssl_context=None): # TODO next major rename host to endpoint and remove port kwarg. self.endpoint = host if isinstance(host, EndPoint) else DefaultEndPoint(host, port) self.authenticator = authenticator self.ssl_options = ssl_options.copy() if ssl_options else None self.ssl_context = ssl_context self.sockopts = sockopts self.compression = compression self.cql_version = cql_version self.protocol_version = protocol_version self.is_control_connection = is_control_connection self.user_type_map = user_type_map self.connect_timeout = connect_timeout self.allow_beta_protocol_version = allow_beta_protocol_version self.no_compact = no_compact self._push_watchers = defaultdict(set) self._requests = {} - self._iobuf = io.BytesIO() + self._io_buffer = _ConnectionIOBuffer(self) + self._continuous_paging_sessions = {} + self._socket_writable = True if ssl_options: self._check_hostname = bool(self.ssl_options.pop('check_hostname', False)) if self._check_hostname: if not getattr(ssl, 'match_hostname', None): raise RuntimeError("ssl_options specify 'check_hostname', but ssl.match_hostname is not provided. " "Patch or upgrade Python to use this option.") self.ssl_options.update(self.endpoint.ssl_options or {}) elif self.endpoint.ssl_options: self.ssl_options = self.endpoint.ssl_options if protocol_version >= 3: self.max_request_id = min(self.max_in_flight - 1, (2 ** 15) - 1) # Don't fill the deque with 2**15 items right away. Start with some and add # more if needed. initial_size = min(300, self.max_in_flight) self.request_ids = deque(range(initial_size)) self.highest_request_id = initial_size - 1 else: self.max_request_id = min(self.max_in_flight, (2 ** 7) - 1) self.request_ids = deque(range(self.max_request_id + 1)) self.highest_request_id = self.max_request_id self.lock = RLock() self.connected_event = Event() @property def host(self): return self.endpoint.address @property def port(self): return self.endpoint.port @classmethod def initialize_reactor(cls): """ Called once by Cluster.connect(). This should be used by implementations to set up any resources that will be shared across connections. """ pass @classmethod def handle_fork(cls): """ Called after a forking. This should cleanup any remaining reactor state from the parent process. """ pass @classmethod def create_timer(cls, timeout, callback): raise NotImplementedError() @classmethod def factory(cls, endpoint, timeout, *args, **kwargs): """ A factory function which returns connections which have succeeded in connecting and are ready for service (or raises an exception otherwise). """ start = time.time() kwargs['connect_timeout'] = timeout conn = cls(endpoint, *args, **kwargs) elapsed = time.time() - start conn.connected_event.wait(timeout - elapsed) if conn.last_error: if conn.is_unsupported_proto_version: raise ProtocolVersionUnsupported(endpoint, conn.protocol_version) raise conn.last_error elif not conn.connected_event.is_set(): conn.close() raise OperationTimedOut("Timed out creating connection (%s seconds)" % timeout) else: return conn + def _wrap_socket_from_context(self): + ssl_options = self.ssl_options or {} + # PYTHON-1186: set the server_hostname only if the SSLContext has + # check_hostname enabled and it is not already provided by the EndPoint ssl options + if (self.ssl_context.check_hostname and + 'server_hostname' not in ssl_options): + ssl_options = ssl_options.copy() + ssl_options['server_hostname'] = self.endpoint.address + self._socket = self.ssl_context.wrap_socket(self._socket, **ssl_options) + + def _initiate_connection(self, sockaddr): + self._socket.connect(sockaddr) + + def _match_hostname(self): + ssl.match_hostname(self._socket.getpeercert(), self.endpoint.address) + def _get_socket_addresses(self): address, port = self.endpoint.resolve() if hasattr(socket, 'AF_UNIX') and self.endpoint.socket_family == socket.AF_UNIX: return [(socket.AF_UNIX, socket.SOCK_STREAM, 0, None, address)] addresses = socket.getaddrinfo(address, port, self.endpoint.socket_family, socket.SOCK_STREAM) if not addresses: raise ConnectionException("getaddrinfo returned empty list for %s" % (self.endpoint,)) return addresses def _connect_socket(self): sockerr = None addresses = self._get_socket_addresses() for (af, socktype, proto, _, sockaddr) in addresses: try: self._socket = self._socket_impl.socket(af, socktype, proto) if self.ssl_context: - self._socket = self.ssl_context.wrap_socket(self._socket, - **(self.ssl_options or {})) + self._wrap_socket_from_context() elif self.ssl_options: if not self._ssl_impl: raise RuntimeError("This version of Python was not compiled with SSL support") self._socket = self._ssl_impl.wrap_socket(self._socket, **self.ssl_options) self._socket.settimeout(self.connect_timeout) - self._socket.connect(sockaddr) + self._initiate_connection(sockaddr) self._socket.settimeout(None) if self._check_hostname: - ssl.match_hostname(self._socket.getpeercert(), self.endpoint.address) + self._match_hostname() sockerr = None break except socket.error as err: if self._socket: self._socket.close() self._socket = None sockerr = err if sockerr: raise socket.error(sockerr.errno, "Tried connecting to %s. Last error: %s" % ([a[4] for a in addresses], sockerr.strerror or sockerr)) if self.sockopts: for args in self.sockopts: self._socket.setsockopt(*args) + def _enable_compression(self): + if self._compressor: + self.compressor = self._compressor + + def _enable_checksumming(self): + self._io_buffer.set_checksumming_buffer() + self._is_checksumming_enabled = True + self._segment_codec = segment_codec_lz4 if self.compressor else segment_codec_no_compression + log.debug("Enabling protocol checksumming on connection (%s).", id(self)) + def close(self): raise NotImplementedError() def defunct(self, exc): with self.lock: if self.is_defunct or self.is_closed: return self.is_defunct = True exc_info = sys.exc_info() # if we are not handling an exception, just use the passed exception, and don't try to format exc_info with the message if any(exc_info): log.debug("Defuncting connection (%s) to %s:", id(self), self.endpoint, exc_info=exc_info) else: log.debug("Defuncting connection (%s) to %s: %s", id(self), self.endpoint, exc) self.last_error = exc self.close() + self.error_all_cp_sessions(exc) self.error_all_requests(exc) self.connected_event.set() return exc + def error_all_cp_sessions(self, exc): + stream_ids = list(self._continuous_paging_sessions.keys()) + for stream_id in stream_ids: + self._continuous_paging_sessions[stream_id].on_error(exc) + def error_all_requests(self, exc): with self.lock: requests = self._requests self._requests = {} if not requests: return new_exc = ConnectionShutdown(str(exc)) + def try_callback(cb): try: cb(new_exc) except Exception: log.warning("Ignoring unhandled exception while erroring requests for a " "failed connection (%s) to host %s:", id(self), self.endpoint, exc_info=True) # run first callback from this thread to ensure pool state before leaving cb, _, _ = requests.popitem()[1] try_callback(cb) if not requests: return # additional requests are optionally errored from a separate thread # The default callback and retry logic is fairly expensive -- we don't # want to tie up the event thread when there are many requests def err_all_callbacks(): for cb, _, _ in requests.values(): try_callback(cb) if len(requests) < Connection.CALLBACK_ERR_THREAD_THRESHOLD: err_all_callbacks() else: # daemon thread here because we want to stay decoupled from the cluster TPE # TODO: would it make sense to just have a driver-global TPE? t = Thread(target=err_all_callbacks) t.daemon = True t.start() def get_request_id(self): """ This must be called while self.lock is held. """ try: return self.request_ids.popleft() except IndexError: new_request_id = self.highest_request_id + 1 # in_flight checks should guarantee this assert new_request_id <= self.max_request_id self.highest_request_id = new_request_id return self.highest_request_id def handle_pushed(self, response): log.debug("Message pushed from server: %r", response) for cb in self._push_watchers.get(response.event_type, []): try: cb(response.event_args) except Exception: log.exception("Pushed event handler errored, ignoring:") def send_msg(self, msg, request_id, cb, encoder=ProtocolHandler.encode_message, decoder=ProtocolHandler.decode_message, result_metadata=None): if self.is_defunct: raise ConnectionShutdown("Connection to %s is defunct" % self.endpoint) elif self.is_closed: raise ConnectionShutdown("Connection to %s is closed" % self.endpoint) + elif not self._socket_writable: + raise ConnectionBusy("Connection %s is overloaded" % self.endpoint) # queue the decoder function with the request # this allows us to inject custom functions per request to encode, decode messages self._requests[request_id] = (cb, decoder, result_metadata) - msg = encoder(msg, request_id, self.protocol_version, compressor=self.compressor, allow_beta_protocol_version=self.allow_beta_protocol_version) + msg = encoder(msg, request_id, self.protocol_version, compressor=self.compressor, + allow_beta_protocol_version=self.allow_beta_protocol_version) + + if self._is_checksumming_enabled: + buffer = io.BytesIO() + self._segment_codec.encode(buffer, msg) + msg = buffer.getvalue() + self.push(msg) return len(msg) def wait_for_response(self, msg, timeout=None, **kwargs): return self.wait_for_responses(msg, timeout=timeout, **kwargs)[0] def wait_for_responses(self, *msgs, **kwargs): """ Returns a list of (success, response) tuples. If success is False, response will be an Exception. Otherwise, response will be the normal query response. If fail_on_error was left as True and one of the requests failed, the corresponding Exception will be raised. """ if self.is_closed or self.is_defunct: raise ConnectionShutdown("Connection %s is already closed" % (self, )) timeout = kwargs.get('timeout') fail_on_error = kwargs.get('fail_on_error', True) waiter = ResponseWaiter(self, len(msgs), fail_on_error) # busy wait for sufficient space on the connection messages_sent = 0 while True: needed = len(msgs) - messages_sent with self.lock: available = min(needed, self.max_request_id - self.in_flight + 1) request_ids = [self.get_request_id() for _ in range(available)] self.in_flight += available for i, request_id in enumerate(request_ids): self.send_msg(msgs[messages_sent + i], request_id, partial(waiter.got_response, index=messages_sent + i)) messages_sent += available if messages_sent == len(msgs): break else: if timeout is not None: timeout -= 0.01 if timeout <= 0.0: raise OperationTimedOut() time.sleep(0.01) try: return waiter.deliver(timeout) except OperationTimedOut: raise except Exception as exc: self.defunct(exc) raise def register_watcher(self, event_type, callback, register_timeout=None): """ Register a callback for a given event type. """ self._push_watchers[event_type].add(callback) self.wait_for_response( RegisterMessage(event_list=[event_type]), timeout=register_timeout) def register_watchers(self, type_callback_dict, register_timeout=None): """ Register multiple callback/event type pairs, expressed as a dict. """ for event_type, callback in type_callback_dict.items(): self._push_watchers[event_type].add(callback) self.wait_for_response( RegisterMessage(event_list=type_callback_dict.keys()), timeout=register_timeout) def control_conn_disposed(self): self.is_control_connection = False self._push_watchers = {} @defunct_on_error def _read_frame_header(self): - buf = self._iobuf.getvalue() + buf = self._io_buffer.cql_frame_buffer.getvalue() pos = len(buf) if pos: version = int_from_buf_item(buf[0]) & PROTOCOL_VERSION_MASK - if version > ProtocolVersion.MAX_SUPPORTED: + if version not in ProtocolVersion.SUPPORTED_VERSIONS: raise ProtocolError("This version of the driver does not support protocol version %d" % version) frame_header = frame_header_v3 if version >= 3 else frame_header_v1_v2 # this frame header struct is everything after the version byte header_size = frame_header.size + 1 if pos >= header_size: flags, stream, op, body_len = frame_header.unpack_from(buf, 1) if body_len < 0: raise ProtocolError("Received negative body length: %r" % body_len) self._current_frame = _Frame(version, flags, stream, op, header_size, body_len + header_size) return pos - def _reset_frame(self): - self._iobuf = io.BytesIO(self._iobuf.read()) - self._iobuf.seek(0, 2) # io.SEEK_END == 2 (constant not present in 2.6) - self._current_frame = None + @defunct_on_error + def _process_segment_buffer(self): + readable_bytes = self._io_buffer.readable_io_bytes() + if readable_bytes >= self._segment_codec.header_length_with_crc: + try: + self._io_buffer.io_buffer.seek(0) + segment_header = self._segment_codec.decode_header(self._io_buffer.io_buffer) + + if readable_bytes >= segment_header.segment_length: + segment = self._segment_codec.decode(self._iobuf, segment_header) + self._io_buffer._segment_consumed = True + self._io_buffer.cql_frame_buffer.write(segment.payload) + else: + # not enough data to read the segment. reset the buffer pointer at the + # beginning to not lose what we previously read (header). + self._io_buffer._segment_consumed = False + self._io_buffer.io_buffer.seek(0) + except CrcException as exc: + # re-raise an exception that inherits from ConnectionException + raise CrcMismatchException(str(exc), self.endpoint) + else: + self._io_buffer._segment_consumed = False def process_io_buffer(self): while True: + if self._is_checksumming_enabled and self._io_buffer.readable_io_bytes(): + self._process_segment_buffer() + self._io_buffer.reset_io_buffer() + + if self._is_checksumming_enabled and not self._io_buffer.has_consumed_segment: + # We couldn't read an entire segment from the io buffer, so return + # control to allow more bytes to be read off the wire + return + if not self._current_frame: pos = self._read_frame_header() else: - pos = self._iobuf.tell() + pos = self._io_buffer.readable_cql_frame_bytes() if not self._current_frame or pos < self._current_frame.end_pos: + if self._is_checksumming_enabled and self._io_buffer.readable_io_bytes(): + # We have a multi-segments message and we need to read more + # data to complete the current cql frame + continue + # we don't have a complete header yet or we # already saw a header, but we don't have a # complete message yet return else: frame = self._current_frame - self._iobuf.seek(frame.body_offset) - msg = self._iobuf.read(frame.end_pos - frame.body_offset) + self._io_buffer.cql_frame_buffer.seek(frame.body_offset) + msg = self._io_buffer.cql_frame_buffer.read(frame.end_pos - frame.body_offset) self.process_msg(frame, msg) - self._reset_frame() + self._io_buffer.reset_cql_frame_buffer() + self._current_frame = None @defunct_on_error def process_msg(self, header, body): self.msg_received = True stream_id = header.stream if stream_id < 0: callback = None decoder = ProtocolHandler.decode_message result_metadata = None else: - try: - callback, decoder, result_metadata = self._requests.pop(stream_id) - # This can only happen if the stream_id was - # removed due to an OperationTimedOut - except KeyError: - return - - with self.lock: - self.request_ids.append(stream_id) + if stream_id in self._continuous_paging_sessions: + paging_session = self._continuous_paging_sessions[stream_id] + callback = paging_session.on_message + decoder = paging_session.decoder + result_metadata = None + else: + try: + callback, decoder, result_metadata = self._requests.pop(stream_id) + # This can only happen if the stream_id was + # removed due to an OperationTimedOut + except KeyError: + return try: response = decoder(header.version, self.user_type_map, stream_id, header.flags, header.opcode, body, self.decompressor, result_metadata) except Exception as exc: log.exception("Error decoding response from Cassandra. " "%s; buffer: %r", header, self._iobuf.getvalue()) if callback is not None: callback(exc) self.defunct(exc) return try: if stream_id >= 0: if isinstance(response, ProtocolException): if 'unsupported protocol version' in response.message: self.is_unsupported_proto_version = True else: log.error("Closing connection %s due to protocol error: %s", self, response.summary_msg()) self.defunct(response) if callback is not None: callback(response) else: self.handle_pushed(response) except Exception: log.exception("Callback handler errored, ignoring:") + # done after callback because the callback might signal this as a paging session + if stream_id >= 0: + if stream_id in self._continuous_paging_sessions: + if self._continuous_paging_sessions[stream_id].released: + self.remove_continuous_paging_session(stream_id) + else: + with self.lock: + self.request_ids.append(stream_id) + + def new_continuous_paging_session(self, stream_id, decoder, row_factory, state): + session = ContinuousPagingSession(stream_id, decoder, row_factory, self, state) + self._continuous_paging_sessions[stream_id] = session + return session + + def remove_continuous_paging_session(self, stream_id): + try: + self._continuous_paging_sessions.pop(stream_id) + with self.lock: + log.debug("Returning cp session stream id %s", stream_id) + self.request_ids.append(stream_id) + except KeyError: + pass + @defunct_on_error def _send_options_message(self): log.debug("Sending initial options message for new connection (%s) to %s", id(self), self.endpoint) self.send_msg(OptionsMessage(), self.get_request_id(), self._handle_options_response) @defunct_on_error def _handle_options_response(self, options_response): if self.is_defunct: return if not isinstance(options_response, SupportedMessage): if isinstance(options_response, ConnectionException): raise options_response else: log.error("Did not get expected SupportedMessage response; " "instead, got: %s", options_response) raise ConnectionException("Did not get expected SupportedMessage " "response; instead, got: %s" % (options_response,)) log.debug("Received options response on new connection (%s) from %s", id(self), self.endpoint) supported_cql_versions = options_response.cql_versions remote_supported_compressions = options_response.options['COMPRESSION'] self._product_type = options_response.options.get('PRODUCT_TYPE', [None])[0] if self.cql_version: if self.cql_version not in supported_cql_versions: raise ProtocolError( "cql_version %r is not supported by remote (w/ native " "protocol). Supported versions: %r" % (self.cql_version, supported_cql_versions)) else: self.cql_version = supported_cql_versions[0] self._compressor = None compression_type = None if self.compression: overlap = (set(locally_supported_compressions.keys()) & set(remote_supported_compressions)) if len(overlap) == 0: log.debug("No available compression types supported on both ends." " locally supported: %r. remotely supported: %r", locally_supported_compressions.keys(), remote_supported_compressions) else: compression_type = None if isinstance(self.compression, six.string_types): # the user picked a specific compression type ('snappy' or 'lz4') if self.compression not in remote_supported_compressions: raise ProtocolError( "The requested compression type (%s) is not supported by the Cassandra server at %s" % (self.compression, self.endpoint)) compression_type = self.compression else: # our locally supported compressions are ordered to prefer # lz4, if available for k in locally_supported_compressions.keys(): if k in overlap: compression_type = k break - # set the decompressor here, but set the compressor only after - # a successful Ready message - self._compressor, self.decompressor = \ - locally_supported_compressions[compression_type] + # If snappy compression is selected with v5+checksumming, the connection + # will fail with OTO. Only lz4 is supported + if (compression_type == 'snappy' and + ProtocolVersion.has_checksumming_support(self.protocol_version)): + log.debug("Snappy compression is not supported with protocol version %s and " + "checksumming. Consider installing lz4. Disabling compression.", self.protocol_version) + compression_type = None + else: + # set the decompressor here, but set the compressor only after + # a successful Ready message + self._compression_type = compression_type + self._compressor, self.decompressor = \ + locally_supported_compressions[compression_type] self._send_startup_message(compression_type, no_compact=self.no_compact) @defunct_on_error def _send_startup_message(self, compression=None, no_compact=False): log.debug("Sending StartupMessage on %s", self) opts = {'DRIVER_NAME': DRIVER_NAME, 'DRIVER_VERSION': DRIVER_VERSION} if compression: opts['COMPRESSION'] = compression if no_compact: opts['NO_COMPACT'] = 'true' sm = StartupMessage(cqlversion=self.cql_version, options=opts) self.send_msg(sm, self.get_request_id(), cb=self._handle_startup_response) log.debug("Sent StartupMessage on %s", self) @defunct_on_error def _handle_startup_response(self, startup_response, did_authenticate=False): if self.is_defunct: return + if isinstance(startup_response, ReadyMessage): if self.authenticator: log.warning("An authentication challenge was not sent, " "this is suspicious because the driver expects " "authentication (configured authenticator = %s)", self.authenticator.__class__.__name__) log.debug("Got ReadyMessage on new connection (%s) from %s", id(self), self.endpoint) - if self._compressor: - self.compressor = self._compressor + self._enable_compression() + + if ProtocolVersion.has_checksumming_support(self.protocol_version): + self._enable_checksumming() + self.connected_event.set() elif isinstance(startup_response, AuthenticateMessage): log.debug("Got AuthenticateMessage on new connection (%s) from %s: %s", id(self), self.endpoint, startup_response.authenticator) if self.authenticator is None: - raise AuthenticationFailed('Remote end requires authentication.') + log.error("Failed to authenticate to %s. If you are trying to connect to a DSE cluster, " + "consider using TransitionalModePlainTextAuthProvider " + "if DSE authentication is configured with transitional mode" % (self.host,)) + raise AuthenticationFailed('Remote end requires authentication') + + self._enable_compression() + if ProtocolVersion.has_checksumming_support(self.protocol_version): + self._enable_checksumming() if isinstance(self.authenticator, dict): log.debug("Sending credentials-based auth response on %s", self) cm = CredentialsMessage(creds=self.authenticator) callback = partial(self._handle_startup_response, did_authenticate=True) self.send_msg(cm, self.get_request_id(), cb=callback) else: log.debug("Sending SASL-based auth response on %s", self) self.authenticator.server_authenticator_class = startup_response.authenticator initial_response = self.authenticator.initial_response() initial_response = "" if initial_response is None else initial_response - self.send_msg(AuthResponseMessage(initial_response), self.get_request_id(), self._handle_auth_response) + self.send_msg(AuthResponseMessage(initial_response), self.get_request_id(), + self._handle_auth_response) elif isinstance(startup_response, ErrorMessage): log.debug("Received ErrorMessage on new connection (%s) from %s: %s", id(self), self.endpoint, startup_response.summary_msg()) if did_authenticate: raise AuthenticationFailed( "Failed to authenticate to %s: %s" % (self.endpoint, startup_response.summary_msg())) else: raise ConnectionException( "Failed to initialize new connection to %s: %s" % (self.endpoint, startup_response.summary_msg())) elif isinstance(startup_response, ConnectionShutdown): log.debug("Connection to %s was closed during the startup handshake", (self.endpoint)) raise startup_response else: msg = "Unexpected response during Connection setup: %r" log.error(msg, startup_response) raise ProtocolError(msg % (startup_response,)) @defunct_on_error def _handle_auth_response(self, auth_response): if self.is_defunct: return if isinstance(auth_response, AuthSuccessMessage): log.debug("Connection %s successfully authenticated", self) self.authenticator.on_authentication_success(auth_response.token) if self._compressor: self.compressor = self._compressor self.connected_event.set() elif isinstance(auth_response, AuthChallengeMessage): response = self.authenticator.evaluate_challenge(auth_response.challenge) msg = AuthResponseMessage("" if response is None else response) log.debug("Responding to auth challenge on %s", self) self.send_msg(msg, self.get_request_id(), self._handle_auth_response) elif isinstance(auth_response, ErrorMessage): log.debug("Received ErrorMessage on new connection (%s) from %s: %s", id(self), self.endpoint, auth_response.summary_msg()) raise AuthenticationFailed( "Failed to authenticate to %s: %s" % (self.endpoint, auth_response.summary_msg())) elif isinstance(auth_response, ConnectionShutdown): log.debug("Connection to %s was closed during the authentication process", self.endpoint) raise auth_response else: msg = "Unexpected response during Connection authentication to %s: %r" log.error(msg, self.endpoint, auth_response) raise ProtocolError(msg % (self.endpoint, auth_response)) def set_keyspace_blocking(self, keyspace): if not keyspace or keyspace == self.keyspace: return query = QueryMessage(query='USE "%s"' % (keyspace,), consistency_level=ConsistencyLevel.ONE) try: result = self.wait_for_response(query) except InvalidRequestException as ire: # the keyspace probably doesn't exist raise ire.to_exception() except Exception as exc: conn_exc = ConnectionException( "Problem while setting keyspace: %r" % (exc,), self.endpoint) self.defunct(conn_exc) raise conn_exc if isinstance(result, ResultMessage): self.keyspace = keyspace else: conn_exc = ConnectionException( "Problem while setting keyspace: %r" % (result,), self.endpoint) self.defunct(conn_exc) raise conn_exc def set_keyspace_async(self, keyspace, callback): """ Use this in order to avoid deadlocking the event loop thread. When the operation completes, `callback` will be called with two arguments: this connection and an Exception if an error occurred, otherwise :const:`None`. This method will always increment :attr:`.in_flight` attribute, even if it doesn't need to make a request, just to maintain an ":attr:`.in_flight` is incremented" invariant. """ # Here we increment in_flight unconditionally, whether we need to issue # a request or not. This is bad, but allows callers -- specifically # _set_keyspace_for_all_conns -- to assume that we increment # self.in_flight during this call. This allows the passed callback to # safely call HostConnection{Pool,}.return_connection on this # Connection. # # We use a busy wait on the lock here because: # - we'll only spin if the connection is at max capacity, which is very # unlikely for a set_keyspace call # - it allows us to avoid signaling a condition every time a request completes while True: with self.lock: if self.in_flight < self.max_request_id: self.in_flight += 1 break time.sleep(0.001) if not keyspace or keyspace == self.keyspace: callback(self, None) return query = QueryMessage(query='USE "%s"' % (keyspace,), consistency_level=ConsistencyLevel.ONE) def process_result(result): if isinstance(result, ResultMessage): self.keyspace = keyspace callback(self, None) elif isinstance(result, InvalidRequestException): callback(self, result.to_exception()) else: callback(self, self.defunct(ConnectionException( "Problem while setting keyspace: %r" % (result,), self.endpoint))) # We've incremented self.in_flight above, so we "have permission" to # acquire a new request id request_id = self.get_request_id() self.send_msg(query, request_id, process_result) @property def is_idle(self): return not self.msg_received def reset_idle(self): self.msg_received = False def __str__(self): status = "" if self.is_defunct: status = " (defunct)" elif self.is_closed: status = " (closed)" return "<%s(%r) %s%s>" % (self.__class__.__name__, id(self), self.endpoint, status) __repr__ = __str__ class ResponseWaiter(object): def __init__(self, connection, num_responses, fail_on_error): self.connection = connection self.pending = num_responses self.fail_on_error = fail_on_error self.error = None self.responses = [None] * num_responses self.event = Event() def got_response(self, response, index): with self.connection.lock: self.connection.in_flight -= 1 if isinstance(response, Exception): if hasattr(response, 'to_exception'): response = response.to_exception() if self.fail_on_error: self.error = response self.event.set() else: self.responses[index] = (False, response) else: if not self.fail_on_error: self.responses[index] = (True, response) else: self.responses[index] = response self.pending -= 1 if not self.pending: self.event.set() def deliver(self, timeout=None): """ If fail_on_error was set to False, a list of (success, response) tuples will be returned. If success is False, response will be an Exception. Otherwise, response will be the normal query response. If fail_on_error was left as True and one of the requests failed, the corresponding Exception will be raised. Otherwise, the normal response will be returned. """ self.event.wait(timeout) if self.error: raise self.error elif not self.event.is_set(): raise OperationTimedOut() else: return self.responses class HeartbeatFuture(object): def __init__(self, connection, owner): self._exception = None self._event = Event() self.connection = connection self.owner = owner log.debug("Sending options message heartbeat on idle connection (%s) %s", id(connection), connection.endpoint) with connection.lock: - if connection.in_flight <= connection.max_request_id: + if connection.in_flight < connection.max_request_id: connection.in_flight += 1 connection.send_msg(OptionsMessage(), connection.get_request_id(), self._options_callback) else: self._exception = Exception("Failed to send heartbeat because connection 'in_flight' exceeds threshold") self._event.set() def wait(self, timeout): self._event.wait(timeout) if self._event.is_set(): if self._exception: raise self._exception else: raise OperationTimedOut("Connection heartbeat timeout after %s seconds" % (timeout,), self.connection.endpoint) def _options_callback(self, response): if isinstance(response, SupportedMessage): log.debug("Received options response on connection (%s) from %s", id(self.connection), self.connection.endpoint) else: if isinstance(response, ConnectionException): self._exception = response else: self._exception = ConnectionException("Received unexpected response to OptionsMessage: %s" % (response,)) self._event.set() class ConnectionHeartbeat(Thread): def __init__(self, interval_sec, get_connection_holders, timeout): Thread.__init__(self, name="Connection heartbeat") self._interval = interval_sec self._timeout = timeout self._get_connection_holders = get_connection_holders self._shutdown_event = Event() self.daemon = True self.start() class ShutdownException(Exception): pass def run(self): self._shutdown_event.wait(self._interval) while not self._shutdown_event.is_set(): start_time = time.time() futures = [] failed_connections = [] try: for connections, owner in [(o.get_connections(), o) for o in self._get_connection_holders()]: for connection in connections: self._raise_if_stopped() if not (connection.is_defunct or connection.is_closed): if connection.is_idle: try: futures.append(HeartbeatFuture(connection, owner)) except Exception as e: log.warning("Failed sending heartbeat message on connection (%s) to %s", id(connection), connection.endpoint) failed_connections.append((connection, owner, e)) else: connection.reset_idle() else: log.debug("Cannot send heartbeat message on connection (%s) to %s", id(connection), connection.endpoint) # make sure the owner sees this defunt/closed connection owner.return_connection(connection) self._raise_if_stopped() # Wait max `self._timeout` seconds for all HeartbeatFutures to complete timeout = self._timeout start_time = time.time() for f in futures: self._raise_if_stopped() connection = f.connection try: f.wait(timeout) # TODO: move this, along with connection locks in pool, down into Connection with connection.lock: connection.in_flight -= 1 connection.reset_idle() except Exception as e: log.warning("Heartbeat failed for connection (%s) to %s", id(connection), connection.endpoint) failed_connections.append((f.connection, f.owner, e)) timeout = self._timeout - (time.time() - start_time) for connection, owner, exc in failed_connections: self._raise_if_stopped() if not connection.is_control_connection: # Only HostConnection supports shutdown_on_error owner.shutdown_on_error = True connection.defunct(exc) owner.return_connection(connection) except self.ShutdownException: pass except Exception: log.error("Failed connection heartbeat", exc_info=True) elapsed = time.time() - start_time self._shutdown_event.wait(max(self._interval - elapsed, 0.01)) def stop(self): self._shutdown_event.set() self.join() def _raise_if_stopped(self): if self._shutdown_event.is_set(): raise self.ShutdownException() class Timer(object): canceled = False def __init__(self, timeout, callback): self.end = time.time() + timeout self.callback = callback def __lt__(self, other): return self.end < other.end def cancel(self): self.canceled = True def finish(self, time_now): if self.canceled: return True if time_now >= self.end: self.callback() return True return False class TimerManager(object): def __init__(self): self._queue = [] self._new_timers = [] def add_timer(self, timer): """ called from client thread with a Timer object """ self._new_timers.append((timer.end, timer)) def service_timeouts(self): """ run callbacks on all expired timers Called from the event thread :return: next end time, or None """ queue = self._queue if self._new_timers: new_timers = self._new_timers while new_timers: heappush(queue, new_timers.pop()) if queue: now = time.time() while queue: try: timer = queue[0][1] if timer.finish(now): heappop(queue) else: return timer.end except Exception: log.exception("Exception while servicing timeout callback: ") @property def next_timeout(self): try: return self._queue[0][0] except IndexError: pass diff --git a/cassandra/cqlengine/connection.py b/cassandra/cqlengine/connection.py index 884e04e..90e6d90 100644 --- a/cassandra/cqlengine/connection.py +++ b/cassandra/cqlengine/connection.py @@ -1,384 +1,392 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections import defaultdict import logging import six import threading from cassandra.cluster import Cluster, _ConfigMode, _NOT_SET, NoHostAvailable, UserTypeDoesNotExist, ConsistencyLevel from cassandra.query import SimpleStatement, dict_factory from cassandra.cqlengine import CQLEngineException from cassandra.cqlengine.statements import BaseCQLStatement log = logging.getLogger(__name__) NOT_SET = _NOT_SET # required for passing timeout to Session.execute cluster = None session = None # connections registry DEFAULT_CONNECTION = object() _connections = {} # Because type models may be registered before a connection is present, # and because sessions may be replaced, we must register UDTs here, in order # to have them registered when a new session is established. udt_by_keyspace = defaultdict(dict) def format_log_context(msg, connection=None, keyspace=None): """Format log message to add keyspace and connection context""" connection_info = connection or 'DEFAULT_CONNECTION' if keyspace: msg = '[Connection: {0}, Keyspace: {1}] {2}'.format(connection_info, keyspace, msg) else: msg = '[Connection: {0}] {1}'.format(connection_info, msg) return msg class UndefinedKeyspaceException(CQLEngineException): pass class Connection(object): """CQLEngine Connection""" name = None hosts = None consistency = None retry_connect = False lazy_connect = False lazy_connect_lock = None cluster_options = None cluster = None session = None def __init__(self, name, hosts, consistency=None, lazy_connect=False, retry_connect=False, cluster_options=None): self.hosts = hosts self.name = name self.consistency = consistency self.lazy_connect = lazy_connect self.retry_connect = retry_connect self.cluster_options = cluster_options if cluster_options else {} self.lazy_connect_lock = threading.RLock() @classmethod def from_session(cls, name, session): instance = cls(name=name, hosts=session.hosts) instance.cluster, instance.session = session.cluster, session instance.setup_session() return instance def setup(self): """Setup the connection""" global cluster, session if 'username' in self.cluster_options or 'password' in self.cluster_options: raise CQLEngineException("Username & Password are now handled by using the native driver's auth_provider") if self.lazy_connect: return - self.cluster = Cluster(self.hosts, **self.cluster_options) + if 'cloud' in self.cluster_options: + if self.hosts: + log.warning("Ignoring hosts %s because a cloud config was provided.", self.hosts) + self.cluster = Cluster(**self.cluster_options) + else: + self.cluster = Cluster(self.hosts, **self.cluster_options) + try: self.session = self.cluster.connect() log.debug(format_log_context("connection initialized with internally created session", connection=self.name)) except NoHostAvailable: if self.retry_connect: log.warning(format_log_context("connect failed, setting up for re-attempt on first use", connection=self.name)) self.lazy_connect = True raise if DEFAULT_CONNECTION in _connections and _connections[DEFAULT_CONNECTION] == self: cluster = _connections[DEFAULT_CONNECTION].cluster session = _connections[DEFAULT_CONNECTION].session self.setup_session() def setup_session(self): if self.cluster._config_mode == _ConfigMode.PROFILES: self.cluster.profile_manager.default.row_factory = dict_factory if self.consistency is not None: self.cluster.profile_manager.default.consistency_level = self.consistency else: self.session.row_factory = dict_factory if self.consistency is not None: self.session.default_consistency_level = self.consistency enc = self.session.encoder enc.mapping[tuple] = enc.cql_encode_tuple _register_known_types(self.session.cluster) def handle_lazy_connect(self): # if lazy_connect is False, it means the cluster is setup and ready # No need to acquire the lock if not self.lazy_connect: return with self.lazy_connect_lock: # lazy_connect might have been set to False by another thread while waiting the lock # In this case, do nothing. if self.lazy_connect: log.debug(format_log_context("Lazy connect enabled", connection=self.name)) self.lazy_connect = False self.setup() def register_connection(name, hosts=None, consistency=None, lazy_connect=False, retry_connect=False, cluster_options=None, default=False, session=None): """ Add a connection to the connection registry. ``hosts`` and ``session`` are mutually exclusive, and ``consistency``, ``lazy_connect``, ``retry_connect``, and ``cluster_options`` only work with ``hosts``. Using ``hosts`` will create a new :class:`cassandra.cluster.Cluster` and :class:`cassandra.cluster.Session`. :param list hosts: list of hosts, (``contact_points`` for :class:`cassandra.cluster.Cluster`). :param int consistency: The default :class:`~.ConsistencyLevel` for the registered connection's new session. Default is the same as :attr:`.Session.default_consistency_level`. For use with ``hosts`` only; will fail when used with ``session``. :param bool lazy_connect: True if should not connect until first use. For use with ``hosts`` only; will fail when used with ``session``. :param bool retry_connect: True if we should retry to connect even if there was a connection failure initially. For use with ``hosts`` only; will fail when used with ``session``. :param dict cluster_options: A dict of options to be used as keyword arguments to :class:`cassandra.cluster.Cluster`. For use with ``hosts`` only; will fail when used with ``session``. :param bool default: If True, set the new connection as the cqlengine default :param Session session: A :class:`cassandra.cluster.Session` to be used in the created connection. """ if name in _connections: log.warning("Registering connection '{0}' when it already exists.".format(name)) if session is not None: invalid_config_args = (hosts is not None or consistency is not None or lazy_connect is not False or retry_connect is not False or cluster_options is not None) if invalid_config_args: raise CQLEngineException( "Session configuration arguments and 'session' argument are mutually exclusive" ) conn = Connection.from_session(name, session=session) else: # use hosts argument conn = Connection( name, hosts=hosts, consistency=consistency, lazy_connect=lazy_connect, retry_connect=retry_connect, cluster_options=cluster_options ) conn.setup() _connections[name] = conn if default: set_default_connection(name) return conn def unregister_connection(name): global cluster, session if name not in _connections: return if DEFAULT_CONNECTION in _connections and _connections[name] == _connections[DEFAULT_CONNECTION]: del _connections[DEFAULT_CONNECTION] cluster = None session = None conn = _connections[name] if conn.cluster: conn.cluster.shutdown() del _connections[name] log.debug("Connection '{0}' has been removed from the registry.".format(name)) def set_default_connection(name): global cluster, session if name not in _connections: raise CQLEngineException("Connection '{0}' doesn't exist.".format(name)) log.debug("Connection '{0}' has been set as default.".format(name)) _connections[DEFAULT_CONNECTION] = _connections[name] cluster = _connections[name].cluster session = _connections[name].session def get_connection(name=None): if not name: name = DEFAULT_CONNECTION if name not in _connections: raise CQLEngineException("Connection name '{0}' doesn't exist in the registry.".format(name)) conn = _connections[name] conn.handle_lazy_connect() return conn def default(): """ Configures the default connection to localhost, using the driver defaults (except for row_factory) """ try: conn = get_connection() if conn.session: log.warning("configuring new default connection for cqlengine when one was already set") except: pass register_connection('default', hosts=None, default=True) log.debug("cqlengine connection initialized with default session to localhost") def set_session(s): """ Configures the default connection with a preexisting :class:`cassandra.cluster.Session` Note: the mapper presently requires a Session :attr:`~.row_factory` set to ``dict_factory``. This may be relaxed in the future """ try: conn = get_connection() except CQLEngineException: # no default connection set; initalize one register_connection('default', session=s, default=True) conn = get_connection() else: if conn.session: log.warning("configuring new default session for cqlengine when one was already set") if not any([ s.cluster.profile_manager.default.row_factory is dict_factory and s.cluster._config_mode in [_ConfigMode.PROFILES, _ConfigMode.UNCOMMITTED], s.row_factory is dict_factory and s.cluster._config_mode in [_ConfigMode.LEGACY, _ConfigMode.UNCOMMITTED], ]): raise CQLEngineException("Failed to initialize: row_factory must be 'dict_factory'") conn.session = s conn.cluster = s.cluster # Set default keyspace from given session's keyspace if conn.session.keyspace: from cassandra.cqlengine import models models.DEFAULT_KEYSPACE = conn.session.keyspace conn.setup_session() log.debug("cqlengine default connection initialized with %s", s) +# TODO next major: if a cloud config is specified in kwargs, hosts will be ignored. +# This function should be refactored to reflect this change. PYTHON-1265 def setup( hosts, default_keyspace, consistency=None, lazy_connect=False, retry_connect=False, **kwargs): """ Setup a the driver connection used by the mapper :param list hosts: list of hosts, (``contact_points`` for :class:`cassandra.cluster.Cluster`) :param str default_keyspace: The default keyspace to use :param int consistency: The global default :class:`~.ConsistencyLevel` - default is the same as :attr:`.Session.default_consistency_level` :param bool lazy_connect: True if should not connect until first use :param bool retry_connect: True if we should retry to connect even if there was a connection failure initially :param \*\*kwargs: Pass-through keyword arguments for :class:`cassandra.cluster.Cluster` """ from cassandra.cqlengine import models models.DEFAULT_KEYSPACE = default_keyspace register_connection('default', hosts=hosts, consistency=consistency, lazy_connect=lazy_connect, retry_connect=retry_connect, cluster_options=kwargs, default=True) def execute(query, params=None, consistency_level=None, timeout=NOT_SET, connection=None): conn = get_connection(connection) if not conn.session: raise CQLEngineException("It is required to setup() cqlengine before executing queries") if isinstance(query, SimpleStatement): pass # elif isinstance(query, BaseCQLStatement): params = query.get_context() query = SimpleStatement(str(query), consistency_level=consistency_level, fetch_size=query.fetch_size) elif isinstance(query, six.string_types): query = SimpleStatement(query, consistency_level=consistency_level) log.debug(format_log_context('Query: {}, Params: {}'.format(query.query_string, params), connection=connection)) result = conn.session.execute(query, params, timeout=timeout) return result def get_session(connection=None): conn = get_connection(connection) return conn.session def get_cluster(connection=None): conn = get_connection(connection) if not conn.cluster: raise CQLEngineException("%s.cluster is not configured. Call one of the setup or default functions first." % __name__) return conn.cluster def register_udt(keyspace, type_name, klass, connection=None): udt_by_keyspace[keyspace][type_name] = klass try: cluster = get_cluster(connection) except CQLEngineException: cluster = None if cluster: try: cluster.register_user_type(keyspace, type_name, klass) except UserTypeDoesNotExist: pass # new types are covered in management sync functions def _register_known_types(cluster): from cassandra.cqlengine import models for ks_name, name_type_map in udt_by_keyspace.items(): for type_name, klass in name_type_map.items(): try: cluster.register_user_type(ks_name or models.DEFAULT_KEYSPACE, type_name, klass) except UserTypeDoesNotExist: pass # new types are covered in management sync functions diff --git a/cassandra/cqlengine/management.py b/cassandra/cqlengine/management.py index 42ded8a..536bde6 100644 --- a/cassandra/cqlengine/management.py +++ b/cassandra/cqlengine/management.py @@ -1,548 +1,548 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections import namedtuple import json import logging import os import six import warnings from itertools import product from cassandra import metadata from cassandra.cqlengine import CQLEngineException from cassandra.cqlengine import columns, query from cassandra.cqlengine.connection import execute, get_cluster, format_log_context from cassandra.cqlengine.models import Model from cassandra.cqlengine.named import NamedTable from cassandra.cqlengine.usertype import UserType CQLENG_ALLOW_SCHEMA_MANAGEMENT = 'CQLENG_ALLOW_SCHEMA_MANAGEMENT' Field = namedtuple('Field', ['name', 'type']) log = logging.getLogger(__name__) # system keyspaces schema_columnfamilies = NamedTable('system', 'schema_columnfamilies') def _get_context(keyspaces, connections): """Return all the execution contexts""" if keyspaces: if not isinstance(keyspaces, (list, tuple)): raise ValueError('keyspaces must be a list or a tuple.') if connections: if not isinstance(connections, (list, tuple)): raise ValueError('connections must be a list or a tuple.') keyspaces = keyspaces if keyspaces else [None] connections = connections if connections else [None] return product(connections, keyspaces) def create_keyspace_simple(name, replication_factor, durable_writes=True, connections=None): """ Creates a keyspace with SimpleStrategy for replica placement If the keyspace already exists, it will not be modified. **This function should be used with caution, especially in production environments. Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** *There are plans to guard schema-modifying functions with an environment-driven conditional.* :param str name: name of keyspace to create :param int replication_factor: keyspace replication factor, used with :attr:`~.SimpleStrategy` :param bool durable_writes: Write log is bypassed if set to False :param list connections: List of connection names """ _create_keyspace(name, durable_writes, 'SimpleStrategy', {'replication_factor': replication_factor}, connections=connections) def create_keyspace_network_topology(name, dc_replication_map, durable_writes=True, connections=None): """ Creates a keyspace with NetworkTopologyStrategy for replica placement If the keyspace already exists, it will not be modified. **This function should be used with caution, especially in production environments. Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** *There are plans to guard schema-modifying functions with an environment-driven conditional.* :param str name: name of keyspace to create :param dict dc_replication_map: map of dc_names: replication_factor :param bool durable_writes: Write log is bypassed if set to False :param list connections: List of connection names """ _create_keyspace(name, durable_writes, 'NetworkTopologyStrategy', dc_replication_map, connections=connections) def _create_keyspace(name, durable_writes, strategy_class, strategy_options, connections=None): if not _allow_schema_modification(): return if connections: if not isinstance(connections, (list, tuple)): raise ValueError('Connections must be a list or a tuple.') def __create_keyspace(name, durable_writes, strategy_class, strategy_options, connection=None): cluster = get_cluster(connection) if name not in cluster.metadata.keyspaces: log.info(format_log_context("Creating keyspace %s", connection=connection), name) ks_meta = metadata.KeyspaceMetadata(name, durable_writes, strategy_class, strategy_options) execute(ks_meta.as_cql_query(), connection=connection) else: log.info(format_log_context("Not creating keyspace %s because it already exists", connection=connection), name) if connections: for connection in connections: __create_keyspace(name, durable_writes, strategy_class, strategy_options, connection=connection) else: __create_keyspace(name, durable_writes, strategy_class, strategy_options) def drop_keyspace(name, connections=None): """ Drops a keyspace, if it exists. *There are plans to guard schema-modifying functions with an environment-driven conditional.* **This function should be used with caution, especially in production environments. Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** :param str name: name of keyspace to drop :param list connections: List of connection names """ if not _allow_schema_modification(): return if connections: if not isinstance(connections, (list, tuple)): raise ValueError('Connections must be a list or a tuple.') def _drop_keyspace(name, connection=None): cluster = get_cluster(connection) if name in cluster.metadata.keyspaces: execute("DROP KEYSPACE {0}".format(metadata.protect_name(name)), connection=connection) if connections: for connection in connections: _drop_keyspace(name, connection) else: _drop_keyspace(name) def _get_index_name_by_column(table, column_name): """ Find the index name for a given table and column. """ protected_name = metadata.protect_name(column_name) possible_index_values = [protected_name, "values(%s)" % protected_name] for index_metadata in table.indexes.values(): options = dict(index_metadata.index_options) if options.get('target') in possible_index_values: return index_metadata.name def sync_table(model, keyspaces=None, connections=None): """ Inspects the model and creates / updates the corresponding table and columns. If `keyspaces` is specified, the table will be synched for all specified keyspaces. Note that the `Model.__keyspace__` is ignored in that case. If `connections` is specified, the table will be synched for all specified connections. Note that the `Model.__connection__` is ignored in that case. If not specified, it will try to get the connection from the Model. Any User Defined Types used in the table are implicitly synchronized. This function can only add fields that are not part of the primary key. Note that the attributes removed from the model are not deleted on the database. They become effectively ignored by (will not show up on) the model. **This function should be used with caution, especially in production environments. Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** *There are plans to guard schema-modifying functions with an environment-driven conditional.* """ context = _get_context(keyspaces, connections) for connection, keyspace in context: with query.ContextQuery(model, keyspace=keyspace) as m: _sync_table(m, connection=connection) def _sync_table(model, connection=None): if not _allow_schema_modification(): return if not issubclass(model, Model): raise CQLEngineException("Models must be derived from base Model.") if model.__abstract__: raise CQLEngineException("cannot create table from abstract model") cf_name = model.column_family_name() raw_cf_name = model._raw_column_family_name() ks_name = model._get_keyspace() connection = connection or model._get_connection() cluster = get_cluster(connection) try: keyspace = cluster.metadata.keyspaces[ks_name] except KeyError: msg = format_log_context("Keyspace '{0}' for model {1} does not exist.", connection=connection) raise CQLEngineException(msg.format(ks_name, model)) tables = keyspace.tables syncd_types = set() for col in model._columns.values(): udts = [] columns.resolve_udts(col, udts) for udt in [u for u in udts if u not in syncd_types]: _sync_type(ks_name, udt, syncd_types, connection=connection) if raw_cf_name not in tables: log.debug(format_log_context("sync_table creating new table %s", keyspace=ks_name, connection=connection), cf_name) qs = _get_create_table(model) try: execute(qs, connection=connection) except CQLEngineException as ex: # 1.2 doesn't return cf names, so we have to examine the exception # and ignore if it says the column family already exists - if "Cannot add already existing column family" not in unicode(ex): + if "Cannot add already existing column family" not in six.text_type(ex): raise else: log.debug(format_log_context("sync_table checking existing table %s", keyspace=ks_name, connection=connection), cf_name) table_meta = tables[raw_cf_name] _validate_pk(model, table_meta) table_columns = table_meta.columns model_fields = set() for model_name, col in model._columns.items(): db_name = col.db_field_name model_fields.add(db_name) if db_name in table_columns: col_meta = table_columns[db_name] if col_meta.cql_type != col.db_type: msg = format_log_context('Existing table {0} has column "{1}" with a type ({2}) differing from the model type ({3}).' ' Model should be updated.', keyspace=ks_name, connection=connection) msg = msg.format(cf_name, db_name, col_meta.cql_type, col.db_type) warnings.warn(msg) log.warning(msg) continue if col.primary_key or col.primary_key: msg = format_log_context("Cannot add primary key '{0}' (with db_field '{1}') to existing table {2}", keyspace=ks_name, connection=connection) raise CQLEngineException(msg.format(model_name, db_name, cf_name)) query = "ALTER TABLE {0} add {1}".format(cf_name, col.get_column_def()) execute(query, connection=connection) db_fields_not_in_model = model_fields.symmetric_difference(table_columns) if db_fields_not_in_model: msg = format_log_context("Table {0} has fields not referenced by model: {1}", keyspace=ks_name, connection=connection) log.info(msg.format(cf_name, db_fields_not_in_model)) _update_options(model, connection=connection) table = cluster.metadata.keyspaces[ks_name].tables[raw_cf_name] indexes = [c for n, c in model._columns.items() if c.index] # TODO: support multiple indexes in C* 3.0+ for column in indexes: index_name = _get_index_name_by_column(table, column.db_field_name) if index_name: continue qs = ['CREATE INDEX'] qs += ['ON {0}'.format(cf_name)] qs += ['("{0}")'.format(column.db_field_name)] qs = ' '.join(qs) execute(qs, connection=connection) def _validate_pk(model, table_meta): model_partition = [c.db_field_name for c in model._partition_keys.values()] meta_partition = [c.name for c in table_meta.partition_key] model_clustering = [c.db_field_name for c in model._clustering_keys.values()] meta_clustering = [c.name for c in table_meta.clustering_key] if model_partition != meta_partition or model_clustering != meta_clustering: def _pk_string(partition, clustering): return "PRIMARY KEY (({0}){1})".format(', '.join(partition), ', ' + ', '.join(clustering) if clustering else '') raise CQLEngineException("Model {0} PRIMARY KEY composition does not match existing table {1}. " "Model: {2}; Table: {3}. " "Update model or drop the table.".format(model, model.column_family_name(), _pk_string(model_partition, model_clustering), _pk_string(meta_partition, meta_clustering))) def sync_type(ks_name, type_model, connection=None): """ Inspects the type_model and creates / updates the corresponding type. Note that the attributes removed from the type_model are not deleted on the database (this operation is not supported). They become effectively ignored by (will not show up on) the type_model. **This function should be used with caution, especially in production environments. Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** *There are plans to guard schema-modifying functions with an environment-driven conditional.* """ if not _allow_schema_modification(): return if not issubclass(type_model, UserType): raise CQLEngineException("Types must be derived from base UserType.") _sync_type(ks_name, type_model, connection=connection) def _sync_type(ks_name, type_model, omit_subtypes=None, connection=None): syncd_sub_types = omit_subtypes or set() for field in type_model._fields.values(): udts = [] columns.resolve_udts(field, udts) for udt in [u for u in udts if u not in syncd_sub_types]: _sync_type(ks_name, udt, syncd_sub_types, connection=connection) syncd_sub_types.add(udt) type_name = type_model.type_name() type_name_qualified = "%s.%s" % (ks_name, type_name) cluster = get_cluster(connection) keyspace = cluster.metadata.keyspaces[ks_name] defined_types = keyspace.user_types if type_name not in defined_types: log.debug(format_log_context("sync_type creating new type %s", keyspace=ks_name, connection=connection), type_name_qualified) cql = get_create_type(type_model, ks_name) execute(cql, connection=connection) cluster.refresh_user_type_metadata(ks_name, type_name) type_model.register_for_keyspace(ks_name, connection=connection) else: type_meta = defined_types[type_name] defined_fields = type_meta.field_names model_fields = set() for field in type_model._fields.values(): model_fields.add(field.db_field_name) if field.db_field_name not in defined_fields: execute("ALTER TYPE {0} ADD {1}".format(type_name_qualified, field.get_column_def()), connection=connection) else: field_type = type_meta.field_types[defined_fields.index(field.db_field_name)] if field_type != field.db_type: msg = format_log_context('Existing user type {0} has field "{1}" with a type ({2}) differing from the model user type ({3}).' ' UserType should be updated.', keyspace=ks_name, connection=connection) msg = msg.format(type_name_qualified, field.db_field_name, field_type, field.db_type) warnings.warn(msg) log.warning(msg) type_model.register_for_keyspace(ks_name, connection=connection) if len(defined_fields) == len(model_fields): log.info(format_log_context("Type %s did not require synchronization", keyspace=ks_name, connection=connection), type_name_qualified) return db_fields_not_in_model = model_fields.symmetric_difference(defined_fields) if db_fields_not_in_model: msg = format_log_context("Type %s has fields not referenced by model: %s", keyspace=ks_name, connection=connection) log.info(msg, type_name_qualified, db_fields_not_in_model) def get_create_type(type_model, keyspace): type_meta = metadata.UserType(keyspace, type_model.type_name(), (f.db_field_name for f in type_model._fields.values()), (v.db_type for v in type_model._fields.values())) return type_meta.as_cql_query() def _get_create_table(model): ks_table_name = model.column_family_name() query_strings = ['CREATE TABLE {0}'.format(ks_table_name)] # add column types pkeys = [] # primary keys ckeys = [] # clustering keys qtypes = [] # field types def add_column(col): s = col.get_column_def() if col.primary_key: keys = (pkeys if col.partition_key else ckeys) keys.append('"{0}"'.format(col.db_field_name)) qtypes.append(s) for name, col in model._columns.items(): add_column(col) qtypes.append('PRIMARY KEY (({0}){1})'.format(', '.join(pkeys), ckeys and ', ' + ', '.join(ckeys) or '')) query_strings += ['({0})'.format(', '.join(qtypes))] property_strings = [] _order = ['"{0}" {1}'.format(c.db_field_name, c.clustering_order or 'ASC') for c in model._clustering_keys.values()] if _order: property_strings.append('CLUSTERING ORDER BY ({0})'.format(', '.join(_order))) # options strings use the V3 format, which matches CQL more closely and does not require mapping property_strings += metadata.TableMetadataV3._make_option_strings(model.__options__ or {}) if property_strings: query_strings += ['WITH {0}'.format(' AND '.join(property_strings))] return ' '.join(query_strings) def _get_table_metadata(model, connection=None): # returns the table as provided by the native driver for a given model cluster = get_cluster(connection) ks = model._get_keyspace() table = model._raw_column_family_name() table = cluster.metadata.keyspaces[ks].tables[table] return table def _options_map_from_strings(option_strings): # converts options strings to a mapping to strings or dict options = {} for option in option_strings: name, value = option.split('=') i = value.find('{') if i >= 0: value = value[i:value.rfind('}') + 1].replace("'", '"') # from cql single quotes to json double; not aware of any values that would be escaped right now value = json.loads(value) else: value = value.strip() options[name.strip()] = value return options def _update_options(model, connection=None): """Updates the table options for the given model if necessary. :param model: The model to update. :param connection: Name of the connection to use :return: `True`, if the options were modified in Cassandra, `False` otherwise. :rtype: bool """ ks_name = model._get_keyspace() msg = format_log_context("Checking %s for option differences", keyspace=ks_name, connection=connection) log.debug(msg, model) model_options = model.__options__ or {} table_meta = _get_table_metadata(model, connection=connection) # go to CQL string first to normalize meta from different versions existing_option_strings = set(table_meta._make_option_strings(table_meta.options)) existing_options = _options_map_from_strings(existing_option_strings) model_option_strings = metadata.TableMetadataV3._make_option_strings(model_options) model_options = _options_map_from_strings(model_option_strings) update_options = {} for name, value in model_options.items(): try: existing_value = existing_options[name] except KeyError: msg = format_log_context("Invalid table option: '%s'; known options: %s", keyspace=ks_name, connection=connection) raise KeyError(msg % (name, existing_options.keys())) if isinstance(existing_value, six.string_types): if value != existing_value: update_options[name] = value else: try: for k, v in value.items(): if existing_value[k] != v: update_options[name] = value break except KeyError: update_options[name] = value if update_options: options = ' AND '.join(metadata.TableMetadataV3._make_option_strings(update_options)) query = "ALTER TABLE {0} WITH {1}".format(model.column_family_name(), options) execute(query, connection=connection) return True return False def drop_table(model, keyspaces=None, connections=None): """ Drops the table indicated by the model, if it exists. If `keyspaces` is specified, the table will be dropped for all specified keyspaces. Note that the `Model.__keyspace__` is ignored in that case. If `connections` is specified, the table will be synched for all specified connections. Note that the `Model.__connection__` is ignored in that case. If not specified, it will try to get the connection from the Model. **This function should be used with caution, especially in production environments. Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** *There are plans to guard schema-modifying functions with an environment-driven conditional.* """ context = _get_context(keyspaces, connections) for connection, keyspace in context: with query.ContextQuery(model, keyspace=keyspace) as m: _drop_table(m, connection=connection) def _drop_table(model, connection=None): if not _allow_schema_modification(): return connection = connection or model._get_connection() # don't try to delete non existant tables meta = get_cluster(connection).metadata ks_name = model._get_keyspace() raw_cf_name = model._raw_column_family_name() try: meta.keyspaces[ks_name].tables[raw_cf_name] execute('DROP TABLE {0};'.format(model.column_family_name()), connection=connection) except KeyError: pass def _allow_schema_modification(): if not os.getenv(CQLENG_ALLOW_SCHEMA_MANAGEMENT): msg = CQLENG_ALLOW_SCHEMA_MANAGEMENT + " environment variable is not set. Future versions of this package will require this variable to enable management functions." warnings.warn(msg) log.warning(msg) return True diff --git a/cassandra/cqlengine/models.py b/cassandra/cqlengine/models.py index 9fe5d3e..b3c7c9e 100644 --- a/cassandra/cqlengine/models.py +++ b/cassandra/cqlengine/models.py @@ -1,1088 +1,1088 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import re import six from warnings import warn from cassandra.cqlengine import CQLEngineException, ValidationError from cassandra.cqlengine import columns from cassandra.cqlengine import connection from cassandra.cqlengine import query from cassandra.cqlengine.query import DoesNotExist as _DoesNotExist from cassandra.cqlengine.query import MultipleObjectsReturned as _MultipleObjectsReturned from cassandra.metadata import protect_name from cassandra.util import OrderedDict log = logging.getLogger(__name__) def _clone_model_class(model, attrs): new_type = type(model.__name__, (model,), attrs) try: new_type.__abstract__ = model.__abstract__ new_type.__discriminator_value__ = model.__discriminator_value__ new_type.__default_ttl__ = model.__default_ttl__ except AttributeError: pass return new_type class ModelException(CQLEngineException): pass class ModelDefinitionException(ModelException): pass class PolymorphicModelException(ModelException): pass class UndefinedKeyspaceWarning(Warning): pass DEFAULT_KEYSPACE = None class hybrid_classmethod(object): """ Allows a method to behave as both a class method and normal instance method depending on how it's called """ def __init__(self, clsmethod, instmethod): self.clsmethod = clsmethod self.instmethod = instmethod def __get__(self, instance, owner): if instance is None: return self.clsmethod.__get__(owner, owner) else: return self.instmethod.__get__(instance, owner) def __call__(self, *args, **kwargs): """ Just a hint to IDEs that it's ok to call this """ raise NotImplementedError class QuerySetDescriptor(object): """ returns a fresh queryset for the given model it's declared on everytime it's accessed """ def __get__(self, obj, model): """ :rtype: ModelQuerySet """ if model.__abstract__: raise CQLEngineException('cannot execute queries against abstract models') queryset = model.__queryset__(model) # if this is a concrete polymorphic model, and the discriminator # key is an indexed column, add a filter clause to only return # logical rows of the proper type if model._is_polymorphic and not model._is_polymorphic_base: name, column = model._discriminator_column_name, model._discriminator_column if column.partition_key or column.index: # look for existing poly types return queryset.filter(**{name: model.__discriminator_value__}) return queryset def __call__(self, *args, **kwargs): """ Just a hint to IDEs that it's ok to call this :rtype: ModelQuerySet """ raise NotImplementedError class ConditionalDescriptor(object): """ returns a query set descriptor """ def __get__(self, instance, model): if instance: def conditional_setter(*prepared_conditional, **unprepared_conditionals): if len(prepared_conditional) > 0: conditionals = prepared_conditional[0] else: conditionals = instance.objects.iff(**unprepared_conditionals)._conditional instance._conditional = conditionals return instance return conditional_setter qs = model.__queryset__(model) def conditional_setter(**unprepared_conditionals): conditionals = model.objects.iff(**unprepared_conditionals)._conditional qs._conditional = conditionals return qs return conditional_setter def __call__(self, *args, **kwargs): raise NotImplementedError class TTLDescriptor(object): """ returns a query set descriptor """ def __get__(self, instance, model): if instance: # instance = copy.deepcopy(instance) # instance method def ttl_setter(ts): instance._ttl = ts return instance return ttl_setter qs = model.__queryset__(model) def ttl_setter(ts): qs._ttl = ts return qs return ttl_setter def __call__(self, *args, **kwargs): raise NotImplementedError class TimestampDescriptor(object): """ returns a query set descriptor with a timestamp specified """ def __get__(self, instance, model): if instance: # instance method def timestamp_setter(ts): instance._timestamp = ts return instance return timestamp_setter return model.objects.timestamp def __call__(self, *args, **kwargs): raise NotImplementedError class IfNotExistsDescriptor(object): """ return a query set descriptor with a if_not_exists flag specified """ def __get__(self, instance, model): if instance: # instance method def ifnotexists_setter(ife=True): instance._if_not_exists = ife return instance return ifnotexists_setter return model.objects.if_not_exists def __call__(self, *args, **kwargs): raise NotImplementedError class IfExistsDescriptor(object): """ return a query set descriptor with a if_exists flag specified """ def __get__(self, instance, model): if instance: # instance method def ifexists_setter(ife=True): instance._if_exists = ife return instance return ifexists_setter return model.objects.if_exists def __call__(self, *args, **kwargs): raise NotImplementedError class ConsistencyDescriptor(object): """ returns a query set descriptor if called on Class, instance if it was an instance call """ def __get__(self, instance, model): if instance: # instance = copy.deepcopy(instance) def consistency_setter(consistency): instance.__consistency__ = consistency return instance return consistency_setter qs = model.__queryset__(model) def consistency_setter(consistency): qs._consistency = consistency return qs return consistency_setter def __call__(self, *args, **kwargs): raise NotImplementedError class UsingDescriptor(object): """ return a query set descriptor with a connection context specified """ def __get__(self, instance, model): if instance: # instance method def using_setter(connection=None): if connection: instance._connection = connection return instance return using_setter return model.objects.using def __call__(self, *args, **kwargs): raise NotImplementedError class ColumnQueryEvaluator(query.AbstractQueryableColumn): """ Wraps a column and allows it to be used in comparator expressions, returning query operators ie: Model.column == 5 """ def __init__(self, column): self.column = column def __unicode__(self): return self.column.db_field_name def _get_column(self): return self.column class ColumnDescriptor(object): """ Handles the reading and writing of column values to and from a model instance's value manager, as well as creating comparator queries """ def __init__(self, column): """ :param column: :type column: columns.Column :return: """ self.column = column self.query_evaluator = ColumnQueryEvaluator(self.column) def __get__(self, instance, owner): """ Returns either the value or column, depending on if an instance is provided or not :param instance: the model instance :type instance: Model """ try: return instance._values[self.column.column_name].getval() except AttributeError: return self.query_evaluator def __set__(self, instance, value): """ Sets the value on an instance, raises an exception with classes TODO: use None instance to create update statements """ if instance: return instance._values[self.column.column_name].setval(value) else: raise AttributeError('cannot reassign column values') def __delete__(self, instance): """ Sets the column value to None, if possible """ if instance: if self.column.can_delete: instance._values[self.column.column_name].delval() else: raise AttributeError('cannot delete {0} columns'.format(self.column.column_name)) class BaseModel(object): """ The base model class, don't inherit from this, inherit from Model, defined below """ class DoesNotExist(_DoesNotExist): pass class MultipleObjectsReturned(_MultipleObjectsReturned): pass objects = QuerySetDescriptor() ttl = TTLDescriptor() consistency = ConsistencyDescriptor() iff = ConditionalDescriptor() # custom timestamps, see USING TIMESTAMP X timestamp = TimestampDescriptor() if_not_exists = IfNotExistsDescriptor() if_exists = IfExistsDescriptor() using = UsingDescriptor() # _len is lazily created by __len__ __table_name__ = None __table_name_case_sensitive__ = False __keyspace__ = None __connection__ = None __discriminator_value__ = None __options__ = None __compute_routing_key__ = True # the queryset class used for this class __queryset__ = query.ModelQuerySet __dmlquery__ = query.DMLQuery __consistency__ = None # can be set per query _timestamp = None # optional timestamp to include with the operation (USING TIMESTAMP) _if_not_exists = False # optional if_not_exists flag to check existence before insertion _if_exists = False # optional if_exists flag to check existence before update _table_name = None # used internally to cache a derived table name _connection = None def __init__(self, **values): self._ttl = None self._timestamp = None self._conditional = None self._batch = None self._timeout = connection.NOT_SET self._is_persisted = False self._connection = None self._values = {} for name, column in self._columns.items(): # Set default values on instantiation. Thanks to this, we don't have # to wait anylonger for a call to validate() to have CQLengine set # default columns values. column_default = column.get_default() if column.has_default else None value = values.get(name, column_default) if value is not None or isinstance(column, columns.BaseContainerColumn): value = column.to_python(value) value_mngr = column.value_manager(self, column, value) value_mngr.explicit = name in values self._values[name] = value_mngr def __repr__(self): return '{0}({1})'.format(self.__class__.__name__, ', '.join('{0}={1!r}'.format(k, getattr(self, k)) for k in self._defined_columns.keys() if k != self._discriminator_column_name)) def __str__(self): """ Pretty printing of models by their primary key """ return '{0} <{1}>'.format(self.__class__.__name__, ', '.join('{0}={1}'.format(k, getattr(self, k)) for k in self._primary_keys.keys())) @classmethod def _routing_key_from_values(cls, pk_values, protocol_version): return cls._key_serializer(pk_values, protocol_version) @classmethod def _discover_polymorphic_submodels(cls): if not cls._is_polymorphic_base: raise ModelException('_discover_polymorphic_submodels can only be called on polymorphic base classes') def _discover(klass): if not klass._is_polymorphic_base and klass.__discriminator_value__ is not None: cls._discriminator_map[klass.__discriminator_value__] = klass for subklass in klass.__subclasses__(): _discover(subklass) _discover(cls) @classmethod def _get_model_by_discriminator_value(cls, key): if not cls._is_polymorphic_base: raise ModelException('_get_model_by_discriminator_value can only be called on polymorphic base classes') return cls._discriminator_map.get(key) @classmethod def _construct_instance(cls, values): """ method used to construct instances from query results this is where polymorphic deserialization occurs """ # we're going to take the values, which is from the DB as a dict # and translate that into our local fields # the db_map is a db_field -> model field map if cls._db_map: values = dict((cls._db_map.get(k, k), v) for k, v in values.items()) if cls._is_polymorphic: disc_key = values.get(cls._discriminator_column_name) if disc_key is None: raise PolymorphicModelException('discriminator value was not found in values') poly_base = cls if cls._is_polymorphic_base else cls._polymorphic_base klass = poly_base._get_model_by_discriminator_value(disc_key) if klass is None: poly_base._discover_polymorphic_submodels() klass = poly_base._get_model_by_discriminator_value(disc_key) if klass is None: raise PolymorphicModelException( 'unrecognized discriminator column {0} for class {1}'.format(disc_key, poly_base.__name__) ) if not issubclass(klass, cls): raise PolymorphicModelException( '{0} is not a subclass of {1}'.format(klass.__name__, cls.__name__) ) values = dict((k, v) for k, v in values.items() if k in klass._columns.keys()) else: klass = cls instance = klass(**values) instance._set_persisted(force=True) return instance def _set_persisted(self, force=False): # ensure we don't modify to any values not affected by the last save/update for v in [v for v in self._values.values() if v.changed or force]: v.reset_previous_value() v.explicit = False self._is_persisted = True def _can_update(self): """ Called by the save function to check if this should be persisted with update or insert :return: """ if not self._is_persisted: return False - return all(not self._values[k].changed for k in self._primary_keys) + return all([not self._values[k].changed for k in self._primary_keys]) @classmethod def _get_keyspace(cls): """ Returns the manual keyspace, if set, otherwise the default keyspace """ return cls.__keyspace__ or DEFAULT_KEYSPACE @classmethod def _get_column(cls, name): """ Returns the column matching the given name, raising a key error if it doesn't exist :param name: the name of the column to return :rtype: Column """ return cls._columns[name] @classmethod def _get_column_by_db_name(cls, name): """ Returns the column, mapped by db_field name """ return cls._columns.get(cls._db_map.get(name, name)) def __eq__(self, other): if self.__class__ != other.__class__: return False # check attribute keys keys = set(self._columns.keys()) other_keys = set(other._columns.keys()) if keys != other_keys: return False return all(getattr(self, key, None) == getattr(other, key, None) for key in other_keys) def __ne__(self, other): return not self.__eq__(other) @classmethod def column_family_name(cls, include_keyspace=True): """ Returns the column family name if it's been defined otherwise, it creates it from the module and class name """ cf_name = protect_name(cls._raw_column_family_name()) if include_keyspace: keyspace = cls._get_keyspace() if not keyspace: raise CQLEngineException("Model keyspace is not set and no default is available. Set model keyspace or setup connection before attempting to generate a query.") return '{0}.{1}'.format(protect_name(keyspace), cf_name) return cf_name @classmethod def _raw_column_family_name(cls): if not cls._table_name: if cls.__table_name__: if cls.__table_name_case_sensitive__: warn("Model __table_name_case_sensitive__ will be removed in 4.0.", PendingDeprecationWarning) cls._table_name = cls.__table_name__ else: table_name = cls.__table_name__.lower() if cls.__table_name__ != table_name: warn(("Model __table_name__ will be case sensitive by default in 4.0. " "You should fix the __table_name__ value of the '{0}' model.").format(cls.__name__)) cls._table_name = table_name else: if cls._is_polymorphic and not cls._is_polymorphic_base: cls._table_name = cls._polymorphic_base._raw_column_family_name() else: camelcase = re.compile(r'([a-z])([A-Z])') ccase = lambda s: camelcase.sub(lambda v: '{0}_{1}'.format(v.group(1), v.group(2).lower()), s) cf_name = ccase(cls.__name__) # trim to less than 48 characters or cassandra will complain cf_name = cf_name[-48:] cf_name = cf_name.lower() cf_name = re.sub(r'^_+', '', cf_name) cls._table_name = cf_name return cls._table_name def _set_column_value(self, name, value): """Function to change a column value without changing the value manager states""" self._values[name].value = value # internal assignement, skip the main setter def validate(self): """ Cleans and validates the field values """ for name, col in self._columns.items(): v = getattr(self, name) if v is None and not self._values[name].explicit and col.has_default: v = col.get_default() val = col.validate(v) self._set_column_value(name, val) # Let an instance be used like a dict of its columns keys/values def __iter__(self): """ Iterate over column ids. """ for column_id in self._columns.keys(): yield column_id def __getitem__(self, key): """ Returns column's value. """ if not isinstance(key, six.string_types): raise TypeError if key not in self._columns.keys(): raise KeyError return getattr(self, key) def __setitem__(self, key, val): """ Sets a column's value. """ if not isinstance(key, six.string_types): raise TypeError if key not in self._columns.keys(): raise KeyError return setattr(self, key, val) def __len__(self): """ Returns the number of columns defined on that model. """ try: return self._len except: self._len = len(self._columns.keys()) return self._len def keys(self): """ Returns a list of column IDs. """ return [k for k in self] def values(self): """ Returns list of column values. """ return [self[k] for k in self] def items(self): """ Returns a list of column ID/value tuples. """ return [(k, self[k]) for k in self] def _as_dict(self): """ Returns a map of column names to cleaned values """ values = self._dynamic_columns or {} for name, col in self._columns.items(): values[name] = col.to_database(getattr(self, name, None)) return values @classmethod def create(cls, **kwargs): """ Create an instance of this model in the database. Takes the model column values as keyword arguments. Setting a value to `None` is equivalent to running a CQL `DELETE` on that column. Returns the instance. """ extra_columns = set(kwargs.keys()) - set(cls._columns.keys()) if extra_columns: raise ValidationError("Incorrect columns passed: {0}".format(extra_columns)) return cls.objects.create(**kwargs) @classmethod def all(cls): """ Returns a queryset representing all stored objects This is a pass-through to the model objects().all() """ return cls.objects.all() @classmethod def filter(cls, *args, **kwargs): """ Returns a queryset based on filter parameters. This is a pass-through to the model objects().:method:`~cqlengine.queries.filter`. """ return cls.objects.filter(*args, **kwargs) @classmethod def get(cls, *args, **kwargs): """ Returns a single object based on the passed filter constraints. This is a pass-through to the model objects().:method:`~cqlengine.queries.get`. """ return cls.objects.get(*args, **kwargs) def timeout(self, timeout): """ Sets a timeout for use in :meth:`~.save`, :meth:`~.update`, and :meth:`~.delete` operations """ assert self._batch is None, 'Setting both timeout and batch is not supported' self._timeout = timeout return self def save(self): """ Saves an object to the database. .. code-block:: python #create a person instance person = Person(first_name='Kimberly', last_name='Eggleston') #saves it to Cassandra person.save() """ # handle polymorphic models if self._is_polymorphic: if self._is_polymorphic_base: raise PolymorphicModelException('cannot save polymorphic base model') else: setattr(self, self._discriminator_column_name, self.__discriminator_value__) self.validate() self.__dmlquery__(self.__class__, self, batch=self._batch, ttl=self._ttl, timestamp=self._timestamp, consistency=self.__consistency__, if_not_exists=self._if_not_exists, conditional=self._conditional, timeout=self._timeout, if_exists=self._if_exists).save() self._set_persisted() self._timestamp = None return self def update(self, **values): """ Performs an update on the model instance. You can pass in values to set on the model for updating, or you can call without values to execute an update against any modified fields. If no fields on the model have been modified since loading, no query will be performed. Model validation is performed normally. Setting a value to `None` is equivalent to running a CQL `DELETE` on that column. It is possible to do a blind update, that is, to update a field without having first selected the object out of the database. See :ref:`Blind Updates ` """ for column_id, v in values.items(): col = self._columns.get(column_id) # check for nonexistant columns if col is None: raise ValidationError( "{0}.{1} has no column named: {2}".format( self.__module__, self.__class__.__name__, column_id)) # check for primary key update attempts if col.is_primary_key: current_value = getattr(self, column_id) if v != current_value: raise ValidationError( "Cannot apply update to primary key '{0}' for {1}.{2}".format( column_id, self.__module__, self.__class__.__name__)) setattr(self, column_id, v) # handle polymorphic models if self._is_polymorphic: if self._is_polymorphic_base: raise PolymorphicModelException('cannot update polymorphic base model') else: setattr(self, self._discriminator_column_name, self.__discriminator_value__) self.validate() self.__dmlquery__(self.__class__, self, batch=self._batch, ttl=self._ttl, timestamp=self._timestamp, consistency=self.__consistency__, conditional=self._conditional, timeout=self._timeout, if_exists=self._if_exists).update() self._set_persisted() self._timestamp = None return self def delete(self): """ Deletes the object from the database """ self.__dmlquery__(self.__class__, self, batch=self._batch, timestamp=self._timestamp, consistency=self.__consistency__, timeout=self._timeout, conditional=self._conditional, if_exists=self._if_exists).delete() def get_changed_columns(self): """ Returns a list of the columns that have been updated since instantiation or save """ return [k for k, v in self._values.items() if v.changed] @classmethod def _class_batch(cls, batch): return cls.objects.batch(batch) def _inst_batch(self, batch): assert self._timeout is connection.NOT_SET, 'Setting both timeout and batch is not supported' if self._connection: raise CQLEngineException("Cannot specify a connection on model in batch mode.") self._batch = batch return self batch = hybrid_classmethod(_class_batch, _inst_batch) @classmethod def _class_get_connection(cls): return cls.__connection__ def _inst_get_connection(self): return self._connection or self.__connection__ _get_connection = hybrid_classmethod(_class_get_connection, _inst_get_connection) class ModelMetaClass(type): def __new__(cls, name, bases, attrs): # move column definitions into columns dict # and set default column names column_dict = OrderedDict() primary_keys = OrderedDict() pk_name = None # get inherited properties inherited_columns = OrderedDict() for base in bases: for k, v in getattr(base, '_defined_columns', {}).items(): inherited_columns.setdefault(k, v) # short circuit __abstract__ inheritance is_abstract = attrs['__abstract__'] = attrs.get('__abstract__', False) # short circuit __discriminator_value__ inheritance attrs['__discriminator_value__'] = attrs.get('__discriminator_value__') # TODO __default__ttl__ should be removed in the next major release options = attrs.get('__options__') or {} attrs['__default_ttl__'] = options.get('default_time_to_live') column_definitions = [(k, v) for k, v in attrs.items() if isinstance(v, columns.Column)] column_definitions = sorted(column_definitions, key=lambda x: x[1].position) is_polymorphic_base = any([c[1].discriminator_column for c in column_definitions]) column_definitions = [x for x in inherited_columns.items()] + column_definitions discriminator_columns = [c for c in column_definitions if c[1].discriminator_column] is_polymorphic = len(discriminator_columns) > 0 if len(discriminator_columns) > 1: raise ModelDefinitionException('only one discriminator_column can be defined in a model, {0} found'.format(len(discriminator_columns))) if attrs['__discriminator_value__'] and not is_polymorphic: raise ModelDefinitionException('__discriminator_value__ specified, but no base columns defined with discriminator_column=True') discriminator_column_name, discriminator_column = discriminator_columns[0] if discriminator_columns else (None, None) if isinstance(discriminator_column, (columns.BaseContainerColumn, columns.Counter)): raise ModelDefinitionException('counter and container columns cannot be used as discriminator columns') # find polymorphic base class polymorphic_base = None if is_polymorphic and not is_polymorphic_base: def _get_polymorphic_base(bases): for base in bases: if getattr(base, '_is_polymorphic_base', False): return base klass = _get_polymorphic_base(base.__bases__) if klass: return klass polymorphic_base = _get_polymorphic_base(bases) defined_columns = OrderedDict(column_definitions) # check for primary key if not is_abstract and not any([v.primary_key for k, v in column_definitions]): raise ModelDefinitionException("At least 1 primary key is required.") counter_columns = [c for c in defined_columns.values() if isinstance(c, columns.Counter)] data_columns = [c for c in defined_columns.values() if not c.primary_key and not isinstance(c, columns.Counter)] if counter_columns and data_columns: raise ModelDefinitionException('counter models may not have data columns') has_partition_keys = any(v.partition_key for (k, v) in column_definitions) def _transform_column(col_name, col_obj): column_dict[col_name] = col_obj if col_obj.primary_key: primary_keys[col_name] = col_obj col_obj.set_column_name(col_name) # set properties attrs[col_name] = ColumnDescriptor(col_obj) partition_key_index = 0 # transform column definitions for k, v in column_definitions: # don't allow a column with the same name as a built-in attribute or method if k in BaseModel.__dict__: raise ModelDefinitionException("column '{0}' conflicts with built-in attribute/method".format(k)) # counter column primary keys are not allowed if (v.primary_key or v.partition_key) and isinstance(v, columns.Counter): raise ModelDefinitionException('counter columns cannot be used as primary keys') # this will mark the first primary key column as a partition # key, if one hasn't been set already if not has_partition_keys and v.primary_key: v.partition_key = True has_partition_keys = True if v.partition_key: v._partition_key_index = partition_key_index partition_key_index += 1 overriding = column_dict.get(k) if overriding: v.position = overriding.position v.partition_key = overriding.partition_key v._partition_key_index = overriding._partition_key_index _transform_column(k, v) partition_keys = OrderedDict(k for k in primary_keys.items() if k[1].partition_key) clustering_keys = OrderedDict(k for k in primary_keys.items() if not k[1].partition_key) if attrs.get('__compute_routing_key__', True): key_cols = [c for c in partition_keys.values()] partition_key_index = dict((col.db_field_name, col._partition_key_index) for col in key_cols) key_cql_types = [c.cql_type for c in key_cols] key_serializer = staticmethod(lambda parts, proto_version: [t.to_binary(p, proto_version) for t, p in zip(key_cql_types, parts)]) else: partition_key_index = {} key_serializer = staticmethod(lambda parts, proto_version: None) # setup partition key shortcut if len(partition_keys) == 0: if not is_abstract: raise ModelException("at least one partition key must be defined") if len(partition_keys) == 1: pk_name = [x for x in partition_keys.keys()][0] attrs['pk'] = attrs[pk_name] else: # composite partition key case, get/set a tuple of values _get = lambda self: tuple(self._values[c].getval() for c in partition_keys.keys()) _set = lambda self, val: tuple(self._values[c].setval(v) for (c, v) in zip(partition_keys.keys(), val)) attrs['pk'] = property(_get, _set) # some validation col_names = set() for v in column_dict.values(): # check for duplicate column names if v.db_field_name in col_names: raise ModelException("{0} defines the column '{1}' more than once".format(name, v.db_field_name)) if v.clustering_order and not (v.primary_key and not v.partition_key): raise ModelException("clustering_order may be specified only for clustering primary keys") if v.clustering_order and v.clustering_order.lower() not in ('asc', 'desc'): raise ModelException("invalid clustering order '{0}' for column '{1}'".format(repr(v.clustering_order), v.db_field_name)) col_names.add(v.db_field_name) # create db_name -> model name map for loading db_map = {} for col_name, field in column_dict.items(): db_field = field.db_field_name if db_field != col_name: db_map[db_field] = col_name # add management members to the class attrs['_columns'] = column_dict attrs['_primary_keys'] = primary_keys attrs['_defined_columns'] = defined_columns # maps the database field to the models key attrs['_db_map'] = db_map attrs['_pk_name'] = pk_name attrs['_dynamic_columns'] = {} attrs['_partition_keys'] = partition_keys attrs['_partition_key_index'] = partition_key_index attrs['_key_serializer'] = key_serializer attrs['_clustering_keys'] = clustering_keys attrs['_has_counter'] = len(counter_columns) > 0 # add polymorphic management attributes attrs['_is_polymorphic_base'] = is_polymorphic_base attrs['_is_polymorphic'] = is_polymorphic attrs['_polymorphic_base'] = polymorphic_base attrs['_discriminator_column'] = discriminator_column attrs['_discriminator_column_name'] = discriminator_column_name attrs['_discriminator_map'] = {} if is_polymorphic_base else None # setup class exceptions DoesNotExistBase = None for base in bases: DoesNotExistBase = getattr(base, 'DoesNotExist', None) if DoesNotExistBase is not None: break DoesNotExistBase = DoesNotExistBase or attrs.pop('DoesNotExist', BaseModel.DoesNotExist) attrs['DoesNotExist'] = type('DoesNotExist', (DoesNotExistBase,), {}) MultipleObjectsReturnedBase = None for base in bases: MultipleObjectsReturnedBase = getattr(base, 'MultipleObjectsReturned', None) if MultipleObjectsReturnedBase is not None: break MultipleObjectsReturnedBase = MultipleObjectsReturnedBase or attrs.pop('MultipleObjectsReturned', BaseModel.MultipleObjectsReturned) attrs['MultipleObjectsReturned'] = type('MultipleObjectsReturned', (MultipleObjectsReturnedBase,), {}) # create the class and add a QuerySet to it klass = super(ModelMetaClass, cls).__new__(cls, name, bases, attrs) udts = [] for col in column_dict.values(): columns.resolve_udts(col, udts) for user_type in set(udts): user_type.register_for_keyspace(klass._get_keyspace()) return klass @six.add_metaclass(ModelMetaClass) class Model(BaseModel): __abstract__ = True """ *Optional.* Indicates that this model is only intended to be used as a base class for other models. You can't create tables for abstract models, but checks around schema validity are skipped during class construction. """ __table_name__ = None """ *Optional.* Sets the name of the CQL table for this model. If left blank, the table name will be the name of the model, with it's module name as it's prefix. Manually defined table names are not inherited. """ __table_name_case_sensitive__ = False """ *Optional.* By default, __table_name__ is case insensitive. Set this to True if you want to preserve the case sensitivity. """ __keyspace__ = None """ Sets the name of the keyspace used by this model. """ __connection__ = None """ Sets the name of the default connection used by this model. """ __options__ = None """ *Optional* Table options applied with this model (e.g. compaction, default ttl, cache settings, tec.) """ __discriminator_value__ = None """ *Optional* Specifies a value for the discriminator column when using model inheritance. """ __compute_routing_key__ = True """ *Optional* Setting False disables computing the routing key for TokenAwareRouting """ diff --git a/cassandra/cqlengine/usertype.py b/cassandra/cqlengine/usertype.py index adf3f5e..155068d 100644 --- a/cassandra/cqlengine/usertype.py +++ b/cassandra/cqlengine/usertype.py @@ -1,215 +1,229 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + import re import six from cassandra.util import OrderedDict from cassandra.cqlengine import CQLEngineException from cassandra.cqlengine import columns from cassandra.cqlengine import connection as conn from cassandra.cqlengine import models class UserTypeException(CQLEngineException): pass class UserTypeDefinitionException(UserTypeException): pass class BaseUserType(object): """ The base type class; don't inherit from this, inherit from UserType, defined below """ __type_name__ = None _fields = None _db_map = None def __init__(self, **values): self._values = {} if self._db_map: values = dict((self._db_map.get(k, k), v) for k, v in values.items()) for name, field in self._fields.items(): field_default = field.get_default() if field.has_default else None value = values.get(name, field_default) if value is not None or isinstance(field, columns.BaseContainerColumn): value = field.to_python(value) value_mngr = field.value_manager(self, field, value) value_mngr.explicit = name in values self._values[name] = value_mngr def __eq__(self, other): if self.__class__ != other.__class__: return False keys = set(self._fields.keys()) other_keys = set(other._fields.keys()) if keys != other_keys: return False for key in other_keys: if getattr(self, key, None) != getattr(other, key, None): return False return True def __ne__(self, other): return not self.__eq__(other) def __str__(self): return "{{{0}}}".format(', '.join("'{0}': {1}".format(k, getattr(self, k)) for k, v in six.iteritems(self._values))) def has_changed_fields(self): return any(v.changed for v in self._values.values()) def reset_changed_fields(self): for v in self._values.values(): v.reset_previous_value() def __iter__(self): for field in self._fields.keys(): yield field def __getattr__(self, attr): # provides the mapping from db_field to fields try: return getattr(self, self._db_map[attr]) except KeyError: raise AttributeError(attr) def __getitem__(self, key): if not isinstance(key, six.string_types): raise TypeError if key not in self._fields.keys(): raise KeyError return getattr(self, key) def __setitem__(self, key, val): if not isinstance(key, six.string_types): raise TypeError if key not in self._fields.keys(): raise KeyError return setattr(self, key, val) def __len__(self): try: return self._len except: self._len = len(self._fields.keys()) return self._len def keys(self): """ Returns a list of column IDs. """ return [k for k in self] def values(self): """ Returns list of column values. """ return [self[k] for k in self] def items(self): """ Returns a list of column ID/value tuples. """ return [(k, self[k]) for k in self] @classmethod def register_for_keyspace(cls, keyspace, connection=None): conn.register_udt(keyspace, cls.type_name(), cls, connection=connection) @classmethod def type_name(cls): """ Returns the type name if it's been defined otherwise, it creates it from the class name """ if cls.__type_name__: type_name = cls.__type_name__.lower() else: camelcase = re.compile(r'([a-z])([A-Z])') ccase = lambda s: camelcase.sub(lambda v: '{0}_{1}'.format(v.group(1), v.group(2)), s) type_name = ccase(cls.__name__) # trim to less than 48 characters or cassandra will complain type_name = type_name[-48:] type_name = type_name.lower() type_name = re.sub(r'^_+', '', type_name) cls.__type_name__ = type_name return type_name def validate(self): """ Cleans and validates the field values """ for name, field in self._fields.items(): v = getattr(self, name) if v is None and not self._values[name].explicit and field.has_default: v = field.get_default() val = field.validate(v) setattr(self, name, val) class UserTypeMetaClass(type): def __new__(cls, name, bases, attrs): field_dict = OrderedDict() field_defs = [(k, v) for k, v in attrs.items() if isinstance(v, columns.Column)] field_defs = sorted(field_defs, key=lambda x: x[1].position) def _transform_column(field_name, field_obj): field_dict[field_name] = field_obj field_obj.set_column_name(field_name) attrs[field_name] = models.ColumnDescriptor(field_obj) # transform field definitions for k, v in field_defs: # don't allow a field with the same name as a built-in attribute or method if k in BaseUserType.__dict__: raise UserTypeDefinitionException("field '{0}' conflicts with built-in attribute/method".format(k)) _transform_column(k, v) attrs['_fields'] = field_dict db_map = {} for field_name, field in field_dict.items(): db_field = field.db_field_name if db_field != field_name: if db_field in field_dict: raise UserTypeDefinitionException("db_field '{0}' for field '{1}' conflicts with another attribute name".format(db_field, field_name)) db_map[db_field] = field_name attrs['_db_map'] = db_map klass = super(UserTypeMetaClass, cls).__new__(cls, name, bases, attrs) return klass @six.add_metaclass(UserTypeMetaClass) class UserType(BaseUserType): """ This class is used to model User Defined Types. To define a type, declare a class inheriting from this, and assign field types as class attributes: .. code-block:: python # connect with default keyspace ... from cassandra.cqlengine.columns import Text, Integer from cassandra.cqlengine.usertype import UserType class address(UserType): street = Text() zipcode = Integer() from cassandra.cqlengine import management management.sync_type(address) Please see :ref:`user_types` for a complete example and discussion. """ __type_name__ = None """ *Optional.* Sets the name of the CQL type for this type. If not specified, the type name will be the name of the class, with it's module name as it's prefix. """ diff --git a/cassandra/cqltypes.py b/cassandra/cqltypes.py index 55bb022..7946a63 100644 --- a/cassandra/cqltypes.py +++ b/cassandra/cqltypes.py @@ -1,1147 +1,1423 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Representation of Cassandra data types. These classes should make it simple for the library (and caller software) to deal with Cassandra-style Java class type names and CQL type specifiers, and convert between them cleanly. Parameterized types are fully supported in both flavors. Once you have the right Type object for the type you want, you can use it to serialize, deserialize, or retrieve the corresponding CQL or Cassandra type strings. """ # NOTE: # If/when the need arises for interpret types from CQL string literals in # different ways (for https://issues.apache.org/jira/browse/CASSANDRA-3799, # for example), these classes would be a good place to tack on # .from_cql_literal() and .as_cql_literal() classmethods (or whatever). from __future__ import absolute_import # to enable import io from stdlib import ast from binascii import unhexlify import calendar from collections import namedtuple from decimal import Decimal import io +from itertools import chain import logging import re import socket import time import six from six.moves import range +import struct import sys from uuid import UUID -import warnings - -if six.PY3: - import ipaddress from cassandra.marshal import (int8_pack, int8_unpack, int16_pack, int16_unpack, uint16_pack, uint16_unpack, uint32_pack, uint32_unpack, int32_pack, int32_unpack, int64_pack, int64_unpack, float_pack, float_unpack, double_pack, double_unpack, - varint_pack, varint_unpack, vints_pack, vints_unpack) + varint_pack, varint_unpack, point_be, point_le, + vints_pack, vints_unpack) from cassandra import util +_little_endian_flag = 1 # we always serialize LE +if six.PY3: + import ipaddress + +_ord = ord if six.PY2 else lambda x: x + apache_cassandra_type_prefix = 'org.apache.cassandra.db.marshal.' cassandra_empty_type = 'org.apache.cassandra.db.marshal.EmptyType' cql_empty_type = 'empty' log = logging.getLogger(__name__) if six.PY3: _number_types = frozenset((int, float)) long = int def _name_from_hex_string(encoded_name): bin_str = unhexlify(encoded_name) return bin_str.decode('ascii') else: _number_types = frozenset((int, long, float)) _name_from_hex_string = unhexlify def trim_if_startswith(s, prefix): if s.startswith(prefix): return s[len(prefix):] return s _casstypes = {} _cqltypes = {} cql_type_scanner = re.Scanner(( ('frozen', None), (r'[a-zA-Z0-9_]+', lambda s, t: t), (r'[\s,<>]', None), )) def cql_types_from_string(cql_type): return cql_type_scanner.scan(cql_type)[0] class CassandraTypeType(type): """ The CassandraType objects in this module will normally be used directly, rather than through instances of those types. They can be instantiated, of course, but the type information is what this driver mainly needs. This metaclass registers CassandraType classes in the global by-cassandra-typename and by-cql-typename registries, unless their class name starts with an underscore. """ def __new__(metacls, name, bases, dct): dct.setdefault('cassname', name) cls = type.__new__(metacls, name, bases, dct) if not name.startswith('_'): _casstypes[name] = cls if not cls.typename.startswith(apache_cassandra_type_prefix): _cqltypes[cls.typename] = cls return cls casstype_scanner = re.Scanner(( (r'[()]', lambda s, t: t), (r'[a-zA-Z0-9_.:=>]+', lambda s, t: t), (r'[\s,]', None), )) def cqltype_to_python(cql_string): """ Given a cql type string, creates a list that can be manipulated in python Example: int -> ['int'] frozen> -> ['frozen', ['tuple', ['text', 'int']]] """ scanner = re.Scanner(( (r'[a-zA-Z0-9_]+', lambda s, t: "'{}'".format(t)), (r'<', lambda s, t: ', ['), (r'>', lambda s, t: ']'), (r'[, ]', lambda s, t: t), (r'".*?"', lambda s, t: "'{}'".format(t)), )) scanned_tokens = scanner.scan(cql_string)[0] hierarchy = ast.literal_eval(''.join(scanned_tokens)) return [hierarchy] if isinstance(hierarchy, str) else list(hierarchy) def python_to_cqltype(types): """ Opposite of the `cql_to_python` function. Given a python list, creates a cql type string from the representation Example: ['int'] -> int ['frozen', ['tuple', ['text', 'int']]] -> frozen> """ scanner = re.Scanner(( (r"'[a-zA-Z0-9_]+'", lambda s, t: t[1:-1]), (r'^\[', lambda s, t: None), (r'\]$', lambda s, t: None), (r',\s*\[', lambda s, t: '<'), (r'\]', lambda s, t: '>'), (r'[, ]', lambda s, t: t), (r'\'".*?"\'', lambda s, t: t[1:-1]), )) scanned_tokens = scanner.scan(repr(types))[0] cql = ''.join(scanned_tokens).replace('\\\\', '\\') return cql def _strip_frozen_from_python(types): """ Given a python list representing a cql type, removes 'frozen' Example: ['frozen', ['tuple', ['text', 'int']]] -> ['tuple', ['text', 'int']] """ while 'frozen' in types: index = types.index('frozen') types = types[:index] + types[index + 1] + types[index + 2:] new_types = [_strip_frozen_from_python(item) if isinstance(item, list) else item for item in types] return new_types def strip_frozen(cql): """ Given a cql type string, and removes frozen Example: frozen> -> tuple """ types = cqltype_to_python(cql) types_without_frozen = _strip_frozen_from_python(types) cql = python_to_cqltype(types_without_frozen) return cql def lookup_casstype_simple(casstype): """ Given a Cassandra type name (either fully distinguished or not), hand back the CassandraType class responsible for it. If a name is not recognized, a custom _UnrecognizedType subclass will be created for it. This function does not handle complex types (so no type parameters-- nothing with parentheses). Use lookup_casstype() instead if you might need that. """ shortname = trim_if_startswith(casstype, apache_cassandra_type_prefix) try: typeclass = _casstypes[shortname] except KeyError: typeclass = mkUnrecognizedType(casstype) return typeclass def parse_casstype_args(typestring): tokens, remainder = casstype_scanner.scan(typestring) if remainder: raise ValueError("weird characters %r at end" % remainder) # use a stack of (types, names) lists args = [([], [])] for tok in tokens: if tok == '(': args.append(([], [])) elif tok == ')': types, names = args.pop() prev_types, prev_names = args[-1] prev_types[-1] = prev_types[-1].apply_parameters(types, names) else: types, names = args[-1] parts = re.split(':|=>', tok) tok = parts.pop() if parts: names.append(parts[0]) else: names.append(None) ctype = lookup_casstype_simple(tok) types.append(ctype) # return the first (outer) type, which will have all parameters applied return args[0][0][0] def lookup_casstype(casstype): """ Given a Cassandra type as a string (possibly including parameters), hand back the CassandraType class responsible for it. If a name is not recognized, a custom _UnrecognizedType subclass will be created for it. Example: >>> lookup_casstype('org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.Int32Type)') """ if isinstance(casstype, (CassandraType, CassandraTypeType)): return casstype try: return parse_casstype_args(casstype) except (ValueError, AssertionError, IndexError) as e: raise ValueError("Don't know how to parse type string %r: %s" % (casstype, e)) def is_reversed_casstype(data_type): return issubclass(data_type, ReversedType) class EmptyValue(object): """ See _CassandraType.support_empty_values """ def __str__(self): return "EMPTY" __repr__ = __str__ EMPTY = EmptyValue() @six.add_metaclass(CassandraTypeType) class _CassandraType(object): subtypes = () num_subtypes = 0 empty_binary_ok = False support_empty_values = False """ Back in the Thrift days, empty strings were used for "null" values of all types, including non-string types. For most users, an empty string value in an int column is the same as being null/not present, so the driver normally returns None in this case. (For string-like types, it *will* return an empty string by default instead of None.) To avoid this behavior, set this to :const:`True`. Instead of returning None for empty string values, the EMPTY singleton (an instance of EmptyValue) will be returned. """ def __repr__(self): return '<%s( %r )>' % (self.cql_parameterized_type(), self.val) @classmethod def from_binary(cls, byts, protocol_version): """ Deserialize a bytestring into a value. See the deserialize() method for more information. This method differs in that if None or the empty string is passed in, None may be returned. """ if byts is None: return None elif len(byts) == 0 and not cls.empty_binary_ok: return EMPTY if cls.support_empty_values else None return cls.deserialize(byts, protocol_version) @classmethod def to_binary(cls, val, protocol_version): """ Serialize a value into a bytestring. See the serialize() method for more information. This method differs in that if None is passed in, the result is the empty string. """ return b'' if val is None else cls.serialize(val, protocol_version) @staticmethod def deserialize(byts, protocol_version): """ Given a bytestring, deserialize into a value according to the protocol for this type. Note that this does not create a new instance of this class; it merely gives back a value that would be appropriate to go inside an instance of this class. """ return byts @staticmethod def serialize(val, protocol_version): """ Given a value appropriate for this class, serialize it according to the protocol for this type and return the corresponding bytestring. """ return val @classmethod def cass_parameterized_type_with(cls, subtypes, full=False): """ Return the name of this type as it would be expressed by Cassandra, optionally fully qualified. If subtypes is not None, it is expected to be a list of other CassandraType subclasses, and the output string includes the Cassandra names for those subclasses as well, as parameters to this one. Example: >>> LongType.cass_parameterized_type_with(()) 'LongType' >>> LongType.cass_parameterized_type_with((), full=True) 'org.apache.cassandra.db.marshal.LongType' >>> SetType.cass_parameterized_type_with([DecimalType], full=True) 'org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.DecimalType)' """ cname = cls.cassname if full and '.' not in cname: cname = apache_cassandra_type_prefix + cname if not subtypes: return cname sublist = ', '.join(styp.cass_parameterized_type(full=full) for styp in subtypes) return '%s(%s)' % (cname, sublist) @classmethod def apply_parameters(cls, subtypes, names=None): """ Given a set of other CassandraTypes, create a new subtype of this type using them as parameters. This is how composite types are constructed. >>> MapType.apply_parameters([DateType, BooleanType]) `subtypes` will be a sequence of CassandraTypes. If provided, `names` will be an equally long sequence of column names or Nones. """ if cls.num_subtypes != 'UNKNOWN' and len(subtypes) != cls.num_subtypes: raise ValueError("%s types require %d subtypes (%d given)" % (cls.typename, cls.num_subtypes, len(subtypes))) newname = cls.cass_parameterized_type_with(subtypes) if six.PY2 and isinstance(newname, unicode): newname = newname.encode('utf-8') return type(newname, (cls,), {'subtypes': subtypes, 'cassname': cls.cassname, 'fieldnames': names}) @classmethod def cql_parameterized_type(cls): """ Return a CQL type specifier for this type. If this type has parameters, they are included in standard CQL <> notation. """ if not cls.subtypes: return cls.typename return '%s<%s>' % (cls.typename, ', '.join(styp.cql_parameterized_type() for styp in cls.subtypes)) @classmethod def cass_parameterized_type(cls, full=False): """ Return a Cassandra type specifier for this type. If this type has parameters, they are included in the standard () notation. """ return cls.cass_parameterized_type_with(cls.subtypes, full=full) # it's initially named with a _ to avoid registering it as a real type, but # client programs may want to use the name still for isinstance(), etc CassandraType = _CassandraType class _UnrecognizedType(_CassandraType): num_subtypes = 'UNKNOWN' if six.PY3: def mkUnrecognizedType(casstypename): return CassandraTypeType(casstypename, (_UnrecognizedType,), {'typename': "'%s'" % casstypename}) else: def mkUnrecognizedType(casstypename): # noqa return CassandraTypeType(casstypename.encode('utf8'), (_UnrecognizedType,), {'typename': "'%s'" % casstypename}) class BytesType(_CassandraType): typename = 'blob' empty_binary_ok = True @staticmethod def serialize(val, protocol_version): return six.binary_type(val) class DecimalType(_CassandraType): typename = 'decimal' @staticmethod def deserialize(byts, protocol_version): scale = int32_unpack(byts[:4]) unscaled = varint_unpack(byts[4:]) return Decimal('%de%d' % (unscaled, -scale)) @staticmethod def serialize(dec, protocol_version): try: sign, digits, exponent = dec.as_tuple() except AttributeError: try: sign, digits, exponent = Decimal(dec).as_tuple() except Exception: raise TypeError("Invalid type for Decimal value: %r", dec) unscaled = int(''.join([str(digit) for digit in digits])) if sign: unscaled *= -1 scale = int32_pack(-exponent) unscaled = varint_pack(unscaled) return scale + unscaled class UUIDType(_CassandraType): typename = 'uuid' @staticmethod def deserialize(byts, protocol_version): return UUID(bytes=byts) @staticmethod def serialize(uuid, protocol_version): try: return uuid.bytes except AttributeError: raise TypeError("Got a non-UUID object for a UUID value") class BooleanType(_CassandraType): typename = 'boolean' @staticmethod def deserialize(byts, protocol_version): return bool(int8_unpack(byts)) @staticmethod def serialize(truth, protocol_version): return int8_pack(truth) class ByteType(_CassandraType): typename = 'tinyint' @staticmethod def deserialize(byts, protocol_version): return int8_unpack(byts) @staticmethod def serialize(byts, protocol_version): return int8_pack(byts) if six.PY2: class AsciiType(_CassandraType): typename = 'ascii' empty_binary_ok = True else: class AsciiType(_CassandraType): typename = 'ascii' empty_binary_ok = True @staticmethod def deserialize(byts, protocol_version): return byts.decode('ascii') @staticmethod def serialize(var, protocol_version): try: return var.encode('ascii') except UnicodeDecodeError: return var class FloatType(_CassandraType): typename = 'float' @staticmethod def deserialize(byts, protocol_version): return float_unpack(byts) @staticmethod def serialize(byts, protocol_version): return float_pack(byts) class DoubleType(_CassandraType): typename = 'double' @staticmethod def deserialize(byts, protocol_version): return double_unpack(byts) @staticmethod def serialize(byts, protocol_version): return double_pack(byts) class LongType(_CassandraType): typename = 'bigint' @staticmethod def deserialize(byts, protocol_version): return int64_unpack(byts) @staticmethod def serialize(byts, protocol_version): return int64_pack(byts) class Int32Type(_CassandraType): typename = 'int' @staticmethod def deserialize(byts, protocol_version): return int32_unpack(byts) @staticmethod def serialize(byts, protocol_version): return int32_pack(byts) class IntegerType(_CassandraType): typename = 'varint' @staticmethod def deserialize(byts, protocol_version): return varint_unpack(byts) @staticmethod def serialize(byts, protocol_version): return varint_pack(byts) class InetAddressType(_CassandraType): typename = 'inet' @staticmethod def deserialize(byts, protocol_version): if len(byts) == 16: return util.inet_ntop(socket.AF_INET6, byts) else: # util.inet_pton could also handle, but this is faster # since we've already determined the AF return socket.inet_ntoa(byts) @staticmethod def serialize(addr, protocol_version): try: if ':' in addr: return util.inet_pton(socket.AF_INET6, addr) else: # util.inet_pton could also handle, but this is faster # since we've already determined the AF return socket.inet_aton(addr) except: if six.PY3 and isinstance(addr, (ipaddress.IPv4Address, ipaddress.IPv6Address)): return addr.packed raise ValueError("can't interpret %r as an inet address" % (addr,)) class CounterColumnType(LongType): typename = 'counter' cql_timestamp_formats = ( '%Y-%m-%d %H:%M', '%Y-%m-%d %H:%M:%S', '%Y-%m-%dT%H:%M', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d' ) _have_warned_about_timestamps = False class DateType(_CassandraType): typename = 'timestamp' @staticmethod def interpret_datestring(val): if val[-5] in ('+', '-'): offset = (int(val[-4:-2]) * 3600 + int(val[-2:]) * 60) * int(val[-5] + '1') val = val[:-5] else: offset = -time.timezone for tformat in cql_timestamp_formats: try: tval = time.strptime(val, tformat) except ValueError: continue # scale seconds to millis for the raw value return (calendar.timegm(tval) + offset) * 1e3 else: raise ValueError("can't interpret %r as a date" % (val,)) @staticmethod def deserialize(byts, protocol_version): timestamp = int64_unpack(byts) / 1000.0 return util.datetime_from_timestamp(timestamp) @staticmethod def serialize(v, protocol_version): try: # v is datetime timestamp_seconds = calendar.timegm(v.utctimetuple()) timestamp = timestamp_seconds * 1e3 + getattr(v, 'microsecond', 0) / 1e3 except AttributeError: try: timestamp = calendar.timegm(v.timetuple()) * 1e3 except AttributeError: # Ints and floats are valid timestamps too if type(v) not in _number_types: raise TypeError('DateType arguments must be a datetime, date, or timestamp') timestamp = v return int64_pack(long(timestamp)) class TimestampType(DateType): pass class TimeUUIDType(DateType): typename = 'timeuuid' def my_timestamp(self): return util.unix_time_from_uuid1(self.val) @staticmethod def deserialize(byts, protocol_version): return UUID(bytes=byts) @staticmethod def serialize(timeuuid, protocol_version): try: return timeuuid.bytes except AttributeError: raise TypeError("Got a non-UUID object for a UUID value") class SimpleDateType(_CassandraType): typename = 'date' date_format = "%Y-%m-%d" # Values of the 'date'` type are encoded as 32-bit unsigned integers # representing a number of days with epoch (January 1st, 1970) at the center of the # range (2^31). EPOCH_OFFSET_DAYS = 2 ** 31 @staticmethod def deserialize(byts, protocol_version): days = uint32_unpack(byts) - SimpleDateType.EPOCH_OFFSET_DAYS return util.Date(days) @staticmethod def serialize(val, protocol_version): try: days = val.days_from_epoch except AttributeError: if isinstance(val, six.integer_types): # the DB wants offset int values, but util.Date init takes days from epoch # here we assume int values are offset, as they would appear in CQL # short circuit to avoid subtracting just to add offset return uint32_pack(val) days = util.Date(val).days_from_epoch return uint32_pack(days + SimpleDateType.EPOCH_OFFSET_DAYS) class ShortType(_CassandraType): typename = 'smallint' @staticmethod def deserialize(byts, protocol_version): return int16_unpack(byts) @staticmethod def serialize(byts, protocol_version): return int16_pack(byts) class TimeType(_CassandraType): typename = 'time' @staticmethod def deserialize(byts, protocol_version): return util.Time(int64_unpack(byts)) @staticmethod def serialize(val, protocol_version): try: nano = val.nanosecond_time except AttributeError: nano = util.Time(val).nanosecond_time return int64_pack(nano) class DurationType(_CassandraType): typename = 'duration' @staticmethod def deserialize(byts, protocol_version): months, days, nanoseconds = vints_unpack(byts) return util.Duration(months, days, nanoseconds) @staticmethod def serialize(duration, protocol_version): try: m, d, n = duration.months, duration.days, duration.nanoseconds except AttributeError: raise TypeError('DurationType arguments must be a Duration.') return vints_pack([m, d, n]) class UTF8Type(_CassandraType): typename = 'text' empty_binary_ok = True @staticmethod def deserialize(byts, protocol_version): return byts.decode('utf8') @staticmethod def serialize(ustr, protocol_version): try: return ustr.encode('utf-8') except UnicodeDecodeError: # already utf-8 return ustr class VarcharType(UTF8Type): typename = 'varchar' class _ParameterizedType(_CassandraType): num_subtypes = 'UNKNOWN' @classmethod def deserialize(cls, byts, protocol_version): if not cls.subtypes: raise NotImplementedError("can't deserialize unparameterized %s" % cls.typename) return cls.deserialize_safe(byts, protocol_version) @classmethod def serialize(cls, val, protocol_version): if not cls.subtypes: raise NotImplementedError("can't serialize unparameterized %s" % cls.typename) return cls.serialize_safe(val, protocol_version) class _SimpleParameterizedType(_ParameterizedType): @classmethod def deserialize_safe(cls, byts, protocol_version): subtype, = cls.subtypes if protocol_version >= 3: unpack = int32_unpack length = 4 else: unpack = uint16_unpack length = 2 numelements = unpack(byts[:length]) p = length result = [] inner_proto = max(3, protocol_version) for _ in range(numelements): itemlen = unpack(byts[p:p + length]) p += length - item = byts[p:p + itemlen] - p += itemlen - result.append(subtype.from_binary(item, inner_proto)) + if itemlen < 0: + result.append(None) + else: + item = byts[p:p + itemlen] + p += itemlen + result.append(subtype.from_binary(item, inner_proto)) return cls.adapter(result) @classmethod def serialize_safe(cls, items, protocol_version): if isinstance(items, six.string_types): raise TypeError("Received a string for a type that expects a sequence") subtype, = cls.subtypes pack = int32_pack if protocol_version >= 3 else uint16_pack buf = io.BytesIO() buf.write(pack(len(items))) inner_proto = max(3, protocol_version) for item in items: itembytes = subtype.to_binary(item, inner_proto) buf.write(pack(len(itembytes))) buf.write(itembytes) return buf.getvalue() class ListType(_SimpleParameterizedType): typename = 'list' num_subtypes = 1 adapter = list class SetType(_SimpleParameterizedType): typename = 'set' num_subtypes = 1 adapter = util.sortedset class MapType(_ParameterizedType): typename = 'map' num_subtypes = 2 @classmethod def deserialize_safe(cls, byts, protocol_version): key_type, value_type = cls.subtypes if protocol_version >= 3: unpack = int32_unpack length = 4 else: unpack = uint16_unpack length = 2 numelements = unpack(byts[:length]) p = length themap = util.OrderedMapSerializedKey(key_type, protocol_version) inner_proto = max(3, protocol_version) for _ in range(numelements): key_len = unpack(byts[p:p + length]) p += length - keybytes = byts[p:p + key_len] - p += key_len + if key_len < 0: + keybytes = None + key = None + else: + keybytes = byts[p:p + key_len] + p += key_len + key = key_type.from_binary(keybytes, inner_proto) + val_len = unpack(byts[p:p + length]) p += length - valbytes = byts[p:p + val_len] - p += val_len - key = key_type.from_binary(keybytes, inner_proto) - val = value_type.from_binary(valbytes, inner_proto) + if val_len < 0: + val = None + else: + valbytes = byts[p:p + val_len] + p += val_len + val = value_type.from_binary(valbytes, inner_proto) + themap._insert_unchecked(key, keybytes, val) return themap @classmethod def serialize_safe(cls, themap, protocol_version): key_type, value_type = cls.subtypes pack = int32_pack if protocol_version >= 3 else uint16_pack buf = io.BytesIO() buf.write(pack(len(themap))) try: items = six.iteritems(themap) except AttributeError: raise TypeError("Got a non-map object for a map value") inner_proto = max(3, protocol_version) for key, val in items: keybytes = key_type.to_binary(key, inner_proto) valbytes = value_type.to_binary(val, inner_proto) buf.write(pack(len(keybytes))) buf.write(keybytes) buf.write(pack(len(valbytes))) buf.write(valbytes) return buf.getvalue() class TupleType(_ParameterizedType): typename = 'tuple' @classmethod def deserialize_safe(cls, byts, protocol_version): proto_version = max(3, protocol_version) p = 0 values = [] for col_type in cls.subtypes: if p == len(byts): break itemlen = int32_unpack(byts[p:p + 4]) p += 4 if itemlen >= 0: item = byts[p:p + itemlen] p += itemlen else: item = None # collections inside UDTs are always encoded with at least the # version 3 format values.append(col_type.from_binary(item, proto_version)) if len(values) < len(cls.subtypes): nones = [None] * (len(cls.subtypes) - len(values)) values = values + nones return tuple(values) @classmethod def serialize_safe(cls, val, protocol_version): if len(val) > len(cls.subtypes): raise ValueError("Expected %d items in a tuple, but got %d: %s" % (len(cls.subtypes), len(val), val)) proto_version = max(3, protocol_version) buf = io.BytesIO() for item, subtype in zip(val, cls.subtypes): if item is not None: packed_item = subtype.to_binary(item, proto_version) buf.write(int32_pack(len(packed_item))) buf.write(packed_item) else: buf.write(int32_pack(-1)) return buf.getvalue() @classmethod def cql_parameterized_type(cls): subtypes_string = ', '.join(sub.cql_parameterized_type() for sub in cls.subtypes) return 'frozen>' % (subtypes_string,) class UserType(TupleType): typename = "org.apache.cassandra.db.marshal.UserType" _cache = {} _module = sys.modules[__name__] @classmethod def make_udt_class(cls, keyspace, udt_name, field_names, field_types): assert len(field_names) == len(field_types) if six.PY2 and isinstance(udt_name, unicode): udt_name = udt_name.encode('utf-8') instance = cls._cache.get((keyspace, udt_name)) if not instance or instance.fieldnames != field_names or instance.subtypes != field_types: instance = type(udt_name, (cls,), {'subtypes': field_types, 'cassname': cls.cassname, 'typename': udt_name, 'fieldnames': field_names, 'keyspace': keyspace, 'mapped_class': None, 'tuple_type': cls._make_registered_udt_namedtuple(keyspace, udt_name, field_names)}) cls._cache[(keyspace, udt_name)] = instance return instance @classmethod def evict_udt_class(cls, keyspace, udt_name): if six.PY2 and isinstance(udt_name, unicode): udt_name = udt_name.encode('utf-8') try: del cls._cache[(keyspace, udt_name)] except KeyError: pass @classmethod def apply_parameters(cls, subtypes, names): keyspace = subtypes[0].cass_parameterized_type() # when parsed from cassandra type, the keyspace is created as an unrecognized cass type; This gets the name back udt_name = _name_from_hex_string(subtypes[1].cassname) field_names = tuple(_name_from_hex_string(encoded_name) for encoded_name in names[2:]) # using tuple here to match what comes into make_udt_class from other sources (for caching equality test) return cls.make_udt_class(keyspace, udt_name, field_names, tuple(subtypes[2:])) @classmethod def cql_parameterized_type(cls): return "frozen<%s>" % (cls.typename,) @classmethod def deserialize_safe(cls, byts, protocol_version): values = super(UserType, cls).deserialize_safe(byts, protocol_version) if cls.mapped_class: return cls.mapped_class(**dict(zip(cls.fieldnames, values))) elif cls.tuple_type: return cls.tuple_type(*values) else: return tuple(values) @classmethod def serialize_safe(cls, val, protocol_version): proto_version = max(3, protocol_version) buf = io.BytesIO() for i, (fieldname, subtype) in enumerate(zip(cls.fieldnames, cls.subtypes)): # first treat as a tuple, else by custom type try: item = val[i] except TypeError: item = getattr(val, fieldname) if item is not None: packed_item = subtype.to_binary(item, proto_version) buf.write(int32_pack(len(packed_item))) buf.write(packed_item) else: buf.write(int32_pack(-1)) return buf.getvalue() @classmethod def _make_registered_udt_namedtuple(cls, keyspace, name, field_names): # this is required to make the type resolvable via this module... # required when unregistered udts are pickled for use as keys in # util.OrderedMap t = cls._make_udt_tuple_type(name, field_names) if t: qualified_name = "%s_%s" % (keyspace, name) setattr(cls._module, qualified_name, t) return t @classmethod def _make_udt_tuple_type(cls, name, field_names): # fallback to positional named, then unnamed tuples # for CQL identifiers that aren't valid in Python, try: t = namedtuple(name, field_names) except ValueError: try: t = namedtuple(name, util._positional_rename_invalid_identifiers(field_names)) log.warning("could not create a namedtuple for '%s' because one or more " "field names are not valid Python identifiers (%s); " "returning positionally-named fields" % (name, field_names)) except ValueError: t = None log.warning("could not create a namedtuple for '%s' because the name is " "not a valid Python identifier; will return tuples in " "its place" % (name,)) return t class CompositeType(_ParameterizedType): typename = "org.apache.cassandra.db.marshal.CompositeType" @classmethod def cql_parameterized_type(cls): """ There is no CQL notation for Composites, so we override this. """ typestring = cls.cass_parameterized_type(full=True) return "'%s'" % (typestring,) @classmethod def deserialize_safe(cls, byts, protocol_version): result = [] for subtype in cls.subtypes: if not byts: # CompositeType can have missing elements at the end break element_length = uint16_unpack(byts[:2]) element = byts[2:2 + element_length] # skip element length, element, and the EOC (one byte) byts = byts[2 + element_length + 1:] result.append(subtype.from_binary(element, protocol_version)) return tuple(result) class DynamicCompositeType(_ParameterizedType): typename = "org.apache.cassandra.db.marshal.DynamicCompositeType" @classmethod def cql_parameterized_type(cls): sublist = ', '.join('%s=>%s' % (alias, typ.cass_parameterized_type(full=True)) for alias, typ in zip(cls.fieldnames, cls.subtypes)) return "'%s(%s)'" % (cls.typename, sublist) class ColumnToCollectionType(_ParameterizedType): """ This class only really exists so that we can cleanly evaluate types when Cassandra includes this. We don't actually need or want the extra information. """ typename = "org.apache.cassandra.db.marshal.ColumnToCollectionType" class ReversedType(_ParameterizedType): typename = "org.apache.cassandra.db.marshal.ReversedType" num_subtypes = 1 @classmethod def deserialize_safe(cls, byts, protocol_version): subtype, = cls.subtypes return subtype.from_binary(byts, protocol_version) @classmethod def serialize_safe(cls, val, protocol_version): subtype, = cls.subtypes return subtype.to_binary(val, protocol_version) class FrozenType(_ParameterizedType): typename = "frozen" num_subtypes = 1 @classmethod def deserialize_safe(cls, byts, protocol_version): subtype, = cls.subtypes return subtype.from_binary(byts, protocol_version) @classmethod def serialize_safe(cls, val, protocol_version): subtype, = cls.subtypes return subtype.to_binary(val, protocol_version) def is_counter_type(t): if isinstance(t, six.string_types): t = lookup_casstype(t) return issubclass(t, CounterColumnType) def cql_typename(casstypename): """ Translate a Cassandra-style type specifier (optionally-fully-distinguished Java class names for data types, along with optional parameters) into a CQL-style type specifier. >>> cql_typename('DateType') 'timestamp' >>> cql_typename('org.apache.cassandra.db.marshal.ListType(IntegerType)') 'list' """ return lookup_casstype(casstypename).cql_parameterized_type() + + +class WKBGeometryType(object): + POINT = 1 + LINESTRING = 2 + POLYGON = 3 + + +class PointType(CassandraType): + typename = 'PointType' + + _type = struct.pack('[[]] + type_ = int8_unpack(byts[0:1]) + + if type_ in (BoundKind.to_int(BoundKind.BOTH_OPEN_RANGE), + BoundKind.to_int(BoundKind.SINGLE_DATE_OPEN)): + time0 = precision0 = None + else: + time0 = int64_unpack(byts[1:9]) + precision0 = int8_unpack(byts[9:10]) + + if type_ == BoundKind.to_int(BoundKind.CLOSED_RANGE): + time1 = int64_unpack(byts[10:18]) + precision1 = int8_unpack(byts[18:19]) + else: + time1 = precision1 = None + + if time0 is not None: + date_range_bound0 = util.DateRangeBound( + time0, + cls._decode_precision(precision0) + ) + if time1 is not None: + date_range_bound1 = util.DateRangeBound( + time1, + cls._decode_precision(precision1) + ) + + if type_ == BoundKind.to_int(BoundKind.SINGLE_DATE): + return util.DateRange(value=date_range_bound0) + if type_ == BoundKind.to_int(BoundKind.CLOSED_RANGE): + return util.DateRange(lower_bound=date_range_bound0, + upper_bound=date_range_bound1) + if type_ == BoundKind.to_int(BoundKind.OPEN_RANGE_HIGH): + return util.DateRange(lower_bound=date_range_bound0, + upper_bound=util.OPEN_BOUND) + if type_ == BoundKind.to_int(BoundKind.OPEN_RANGE_LOW): + return util.DateRange(lower_bound=util.OPEN_BOUND, + upper_bound=date_range_bound0) + if type_ == BoundKind.to_int(BoundKind.BOTH_OPEN_RANGE): + return util.DateRange(lower_bound=util.OPEN_BOUND, + upper_bound=util.OPEN_BOUND) + if type_ == BoundKind.to_int(BoundKind.SINGLE_DATE_OPEN): + return util.DateRange(value=util.OPEN_BOUND) + raise ValueError('Could not deserialize %r' % (byts,)) + + @classmethod + def serialize(cls, v, protocol_version): + buf = io.BytesIO() + bound_kind, bounds = None, () + + try: + value = v.value + except AttributeError: + raise ValueError( + '%s.serialize expects an object with a value attribute; got' + '%r' % (cls.__name__, v) + ) + + if value is None: + try: + lower_bound, upper_bound = v.lower_bound, v.upper_bound + except AttributeError: + raise ValueError( + '%s.serialize expects an object with lower_bound and ' + 'upper_bound attributes; got %r' % (cls.__name__, v) + ) + if lower_bound == util.OPEN_BOUND and upper_bound == util.OPEN_BOUND: + bound_kind = BoundKind.BOTH_OPEN_RANGE + elif lower_bound == util.OPEN_BOUND: + bound_kind = BoundKind.OPEN_RANGE_LOW + bounds = (upper_bound,) + elif upper_bound == util.OPEN_BOUND: + bound_kind = BoundKind.OPEN_RANGE_HIGH + bounds = (lower_bound,) + else: + bound_kind = BoundKind.CLOSED_RANGE + bounds = lower_bound, upper_bound + else: # value is not None + if value == util.OPEN_BOUND: + bound_kind = BoundKind.SINGLE_DATE_OPEN + else: + bound_kind = BoundKind.SINGLE_DATE + bounds = (value,) + + if bound_kind is None: + raise ValueError( + 'Cannot serialize %r; could not find bound kind' % (v,) + ) + + buf.write(int8_pack(BoundKind.to_int(bound_kind))) + for bound in bounds: + buf.write(int64_pack(bound.milliseconds)) + buf.write(int8_pack(cls._encode_precision(bound.precision))) + + return buf.getvalue() diff --git a/cassandra/datastax/cloud/__init__.py b/cassandra/datastax/cloud/__init__.py index ed9435e..ecb4a73 100644 --- a/cassandra/datastax/cloud/__init__.py +++ b/cassandra/datastax/cloud/__init__.py @@ -1,167 +1,196 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import logging import json +import sys import tempfile import shutil +import six from six.moves.urllib.request import urlopen _HAS_SSL = True try: - from ssl import SSLContext, PROTOCOL_TLSv1, CERT_REQUIRED + from ssl import SSLContext, PROTOCOL_TLS, CERT_REQUIRED except: _HAS_SSL = False from zipfile import ZipFile # 2.7 vs 3.x try: from zipfile import BadZipFile except: from zipfile import BadZipfile as BadZipFile from cassandra import DriverException log = logging.getLogger(__name__) __all__ = ['get_cloud_config'] -PRODUCT_APOLLO = "DATASTAX_APOLLO" +DATASTAX_CLOUD_PRODUCT_TYPE = "DATASTAX_APOLLO" class CloudConfig(object): username = None password = None host = None port = None keyspace = None local_dc = None ssl_context = None sni_host = None sni_port = None host_ids = None @classmethod def from_dict(cls, d): c = cls() c.port = d.get('port', None) try: c.port = int(d['port']) except: pass c.username = d.get('username', None) c.password = d.get('password', None) c.host = d.get('host', None) c.keyspace = d.get('keyspace', None) c.local_dc = d.get('localDC', None) return c -def get_cloud_config(cloud_config): +def get_cloud_config(cloud_config, create_pyopenssl_context=False): if not _HAS_SSL: raise DriverException("A Python installation with SSL is required to connect to a cloud cluster.") if 'secure_connect_bundle' not in cloud_config: raise ValueError("The cloud config doesn't have a secure_connect_bundle specified.") try: - config = read_cloud_config_from_zip(cloud_config) + config = read_cloud_config_from_zip(cloud_config, create_pyopenssl_context) except BadZipFile: raise ValueError("Unable to open the zip file for the cloud config. Check your secure connect bundle.") - return read_metadata_info(config, cloud_config) + config = read_metadata_info(config, cloud_config) + if create_pyopenssl_context: + config.ssl_context = config.pyopenssl_context + return config -def read_cloud_config_from_zip(cloud_config): +def read_cloud_config_from_zip(cloud_config, create_pyopenssl_context): secure_bundle = cloud_config['secure_connect_bundle'] + use_default_tempdir = cloud_config.get('use_default_tempdir', None) with ZipFile(secure_bundle) as zipfile: - base_dir = os.path.dirname(secure_bundle) + base_dir = tempfile.gettempdir() if use_default_tempdir else os.path.dirname(secure_bundle) tmp_dir = tempfile.mkdtemp(dir=base_dir) try: zipfile.extractall(path=tmp_dir) - return parse_cloud_config(os.path.join(tmp_dir, 'config.json'), cloud_config) + return parse_cloud_config(os.path.join(tmp_dir, 'config.json'), cloud_config, create_pyopenssl_context) finally: shutil.rmtree(tmp_dir) -def parse_cloud_config(path, cloud_config): +def parse_cloud_config(path, cloud_config, create_pyopenssl_context): with open(path, 'r') as stream: data = json.load(stream) config = CloudConfig.from_dict(data) config_dir = os.path.dirname(path) if 'ssl_context' in cloud_config: config.ssl_context = cloud_config['ssl_context'] else: # Load the ssl_context before we delete the temporary directory ca_cert_location = os.path.join(config_dir, 'ca.crt') cert_location = os.path.join(config_dir, 'cert') key_location = os.path.join(config_dir, 'key') + # Regardless of if we create a pyopenssl context, we still need the builtin one + # to connect to the metadata service config.ssl_context = _ssl_context_from_cert(ca_cert_location, cert_location, key_location) + if create_pyopenssl_context: + config.pyopenssl_context = _pyopenssl_context_from_cert(ca_cert_location, cert_location, key_location) return config def read_metadata_info(config, cloud_config): url = "https://{}:{}/metadata".format(config.host, config.port) timeout = cloud_config['connect_timeout'] if 'connect_timeout' in cloud_config else 5 try: response = urlopen(url, context=config.ssl_context, timeout=timeout) except Exception as e: log.exception(e) - raise DriverException("Unable to connect to the metadata service at %s" % url) + raise DriverException("Unable to connect to the metadata service at %s. " + "Check the cluster status in the cloud console. " % url) if response.code != 200: raise DriverException(("Error while fetching the metadata at: %s. " "The service returned error code %d." % (url, response.code))) return parse_metadata_info(config, response.read().decode('utf-8')) def parse_metadata_info(config, http_data): try: data = json.loads(http_data) except: msg = "Failed to load cluster metadata" raise DriverException(msg) contact_info = data['contact_info'] config.local_dc = contact_info['local_dc'] proxy_info = contact_info['sni_proxy_address'].split(':') config.sni_host = proxy_info[0] try: config.sni_port = int(proxy_info[1]) except: config.sni_port = 9042 config.host_ids = [host_id for host_id in contact_info['contact_points']] return config def _ssl_context_from_cert(ca_cert_location, cert_location, key_location): - ssl_context = SSLContext(PROTOCOL_TLSv1) + ssl_context = SSLContext(PROTOCOL_TLS) ssl_context.load_verify_locations(ca_cert_location) ssl_context.verify_mode = CERT_REQUIRED ssl_context.load_cert_chain(certfile=cert_location, keyfile=key_location) return ssl_context + + +def _pyopenssl_context_from_cert(ca_cert_location, cert_location, key_location): + try: + from OpenSSL import SSL + except ImportError as e: + six.reraise( + ImportError, + ImportError("PyOpenSSL must be installed to connect to Astra with the Eventlet or Twisted event loops"), + sys.exc_info()[2] + ) + ssl_context = SSL.Context(SSL.TLSv1_METHOD) + ssl_context.set_verify(SSL.VERIFY_PEER, callback=lambda _1, _2, _3, _4, ok: ok) + ssl_context.use_certificate_file(cert_location) + ssl_context.use_privatekey_file(key_location) + ssl_context.load_verify_locations(ca_cert_location) + + return ssl_context \ No newline at end of file diff --git a/tests/integration/advanced/__init__.py b/cassandra/datastax/graph/__init__.py similarity index 54% copy from tests/integration/advanced/__init__.py copy to cassandra/datastax/graph/__init__.py index 662f5b8..11785c8 100644 --- a/tests/integration/advanced/__init__.py +++ b/cassandra/datastax/graph/__init__.py @@ -1,23 +1,23 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License +# limitations under the License. -try: - import unittest2 as unittest -except ImportError: - import unittest # noqa -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) +from cassandra.datastax.graph.types import Element, Vertex, VertexProperty, Edge, Path, T +from cassandra.datastax.graph.query import ( + GraphOptions, GraphProtocol, GraphStatement, SimpleGraphStatement, Result, + graph_object_row_factory, single_object_row_factory, + graph_result_row_factory, graph_graphson2_row_factory, + graph_graphson3_row_factory +) +from cassandra.datastax.graph.graphson import * diff --git a/cassandra/datastax/graph/fluent/__init__.py b/cassandra/datastax/graph/fluent/__init__.py new file mode 100644 index 0000000..44a0d13 --- /dev/null +++ b/cassandra/datastax/graph/fluent/__init__.py @@ -0,0 +1,303 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import copy + +from concurrent.futures import Future + +HAVE_GREMLIN = False +try: + import gremlin_python + HAVE_GREMLIN = True +except ImportError: + # gremlinpython is not installed. + pass + +if HAVE_GREMLIN: + from gremlin_python.structure.graph import Graph + from gremlin_python.driver.remote_connection import RemoteConnection, RemoteTraversal + from gremlin_python.process.traversal import Traverser, TraversalSideEffects + from gremlin_python.process.graph_traversal import GraphTraversal + + from cassandra.cluster import Session, GraphExecutionProfile, EXEC_PROFILE_GRAPH_DEFAULT + from cassandra.datastax.graph import GraphOptions, GraphProtocol + from cassandra.datastax.graph.query import _GraphSONContextRowFactory + + from cassandra.datastax.graph.fluent.serializers import ( + GremlinGraphSONReaderV2, + GremlinGraphSONReaderV3, + dse_graphson2_deserializers, + gremlin_graphson2_deserializers, + dse_graphson3_deserializers, + gremlin_graphson3_deserializers + ) + from cassandra.datastax.graph.fluent.query import _DefaultTraversalBatch, _query_from_traversal + + log = logging.getLogger(__name__) + + __all__ = ['BaseGraphRowFactory', 'graph_traversal_row_factory', + 'graph_traversal_dse_object_row_factory', 'DSESessionRemoteGraphConnection', 'DseGraph'] + + # Traversal result keys + _bulk_key = 'bulk' + _result_key = 'result' + + + class BaseGraphRowFactory(_GraphSONContextRowFactory): + """ + Base row factory for graph traversal. This class basically wraps a + graphson reader function to handle additional features of Gremlin/DSE + and is callable as a normal row factory. + + Currently supported: + - bulk results + """ + + def __call__(self, column_names, rows): + for row in rows: + parsed_row = self.graphson_reader.readObject(row[0]) + yield parsed_row[_result_key] + bulk = parsed_row.get(_bulk_key, 1) + for _ in range(bulk - 1): + yield copy.deepcopy(parsed_row[_result_key]) + + + class _GremlinGraphSON2RowFactory(BaseGraphRowFactory): + """Row Factory that returns the decoded graphson2.""" + graphson_reader_class = GremlinGraphSONReaderV2 + graphson_reader_kwargs = {'deserializer_map': gremlin_graphson2_deserializers} + + + class _DseGraphSON2RowFactory(BaseGraphRowFactory): + """Row Factory that returns the decoded graphson2 as DSE types.""" + graphson_reader_class = GremlinGraphSONReaderV2 + graphson_reader_kwargs = {'deserializer_map': dse_graphson2_deserializers} + + gremlin_graphson2_traversal_row_factory = _GremlinGraphSON2RowFactory + # TODO remove in next major + graph_traversal_row_factory = gremlin_graphson2_traversal_row_factory + + dse_graphson2_traversal_row_factory = _DseGraphSON2RowFactory + # TODO remove in next major + graph_traversal_dse_object_row_factory = dse_graphson2_traversal_row_factory + + + class _GremlinGraphSON3RowFactory(BaseGraphRowFactory): + """Row Factory that returns the decoded graphson2.""" + graphson_reader_class = GremlinGraphSONReaderV3 + graphson_reader_kwargs = {'deserializer_map': gremlin_graphson3_deserializers} + + + class _DseGraphSON3RowFactory(BaseGraphRowFactory): + """Row Factory that returns the decoded graphson3 as DSE types.""" + graphson_reader_class = GremlinGraphSONReaderV3 + graphson_reader_kwargs = {'deserializer_map': dse_graphson3_deserializers} + + + gremlin_graphson3_traversal_row_factory = _GremlinGraphSON3RowFactory + dse_graphson3_traversal_row_factory = _DseGraphSON3RowFactory + + + class DSESessionRemoteGraphConnection(RemoteConnection): + """ + A Tinkerpop RemoteConnection to execute traversal queries on DSE. + + :param session: A DSE session + :param graph_name: (Optional) DSE Graph name. + :param execution_profile: (Optional) Execution profile for traversal queries. Default is set to `EXEC_PROFILE_GRAPH_DEFAULT`. + """ + + session = None + graph_name = None + execution_profile = None + + def __init__(self, session, graph_name=None, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT): + super(DSESessionRemoteGraphConnection, self).__init__(None, None) + + if not isinstance(session, Session): + raise ValueError('A DSE Session must be provided to execute graph traversal queries.') + + self.session = session + self.graph_name = graph_name + self.execution_profile = execution_profile + + @staticmethod + def _traversers_generator(traversers): + for t in traversers: + yield Traverser(t) + + def _prepare_query(self, bytecode): + ep = self.session.execution_profile_clone_update(self.execution_profile) + graph_options = ep.graph_options + graph_options.graph_name = self.graph_name or graph_options.graph_name + graph_options.graph_language = DseGraph.DSE_GRAPH_QUERY_LANGUAGE + # We resolve the execution profile options here , to know how what gremlin factory to set + self.session._resolve_execution_profile_options(ep) + + context = None + if graph_options.graph_protocol == GraphProtocol.GRAPHSON_2_0: + row_factory = gremlin_graphson2_traversal_row_factory + elif graph_options.graph_protocol == GraphProtocol.GRAPHSON_3_0: + row_factory = gremlin_graphson3_traversal_row_factory + context = { + 'cluster': self.session.cluster, + 'graph_name': graph_options.graph_name.decode('utf-8') + } + else: + raise ValueError('Unknown graph protocol: {}'.format(graph_options.graph_protocol)) + + ep.row_factory = row_factory + query = DseGraph.query_from_traversal(bytecode, graph_options.graph_protocol, context) + + return query, ep + + @staticmethod + def _handle_query_results(result_set, gremlin_future): + try: + gremlin_future.set_result( + RemoteTraversal(DSESessionRemoteGraphConnection._traversers_generator(result_set), TraversalSideEffects()) + ) + except Exception as e: + gremlin_future.set_exception(e) + + @staticmethod + def _handle_query_error(response, gremlin_future): + gremlin_future.set_exception(response) + + def submit(self, bytecode): + # the only reason I don't use submitAsync here + # is to avoid an unuseful future wrap + query, ep = self._prepare_query(bytecode) + + traversers = self.session.execute_graph(query, execution_profile=ep) + return RemoteTraversal(self._traversers_generator(traversers), TraversalSideEffects()) + + def submitAsync(self, bytecode): + query, ep = self._prepare_query(bytecode) + + # to be compatible with gremlinpython, we need to return a concurrent.futures.Future + gremlin_future = Future() + response_future = self.session.execute_graph_async(query, execution_profile=ep) + response_future.add_callback(self._handle_query_results, gremlin_future) + response_future.add_errback(self._handle_query_error, gremlin_future) + + return gremlin_future + + def __str__(self): + return "".format(self.graph_name) + + __repr__ = __str__ + + + class DseGraph(object): + """ + Dse Graph utility class for GraphTraversal construction and execution. + """ + + DSE_GRAPH_QUERY_LANGUAGE = 'bytecode-json' + """ + Graph query language, Default is 'bytecode-json' (GraphSON). + """ + + DSE_GRAPH_QUERY_PROTOCOL = GraphProtocol.GRAPHSON_2_0 + """ + Graph query language, Default is GraphProtocol.GRAPHSON_2_0. + """ + + @staticmethod + def query_from_traversal(traversal, graph_protocol=DSE_GRAPH_QUERY_PROTOCOL, context=None): + """ + From a GraphTraversal, return a query string based on the language specified in `DseGraph.DSE_GRAPH_QUERY_LANGUAGE`. + + :param traversal: The GraphTraversal object + :param graph_protocol: The graph protocol. Default is `DseGraph.DSE_GRAPH_QUERY_PROTOCOL`. + :param context: The dict of the serialization context, needed for GraphSON3 (tuple, udt). + e.g: {'cluster': cluster, 'graph_name': name} + """ + + if isinstance(traversal, GraphTraversal): + for strategy in traversal.traversal_strategies.traversal_strategies: + rc = strategy.remote_connection + if (isinstance(rc, DSESessionRemoteGraphConnection) and + rc.session or rc.graph_name or rc.execution_profile): + log.warning("GraphTraversal session, graph_name and execution_profile are " + "only taken into account when executed with TinkerPop.") + + return _query_from_traversal(traversal, graph_protocol, context) + + @staticmethod + def traversal_source(session=None, graph_name=None, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT, + traversal_class=None): + """ + Returns a TinkerPop GraphTraversalSource binded to the session and graph_name if provided. + + :param session: (Optional) A DSE session + :param graph_name: (Optional) DSE Graph name + :param execution_profile: (Optional) Execution profile for traversal queries. Default is set to `EXEC_PROFILE_GRAPH_DEFAULT`. + :param traversal_class: (Optional) The GraphTraversalSource class to use (DSL). + + .. code-block:: python + + from cassandra.cluster import Cluster + from cassandra.datastax.graph.fluent import DseGraph + + c = Cluster() + session = c.connect() + + g = DseGraph.traversal_source(session, 'my_graph') + print g.V().valueMap().toList() + + """ + + graph = Graph() + traversal_source = graph.traversal(traversal_class) + + if session: + traversal_source = traversal_source.withRemote( + DSESessionRemoteGraphConnection(session, graph_name, execution_profile)) + + return traversal_source + + @staticmethod + def create_execution_profile(graph_name, graph_protocol=DSE_GRAPH_QUERY_PROTOCOL, **kwargs): + """ + Creates an ExecutionProfile for GraphTraversal execution. You need to register that execution profile to the + cluster by using `cluster.add_execution_profile`. + + :param graph_name: The graph name + :param graph_protocol: (Optional) The graph protocol, default is `DSE_GRAPH_QUERY_PROTOCOL`. + """ + + if graph_protocol == GraphProtocol.GRAPHSON_2_0: + row_factory = dse_graphson2_traversal_row_factory + elif graph_protocol == GraphProtocol.GRAPHSON_3_0: + row_factory = dse_graphson3_traversal_row_factory + else: + raise ValueError('Unknown graph protocol: {}'.format(graph_protocol)) + + ep = GraphExecutionProfile(row_factory=row_factory, + graph_options=GraphOptions(graph_name=graph_name, + graph_language=DseGraph.DSE_GRAPH_QUERY_LANGUAGE, + graph_protocol=graph_protocol), + **kwargs) + return ep + + @staticmethod + def batch(*args, **kwargs): + """ + Returns the :class:`cassandra.datastax.graph.fluent.query.TraversalBatch` object allowing to + execute multiple traversals in the same transaction. + """ + return _DefaultTraversalBatch(*args, **kwargs) diff --git a/cassandra/datastax/graph/fluent/_predicates.py b/cassandra/datastax/graph/fluent/_predicates.py new file mode 100644 index 0000000..95bd533 --- /dev/null +++ b/cassandra/datastax/graph/fluent/_predicates.py @@ -0,0 +1,202 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math + +from gremlin_python.process.traversal import P + +from cassandra.util import Distance + +__all__ = ['GeoP', 'TextDistanceP', 'Search', 'GeoUnit', 'Geo', 'CqlCollection'] + + +class GeoP(object): + + def __init__(self, operator, value, other=None): + self.operator = operator + self.value = value + self.other = other + + @staticmethod + def inside(*args, **kwargs): + return GeoP("inside", *args, **kwargs) + + def __eq__(self, other): + return isinstance(other, + self.__class__) and self.operator == other.operator and self.value == other.value and self.other == other.other + + def __repr__(self): + return self.operator + "(" + str(self.value) + ")" if self.other is None else self.operator + "(" + str( + self.value) + "," + str(self.other) + ")" + + +class TextDistanceP(object): + + def __init__(self, operator, value, distance): + self.operator = operator + self.value = value + self.distance = distance + + @staticmethod + def fuzzy(*args): + return TextDistanceP("fuzzy", *args) + + @staticmethod + def token_fuzzy(*args): + return TextDistanceP("tokenFuzzy", *args) + + @staticmethod + def phrase(*args): + return TextDistanceP("phrase", *args) + + def __eq__(self, other): + return isinstance(other, + self.__class__) and self.operator == other.operator and self.value == other.value and self.distance == other.distance + + def __repr__(self): + return self.operator + "(" + str(self.value) + "," + str(self.distance) + ")" + + +class Search(object): + + @staticmethod + def token(value): + """ + Search any instance of a certain token within the text property targeted. + :param value: the value to look for. + """ + return P('token', value) + + @staticmethod + def token_prefix(value): + """ + Search any instance of a certain token prefix withing the text property targeted. + :param value: the value to look for. + """ + return P('tokenPrefix', value) + + @staticmethod + def token_regex(value): + """ + Search any instance of the provided regular expression for the targeted property. + :param value: the value to look for. + """ + return P('tokenRegex', value) + + @staticmethod + def prefix(value): + """ + Search for a specific prefix at the beginning of the text property targeted. + :param value: the value to look for. + """ + return P('prefix', value) + + @staticmethod + def regex(value): + """ + Search for this regular expression inside the text property targeted. + :param value: the value to look for. + """ + return P('regex', value) + + @staticmethod + def fuzzy(value, distance): + """ + Search for a fuzzy string inside the text property targeted. + :param value: the value to look for. + :param distance: The distance for the fuzzy search. ie. 1, to allow a one-letter misspellings. + """ + return TextDistanceP.fuzzy(value, distance) + + @staticmethod + def token_fuzzy(value, distance): + """ + Search for a token fuzzy inside the text property targeted. + :param value: the value to look for. + :param distance: The distance for the token fuzzy search. ie. 1, to allow a one-letter misspellings. + """ + return TextDistanceP.token_fuzzy(value, distance) + + @staticmethod + def phrase(value, proximity): + """ + Search for a phrase inside the text property targeted. + :param value: the value to look for. + :param proximity: The proximity for the phrase search. ie. phrase('David Felcey', 2).. to find 'David Felcey' with up to two middle names. + """ + return TextDistanceP.phrase(value, proximity) + + +class CqlCollection(object): + + @staticmethod + def contains(value): + """ + Search for a value inside a cql list/set column. + :param value: the value to look for. + """ + return P('contains', value) + + @staticmethod + def contains_value(value): + """ + Search for a map value. + :param value: the value to look for. + """ + return P('containsValue', value) + + @staticmethod + def contains_key(value): + """ + Search for a map key. + :param value: the value to look for. + """ + return P('containsKey', value) + + @staticmethod + def entry_eq(value): + """ + Search for a map entry. + :param value: the value to look for. + """ + return P('entryEq', value) + + +class GeoUnit(object): + _EARTH_MEAN_RADIUS_KM = 6371.0087714 + _DEGREES_TO_RADIANS = math.pi / 180 + _DEG_TO_KM = _DEGREES_TO_RADIANS * _EARTH_MEAN_RADIUS_KM + _KM_TO_DEG = 1 / _DEG_TO_KM + _MILES_TO_KM = 1.609344001 + + MILES = _MILES_TO_KM * _KM_TO_DEG + KILOMETERS = _KM_TO_DEG + METERS = _KM_TO_DEG / 1000.0 + DEGREES = 1 + + +class Geo(object): + + @staticmethod + def inside(value, units=GeoUnit.DEGREES): + """ + Search any instance of geometry inside the Distance targeted. + :param value: A Distance to look for. + :param units: The units for ``value``. See GeoUnit enum. (Can also + provide an integer to use as a multiplier to convert ``value`` to + degrees.) + """ + return GeoP.inside( + value=Distance(x=value.x, y=value.y, radius=value.radius * units) + ) diff --git a/cassandra/datastax/graph/fluent/_query.py b/cassandra/datastax/graph/fluent/_query.py new file mode 100644 index 0000000..bd89046 --- /dev/null +++ b/cassandra/datastax/graph/fluent/_query.py @@ -0,0 +1,229 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import six +import logging + +from cassandra.graph import SimpleGraphStatement, GraphProtocol +from cassandra.cluster import EXEC_PROFILE_GRAPH_DEFAULT + +from gremlin_python.process.graph_traversal import GraphTraversal +from gremlin_python.structure.io.graphsonV2d0 import GraphSONWriter as GraphSONWriterV2 +from gremlin_python.structure.io.graphsonV3d0 import GraphSONWriter as GraphSONWriterV3 + +from cassandra.datastax.graph.fluent.serializers import GremlinUserTypeIO, \ + dse_graphson2_serializers, dse_graphson3_serializers + +log = logging.getLogger(__name__) + + +__all__ = ['TraversalBatch', '_query_from_traversal', '_DefaultTraversalBatch'] + + +class _GremlinGraphSONWriterAdapter(object): + + def __init__(self, context, **kwargs): + super(_GremlinGraphSONWriterAdapter, self).__init__(**kwargs) + self.context = context + self.user_types = None + + def serialize(self, value, _): + return self.toDict(value) + + def get_serializer(self, value): + serializer = None + try: + serializer = self.serializers[type(value)] + except KeyError: + for key, ser in self.serializers.items(): + if isinstance(value, key): + serializer = ser + + if self.context: + # Check if UDT + if self.user_types is None: + try: + user_types = self.context['cluster']._user_types[self.context['graph_name']] + self.user_types = dict(map(reversed, six.iteritems(user_types))) + except KeyError: + self.user_types = {} + + # Custom detection to map a namedtuple to udt + if (tuple in self.serializers and serializer is self.serializers[tuple] and hasattr(value, '_fields') or + (not serializer and type(value) in self.user_types)): + serializer = GremlinUserTypeIO + + if serializer: + try: + # A serializer can have specialized serializers (e.g for Int32 and Int64, so value dependant) + serializer = serializer.get_specialized_serializer(value) + except AttributeError: + pass + + return serializer + + def toDict(self, obj): + serializer = self.get_serializer(obj) + return serializer.dictify(obj, self) if serializer else obj + + def definition(self, value): + serializer = self.get_serializer(value) + return serializer.definition(value, self) + + +class GremlinGraphSON2Writer(_GremlinGraphSONWriterAdapter, GraphSONWriterV2): + pass + + +class GremlinGraphSON3Writer(_GremlinGraphSONWriterAdapter, GraphSONWriterV3): + pass + + +graphson2_writer = GremlinGraphSON2Writer +graphson3_writer = GremlinGraphSON3Writer + + +def _query_from_traversal(traversal, graph_protocol, context=None): + """ + From a GraphTraversal, return a query string. + + :param traversal: The GraphTraversal object + :param graphson_protocol: The graph protocol to determine the output format. + """ + if graph_protocol == GraphProtocol.GRAPHSON_2_0: + graphson_writer = graphson2_writer(context, serializer_map=dse_graphson2_serializers) + elif graph_protocol == GraphProtocol.GRAPHSON_3_0: + if context is None: + raise ValueError('Missing context for GraphSON3 serialization requires.') + graphson_writer = graphson3_writer(context, serializer_map=dse_graphson3_serializers) + else: + raise ValueError('Unknown graph protocol: {}'.format(graph_protocol)) + + try: + query = graphson_writer.writeObject(traversal) + except Exception: + log.exception("Error preparing graphson traversal query:") + raise + + return query + + +class TraversalBatch(object): + """ + A `TraversalBatch` is used to execute multiple graph traversals in a + single transaction. If any traversal in the batch fails, the entire + batch will fail to apply. + + If a TraversalBatch is bounded to a DSE session, it can be executed using + `traversal_batch.execute()`. + """ + + _session = None + _execution_profile = None + + def __init__(self, session=None, execution_profile=None): + """ + :param session: (Optional) A DSE session + :param execution_profile: (Optional) The execution profile to use for the batch execution + """ + self._session = session + self._execution_profile = execution_profile + + def add(self, traversal): + """ + Add a traversal to the batch. + + :param traversal: A gremlin GraphTraversal + """ + raise NotImplementedError() + + def add_all(self, traversals): + """ + Adds a sequence of traversals to the batch. + + :param traversals: A sequence of gremlin GraphTraversal + """ + raise NotImplementedError() + + def execute(self): + """ + Execute the traversal batch if bounded to a `DSE Session`. + """ + raise NotImplementedError() + + def as_graph_statement(self, graph_protocol=GraphProtocol.GRAPHSON_2_0): + """ + Return the traversal batch as GraphStatement. + + :param graph_protocol: The graph protocol for the GraphSONWriter. Default is GraphProtocol.GRAPHSON_2_0. + """ + raise NotImplementedError() + + def clear(self): + """ + Clear a traversal batch for reuse. + """ + raise NotImplementedError() + + def __len__(self): + raise NotImplementedError() + + def __str__(self): + return u''.format(len(self)) + __repr__ = __str__ + + +class _DefaultTraversalBatch(TraversalBatch): + + _traversals = None + + def __init__(self, *args, **kwargs): + super(_DefaultTraversalBatch, self).__init__(*args, **kwargs) + self._traversals = [] + + def add(self, traversal): + if not isinstance(traversal, GraphTraversal): + raise ValueError('traversal should be a gremlin GraphTraversal') + + self._traversals.append(traversal) + return self + + def add_all(self, traversals): + for traversal in traversals: + self.add(traversal) + + def as_graph_statement(self, graph_protocol=GraphProtocol.GRAPHSON_2_0, context=None): + statements = [_query_from_traversal(t, graph_protocol, context) for t in self._traversals] + query = u"[{0}]".format(','.join(statements)) + return SimpleGraphStatement(query) + + def execute(self): + if self._session is None: + raise ValueError('A DSE Session must be provided to execute the traversal batch.') + + execution_profile = self._execution_profile if self._execution_profile else EXEC_PROFILE_GRAPH_DEFAULT + graph_options = self._session.get_execution_profile(execution_profile).graph_options + context = { + 'cluster': self._session.cluster, + 'graph_name': graph_options.graph_name + } + statement = self.as_graph_statement(graph_options.graph_protocol, context=context) \ + if graph_options.graph_protocol else self.as_graph_statement(context=context) + return self._session.execute_graph(statement, execution_profile=execution_profile) + + def clear(self): + del self._traversals[:] + + def __len__(self): + return len(self._traversals) diff --git a/cassandra/datastax/graph/fluent/_serializers.py b/cassandra/datastax/graph/fluent/_serializers.py new file mode 100644 index 0000000..db8e715 --- /dev/null +++ b/cassandra/datastax/graph/fluent/_serializers.py @@ -0,0 +1,262 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections import OrderedDict + +import six + +from gremlin_python.structure.io.graphsonV2d0 import ( + GraphSONReader as GraphSONReaderV2, + GraphSONUtil as GraphSONUtil, # no difference between v2 and v3 + VertexDeserializer as VertexDeserializerV2, + VertexPropertyDeserializer as VertexPropertyDeserializerV2, + PropertyDeserializer as PropertyDeserializerV2, + EdgeDeserializer as EdgeDeserializerV2, + PathDeserializer as PathDeserializerV2 +) + +from gremlin_python.structure.io.graphsonV3d0 import ( + GraphSONReader as GraphSONReaderV3, + VertexDeserializer as VertexDeserializerV3, + VertexPropertyDeserializer as VertexPropertyDeserializerV3, + PropertyDeserializer as PropertyDeserializerV3, + EdgeDeserializer as EdgeDeserializerV3, + PathDeserializer as PathDeserializerV3 +) + +try: + from gremlin_python.structure.io.graphsonV2d0 import ( + TraversalMetricsDeserializer as TraversalMetricsDeserializerV2, + MetricsDeserializer as MetricsDeserializerV2 + ) + from gremlin_python.structure.io.graphsonV3d0 import ( + TraversalMetricsDeserializer as TraversalMetricsDeserializerV3, + MetricsDeserializer as MetricsDeserializerV3 + ) +except ImportError: + TraversalMetricsDeserializerV2 = MetricsDeserializerV2 = None + TraversalMetricsDeserializerV3 = MetricsDeserializerV3 = None + +from cassandra.graph import ( + GraphSON2Serializer, + GraphSON2Deserializer, + GraphSON3Serializer, + GraphSON3Deserializer +) +from cassandra.graph.graphson import UserTypeIO, TypeWrapperTypeIO +from cassandra.datastax.graph.fluent.predicates import GeoP, TextDistanceP +from cassandra.util import Distance + + +__all__ = ['GremlinGraphSONReader', 'GeoPSerializer', 'TextDistancePSerializer', + 'DistanceIO', 'gremlin_deserializers', 'deserializers', 'serializers', + 'GremlinGraphSONReaderV2', 'GremlinGraphSONReaderV3', 'dse_graphson2_serializers', + 'dse_graphson2_deserializers', 'dse_graphson3_serializers', 'dse_graphson3_deserializers', + 'gremlin_graphson2_deserializers', 'gremlin_graphson3_deserializers', 'GremlinUserTypeIO'] + + +class _GremlinGraphSONTypeSerializer(object): + TYPE_KEY = "@type" + VALUE_KEY = "@value" + serializer = None + + def __init__(self, serializer): + self.serializer = serializer + + def dictify(self, v, writer): + value = self.serializer.serialize(v, writer) + if self.serializer is TypeWrapperTypeIO: + graphson_base_type = v.type_io.graphson_base_type + graphson_type = v.type_io.graphson_type + else: + graphson_base_type = self.serializer.graphson_base_type + graphson_type = self.serializer.graphson_type + + if graphson_base_type is None: + out = value + else: + out = {self.TYPE_KEY: graphson_type} + if value is not None: + out[self.VALUE_KEY] = value + + return out + + def definition(self, value, writer=None): + return self.serializer.definition(value, writer) + + def get_specialized_serializer(self, value): + ser = self.serializer.get_specialized_serializer(value) + if ser is not self.serializer: + return _GremlinGraphSONTypeSerializer(ser) + return self + + +class _GremlinGraphSONTypeDeserializer(object): + + deserializer = None + + def __init__(self, deserializer): + self.deserializer = deserializer + + def objectify(self, v, reader): + return self.deserializer.deserialize(v, reader) + + +def _make_gremlin_graphson2_deserializer(graphson_type): + return _GremlinGraphSONTypeDeserializer( + GraphSON2Deserializer.get_deserializer(graphson_type.graphson_type) + ) + + +def _make_gremlin_graphson3_deserializer(graphson_type): + return _GremlinGraphSONTypeDeserializer( + GraphSON3Deserializer.get_deserializer(graphson_type.graphson_type) + ) + + +class _GremlinGraphSONReader(object): + """Gremlin GraphSONReader Adapter, required to use gremlin types""" + + context = None + + def __init__(self, context, deserializer_map=None): + self.context = context + super(_GremlinGraphSONReader, self).__init__(deserializer_map) + + def deserialize(self, obj): + return self.toObject(obj) + + +class GremlinGraphSONReaderV2(_GremlinGraphSONReader, GraphSONReaderV2): + pass + +# TODO remove next major +GremlinGraphSONReader = GremlinGraphSONReaderV2 + +class GremlinGraphSONReaderV3(_GremlinGraphSONReader, GraphSONReaderV3): + pass + + +class GeoPSerializer(object): + @classmethod + def dictify(cls, p, writer): + out = { + "predicateType": "Geo", + "predicate": p.operator, + "value": [writer.toDict(p.value), writer.toDict(p.other)] if p.other is not None else writer.toDict(p.value) + } + return GraphSONUtil.typedValue("P", out, prefix='dse') + + +class TextDistancePSerializer(object): + @classmethod + def dictify(cls, p, writer): + out = { + "predicate": p.operator, + "value": { + 'query': writer.toDict(p.value), + 'distance': writer.toDict(p.distance) + } + } + return GraphSONUtil.typedValue("P", out) + + +class DistanceIO(object): + @classmethod + def dictify(cls, v, _): + return GraphSONUtil.typedValue('Distance', six.text_type(v), prefix='dse') + + +GremlinUserTypeIO = _GremlinGraphSONTypeSerializer(UserTypeIO) + +# GraphSON2 +dse_graphson2_serializers = OrderedDict([ + (t, _GremlinGraphSONTypeSerializer(s)) + for t, s in six.iteritems(GraphSON2Serializer.get_type_definitions()) +]) + +dse_graphson2_serializers.update(OrderedDict([ + (Distance, DistanceIO), + (GeoP, GeoPSerializer), + (TextDistanceP, TextDistancePSerializer) +])) + +# TODO remove next major, this is just in case someone was using it +serializers = dse_graphson2_serializers + +dse_graphson2_deserializers = { + k: _make_gremlin_graphson2_deserializer(v) + for k, v in six.iteritems(GraphSON2Deserializer.get_type_definitions()) +} + +dse_graphson2_deserializers.update({ + "dse:Distance": DistanceIO, +}) + +# TODO remove next major, this is just in case someone was using it +deserializers = dse_graphson2_deserializers + +gremlin_graphson2_deserializers = dse_graphson2_deserializers.copy() +gremlin_graphson2_deserializers.update({ + 'g:Vertex': VertexDeserializerV2, + 'g:VertexProperty': VertexPropertyDeserializerV2, + 'g:Edge': EdgeDeserializerV2, + 'g:Property': PropertyDeserializerV2, + 'g:Path': PathDeserializerV2 +}) + +if TraversalMetricsDeserializerV2: + gremlin_graphson2_deserializers.update({ + 'g:TraversalMetrics': TraversalMetricsDeserializerV2, + 'g:lMetrics': MetricsDeserializerV2 + }) + +# TODO remove next major, this is just in case someone was using it +gremlin_deserializers = gremlin_graphson2_deserializers + +# GraphSON3 +dse_graphson3_serializers = OrderedDict([ + (t, _GremlinGraphSONTypeSerializer(s)) + for t, s in six.iteritems(GraphSON3Serializer.get_type_definitions()) +]) + +dse_graphson3_serializers.update(OrderedDict([ + (Distance, DistanceIO), + (GeoP, GeoPSerializer), + (TextDistanceP, TextDistancePSerializer) +])) + +dse_graphson3_deserializers = { + k: _make_gremlin_graphson3_deserializer(v) + for k, v in six.iteritems(GraphSON3Deserializer.get_type_definitions()) +} + +dse_graphson3_deserializers.update({ + "dse:Distance": DistanceIO +}) + +gremlin_graphson3_deserializers = dse_graphson3_deserializers.copy() +gremlin_graphson3_deserializers.update({ + 'g:Vertex': VertexDeserializerV3, + 'g:VertexProperty': VertexPropertyDeserializerV3, + 'g:Edge': EdgeDeserializerV3, + 'g:Property': PropertyDeserializerV3, + 'g:Path': PathDeserializerV3 +}) + +if TraversalMetricsDeserializerV3: + gremlin_graphson3_deserializers.update({ + 'g:TraversalMetrics': TraversalMetricsDeserializerV3, + 'g:Metrics': MetricsDeserializerV3 + }) diff --git a/tests/integration/advanced/__init__.py b/cassandra/datastax/graph/fluent/predicates.py similarity index 70% copy from tests/integration/advanced/__init__.py copy to cassandra/datastax/graph/fluent/predicates.py index 662f5b8..6bfd6b3 100644 --- a/tests/integration/advanced/__init__.py +++ b/cassandra/datastax/graph/fluent/predicates.py @@ -1,23 +1,20 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License +# limitations under the License. try: - import unittest2 as unittest + import gremlin_python + from cassandra.datastax.graph.fluent._predicates import * except ImportError: - import unittest # noqa - -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) + # gremlinpython is not installed. + pass diff --git a/tests/integration/advanced/__init__.py b/cassandra/datastax/graph/fluent/query.py similarity index 70% copy from tests/integration/advanced/__init__.py copy to cassandra/datastax/graph/fluent/query.py index 662f5b8..c5026cc 100644 --- a/tests/integration/advanced/__init__.py +++ b/cassandra/datastax/graph/fluent/query.py @@ -1,23 +1,20 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License +# limitations under the License. try: - import unittest2 as unittest + import gremlin_python + from cassandra.datastax.graph.fluent._query import * except ImportError: - import unittest # noqa - -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) + # gremlinpython is not installed. + pass diff --git a/tests/integration/advanced/__init__.py b/cassandra/datastax/graph/fluent/serializers.py similarity index 70% copy from tests/integration/advanced/__init__.py copy to cassandra/datastax/graph/fluent/serializers.py index 662f5b8..680e613 100644 --- a/tests/integration/advanced/__init__.py +++ b/cassandra/datastax/graph/fluent/serializers.py @@ -1,23 +1,20 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License +# limitations under the License. try: - import unittest2 as unittest + import gremlin_python + from cassandra.datastax.graph.fluent._serializers import * except ImportError: - import unittest # noqa - -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) + # gremlinpython is not installed. + pass diff --git a/cassandra/datastax/graph/graphson.py b/cassandra/datastax/graph/graphson.py new file mode 100644 index 0000000..4b333eb --- /dev/null +++ b/cassandra/datastax/graph/graphson.py @@ -0,0 +1,1151 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import datetime +import base64 +import uuid +import re +import json +from decimal import Decimal +from collections import OrderedDict +import logging +import itertools +from functools import partial + +import six + +try: + import ipaddress +except: + ipaddress = None + + +from cassandra.cqltypes import cql_types_from_string +from cassandra.metadata import UserType +from cassandra.util import Polygon, Point, LineString, Duration +from cassandra.datastax.graph.types import Vertex, VertexProperty, Edge, Path, T + +__all__ = ['GraphSON1Serializer', 'GraphSON1Deserializer', 'GraphSON1TypeDeserializer', + 'GraphSON2Serializer', 'GraphSON2Deserializer', 'GraphSON2Reader', + 'GraphSON3Serializer', 'GraphSON3Deserializer', 'GraphSON3Reader', + 'to_bigint', 'to_int', 'to_double', 'to_float', 'to_smallint', + 'BooleanTypeIO', 'Int16TypeIO', 'Int32TypeIO', 'DoubleTypeIO', + 'FloatTypeIO', 'UUIDTypeIO', 'BigDecimalTypeIO', 'DurationTypeIO', 'InetTypeIO', + 'InstantTypeIO', 'LocalDateTypeIO', 'LocalTimeTypeIO', 'Int64TypeIO', 'BigIntegerTypeIO', + 'LocalDateTypeIO', 'PolygonTypeIO', 'PointTypeIO', 'LineStringTypeIO', 'BlobTypeIO', + 'GraphSON3Serializer', 'GraphSON3Deserializer', 'UserTypeIO', 'TypeWrapperTypeIO'] + +""" +Supported types: + +DSE Graph GraphSON 2.0 GraphSON 3.0 | Python Driver +------------ | -------------- | -------------- | ------------ +text | string | string | str +boolean | | | bool +bigint | g:Int64 | g:Int64 | long +int | g:Int32 | g:Int32 | int +double | g:Double | g:Double | float +float | g:Float | g:Float | float +uuid | g:UUID | g:UUID | UUID +bigdecimal | gx:BigDecimal | gx:BigDecimal | Decimal +duration | gx:Duration | N/A | timedelta (Classic graph only) +DSE Duration | N/A | dse:Duration | Duration (Core graph only) +inet | gx:InetAddress | gx:InetAddress | str (unicode), IPV4Address/IPV6Address (PY3) +timestamp | gx:Instant | gx:Instant | datetime.datetime +date | gx:LocalDate | gx:LocalDate | datetime.date +time | gx:LocalTime | gx:LocalTime | datetime.time +smallint | gx:Int16 | gx:Int16 | int +varint | gx:BigInteger | gx:BigInteger | long +date | gx:LocalDate | gx:LocalDate | Date +polygon | dse:Polygon | dse:Polygon | Polygon +point | dse:Point | dse:Point | Point +linestring | dse:Linestring | dse:LineString | LineString +blob | dse:Blob | dse:Blob | bytearray, buffer (PY2), memoryview (PY3), bytes (PY3) +blob | gx:ByteBuffer | gx:ByteBuffer | bytearray, buffer (PY2), memoryview (PY3), bytes (PY3) +list | N/A | g:List | list (Core graph only) +map | N/A | g:Map | dict (Core graph only) +set | N/A | g:Set | set or list (Core graph only) + Can return a list due to numerical values returned by Java +tuple | N/A | dse:Tuple | tuple (Core graph only) +udt | N/A | dse:UDT | class or namedtuple (Core graph only) +""" + +MAX_INT32 = 2 ** 32 - 1 +MIN_INT32 = -2 ** 31 + +log = logging.getLogger(__name__) + + +class _GraphSONTypeType(type): + """GraphSONType metaclass, required to create a class property.""" + + @property + def graphson_type(cls): + return "{0}:{1}".format(cls.prefix, cls.graphson_base_type) + + +@six.add_metaclass(_GraphSONTypeType) +class GraphSONTypeIO(object): + """Represent a serializable GraphSON type""" + + prefix = 'g' + graphson_base_type = None + cql_type = None + + @classmethod + def definition(cls, value, writer=None): + return {'cqlType': cls.cql_type} + + @classmethod + def serialize(cls, value, writer=None): + return six.text_type(value) + + @classmethod + def deserialize(cls, value, reader=None): + return value + + @classmethod + def get_specialized_serializer(cls, value): + return cls + + +class TextTypeIO(GraphSONTypeIO): + cql_type = 'text' + + +class BooleanTypeIO(GraphSONTypeIO): + graphson_base_type = None + cql_type = 'boolean' + + @classmethod + def serialize(cls, value, writer=None): + return bool(value) + + +class IntegerTypeIO(GraphSONTypeIO): + + @classmethod + def serialize(cls, value, writer=None): + return value + + @classmethod + def get_specialized_serializer(cls, value): + if type(value) in six.integer_types and (value > MAX_INT32 or value < MIN_INT32): + return Int64TypeIO + + return Int32TypeIO + + +class Int16TypeIO(IntegerTypeIO): + prefix = 'gx' + graphson_base_type = 'Int16' + cql_type = 'smallint' + + +class Int32TypeIO(IntegerTypeIO): + graphson_base_type = 'Int32' + cql_type = 'int' + + +class Int64TypeIO(IntegerTypeIO): + graphson_base_type = 'Int64' + cql_type = 'bigint' + + @classmethod + def deserialize(cls, value, reader=None): + if six.PY3: + return value + return long(value) + + +class FloatTypeIO(GraphSONTypeIO): + graphson_base_type = 'Float' + cql_type = 'float' + + @classmethod + def serialize(cls, value, writer=None): + return value + + @classmethod + def deserialize(cls, value, reader=None): + return float(value) + + +class DoubleTypeIO(FloatTypeIO): + graphson_base_type = 'Double' + cql_type = 'double' + + +class BigIntegerTypeIO(IntegerTypeIO): + prefix = 'gx' + graphson_base_type = 'BigInteger' + + +class LocalDateTypeIO(GraphSONTypeIO): + FORMAT = '%Y-%m-%d' + + prefix = 'gx' + graphson_base_type = 'LocalDate' + cql_type = 'date' + + @classmethod + def serialize(cls, value, writer=None): + return value.isoformat() + + @classmethod + def deserialize(cls, value, reader=None): + try: + return datetime.datetime.strptime(value, cls.FORMAT).date() + except ValueError: + # negative date + return value + + +class InstantTypeIO(GraphSONTypeIO): + prefix = 'gx' + graphson_base_type = 'Instant' + cql_type = 'timestamp' + + @classmethod + def serialize(cls, value, writer=None): + if isinstance(value, datetime.datetime): + value = datetime.datetime(*value.utctimetuple()[:6]).replace(microsecond=value.microsecond) + else: + value = datetime.datetime.combine(value, datetime.datetime.min.time()) + + return "{0}Z".format(value.isoformat()) + + @classmethod + def deserialize(cls, value, reader=None): + try: + d = datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ') + except ValueError: + d = datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ') + return d + + +class LocalTimeTypeIO(GraphSONTypeIO): + FORMATS = [ + '%H:%M', + '%H:%M:%S', + '%H:%M:%S.%f' + ] + + prefix = 'gx' + graphson_base_type = 'LocalTime' + cql_type = 'time' + + @classmethod + def serialize(cls, value, writer=None): + return value.strftime(cls.FORMATS[2]) + + @classmethod + def deserialize(cls, value, reader=None): + dt = None + for f in cls.FORMATS: + try: + dt = datetime.datetime.strptime(value, f) + break + except ValueError: + continue + + if dt is None: + raise ValueError('Unable to decode LocalTime: {0}'.format(value)) + + return dt.time() + + +class BlobTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'Blob' + cql_type = 'blob' + + @classmethod + def serialize(cls, value, writer=None): + value = base64.b64encode(value) + if six.PY3: + value = value.decode('utf-8') + return value + + @classmethod + def deserialize(cls, value, reader=None): + return bytearray(base64.b64decode(value)) + + +class ByteBufferTypeIO(BlobTypeIO): + prefix = 'gx' + graphson_base_type = 'ByteBuffer' + + +class UUIDTypeIO(GraphSONTypeIO): + graphson_base_type = 'UUID' + cql_type = 'uuid' + + @classmethod + def deserialize(cls, value, reader=None): + return uuid.UUID(value) + + +class BigDecimalTypeIO(GraphSONTypeIO): + prefix = 'gx' + graphson_base_type = 'BigDecimal' + cql_type = 'bigdecimal' + + @classmethod + def deserialize(cls, value, reader=None): + return Decimal(value) + + +class DurationTypeIO(GraphSONTypeIO): + prefix = 'gx' + graphson_base_type = 'Duration' + cql_type = 'duration' + + _duration_regex = re.compile(r""" + ^P((?P\d+)D)? + T((?P\d+)H)? + ((?P\d+)M)? + ((?P[0-9.]+)S)?$ + """, re.VERBOSE) + _duration_format = "P{days}DT{hours}H{minutes}M{seconds}S" + + _seconds_in_minute = 60 + _seconds_in_hour = 60 * _seconds_in_minute + _seconds_in_day = 24 * _seconds_in_hour + + @classmethod + def serialize(cls, value, writer=None): + total_seconds = int(value.total_seconds()) + days, total_seconds = divmod(total_seconds, cls._seconds_in_day) + hours, total_seconds = divmod(total_seconds, cls._seconds_in_hour) + minutes, total_seconds = divmod(total_seconds, cls._seconds_in_minute) + total_seconds += value.microseconds / 1e6 + + return cls._duration_format.format( + days=int(days), hours=int(hours), minutes=int(minutes), seconds=total_seconds + ) + + @classmethod + def deserialize(cls, value, reader=None): + duration = cls._duration_regex.match(value) + if duration is None: + raise ValueError('Invalid duration: {0}'.format(value)) + + duration = {k: float(v) if v is not None else 0 + for k, v in six.iteritems(duration.groupdict())} + return datetime.timedelta(days=duration['days'], hours=duration['hours'], + minutes=duration['minutes'], seconds=duration['seconds']) + + +class DseDurationTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'Duration' + cql_type = 'duration' + + @classmethod + def serialize(cls, value, writer=None): + return { + 'months': value.months, + 'days': value.days, + 'nanos': value.nanoseconds + } + + @classmethod + def deserialize(cls, value, reader=None): + return Duration( + reader.deserialize(value['months']), + reader.deserialize(value['days']), + reader.deserialize(value['nanos']) + ) + + +class TypeWrapperTypeIO(GraphSONTypeIO): + + @classmethod + def definition(cls, value, writer=None): + return {'cqlType': value.type_io.cql_type} + + @classmethod + def serialize(cls, value, writer=None): + return value.type_io.serialize(value.value) + + @classmethod + def deserialize(cls, value, reader=None): + return value.type_io.deserialize(value.value) + + +class PointTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'Point' + cql_type = "org.apache.cassandra.db.marshal.PointType" + + @classmethod + def deserialize(cls, value, reader=None): + return Point.from_wkt(value) + + +class LineStringTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'LineString' + cql_type = "org.apache.cassandra.db.marshal.LineStringType" + + @classmethod + def deserialize(cls, value, reader=None): + return LineString.from_wkt(value) + + +class PolygonTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'Polygon' + cql_type = "org.apache.cassandra.db.marshal.PolygonType" + + @classmethod + def deserialize(cls, value, reader=None): + return Polygon.from_wkt(value) + + +class InetTypeIO(GraphSONTypeIO): + prefix = 'gx' + graphson_base_type = 'InetAddress' + cql_type = 'inet' + + +class VertexTypeIO(GraphSONTypeIO): + graphson_base_type = 'Vertex' + + @classmethod + def deserialize(cls, value, reader=None): + vertex = Vertex(id=reader.deserialize(value["id"]), + label=value["label"] if "label" in value else "vertex", + type='vertex', + properties={}) + # avoid the properties processing in Vertex.__init__ + vertex.properties = reader.deserialize(value.get('properties', {})) + return vertex + + +class VertexPropertyTypeIO(GraphSONTypeIO): + graphson_base_type = 'VertexProperty' + + @classmethod + def deserialize(cls, value, reader=None): + return VertexProperty(label=value['label'], + value=reader.deserialize(value["value"]), + properties=reader.deserialize(value.get('properties', {}))) + + +class EdgeTypeIO(GraphSONTypeIO): + graphson_base_type = 'Edge' + + @classmethod + def deserialize(cls, value, reader=None): + in_vertex = Vertex(id=reader.deserialize(value["inV"]), + label=value['inVLabel'], + type='vertex', + properties={}) + out_vertex = Vertex(id=reader.deserialize(value["outV"]), + label=value['outVLabel'], + type='vertex', + properties={}) + return Edge( + id=reader.deserialize(value["id"]), + label=value["label"] if "label" in value else "vertex", + type='edge', + properties=reader.deserialize(value.get("properties", {})), + inV=in_vertex, + inVLabel=value['inVLabel'], + outV=out_vertex, + outVLabel=value['outVLabel'] + ) + + +class PropertyTypeIO(GraphSONTypeIO): + graphson_base_type = 'Property' + + @classmethod + def deserialize(cls, value, reader=None): + return {value["key"]: reader.deserialize(value["value"])} + + +class PathTypeIO(GraphSONTypeIO): + graphson_base_type = 'Path' + + @classmethod + def deserialize(cls, value, reader=None): + labels = [set(label) for label in reader.deserialize(value['labels'])] + objects = [obj for obj in reader.deserialize(value['objects'])] + p = Path(labels, []) + p.objects = objects # avoid the object processing in Path.__init__ + return p + + +class TraversalMetricsTypeIO(GraphSONTypeIO): + graphson_base_type = 'TraversalMetrics' + + @classmethod + def deserialize(cls, value, reader=None): + return reader.deserialize(value) + + +class MetricsTypeIO(GraphSONTypeIO): + graphson_base_type = 'Metrics' + + @classmethod + def deserialize(cls, value, reader=None): + return reader.deserialize(value) + + +class JsonMapTypeIO(GraphSONTypeIO): + """In GraphSON2, dict are simply serialized as json map""" + + @classmethod + def serialize(cls, value, writer=None): + out = {} + for k, v in six.iteritems(value): + out[k] = writer.serialize(v, writer) + + return out + + +class MapTypeIO(GraphSONTypeIO): + """In GraphSON3, dict has its own type""" + + graphson_base_type = 'Map' + cql_type = 'map' + + @classmethod + def definition(cls, value, writer=None): + out = OrderedDict([('cqlType', cls.cql_type)]) + out['definition'] = [] + for k, v in six.iteritems(value): + # we just need the first pair to write the def + out['definition'].append(writer.definition(k)) + out['definition'].append(writer.definition(v)) + break + return out + + @classmethod + def serialize(cls, value, writer=None): + out = [] + for k, v in six.iteritems(value): + out.append(writer.serialize(k, writer)) + out.append(writer.serialize(v, writer)) + + return out + + @classmethod + def deserialize(cls, value, reader=None): + out = {} + a, b = itertools.tee(value) + for key, val in zip( + itertools.islice(a, 0, None, 2), + itertools.islice(b, 1, None, 2) + ): + out[reader.deserialize(key)] = reader.deserialize(val) + return out + + +class ListTypeIO(GraphSONTypeIO): + """In GraphSON3, list has its own type""" + + graphson_base_type = 'List' + cql_type = 'list' + + @classmethod + def definition(cls, value, writer=None): + out = OrderedDict([('cqlType', cls.cql_type)]) + out['definition'] = [] + if value: + out['definition'].append(writer.definition(value[0])) + return out + + @classmethod + def serialize(cls, value, writer=None): + return [writer.serialize(v, writer) for v in value] + + @classmethod + def deserialize(cls, value, reader=None): + return [reader.deserialize(obj) for obj in value] + + +class SetTypeIO(GraphSONTypeIO): + """In GraphSON3, set has its own type""" + + graphson_base_type = 'Set' + cql_type = 'set' + + @classmethod + def definition(cls, value, writer=None): + out = OrderedDict([('cqlType', cls.cql_type)]) + out['definition'] = [] + for v in value: + # we only take into account the first value for the definition + out['definition'].append(writer.definition(v)) + break + return out + + @classmethod + def serialize(cls, value, writer=None): + return [writer.serialize(v, writer) for v in value] + + @classmethod + def deserialize(cls, value, reader=None): + lst = [reader.deserialize(obj) for obj in value] + + s = set(lst) + if len(s) != len(lst): + log.warning("Coercing g:Set to list due to numerical values returned by Java. " + "See TINKERPOP-1844 for details.") + return lst + + return s + + +class BulkSetTypeIO(GraphSONTypeIO): + graphson_base_type = "BulkSet" + + @classmethod + def deserialize(cls, value, reader=None): + out = [] + + a, b = itertools.tee(value) + for val, bulk in zip( + itertools.islice(a, 0, None, 2), + itertools.islice(b, 1, None, 2) + ): + val = reader.deserialize(val) + bulk = reader.deserialize(bulk) + for n in range(bulk): + out.append(val) + + return out + + +class TupleTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'Tuple' + cql_type = 'tuple' + + @classmethod + def definition(cls, value, writer=None): + out = OrderedDict() + out['cqlType'] = cls.cql_type + serializers = [writer.get_serializer(s) for s in value] + out['definition'] = [s.definition(v, writer) for v, s in zip(value, serializers)] + return out + + @classmethod + def serialize(cls, value, writer=None): + out = cls.definition(value, writer) + out['value'] = [writer.serialize(v, writer) for v in value] + return out + + @classmethod + def deserialize(cls, value, reader=None): + return tuple(reader.deserialize(obj) for obj in value['value']) + + +class UserTypeIO(GraphSONTypeIO): + prefix = 'dse' + graphson_base_type = 'UDT' + cql_type = 'udt' + + FROZEN_REMOVAL_REGEX = re.compile(r'frozen<"*([^"]+)"*>') + + @classmethod + def cql_types_from_string(cls, typ): + # sanitizing: remove frozen references and double quotes... + return cql_types_from_string( + re.sub(cls.FROZEN_REMOVAL_REGEX, r'\1', typ) + ) + + @classmethod + def get_udt_definition(cls, value, writer): + user_type_name = writer.user_types[type(value)] + keyspace = writer.context['graph_name'] + return writer.context['cluster'].metadata.keyspaces[keyspace].user_types[user_type_name] + + @classmethod + def is_collection(cls, typ): + return typ in ['list', 'tuple', 'map', 'set'] + + @classmethod + def is_udt(cls, typ, writer): + keyspace = writer.context['graph_name'] + if keyspace in writer.context['cluster'].metadata.keyspaces: + return typ in writer.context['cluster'].metadata.keyspaces[keyspace].user_types + return False + + @classmethod + def field_definition(cls, types, writer, name=None): + """ + Build the udt field definition. This is required when we have a complex udt type. + """ + index = -1 + out = [OrderedDict() if name is None else OrderedDict([('fieldName', name)])] + + while types: + index += 1 + typ = types.pop(0) + if index > 0: + out.append(OrderedDict()) + + if cls.is_udt(typ, writer): + keyspace = writer.context['graph_name'] + udt = writer.context['cluster'].metadata.keyspaces[keyspace].user_types[typ] + out[index].update(cls.definition(udt, writer)) + elif cls.is_collection(typ): + out[index]['cqlType'] = typ + definition = cls.field_definition(types, writer) + out[index]['definition'] = definition if isinstance(definition, list) else [definition] + else: + out[index]['cqlType'] = typ + + return out if len(out) > 1 else out[0] + + @classmethod + def definition(cls, value, writer=None): + udt = value if isinstance(value, UserType) else cls.get_udt_definition(value, writer) + return OrderedDict([ + ('cqlType', cls.cql_type), + ('keyspace', udt.keyspace), + ('name', udt.name), + ('definition', [ + cls.field_definition(cls.cql_types_from_string(typ), writer, name=name) + for name, typ in zip(udt.field_names, udt.field_types)]) + ]) + + @classmethod + def serialize(cls, value, writer=None): + udt = cls.get_udt_definition(value, writer) + out = cls.definition(value, writer) + out['value'] = [] + for name, typ in zip(udt.field_names, udt.field_types): + out['value'].append(writer.serialize(getattr(value, name), writer)) + return out + + @classmethod + def deserialize(cls, value, reader=None): + udt_class = reader.context['cluster']._user_types[value['keyspace']][value['name']] + kwargs = zip( + list(map(lambda v: v['fieldName'], value['definition'])), + [reader.deserialize(v) for v in value['value']] + ) + return udt_class(**dict(kwargs)) + + +class TTypeIO(GraphSONTypeIO): + prefix = 'g' + graphson_base_type = 'T' + + @classmethod + def deserialize(cls, value, reader=None): + return T.name_to_value[value] + + +class _BaseGraphSONSerializer(object): + + _serializers = OrderedDict() + + @classmethod + def register(cls, type, serializer): + cls._serializers[type] = serializer + + @classmethod + def get_type_definitions(cls): + return cls._serializers.copy() + + @classmethod + def get_serializer(cls, value): + """ + Get the serializer for a python object. + + :param value: The python object. + """ + + # The serializer matching logic is as follow: + # 1. Try to find the python type by direct access. + # 2. Try to find the first serializer by class inheritance. + # 3. If no serializer found, return the raw value. + + # Note that when trying to find the serializer by class inheritance, + # the order that serializers are registered is important. The use of + # an OrderedDict is to avoid the difference between executions. + serializer = None + try: + serializer = cls._serializers[type(value)] + except KeyError: + for key, serializer_ in cls._serializers.items(): + if isinstance(value, key): + serializer = serializer_ + break + + if serializer: + # A serializer can have specialized serializers (e.g for Int32 and Int64, so value dependant) + serializer = serializer.get_specialized_serializer(value) + + return serializer + + @classmethod + def serialize(cls, value, writer=None): + """ + Serialize a python object to GraphSON. + + e.g 'P42DT10H5M37S' + e.g. {'key': value} + + :param value: The python object to serialize. + :param writer: A graphson serializer for recursive types (Optional) + """ + serializer = cls.get_serializer(value) + if serializer: + return serializer.serialize(value, writer or cls) + + return value + + +class GraphSON1Serializer(_BaseGraphSONSerializer): + """ + Serialize python objects to graphson types. + """ + + # When we fall back to a superclass's serializer, we iterate over this map. + # We want that iteration order to be consistent, so we use an OrderedDict, + # not a dict. + _serializers = OrderedDict([ + (str, TextTypeIO), + (bool, BooleanTypeIO), + (bytearray, ByteBufferTypeIO), + (Decimal, BigDecimalTypeIO), + (datetime.date, LocalDateTypeIO), + (datetime.time, LocalTimeTypeIO), + (datetime.timedelta, DurationTypeIO), + (datetime.datetime, InstantTypeIO), + (uuid.UUID, UUIDTypeIO), + (Polygon, PolygonTypeIO), + (Point, PointTypeIO), + (LineString, LineStringTypeIO), + (dict, JsonMapTypeIO), + (float, FloatTypeIO) + ]) + + +if ipaddress: + GraphSON1Serializer.register(ipaddress.IPv4Address, InetTypeIO) + GraphSON1Serializer.register(ipaddress.IPv6Address, InetTypeIO) + +if six.PY2: + GraphSON1Serializer.register(buffer, ByteBufferTypeIO) + GraphSON1Serializer.register(unicode, TextTypeIO) +else: + GraphSON1Serializer.register(memoryview, ByteBufferTypeIO) + GraphSON1Serializer.register(bytes, ByteBufferTypeIO) + + +class _BaseGraphSONDeserializer(object): + + _deserializers = {} + + @classmethod + def get_type_definitions(cls): + return cls._deserializers.copy() + + @classmethod + def register(cls, graphson_type, serializer): + cls._deserializers[graphson_type] = serializer + + @classmethod + def get_deserializer(cls, graphson_type): + try: + return cls._deserializers[graphson_type] + except KeyError: + raise ValueError('Invalid `graphson_type` specified: {}'.format(graphson_type)) + + @classmethod + def deserialize(cls, graphson_type, value): + """ + Deserialize a `graphson_type` value to a python object. + + :param graphson_base_type: The graphson graphson_type. e.g. 'gx:Instant' + :param value: The graphson value to deserialize. + """ + return cls.get_deserializer(graphson_type).deserialize(value) + + +class GraphSON1Deserializer(_BaseGraphSONDeserializer): + """ + Deserialize graphson1 types to python objects. + """ + _TYPES = [UUIDTypeIO, BigDecimalTypeIO, InstantTypeIO, BlobTypeIO, ByteBufferTypeIO, + PointTypeIO, LineStringTypeIO, PolygonTypeIO, LocalDateTypeIO, + LocalTimeTypeIO, DurationTypeIO, InetTypeIO] + + _deserializers = { + t.graphson_type: t + for t in _TYPES + } + + @classmethod + def deserialize_date(cls, value): + return cls._deserializers[LocalDateTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_time(cls, value): + return cls._deserializers[LocalTimeTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_timestamp(cls, value): + return cls._deserializers[InstantTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_duration(cls, value): + return cls._deserializers[DurationTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_int(cls, value): + return int(value) + + deserialize_smallint = deserialize_int + + deserialize_varint = deserialize_int + + @classmethod + def deserialize_bigint(cls, value): + if six.PY3: + return cls.deserialize_int(value) + return long(value) + + @classmethod + def deserialize_double(cls, value): + return float(value) + + deserialize_float = deserialize_double + + @classmethod + def deserialize_uuid(cls, value): + return cls._deserializers[UUIDTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_decimal(cls, value): + return cls._deserializers[BigDecimalTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_blob(cls, value): + return cls._deserializers[ByteBufferTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_point(cls, value): + return cls._deserializers[PointTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_linestring(cls, value): + return cls._deserializers[LineStringTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_polygon(cls, value): + return cls._deserializers[PolygonTypeIO.graphson_type].deserialize(value) + + @classmethod + def deserialize_inet(cls, value): + return value + + @classmethod + def deserialize_boolean(cls, value): + return value + + +# TODO Remove in the next major +GraphSON1TypeDeserializer = GraphSON1Deserializer +GraphSON1TypeSerializer = GraphSON1Serializer + + +class GraphSON2Serializer(_BaseGraphSONSerializer): + TYPE_KEY = "@type" + VALUE_KEY = "@value" + + _serializers = GraphSON1Serializer.get_type_definitions() + + def serialize(self, value, writer=None): + """ + Serialize a type to GraphSON2. + + e.g {'@type': 'gx:Duration', '@value': 'P2DT4H'} + + :param value: The python object to serialize. + """ + serializer = self.get_serializer(value) + if not serializer: + raise ValueError("Unable to find a serializer for value of type: ".format(type(value))) + + val = serializer.serialize(value, writer or self) + if serializer is TypeWrapperTypeIO: + graphson_base_type = value.type_io.graphson_base_type + graphson_type = value.type_io.graphson_type + else: + graphson_base_type = serializer.graphson_base_type + graphson_type = serializer.graphson_type + + if graphson_base_type is None: + out = val + else: + out = {self.TYPE_KEY: graphson_type} + if val is not None: + out[self.VALUE_KEY] = val + + return out + + +GraphSON2Serializer.register(int, IntegerTypeIO) +if six.PY2: + GraphSON2Serializer.register(long, IntegerTypeIO) + + +class GraphSON2Deserializer(_BaseGraphSONDeserializer): + + _TYPES = GraphSON1Deserializer._TYPES + [ + Int16TypeIO, Int32TypeIO, Int64TypeIO, DoubleTypeIO, FloatTypeIO, + BigIntegerTypeIO, VertexTypeIO, VertexPropertyTypeIO, EdgeTypeIO, + PathTypeIO, PropertyTypeIO, TraversalMetricsTypeIO, MetricsTypeIO] + + _deserializers = { + t.graphson_type: t + for t in _TYPES + } + + +class GraphSON2Reader(object): + """ + GraphSON2 Reader that parse json and deserialize to python objects. + """ + + def __init__(self, context, extra_deserializer_map=None): + """ + :param extra_deserializer_map: map from GraphSON type tag to deserializer instance implementing `deserialize` + """ + self.context = context + self.deserializers = GraphSON2Deserializer.get_type_definitions() + if extra_deserializer_map: + self.deserializers.update(extra_deserializer_map) + + def read(self, json_data): + """ + Read and deserialize ``json_data``. + """ + return self.deserialize(json.loads(json_data)) + + def deserialize(self, obj): + """ + Deserialize GraphSON type-tagged dict values into objects mapped in self.deserializers + """ + if isinstance(obj, dict): + try: + des = self.deserializers[obj[GraphSON2Serializer.TYPE_KEY]] + return des.deserialize(obj[GraphSON2Serializer.VALUE_KEY], self) + except KeyError: + pass + # list and map are treated as normal json objs (could be isolated deserializers) + return {self.deserialize(k): self.deserialize(v) for k, v in six.iteritems(obj)} + elif isinstance(obj, list): + return [self.deserialize(o) for o in obj] + else: + return obj + + +class TypeIOWrapper(object): + """Used to force a graphson type during serialization""" + + type_io = None + value = None + + def __init__(self, type_io, value): + self.type_io = type_io + self.value = value + + +def _wrap_value(type_io, value): + return TypeIOWrapper(type_io, value) + + +to_bigint = partial(_wrap_value, Int64TypeIO) +to_int = partial(_wrap_value, Int32TypeIO) +to_smallint = partial(_wrap_value, Int16TypeIO) +to_double = partial(_wrap_value, DoubleTypeIO) +to_float = partial(_wrap_value, FloatTypeIO) + + +class GraphSON3Serializer(GraphSON2Serializer): + + _serializers = GraphSON2Serializer.get_type_definitions() + + context = None + """A dict of the serialization context""" + + def __init__(self, context): + self.context = context + self.user_types = None + + def definition(self, value): + serializer = self.get_serializer(value) + return serializer.definition(value, self) + + def get_serializer(self, value): + """Custom get_serializer to support UDT/Tuple""" + + serializer = super(GraphSON3Serializer, self).get_serializer(value) + is_namedtuple_udt = serializer is TupleTypeIO and hasattr(value, '_fields') + if not serializer or is_namedtuple_udt: + # Check if UDT + if self.user_types is None: + try: + user_types = self.context['cluster']._user_types[self.context['graph_name']] + self.user_types = dict(map(reversed, six.iteritems(user_types))) + except KeyError: + self.user_types = {} + + serializer = UserTypeIO if (is_namedtuple_udt or (type(value) in self.user_types)) else serializer + + return serializer + + +GraphSON3Serializer.register(dict, MapTypeIO) +GraphSON3Serializer.register(list, ListTypeIO) +GraphSON3Serializer.register(set, SetTypeIO) +GraphSON3Serializer.register(tuple, TupleTypeIO) +GraphSON3Serializer.register(Duration, DseDurationTypeIO) +GraphSON3Serializer.register(TypeIOWrapper, TypeWrapperTypeIO) + + +class GraphSON3Deserializer(GraphSON2Deserializer): + _TYPES = GraphSON2Deserializer._TYPES + [MapTypeIO, ListTypeIO, + SetTypeIO, TupleTypeIO, + UserTypeIO, DseDurationTypeIO, + TTypeIO, BulkSetTypeIO] + + _deserializers = {t.graphson_type: t for t in _TYPES} + + +class GraphSON3Reader(GraphSON2Reader): + """ + GraphSON3 Reader that parse json and deserialize to python objects. + """ + + def __init__(self, context, extra_deserializer_map=None): + """ + :param context: A dict of the context, mostly used as context for udt deserialization. + :param extra_deserializer_map: map from GraphSON type tag to deserializer instance implementing `deserialize` + """ + self.context = context + self.deserializers = GraphSON3Deserializer.get_type_definitions() + if extra_deserializer_map: + self.deserializers.update(extra_deserializer_map) diff --git a/cassandra/datastax/graph/query.py b/cassandra/datastax/graph/query.py new file mode 100644 index 0000000..7c0e265 --- /dev/null +++ b/cassandra/datastax/graph/query.py @@ -0,0 +1,332 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +from warnings import warn + +import six + +from cassandra import ConsistencyLevel +from cassandra.query import Statement, SimpleStatement +from cassandra.datastax.graph.types import Vertex, Edge, Path, VertexProperty +from cassandra.datastax.graph.graphson import GraphSON2Reader, GraphSON3Reader + + +__all__ = [ + 'GraphProtocol', 'GraphOptions', 'GraphStatement', 'SimpleGraphStatement', + 'single_object_row_factory', 'graph_result_row_factory', 'graph_object_row_factory', + 'graph_graphson2_row_factory', 'Result', 'graph_graphson3_row_factory' +] + +# (attr, description, server option) +_graph_options = ( + ('graph_name', 'name of the targeted graph.', 'graph-name'), + ('graph_source', 'choose the graph traversal source, configured on the server side.', 'graph-source'), + ('graph_language', 'the language used in the queries (default "gremlin-groovy")', 'graph-language'), + ('graph_protocol', 'the graph protocol that the server should use for query results (default "graphson-1-0")', 'graph-results'), + ('graph_read_consistency_level', '''read `cassandra.ConsistencyLevel `_ for graph queries (if distinct from session default). +Setting this overrides the native `Statement.consistency_level `_ for read operations from Cassandra persistence''', 'graph-read-consistency'), + ('graph_write_consistency_level', '''write `cassandra.ConsistencyLevel `_ for graph queries (if distinct from session default). +Setting this overrides the native `Statement.consistency_level `_ for write operations to Cassandra persistence.''', 'graph-write-consistency') +) +_graph_option_names = tuple(option[0] for option in _graph_options) + +# this is defined by the execution profile attribute, not in graph options +_request_timeout_key = 'request-timeout' + + +class GraphProtocol(object): + + GRAPHSON_1_0 = b'graphson-1.0' + """ + GraphSON1 + """ + + GRAPHSON_2_0 = b'graphson-2.0' + """ + GraphSON2 + """ + + GRAPHSON_3_0 = b'graphson-3.0' + """ + GraphSON3 + """ + + +class GraphOptions(object): + """ + Options for DSE Graph Query handler. + """ + # See _graph_options map above for notes on valid options + + DEFAULT_GRAPH_PROTOCOL = GraphProtocol.GRAPHSON_1_0 + DEFAULT_GRAPH_LANGUAGE = b'gremlin-groovy' + + def __init__(self, **kwargs): + self._graph_options = {} + kwargs.setdefault('graph_source', 'g') + kwargs.setdefault('graph_language', GraphOptions.DEFAULT_GRAPH_LANGUAGE) + for attr, value in six.iteritems(kwargs): + if attr not in _graph_option_names: + warn("Unknown keyword argument received for GraphOptions: {0}".format(attr)) + setattr(self, attr, value) + + def copy(self): + new_options = GraphOptions() + new_options._graph_options = self._graph_options.copy() + return new_options + + def update(self, options): + self._graph_options.update(options._graph_options) + + def get_options_map(self, other_options=None): + """ + Returns a map for these options updated with other options, + and mapped to graph payload types. + """ + options = self._graph_options.copy() + if other_options: + options.update(other_options._graph_options) + + # cls are special-cased so they can be enums in the API, and names in the protocol + for cl in ('graph-write-consistency', 'graph-read-consistency'): + cl_enum = options.get(cl) + if cl_enum is not None: + options[cl] = six.b(ConsistencyLevel.value_to_name[cl_enum]) + return options + + def set_source_default(self): + """ + Sets ``graph_source`` to the server-defined default traversal source ('default') + """ + self.graph_source = 'default' + + def set_source_analytics(self): + """ + Sets ``graph_source`` to the server-defined analytic traversal source ('a') + """ + self.graph_source = 'a' + + def set_source_graph(self): + """ + Sets ``graph_source`` to the server-defined graph traversal source ('g') + """ + self.graph_source = 'g' + + def set_graph_protocol(self, protocol): + """ + Sets ``graph_protocol`` as server graph results format (See :class:`cassandra.datastax.graph.GraphProtocol`) + """ + self.graph_protocol = protocol + + @property + def is_default_source(self): + return self.graph_source in (b'default', None) + + @property + def is_analytics_source(self): + """ + True if ``graph_source`` is set to the server-defined analytics traversal source ('a') + """ + return self.graph_source == b'a' + + @property + def is_graph_source(self): + """ + True if ``graph_source`` is set to the server-defined graph traversal source ('g') + """ + return self.graph_source == b'g' + + +for opt in _graph_options: + + def get(self, key=opt[2]): + return self._graph_options.get(key) + + def set(self, value, key=opt[2]): + if value is not None: + # normalize text here so it doesn't have to be done every time we get options map + if isinstance(value, six.text_type) and not isinstance(value, six.binary_type): + value = six.b(value) + self._graph_options[key] = value + else: + self._graph_options.pop(key, None) + + def delete(self, key=opt[2]): + self._graph_options.pop(key, None) + + setattr(GraphOptions, opt[0], property(get, set, delete, opt[1])) + + +class GraphStatement(Statement): + """ An abstract class representing a graph query.""" + + @property + def query(self): + raise NotImplementedError() + + def __str__(self): + return u''.format(self.query) + __repr__ = __str__ + + +class SimpleGraphStatement(GraphStatement, SimpleStatement): + """ + Simple graph statement for :meth:`.Session.execute_graph`. + Takes the same parameters as :class:`.SimpleStatement`. + """ + @property + def query(self): + return self._query_string + + +def single_object_row_factory(column_names, rows): + """ + returns the JSON string value of graph results + """ + return [row[0] for row in rows] + + +def graph_result_row_factory(column_names, rows): + """ + Returns a :class:`Result ` object that can load graph results and produce specific types. + The Result JSON is deserialized and unpacked from the top-level 'result' dict. + """ + return [Result(json.loads(row[0])['result']) for row in rows] + + +def graph_object_row_factory(column_names, rows): + """ + Like :func:`~.graph_result_row_factory`, except known element types (:class:`~.Vertex`, :class:`~.Edge`) are + converted to their simplified objects. Some low-level metadata is shed in this conversion. Unknown result types are + still returned as :class:`Result `. + """ + return _graph_object_sequence(json.loads(row[0])['result'] for row in rows) + + +def _graph_object_sequence(objects): + for o in objects: + res = Result(o) + if isinstance(o, dict): + typ = res.value.get('type') + if typ == 'vertex': + res = res.as_vertex() + elif typ == 'edge': + res = res.as_edge() + yield res + + +class _GraphSONContextRowFactory(object): + graphson_reader_class = None + graphson_reader_kwargs = None + + def __init__(self, cluster): + context = {'cluster': cluster} + kwargs = self.graphson_reader_kwargs or {} + self.graphson_reader = self.graphson_reader_class(context, **kwargs) + + def __call__(self, column_names, rows): + return [self.graphson_reader.read(row[0])['result'] for row in rows] + + +class _GraphSON2RowFactory(_GraphSONContextRowFactory): + """Row factory to deserialize GraphSON2 results.""" + graphson_reader_class = GraphSON2Reader + + +class _GraphSON3RowFactory(_GraphSONContextRowFactory): + """Row factory to deserialize GraphSON3 results.""" + graphson_reader_class = GraphSON3Reader + + +graph_graphson2_row_factory = _GraphSON2RowFactory +graph_graphson3_row_factory = _GraphSON3RowFactory + + +class Result(object): + """ + Represents deserialized graph results. + Property and item getters are provided for convenience. + """ + + value = None + """ + Deserialized value from the result + """ + + def __init__(self, value): + self.value = value + + def __getattr__(self, attr): + if not isinstance(self.value, dict): + raise ValueError("Value cannot be accessed as a dict") + + if attr in self.value: + return self.value[attr] + + raise AttributeError("Result has no top-level attribute %r" % (attr,)) + + def __getitem__(self, item): + if isinstance(self.value, dict) and isinstance(item, six.string_types): + return self.value[item] + elif isinstance(self.value, list) and isinstance(item, int): + return self.value[item] + else: + raise ValueError("Result cannot be indexed by %r" % (item,)) + + def __str__(self): + return str(self.value) + + def __repr__(self): + return "%s(%r)" % (Result.__name__, self.value) + + def __eq__(self, other): + return self.value == other.value + + def as_vertex(self): + """ + Return a :class:`Vertex` parsed from this result + + Raises TypeError if parsing fails (i.e. the result structure is not valid). + """ + try: + return Vertex(self.id, self.label, self.type, self.value.get('properties', {})) + except (AttributeError, ValueError, TypeError): + raise TypeError("Could not create Vertex from %r" % (self,)) + + def as_edge(self): + """ + Return a :class:`Edge` parsed from this result + + Raises TypeError if parsing fails (i.e. the result structure is not valid). + """ + try: + return Edge(self.id, self.label, self.type, self.value.get('properties', {}), + self.inV, self.inVLabel, self.outV, self.outVLabel) + except (AttributeError, ValueError, TypeError): + raise TypeError("Could not create Edge from %r" % (self,)) + + def as_path(self): + """ + Return a :class:`Path` parsed from this result + + Raises TypeError if parsing fails (i.e. the result structure is not valid). + """ + try: + return Path(self.labels, self.objects) + except (AttributeError, ValueError, TypeError): + raise TypeError("Could not create Path from %r" % (self,)) + + def as_vertex_property(self): + return VertexProperty(self.value.get('label'), self.value.get('value'), self.value.get('properties', {})) diff --git a/cassandra/datastax/graph/types.py b/cassandra/datastax/graph/types.py new file mode 100644 index 0000000..9817c99 --- /dev/null +++ b/cassandra/datastax/graph/types.py @@ -0,0 +1,210 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +__all__ = ['Element', 'Vertex', 'Edge', 'VertexProperty', 'Path', 'T'] + + +class Element(object): + + element_type = None + + _attrs = ('id', 'label', 'type', 'properties') + + def __init__(self, id, label, type, properties): + if type != self.element_type: + raise TypeError("Attempted to create %s from %s element", (type, self.element_type)) + + self.id = id + self.label = label + self.type = type + self.properties = self._extract_properties(properties) + + @staticmethod + def _extract_properties(properties): + return dict(properties) + + def __eq__(self, other): + return all(getattr(self, attr) == getattr(other, attr) for attr in self._attrs) + + def __str__(self): + return str(dict((k, getattr(self, k)) for k in self._attrs)) + + +class Vertex(Element): + """ + Represents a Vertex element from a graph query. + + Vertex ``properties`` are extracted into a ``dict`` of property names to list of :class:`~VertexProperty` (list + because they are always encoded that way, and sometimes have multiple cardinality; VertexProperty because sometimes + the properties themselves have property maps). + """ + + element_type = 'vertex' + + @staticmethod + def _extract_properties(properties): + # vertex properties are always encoded as a list, regardless of Cardinality + return dict((k, [VertexProperty(k, p['value'], p.get('properties')) for p in v]) for k, v in properties.items()) + + def __repr__(self): + properties = dict((name, [{'label': prop.label, 'value': prop.value, 'properties': prop.properties} for prop in prop_list]) + for name, prop_list in self.properties.items()) + return "%s(%r, %r, %r, %r)" % (self.__class__.__name__, + self.id, self.label, + self.type, properties) + + +class VertexProperty(object): + """ + Vertex properties have a top-level value and an optional ``dict`` of properties. + """ + + label = None + """ + label of the property + """ + + value = None + """ + Value of the property + """ + + properties = None + """ + dict of properties attached to the property + """ + + def __init__(self, label, value, properties=None): + self.label = label + self.value = value + self.properties = properties or {} + + def __eq__(self, other): + return isinstance(other, VertexProperty) and self.label == other.label and self.value == other.value and self.properties == other.properties + + def __repr__(self): + return "%s(%r, %r, %r)" % (self.__class__.__name__, self.label, self.value, self.properties) + + +class Edge(Element): + """ + Represents an Edge element from a graph query. + + Attributes match initializer parameters. + """ + + element_type = 'edge' + + _attrs = Element._attrs + ('inV', 'inVLabel', 'outV', 'outVLabel') + + def __init__(self, id, label, type, properties, + inV, inVLabel, outV, outVLabel): + super(Edge, self).__init__(id, label, type, properties) + self.inV = inV + self.inVLabel = inVLabel + self.outV = outV + self.outVLabel = outVLabel + + def __repr__(self): + return "%s(%r, %r, %r, %r, %r, %r, %r, %r)" %\ + (self.__class__.__name__, + self.id, self.label, + self.type, self.properties, + self.inV, self.inVLabel, + self.outV, self.outVLabel) + + +class Path(object): + """ + Represents a graph path. + + Labels list is taken verbatim from the results. + + Objects are either :class:`~.Result` or :class:`~.Vertex`/:class:`~.Edge` for recognized types + """ + + labels = None + """ + List of labels in the path + """ + + objects = None + """ + List of objects in the path + """ + + def __init__(self, labels, objects): + # TODO fix next major + # The Path class should not do any deserialization by itself. To fix in the next major. + from cassandra.datastax.graph.query import _graph_object_sequence + self.labels = labels + self.objects = list(_graph_object_sequence(objects)) + + def __eq__(self, other): + return self.labels == other.labels and self.objects == other.objects + + def __str__(self): + return str({'labels': self.labels, 'objects': self.objects}) + + def __repr__(self): + return "%s(%r, %r)" % (self.__class__.__name__, self.labels, [o.value for o in self.objects]) + + +class T(object): + """ + Represents a collection of tokens for more concise Traversal definitions. + """ + + name = None + val = None + + # class attributes + id = None + """ + """ + + key = None + """ + """ + label = None + """ + """ + value = None + """ + """ + + def __init__(self, name, val): + self.name = name + self.val = val + + def __str__(self): + return self.name + + def __repr__(self): + return "T.%s" % (self.name, ) + + +T.id = T("id", 1) +T.id_ = T("id_", 2) +T.key = T("key", 3) +T.label = T("label", 4) +T.value = T("value", 5) + +T.name_to_value = { + 'id': T.id, + 'id_': T.id_, + 'key': T.key, + 'label': T.label, + 'value': T.value +} diff --git a/tests/integration/advanced/__init__.py b/cassandra/datastax/insights/__init__.py similarity index 67% copy from tests/integration/advanced/__init__.py copy to cassandra/datastax/insights/__init__.py index 662f5b8..2c9ca17 100644 --- a/tests/integration/advanced/__init__.py +++ b/cassandra/datastax/insights/__init__.py @@ -1,23 +1,13 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License - -try: - import unittest2 as unittest -except ImportError: - import unittest # noqa - -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) +# limitations under the License. diff --git a/cassandra/datastax/insights/registry.py b/cassandra/datastax/insights/registry.py new file mode 100644 index 0000000..3dd1d25 --- /dev/null +++ b/cassandra/datastax/insights/registry.py @@ -0,0 +1,123 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import six +from collections import OrderedDict +from warnings import warn + +from cassandra.datastax.insights.util import namespace + +_NOT_SET = object() + + +def _default_serializer_for_object(obj, policy): + # the insights server expects an 'options' dict for policy + # objects, but not for other objects + if policy: + return {'type': obj.__class__.__name__, + 'namespace': namespace(obj.__class__), + 'options': {}} + else: + return {'type': obj.__class__.__name__, + 'namespace': namespace(obj.__class__)} + + +class InsightsSerializerRegistry(object): + + initialized = False + + def __init__(self, mapping_dict=None): + mapping_dict = mapping_dict or {} + class_order = self._class_topological_sort(mapping_dict) + self._mapping_dict = OrderedDict( + ((cls, mapping_dict[cls]) for cls in class_order) + ) + + def serialize(self, obj, policy=False, default=_NOT_SET, cls=None): + try: + return self._get_serializer(cls if cls is not None else obj.__class__)(obj) + except Exception: + if default is _NOT_SET: + result = _default_serializer_for_object(obj, policy) + else: + result = default + + return result + + def _get_serializer(self, cls): + try: + return self._mapping_dict[cls] + except KeyError: + for registered_cls, serializer in six.iteritems(self._mapping_dict): + if issubclass(cls, registered_cls): + return self._mapping_dict[registered_cls] + raise ValueError + + def register(self, cls, serializer): + self._mapping_dict[cls] = serializer + self._mapping_dict = OrderedDict( + ((cls, self._mapping_dict[cls]) + for cls in self._class_topological_sort(self._mapping_dict)) + ) + + def register_serializer_for(self, cls): + """ + Parameterized registration helper decorator. Given a class `cls`, + produces a function that registers the decorated function as a + serializer for it. + """ + def decorator(serializer): + self.register(cls, serializer) + return serializer + + return decorator + + @staticmethod + def _class_topological_sort(classes): + """ + A simple topological sort for classes. Takes an iterable of class objects + and returns a list A of those classes, ordered such that A[X] is never a + superclass of A[Y] for X < Y. + + This is an inefficient sort, but that's ok because classes are infrequently + registered. It's more important that this be maintainable than fast. + + We can't use `.sort()` or `sorted()` with a custom `key` -- those assume + a total ordering, which we don't have. + """ + unsorted, sorted_ = list(classes), [] + while unsorted: + head, tail = unsorted[0], unsorted[1:] + + # if head has no subclasses remaining, it can safely go in the list + if not any(issubclass(x, head) for x in tail): + sorted_.append(head) + else: + # move to the back -- head has to wait until all its subclasses + # are sorted into the list + tail.append(head) + + unsorted = tail + + # check that sort is valid + for i, head in enumerate(sorted_): + for after_head_value in sorted_[(i + 1):]: + if issubclass(after_head_value, head): + warn('Sorting classes produced an invalid ordering.\n' + 'In: {classes}\n' + 'Out: {sorted_}'.format(classes=classes, sorted_=sorted_)) + return sorted_ + + +insights_registry = InsightsSerializerRegistry() diff --git a/cassandra/datastax/insights/reporter.py b/cassandra/datastax/insights/reporter.py new file mode 100644 index 0000000..b05a88d --- /dev/null +++ b/cassandra/datastax/insights/reporter.py @@ -0,0 +1,222 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections import Counter +import datetime +import json +import logging +import multiprocessing +import random +import platform +import socket +import ssl +import sys +from threading import Event, Thread +import time +import six + +from cassandra.policies import HostDistance +from cassandra.util import ms_timestamp_from_datetime +from cassandra.datastax.insights.registry import insights_registry +from cassandra.datastax.insights.serializers import initialize_registry + +log = logging.getLogger(__name__) + + +class MonitorReporter(Thread): + + def __init__(self, interval_sec, session): + """ + takes an int indicating interval between requests, a function returning + the connection to be used, and the timeout per request + """ + # Thread is an old-style class so we can't super() + Thread.__init__(self, name='monitor_reporter') + + initialize_registry(insights_registry) + + self._interval, self._session = interval_sec, session + + self._shutdown_event = Event() + self.daemon = True + self.start() + + def run(self): + self._send_via_rpc(self._get_startup_data()) + + # introduce some jitter -- send up to 1/10 of _interval early + self._shutdown_event.wait(self._interval * random.uniform(.9, 1)) + + while not self._shutdown_event.is_set(): + start_time = time.time() + + self._send_via_rpc(self._get_status_data()) + + elapsed = time.time() - start_time + self._shutdown_event.wait(max(self._interval - elapsed, 0.01)) + + # TODO: redundant with ConnectionHeartbeat.ShutdownException + class ShutDownException(Exception): + pass + + def _send_via_rpc(self, data): + try: + self._session.execute( + "CALL InsightsRpc.reportInsight(%s)", (json.dumps(data),) + ) + log.debug('Insights RPC data: {}'.format(data)) + except Exception as e: + log.debug('Insights RPC send failed with {}'.format(e)) + log.debug('Insights RPC data: {}'.format(data)) + + def _get_status_data(self): + cc = self._session.cluster.control_connection + + connected_nodes = { + host.address: { + 'connections': state['open_count'], + 'inFlightQueries': state['in_flights'] + } + for (host, state) in self._session.get_pool_state().items() + } + + return { + 'metadata': { + # shared across drivers; never change + 'name': 'driver.status', + # format version + 'insightMappingId': 'v1', + 'insightType': 'EVENT', + # since epoch + 'timestamp': ms_timestamp_from_datetime(datetime.datetime.utcnow()), + 'tags': { + 'language': 'python' + } + }, + # // 'clientId', 'sessionId' and 'controlConnection' are mandatory + # // the rest of the properties are optional + 'data': { + # // 'clientId' must be the same as the one provided in the startup message + 'clientId': str(self._session.cluster.client_id), + # // 'sessionId' must be the same as the one provided in the startup message + 'sessionId': str(self._session.session_id), + 'controlConnection': cc._connection.host if cc._connection else None, + 'connectedNodes': connected_nodes + } + } + + def _get_startup_data(self): + cc = self._session.cluster.control_connection + try: + local_ipaddr = cc._connection._socket.getsockname()[0] + except Exception as e: + local_ipaddr = None + log.debug('Unable to get local socket addr from {}: {}'.format(cc._connection, e)) + hostname = socket.getfqdn() + + host_distances_counter = Counter( + self._session.cluster.profile_manager.distance(host) + for host in self._session.hosts + ) + host_distances_dict = { + 'local': host_distances_counter[HostDistance.LOCAL], + 'remote': host_distances_counter[HostDistance.REMOTE], + 'ignored': host_distances_counter[HostDistance.IGNORED] + } + + try: + compression_type = cc._connection._compression_type + except AttributeError: + compression_type = 'NONE' + + cert_validation = None + try: + if self._session.cluster.ssl_context: + if isinstance(self._session.cluster.ssl_context, ssl.SSLContext): + cert_validation = self._session.cluster.ssl_context.verify_mode == ssl.CERT_REQUIRED + else: # pyopenssl + from OpenSSL import SSL + cert_validation = self._session.cluster.ssl_context.get_verify_mode() != SSL.VERIFY_NONE + elif self._session.cluster.ssl_options: + cert_validation = self._session.cluster.ssl_options.get('cert_reqs') == ssl.CERT_REQUIRED + except Exception as e: + log.debug('Unable to get the cert validation: {}'.format(e)) + + uname_info = platform.uname() + + return { + 'metadata': { + 'name': 'driver.startup', + 'insightMappingId': 'v1', + 'insightType': 'EVENT', + 'timestamp': ms_timestamp_from_datetime(datetime.datetime.utcnow()), + 'tags': { + 'language': 'python' + }, + }, + 'data': { + 'driverName': 'DataStax Python Driver', + 'driverVersion': sys.modules['cassandra'].__version__, + 'clientId': str(self._session.cluster.client_id), + 'sessionId': str(self._session.session_id), + 'applicationName': self._session.cluster.application_name or 'python', + 'applicationNameWasGenerated': not self._session.cluster.application_name, + 'applicationVersion': self._session.cluster.application_version, + 'contactPoints': self._session.cluster._endpoint_map_for_insights, + 'dataCenters': list(set(h.datacenter for h in self._session.cluster.metadata.all_hosts() + if (h.datacenter and + self._session.cluster.profile_manager.distance(h) == HostDistance.LOCAL))), + 'initialControlConnection': cc._connection.host if cc._connection else None, + 'protocolVersion': self._session.cluster.protocol_version, + 'localAddress': local_ipaddr, + 'hostName': hostname, + 'executionProfiles': insights_registry.serialize(self._session.cluster.profile_manager), + 'configuredConnectionLength': host_distances_dict, + 'heartbeatInterval': self._session.cluster.idle_heartbeat_interval, + 'compression': compression_type.upper() if compression_type else 'NONE', + 'reconnectionPolicy': insights_registry.serialize(self._session.cluster.reconnection_policy), + 'sslConfigured': { + 'enabled': bool(self._session.cluster.ssl_options or self._session.cluster.ssl_context), + 'certValidation': cert_validation + }, + 'authProvider': { + 'type': (self._session.cluster.auth_provider.__class__.__name__ + if self._session.cluster.auth_provider else + None) + }, + 'otherOptions': { + }, + 'platformInfo': { + 'os': { + 'name': uname_info.system if six.PY3 else uname_info[0], + 'version': uname_info.release if six.PY3 else uname_info[2], + 'arch': uname_info.machine if six.PY3 else uname_info[4] + }, + 'cpus': { + 'length': multiprocessing.cpu_count(), + 'model': platform.processor() + }, + 'runtime': { + 'python': sys.version, + 'event_loop': self._session.cluster.connection_class.__name__ + } + }, + 'periodicStatusInterval': self._interval + } + } + + def stop(self): + log.debug("Shutting down Monitor Reporter") + self._shutdown_event.set() + self.join() diff --git a/cassandra/datastax/insights/serializers.py b/cassandra/datastax/insights/serializers.py new file mode 100644 index 0000000..aec4467 --- /dev/null +++ b/cassandra/datastax/insights/serializers.py @@ -0,0 +1,221 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import six + + +def initialize_registry(insights_registry): + # This will be called from the cluster module, so we put all this behavior + # in a function to avoid circular imports + + if insights_registry.initialized: + return False + + from cassandra import ConsistencyLevel + from cassandra.cluster import ( + ExecutionProfile, GraphExecutionProfile, + ProfileManager, ContinuousPagingOptions, + EXEC_PROFILE_DEFAULT, EXEC_PROFILE_GRAPH_DEFAULT, + EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT, + EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT, + _NOT_SET + ) + from cassandra.datastax.graph import GraphOptions + from cassandra.datastax.insights.registry import insights_registry + from cassandra.datastax.insights.util import namespace + from cassandra.policies import ( + RoundRobinPolicy, + DCAwareRoundRobinPolicy, + TokenAwarePolicy, + WhiteListRoundRobinPolicy, + HostFilterPolicy, + ConstantReconnectionPolicy, + ExponentialReconnectionPolicy, + RetryPolicy, + SpeculativeExecutionPolicy, + ConstantSpeculativeExecutionPolicy, + WrapperPolicy + ) + + import logging + + log = logging.getLogger(__name__) + + @insights_registry.register_serializer_for(RoundRobinPolicy) + def round_robin_policy_insights_serializer(policy): + return {'type': policy.__class__.__name__, + 'namespace': namespace(policy.__class__), + 'options': {}} + + @insights_registry.register_serializer_for(DCAwareRoundRobinPolicy) + def dc_aware_round_robin_policy_insights_serializer(policy): + return {'type': policy.__class__.__name__, + 'namespace': namespace(policy.__class__), + 'options': {'local_dc': policy.local_dc, + 'used_hosts_per_remote_dc': policy.used_hosts_per_remote_dc} + } + + @insights_registry.register_serializer_for(TokenAwarePolicy) + def token_aware_policy_insights_serializer(policy): + return {'type': policy.__class__.__name__, + 'namespace': namespace(policy.__class__), + 'options': {'child_policy': insights_registry.serialize(policy._child_policy, + policy=True), + 'shuffle_replicas': policy.shuffle_replicas} + } + + @insights_registry.register_serializer_for(WhiteListRoundRobinPolicy) + def whitelist_round_robin_policy_insights_serializer(policy): + return {'type': policy.__class__.__name__, + 'namespace': namespace(policy.__class__), + 'options': {'allowed_hosts': policy._allowed_hosts} + } + + @insights_registry.register_serializer_for(HostFilterPolicy) + def host_filter_policy_insights_serializer(policy): + return { + 'type': policy.__class__.__name__, + 'namespace': namespace(policy.__class__), + 'options': {'child_policy': insights_registry.serialize(policy._child_policy, + policy=True), + 'predicate': policy.predicate.__name__} + } + + @insights_registry.register_serializer_for(ConstantReconnectionPolicy) + def constant_reconnection_policy_insights_serializer(policy): + return {'type': policy.__class__.__name__, + 'namespace': namespace(policy.__class__), + 'options': {'delay': policy.delay, + 'max_attempts': policy.max_attempts} + } + + @insights_registry.register_serializer_for(ExponentialReconnectionPolicy) + def exponential_reconnection_policy_insights_serializer(policy): + return {'type': policy.__class__.__name__, + 'namespace': namespace(policy.__class__), + 'options': {'base_delay': policy.base_delay, + 'max_delay': policy.max_delay, + 'max_attempts': policy.max_attempts} + } + + @insights_registry.register_serializer_for(RetryPolicy) + def retry_policy_insights_serializer(policy): + return {'type': policy.__class__.__name__, + 'namespace': namespace(policy.__class__), + 'options': {}} + + @insights_registry.register_serializer_for(SpeculativeExecutionPolicy) + def speculative_execution_policy_insights_serializer(policy): + return {'type': policy.__class__.__name__, + 'namespace': namespace(policy.__class__), + 'options': {}} + + @insights_registry.register_serializer_for(ConstantSpeculativeExecutionPolicy) + def constant_speculative_execution_policy_insights_serializer(policy): + return {'type': policy.__class__.__name__, + 'namespace': namespace(policy.__class__), + 'options': {'delay': policy.delay, + 'max_attempts': policy.max_attempts} + } + + @insights_registry.register_serializer_for(WrapperPolicy) + def wrapper_policy_insights_serializer(policy): + return {'type': policy.__class__.__name__, + 'namespace': namespace(policy.__class__), + 'options': { + 'child_policy': insights_registry.serialize(policy._child_policy, + policy=True) + }} + + @insights_registry.register_serializer_for(ExecutionProfile) + def execution_profile_insights_serializer(profile): + return { + 'loadBalancing': insights_registry.serialize(profile.load_balancing_policy, + policy=True), + 'retry': insights_registry.serialize(profile.retry_policy, + policy=True), + 'readTimeout': profile.request_timeout, + 'consistency': ConsistencyLevel.value_to_name.get(profile.consistency_level, None), + 'serialConsistency': ConsistencyLevel.value_to_name.get(profile.serial_consistency_level, None), + 'continuousPagingOptions': (insights_registry.serialize(profile.continuous_paging_options) + if (profile.continuous_paging_options is not None and + profile.continuous_paging_options is not _NOT_SET) else + None), + 'speculativeExecution': insights_registry.serialize(profile.speculative_execution_policy), + 'graphOptions': None + } + + @insights_registry.register_serializer_for(GraphExecutionProfile) + def graph_execution_profile_insights_serializer(profile): + rv = insights_registry.serialize(profile, cls=ExecutionProfile) + rv['graphOptions'] = insights_registry.serialize(profile.graph_options) + return rv + + _EXEC_PROFILE_DEFAULT_KEYS = (EXEC_PROFILE_DEFAULT, + EXEC_PROFILE_GRAPH_DEFAULT, + EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT, + EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT) + + @insights_registry.register_serializer_for(ProfileManager) + def profile_manager_insights_serializer(manager): + defaults = { + # Insights's expected default + 'default': insights_registry.serialize(manager.profiles[EXEC_PROFILE_DEFAULT]), + # remaining named defaults for driver's defaults, including duplicated default + 'EXEC_PROFILE_DEFAULT': insights_registry.serialize(manager.profiles[EXEC_PROFILE_DEFAULT]), + 'EXEC_PROFILE_GRAPH_DEFAULT': insights_registry.serialize(manager.profiles[EXEC_PROFILE_GRAPH_DEFAULT]), + 'EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT': insights_registry.serialize( + manager.profiles[EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT] + ), + 'EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT': insights_registry.serialize( + manager.profiles[EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT] + ) + } + other = { + key: insights_registry.serialize(value) + for key, value in manager.profiles.items() + if key not in _EXEC_PROFILE_DEFAULT_KEYS + } + overlapping_keys = set(defaults) & set(other) + if overlapping_keys: + log.debug('The following key names overlap default key sentinel keys ' + 'and these non-default EPs will not be displayed in Insights ' + ': {}'.format(list(overlapping_keys))) + + other.update(defaults) + return other + + @insights_registry.register_serializer_for(GraphOptions) + def graph_options_insights_serializer(options): + rv = { + 'source': options.graph_source, + 'language': options.graph_language, + 'graphProtocol': options.graph_protocol + } + updates = {k: v.decode('utf-8') for k, v in six.iteritems(rv) + if isinstance(v, six.binary_type)} + rv.update(updates) + return rv + + @insights_registry.register_serializer_for(ContinuousPagingOptions) + def continuous_paging_options_insights_serializer(paging_options): + return { + 'page_unit': paging_options.page_unit, + 'max_pages': paging_options.max_pages, + 'max_pages_per_second': paging_options.max_pages_per_second, + 'max_queue_size': paging_options.max_queue_size + } + + insights_registry.initialized = True + return True diff --git a/cassandra/datastax/insights/util.py b/cassandra/datastax/insights/util.py new file mode 100644 index 0000000..a483b3f --- /dev/null +++ b/cassandra/datastax/insights/util.py @@ -0,0 +1,75 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import traceback +from warnings import warn + +from cassandra.util import Version + + +DSE_60 = Version('6.0.0') +DSE_51_MIN_SUPPORTED = Version('5.1.13') +DSE_60_MIN_SUPPORTED = Version('6.0.5') + + +log = logging.getLogger(__name__) + + +def namespace(cls): + """ + Best-effort method for getting the namespace in which a class is defined. + """ + try: + # __module__ can be None + module = cls.__module__ or '' + except Exception: + warn("Unable to obtain namespace for {cls} for Insights, returning ''. " + "Exception: \n{e}".format(e=traceback.format_exc(), cls=cls)) + module = '' + + module_internal_namespace = _module_internal_namespace_or_emtpy_string(cls) + if module_internal_namespace: + return '.'.join((module, module_internal_namespace)) + return module + + +def _module_internal_namespace_or_emtpy_string(cls): + """ + Best-effort method for getting the module-internal namespace in which a + class is defined -- i.e. the namespace _inside_ the module. + """ + try: + qualname = cls.__qualname__ + except AttributeError: + return '' + + return '.'.join( + # the last segment is the name of the class -- use everything else + qualname.split('.')[:-1] + ) + + +def version_supports_insights(dse_version): + if dse_version: + try: + dse_version = Version(dse_version) + return (DSE_51_MIN_SUPPORTED <= dse_version < DSE_60 + or + DSE_60_MIN_SUPPORTED <= dse_version) + except Exception: + warn("Unable to check version {v} for Insights compatibility, returning False. " + "Exception: \n{e}".format(e=traceback.format_exc(), v=dse_version)) + + return False diff --git a/cassandra/encoder.py b/cassandra/encoder.py index 00f7bf1..f2c3f8d 100644 --- a/cassandra/encoder.py +++ b/cassandra/encoder.py @@ -1,243 +1,249 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ These functions are used to convert Python objects into CQL strings. When non-prepared statements are executed, these encoder functions are called on each query parameter. """ import logging log = logging.getLogger(__name__) from binascii import hexlify import calendar import datetime import math import sys import types from uuid import UUID import six +from cassandra.util import (OrderedDict, OrderedMap, OrderedMapSerializedKey, + sortedset, Time, Date, Point, LineString, Polygon) + if six.PY3: import ipaddress -from cassandra.util import (OrderedDict, OrderedMap, OrderedMapSerializedKey, - sortedset, Time, Date) - if six.PY3: long = int def cql_quote(term): # The ordering of this method is important for the result of this method to # be a native str type (for both Python 2 and 3) if isinstance(term, str): return "'%s'" % str(term).replace("'", "''") # This branch of the if statement will only be used by Python 2 to catch # unicode strings, text_type is used to prevent type errors with Python 3. elif isinstance(term, six.text_type): return "'%s'" % term.encode('utf8').replace("'", "''") else: return str(term) class ValueSequence(list): pass class Encoder(object): """ A container for mapping python types to CQL string literals when working with non-prepared statements. The type :attr:`~.Encoder.mapping` can be directly customized by users. """ mapping = None """ A map of python types to encoder functions. """ def __init__(self): self.mapping = { float: self.cql_encode_float, bytearray: self.cql_encode_bytes, str: self.cql_encode_str, int: self.cql_encode_object, UUID: self.cql_encode_object, datetime.datetime: self.cql_encode_datetime, datetime.date: self.cql_encode_date, datetime.time: self.cql_encode_time, Date: self.cql_encode_date_ext, Time: self.cql_encode_time, dict: self.cql_encode_map_collection, OrderedDict: self.cql_encode_map_collection, OrderedMap: self.cql_encode_map_collection, OrderedMapSerializedKey: self.cql_encode_map_collection, list: self.cql_encode_list_collection, tuple: self.cql_encode_list_collection, # TODO: change to tuple in next major set: self.cql_encode_set_collection, sortedset: self.cql_encode_set_collection, frozenset: self.cql_encode_set_collection, types.GeneratorType: self.cql_encode_list_collection, - ValueSequence: self.cql_encode_sequence + ValueSequence: self.cql_encode_sequence, + Point: self.cql_encode_str_quoted, + LineString: self.cql_encode_str_quoted, + Polygon: self.cql_encode_str_quoted } if six.PY2: self.mapping.update({ unicode: self.cql_encode_unicode, buffer: self.cql_encode_bytes, long: self.cql_encode_object, types.NoneType: self.cql_encode_none, }) else: self.mapping.update({ memoryview: self.cql_encode_bytes, bytes: self.cql_encode_bytes, type(None): self.cql_encode_none, ipaddress.IPv4Address: self.cql_encode_ipaddress, ipaddress.IPv6Address: self.cql_encode_ipaddress }) def cql_encode_none(self, val): """ Converts :const:`None` to the string 'NULL'. """ return 'NULL' def cql_encode_unicode(self, val): """ Converts :class:`unicode` objects to UTF-8 encoded strings with quote escaping. """ return cql_quote(val.encode('utf-8')) def cql_encode_str(self, val): """ Escapes quotes in :class:`str` objects. """ return cql_quote(val) + def cql_encode_str_quoted(self, val): + return "'%s'" % val + if six.PY3: def cql_encode_bytes(self, val): return (b'0x' + hexlify(val)).decode('utf-8') elif sys.version_info >= (2, 7): def cql_encode_bytes(self, val): # noqa return b'0x' + hexlify(val) else: # python 2.6 requires string or read-only buffer for hexlify def cql_encode_bytes(self, val): # noqa return b'0x' + hexlify(buffer(val)) def cql_encode_object(self, val): """ Default encoder for all objects that do not have a specific encoder function registered. This function simply calls :meth:`str()` on the object. """ return str(val) def cql_encode_float(self, val): """ Encode floats using repr to preserve precision """ if math.isinf(val): return 'Infinity' if val > 0 else '-Infinity' elif math.isnan(val): return 'NaN' else: return repr(val) def cql_encode_datetime(self, val): """ Converts a :class:`datetime.datetime` object to a (string) integer timestamp with millisecond precision. """ timestamp = calendar.timegm(val.utctimetuple()) return str(long(timestamp * 1e3 + getattr(val, 'microsecond', 0) / 1e3)) def cql_encode_date(self, val): """ Converts a :class:`datetime.date` object to a string with format ``YYYY-MM-DD``. """ return "'%s'" % val.strftime('%Y-%m-%d') def cql_encode_time(self, val): """ Converts a :class:`cassandra.util.Time` object to a string with format ``HH:MM:SS.mmmuuunnn``. """ return "'%s'" % val def cql_encode_date_ext(self, val): """ Encodes a :class:`cassandra.util.Date` object as an integer """ # using the int form in case the Date exceeds datetime.[MIN|MAX]YEAR return str(val.days_from_epoch + 2 ** 31) def cql_encode_sequence(self, val): """ Converts a sequence to a string of the form ``(item1, item2, ...)``. This is suitable for ``IN`` value lists. """ return '(%s)' % ', '.join(self.mapping.get(type(v), self.cql_encode_object)(v) for v in val) cql_encode_tuple = cql_encode_sequence """ Converts a sequence to a string of the form ``(item1, item2, ...)``. This is suitable for ``tuple`` type columns. """ def cql_encode_map_collection(self, val): """ Converts a dict into a string of the form ``{key1: val1, key2: val2, ...}``. This is suitable for ``map`` type columns. """ return '{%s}' % ', '.join('%s: %s' % ( self.mapping.get(type(k), self.cql_encode_object)(k), self.mapping.get(type(v), self.cql_encode_object)(v) ) for k, v in six.iteritems(val)) def cql_encode_list_collection(self, val): """ Converts a sequence to a string of the form ``[item1, item2, ...]``. This is suitable for ``list`` type columns. """ return '[%s]' % ', '.join(self.mapping.get(type(v), self.cql_encode_object)(v) for v in val) def cql_encode_set_collection(self, val): """ Converts a sequence to a string of the form ``{item1, item2, ...}``. This is suitable for ``set`` type columns. """ return '{%s}' % ', '.join(self.mapping.get(type(v), self.cql_encode_object)(v) for v in val) def cql_encode_all_types(self, val, as_text_type=False): """ Converts any type into a CQL string, defaulting to ``cql_encode_object`` if :attr:`~Encoder.mapping` does not contain an entry for the type. """ encoded = self.mapping.get(type(val), self.cql_encode_object)(val) if as_text_type and not isinstance(encoded, six.text_type): return encoded.decode('utf-8') return encoded if six.PY3: def cql_encode_ipaddress(self, val): """ Converts an ipaddress (IPV4Address, IPV6Address) to a CQL string. This is suitable for ``inet`` type columns. """ return "'%s'" % val.compressed diff --git a/tests/integration/advanced/__init__.py b/cassandra/graph/__init__.py similarity index 67% copy from tests/integration/advanced/__init__.py copy to cassandra/graph/__init__.py index 662f5b8..51bd1de 100644 --- a/tests/integration/advanced/__init__.py +++ b/cassandra/graph/__init__.py @@ -1,23 +1,16 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License +# limitations under the License. -try: - import unittest2 as unittest -except ImportError: - import unittest # noqa - -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) +# This is only for backward compatibility when migrating from dse-driver. +from cassandra.datastax.graph import * \ No newline at end of file diff --git a/tests/integration/advanced/__init__.py b/cassandra/graph/graphson.py similarity index 67% copy from tests/integration/advanced/__init__.py copy to cassandra/graph/graphson.py index 662f5b8..d37c172 100644 --- a/tests/integration/advanced/__init__.py +++ b/cassandra/graph/graphson.py @@ -1,23 +1,16 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License +# limitations under the License. -try: - import unittest2 as unittest -except ImportError: - import unittest # noqa - -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) +# This is only for backward compatibility when migrating from dse-driver. +from cassandra.datastax.graph.graphson import * diff --git a/tests/integration/advanced/__init__.py b/cassandra/graph/query.py similarity index 67% copy from tests/integration/advanced/__init__.py copy to cassandra/graph/query.py index 662f5b8..50eef72 100644 --- a/tests/integration/advanced/__init__.py +++ b/cassandra/graph/query.py @@ -1,23 +1,16 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License +# limitations under the License. -try: - import unittest2 as unittest -except ImportError: - import unittest # noqa - -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) +# This is only for backward compatibility when migrating from dse-driver. +from cassandra.datastax.graph.query import * diff --git a/tests/integration/advanced/__init__.py b/cassandra/graph/types.py similarity index 67% copy from tests/integration/advanced/__init__.py copy to cassandra/graph/types.py index 662f5b8..c8b613f 100644 --- a/tests/integration/advanced/__init__.py +++ b/cassandra/graph/types.py @@ -1,23 +1,16 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License +# limitations under the License. -try: - import unittest2 as unittest -except ImportError: - import unittest # noqa - -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) +# This is only for backward compatibility when migrating from dse-driver. +from cassandra.datastax.graph.types import * diff --git a/cassandra/io/asyncioreactor.py b/cassandra/io/asyncioreactor.py index b386388..7cb0444 100644 --- a/cassandra/io/asyncioreactor.py +++ b/cassandra/io/asyncioreactor.py @@ -1,215 +1,225 @@ from cassandra.connection import Connection, ConnectionShutdown import asyncio import logging import os import socket import ssl from threading import Lock, Thread, get_ident log = logging.getLogger(__name__) # This module uses ``yield from`` and ``@asyncio.coroutine`` over ``await`` and # ``async def`` for pre-Python-3.5 compatibility, so keep in mind that the # managed coroutines are generator-based, not native coroutines. See PEP 492: # https://www.python.org/dev/peps/pep-0492/#coroutine-objects try: asyncio.run_coroutine_threadsafe except AttributeError: raise ImportError( 'Cannot use asyncioreactor without access to ' 'asyncio.run_coroutine_threadsafe (added in 3.4.6 and 3.5.1)' ) class AsyncioTimer(object): """ An ``asyncioreactor``-specific Timer. Similar to :class:`.connection.Timer, but with a slightly different API due to limitations in the underlying ``call_later`` interface. Not meant to be used with a :class:`.connection.TimerManager`. """ @property def end(self): raise NotImplementedError('{} is not compatible with TimerManager and ' 'does not implement .end()') def __init__(self, timeout, callback, loop): delayed = self._call_delayed_coro(timeout=timeout, callback=callback, loop=loop) self._handle = asyncio.run_coroutine_threadsafe(delayed, loop=loop) @staticmethod @asyncio.coroutine def _call_delayed_coro(timeout, callback, loop): yield from asyncio.sleep(timeout, loop=loop) return callback() def __lt__(self, other): try: return self._handle < other._handle except AttributeError: raise NotImplemented def cancel(self): self._handle.cancel() def finish(self): # connection.Timer method not implemented here because we can't inspect # the Handle returned from call_later raise NotImplementedError('{} is not compatible with TimerManager and ' 'does not implement .finish()') class AsyncioConnection(Connection): """ An experimental implementation of :class:`.Connection` that uses the ``asyncio`` module in the Python standard library for its event loop. Note that it requires ``asyncio`` features that were only introduced in the 3.4 line in 3.4.6, and in the 3.5 line in 3.5.1. """ _loop = None _pid = os.getpid() _lock = Lock() _loop_thread = None _write_queue = None + _write_queue_lock = None def __init__(self, *args, **kwargs): Connection.__init__(self, *args, **kwargs) self._connect_socket() self._socket.setblocking(0) self._write_queue = asyncio.Queue(loop=self._loop) + self._write_queue_lock = asyncio.Lock(loop=self._loop) # see initialize_reactor -- loop is running in a separate thread, so we # have to use a threadsafe call self._read_watcher = asyncio.run_coroutine_threadsafe( self.handle_read(), loop=self._loop ) self._write_watcher = asyncio.run_coroutine_threadsafe( self.handle_write(), loop=self._loop ) self._send_options_message() @classmethod def initialize_reactor(cls): with cls._lock: if cls._pid != os.getpid(): cls._loop = None if cls._loop is None: cls._loop = asyncio.new_event_loop() asyncio.set_event_loop(cls._loop) if not cls._loop_thread: # daemonize so the loop will be shut down on interpreter # shutdown cls._loop_thread = Thread(target=cls._loop.run_forever, daemon=True, name="asyncio_thread") cls._loop_thread.start() @classmethod def create_timer(cls, timeout, callback): return AsyncioTimer(timeout, callback, loop=cls._loop) def close(self): with self.lock: if self.is_closed: return self.is_closed = True # close from the loop thread to avoid races when removing file # descriptors asyncio.run_coroutine_threadsafe( self._close(), loop=self._loop ) @asyncio.coroutine def _close(self): log.debug("Closing connection (%s) to %s" % (id(self), self.endpoint)) if self._write_watcher: self._write_watcher.cancel() if self._read_watcher: self._read_watcher.cancel() if self._socket: self._loop.remove_writer(self._socket.fileno()) self._loop.remove_reader(self._socket.fileno()) self._socket.close() log.debug("Closed socket to %s" % (self.endpoint,)) if not self.is_defunct: self.error_all_requests( ConnectionShutdown("Connection to %s was closed" % self.endpoint)) # don't leave in-progress operations hanging self.connected_event.set() def push(self, data): buff_size = self.out_buffer_size if len(data) > buff_size: + chunks = [] for i in range(0, len(data), buff_size): - self._push_chunk(data[i:i + buff_size]) + chunks.append(data[i:i + buff_size]) else: - self._push_chunk(data) + chunks = [data] - def _push_chunk(self, chunk): if self._loop_thread.ident != get_ident(): asyncio.run_coroutine_threadsafe( - self._write_queue.put(chunk), + self._push_msg(chunks), loop=self._loop ) else: # avoid races/hangs by just scheduling this, not using threadsafe - self._loop.create_task(self._write_queue.put(chunk)) + self._loop.create_task(self._push_msg(chunks)) + + @asyncio.coroutine + def _push_msg(self, chunks): + # This lock ensures all chunks of a message are sequential in the Queue + with (yield from self._write_queue_lock): + for chunk in chunks: + self._write_queue.put_nowait(chunk) + @asyncio.coroutine def handle_write(self): while True: try: next_msg = yield from self._write_queue.get() if next_msg: yield from self._loop.sock_sendall(self._socket, next_msg) except socket.error as err: log.debug("Exception in send for %s: %s", self, err) self.defunct(err) return except asyncio.CancelledError: return @asyncio.coroutine def handle_read(self): while True: try: buf = yield from self._loop.sock_recv(self._socket, self.in_buffer_size) self._iobuf.write(buf) # sock_recv expects EWOULDBLOCK if socket provides no data, but # nonblocking ssl sockets raise these instead, so we handle them # ourselves by yielding to the event loop, where the socket will # get the reading/writing it "wants" before retrying except (ssl.SSLWantWriteError, ssl.SSLWantReadError): yield continue except socket.error as err: log.debug("Exception during socket recv for %s: %s", self, err) self.defunct(err) return # leave the read loop except asyncio.CancelledError: return if buf and self._iobuf.tell(): self.process_io_buffer() else: log.debug("Connection %s closed by server", self) self.close() return diff --git a/cassandra/io/asyncorereactor.py b/cassandra/io/asyncorereactor.py index d3dd0cf..681552e 100644 --- a/cassandra/io/asyncorereactor.py +++ b/cassandra/io/asyncorereactor.py @@ -1,464 +1,467 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import atexit from collections import deque from functools import partial import logging import os import socket import sys from threading import Lock, Thread, Event import time import weakref import sys +import ssl from six.moves import range try: from weakref import WeakSet except ImportError: from cassandra.util import WeakSet # noqa import asyncore -try: - import ssl -except ImportError: - ssl = None # NOQA - from cassandra.connection import Connection, ConnectionShutdown, NONBLOCKING, Timer, TimerManager + log = logging.getLogger(__name__) _dispatcher_map = {} def _cleanup(loop): if loop: loop._cleanup() class WaitableTimer(Timer): def __init__(self, timeout, callback): Timer.__init__(self, timeout, callback) self.callback = callback self.event = Event() self.final_exception = None def finish(self, time_now): try: finished = Timer.finish(self, time_now) if finished: self.event.set() return True return False except Exception as e: self.final_exception = e self.event.set() return True def wait(self, timeout=None): self.event.wait(timeout) if self.final_exception: raise self.final_exception class _PipeWrapper(object): def __init__(self, fd): self.fd = fd def fileno(self): return self.fd def close(self): os.close(self.fd) def getsockopt(self, level, optname, buflen=None): # act like an unerrored socket for the asyncore error handling if level == socket.SOL_SOCKET and optname == socket.SO_ERROR and not buflen: return 0 raise NotImplementedError() class _AsyncoreDispatcher(asyncore.dispatcher): def __init__(self, socket): asyncore.dispatcher.__init__(self, map=_dispatcher_map) # inject after to avoid base class validation self.set_socket(socket) self._notified = False def writable(self): return False def validate(self): assert not self._notified self.notify_loop() assert self._notified self.loop(0.1) assert not self._notified def loop(self, timeout): asyncore.loop(timeout=timeout, use_poll=True, map=_dispatcher_map, count=1) class _AsyncorePipeDispatcher(_AsyncoreDispatcher): def __init__(self): self.read_fd, self.write_fd = os.pipe() _AsyncoreDispatcher.__init__(self, _PipeWrapper(self.read_fd)) def writable(self): return False def handle_read(self): while len(os.read(self.read_fd, 4096)) == 4096: pass self._notified = False def notify_loop(self): if not self._notified: self._notified = True os.write(self.write_fd, b'x') class _AsyncoreUDPDispatcher(_AsyncoreDispatcher): """ Experimental alternate dispatcher for avoiding busy wait in the asyncore loop. It is not used by default because it relies on local port binding. Port scanning is not implemented, so multiple clients on one host will collide. This address would need to be set per instance, or this could be specialized to scan until an address is found. To use:: from cassandra.io.asyncorereactor import _AsyncoreUDPDispatcher, AsyncoreLoop AsyncoreLoop._loop_dispatch_class = _AsyncoreUDPDispatcher """ bind_address = ('localhost', 10000) def __init__(self): self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self._socket.bind(self.bind_address) self._socket.setblocking(0) _AsyncoreDispatcher.__init__(self, self._socket) def handle_read(self): try: d = self._socket.recvfrom(1) while d and d[1]: d = self._socket.recvfrom(1) except socket.error as e: pass self._notified = False def notify_loop(self): if not self._notified: self._notified = True self._socket.sendto(b'', self.bind_address) def loop(self, timeout): asyncore.loop(timeout=timeout, use_poll=False, map=_dispatcher_map, count=1) class _BusyWaitDispatcher(object): max_write_latency = 0.001 """ Timeout pushed down to asyncore select/poll. Dictates the amount of time it will sleep before coming back to check if anything is writable. """ def notify_loop(self): pass def loop(self, timeout): if not _dispatcher_map: time.sleep(0.005) count = timeout // self.max_write_latency asyncore.loop(timeout=self.max_write_latency, use_poll=True, map=_dispatcher_map, count=count) def validate(self): pass def close(self): pass class AsyncoreLoop(object): timer_resolution = 0.1 # used as the max interval to be in the io loop before returning to service timeouts _loop_dispatch_class = _AsyncorePipeDispatcher if os.name != 'nt' else _BusyWaitDispatcher def __init__(self): self._pid = os.getpid() self._loop_lock = Lock() self._started = False self._shutdown = False self._thread = None self._timers = TimerManager() try: dispatcher = self._loop_dispatch_class() dispatcher.validate() log.debug("Validated loop dispatch with %s", self._loop_dispatch_class) except Exception: log.exception("Failed validating loop dispatch with %s. Using busy wait execution instead.", self._loop_dispatch_class) dispatcher.close() dispatcher = _BusyWaitDispatcher() self._loop_dispatcher = dispatcher def maybe_start(self): should_start = False did_acquire = False try: did_acquire = self._loop_lock.acquire(False) if did_acquire and not self._started: self._started = True should_start = True finally: if did_acquire: self._loop_lock.release() if should_start: self._thread = Thread(target=self._run_loop, name="asyncore_cassandra_driver_event_loop") self._thread.daemon = True self._thread.start() def wake_loop(self): self._loop_dispatcher.notify_loop() def _run_loop(self): log.debug("Starting asyncore event loop") with self._loop_lock: while not self._shutdown: try: self._loop_dispatcher.loop(self.timer_resolution) self._timers.service_timeouts() except Exception: - log.debug("Asyncore event loop stopped unexepectedly", exc_info=True) + try: + log.debug("Asyncore event loop stopped unexpectedly", exc_info=True) + except Exception: + # TODO: Remove when Python 2 support is removed + # PYTHON-1266. If our logger has disappeared, there's nothing we + # can do, so just log nothing. + pass break self._started = False log.debug("Asyncore event loop ended") def add_timer(self, timer): self._timers.add_timer(timer) # This function is called from a different thread than the event loop # thread, so for this call to be thread safe, we must wake up the loop # in case it's stuck at a select self.wake_loop() def _cleanup(self): global _dispatcher_map self._shutdown = True if not self._thread: return log.debug("Waiting for event loop thread to join...") self._thread.join(timeout=1.0) if self._thread.is_alive(): log.warning( "Event loop thread could not be joined, so shutdown may not be clean. " "Please call Cluster.shutdown() to avoid this.") log.debug("Event loop thread was joined") # Ensure all connections are closed and in-flight requests cancelled for conn in tuple(_dispatcher_map.values()): if conn is not self._loop_dispatcher: conn.close() self._timers.service_timeouts() # Once all the connections are closed, close the dispatcher self._loop_dispatcher.close() log.debug("Dispatchers were closed") _global_loop = None atexit.register(partial(_cleanup, _global_loop)) class AsyncoreConnection(Connection, asyncore.dispatcher): """ An implementation of :class:`.Connection` that uses the ``asyncore`` module in the Python standard library for its event loop. """ _writable = False _readable = False @classmethod def initialize_reactor(cls): global _global_loop if not _global_loop: _global_loop = AsyncoreLoop() else: current_pid = os.getpid() if _global_loop._pid != current_pid: log.debug("Detected fork, clearing and reinitializing reactor state") cls.handle_fork() _global_loop = AsyncoreLoop() @classmethod def handle_fork(cls): global _dispatcher_map, _global_loop _dispatcher_map = {} if _global_loop: _global_loop._cleanup() _global_loop = None @classmethod def create_timer(cls, timeout, callback): timer = Timer(timeout, callback) _global_loop.add_timer(timer) return timer def __init__(self, *args, **kwargs): Connection.__init__(self, *args, **kwargs) self.deque = deque() self.deque_lock = Lock() self._connect_socket() # start the event loop if needed _global_loop.maybe_start() init_handler = WaitableTimer( timeout=0, callback=partial(asyncore.dispatcher.__init__, self, self._socket, _dispatcher_map) ) _global_loop.add_timer(init_handler) init_handler.wait(kwargs["connect_timeout"]) self._writable = True self._readable = True self._send_options_message() def close(self): with self.lock: if self.is_closed: return self.is_closed = True log.debug("Closing connection (%s) to %s", id(self), self.endpoint) self._writable = False self._readable = False # We don't have to wait for this to be closed, we can just schedule it self.create_timer(0, partial(asyncore.dispatcher.close, self)) log.debug("Closed socket to %s", self.endpoint) if not self.is_defunct: self.error_all_requests( ConnectionShutdown("Connection to %s was closed" % self.endpoint)) #This happens when the connection is shutdown while waiting for the ReadyMessage if not self.connected_event.is_set(): self.last_error = ConnectionShutdown("Connection to %s was closed" % self.endpoint) # don't leave in-progress operations hanging self.connected_event.set() def handle_error(self): self.defunct(sys.exc_info()[1]) def handle_close(self): log.debug("Connection %s closed by server", self) self.close() def handle_write(self): while True: with self.deque_lock: try: next_msg = self.deque.popleft() except IndexError: self._writable = False return try: sent = self.send(next_msg) self._readable = True except socket.error as err: if (err.args[0] in NONBLOCKING or err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE)): with self.deque_lock: self.deque.appendleft(next_msg) else: self.defunct(err) return else: if sent < len(next_msg): with self.deque_lock: self.deque.appendleft(next_msg[sent:]) if sent == 0: return def handle_read(self): try: while True: buf = self.recv(self.in_buffer_size) self._iobuf.write(buf) if len(buf) < self.in_buffer_size: break except socket.error as err: - if ssl and isinstance(err, ssl.SSLError): + if isinstance(err, ssl.SSLError): if err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): if not self._iobuf.tell(): return else: self.defunct(err) return elif err.args[0] in NONBLOCKING: if not self._iobuf.tell(): return else: self.defunct(err) return if self._iobuf.tell(): self.process_io_buffer() if not self._requests and not self.is_control_connection: self._readable = False def push(self, data): sabs = self.out_buffer_size if len(data) > sabs: chunks = [] for i in range(0, len(data), sabs): chunks.append(data[i:i + sabs]) else: chunks = [data] with self.deque_lock: self.deque.extend(chunks) self._writable = True _global_loop.wake_loop() def writable(self): return self._writable def readable(self): - return self._readable or (self.is_control_connection and not (self.is_defunct or self.is_closed)) + return self._readable or ((self.is_control_connection or self._continuous_paging_sessions) and not (self.is_defunct or self.is_closed)) diff --git a/cassandra/io/eventletreactor.py b/cassandra/io/eventletreactor.py index 2b16ef6..162661f 100644 --- a/cassandra/io/eventletreactor.py +++ b/cassandra/io/eventletreactor.py @@ -1,155 +1,194 @@ # Copyright 2014 Symantec Corporation # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Originally derived from MagnetoDB source: # https://github.com/stackforge/magnetodb/blob/2015.1.0b1/magnetodb/common/cassandra/io/eventletreactor.py - import eventlet from eventlet.green import socket from eventlet.queue import Queue from greenlet import GreenletExit import logging from threading import Event import time from six.moves import xrange from cassandra.connection import Connection, ConnectionShutdown, Timer, TimerManager +try: + from eventlet.green.OpenSSL import SSL + _PYOPENSSL = True +except ImportError as e: + _PYOPENSSL = False + no_pyopenssl_error = e log = logging.getLogger(__name__) +def _check_pyopenssl(): + if not _PYOPENSSL: + raise ImportError( + "{}, pyOpenSSL must be installed to enable " + "SSL support with the Eventlet event loop".format(str(no_pyopenssl_error)) + ) + + class EventletConnection(Connection): """ An implementation of :class:`.Connection` that utilizes ``eventlet``. This implementation assumes all eventlet monkey patching is active. It is not tested with partial patching. """ _read_watcher = None _write_watcher = None _socket_impl = eventlet.green.socket _ssl_impl = eventlet.green.ssl _timers = None _timeout_watcher = None _new_timer = None @classmethod def initialize_reactor(cls): eventlet.monkey_patch() if not cls._timers: cls._timers = TimerManager() cls._timeout_watcher = eventlet.spawn(cls.service_timeouts) cls._new_timer = Event() @classmethod def create_timer(cls, timeout, callback): timer = Timer(timeout, callback) cls._timers.add_timer(timer) cls._new_timer.set() return timer @classmethod def service_timeouts(cls): """ cls._timeout_watcher runs in this loop forever. It is usually waiting for the next timeout on the cls._new_timer Event. When new timers are added, that event is set so that the watcher can wake up and possibly set an earlier timeout. """ timer_manager = cls._timers while True: next_end = timer_manager.service_timeouts() sleep_time = max(next_end - time.time(), 0) if next_end else 10000 cls._new_timer.wait(sleep_time) cls._new_timer.clear() def __init__(self, *args, **kwargs): Connection.__init__(self, *args, **kwargs) + self.uses_legacy_ssl_options = self.ssl_options and not self.ssl_context self._write_queue = Queue() self._connect_socket() self._read_watcher = eventlet.spawn(lambda: self.handle_read()) self._write_watcher = eventlet.spawn(lambda: self.handle_write()) self._send_options_message() + def _wrap_socket_from_context(self): + _check_pyopenssl() + self._socket = SSL.Connection(self.ssl_context, self._socket) + self._socket.set_connect_state() + if self.ssl_options and 'server_hostname' in self.ssl_options: + # This is necessary for SNI + self._socket.set_tlsext_host_name(self.ssl_options['server_hostname'].encode('ascii')) + + def _initiate_connection(self, sockaddr): + if self.uses_legacy_ssl_options: + super(EventletConnection, self)._initiate_connection(sockaddr) + else: + self._socket.connect(sockaddr) + if self.ssl_context or self.ssl_options: + self._socket.do_handshake() + + def _match_hostname(self): + if self.uses_legacy_ssl_options: + super(EventletConnection, self)._match_hostname() + else: + cert_name = self._socket.get_peer_certificate().get_subject().commonName + if cert_name != self.endpoint.address: + raise Exception("Hostname verification failed! Certificate name '{}' " + "doesn't endpoint '{}'".format(cert_name, self.endpoint.address)) + def close(self): with self.lock: if self.is_closed: return self.is_closed = True log.debug("Closing connection (%s) to %s" % (id(self), self.endpoint)) cur_gthread = eventlet.getcurrent() if self._read_watcher and self._read_watcher != cur_gthread: self._read_watcher.kill() if self._write_watcher and self._write_watcher != cur_gthread: self._write_watcher.kill() if self._socket: self._socket.close() log.debug("Closed socket to %s" % (self.endpoint,)) if not self.is_defunct: self.error_all_requests( ConnectionShutdown("Connection to %s was closed" % self.endpoint)) # don't leave in-progress operations hanging self.connected_event.set() def handle_close(self): log.debug("connection closed by server") self.close() def handle_write(self): while True: try: next_msg = self._write_queue.get() self._socket.sendall(next_msg) except socket.error as err: log.debug("Exception during socket send for %s: %s", self, err) self.defunct(err) return # Leave the write loop except GreenletExit: # graceful greenthread exit return def handle_read(self): while True: try: buf = self._socket.recv(self.in_buffer_size) self._iobuf.write(buf) except socket.error as err: log.debug("Exception during socket recv for %s: %s", self, err) self.defunct(err) return # leave the read loop except GreenletExit: # graceful greenthread exit return if buf and self._iobuf.tell(): self.process_io_buffer() else: log.debug("Connection %s closed by server", self) self.close() return def push(self, data): chunk_size = self.out_buffer_size for i in xrange(0, len(data), chunk_size): self._write_queue.put(data[i:i + chunk_size]) diff --git a/cassandra/io/libevreactor.py b/cassandra/io/libevreactor.py index 7d4bf8e..54e2d0d 100644 --- a/cassandra/io/libevreactor.py +++ b/cassandra/io/libevreactor.py @@ -1,377 +1,386 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import atexit from collections import deque from functools import partial import logging import os import socket import ssl from threading import Lock, Thread import time from six.moves import range from cassandra.connection import (Connection, ConnectionShutdown, NONBLOCKING, Timer, TimerManager) try: import cassandra.io.libevwrapper as libev except ImportError: raise ImportError( "The C extension needed to use libev was not found. This " "probably means that you didn't have the required build dependencies " "when installing the driver. See " "http://datastax.github.io/python-driver/installation.html#c-extensions " "for instructions on installing build dependencies and building " "the C extension.") log = logging.getLogger(__name__) def _cleanup(loop): if loop: loop._cleanup() class LibevLoop(object): def __init__(self): self._pid = os.getpid() self._loop = libev.Loop() self._notifier = libev.Async(self._loop) self._notifier.start() # prevent _notifier from keeping the loop from returning self._loop.unref() self._started = False self._shutdown = False self._lock = Lock() self._lock_thread = Lock() self._thread = None # set of all connections; only replaced with a new copy # while holding _conn_set_lock, never modified in place self._live_conns = set() # newly created connections that need their write/read watcher started self._new_conns = set() # recently closed connections that need their write/read watcher stopped self._closed_conns = set() self._conn_set_lock = Lock() self._preparer = libev.Prepare(self._loop, self._loop_will_run) # prevent _preparer from keeping the loop from returning self._loop.unref() self._preparer.start() self._timers = TimerManager() self._loop_timer = libev.Timer(self._loop, self._on_loop_timer) def maybe_start(self): should_start = False with self._lock: if not self._started: log.debug("Starting libev event loop") self._started = True should_start = True if should_start: with self._lock_thread: if not self._shutdown: self._thread = Thread(target=self._run_loop, name="event_loop") self._thread.daemon = True self._thread.start() self._notifier.send() def _run_loop(self): while True: self._loop.start() # there are still active watchers, no deadlock with self._lock: if not self._shutdown and self._live_conns: log.debug("Restarting event loop") continue else: # all Connections have been closed, no active watchers log.debug("All Connections currently closed, event loop ended") self._started = False break def _cleanup(self): self._shutdown = True if not self._thread: return for conn in self._live_conns | self._new_conns | self._closed_conns: conn.close() for watcher in (conn._write_watcher, conn._read_watcher): if watcher: watcher.stop() self.notify() # wake the timer watcher # PYTHON-752 Thread might have just been created and not started with self._lock_thread: self._thread.join(timeout=1.0) if self._thread.is_alive(): log.warning( "Event loop thread could not be joined, so shutdown may not be clean. " "Please call Cluster.shutdown() to avoid this.") log.debug("Event loop thread was joined") def add_timer(self, timer): self._timers.add_timer(timer) self._notifier.send() # wake up in case this timer is earlier def _update_timer(self): if not self._shutdown: next_end = self._timers.service_timeouts() if next_end: self._loop_timer.start(next_end - time.time()) # timer handles negative values else: self._loop_timer.stop() def _on_loop_timer(self): self._timers.service_timeouts() def notify(self): self._notifier.send() def connection_created(self, conn): with self._conn_set_lock: new_live_conns = self._live_conns.copy() new_live_conns.add(conn) self._live_conns = new_live_conns new_new_conns = self._new_conns.copy() new_new_conns.add(conn) self._new_conns = new_new_conns def connection_destroyed(self, conn): with self._conn_set_lock: new_live_conns = self._live_conns.copy() new_live_conns.discard(conn) self._live_conns = new_live_conns new_closed_conns = self._closed_conns.copy() new_closed_conns.add(conn) self._closed_conns = new_closed_conns self._notifier.send() def _loop_will_run(self, prepare): changed = False for conn in self._live_conns: if not conn.deque and conn._write_watcher_is_active: if conn._write_watcher: conn._write_watcher.stop() conn._write_watcher_is_active = False changed = True elif conn.deque and not conn._write_watcher_is_active: conn._write_watcher.start() conn._write_watcher_is_active = True changed = True if self._new_conns: with self._conn_set_lock: to_start = self._new_conns self._new_conns = set() for conn in to_start: conn._read_watcher.start() changed = True if self._closed_conns: with self._conn_set_lock: to_stop = self._closed_conns self._closed_conns = set() for conn in to_stop: if conn._write_watcher: conn._write_watcher.stop() # clear reference cycles from IO callback del conn._write_watcher if conn._read_watcher: conn._read_watcher.stop() # clear reference cycles from IO callback del conn._read_watcher changed = True # TODO: update to do connection management, timer updates through dedicated async 'notifier' callbacks self._update_timer() if changed: self._notifier.send() _global_loop = None atexit.register(partial(_cleanup, _global_loop)) class LibevConnection(Connection): """ An implementation of :class:`.Connection` that uses libev for its event loop. """ _write_watcher_is_active = False _read_watcher = None _write_watcher = None _socket = None @classmethod def initialize_reactor(cls): global _global_loop if not _global_loop: _global_loop = LibevLoop() else: if _global_loop._pid != os.getpid(): log.debug("Detected fork, clearing and reinitializing reactor state") cls.handle_fork() _global_loop = LibevLoop() @classmethod def handle_fork(cls): global _global_loop if _global_loop: _global_loop._cleanup() _global_loop = None @classmethod def create_timer(cls, timeout, callback): timer = Timer(timeout, callback) _global_loop.add_timer(timer) return timer def __init__(self, *args, **kwargs): Connection.__init__(self, *args, **kwargs) self.deque = deque() self._deque_lock = Lock() self._connect_socket() self._socket.setblocking(0) with _global_loop._lock: self._read_watcher = libev.IO(self._socket.fileno(), libev.EV_READ, _global_loop._loop, self.handle_read) self._write_watcher = libev.IO(self._socket.fileno(), libev.EV_WRITE, _global_loop._loop, self.handle_write) self._send_options_message() _global_loop.connection_created(self) # start the global event loop if needed _global_loop.maybe_start() def close(self): with self.lock: if self.is_closed: return self.is_closed = True log.debug("Closing connection (%s) to %s", id(self), self.endpoint) _global_loop.connection_destroyed(self) self._socket.close() log.debug("Closed socket to %s", self.endpoint) # don't leave in-progress operations hanging if not self.is_defunct: self.error_all_requests( ConnectionShutdown("Connection to %s was closed" % self.endpoint)) def handle_write(self, watcher, revents, errno=None): if revents & libev.EV_ERROR: if errno: exc = IOError(errno, os.strerror(errno)) else: exc = Exception("libev reported an error") self.defunct(exc) return while True: try: with self._deque_lock: next_msg = self.deque.popleft() except IndexError: + if not self._socket_writable: + self._socket_writable = True return try: sent = self._socket.send(next_msg) except socket.error as err: if (err.args[0] in NONBLOCKING or err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE)): + if err.args[0] in NONBLOCKING: + self._socket_writable = False with self._deque_lock: self.deque.appendleft(next_msg) else: self.defunct(err) return else: if sent < len(next_msg): with self._deque_lock: self.deque.appendleft(next_msg[sent:]) + # we've seen some cases that 0 is returned instead of NONBLOCKING. But usually, + # we don't expect this to happen. https://bugs.python.org/issue20951 + if sent == 0: + self._socket_writable = False + return def handle_read(self, watcher, revents, errno=None): if revents & libev.EV_ERROR: if errno: exc = IOError(errno, os.strerror(errno)) else: exc = Exception("libev reported an error") self.defunct(exc) return try: while True: buf = self._socket.recv(self.in_buffer_size) self._iobuf.write(buf) if len(buf) < self.in_buffer_size: break except socket.error as err: - if ssl and isinstance(err, ssl.SSLError): + if isinstance(err, ssl.SSLError): if err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): if not self._iobuf.tell(): return else: self.defunct(err) return elif err.args[0] in NONBLOCKING: if not self._iobuf.tell(): return else: self.defunct(err) return if self._iobuf.tell(): self.process_io_buffer() else: log.debug("Connection %s closed by server", self) self.close() def push(self, data): sabs = self.out_buffer_size if len(data) > sabs: chunks = [] for i in range(0, len(data), sabs): chunks.append(data[i:i + sabs]) else: chunks = [data] with self._deque_lock: self.deque.extend(chunks) _global_loop.notify() diff --git a/cassandra/io/twistedreactor.py b/cassandra/io/twistedreactor.py index 1dbe9d8..9b3ff09 100644 --- a/cassandra/io/twistedreactor.py +++ b/cassandra/io/twistedreactor.py @@ -1,317 +1,303 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Module that implements an event loop based on twisted ( https://twistedmatrix.com ). """ import atexit -from functools import partial import logging -from threading import Thread, Lock import time -from twisted.internet import reactor, protocol +from functools import partial +from threading import Thread, Lock import weakref -from cassandra.connection import Connection, ConnectionShutdown, Timer, TimerManager +from twisted.internet import reactor, protocol +from twisted.internet.endpoints import connectProtocol, TCP4ClientEndpoint, SSL4ClientEndpoint +from twisted.internet.interfaces import IOpenSSLClientConnectionCreator +from twisted.python.failure import Failure +from zope.interface import implementer +from cassandra.connection import Connection, ConnectionShutdown, Timer, TimerManager, ConnectionException +try: + from OpenSSL import SSL + _HAS_SSL = True +except ImportError as e: + _HAS_SSL = False + import_exception = e log = logging.getLogger(__name__) def _cleanup(cleanup_weakref): try: cleanup_weakref()._cleanup() except ReferenceError: return class TwistedConnectionProtocol(protocol.Protocol): """ Twisted Protocol class for handling data received and connection made events. """ - def __init__(self): - self.connection = None + def __init__(self, connection): + self.connection = connection def dataReceived(self, data): """ Callback function that is called when data has been received on the connection. Reaches back to the Connection object and queues the data for processing. """ self.connection._iobuf.write(data) self.connection.handle_read() + def connectionMade(self): """ Callback function that is called when a connection has succeeded. Reaches back to the Connection object and confirms that the connection is ready. """ - try: - # Non SSL connection - self.connection = self.transport.connector.factory.conn - except AttributeError: - # SSL connection - self.connection = self.transport.connector.factory.wrappedFactory.conn - self.connection.client_connection_made(self.transport) def connectionLost(self, reason): # reason is a Failure instance - self.connection.defunct(reason.value) - - -class TwistedConnectionClientFactory(protocol.ClientFactory): - - def __init__(self, connection): - # ClientFactory does not define __init__() in parent classes - # and does not inherit from object. - self.conn = connection - - def buildProtocol(self, addr): - """ - Twisted function that defines which kind of protocol to use - in the ClientFactory. - """ - return TwistedConnectionProtocol() - - def clientConnectionFailed(self, connector, reason): - """ - Overridden twisted callback which is called when the - connection attempt fails. - """ - log.debug("Connect failed: %s", reason) - self.conn.defunct(reason.value) - - def clientConnectionLost(self, connector, reason): - """ - Overridden twisted callback which is called when the - connection goes away (cleanly or otherwise). - - It should be safe to call defunct() here instead of just close, because - we can assume that if the connection was closed cleanly, there are no - requests to error out. If this assumption turns out to be false, we - can call close() instead of defunct() when "reason" is an appropriate - type. - """ log.debug("Connect lost: %s", reason) - self.conn.defunct(reason.value) + self.connection.defunct(reason.value) class TwistedLoop(object): _lock = None _thread = None _timeout_task = None _timeout = None def __init__(self): self._lock = Lock() self._timers = TimerManager() def maybe_start(self): with self._lock: if not reactor.running: self._thread = Thread(target=reactor.run, name="cassandra_driver_twisted_event_loop", kwargs={'installSignalHandlers': False}) self._thread.daemon = True self._thread.start() atexit.register(partial(_cleanup, weakref.ref(self))) def _cleanup(self): if self._thread: reactor.callFromThread(reactor.stop) self._thread.join(timeout=1.0) if self._thread.is_alive(): log.warning("Event loop thread could not be joined, so " "shutdown may not be clean. Please call " "Cluster.shutdown() to avoid this.") log.debug("Event loop thread was joined") def add_timer(self, timer): self._timers.add_timer(timer) # callFromThread to schedule from the loop thread, where # the timeout task can safely be modified reactor.callFromThread(self._schedule_timeout, timer.end) def _schedule_timeout(self, next_timeout): if next_timeout: delay = max(next_timeout - time.time(), 0) if self._timeout_task and self._timeout_task.active(): if next_timeout < self._timeout: self._timeout_task.reset(delay) self._timeout = next_timeout else: self._timeout_task = reactor.callLater(delay, self._on_loop_timer) self._timeout = next_timeout def _on_loop_timer(self): self._timers.service_timeouts() self._schedule_timeout(self._timers.next_timeout) -try: - from twisted.internet import ssl - import OpenSSL.crypto - from OpenSSL.crypto import load_certificate, FILETYPE_PEM - - class _SSLContextFactory(ssl.ClientContextFactory): - def __init__(self, ssl_options, check_hostname, host): - self.ssl_options = ssl_options - self.check_hostname = check_hostname - self.host = host - - def getContext(self): - # This version has to be OpenSSL.SSL.DESIRED_VERSION - # instead of ssl.DESIRED_VERSION as in other loops - self.method = self.ssl_options["ssl_version"] - context = ssl.ClientContextFactory.getContext(self) +@implementer(IOpenSSLClientConnectionCreator) +class _SSLCreator(object): + def __init__(self, endpoint, ssl_context, ssl_options, check_hostname, timeout): + self.endpoint = endpoint + self.ssl_options = ssl_options + self.check_hostname = check_hostname + self.timeout = timeout + + if ssl_context: + self.context = ssl_context + else: + self.context = SSL.Context(SSL.TLSv1_METHOD) if "certfile" in self.ssl_options: - context.use_certificate_file(self.ssl_options["certfile"]) + self.context.use_certificate_file(self.ssl_options["certfile"]) if "keyfile" in self.ssl_options: - context.use_privatekey_file(self.ssl_options["keyfile"]) + self.context.use_privatekey_file(self.ssl_options["keyfile"]) if "ca_certs" in self.ssl_options: - x509 = load_certificate(FILETYPE_PEM, open(self.ssl_options["ca_certs"]).read()) - store = context.get_cert_store() - store.add_cert(x509) + self.context.load_verify_locations(self.ssl_options["ca_certs"]) if "cert_reqs" in self.ssl_options: - # This expects OpenSSL.SSL.VERIFY_NONE/OpenSSL.SSL.VERIFY_PEER - # or OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT - context.set_verify(self.ssl_options["cert_reqs"], - callback=self.verify_callback) - return context - - def verify_callback(self, connection, x509, errnum, errdepth, ok): - if ok: - if self.check_hostname and self.host != x509.get_subject().commonName: - return False - return ok + self.context.set_verify( + self.ssl_options["cert_reqs"], + callback=self.verify_callback + ) + self.context.set_info_callback(self.info_callback) - _HAS_SSL = True + def verify_callback(self, connection, x509, errnum, errdepth, ok): + return ok -except ImportError as e: - _HAS_SSL = False + def info_callback(self, connection, where, ret): + if where & SSL.SSL_CB_HANDSHAKE_DONE: + if self.check_hostname and self.endpoint.address != connection.get_peer_certificate().get_subject().commonName: + transport = connection.get_app_data() + transport.failVerification(Failure(ConnectionException("Hostname verification failed", self.endpoint))) + + def clientConnectionForTLS(self, tlsProtocol): + connection = SSL.Connection(self.context, None) + connection.set_app_data(tlsProtocol) + if self.ssl_options and "server_hostname" in self.ssl_options: + connection.set_tlsext_host_name(self.ssl_options['server_hostname'].encode('ascii')) + return connection class TwistedConnection(Connection): """ An implementation of :class:`.Connection` that utilizes the Twisted event loop. """ _loop = None @classmethod def initialize_reactor(cls): if not cls._loop: cls._loop = TwistedLoop() @classmethod def create_timer(cls, timeout, callback): timer = Timer(timeout, callback) cls._loop.add_timer(timer) return timer def __init__(self, *args, **kwargs): """ Initialization method. Note that we can't call reactor methods directly here because it's not thread-safe, so we schedule the reactor/connection stuff to be run from the event loop thread when it gets the chance. """ Connection.__init__(self, *args, **kwargs) self.is_closed = True self.connector = None self.transport = None reactor.callFromThread(self.add_connection) self._loop.maybe_start() - def add_connection(self): - """ - Convenience function to connect and store the resulting - connector. - """ - if self.ssl_options: - + def _check_pyopenssl(self): + if self.ssl_context or self.ssl_options: if not _HAS_SSL: raise ImportError( - str(e) + + str(import_exception) + ', pyOpenSSL must be installed to enable SSL support with the Twisted event loop' ) - self.connector = reactor.connectSSL( - host=self.endpoint.address, port=self.port, - factory=TwistedConnectionClientFactory(self), - contextFactory=_SSLContextFactory(self.ssl_options, self._check_hostname, self.endpoint.address), - timeout=self.connect_timeout) + def add_connection(self): + """ + Convenience function to connect and store the resulting + connector. + """ + host, port = self.endpoint.resolve() + if self.ssl_context or self.ssl_options: + # Can't use optionsForClientTLS here because it *forces* hostname verification. + # Cool they enforce strong security, but we have to be able to turn it off + self._check_pyopenssl() + + ssl_connection_creator = _SSLCreator( + self.endpoint, + self.ssl_context if self.ssl_context else None, + self.ssl_options, + self._check_hostname, + self.connect_timeout, + ) + + endpoint = SSL4ClientEndpoint( + reactor, + host, + port, + sslContextFactory=ssl_connection_creator, + timeout=self.connect_timeout, + ) else: - self.connector = reactor.connectTCP( - host=self.endpoint.address, port=self.port, - factory=TwistedConnectionClientFactory(self), - timeout=self.connect_timeout) + endpoint = TCP4ClientEndpoint( + reactor, + host, + port, + timeout=self.connect_timeout + ) + connectProtocol(endpoint, TwistedConnectionProtocol(self)) def client_connection_made(self, transport): """ Called by twisted protocol when a connection attempt has succeeded. """ with self.lock: self.is_closed = False self.transport = transport self._send_options_message() def close(self): """ Disconnect and error-out all requests. """ with self.lock: if self.is_closed: return self.is_closed = True log.debug("Closing connection (%s) to %s", id(self), self.endpoint) - reactor.callFromThread(self.connector.disconnect) + reactor.callFromThread(self.transport.connector.disconnect) log.debug("Closed socket to %s", self.endpoint) if not self.is_defunct: self.error_all_requests( ConnectionShutdown("Connection to %s was closed" % self.endpoint)) # don't leave in-progress operations hanging self.connected_event.set() def handle_read(self): """ Process the incoming data buffer. """ self.process_io_buffer() def push(self, data): """ This function is called when outgoing data should be queued for sending. Note that we can't call transport.write() directly because it is not thread-safe, so we schedule it to run from within the event loop when it gets the chance. """ reactor.callFromThread(self.transport.write, data) diff --git a/cassandra/marshal.py b/cassandra/marshal.py index 3b80f34..43cb627 100644 --- a/cassandra/marshal.py +++ b/cassandra/marshal.py @@ -1,157 +1,165 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import six import struct def _make_packer(format_string): packer = struct.Struct(format_string) pack = packer.pack unpack = lambda s: packer.unpack(s)[0] return pack, unpack int64_pack, int64_unpack = _make_packer('>q') int32_pack, int32_unpack = _make_packer('>i') int16_pack, int16_unpack = _make_packer('>h') int8_pack, int8_unpack = _make_packer('>b') uint64_pack, uint64_unpack = _make_packer('>Q') uint32_pack, uint32_unpack = _make_packer('>I') +uint32_le_pack, uint32_le_unpack = _make_packer('H') uint8_pack, uint8_unpack = _make_packer('>B') float_pack, float_unpack = _make_packer('>f') double_pack, double_unpack = _make_packer('>d') # Special case for cassandra header header_struct = struct.Struct('>BBbB') header_pack = header_struct.pack header_unpack = header_struct.unpack # in protocol version 3 and higher, the stream ID is two bytes v3_header_struct = struct.Struct('>BBhB') v3_header_pack = v3_header_struct.pack v3_header_unpack = v3_header_struct.unpack if six.PY3: def byte2int(b): return b def varint_unpack(term): val = int(''.join("%02x" % i for i in term), 16) if (term[0] & 128) != 0: len_term = len(term) # pulling this out of the expression to avoid overflow in cython optimized code val -= 1 << (len_term * 8) return val else: def byte2int(b): return ord(b) def varint_unpack(term): # noqa val = int(term.encode('hex'), 16) if (ord(term[0]) & 128) != 0: len_term = len(term) # pulling this out of the expression to avoid overflow in cython optimized code val = val - (1 << (len_term * 8)) return val def bit_length(n): if six.PY3 or isinstance(n, int): return int.bit_length(n) else: return long.bit_length(n) def varint_pack(big): pos = True if big == 0: return b'\x00' if big < 0: bytelength = bit_length(abs(big) - 1) // 8 + 1 big = (1 << bytelength * 8) + big pos = False revbytes = bytearray() while big > 0: revbytes.append(big & 0xff) big >>= 8 if pos and revbytes[-1] & 0x80: revbytes.append(0) revbytes.reverse() return six.binary_type(revbytes) +point_be = struct.Struct('>dd') +point_le = struct.Struct('ddd') +circle_le = struct.Struct('> 63) def decode_zig_zag(n): return (n >> 1) ^ -(n & 1) def vints_unpack(term): # noqa values = [] n = 0 while n < len(term): first_byte = byte2int(term[n]) if (first_byte & 128) == 0: val = first_byte else: num_extra_bytes = 8 - (~first_byte & 0xff).bit_length() val = first_byte & (0xff >> num_extra_bytes) end = n + num_extra_bytes while n < end: n += 1 val <<= 8 val |= byte2int(term[n]) & 0xff n += 1 values.append(decode_zig_zag(val)) return tuple(values) def vints_pack(values): revbytes = bytearray() values = [int(v) for v in values[::-1]] for value in values: v = encode_zig_zag(value) if v < 128: revbytes.append(v) else: num_extra_bytes = 0 num_bits = v.bit_length() # We need to reserve (num_extra_bytes+1) bits in the first byte # ie. with 1 extra byte, the first byte needs to be something like '10XXXXXX' # 2 bits reserved # ie. with 8 extra bytes, the first byte needs to be '11111111' # 8 bits reserved reserved_bits = num_extra_bytes + 1 while num_bits > (8-(reserved_bits)): num_extra_bytes += 1 num_bits -= 8 reserved_bits = min(num_extra_bytes + 1, 8) revbytes.append(v & 0xff) v >>= 8 if num_extra_bytes > 8: raise ValueError('Value %d is too big and cannot be encoded as vint' % value) # We can now store the last bits in the first byte n = 8 - num_extra_bytes v |= (0xff >> n << n) revbytes.append(abs(v)) revbytes.reverse() return six.binary_type(revbytes) diff --git a/cassandra/metadata.py b/cassandra/metadata.py index 1824b3f..a82fbe4 100644 --- a/cassandra/metadata.py +++ b/cassandra/metadata.py @@ -1,2845 +1,3416 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from binascii import unhexlify from bisect import bisect_left from collections import defaultdict from functools import total_ordering from hashlib import md5 -from itertools import islice, cycle import json import logging import re import six from six.moves import zip import sys from threading import RLock import struct import random murmur3 = None try: from cassandra.murmur3 import murmur3 except ImportError as e: pass from cassandra import SignatureDescriptor, ConsistencyLevel, InvalidRequest, Unauthorized import cassandra.cqltypes as types from cassandra.encoder import Encoder from cassandra.marshal import varint_unpack from cassandra.protocol import QueryMessage from cassandra.query import dict_factory, bind_params from cassandra.util import OrderedDict, Version from cassandra.pool import HostDistance from cassandra.connection import EndPoint from cassandra.compat import Mapping log = logging.getLogger(__name__) cql_keywords = set(( 'add', 'aggregate', 'all', 'allow', 'alter', 'and', 'apply', 'as', 'asc', 'ascii', 'authorize', 'batch', 'begin', 'bigint', 'blob', 'boolean', 'by', 'called', 'clustering', 'columnfamily', 'compact', 'contains', 'count', - 'counter', 'create', 'custom', 'date', 'decimal', 'delete', 'desc', 'describe', 'distinct', 'double', 'drop', + 'counter', 'create', 'custom', 'date', 'decimal', 'default', 'delete', 'desc', 'describe', 'deterministic', 'distinct', 'double', 'drop', 'entries', 'execute', 'exists', 'filtering', 'finalfunc', 'float', 'from', 'frozen', 'full', 'function', 'functions', 'grant', 'if', 'in', 'index', 'inet', 'infinity', 'initcond', 'input', 'insert', 'int', 'into', 'is', 'json', - 'key', 'keys', 'keyspace', 'keyspaces', 'language', 'limit', 'list', 'login', 'map', 'materialized', 'modify', 'nan', 'nologin', - 'norecursive', 'nosuperuser', 'not', 'null', 'of', 'on', 'options', 'or', 'order', 'password', 'permission', + 'key', 'keys', 'keyspace', 'keyspaces', 'language', 'limit', 'list', 'login', 'map', 'materialized', 'mbean', 'mbeans', 'modify', 'monotonic', + 'nan', 'nologin', 'norecursive', 'nosuperuser', 'not', 'null', 'of', 'on', 'options', 'or', 'order', 'password', 'permission', 'permissions', 'primary', 'rename', 'replace', 'returns', 'revoke', 'role', 'roles', 'schema', 'select', 'set', 'sfunc', 'smallint', 'static', 'storage', 'stype', 'superuser', 'table', 'text', 'time', 'timestamp', 'timeuuid', - 'tinyint', 'to', 'token', 'trigger', 'truncate', 'ttl', 'tuple', 'type', 'unlogged', 'update', 'use', 'user', - 'users', 'using', 'uuid', 'values', 'varchar', 'varint', 'view', 'where', 'with', 'writetime' + 'tinyint', 'to', 'token', 'trigger', 'truncate', 'ttl', 'tuple', 'type', 'unlogged', 'unset', 'update', 'use', 'user', + 'users', 'using', 'uuid', 'values', 'varchar', 'varint', 'view', 'where', 'with', 'writetime', + + # DSE specifics + "node", "nodes", "plan", "active", "application", "applications", "java", "executor", "executors", "std_out", "std_err", + "renew", "delegation", "no", "redact", "token", "lowercasestring", "cluster", "authentication", "schemes", "scheme", + "internal", "ldap", "kerberos", "remote", "object", "method", "call", "calls", "search", "schema", "config", "rows", + "columns", "profiles", "commit", "reload", "rebuild", "field", "workpool", "any", "submission", "indices", + "restrict", "unrestrict" )) """ Set of keywords in CQL. Derived from .../cassandra/src/java/org/apache/cassandra/cql3/Cql.g """ cql_keywords_unreserved = set(( 'aggregate', 'all', 'as', 'ascii', 'bigint', 'blob', 'boolean', 'called', 'clustering', 'compact', 'contains', - 'count', 'counter', 'custom', 'date', 'decimal', 'distinct', 'double', 'exists', 'filtering', 'finalfunc', 'float', + 'count', 'counter', 'custom', 'date', 'decimal', 'deterministic', 'distinct', 'double', 'exists', 'filtering', 'finalfunc', 'float', 'frozen', 'function', 'functions', 'inet', 'initcond', 'input', 'int', 'json', 'key', 'keys', 'keyspaces', - 'language', 'list', 'login', 'map', 'nologin', 'nosuperuser', 'options', 'password', 'permission', 'permissions', + 'language', 'list', 'login', 'map', 'monotonic', 'nologin', 'nosuperuser', 'options', 'password', 'permission', 'permissions', 'returns', 'role', 'roles', 'sfunc', 'smallint', 'static', 'storage', 'stype', 'superuser', 'text', 'time', 'timestamp', 'timeuuid', 'tinyint', 'trigger', 'ttl', 'tuple', 'type', 'user', 'users', 'uuid', 'values', 'varchar', 'varint', 'writetime' )) """ Set of unreserved keywords in CQL. Derived from .../cassandra/src/java/org/apache/cassandra/cql3/Cql.g """ cql_keywords_reserved = cql_keywords - cql_keywords_unreserved """ Set of reserved keywords in CQL. """ _encoder = Encoder() class Metadata(object): """ Holds a representation of the cluster schema and topology. """ cluster_name = None """ The string name of the cluster. """ keyspaces = None """ A map from keyspace names to matching :class:`~.KeyspaceMetadata` instances. """ partitioner = None """ The string name of the partitioner for the cluster. """ token_map = None """ A :class:`~.TokenMap` instance describing the ring topology. """ dbaas = False """ A boolean indicating if connected to a DBaaS cluster """ def __init__(self): self.keyspaces = {} self.dbaas = False self._hosts = {} self._hosts_lock = RLock() def export_schema_as_string(self): """ Returns a string that can be executed as a query in order to recreate the entire schema. The string is formatted to be human readable. """ return "\n\n".join(ks.export_as_string() for ks in self.keyspaces.values()) def refresh(self, connection, timeout, target_type=None, change_type=None, **kwargs): server_version = self.get_host(connection.endpoint).release_version - parser = get_schema_parser(connection, server_version, timeout) + dse_version = self.get_host(connection.endpoint).dse_version + parser = get_schema_parser(connection, server_version, dse_version, timeout) if not target_type: self._rebuild_all(parser) return tt_lower = target_type.lower() try: parse_method = getattr(parser, 'get_' + tt_lower) meta = parse_method(self.keyspaces, **kwargs) if meta: update_method = getattr(self, '_update_' + tt_lower) if tt_lower == 'keyspace' and connection.protocol_version < 3: # we didn't have 'type' target in legacy protocol versions, so we need to query those too user_types = parser.get_types_map(self.keyspaces, **kwargs) self._update_keyspace(meta, user_types) else: update_method(meta) else: drop_method = getattr(self, '_drop_' + tt_lower) drop_method(**kwargs) except AttributeError: raise ValueError("Unknown schema target_type: '%s'" % target_type) def _rebuild_all(self, parser): current_keyspaces = set() for keyspace_meta in parser.get_all_keyspaces(): current_keyspaces.add(keyspace_meta.name) old_keyspace_meta = self.keyspaces.get(keyspace_meta.name, None) self.keyspaces[keyspace_meta.name] = keyspace_meta if old_keyspace_meta: self._keyspace_updated(keyspace_meta.name) else: self._keyspace_added(keyspace_meta.name) # remove not-just-added keyspaces removed_keyspaces = [name for name in self.keyspaces.keys() if name not in current_keyspaces] self.keyspaces = dict((name, meta) for name, meta in self.keyspaces.items() if name in current_keyspaces) for ksname in removed_keyspaces: self._keyspace_removed(ksname) def _update_keyspace(self, keyspace_meta, new_user_types=None): ks_name = keyspace_meta.name old_keyspace_meta = self.keyspaces.get(ks_name, None) self.keyspaces[ks_name] = keyspace_meta if old_keyspace_meta: keyspace_meta.tables = old_keyspace_meta.tables keyspace_meta.user_types = new_user_types if new_user_types is not None else old_keyspace_meta.user_types keyspace_meta.indexes = old_keyspace_meta.indexes keyspace_meta.functions = old_keyspace_meta.functions keyspace_meta.aggregates = old_keyspace_meta.aggregates keyspace_meta.views = old_keyspace_meta.views if (keyspace_meta.replication_strategy != old_keyspace_meta.replication_strategy): self._keyspace_updated(ks_name) else: self._keyspace_added(ks_name) def _drop_keyspace(self, keyspace): if self.keyspaces.pop(keyspace, None): self._keyspace_removed(keyspace) def _update_table(self, meta): try: keyspace_meta = self.keyspaces[meta.keyspace_name] # this is unfortunate, but protocol v4 does not differentiate # between events for tables and views. .get_table will # return one or the other based on the query results. # Here we deal with that. if isinstance(meta, TableMetadata): keyspace_meta._add_table_metadata(meta) else: keyspace_meta._add_view_metadata(meta) except KeyError: # can happen if keyspace disappears while processing async event pass def _drop_table(self, keyspace, table): try: keyspace_meta = self.keyspaces[keyspace] keyspace_meta._drop_table_metadata(table) # handles either table or view except KeyError: # can happen if keyspace disappears while processing async event pass def _update_type(self, type_meta): try: self.keyspaces[type_meta.keyspace].user_types[type_meta.name] = type_meta except KeyError: # can happen if keyspace disappears while processing async event pass def _drop_type(self, keyspace, type): try: self.keyspaces[keyspace].user_types.pop(type, None) except KeyError: # can happen if keyspace disappears while processing async event pass def _update_function(self, function_meta): try: self.keyspaces[function_meta.keyspace].functions[function_meta.signature] = function_meta except KeyError: # can happen if keyspace disappears while processing async event pass def _drop_function(self, keyspace, function): try: self.keyspaces[keyspace].functions.pop(function.signature, None) except KeyError: pass def _update_aggregate(self, aggregate_meta): try: self.keyspaces[aggregate_meta.keyspace].aggregates[aggregate_meta.signature] = aggregate_meta except KeyError: pass def _drop_aggregate(self, keyspace, aggregate): try: self.keyspaces[keyspace].aggregates.pop(aggregate.signature, None) except KeyError: pass def _keyspace_added(self, ksname): if self.token_map: self.token_map.rebuild_keyspace(ksname, build_if_absent=False) def _keyspace_updated(self, ksname): if self.token_map: self.token_map.rebuild_keyspace(ksname, build_if_absent=False) def _keyspace_removed(self, ksname): if self.token_map: self.token_map.remove_keyspace(ksname) def rebuild_token_map(self, partitioner, token_map): """ Rebuild our view of the topology from fresh rows from the system topology tables. For internal use only. """ self.partitioner = partitioner if partitioner.endswith('RandomPartitioner'): token_class = MD5Token elif partitioner.endswith('Murmur3Partitioner'): token_class = Murmur3Token elif partitioner.endswith('ByteOrderedPartitioner'): token_class = BytesToken else: self.token_map = None return token_to_host_owner = {} ring = [] for host, token_strings in six.iteritems(token_map): for token_string in token_strings: token = token_class.from_string(token_string) ring.append(token) token_to_host_owner[token] = host all_tokens = sorted(ring) self.token_map = TokenMap( token_class, token_to_host_owner, all_tokens, self) def get_replicas(self, keyspace, key): """ Returns a list of :class:`.Host` instances that are replicas for a given partition key. """ t = self.token_map if not t: return [] try: return t.get_replicas(keyspace, t.token_class.from_key(key)) except NoMurmur3: return [] def can_support_partitioner(self): if self.partitioner.endswith('Murmur3Partitioner') and murmur3 is None: return False else: return True def add_or_return_host(self, host): """ Returns a tuple (host, new), where ``host`` is a Host instance, and ``new`` is a bool indicating whether the host was newly added. """ with self._hosts_lock: try: return self._hosts[host.endpoint], False except KeyError: self._hosts[host.endpoint] = host return host, True def remove_host(self, host): with self._hosts_lock: return bool(self._hosts.pop(host.endpoint, False)) - def get_host(self, endpoint_or_address): + def get_host(self, endpoint_or_address, port=None): """ - Find a host in the metadata for a specific endpoint. If a string inet address is passed, - iterate all hosts to match the :attr:`~.pool.Host.broadcast_rpc_address` attribute. + Find a host in the metadata for a specific endpoint. If a string inet address and port are passed, + iterate all hosts to match the :attr:`~.pool.Host.broadcast_rpc_address` and + :attr:`~.pool.Host.broadcast_rpc_port`attributes. """ if not isinstance(endpoint_or_address, EndPoint): - return self._get_host_by_address(endpoint_or_address) + return self._get_host_by_address(endpoint_or_address, port) return self._hosts.get(endpoint_or_address) - def _get_host_by_address(self, address): + def _get_host_by_address(self, address, port=None): for host in six.itervalues(self._hosts): - if host.broadcast_rpc_address == address: + if (host.broadcast_rpc_address == address and + (port is None or host.broadcast_rpc_port is None or host.broadcast_rpc_port == port)): return host + return None def all_hosts(self): """ Returns a list of all known :class:`.Host` instances in the cluster. """ with self._hosts_lock: return list(self._hosts.values()) REPLICATION_STRATEGY_CLASS_PREFIX = "org.apache.cassandra.locator." def trim_if_startswith(s, prefix): if s.startswith(prefix): return s[len(prefix):] return s _replication_strategies = {} class ReplicationStrategyTypeType(type): def __new__(metacls, name, bases, dct): dct.setdefault('name', name) cls = type.__new__(metacls, name, bases, dct) if not name.startswith('_'): _replication_strategies[name] = cls return cls + @six.add_metaclass(ReplicationStrategyTypeType) class _ReplicationStrategy(object): options_map = None @classmethod def create(cls, strategy_class, options_map): if not strategy_class: return None strategy_name = trim_if_startswith(strategy_class, REPLICATION_STRATEGY_CLASS_PREFIX) rs_class = _replication_strategies.get(strategy_name, None) if rs_class is None: rs_class = _UnknownStrategyBuilder(strategy_name) _replication_strategies[strategy_name] = rs_class try: rs_instance = rs_class(options_map) except Exception as exc: log.warning("Failed creating %s with options %s: %s", strategy_name, options_map, exc) return None return rs_instance def make_token_replica_map(self, token_to_host_owner, ring): raise NotImplementedError() def export_for_schema(self): raise NotImplementedError() ReplicationStrategy = _ReplicationStrategy class _UnknownStrategyBuilder(object): def __init__(self, name): self.name = name def __call__(self, options_map): strategy_instance = _UnknownStrategy(self.name, options_map) return strategy_instance class _UnknownStrategy(ReplicationStrategy): def __init__(self, name, options_map): self.name = name self.options_map = options_map.copy() if options_map is not None else dict() self.options_map['class'] = self.name def __eq__(self, other): return (isinstance(other, _UnknownStrategy) and self.name == other.name and self.options_map == other.options_map) def export_for_schema(self): """ Returns a string version of these replication options which are suitable for use in a CREATE KEYSPACE statement. """ if self.options_map: return dict((str(key), str(value)) for key, value in self.options_map.items()) return "{'class': '%s'}" % (self.name, ) def make_token_replica_map(self, token_to_host_owner, ring): return {} +class ReplicationFactor(object): + """ + Represent the replication factor of a keyspace. + """ + + all_replicas = None + """ + The number of total replicas. + """ + + full_replicas = None + """ + The number of replicas that own a full copy of the data. This is the same + than `all_replicas` when transient replication is not enabled. + """ + + transient_replicas = None + """ + The number of transient replicas. + + Only set if the keyspace has transient replication enabled. + """ + + def __init__(self, all_replicas, transient_replicas=None): + self.all_replicas = all_replicas + self.transient_replicas = transient_replicas + self.full_replicas = (all_replicas - transient_replicas) if transient_replicas else all_replicas + + @staticmethod + def create(rf): + """ + Given the inputted replication factor string, parse and return the ReplicationFactor instance. + """ + transient_replicas = None + try: + all_replicas = int(rf) + except ValueError: + try: + rf = rf.split('/') + all_replicas, transient_replicas = int(rf[0]), int(rf[1]) + except Exception: + raise ValueError("Unable to determine replication factor from: {}".format(rf)) + + return ReplicationFactor(all_replicas, transient_replicas) + + def __str__(self): + return ("%d/%d" % (self.all_replicas, self.transient_replicas) if self.transient_replicas + else "%d" % self.all_replicas) + + def __eq__(self, other): + if not isinstance(other, ReplicationFactor): + return False + + return self.all_replicas == other.all_replicas and self.full_replicas == other.full_replicas + + class SimpleStrategy(ReplicationStrategy): - replication_factor = None + replication_factor_info = None """ - The replication factor for this keyspace. + A :class:`cassandra.metadata.ReplicationFactor` instance. """ + @property + def replication_factor(self): + """ + The replication factor for this keyspace. + + For backward compatibility, this returns the + :attr:`cassandra.metadata.ReplicationFactor.full_replicas` value of + :attr:`cassandra.metadata.SimpleStrategy.replication_factor_info`. + """ + return self.replication_factor_info.full_replicas + def __init__(self, options_map): - try: - self.replication_factor = int(options_map['replication_factor']) - except Exception: - raise ValueError("SimpleStrategy requires an integer 'replication_factor' option") + self.replication_factor_info = ReplicationFactor.create(options_map['replication_factor']) def make_token_replica_map(self, token_to_host_owner, ring): replica_map = {} for i in range(len(ring)): j, hosts = 0, list() while len(hosts) < self.replication_factor and j < len(ring): token = ring[(i + j) % len(ring)] host = token_to_host_owner[token] if host not in hosts: hosts.append(host) j += 1 replica_map[ring[i]] = hosts return replica_map def export_for_schema(self): """ Returns a string version of these replication options which are suitable for use in a CREATE KEYSPACE statement. """ - return "{'class': 'SimpleStrategy', 'replication_factor': '%d'}" \ - % (self.replication_factor,) + return "{'class': 'SimpleStrategy', 'replication_factor': '%s'}" \ + % (str(self.replication_factor_info),) def __eq__(self, other): if not isinstance(other, SimpleStrategy): return False - return self.replication_factor == other.replication_factor + return str(self.replication_factor_info) == str(other.replication_factor_info) class NetworkTopologyStrategy(ReplicationStrategy): + dc_replication_factors_info = None + """ + A map of datacenter names to the :class:`cassandra.metadata.ReplicationFactor` instance for that DC. + """ + dc_replication_factors = None """ A map of datacenter names to the replication factor for that DC. + + For backward compatibility, this maps to the :attr:`cassandra.metadata.ReplicationFactor.full_replicas` + value of the :attr:`cassandra.metadata.NetworkTopologyStrategy.dc_replication_factors_info` dict. """ def __init__(self, dc_replication_factors): + self.dc_replication_factors_info = dict( + (str(k), ReplicationFactor.create(v)) for k, v in dc_replication_factors.items()) self.dc_replication_factors = dict( - (str(k), int(v)) for k, v in dc_replication_factors.items()) + (dc, rf.full_replicas) for dc, rf in self.dc_replication_factors_info.items()) def make_token_replica_map(self, token_to_host_owner, ring): - dc_rf_map = dict((dc, int(rf)) - for dc, rf in self.dc_replication_factors.items() if rf > 0) + dc_rf_map = dict( + (dc, full_replicas) for dc, full_replicas in self.dc_replication_factors.items() + if full_replicas > 0) # build a map of DCs to lists of indexes into `ring` for tokens that # belong to that DC dc_to_token_offset = defaultdict(list) dc_racks = defaultdict(set) hosts_per_dc = defaultdict(set) for i, token in enumerate(ring): host = token_to_host_owner[token] dc_to_token_offset[host.datacenter].append(i) if host.datacenter and host.rack: dc_racks[host.datacenter].add(host.rack) hosts_per_dc[host.datacenter].add(host) # A map of DCs to an index into the dc_to_token_offset value for that dc. # This is how we keep track of advancing around the ring for each DC. dc_to_current_index = defaultdict(int) replica_map = defaultdict(list) for i in range(len(ring)): replicas = replica_map[ring[i]] # go through each DC and find the replicas in that DC for dc in dc_to_token_offset.keys(): if dc not in dc_rf_map: continue # advance our per-DC index until we're up to at least the # current token in the ring token_offsets = dc_to_token_offset[dc] index = dc_to_current_index[dc] num_tokens = len(token_offsets) while index < num_tokens and token_offsets[index] < i: index += 1 dc_to_current_index[dc] = index replicas_remaining = dc_rf_map[dc] replicas_this_dc = 0 skipped_hosts = [] racks_placed = set() racks_this_dc = dc_racks[dc] hosts_this_dc = len(hosts_per_dc[dc]) for token_offset_index in six.moves.range(index, index+num_tokens): if token_offset_index >= len(token_offsets): token_offset_index = token_offset_index - len(token_offsets) token_offset = token_offsets[token_offset_index] host = token_to_host_owner[ring[token_offset]] if replicas_remaining == 0 or replicas_this_dc == hosts_this_dc: break if host in replicas: continue if host.rack in racks_placed and len(racks_placed) < len(racks_this_dc): skipped_hosts.append(host) continue replicas.append(host) replicas_this_dc += 1 replicas_remaining -= 1 racks_placed.add(host.rack) if len(racks_placed) == len(racks_this_dc): for host in skipped_hosts: if replicas_remaining == 0: break replicas.append(host) replicas_remaining -= 1 del skipped_hosts[:] return replica_map def export_for_schema(self): """ Returns a string version of these replication options which are suitable for use in a CREATE KEYSPACE statement. """ ret = "{'class': 'NetworkTopologyStrategy'" - for dc, repl_factor in sorted(self.dc_replication_factors.items()): - ret += ", '%s': '%d'" % (dc, repl_factor) + for dc, rf in sorted(self.dc_replication_factors_info.items()): + ret += ", '%s': '%s'" % (dc, str(rf)) return ret + "}" def __eq__(self, other): if not isinstance(other, NetworkTopologyStrategy): return False - return self.dc_replication_factors == other.dc_replication_factors + return self.dc_replication_factors_info == other.dc_replication_factors_info class LocalStrategy(ReplicationStrategy): def __init__(self, options_map): pass def make_token_replica_map(self, token_to_host_owner, ring): return {} def export_for_schema(self): """ Returns a string version of these replication options which are suitable for use in a CREATE KEYSPACE statement. """ return "{'class': 'LocalStrategy'}" def __eq__(self, other): return isinstance(other, LocalStrategy) class KeyspaceMetadata(object): """ A representation of the schema for a single keyspace. """ name = None """ The string name of the keyspace. """ durable_writes = True """ A boolean indicating whether durable writes are enabled for this keyspace or not. """ replication_strategy = None """ A :class:`.ReplicationStrategy` subclass object. """ tables = None """ A map from table names to instances of :class:`~.TableMetadata`. """ indexes = None """ A dict mapping index names to :class:`.IndexMetadata` instances. """ user_types = None """ A map from user-defined type names to instances of :class:`~cassandra.metadata.UserType`. .. versionadded:: 2.1.0 """ functions = None """ A map from user-defined function signatures to instances of :class:`~cassandra.metadata.Function`. .. versionadded:: 2.6.0 """ aggregates = None """ A map from user-defined aggregate signatures to instances of :class:`~cassandra.metadata.Aggregate`. .. versionadded:: 2.6.0 """ views = None """ A dict mapping view names to :class:`.MaterializedViewMetadata` instances. """ virtual = False """ A boolean indicating if this is a virtual keyspace or not. Always ``False`` - for clusters running pre-4.0 versions of Cassandra. + for clusters running Cassandra pre-4.0 and DSE pre-6.7 versions. .. versionadded:: 3.15 """ + graph_engine = None + """ + A string indicating whether a graph engine is enabled for this keyspace (Core/Classic). + """ + _exc_info = None """ set if metadata parsing failed """ - def __init__(self, name, durable_writes, strategy_class, strategy_options): + def __init__(self, name, durable_writes, strategy_class, strategy_options, graph_engine=None): self.name = name self.durable_writes = durable_writes self.replication_strategy = ReplicationStrategy.create(strategy_class, strategy_options) self.tables = {} self.indexes = {} self.user_types = {} self.functions = {} self.aggregates = {} self.views = {} + self.graph_engine = graph_engine + + @property + def is_graph_enabled(self): + return self.graph_engine is not None def export_as_string(self): """ Returns a CQL query string that can be used to recreate the entire keyspace, including user-defined types and tables. """ - cql = "\n\n".join([self.as_cql_query() + ';'] + - self.user_type_strings() + - [f.export_as_string() for f in self.functions.values()] + - [a.export_as_string() for a in self.aggregates.values()] + - [t.export_as_string() for t in self.tables.values()]) + # Make sure tables with vertex are exported before tables with edges + tables_with_vertex = [t for t in self.tables.values() if hasattr(t, 'vertex') and t.vertex] + other_tables = [t for t in self.tables.values() if t not in tables_with_vertex] + + cql = "\n\n".join( + [self.as_cql_query() + ';'] + + self.user_type_strings() + + [f.export_as_string() for f in self.functions.values()] + + [a.export_as_string() for a in self.aggregates.values()] + + [t.export_as_string() for t in tables_with_vertex + other_tables]) + if self._exc_info: import traceback ret = "/*\nWarning: Keyspace %s is incomplete because of an error processing metadata.\n" % \ (self.name) for line in traceback.format_exception(*self._exc_info): ret += line ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % cql return ret if self.virtual: return ("/*\nWarning: Keyspace {ks} is a virtual keyspace and cannot be recreated with CQL.\n" "Structure, for reference:*/\n" "{cql}\n" "").format(ks=self.name, cql=cql) return cql def as_cql_query(self): """ Returns a CQL query string that can be used to recreate just this keyspace, not including user-defined types and tables. """ if self.virtual: return "// VIRTUAL KEYSPACE {}".format(protect_name(self.name)) ret = "CREATE KEYSPACE %s WITH replication = %s " % ( protect_name(self.name), self.replication_strategy.export_for_schema()) - return ret + (' AND durable_writes = %s' % ("true" if self.durable_writes else "false")) + ret = ret + (' AND durable_writes = %s' % ("true" if self.durable_writes else "false")) + if self.graph_engine is not None: + ret = ret + (" AND graph_engine = '%s'" % self.graph_engine) + return ret def user_type_strings(self): user_type_strings = [] user_types = self.user_types.copy() keys = sorted(user_types.keys()) for k in keys: if k in user_types: self.resolve_user_types(k, user_types, user_type_strings) return user_type_strings def resolve_user_types(self, key, user_types, user_type_strings): user_type = user_types.pop(key) for type_name in user_type.field_types: for sub_type in types.cql_types_from_string(type_name): if sub_type in user_types: self.resolve_user_types(sub_type, user_types, user_type_strings) user_type_strings.append(user_type.export_as_string()) def _add_table_metadata(self, table_metadata): old_indexes = {} old_meta = self.tables.get(table_metadata.name, None) if old_meta: # views are not queried with table, so they must be transferred to new table_metadata.views = old_meta.views # indexes will be updated with what is on the new metadata old_indexes = old_meta.indexes # note the intentional order of add before remove # this makes sure the maps are never absent something that existed before this update for index_name, index_metadata in six.iteritems(table_metadata.indexes): self.indexes[index_name] = index_metadata for index_name in (n for n in old_indexes if n not in table_metadata.indexes): self.indexes.pop(index_name, None) self.tables[table_metadata.name] = table_metadata def _drop_table_metadata(self, table_name): table_meta = self.tables.pop(table_name, None) if table_meta: for index_name in table_meta.indexes: self.indexes.pop(index_name, None) for view_name in table_meta.views: self.views.pop(view_name, None) return # we can't tell table drops from views, so drop both # (name is unique among them, within a keyspace) view_meta = self.views.pop(table_name, None) if view_meta: try: self.tables[view_meta.base_table_name].views.pop(table_name, None) except KeyError: pass def _add_view_metadata(self, view_metadata): try: self.tables[view_metadata.base_table_name].views[view_metadata.name] = view_metadata self.views[view_metadata.name] = view_metadata except KeyError: pass class UserType(object): """ A user defined type, as created by ``CREATE TYPE`` statements. User-defined types were introduced in Cassandra 2.1. .. versionadded:: 2.1.0 """ keyspace = None """ The string name of the keyspace in which this type is defined. """ name = None """ The name of this type. """ field_names = None """ An ordered list of the names for each field in this user-defined type. """ field_types = None """ An ordered list of the types for each field in this user-defined type. """ def __init__(self, keyspace, name, field_names, field_types): self.keyspace = keyspace self.name = name # non-frozen collections can return None self.field_names = field_names or [] self.field_types = field_types or [] def as_cql_query(self, formatted=False): """ Returns a CQL query that can be used to recreate this type. If `formatted` is set to :const:`True`, extra whitespace will be added to make the query more readable. """ ret = "CREATE TYPE %s.%s (%s" % ( protect_name(self.keyspace), protect_name(self.name), "\n" if formatted else "") if formatted: field_join = ",\n" padding = " " else: field_join = ", " padding = "" fields = [] for field_name, field_type in zip(self.field_names, self.field_types): fields.append("%s %s" % (protect_name(field_name), field_type)) ret += field_join.join("%s%s" % (padding, field) for field in fields) ret += "\n)" if formatted else ")" return ret def export_as_string(self): return self.as_cql_query(formatted=True) + ';' class Aggregate(object): """ A user defined aggregate function, as created by ``CREATE AGGREGATE`` statements. Aggregate functions were introduced in Cassandra 2.2 .. versionadded:: 2.6.0 """ keyspace = None """ The string name of the keyspace in which this aggregate is defined """ name = None """ The name of this aggregate """ argument_types = None """ An ordered list of the types for each argument to the aggregate """ final_func = None """ Name of a final function """ initial_condition = None """ Initial condition of the aggregate """ return_type = None """ Return type of the aggregate """ state_func = None """ Name of a state function """ state_type = None """ Type of the aggregate state """ + deterministic = None + """ + Flag indicating if this function is guaranteed to produce the same result + for a particular input and state. This is available only with DSE >=6.0. + """ + def __init__(self, keyspace, name, argument_types, state_func, - state_type, final_func, initial_condition, return_type): + state_type, final_func, initial_condition, return_type, + deterministic): self.keyspace = keyspace self.name = name self.argument_types = argument_types self.state_func = state_func self.state_type = state_type self.final_func = final_func self.initial_condition = initial_condition self.return_type = return_type + self.deterministic = deterministic def as_cql_query(self, formatted=False): """ Returns a CQL query that can be used to recreate this aggregate. If `formatted` is set to :const:`True`, extra whitespace will be added to make the query more readable. """ sep = '\n ' if formatted else ' ' keyspace = protect_name(self.keyspace) name = protect_name(self.name) type_list = ', '.join([types.strip_frozen(arg_type) for arg_type in self.argument_types]) state_func = protect_name(self.state_func) state_type = types.strip_frozen(self.state_type) ret = "CREATE AGGREGATE %(keyspace)s.%(name)s(%(type_list)s)%(sep)s" \ "SFUNC %(state_func)s%(sep)s" \ "STYPE %(state_type)s" % locals() ret += ''.join((sep, 'FINALFUNC ', protect_name(self.final_func))) if self.final_func else '' ret += ''.join((sep, 'INITCOND ', self.initial_condition)) if self.initial_condition is not None else '' + ret += '{}DETERMINISTIC'.format(sep) if self.deterministic else '' return ret def export_as_string(self): return self.as_cql_query(formatted=True) + ';' @property def signature(self): return SignatureDescriptor.format_signature(self.name, self.argument_types) class Function(object): """ A user defined function, as created by ``CREATE FUNCTION`` statements. User-defined functions were introduced in Cassandra 2.2 .. versionadded:: 2.6.0 """ keyspace = None """ The string name of the keyspace in which this function is defined """ name = None """ The name of this function """ argument_types = None """ An ordered list of the types for each argument to the function """ argument_names = None """ An ordered list of the names of each argument to the function """ return_type = None """ Return type of the function """ language = None """ Language of the function body """ body = None """ Function body string """ called_on_null_input = None """ Flag indicating whether this function should be called for rows with null values (convenience function to avoid handling nulls explicitly if the result will just be null) """ + deterministic = None + """ + Flag indicating if this function is guaranteed to produce the same result + for a particular input. This is available only for DSE >=6.0. + """ + + monotonic = None + """ + Flag indicating if this function is guaranteed to increase or decrease + monotonically on any of its arguments. This is available only for DSE >=6.0. + """ + + monotonic_on = None + """ + A list containing the argument or arguments over which this function is + monotonic. This is available only for DSE >=6.0. + """ + def __init__(self, keyspace, name, argument_types, argument_names, - return_type, language, body, called_on_null_input): + return_type, language, body, called_on_null_input, + deterministic, monotonic, monotonic_on): self.keyspace = keyspace self.name = name self.argument_types = argument_types # argument_types (frozen>) will always be a list # argument_name is not frozen in C* < 3.0 and may return None self.argument_names = argument_names or [] self.return_type = return_type self.language = language self.body = body self.called_on_null_input = called_on_null_input + self.deterministic = deterministic + self.monotonic = monotonic + self.monotonic_on = monotonic_on def as_cql_query(self, formatted=False): """ Returns a CQL query that can be used to recreate this function. If `formatted` is set to :const:`True`, extra whitespace will be added to make the query more readable. """ sep = '\n ' if formatted else ' ' keyspace = protect_name(self.keyspace) name = protect_name(self.name) arg_list = ', '.join(["%s %s" % (protect_name(n), types.strip_frozen(t)) for n, t in zip(self.argument_names, self.argument_types)]) typ = self.return_type lang = self.language body = self.body on_null = "CALLED" if self.called_on_null_input else "RETURNS NULL" + deterministic_token = ('DETERMINISTIC{}'.format(sep) + if self.deterministic else + '') + monotonic_tokens = '' # default for nonmonotonic function + if self.monotonic: + # monotonic on all arguments; ignore self.monotonic_on + monotonic_tokens = 'MONOTONIC{}'.format(sep) + elif self.monotonic_on: + # if monotonic == False and monotonic_on is nonempty, we know that + # monotonicity was specified with MONOTONIC ON , so there's + # exactly 1 value there + monotonic_tokens = 'MONOTONIC ON {}{}'.format(self.monotonic_on[0], + sep) return "CREATE FUNCTION %(keyspace)s.%(name)s(%(arg_list)s)%(sep)s" \ "%(on_null)s ON NULL INPUT%(sep)s" \ "RETURNS %(typ)s%(sep)s" \ + "%(deterministic_token)s" \ + "%(monotonic_tokens)s" \ "LANGUAGE %(lang)s%(sep)s" \ "AS $$%(body)s$$" % locals() def export_as_string(self): return self.as_cql_query(formatted=True) + ';' @property def signature(self): return SignatureDescriptor.format_signature(self.name, self.argument_types) class TableMetadata(object): """ A representation of the schema for a single table. """ keyspace_name = None """ String name of this Table's keyspace """ name = None """ The string name of the table. """ partition_key = None """ A list of :class:`.ColumnMetadata` instances representing the columns in the partition key for this table. This will always hold at least one column. """ clustering_key = None """ A list of :class:`.ColumnMetadata` instances representing the columns in the clustering key for this table. These are all of the :attr:`.primary_key` columns that are not in the :attr:`.partition_key`. Note that a table may have no clustering keys, in which case this will be an empty list. """ @property def primary_key(self): """ A list of :class:`.ColumnMetadata` representing the components of the primary key for this table. """ return self.partition_key + self.clustering_key columns = None """ A dict mapping column names to :class:`.ColumnMetadata` instances. """ indexes = None """ A dict mapping index names to :class:`.IndexMetadata` instances. """ is_compact_storage = False options = None """ A dict mapping table option names to their specific settings for this table. """ compaction_options = { "min_compaction_threshold": "min_threshold", "max_compaction_threshold": "max_threshold", "compaction_strategy_class": "class"} triggers = None """ A dict mapping trigger names to :class:`.TriggerMetadata` instances. """ views = None """ A dict mapping view names to :class:`.MaterializedViewMetadata` instances. """ _exc_info = None """ set if metadata parsing failed """ virtual = False """ A boolean indicating if this is a virtual table or not. Always ``False`` - for clusters running pre-4.0 versions of Cassandra. + for clusters running Cassandra pre-4.0 and DSE pre-6.7 versions. .. versionadded:: 3.15 """ @property def is_cql_compatible(self): """ A boolean indicating if this table can be represented as CQL in export """ if self.virtual: return False comparator = getattr(self, 'comparator', None) if comparator: # no compact storage with more than one column beyond PK if there # are clustering columns incompatible = (self.is_compact_storage and len(self.columns) > len(self.primary_key) + 1 and len(self.clustering_key) >= 1) return not incompatible return True extensions = None """ Metadata describing configuration for table extensions """ def __init__(self, keyspace_name, name, partition_key=None, clustering_key=None, columns=None, triggers=None, options=None, virtual=False): self.keyspace_name = keyspace_name self.name = name self.partition_key = [] if partition_key is None else partition_key self.clustering_key = [] if clustering_key is None else clustering_key self.columns = OrderedDict() if columns is None else columns self.indexes = {} self.options = {} if options is None else options self.comparator = None self.triggers = OrderedDict() if triggers is None else triggers self.views = {} self.virtual = virtual def export_as_string(self): """ Returns a string of CQL queries that can be used to recreate this table along with all indexes on it. The returned string is formatted to be human readable. """ if self._exc_info: import traceback ret = "/*\nWarning: Table %s.%s is incomplete because of an error processing metadata.\n" % \ (self.keyspace_name, self.name) for line in traceback.format_exception(*self._exc_info): ret += line ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % self._all_as_cql() elif not self.is_cql_compatible: # If we can't produce this table with CQL, comment inline ret = "/*\nWarning: Table %s.%s omitted because it has constructs not compatible with CQL (was created via legacy API).\n" % \ (self.keyspace_name, self.name) ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % self._all_as_cql() elif self.virtual: ret = ('/*\nWarning: Table {ks}.{tab} is a virtual table and cannot be recreated with CQL.\n' 'Structure, for reference:\n' '{cql}\n*/').format(ks=self.keyspace_name, tab=self.name, cql=self._all_as_cql()) else: ret = self._all_as_cql() return ret def _all_as_cql(self): ret = self.as_cql_query(formatted=True) ret += ";" for index in self.indexes.values(): ret += "\n%s;" % index.as_cql_query() for trigger_meta in self.triggers.values(): ret += "\n%s;" % (trigger_meta.as_cql_query(),) for view_meta in self.views.values(): ret += "\n\n%s;" % (view_meta.as_cql_query(formatted=True),) if self.extensions: registry = _RegisteredExtensionType._extension_registry for k in six.viewkeys(registry) & self.extensions: # no viewkeys on OrderedMapSerializeKey ext = registry[k] cql = ext.after_table_cql(self, k, self.extensions[k]) if cql: ret += "\n\n%s" % (cql,) return ret def as_cql_query(self, formatted=False): """ Returns a CQL query that can be used to recreate this table (index creations are not included). If `formatted` is set to :const:`True`, extra whitespace will be added to make the query human readable. """ ret = "%s TABLE %s.%s (%s" % ( ('VIRTUAL' if self.virtual else 'CREATE'), protect_name(self.keyspace_name), protect_name(self.name), "\n" if formatted else "") if formatted: column_join = ",\n" padding = " " else: column_join = ", " padding = "" columns = [] for col in self.columns.values(): columns.append("%s %s%s" % (protect_name(col.name), col.cql_type, ' static' if col.is_static else '')) if len(self.partition_key) == 1 and not self.clustering_key: columns[0] += " PRIMARY KEY" ret += column_join.join("%s%s" % (padding, col) for col in columns) # primary key if len(self.partition_key) > 1 or self.clustering_key: ret += "%s%sPRIMARY KEY (" % (column_join, padding) if len(self.partition_key) > 1: ret += "(%s)" % ", ".join(protect_name(col.name) for col in self.partition_key) else: ret += protect_name(self.partition_key[0].name) if self.clustering_key: ret += ", %s" % ", ".join(protect_name(col.name) for col in self.clustering_key) ret += ")" # properties ret += "%s) WITH " % ("\n" if formatted else "") ret += self._property_string(formatted, self.clustering_key, self.options, self.is_compact_storage) return ret @classmethod def _property_string(cls, formatted, clustering_key, options_map, is_compact_storage=False): properties = [] if is_compact_storage: properties.append("COMPACT STORAGE") if clustering_key: cluster_str = "CLUSTERING ORDER BY " inner = [] for col in clustering_key: ordering = "DESC" if col.is_reversed else "ASC" inner.append("%s %s" % (protect_name(col.name), ordering)) cluster_str += "(%s)" % ", ".join(inner) properties.append(cluster_str) properties.extend(cls._make_option_strings(options_map)) join_str = "\n AND " if formatted else " AND " return join_str.join(properties) @classmethod def _make_option_strings(cls, options_map): ret = [] options_copy = dict(options_map.items()) actual_options = json.loads(options_copy.pop('compaction_strategy_options', '{}')) value = options_copy.pop("compaction_strategy_class", None) actual_options.setdefault("class", value) compaction_option_strings = ["'%s': '%s'" % (k, v) for k, v in actual_options.items()] ret.append('compaction = {%s}' % ', '.join(compaction_option_strings)) for system_table_name in cls.compaction_options.keys(): options_copy.pop(system_table_name, None) # delete if present options_copy.pop('compaction_strategy_option', None) if not options_copy.get('compression'): params = json.loads(options_copy.pop('compression_parameters', '{}')) param_strings = ["'%s': '%s'" % (k, v) for k, v in params.items()] ret.append('compression = {%s}' % ', '.join(param_strings)) for name, value in options_copy.items(): if value is not None: if name == "comment": value = value or "" ret.append("%s = %s" % (name, protect_value(value))) return list(sorted(ret)) +class TableMetadataV3(TableMetadata): + """ + For C* 3.0+. `option_maps` take a superset of map names, so if nothing + changes structurally, new option maps can just be appended to the list. + """ + compaction_options = {} + + option_maps = [ + 'compaction', 'compression', 'caching', + 'nodesync' # added DSE 6.0 + ] + + @property + def is_cql_compatible(self): + return True + + @classmethod + def _make_option_strings(cls, options_map): + ret = [] + options_copy = dict(options_map.items()) + + for option in cls.option_maps: + value = options_copy.get(option) + if isinstance(value, Mapping): + del options_copy[option] + params = ("'%s': '%s'" % (k, v) for k, v in value.items()) + ret.append("%s = {%s}" % (option, ', '.join(params))) + + for name, value in options_copy.items(): + if value is not None: + if name == "comment": + value = value or "" + ret.append("%s = %s" % (name, protect_value(value))) + + return list(sorted(ret)) + + +class TableMetadataDSE68(TableMetadataV3): + + vertex = None + """A :class:`.VertexMetadata` instance, if graph enabled""" + + edge = None + """A :class:`.EdgeMetadata` instance, if graph enabled""" + + def as_cql_query(self, formatted=False): + ret = super(TableMetadataDSE68, self).as_cql_query(formatted) + + if self.vertex: + ret += " AND VERTEX LABEL %s" % protect_name(self.vertex.label_name) + + if self.edge: + ret += " AND EDGE LABEL %s" % protect_name(self.edge.label_name) + + ret += self._export_edge_as_cql( + self.edge.from_label, + self.edge.from_partition_key_columns, + self.edge.from_clustering_columns, "FROM") + + ret += self._export_edge_as_cql( + self.edge.to_label, + self.edge.to_partition_key_columns, + self.edge.to_clustering_columns, "TO") + + return ret + + @staticmethod + def _export_edge_as_cql(label_name, partition_keys, + clustering_columns, keyword): + ret = " %s %s(" % (keyword, protect_name(label_name)) + + if len(partition_keys) == 1: + ret += protect_name(partition_keys[0]) + else: + ret += "(%s)" % ", ".join([protect_name(k) for k in partition_keys]) + + if clustering_columns: + ret += ", %s" % ", ".join([protect_name(k) for k in clustering_columns]) + ret += ")" + + return ret + + class TableExtensionInterface(object): """ Defines CQL/DDL for Cassandra table extensions. """ # limited API for now. Could be expanded as new extension types materialize -- "extend_option_strings", for example @classmethod def after_table_cql(cls, ext_key, ext_blob): """ Called to produce CQL/DDL to follow the table definition. Should contain requisite terminating semicolon(s). """ pass class _RegisteredExtensionType(type): _extension_registry = {} def __new__(mcs, name, bases, dct): cls = super(_RegisteredExtensionType, mcs).__new__(mcs, name, bases, dct) if name != 'RegisteredTableExtension': mcs._extension_registry[cls.name] = cls return cls @six.add_metaclass(_RegisteredExtensionType) class RegisteredTableExtension(TableExtensionInterface): """ Extending this class registers it by name (associated by key in the `system_schema.tables.extensions` map). """ name = None """ Name of the extension (key in the map) """ def protect_name(name): return maybe_escape_name(name) def protect_names(names): return [protect_name(n) for n in names] def protect_value(value): if value is None: return 'NULL' if isinstance(value, (int, float, bool)): return str(value).lower() return "'%s'" % value.replace("'", "''") valid_cql3_word_re = re.compile(r'^[a-z][0-9a-z_]*$') def is_valid_name(name): if name is None: return False if name.lower() in cql_keywords_reserved: return False return valid_cql3_word_re.match(name) is not None def maybe_escape_name(name): if is_valid_name(name): return name return escape_name(name) def escape_name(name): return '"%s"' % (name.replace('"', '""'),) class ColumnMetadata(object): """ A representation of a single column in a table. """ table = None """ The :class:`.TableMetadata` this column belongs to. """ name = None """ The string name of this column. """ cql_type = None """ The CQL type for the column. """ is_static = False """ If this column is static (available in Cassandra 2.1+), this will be :const:`True`, otherwise :const:`False`. """ is_reversed = False """ If this column is reversed (DESC) as in clustering order """ _cass_type = None def __init__(self, table_metadata, column_name, cql_type, is_static=False, is_reversed=False): self.table = table_metadata self.name = column_name self.cql_type = cql_type self.is_static = is_static self.is_reversed = is_reversed def __str__(self): return "%s %s" % (self.name, self.cql_type) class IndexMetadata(object): """ A representation of a secondary index on a column. """ keyspace_name = None """ A string name of the keyspace. """ table_name = None """ A string name of the table this index is on. """ name = None """ A string name for the index. """ kind = None """ A string representing the kind of index (COMPOSITE, CUSTOM,...). """ index_options = {} """ A dict of index options. """ def __init__(self, keyspace_name, table_name, index_name, kind, index_options): self.keyspace_name = keyspace_name self.table_name = table_name self.name = index_name self.kind = kind self.index_options = index_options def as_cql_query(self): """ Returns a CQL query that can be used to recreate this index. """ options = dict(self.index_options) index_target = options.pop("target") if self.kind != "CUSTOM": return "CREATE INDEX %s ON %s.%s (%s)" % ( protect_name(self.name), protect_name(self.keyspace_name), protect_name(self.table_name), index_target) else: class_name = options.pop("class_name") ret = "CREATE CUSTOM INDEX %s ON %s.%s (%s) USING '%s'" % ( protect_name(self.name), protect_name(self.keyspace_name), protect_name(self.table_name), index_target, class_name) if options: # PYTHON-1008: `ret` will always be a unicode opts_cql_encoded = _encoder.cql_encode_all_types(options, as_text_type=True) ret += " WITH OPTIONS = %s" % opts_cql_encoded return ret def export_as_string(self): """ Returns a CQL query string that can be used to recreate this index. """ return self.as_cql_query() + ';' class TokenMap(object): """ Information about the layout of the ring. """ token_class = None """ A subclass of :class:`.Token`, depending on what partitioner the cluster uses. """ token_to_host_owner = None """ A map of :class:`.Token` objects to the :class:`.Host` that owns that token. """ tokens_to_hosts_by_ks = None """ A map of keyspace names to a nested map of :class:`.Token` objects to sets of :class:`.Host` objects. """ ring = None """ An ordered list of :class:`.Token` instances in the ring. """ _metadata = None def __init__(self, token_class, token_to_host_owner, all_tokens, metadata): self.token_class = token_class self.ring = all_tokens self.token_to_host_owner = token_to_host_owner self.tokens_to_hosts_by_ks = {} self._metadata = metadata self._rebuild_lock = RLock() def rebuild_keyspace(self, keyspace, build_if_absent=False): with self._rebuild_lock: try: current = self.tokens_to_hosts_by_ks.get(keyspace, None) if (build_if_absent and current is None) or (not build_if_absent and current is not None): ks_meta = self._metadata.keyspaces.get(keyspace) if ks_meta: replica_map = self.replica_map_for_keyspace(self._metadata.keyspaces[keyspace]) self.tokens_to_hosts_by_ks[keyspace] = replica_map except Exception: # should not happen normally, but we don't want to blow up queries because of unexpected meta state # bypass until new map is generated self.tokens_to_hosts_by_ks[keyspace] = {} log.exception("Failed creating a token map for keyspace '%s' with %s. PLEASE REPORT THIS: https://datastax-oss.atlassian.net/projects/PYTHON", keyspace, self.token_to_host_owner) def replica_map_for_keyspace(self, ks_metadata): strategy = ks_metadata.replication_strategy if strategy: return strategy.make_token_replica_map(self.token_to_host_owner, self.ring) else: return None def remove_keyspace(self, keyspace): self.tokens_to_hosts_by_ks.pop(keyspace, None) def get_replicas(self, keyspace, token): """ Get a set of :class:`.Host` instances representing all of the replica nodes for a given :class:`.Token`. """ tokens_to_hosts = self.tokens_to_hosts_by_ks.get(keyspace, None) if tokens_to_hosts is None: self.rebuild_keyspace(keyspace, build_if_absent=True) tokens_to_hosts = self.tokens_to_hosts_by_ks.get(keyspace, None) if tokens_to_hosts: # The values in self.ring correspond to the end of the # token range up to and including the value listed. point = bisect_left(self.ring, token) if point == len(self.ring): return tokens_to_hosts[self.ring[0]] else: return tokens_to_hosts[self.ring[point]] return [] @total_ordering class Token(object): """ Abstract class representing a token. """ def __init__(self, token): self.value = token @classmethod def hash_fn(cls, key): return key @classmethod def from_key(cls, key): return cls(cls.hash_fn(key)) @classmethod def from_string(cls, token_string): raise NotImplementedError() def __eq__(self, other): return self.value == other.value def __lt__(self, other): return self.value < other.value def __hash__(self): return hash(self.value) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self.value) __str__ = __repr__ MIN_LONG = -(2 ** 63) MAX_LONG = (2 ** 63) - 1 class NoMurmur3(Exception): pass class HashToken(Token): @classmethod def from_string(cls, token_string): """ `token_string` should be the string representation from the server. """ # The hash partitioners just store the deciman value return cls(int(token_string)) class Murmur3Token(HashToken): """ A token for ``Murmur3Partitioner``. """ @classmethod def hash_fn(cls, key): if murmur3 is not None: h = int(murmur3(key)) return h if h != MIN_LONG else MAX_LONG else: raise NoMurmur3() def __init__(self, token): """ `token` is an int or string representing the token. """ self.value = int(token) class MD5Token(HashToken): """ A token for ``RandomPartitioner``. """ @classmethod def hash_fn(cls, key): if isinstance(key, six.text_type): key = key.encode('UTF-8') return abs(varint_unpack(md5(key).digest())) class BytesToken(Token): """ A token for ``ByteOrderedPartitioner``. """ @classmethod def from_string(cls, token_string): """ `token_string` should be the string representation from the server. """ # unhexlify works fine with unicode input in everythin but pypy3, where it Raises "TypeError: 'str' does not support the buffer interface" if isinstance(token_string, six.text_type): token_string = token_string.encode('ascii') # The BOP stores a hex string return cls(unhexlify(token_string)) class TriggerMetadata(object): """ A representation of a trigger for a table. """ table = None """ The :class:`.TableMetadata` this trigger belongs to. """ name = None """ The string name of this trigger. """ options = None """ A dict mapping trigger option names to their specific settings for this table. """ def __init__(self, table_metadata, trigger_name, options=None): self.table = table_metadata self.name = trigger_name self.options = options def as_cql_query(self): ret = "CREATE TRIGGER %s ON %s.%s USING %s" % ( protect_name(self.name), protect_name(self.table.keyspace_name), protect_name(self.table.name), protect_value(self.options['class']) ) return ret def export_as_string(self): return self.as_cql_query() + ';' class _SchemaParser(object): def __init__(self, connection, timeout): self.connection = connection self.timeout = timeout def _handle_results(self, success, result, expected_failures=tuple()): """ Given a bool and a ResultSet (the form returned per result from Connection.wait_for_responses), return a dictionary containing the results. Used to process results from asynchronous queries to system tables. ``expected_failures`` will usually be used to allow callers to ignore ``InvalidRequest`` errors caused by a missing system keyspace. For example, some DSE versions report a 4.X server version, but do not have virtual tables. Thus, running against 4.X servers, SchemaParserV4 uses expected_failures to make a best-effort attempt to read those keyspaces, but treat them as empty if they're not found. :param success: A boolean representing whether or not the query succeeded :param result: The resultset in question. :expected_failures: An Exception class or an iterable thereof. If the query failed, but raised an instance of an expected failure class, this will ignore the failure and return an empty list. """ if not success and isinstance(result, expected_failures): return [] elif success: - return dict_factory(*result.results) if result else [] + return dict_factory(result.column_names, result.parsed_rows) if result else [] else: raise result def _query_build_row(self, query_string, build_func): result = self._query_build_rows(query_string, build_func) return result[0] if result else None def _query_build_rows(self, query_string, build_func): query = QueryMessage(query=query_string, consistency_level=ConsistencyLevel.ONE) responses = self.connection.wait_for_responses((query), timeout=self.timeout, fail_on_error=False) (success, response) = responses[0] if success: - result = dict_factory(*response.results) + result = dict_factory(response.column_names, response.parsed_rows) return [build_func(row) for row in result] elif isinstance(response, InvalidRequest): log.debug("user types table not found") return [] else: raise response class SchemaParserV22(_SchemaParser): + """ + For C* 2.2+ + """ _SELECT_KEYSPACES = "SELECT * FROM system.schema_keyspaces" _SELECT_COLUMN_FAMILIES = "SELECT * FROM system.schema_columnfamilies" _SELECT_COLUMNS = "SELECT * FROM system.schema_columns" _SELECT_TRIGGERS = "SELECT * FROM system.schema_triggers" _SELECT_TYPES = "SELECT * FROM system.schema_usertypes" _SELECT_FUNCTIONS = "SELECT * FROM system.schema_functions" _SELECT_AGGREGATES = "SELECT * FROM system.schema_aggregates" _table_name_col = 'columnfamily_name' _function_agg_arument_type_col = 'signature' recognized_table_options = ( "comment", "read_repair_chance", "dclocal_read_repair_chance", # kept to be safe, but see _build_table_options() "local_read_repair_chance", "replicate_on_write", "gc_grace_seconds", "bloom_filter_fp_chance", "caching", "compaction_strategy_class", "compaction_strategy_options", "min_compaction_threshold", "max_compaction_threshold", "compression_parameters", "min_index_interval", "max_index_interval", "index_interval", "speculative_retry", "rows_per_partition_to_cache", "memtable_flush_period_in_ms", "populate_io_cache_on_flush", "compression", "default_time_to_live") def __init__(self, connection, timeout): super(SchemaParserV22, self).__init__(connection, timeout) self.keyspaces_result = [] self.tables_result = [] self.columns_result = [] self.triggers_result = [] self.types_result = [] self.functions_result = [] self.aggregates_result = [] self.keyspace_table_rows = defaultdict(list) self.keyspace_table_col_rows = defaultdict(lambda: defaultdict(list)) self.keyspace_type_rows = defaultdict(list) self.keyspace_func_rows = defaultdict(list) self.keyspace_agg_rows = defaultdict(list) self.keyspace_table_trigger_rows = defaultdict(lambda: defaultdict(list)) def get_all_keyspaces(self): self._query_all() for row in self.keyspaces_result: keyspace_meta = self._build_keyspace_metadata(row) try: for table_row in self.keyspace_table_rows.get(keyspace_meta.name, []): table_meta = self._build_table_metadata(table_row) keyspace_meta._add_table_metadata(table_meta) for usertype_row in self.keyspace_type_rows.get(keyspace_meta.name, []): usertype = self._build_user_type(usertype_row) keyspace_meta.user_types[usertype.name] = usertype for fn_row in self.keyspace_func_rows.get(keyspace_meta.name, []): fn = self._build_function(fn_row) keyspace_meta.functions[fn.signature] = fn for agg_row in self.keyspace_agg_rows.get(keyspace_meta.name, []): agg = self._build_aggregate(agg_row) keyspace_meta.aggregates[agg.signature] = agg except Exception: log.exception("Error while parsing metadata for keyspace %s. Metadata model will be incomplete.", keyspace_meta.name) keyspace_meta._exc_info = sys.exc_info() yield keyspace_meta def get_table(self, keyspaces, keyspace, table): cl = ConsistencyLevel.ONE where_clause = bind_params(" WHERE keyspace_name = %%s AND %s = %%s" % (self._table_name_col,), (keyspace, table), _encoder) cf_query = QueryMessage(query=self._SELECT_COLUMN_FAMILIES + where_clause, consistency_level=cl) col_query = QueryMessage(query=self._SELECT_COLUMNS + where_clause, consistency_level=cl) triggers_query = QueryMessage(query=self._SELECT_TRIGGERS + where_clause, consistency_level=cl) (cf_success, cf_result), (col_success, col_result), (triggers_success, triggers_result) \ = self.connection.wait_for_responses(cf_query, col_query, triggers_query, timeout=self.timeout, fail_on_error=False) table_result = self._handle_results(cf_success, cf_result) col_result = self._handle_results(col_success, col_result) # the triggers table doesn't exist in C* 1.2 triggers_result = self._handle_results(triggers_success, triggers_result, expected_failures=InvalidRequest) if table_result: return self._build_table_metadata(table_result[0], col_result, triggers_result) def get_type(self, keyspaces, keyspace, type): where_clause = bind_params(" WHERE keyspace_name = %s AND type_name = %s", (keyspace, type), _encoder) return self._query_build_row(self._SELECT_TYPES + where_clause, self._build_user_type) def get_types_map(self, keyspaces, keyspace): where_clause = bind_params(" WHERE keyspace_name = %s", (keyspace,), _encoder) types = self._query_build_rows(self._SELECT_TYPES + where_clause, self._build_user_type) return dict((t.name, t) for t in types) def get_function(self, keyspaces, keyspace, function): where_clause = bind_params(" WHERE keyspace_name = %%s AND function_name = %%s AND %s = %%s" % (self._function_agg_arument_type_col,), (keyspace, function.name, function.argument_types), _encoder) return self._query_build_row(self._SELECT_FUNCTIONS + where_clause, self._build_function) def get_aggregate(self, keyspaces, keyspace, aggregate): where_clause = bind_params(" WHERE keyspace_name = %%s AND aggregate_name = %%s AND %s = %%s" % (self._function_agg_arument_type_col,), (keyspace, aggregate.name, aggregate.argument_types), _encoder) return self._query_build_row(self._SELECT_AGGREGATES + where_clause, self._build_aggregate) def get_keyspace(self, keyspaces, keyspace): where_clause = bind_params(" WHERE keyspace_name = %s", (keyspace,), _encoder) return self._query_build_row(self._SELECT_KEYSPACES + where_clause, self._build_keyspace_metadata) @classmethod def _build_keyspace_metadata(cls, row): try: ksm = cls._build_keyspace_metadata_internal(row) except Exception: name = row["keyspace_name"] ksm = KeyspaceMetadata(name, False, 'UNKNOWN', {}) ksm._exc_info = sys.exc_info() # capture exc_info before log because nose (test) logging clears it in certain circumstances log.exception("Error while parsing metadata for keyspace %s row(%s)", name, row) return ksm @staticmethod def _build_keyspace_metadata_internal(row): name = row["keyspace_name"] durable_writes = row["durable_writes"] strategy_class = row["strategy_class"] strategy_options = json.loads(row["strategy_options"]) return KeyspaceMetadata(name, durable_writes, strategy_class, strategy_options) @classmethod def _build_user_type(cls, usertype_row): field_types = list(map(cls._schema_type_to_cql, usertype_row['field_types'])) return UserType(usertype_row['keyspace_name'], usertype_row['type_name'], usertype_row['field_names'], field_types) @classmethod def _build_function(cls, function_row): return_type = cls._schema_type_to_cql(function_row['return_type']) + deterministic = function_row.get('deterministic', False) + monotonic = function_row.get('monotonic', False) + monotonic_on = function_row.get('monotonic_on', ()) return Function(function_row['keyspace_name'], function_row['function_name'], function_row[cls._function_agg_arument_type_col], function_row['argument_names'], return_type, function_row['language'], function_row['body'], - function_row['called_on_null_input']) + function_row['called_on_null_input'], + deterministic, monotonic, monotonic_on) @classmethod def _build_aggregate(cls, aggregate_row): cass_state_type = types.lookup_casstype(aggregate_row['state_type']) initial_condition = aggregate_row['initcond'] if initial_condition is not None: initial_condition = _encoder.cql_encode_all_types(cass_state_type.deserialize(initial_condition, 3)) state_type = _cql_from_cass_type(cass_state_type) return_type = cls._schema_type_to_cql(aggregate_row['return_type']) return Aggregate(aggregate_row['keyspace_name'], aggregate_row['aggregate_name'], aggregate_row['signature'], aggregate_row['state_func'], state_type, - aggregate_row['final_func'], initial_condition, return_type) + aggregate_row['final_func'], initial_condition, return_type, + aggregate_row.get('deterministic', False)) def _build_table_metadata(self, row, col_rows=None, trigger_rows=None): keyspace_name = row["keyspace_name"] cfname = row[self._table_name_col] col_rows = col_rows or self.keyspace_table_col_rows[keyspace_name][cfname] trigger_rows = trigger_rows or self.keyspace_table_trigger_rows[keyspace_name][cfname] if not col_rows: # CASSANDRA-8487 log.warning("Building table metadata with no column meta for %s.%s", keyspace_name, cfname) table_meta = TableMetadata(keyspace_name, cfname) try: comparator = types.lookup_casstype(row["comparator"]) table_meta.comparator = comparator is_dct_comparator = issubclass(comparator, types.DynamicCompositeType) is_composite_comparator = issubclass(comparator, types.CompositeType) column_name_types = comparator.subtypes if is_composite_comparator else (comparator,) num_column_name_components = len(column_name_types) last_col = column_name_types[-1] column_aliases = row.get("column_aliases", None) clustering_rows = [r for r in col_rows if r.get('type', None) == "clustering_key"] if len(clustering_rows) > 1: clustering_rows = sorted(clustering_rows, key=lambda row: row.get('component_index')) if column_aliases is not None: column_aliases = json.loads(column_aliases) if not column_aliases: # json load failed or column_aliases empty PYTHON-562 column_aliases = [r.get('column_name') for r in clustering_rows] if is_composite_comparator: if issubclass(last_col, types.ColumnToCollectionType): # collections is_compact = False has_value = False clustering_size = num_column_name_components - 2 elif (len(column_aliases) == num_column_name_components - 1 and issubclass(last_col, types.UTF8Type)): # aliases? is_compact = False has_value = False clustering_size = num_column_name_components - 1 else: # compact table is_compact = True has_value = column_aliases or not col_rows clustering_size = num_column_name_components # Some thrift tables define names in composite types (see PYTHON-192) if not column_aliases and hasattr(comparator, 'fieldnames'): column_aliases = filter(None, comparator.fieldnames) else: is_compact = True if column_aliases or not col_rows or is_dct_comparator: has_value = True clustering_size = num_column_name_components else: has_value = False clustering_size = 0 # partition key partition_rows = [r for r in col_rows if r.get('type', None) == "partition_key"] if len(partition_rows) > 1: partition_rows = sorted(partition_rows, key=lambda row: row.get('component_index')) key_aliases = row.get("key_aliases") if key_aliases is not None: key_aliases = json.loads(key_aliases) if key_aliases else [] else: # In 2.0+, we can use the 'type' column. In 3.0+, we have to use it. key_aliases = [r.get('column_name') for r in partition_rows] key_validator = row.get("key_validator") if key_validator is not None: key_type = types.lookup_casstype(key_validator) key_types = key_type.subtypes if issubclass(key_type, types.CompositeType) else [key_type] else: key_types = [types.lookup_casstype(r.get('validator')) for r in partition_rows] for i, col_type in enumerate(key_types): if len(key_aliases) > i: column_name = key_aliases[i] elif i == 0: column_name = "key" else: column_name = "key%d" % i col = ColumnMetadata(table_meta, column_name, col_type.cql_parameterized_type()) table_meta.columns[column_name] = col table_meta.partition_key.append(col) # clustering key for i in range(clustering_size): if len(column_aliases) > i: column_name = column_aliases[i] else: column_name = "column%d" % (i + 1) data_type = column_name_types[i] cql_type = _cql_from_cass_type(data_type) is_reversed = types.is_reversed_casstype(data_type) col = ColumnMetadata(table_meta, column_name, cql_type, is_reversed=is_reversed) table_meta.columns[column_name] = col table_meta.clustering_key.append(col) # value alias (if present) if has_value: value_alias_rows = [r for r in col_rows if r.get('type', None) == "compact_value"] if not key_aliases: # TODO are we checking the right thing here? value_alias = "value" else: value_alias = row.get("value_alias", None) if value_alias is None and value_alias_rows: # CASSANDRA-8487 # In 2.0+, we can use the 'type' column. In 3.0+, we have to use it. value_alias = value_alias_rows[0].get('column_name') default_validator = row.get("default_validator") if default_validator: validator = types.lookup_casstype(default_validator) else: if value_alias_rows: # CASSANDRA-8487 validator = types.lookup_casstype(value_alias_rows[0].get('validator')) cql_type = _cql_from_cass_type(validator) col = ColumnMetadata(table_meta, value_alias, cql_type) if value_alias: # CASSANDRA-8487 table_meta.columns[value_alias] = col # other normal columns for col_row in col_rows: column_meta = self._build_column_metadata(table_meta, col_row) if column_meta.name is not None: table_meta.columns[column_meta.name] = column_meta index_meta = self._build_index_metadata(column_meta, col_row) if index_meta: table_meta.indexes[index_meta.name] = index_meta for trigger_row in trigger_rows: trigger_meta = self._build_trigger_metadata(table_meta, trigger_row) table_meta.triggers[trigger_meta.name] = trigger_meta table_meta.options = self._build_table_options(row) table_meta.is_compact_storage = is_compact except Exception: table_meta._exc_info = sys.exc_info() log.exception("Error while parsing metadata for table %s.%s row(%s) columns(%s)", keyspace_name, cfname, row, col_rows) return table_meta def _build_table_options(self, row): """ Setup the mostly-non-schema table options, like caching settings """ options = dict((o, row.get(o)) for o in self.recognized_table_options if o in row) # the option name when creating tables is "dclocal_read_repair_chance", # but the column name in system.schema_columnfamilies is # "local_read_repair_chance". We'll store this as dclocal_read_repair_chance, # since that's probably what users are expecting (and we need it for the # CREATE TABLE statement anyway). if "local_read_repair_chance" in options: val = options.pop("local_read_repair_chance") options["dclocal_read_repair_chance"] = val return options @classmethod def _build_column_metadata(cls, table_metadata, row): name = row["column_name"] type_string = row["validator"] data_type = types.lookup_casstype(type_string) cql_type = _cql_from_cass_type(data_type) is_static = row.get("type", None) == "static" is_reversed = types.is_reversed_casstype(data_type) column_meta = ColumnMetadata(table_metadata, name, cql_type, is_static, is_reversed) column_meta._cass_type = data_type return column_meta @staticmethod def _build_index_metadata(column_metadata, row): index_name = row.get("index_name") kind = row.get("index_type") if index_name or kind: options = row.get("index_options") options = json.loads(options) if options else {} options = options or {} # if the json parsed to None, init empty dict # generate a CQL index identity string target = protect_name(column_metadata.name) if kind != "CUSTOM": if "index_keys" in options: target = 'keys(%s)' % (target,) elif "index_values" in options: # don't use any "function" for collection values pass else: # it might be a "full" index on a frozen collection, but # we need to check the data type to verify that, because # there is no special index option for full-collection # indexes. data_type = column_metadata._cass_type collection_types = ('map', 'set', 'list') if data_type.typename == "frozen" and data_type.subtypes[0].typename in collection_types: # no index option for full-collection index target = 'full(%s)' % (target,) options['target'] = target return IndexMetadata(column_metadata.table.keyspace_name, column_metadata.table.name, index_name, kind, options) @staticmethod def _build_trigger_metadata(table_metadata, row): name = row["trigger_name"] options = row["trigger_options"] trigger_meta = TriggerMetadata(table_metadata, name, options) return trigger_meta def _query_all(self): cl = ConsistencyLevel.ONE queries = [ QueryMessage(query=self._SELECT_KEYSPACES, consistency_level=cl), QueryMessage(query=self._SELECT_COLUMN_FAMILIES, consistency_level=cl), QueryMessage(query=self._SELECT_COLUMNS, consistency_level=cl), QueryMessage(query=self._SELECT_TYPES, consistency_level=cl), QueryMessage(query=self._SELECT_FUNCTIONS, consistency_level=cl), QueryMessage(query=self._SELECT_AGGREGATES, consistency_level=cl), QueryMessage(query=self._SELECT_TRIGGERS, consistency_level=cl) ] ((ks_success, ks_result), (table_success, table_result), (col_success, col_result), (types_success, types_result), (functions_success, functions_result), (aggregates_success, aggregates_result), (triggers_success, triggers_result)) = ( self.connection.wait_for_responses(*queries, timeout=self.timeout, fail_on_error=False) ) self.keyspaces_result = self._handle_results(ks_success, ks_result) self.tables_result = self._handle_results(table_success, table_result) self.columns_result = self._handle_results(col_success, col_result) # if we're connected to Cassandra < 2.0, the triggers table will not exist if triggers_success: - self.triggers_result = dict_factory(*triggers_result.results) + self.triggers_result = dict_factory(triggers_result.column_names, triggers_result.parsed_rows) else: if isinstance(triggers_result, InvalidRequest): log.debug("triggers table not found") elif isinstance(triggers_result, Unauthorized): log.warning("this version of Cassandra does not allow access to schema_triggers metadata with authorization enabled (CASSANDRA-7967); " "The driver will operate normally, but will not reflect triggers in the local metadata model, or schema strings.") else: raise triggers_result # if we're connected to Cassandra < 2.1, the usertypes table will not exist if types_success: - self.types_result = dict_factory(*types_result.results) + self.types_result = dict_factory(types_result.column_names, types_result.parsed_rows) else: if isinstance(types_result, InvalidRequest): log.debug("user types table not found") self.types_result = {} else: raise types_result # functions were introduced in Cassandra 2.2 if functions_success: - self.functions_result = dict_factory(*functions_result.results) + self.functions_result = dict_factory(functions_result.column_names, functions_result.parsed_rows) else: if isinstance(functions_result, InvalidRequest): log.debug("user functions table not found") else: raise functions_result # aggregates were introduced in Cassandra 2.2 if aggregates_success: - self.aggregates_result = dict_factory(*aggregates_result.results) + self.aggregates_result = dict_factory(aggregates_result.column_names, aggregates_result.parsed_rows) else: if isinstance(aggregates_result, InvalidRequest): log.debug("user aggregates table not found") else: raise aggregates_result self._aggregate_results() def _aggregate_results(self): m = self.keyspace_table_rows for row in self.tables_result: m[row["keyspace_name"]].append(row) m = self.keyspace_table_col_rows for row in self.columns_result: ksname = row["keyspace_name"] cfname = row[self._table_name_col] m[ksname][cfname].append(row) m = self.keyspace_type_rows for row in self.types_result: m[row["keyspace_name"]].append(row) m = self.keyspace_func_rows for row in self.functions_result: m[row["keyspace_name"]].append(row) m = self.keyspace_agg_rows for row in self.aggregates_result: m[row["keyspace_name"]].append(row) m = self.keyspace_table_trigger_rows for row in self.triggers_result: ksname = row["keyspace_name"] cfname = row[self._table_name_col] m[ksname][cfname].append(row) @staticmethod def _schema_type_to_cql(type_string): cass_type = types.lookup_casstype(type_string) return _cql_from_cass_type(cass_type) class SchemaParserV3(SchemaParserV22): + """ + For C* 3.0+ + """ _SELECT_KEYSPACES = "SELECT * FROM system_schema.keyspaces" _SELECT_TABLES = "SELECT * FROM system_schema.tables" _SELECT_COLUMNS = "SELECT * FROM system_schema.columns" _SELECT_INDEXES = "SELECT * FROM system_schema.indexes" _SELECT_TRIGGERS = "SELECT * FROM system_schema.triggers" _SELECT_TYPES = "SELECT * FROM system_schema.types" _SELECT_FUNCTIONS = "SELECT * FROM system_schema.functions" _SELECT_AGGREGATES = "SELECT * FROM system_schema.aggregates" _SELECT_VIEWS = "SELECT * FROM system_schema.views" _table_name_col = 'table_name' _function_agg_arument_type_col = 'argument_types' + _table_metadata_class = TableMetadataV3 + recognized_table_options = ( 'bloom_filter_fp_chance', 'caching', 'cdc', 'comment', 'compaction', 'compression', 'crc_check_chance', 'dclocal_read_repair_chance', 'default_time_to_live', 'gc_grace_seconds', 'max_index_interval', 'memtable_flush_period_in_ms', 'min_index_interval', 'read_repair_chance', 'speculative_retry') def __init__(self, connection, timeout): super(SchemaParserV3, self).__init__(connection, timeout) self.indexes_result = [] self.keyspace_table_index_rows = defaultdict(lambda: defaultdict(list)) self.keyspace_view_rows = defaultdict(list) def get_all_keyspaces(self): for keyspace_meta in super(SchemaParserV3, self).get_all_keyspaces(): for row in self.keyspace_view_rows[keyspace_meta.name]: view_meta = self._build_view_metadata(row) keyspace_meta._add_view_metadata(view_meta) yield keyspace_meta def get_table(self, keyspaces, keyspace, table): cl = ConsistencyLevel.ONE where_clause = bind_params(" WHERE keyspace_name = %%s AND %s = %%s" % (self._table_name_col), (keyspace, table), _encoder) cf_query = QueryMessage(query=self._SELECT_TABLES + where_clause, consistency_level=cl) col_query = QueryMessage(query=self._SELECT_COLUMNS + where_clause, consistency_level=cl) indexes_query = QueryMessage(query=self._SELECT_INDEXES + where_clause, consistency_level=cl) triggers_query = QueryMessage(query=self._SELECT_TRIGGERS + where_clause, consistency_level=cl) # in protocol v4 we don't know if this event is a view or a table, so we look for both where_clause = bind_params(" WHERE keyspace_name = %s AND view_name = %s", (keyspace, table), _encoder) view_query = QueryMessage(query=self._SELECT_VIEWS + where_clause, consistency_level=cl) ((cf_success, cf_result), (col_success, col_result), (indexes_sucess, indexes_result), (triggers_success, triggers_result), (view_success, view_result)) = ( self.connection.wait_for_responses( cf_query, col_query, indexes_query, triggers_query, view_query, timeout=self.timeout, fail_on_error=False) ) table_result = self._handle_results(cf_success, cf_result) col_result = self._handle_results(col_success, col_result) if table_result: indexes_result = self._handle_results(indexes_sucess, indexes_result) triggers_result = self._handle_results(triggers_success, triggers_result) return self._build_table_metadata(table_result[0], col_result, triggers_result, indexes_result) view_result = self._handle_results(view_success, view_result) if view_result: return self._build_view_metadata(view_result[0], col_result) @staticmethod def _build_keyspace_metadata_internal(row): name = row["keyspace_name"] durable_writes = row["durable_writes"] strategy_options = dict(row["replication"]) strategy_class = strategy_options.pop("class") return KeyspaceMetadata(name, durable_writes, strategy_class, strategy_options) @staticmethod def _build_aggregate(aggregate_row): return Aggregate(aggregate_row['keyspace_name'], aggregate_row['aggregate_name'], aggregate_row['argument_types'], aggregate_row['state_func'], aggregate_row['state_type'], - aggregate_row['final_func'], aggregate_row['initcond'], aggregate_row['return_type']) + aggregate_row['final_func'], aggregate_row['initcond'], aggregate_row['return_type'], + aggregate_row.get('deterministic', False)) def _build_table_metadata(self, row, col_rows=None, trigger_rows=None, index_rows=None, virtual=False): keyspace_name = row["keyspace_name"] table_name = row[self._table_name_col] col_rows = col_rows or self.keyspace_table_col_rows[keyspace_name][table_name] trigger_rows = trigger_rows or self.keyspace_table_trigger_rows[keyspace_name][table_name] index_rows = index_rows or self.keyspace_table_index_rows[keyspace_name][table_name] - table_meta = TableMetadataV3(keyspace_name, table_name, virtual=virtual) + table_meta = self._table_metadata_class(keyspace_name, table_name, virtual=virtual) try: table_meta.options = self._build_table_options(row) flags = row.get('flags', set()) if flags: is_dense = 'dense' in flags compact_static = not is_dense and 'super' not in flags and 'compound' not in flags table_meta.is_compact_storage = is_dense or 'super' in flags or 'compound' not in flags elif virtual: compact_static = False table_meta.is_compact_storage = False is_dense = False else: compact_static = True table_meta.is_compact_storage = True is_dense = False self._build_table_columns(table_meta, col_rows, compact_static, is_dense, virtual) for trigger_row in trigger_rows: trigger_meta = self._build_trigger_metadata(table_meta, trigger_row) table_meta.triggers[trigger_meta.name] = trigger_meta for index_row in index_rows: index_meta = self._build_index_metadata(table_meta, index_row) if index_meta: table_meta.indexes[index_meta.name] = index_meta table_meta.extensions = row.get('extensions', {}) except Exception: table_meta._exc_info = sys.exc_info() log.exception("Error while parsing metadata for table %s.%s row(%s) columns(%s)", keyspace_name, table_name, row, col_rows) return table_meta def _build_table_options(self, row): """ Setup the mostly-non-schema table options, like caching settings """ return dict((o, row.get(o)) for o in self.recognized_table_options if o in row) def _build_table_columns(self, meta, col_rows, compact_static=False, is_dense=False, virtual=False): # partition key partition_rows = [r for r in col_rows if r.get('kind', None) == "partition_key"] if len(partition_rows) > 1: partition_rows = sorted(partition_rows, key=lambda row: row.get('position')) for r in partition_rows: # we have to add meta here (and not in the later loop) because TableMetadata.columns is an # OrderedDict, and it assumes keys are inserted first, in order, when exporting CQL column_meta = self._build_column_metadata(meta, r) meta.columns[column_meta.name] = column_meta meta.partition_key.append(meta.columns[r.get('column_name')]) # clustering key if not compact_static: clustering_rows = [r for r in col_rows if r.get('kind', None) == "clustering"] if len(clustering_rows) > 1: clustering_rows = sorted(clustering_rows, key=lambda row: row.get('position')) for r in clustering_rows: column_meta = self._build_column_metadata(meta, r) meta.columns[column_meta.name] = column_meta meta.clustering_key.append(meta.columns[r.get('column_name')]) for col_row in (r for r in col_rows if r.get('kind', None) not in ('partition_key', 'clustering_key')): column_meta = self._build_column_metadata(meta, col_row) if is_dense and column_meta.cql_type == types.cql_empty_type: continue if compact_static and not column_meta.is_static: # for compact static tables, we omit the clustering key and value, and only add the logical columns. # They are marked not static so that it generates appropriate CQL continue if compact_static: column_meta.is_static = False meta.columns[column_meta.name] = column_meta def _build_view_metadata(self, row, col_rows=None): keyspace_name = row["keyspace_name"] view_name = row["view_name"] base_table_name = row["base_table_name"] include_all_columns = row["include_all_columns"] where_clause = row["where_clause"] col_rows = col_rows or self.keyspace_table_col_rows[keyspace_name][view_name] view_meta = MaterializedViewMetadata(keyspace_name, view_name, base_table_name, include_all_columns, where_clause, self._build_table_options(row)) self._build_table_columns(view_meta, col_rows) view_meta.extensions = row.get('extensions', {}) return view_meta @staticmethod def _build_column_metadata(table_metadata, row): name = row["column_name"] cql_type = row["type"] is_static = row.get("kind", None) == "static" is_reversed = row["clustering_order"].upper() == "DESC" column_meta = ColumnMetadata(table_metadata, name, cql_type, is_static, is_reversed) return column_meta @staticmethod def _build_index_metadata(table_metadata, row): index_name = row.get("index_name") kind = row.get("kind") if index_name or kind: index_options = row.get("options") return IndexMetadata(table_metadata.keyspace_name, table_metadata.name, index_name, kind, index_options) else: return None @staticmethod def _build_trigger_metadata(table_metadata, row): name = row["trigger_name"] options = row["options"] trigger_meta = TriggerMetadata(table_metadata, name, options) return trigger_meta def _query_all(self): cl = ConsistencyLevel.ONE queries = [ QueryMessage(query=self._SELECT_KEYSPACES, consistency_level=cl), QueryMessage(query=self._SELECT_TABLES, consistency_level=cl), QueryMessage(query=self._SELECT_COLUMNS, consistency_level=cl), QueryMessage(query=self._SELECT_TYPES, consistency_level=cl), QueryMessage(query=self._SELECT_FUNCTIONS, consistency_level=cl), QueryMessage(query=self._SELECT_AGGREGATES, consistency_level=cl), QueryMessage(query=self._SELECT_TRIGGERS, consistency_level=cl), QueryMessage(query=self._SELECT_INDEXES, consistency_level=cl), QueryMessage(query=self._SELECT_VIEWS, consistency_level=cl) ] ((ks_success, ks_result), (table_success, table_result), (col_success, col_result), (types_success, types_result), (functions_success, functions_result), (aggregates_success, aggregates_result), (triggers_success, triggers_result), (indexes_success, indexes_result), (views_success, views_result)) = self.connection.wait_for_responses( *queries, timeout=self.timeout, fail_on_error=False ) self.keyspaces_result = self._handle_results(ks_success, ks_result) self.tables_result = self._handle_results(table_success, table_result) self.columns_result = self._handle_results(col_success, col_result) self.triggers_result = self._handle_results(triggers_success, triggers_result) self.types_result = self._handle_results(types_success, types_result) self.functions_result = self._handle_results(functions_success, functions_result) self.aggregates_result = self._handle_results(aggregates_success, aggregates_result) self.indexes_result = self._handle_results(indexes_success, indexes_result) self.views_result = self._handle_results(views_success, views_result) self._aggregate_results() def _aggregate_results(self): super(SchemaParserV3, self)._aggregate_results() m = self.keyspace_table_index_rows for row in self.indexes_result: ksname = row["keyspace_name"] cfname = row[self._table_name_col] m[ksname][cfname].append(row) m = self.keyspace_view_rows for row in self.views_result: m[row["keyspace_name"]].append(row) @staticmethod def _schema_type_to_cql(type_string): return type_string +class SchemaParserDSE60(SchemaParserV3): + """ + For DSE 6.0+ + """ + recognized_table_options = (SchemaParserV3.recognized_table_options + + ("nodesync",)) + + class SchemaParserV4(SchemaParserV3): - recognized_table_options = tuple( - opt for opt in - SchemaParserV3.recognized_table_options - if opt not in ( - # removed in V4: CASSANDRA-13910 - 'dclocal_read_repair_chance', 'read_repair_chance' - ) - ) + recognized_table_options = ( + 'additional_write_policy', + 'bloom_filter_fp_chance', + 'caching', + 'cdc', + 'comment', + 'compaction', + 'compression', + 'crc_check_chance', + 'default_time_to_live', + 'gc_grace_seconds', + 'max_index_interval', + 'memtable_flush_period_in_ms', + 'min_index_interval', + 'read_repair', + 'speculative_retry') _SELECT_VIRTUAL_KEYSPACES = 'SELECT * from system_virtual_schema.keyspaces' _SELECT_VIRTUAL_TABLES = 'SELECT * from system_virtual_schema.tables' _SELECT_VIRTUAL_COLUMNS = 'SELECT * from system_virtual_schema.columns' def __init__(self, connection, timeout): super(SchemaParserV4, self).__init__(connection, timeout) self.virtual_keyspaces_rows = defaultdict(list) self.virtual_tables_rows = defaultdict(list) self.virtual_columns_rows = defaultdict(lambda: defaultdict(list)) def _query_all(self): cl = ConsistencyLevel.ONE # todo: this duplicates V3; we should find a way for _query_all methods # to extend each other. queries = [ # copied from V3 QueryMessage(query=self._SELECT_KEYSPACES, consistency_level=cl), QueryMessage(query=self._SELECT_TABLES, consistency_level=cl), QueryMessage(query=self._SELECT_COLUMNS, consistency_level=cl), QueryMessage(query=self._SELECT_TYPES, consistency_level=cl), QueryMessage(query=self._SELECT_FUNCTIONS, consistency_level=cl), QueryMessage(query=self._SELECT_AGGREGATES, consistency_level=cl), QueryMessage(query=self._SELECT_TRIGGERS, consistency_level=cl), QueryMessage(query=self._SELECT_INDEXES, consistency_level=cl), QueryMessage(query=self._SELECT_VIEWS, consistency_level=cl), # V4-only queries QueryMessage(query=self._SELECT_VIRTUAL_KEYSPACES, consistency_level=cl), QueryMessage(query=self._SELECT_VIRTUAL_TABLES, consistency_level=cl), QueryMessage(query=self._SELECT_VIRTUAL_COLUMNS, consistency_level=cl) ] responses = self.connection.wait_for_responses( *queries, timeout=self.timeout, fail_on_error=False) ( # copied from V3 (ks_success, ks_result), (table_success, table_result), (col_success, col_result), (types_success, types_result), (functions_success, functions_result), (aggregates_success, aggregates_result), (triggers_success, triggers_result), (indexes_success, indexes_result), (views_success, views_result), # V4-only responses (virtual_ks_success, virtual_ks_result), (virtual_table_success, virtual_table_result), (virtual_column_success, virtual_column_result) ) = responses # copied from V3 self.keyspaces_result = self._handle_results(ks_success, ks_result) self.tables_result = self._handle_results(table_success, table_result) self.columns_result = self._handle_results(col_success, col_result) self.triggers_result = self._handle_results(triggers_success, triggers_result) self.types_result = self._handle_results(types_success, types_result) self.functions_result = self._handle_results(functions_success, functions_result) self.aggregates_result = self._handle_results(aggregates_success, aggregates_result) self.indexes_result = self._handle_results(indexes_success, indexes_result) self.views_result = self._handle_results(views_success, views_result) # V4-only results # These tables don't exist in some DSE versions reporting 4.X so we can # ignore them if we got an error self.virtual_keyspaces_result = self._handle_results( virtual_ks_success, virtual_ks_result, - expected_failures=InvalidRequest + expected_failures=(InvalidRequest,) ) self.virtual_tables_result = self._handle_results( virtual_table_success, virtual_table_result, - expected_failures=InvalidRequest + expected_failures=(InvalidRequest,) ) self.virtual_columns_result = self._handle_results( virtual_column_success, virtual_column_result, - expected_failures=InvalidRequest + expected_failures=(InvalidRequest,) ) self._aggregate_results() def _aggregate_results(self): super(SchemaParserV4, self)._aggregate_results() m = self.virtual_tables_rows for row in self.virtual_tables_result: m[row["keyspace_name"]].append(row) m = self.virtual_columns_rows for row in self.virtual_columns_result: ks_name = row['keyspace_name'] tab_name = row[self._table_name_col] m[ks_name][tab_name].append(row) def get_all_keyspaces(self): for x in super(SchemaParserV4, self).get_all_keyspaces(): yield x for row in self.virtual_keyspaces_result: ks_name = row['keyspace_name'] keyspace_meta = self._build_keyspace_metadata(row) keyspace_meta.virtual = True for table_row in self.virtual_tables_rows.get(ks_name, []): table_name = table_row[self._table_name_col] col_rows = self.virtual_columns_rows[ks_name][table_name] keyspace_meta._add_table_metadata( self._build_table_metadata(table_row, col_rows=col_rows, virtual=True) ) yield keyspace_meta @staticmethod def _build_keyspace_metadata_internal(row): # necessary fields that aren't int virtual ks row["durable_writes"] = row.get("durable_writes", None) row["replication"] = row.get("replication", {}) row["replication"]["class"] = row["replication"].get("class", None) return super(SchemaParserV4, SchemaParserV4)._build_keyspace_metadata_internal(row) -class TableMetadataV3(TableMetadata): - compaction_options = {} +class SchemaParserDSE67(SchemaParserV4): + """ + For DSE 6.7+ + """ + recognized_table_options = (SchemaParserV4.recognized_table_options + + ("nodesync",)) - option_maps = ['compaction', 'compression', 'caching'] - @property - def is_cql_compatible(self): - return True +class SchemaParserDSE68(SchemaParserDSE67): + """ + For DSE 6.8+ + """ - @classmethod - def _make_option_strings(cls, options_map): - ret = [] - options_copy = dict(options_map.items()) + _SELECT_VERTICES = "SELECT * FROM system_schema.vertices" + _SELECT_EDGES = "SELECT * FROM system_schema.edges" - for option in cls.option_maps: - value = options_copy.get(option) - if isinstance(value, Mapping): - del options_copy[option] - params = ("'%s': '%s'" % (k, v) for k, v in value.items()) - ret.append("%s = {%s}" % (option, ', '.join(params))) + _table_metadata_class = TableMetadataDSE68 - for name, value in options_copy.items(): - if value is not None: - if name == "comment": - value = value or "" - ret.append("%s = %s" % (name, protect_value(value))) + def __init__(self, connection, timeout): + super(SchemaParserDSE68, self).__init__(connection, timeout) + self.keyspace_table_vertex_rows = defaultdict(lambda: defaultdict(list)) + self.keyspace_table_edge_rows = defaultdict(lambda: defaultdict(list)) - return list(sorted(ret)) + def get_all_keyspaces(self): + for keyspace_meta in super(SchemaParserDSE68, self).get_all_keyspaces(): + self._build_graph_metadata(keyspace_meta) + yield keyspace_meta + + def get_table(self, keyspaces, keyspace, table): + table_meta = super(SchemaParserDSE68, self).get_table(keyspaces, keyspace, table) + cl = ConsistencyLevel.ONE + where_clause = bind_params(" WHERE keyspace_name = %%s AND %s = %%s" % (self._table_name_col), (keyspace, table), _encoder) + vertices_query = QueryMessage(query=self._SELECT_VERTICES + where_clause, consistency_level=cl) + edges_query = QueryMessage(query=self._SELECT_EDGES + where_clause, consistency_level=cl) + + (vertices_success, vertices_result), (edges_success, edges_result) \ + = self.connection.wait_for_responses(vertices_query, edges_query, timeout=self.timeout, fail_on_error=False) + vertices_result = self._handle_results(vertices_success, vertices_result) + edges_result = self._handle_results(edges_success, edges_result) + + try: + if vertices_result: + table_meta.vertex = self._build_table_vertex_metadata(vertices_result[0]) + elif edges_result: + table_meta.edge = self._build_table_edge_metadata(keyspaces[keyspace], edges_result[0]) + except Exception: + table_meta.vertex = None + table_meta.edge = None + table_meta._exc_info = sys.exc_info() + log.exception("Error while parsing graph metadata for table %s.%s.", keyspace, table) + + return table_meta + + @staticmethod + def _build_keyspace_metadata_internal(row): + name = row["keyspace_name"] + durable_writes = row.get("durable_writes", None) + replication = dict(row.get("replication")) if 'replication' in row else {} + replication_class = replication.pop("class") if 'class' in replication else None + graph_engine = row.get("graph_engine", None) + return KeyspaceMetadata(name, durable_writes, replication_class, replication, graph_engine) + + def _build_graph_metadata(self, keyspace_meta): + + def _build_table_graph_metadata(table_meta): + for row in self.keyspace_table_vertex_rows[keyspace_meta.name][table_meta.name]: + table_meta.vertex = self._build_table_vertex_metadata(row) + + for row in self.keyspace_table_edge_rows[keyspace_meta.name][table_meta.name]: + table_meta.edge = self._build_table_edge_metadata(keyspace_meta, row) + + try: + # Make sure we process vertices before edges + for table_meta in [t for t in six.itervalues(keyspace_meta.tables) + if t.name in self.keyspace_table_vertex_rows[keyspace_meta.name]]: + _build_table_graph_metadata(table_meta) + + # all other tables... + for table_meta in [t for t in six.itervalues(keyspace_meta.tables) + if t.name not in self.keyspace_table_vertex_rows[keyspace_meta.name]]: + _build_table_graph_metadata(table_meta) + except Exception: + # schema error, remove all graph metadata for this keyspace + for t in six.itervalues(keyspace_meta.tables): + t.edge = t.vertex = None + keyspace_meta._exc_info = sys.exc_info() + log.exception("Error while parsing graph metadata for keyspace %s", keyspace_meta.name) + + @staticmethod + def _build_table_vertex_metadata(row): + return VertexMetadata(row.get("keyspace_name"), row.get("table_name"), + row.get("label_name")) + + @staticmethod + def _build_table_edge_metadata(keyspace_meta, row): + from_table = row.get("from_table") + from_table_meta = keyspace_meta.tables.get(from_table) + from_label = from_table_meta.vertex.label_name + to_table = row.get("to_table") + to_table_meta = keyspace_meta.tables.get(to_table) + to_label = to_table_meta.vertex.label_name + + return EdgeMetadata( + row.get("keyspace_name"), row.get("table_name"), + row.get("label_name"), from_table, from_label, + row.get("from_partition_key_columns"), + row.get("from_clustering_columns"), to_table, to_label, + row.get("to_partition_key_columns"), + row.get("to_clustering_columns")) + + def _query_all(self): + cl = ConsistencyLevel.ONE + queries = [ + # copied from v4 + QueryMessage(query=self._SELECT_KEYSPACES, consistency_level=cl), + QueryMessage(query=self._SELECT_TABLES, consistency_level=cl), + QueryMessage(query=self._SELECT_COLUMNS, consistency_level=cl), + QueryMessage(query=self._SELECT_TYPES, consistency_level=cl), + QueryMessage(query=self._SELECT_FUNCTIONS, consistency_level=cl), + QueryMessage(query=self._SELECT_AGGREGATES, consistency_level=cl), + QueryMessage(query=self._SELECT_TRIGGERS, consistency_level=cl), + QueryMessage(query=self._SELECT_INDEXES, consistency_level=cl), + QueryMessage(query=self._SELECT_VIEWS, consistency_level=cl), + QueryMessage(query=self._SELECT_VIRTUAL_KEYSPACES, consistency_level=cl), + QueryMessage(query=self._SELECT_VIRTUAL_TABLES, consistency_level=cl), + QueryMessage(query=self._SELECT_VIRTUAL_COLUMNS, consistency_level=cl), + # dse6.8 only + QueryMessage(query=self._SELECT_VERTICES, consistency_level=cl), + QueryMessage(query=self._SELECT_EDGES, consistency_level=cl) + ] + + responses = self.connection.wait_for_responses( + *queries, timeout=self.timeout, fail_on_error=False) + ( + # copied from V4 + (ks_success, ks_result), + (table_success, table_result), + (col_success, col_result), + (types_success, types_result), + (functions_success, functions_result), + (aggregates_success, aggregates_result), + (triggers_success, triggers_result), + (indexes_success, indexes_result), + (views_success, views_result), + (virtual_ks_success, virtual_ks_result), + (virtual_table_success, virtual_table_result), + (virtual_column_success, virtual_column_result), + # dse6.8 responses + (vertices_success, vertices_result), + (edges_success, edges_result) + ) = responses + + # copied from V4 + self.keyspaces_result = self._handle_results(ks_success, ks_result) + self.tables_result = self._handle_results(table_success, table_result) + self.columns_result = self._handle_results(col_success, col_result) + self.triggers_result = self._handle_results(triggers_success, triggers_result) + self.types_result = self._handle_results(types_success, types_result) + self.functions_result = self._handle_results(functions_success, functions_result) + self.aggregates_result = self._handle_results(aggregates_success, aggregates_result) + self.indexes_result = self._handle_results(indexes_success, indexes_result) + self.views_result = self._handle_results(views_success, views_result) + + # These tables don't exist in some DSE versions reporting 4.X so we can + # ignore them if we got an error + self.virtual_keyspaces_result = self._handle_results( + virtual_ks_success, virtual_ks_result, + expected_failures=(InvalidRequest,) + ) + self.virtual_tables_result = self._handle_results( + virtual_table_success, virtual_table_result, + expected_failures=(InvalidRequest,) + ) + self.virtual_columns_result = self._handle_results( + virtual_column_success, virtual_column_result, + expected_failures=(InvalidRequest,) + ) + + # dse6.8-only results + self.vertices_result = self._handle_results(vertices_success, vertices_result) + self.edges_result = self._handle_results(edges_success, edges_result) + + self._aggregate_results() + + def _aggregate_results(self): + super(SchemaParserDSE68, self)._aggregate_results() + + m = self.keyspace_table_vertex_rows + for row in self.vertices_result: + ksname = row["keyspace_name"] + cfname = row['table_name'] + m[ksname][cfname].append(row) + + m = self.keyspace_table_edge_rows + for row in self.edges_result: + ksname = row["keyspace_name"] + cfname = row['table_name'] + m[ksname][cfname].append(row) class MaterializedViewMetadata(object): """ A representation of a materialized view on a table """ keyspace_name = None - - """ A string name of the view.""" + """ A string name of the keyspace of this view.""" name = None """ A string name of the view.""" base_table_name = None """ A string name of the base table for this view.""" partition_key = None """ A list of :class:`.ColumnMetadata` instances representing the columns in the partition key for this view. This will always hold at least one column. """ clustering_key = None """ A list of :class:`.ColumnMetadata` instances representing the columns in the clustering key for this view. Note that a table may have no clustering keys, in which case this will be an empty list. """ columns = None """ A dict mapping column names to :class:`.ColumnMetadata` instances. """ include_all_columns = None """ A flag indicating whether the view was created AS SELECT * """ where_clause = None """ String WHERE clause for the view select statement. From server metadata """ options = None """ A dict mapping table option names to their specific settings for this view. """ extensions = None """ Metadata describing configuration for table extensions """ def __init__(self, keyspace_name, view_name, base_table_name, include_all_columns, where_clause, options): self.keyspace_name = keyspace_name self.name = view_name self.base_table_name = base_table_name self.partition_key = [] self.clustering_key = [] self.columns = OrderedDict() self.include_all_columns = include_all_columns self.where_clause = where_clause self.options = options or {} def as_cql_query(self, formatted=False): """ Returns a CQL query that can be used to recreate this function. If `formatted` is set to :const:`True`, extra whitespace will be added to make the query more readable. """ sep = '\n ' if formatted else ' ' keyspace = protect_name(self.keyspace_name) name = protect_name(self.name) selected_cols = '*' if self.include_all_columns else ', '.join(protect_name(col.name) for col in self.columns.values()) base_table = protect_name(self.base_table_name) where_clause = self.where_clause part_key = ', '.join(protect_name(col.name) for col in self.partition_key) if len(self.partition_key) > 1: pk = "((%s)" % part_key else: pk = "(%s" % part_key if self.clustering_key: pk += ", %s" % ', '.join(protect_name(col.name) for col in self.clustering_key) pk += ")" properties = TableMetadataV3._property_string(formatted, self.clustering_key, self.options) ret = ("CREATE MATERIALIZED VIEW %(keyspace)s.%(name)s AS%(sep)s" "SELECT %(selected_cols)s%(sep)s" "FROM %(keyspace)s.%(base_table)s%(sep)s" "WHERE %(where_clause)s%(sep)s" "PRIMARY KEY %(pk)s%(sep)s" "WITH %(properties)s") % locals() if self.extensions: registry = _RegisteredExtensionType._extension_registry for k in six.viewkeys(registry) & self.extensions: # no viewkeys on OrderedMapSerializeKey ext = registry[k] cql = ext.after_table_cql(self, k, self.extensions[k]) if cql: ret += "\n\n%s" % (cql,) return ret def export_as_string(self): return self.as_cql_query(formatted=True) + ";" -def get_schema_parser(connection, server_version, timeout): +class VertexMetadata(object): + """ + A representation of a vertex on a table + """ + + keyspace_name = None + """ A string name of the keyspace. """ + + table_name = None + """ A string name of the table this vertex is on. """ + + label_name = None + """ A string name of the label of this vertex.""" + + def __init__(self, keyspace_name, table_name, label_name): + self.keyspace_name = keyspace_name + self.table_name = table_name + self.label_name = label_name + + +class EdgeMetadata(object): + """ + A representation of an edge on a table + """ + + keyspace_name = None + """A string name of the keyspace """ + + table_name = None + """A string name of the table this edge is on""" + + label_name = None + """A string name of the label of this edge""" + + from_table = None + """A string name of the from table of this edge (incoming vertex)""" + + from_label = None + """A string name of the from table label of this edge (incoming vertex)""" + + from_partition_key_columns = None + """The columns that match the partition key of the incoming vertex table.""" + + from_clustering_columns = None + """The columns that match the clustering columns of the incoming vertex table.""" + + to_table = None + """A string name of the to table of this edge (outgoing vertex)""" + + to_label = None + """A string name of the to table label of this edge (outgoing vertex)""" + + to_partition_key_columns = None + """The columns that match the partition key of the outgoing vertex table.""" + + to_clustering_columns = None + """The columns that match the clustering columns of the outgoing vertex table.""" + + def __init__( + self, keyspace_name, table_name, label_name, from_table, + from_label, from_partition_key_columns, from_clustering_columns, + to_table, to_label, to_partition_key_columns, + to_clustering_columns): + self.keyspace_name = keyspace_name + self.table_name = table_name + self.label_name = label_name + self.from_table = from_table + self.from_label = from_label + self.from_partition_key_columns = from_partition_key_columns + self.from_clustering_columns = from_clustering_columns + self.to_table = to_table + self.to_label = to_label + self.to_partition_key_columns = to_partition_key_columns + self.to_clustering_columns = to_clustering_columns + + +def get_schema_parser(connection, server_version, dse_version, timeout): version = Version(server_version) + if dse_version: + v = Version(dse_version) + if v >= Version('6.8.0'): + return SchemaParserDSE68(connection, timeout) + elif v >= Version('6.7.0'): + return SchemaParserDSE67(connection, timeout) + elif v >= Version('6.0.0'): + return SchemaParserDSE60(connection, timeout) + if version >= Version('4-a'): return SchemaParserV4(connection, timeout) - if version >= Version('3.0.0'): + elif version >= Version('3.0.0'): return SchemaParserV3(connection, timeout) else: # we could further specialize by version. Right now just refactoring the # multi-version parser we have as of C* 2.2.0rc1. return SchemaParserV22(connection, timeout) def _cql_from_cass_type(cass_type): """ A string representation of the type for this column, such as "varchar" or "map". """ if issubclass(cass_type, types.ReversedType): return cass_type.subtypes[0].cql_parameterized_type() else: return cass_type.cql_parameterized_type() +class RLACTableExtension(RegisteredTableExtension): + name = "DSE_RLACA" + + @classmethod + def after_table_cql(cls, table_meta, ext_key, ext_blob): + return "RESTRICT ROWS ON %s.%s USING %s;" % (protect_name(table_meta.keyspace_name), + protect_name(table_meta.name), + protect_name(ext_blob.decode('utf-8'))) NO_VALID_REPLICA = object() def group_keys_by_replica(session, keyspace, table, keys): """ Returns a :class:`dict` with the keys grouped per host. This can be used to more accurately group by IN clause or to batch the keys per host. If a valid replica is not found for a particular key it will be grouped under :class:`~.NO_VALID_REPLICA` Example usage:: result = group_keys_by_replica( session, "system", "peers", (("127.0.0.1", ), ("127.0.0.2", )) ) """ cluster = session.cluster partition_keys = cluster.metadata.keyspaces[keyspace].tables[table].partition_key serializers = list(types._cqltypes[partition_key.cql_type] for partition_key in partition_keys) keys_per_host = defaultdict(list) distance = cluster._default_load_balancing_policy.distance for key in keys: serialized_key = [serializer.serialize(pk, cluster.protocol_version) for serializer, pk in zip(serializers, key)] if len(serialized_key) == 1: routing_key = serialized_key[0] else: routing_key = b"".join(struct.pack(">H%dsB" % len(p), len(p), p, 0) for p in serialized_key) all_replicas = cluster.metadata.get_replicas(keyspace, routing_key) # First check if there are local replicas valid_replicas = [host for host in all_replicas if host.is_up and distance(host) == HostDistance.LOCAL] if not valid_replicas: valid_replicas = [host for host in all_replicas if host.is_up] if valid_replicas: keys_per_host[random.choice(valid_replicas)].append(key) else: # We will group under this statement all the keys for which # we haven't found a valid replica keys_per_host[NO_VALID_REPLICA].append(key) return dict(keys_per_host) + +# TODO next major reorg +class _NodeInfo(object): + """ + Internal utility functions to determine the different host addresses/ports + from a local or peers row. + """ + + @staticmethod + def get_broadcast_rpc_address(row): + # TODO next major, change the parsing logic to avoid any + # overriding of a non-null value + addr = row.get("rpc_address") + if "native_address" in row: + addr = row.get("native_address") + if "native_transport_address" in row: + addr = row.get("native_transport_address") + if not addr or addr in ["0.0.0.0", "::"]: + addr = row.get("peer") + + return addr + + @staticmethod + def get_broadcast_rpc_port(row): + port = row.get("rpc_port") + if port is None or port == 0: + port = row.get("native_port") + + return port if port and port > 0 else None + + @staticmethod + def get_broadcast_address(row): + addr = row.get("broadcast_address") + if addr is None: + addr = row.get("peer") + + return addr + + @staticmethod + def get_broadcast_port(row): + port = row.get("broadcast_port") + if port is None or port == 0: + port = row.get("peer_port") + + return port if port and port > 0 else None diff --git a/cassandra/policies.py b/cassandra/policies.py index d610666..fa1e8cf 100644 --- a/cassandra/policies.py +++ b/cassandra/policies.py @@ -1,1104 +1,1183 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from itertools import islice, cycle, groupby, repeat import logging from random import randint, shuffle from threading import Lock import socket import warnings from cassandra import WriteType as WT # This is done this way because WriteType was originally # defined here and in order not to break the API. # It may removed in the next mayor. WriteType = WT from cassandra import ConsistencyLevel, OperationTimedOut log = logging.getLogger(__name__) class HostDistance(object): """ A measure of how "distant" a node is from the client, which may influence how the load balancer distributes requests and how many connections are opened to the node. """ IGNORED = -1 """ A node with this distance should never be queried or have connections opened to it. """ LOCAL = 0 """ Nodes with ``LOCAL`` distance will be preferred for operations under some load balancing policies (such as :class:`.DCAwareRoundRobinPolicy`) and will have a greater number of connections opened against them by default. This distance is typically used for nodes within the same datacenter as the client. """ REMOTE = 1 """ Nodes with ``REMOTE`` distance will be treated as a last resort by some load balancing policies (such as :class:`.DCAwareRoundRobinPolicy`) and will have a smaller number of connections opened against them by default. This distance is typically used for nodes outside of the datacenter that the client is running in. """ class HostStateListener(object): def on_up(self, host): """ Called when a node is marked up. """ raise NotImplementedError() def on_down(self, host): """ Called when a node is marked down. """ raise NotImplementedError() def on_add(self, host): """ Called when a node is added to the cluster. The newly added node should be considered up. """ raise NotImplementedError() def on_remove(self, host): """ Called when a node is removed from the cluster. """ raise NotImplementedError() class LoadBalancingPolicy(HostStateListener): """ Load balancing policies are used to decide how to distribute requests among all possible coordinator nodes in the cluster. In particular, they may focus on querying "near" nodes (those in a local datacenter) or on querying nodes who happen to be replicas for the requested data. You may also use subclasses of :class:`.LoadBalancingPolicy` for custom behavior. """ _hosts_lock = None def __init__(self): self._hosts_lock = Lock() def distance(self, host): """ Returns a measure of how remote a :class:`~.pool.Host` is in terms of the :class:`.HostDistance` enums. """ raise NotImplementedError() def populate(self, cluster, hosts): """ This method is called to initialize the load balancing policy with a set of :class:`.Host` instances before its first use. The `cluster` parameter is an instance of :class:`.Cluster`. """ raise NotImplementedError() def make_query_plan(self, working_keyspace=None, query=None): """ Given a :class:`~.query.Statement` instance, return a iterable of :class:`.Host` instances which should be queried in that order. A generator may work well for custom implementations of this method. Note that the `query` argument may be :const:`None` when preparing statements. `working_keyspace` should be the string name of the current keyspace, as set through :meth:`.Session.set_keyspace()` or with a ``USE`` statement. """ raise NotImplementedError() def check_supported(self): """ This will be called after the cluster Metadata has been initialized. If the load balancing policy implementation cannot be supported for some reason (such as a missing C extension), this is the point at which it should raise an exception. """ pass class RoundRobinPolicy(LoadBalancingPolicy): """ A subclass of :class:`.LoadBalancingPolicy` which evenly distributes queries across all nodes in the cluster, regardless of what datacenter the nodes may be in. """ _live_hosts = frozenset(()) _position = 0 def populate(self, cluster, hosts): self._live_hosts = frozenset(hosts) if len(hosts) > 1: self._position = randint(0, len(hosts) - 1) def distance(self, host): return HostDistance.LOCAL def make_query_plan(self, working_keyspace=None, query=None): # not thread-safe, but we don't care much about lost increments # for the purposes of load balancing pos = self._position self._position += 1 hosts = self._live_hosts length = len(hosts) if length: pos %= length return islice(cycle(hosts), pos, pos + length) else: return [] def on_up(self, host): with self._hosts_lock: self._live_hosts = self._live_hosts.union((host, )) def on_down(self, host): with self._hosts_lock: self._live_hosts = self._live_hosts.difference((host, )) def on_add(self, host): with self._hosts_lock: self._live_hosts = self._live_hosts.union((host, )) def on_remove(self, host): with self._hosts_lock: self._live_hosts = self._live_hosts.difference((host, )) class DCAwareRoundRobinPolicy(LoadBalancingPolicy): """ Similar to :class:`.RoundRobinPolicy`, but prefers hosts in the local datacenter and only uses nodes in remote datacenters as a last resort. """ local_dc = None used_hosts_per_remote_dc = 0 def __init__(self, local_dc='', used_hosts_per_remote_dc=0): """ The `local_dc` parameter should be the name of the datacenter (such as is reported by ``nodetool ring``) that should be considered local. If not specified, the driver will choose a local_dc based on the first host among :attr:`.Cluster.contact_points` having a valid DC. If relying on this mechanism, all specified contact points should be nodes in a single, local DC. `used_hosts_per_remote_dc` controls how many nodes in each remote datacenter will have connections opened against them. In other words, `used_hosts_per_remote_dc` hosts will be considered :attr:`~.HostDistance.REMOTE` and the rest will be considered :attr:`~.HostDistance.IGNORED`. By default, all remote hosts are ignored. """ self.local_dc = local_dc self.used_hosts_per_remote_dc = used_hosts_per_remote_dc self._dc_live_hosts = {} self._position = 0 self._endpoints = [] LoadBalancingPolicy.__init__(self) def _dc(self, host): return host.datacenter or self.local_dc def populate(self, cluster, hosts): for dc, dc_hosts in groupby(hosts, lambda h: self._dc(h)): self._dc_live_hosts[dc] = tuple(set(dc_hosts)) if not self.local_dc: self._endpoints = [ endpoint for endpoint in cluster.endpoints_resolved] self._position = randint(0, len(hosts) - 1) if hosts else 0 def distance(self, host): dc = self._dc(host) if dc == self.local_dc: return HostDistance.LOCAL if not self.used_hosts_per_remote_dc: return HostDistance.IGNORED else: dc_hosts = self._dc_live_hosts.get(dc) if not dc_hosts: return HostDistance.IGNORED if host in list(dc_hosts)[:self.used_hosts_per_remote_dc]: return HostDistance.REMOTE else: return HostDistance.IGNORED def make_query_plan(self, working_keyspace=None, query=None): # not thread-safe, but we don't care much about lost increments # for the purposes of load balancing pos = self._position self._position += 1 local_live = self._dc_live_hosts.get(self.local_dc, ()) pos = (pos % len(local_live)) if local_live else 0 for host in islice(cycle(local_live), pos, pos + len(local_live)): yield host # the dict can change, so get candidate DCs iterating over keys of a copy other_dcs = [dc for dc in self._dc_live_hosts.copy().keys() if dc != self.local_dc] for dc in other_dcs: remote_live = self._dc_live_hosts.get(dc, ()) for host in remote_live[:self.used_hosts_per_remote_dc]: yield host def on_up(self, host): # not worrying about threads because this will happen during # control connection startup/refresh if not self.local_dc and host.datacenter: if host.endpoint in self._endpoints: self.local_dc = host.datacenter log.info("Using datacenter '%s' for DCAwareRoundRobinPolicy (via host '%s'); " "if incorrect, please specify a local_dc to the constructor, " "or limit contact points to local cluster nodes" % (self.local_dc, host.endpoint)) del self._endpoints dc = self._dc(host) with self._hosts_lock: current_hosts = self._dc_live_hosts.get(dc, ()) if host not in current_hosts: self._dc_live_hosts[dc] = current_hosts + (host, ) def on_down(self, host): dc = self._dc(host) with self._hosts_lock: current_hosts = self._dc_live_hosts.get(dc, ()) if host in current_hosts: hosts = tuple(h for h in current_hosts if h != host) if hosts: self._dc_live_hosts[dc] = hosts else: del self._dc_live_hosts[dc] def on_add(self, host): self.on_up(host) def on_remove(self, host): self.on_down(host) class TokenAwarePolicy(LoadBalancingPolicy): """ A :class:`.LoadBalancingPolicy` wrapper that adds token awareness to a child policy. This alters the child policy's behavior so that it first attempts to send queries to :attr:`~.HostDistance.LOCAL` replicas (as determined by the child policy) based on the :class:`.Statement`'s :attr:`~.Statement.routing_key`. If :attr:`.shuffle_replicas` is truthy, these replicas will be yielded in a random order. Once those hosts are exhausted, the remaining hosts in the child policy's query plan will be used in the order provided by the child policy. If no :attr:`~.Statement.routing_key` is set on the query, the child policy's query plan will be used as is. """ _child_policy = None _cluster_metadata = None shuffle_replicas = False """ Yield local replicas in a random order. """ def __init__(self, child_policy, shuffle_replicas=False): self._child_policy = child_policy self.shuffle_replicas = shuffle_replicas def populate(self, cluster, hosts): self._cluster_metadata = cluster.metadata self._child_policy.populate(cluster, hosts) def check_supported(self): if not self._cluster_metadata.can_support_partitioner(): raise RuntimeError( '%s cannot be used with the cluster partitioner (%s) because ' 'the relevant C extension for this driver was not compiled. ' 'See the installation instructions for details on building ' 'and installing the C extensions.' % (self.__class__.__name__, self._cluster_metadata.partitioner)) def distance(self, *args, **kwargs): return self._child_policy.distance(*args, **kwargs) def make_query_plan(self, working_keyspace=None, query=None): if query and query.keyspace: keyspace = query.keyspace else: keyspace = working_keyspace child = self._child_policy if query is None: for host in child.make_query_plan(keyspace, query): yield host else: routing_key = query.routing_key if routing_key is None or keyspace is None: for host in child.make_query_plan(keyspace, query): yield host else: replicas = self._cluster_metadata.get_replicas(keyspace, routing_key) if self.shuffle_replicas: shuffle(replicas) for replica in replicas: if replica.is_up and \ child.distance(replica) == HostDistance.LOCAL: yield replica for host in child.make_query_plan(keyspace, query): # skip if we've already listed this host if host not in replicas or \ child.distance(host) == HostDistance.REMOTE: yield host def on_up(self, *args, **kwargs): return self._child_policy.on_up(*args, **kwargs) def on_down(self, *args, **kwargs): return self._child_policy.on_down(*args, **kwargs) def on_add(self, *args, **kwargs): return self._child_policy.on_add(*args, **kwargs) def on_remove(self, *args, **kwargs): return self._child_policy.on_remove(*args, **kwargs) class WhiteListRoundRobinPolicy(RoundRobinPolicy): """ A subclass of :class:`.RoundRobinPolicy` which evenly distributes queries across all nodes in the cluster, regardless of what datacenter the nodes may be in, but only if that node exists in the list of allowed nodes This policy is addresses the issue described in https://datastax-oss.atlassian.net/browse/JAVA-145 Where connection errors occur when connection attempts are made to private IP addresses remotely """ def __init__(self, hosts): """ The `hosts` parameter should be a sequence of hosts to permit connections to. """ - self._allowed_hosts = hosts + self._allowed_hosts = tuple(hosts) self._allowed_hosts_resolved = [endpoint[4][0] for a in self._allowed_hosts for endpoint in socket.getaddrinfo(a, None, socket.AF_UNSPEC, socket.SOCK_STREAM)] RoundRobinPolicy.__init__(self) def populate(self, cluster, hosts): self._live_hosts = frozenset(h for h in hosts if h.address in self._allowed_hosts_resolved) if len(hosts) <= 1: self._position = 0 else: self._position = randint(0, len(hosts) - 1) def distance(self, host): if host.address in self._allowed_hosts_resolved: return HostDistance.LOCAL else: return HostDistance.IGNORED def on_up(self, host): if host.address in self._allowed_hosts_resolved: RoundRobinPolicy.on_up(self, host) def on_add(self, host): if host.address in self._allowed_hosts_resolved: RoundRobinPolicy.on_add(self, host) class HostFilterPolicy(LoadBalancingPolicy): """ A :class:`.LoadBalancingPolicy` subclass configured with a child policy, and a single-argument predicate. This policy defers to the child policy for hosts where ``predicate(host)`` is truthy. Hosts for which ``predicate(host)`` is falsey will be considered :attr:`.IGNORED`, and will not be used in a query plan. This can be used in the cases where you need a whitelist or blacklist policy, e.g. to prepare for decommissioning nodes or for testing: .. code-block:: python def address_is_ignored(host): return host.address in [ignored_address0, ignored_address1] blacklist_filter_policy = HostFilterPolicy( child_policy=RoundRobinPolicy(), predicate=address_is_ignored ) cluster = Cluster( primary_host, load_balancing_policy=blacklist_filter_policy, ) See the note in the :meth:`.make_query_plan` documentation for a caveat on how wrapping ordering polices (e.g. :class:`.RoundRobinPolicy`) may break desirable properties of the wrapped policy. Please note that whitelist and blacklist policies are not recommended for general, day-to-day use. You probably want something like :class:`.DCAwareRoundRobinPolicy`, which prefers a local DC but has fallbacks, over a brute-force method like whitelisting or blacklisting. """ def __init__(self, child_policy, predicate): """ :param child_policy: an instantiated :class:`.LoadBalancingPolicy` that this one will defer to. :param predicate: a one-parameter function that takes a :class:`.Host`. If it returns a falsey value, the :class:`.Host` will be :attr:`.IGNORED` and not returned in query plans. """ super(HostFilterPolicy, self).__init__() self._child_policy = child_policy self._predicate = predicate def on_up(self, host, *args, **kwargs): return self._child_policy.on_up(host, *args, **kwargs) def on_down(self, host, *args, **kwargs): return self._child_policy.on_down(host, *args, **kwargs) def on_add(self, host, *args, **kwargs): return self._child_policy.on_add(host, *args, **kwargs) def on_remove(self, host, *args, **kwargs): return self._child_policy.on_remove(host, *args, **kwargs) @property def predicate(self): """ A predicate, set on object initialization, that takes a :class:`.Host` and returns a value. If the value is falsy, the :class:`.Host` is :class:`~HostDistance.IGNORED`. If the value is truthy, :class:`.HostFilterPolicy` defers to the child policy to determine the host's distance. This is a read-only value set in ``__init__``, implemented as a ``property``. """ return self._predicate def distance(self, host): """ Checks if ``predicate(host)``, then returns :attr:`~HostDistance.IGNORED` if falsey, and defers to the child policy otherwise. """ if self.predicate(host): return self._child_policy.distance(host) else: return HostDistance.IGNORED def populate(self, cluster, hosts): self._child_policy.populate(cluster=cluster, hosts=hosts) def make_query_plan(self, working_keyspace=None, query=None): """ Defers to the child policy's :meth:`.LoadBalancingPolicy.make_query_plan` and filters the results. Note that this filtering may break desirable properties of the wrapped policy in some cases. For instance, imagine if you configure this policy to filter out ``host2``, and to wrap a round-robin policy that rotates through three hosts in the order ``host1, host2, host3``, ``host2, host3, host1``, ``host3, host1, host2``, repeating. This policy will yield ``host1, host3``, ``host3, host1``, ``host3, host1``, disproportionately favoring ``host3``. """ child_qp = self._child_policy.make_query_plan( working_keyspace=working_keyspace, query=query ) for host in child_qp: if self.predicate(host): yield host def check_supported(self): return self._child_policy.check_supported() class ConvictionPolicy(object): """ A policy which decides when hosts should be considered down based on the types of failures and the number of failures. If custom behavior is needed, this class may be subclassed. """ def __init__(self, host): """ `host` is an instance of :class:`.Host`. """ self.host = host def add_failure(self, connection_exc): """ Implementations should return :const:`True` if the host should be convicted, :const:`False` otherwise. """ raise NotImplementedError() def reset(self): """ Implementations should clear out any convictions or state regarding the host. """ raise NotImplementedError() class SimpleConvictionPolicy(ConvictionPolicy): """ The default implementation of :class:`ConvictionPolicy`, which simply marks a host as down after the first failure of any kind. """ def add_failure(self, connection_exc): return not isinstance(connection_exc, OperationTimedOut) def reset(self): pass class ReconnectionPolicy(object): """ This class and its subclasses govern how frequently an attempt is made to reconnect to nodes that are marked as dead. If custom behavior is needed, this class may be subclassed. """ def new_schedule(self): """ This should return a finite or infinite iterable of delays (each as a floating point number of seconds) inbetween each failed reconnection attempt. Note that if the iterable is finite, reconnection attempts will cease once the iterable is exhausted. """ raise NotImplementedError() class ConstantReconnectionPolicy(ReconnectionPolicy): """ A :class:`.ReconnectionPolicy` subclass which sleeps for a fixed delay inbetween each reconnection attempt. """ def __init__(self, delay, max_attempts=64): """ `delay` should be a floating point number of seconds to wait inbetween each attempt. `max_attempts` should be a total number of attempts to be made before giving up, or :const:`None` to continue reconnection attempts forever. The default is 64. """ if delay < 0: raise ValueError("delay must not be negative") if max_attempts is not None and max_attempts < 0: raise ValueError("max_attempts must not be negative") self.delay = delay self.max_attempts = max_attempts def new_schedule(self): if self.max_attempts: return repeat(self.delay, self.max_attempts) return repeat(self.delay) class ExponentialReconnectionPolicy(ReconnectionPolicy): """ A :class:`.ReconnectionPolicy` subclass which exponentially increases the length of the delay inbetween each reconnection attempt up to a set maximum delay. A random amount of jitter (+/- 15%) will be added to the pure exponential delay value to avoid the situations where many reconnection handlers are trying to reconnect at exactly the same time. """ # TODO: max_attempts is 64 to preserve legacy default behavior # consider changing to None in major release to prevent the policy # giving up forever def __init__(self, base_delay, max_delay, max_attempts=64): """ `base_delay` and `max_delay` should be in floating point units of seconds. `max_attempts` should be a total number of attempts to be made before giving up, or :const:`None` to continue reconnection attempts forever. The default is 64. """ if base_delay < 0 or max_delay < 0: raise ValueError("Delays may not be negative") if max_delay < base_delay: raise ValueError("Max delay must be greater than base delay") if max_attempts is not None and max_attempts < 0: raise ValueError("max_attempts must not be negative") self.base_delay = base_delay self.max_delay = max_delay self.max_attempts = max_attempts def new_schedule(self): i, overflowed = 0, False while self.max_attempts is None or i < self.max_attempts: if overflowed: yield self.max_delay else: try: yield self._add_jitter(min(self.base_delay * (2 ** i), self.max_delay)) except OverflowError: overflowed = True yield self.max_delay i += 1 # Adds -+ 15% to the delay provided def _add_jitter(self, value): jitter = randint(85, 115) delay = (jitter * value) / 100 return min(max(self.base_delay, delay), self.max_delay) class RetryPolicy(object): """ A policy that describes whether to retry, rethrow, or ignore coordinator timeout and unavailable failures. These are failures reported from the server side. Timeouts are configured by `settings in cassandra.yaml `_. Unavailable failures occur when the coordinator cannot acheive the consistency level for a request. For further information see the method descriptions below. To specify a default retry policy, set the :attr:`.Cluster.default_retry_policy` attribute to an instance of this class or one of its subclasses. To specify a retry policy per query, set the :attr:`.Statement.retry_policy` attribute to an instance of this class or one of its subclasses. If custom behavior is needed for retrying certain operations, this class may be subclassed. """ RETRY = 0 """ This should be returned from the below methods if the operation should be retried on the same connection. """ RETHROW = 1 """ This should be returned from the below methods if the failure should be propagated and no more retries attempted. """ IGNORE = 2 """ This should be returned from the below methods if the failure should be ignored but no more retries should be attempted. """ RETRY_NEXT_HOST = 3 """ This should be returned from the below methods if the operation should be retried on another connection. """ def on_read_timeout(self, query, consistency, required_responses, received_responses, data_retrieved, retry_num): """ This is called when a read operation times out from the coordinator's perspective (i.e. a replica did not respond to the coordinator in time). It should return a tuple with two items: one of the class enums (such as :attr:`.RETRY`) and a :class:`.ConsistencyLevel` to retry the operation at or :const:`None` to keep the same consistency level. `query` is the :class:`.Statement` that timed out. `consistency` is the :class:`.ConsistencyLevel` that the operation was attempted at. The `required_responses` and `received_responses` parameters describe how many replicas needed to respond to meet the requested consistency level and how many actually did respond before the coordinator timed out the request. `data_retrieved` is a boolean indicating whether any of those responses contained data (as opposed to just a digest). `retry_num` counts how many times the operation has been retried, so the first time this method is called, `retry_num` will be 0. By default, operations will be retried at most once, and only if a sufficient number of replicas responded (with data digests). """ if retry_num != 0: return self.RETHROW, None elif received_responses >= required_responses and not data_retrieved: return self.RETRY, consistency else: return self.RETHROW, None def on_write_timeout(self, query, consistency, write_type, required_responses, received_responses, retry_num): """ This is called when a write operation times out from the coordinator's perspective (i.e. a replica did not respond to the coordinator in time). `query` is the :class:`.Statement` that timed out. `consistency` is the :class:`.ConsistencyLevel` that the operation was attempted at. `write_type` is one of the :class:`.WriteType` enums describing the type of write operation. The `required_responses` and `received_responses` parameters describe how many replicas needed to acknowledge the write to meet the requested consistency level and how many replicas actually did acknowledge the write before the coordinator timed out the request. `retry_num` counts how many times the operation has been retried, so the first time this method is called, `retry_num` will be 0. By default, failed write operations will retried at most once, and they will only be retried if the `write_type` was :attr:`~.WriteType.BATCH_LOG`. """ if retry_num != 0: return self.RETHROW, None elif write_type == WriteType.BATCH_LOG: return self.RETRY, consistency else: return self.RETHROW, None def on_unavailable(self, query, consistency, required_replicas, alive_replicas, retry_num): """ This is called when the coordinator node determines that a read or write operation cannot be successful because the number of live replicas are too low to meet the requested :class:`.ConsistencyLevel`. This means that the read or write operation was never forwarded to any replicas. `query` is the :class:`.Statement` that failed. `consistency` is the :class:`.ConsistencyLevel` that the operation was attempted at. `required_replicas` is the number of replicas that would have needed to acknowledge the operation to meet the requested consistency level. `alive_replicas` is the number of replicas that the coordinator considered alive at the time of the request. `retry_num` counts how many times the operation has been retried, so the first time this method is called, `retry_num` will be 0. By default, if this is the first retry, it triggers a retry on the next host in the query plan with the same consistency level. If this is not the first retry, no retries will be attempted and the error will be re-raised. """ return (self.RETRY_NEXT_HOST, None) if retry_num == 0 else (self.RETHROW, None) def on_request_error(self, query, consistency, error, retry_num): """ This is called when an unexpected error happens. This can be in the following situations: * On a connection error * On server errors: overloaded, isBootstrapping, serverError, etc. `query` is the :class:`.Statement` that timed out. `consistency` is the :class:`.ConsistencyLevel` that the operation was attempted at. `error` the instance of the exception. `retry_num` counts how many times the operation has been retried, so the first time this method is called, `retry_num` will be 0. The default, it triggers a retry on the next host in the query plan with the same consistency level. """ # TODO revisit this for the next major # To preserve the same behavior than before, we don't take retry_num into account return self.RETRY_NEXT_HOST, None class FallthroughRetryPolicy(RetryPolicy): """ A retry policy that never retries and always propagates failures to the application. """ def on_read_timeout(self, *args, **kwargs): return self.RETHROW, None def on_write_timeout(self, *args, **kwargs): return self.RETHROW, None def on_unavailable(self, *args, **kwargs): return self.RETHROW, None def on_request_error(self, *args, **kwargs): return self.RETHROW, None class DowngradingConsistencyRetryPolicy(RetryPolicy): """ *Deprecated:* This retry policy will be removed in the next major release. A retry policy that sometimes retries with a lower consistency level than the one initially requested. **BEWARE**: This policy may retry queries using a lower consistency level than the one initially requested. By doing so, it may break consistency guarantees. In other words, if you use this retry policy, there are cases (documented below) where a read at :attr:`~.QUORUM` *may not* see a preceding write at :attr:`~.QUORUM`. Do not use this policy unless you have understood the cases where this can happen and are ok with that. It is also recommended to subclass this class so that queries that required a consistency level downgrade can be recorded (so that repairs can be made later, etc). This policy implements the same retries as :class:`.RetryPolicy`, but on top of that, it also retries in the following cases: * On a read timeout: if the number of replicas that responded is greater than one but lower than is required by the requested consistency level, the operation is retried at a lower consistency level. * On a write timeout: if the operation is an :attr:`~.UNLOGGED_BATCH` and at least one replica acknowledged the write, the operation is retried at a lower consistency level. Furthermore, for other write types, if at least one replica acknowledged the write, the timeout is ignored. * On an unavailable exception: if at least one replica is alive, the operation is retried at a lower consistency level. The reasoning behind this retry policy is as follows: if, based on the information the Cassandra coordinator node returns, retrying the operation with the initially requested consistency has a chance to succeed, do it. Otherwise, if based on that information we know the initially requested consistency level cannot be achieved currently, then: * For writes, ignore the exception (thus silently failing the consistency requirement) if we know the write has been persisted on at least one replica. * For reads, try reading at a lower consistency level (thus silently failing the consistency requirement). In other words, this policy implements the idea that if the requested consistency level cannot be achieved, the next best thing for writes is to make sure the data is persisted, and that reading something is better than reading nothing, even if there is a risk of reading stale data. """ def __init__(self, *args, **kwargs): super(DowngradingConsistencyRetryPolicy, self).__init__(*args, **kwargs) warnings.warn('DowngradingConsistencyRetryPolicy is deprecated ' 'and will be removed in the next major release.', DeprecationWarning) def _pick_consistency(self, num_responses): if num_responses >= 3: return self.RETRY, ConsistencyLevel.THREE elif num_responses >= 2: return self.RETRY, ConsistencyLevel.TWO elif num_responses >= 1: return self.RETRY, ConsistencyLevel.ONE else: return self.RETHROW, None def on_read_timeout(self, query, consistency, required_responses, received_responses, data_retrieved, retry_num): if retry_num != 0: return self.RETHROW, None elif ConsistencyLevel.is_serial(consistency): # Downgrading does not make sense for a CAS read query return self.RETHROW, None elif received_responses < required_responses: return self._pick_consistency(received_responses) elif not data_retrieved: return self.RETRY, consistency else: return self.RETHROW, None def on_write_timeout(self, query, consistency, write_type, required_responses, received_responses, retry_num): if retry_num != 0: return self.RETHROW, None if write_type in (WriteType.SIMPLE, WriteType.BATCH, WriteType.COUNTER): if received_responses > 0: # persisted on at least one replica return self.IGNORE, None else: return self.RETHROW, None elif write_type == WriteType.UNLOGGED_BATCH: return self._pick_consistency(received_responses) elif write_type == WriteType.BATCH_LOG: return self.RETRY, consistency return self.RETHROW, None def on_unavailable(self, query, consistency, required_replicas, alive_replicas, retry_num): if retry_num != 0: return self.RETHROW, None elif ConsistencyLevel.is_serial(consistency): # failed at the paxos phase of a LWT, retry on the next host return self.RETRY_NEXT_HOST, None else: return self._pick_consistency(alive_replicas) class AddressTranslator(object): """ Interface for translating cluster-defined endpoints. The driver discovers nodes using server metadata and topology change events. Normally, the endpoint defined by the server is the right way to connect to a node. In some environments, these addresses may not be reachable, or not preferred (public vs. private IPs in cloud environments, suboptimal routing, etc). This interface allows for translating from server defined endpoints to preferred addresses for driver connections. *Note:* :attr:`~Cluster.contact_points` provided while creating the :class:`~.Cluster` instance are not translated using this mechanism -- only addresses received from Cassandra nodes are. """ def translate(self, addr): """ Accepts the node ip address, and returns a translated address to be used connecting to this node. """ raise NotImplementedError() class IdentityTranslator(AddressTranslator): """ Returns the endpoint with no translation """ def translate(self, addr): return addr class EC2MultiRegionTranslator(AddressTranslator): """ Resolves private ips of the hosts in the same datacenter as the client, and public ips of hosts in other datacenters. """ def translate(self, addr): """ Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which will point to the private IP address within the same datacenter. """ # get family of this address so we translate to the same family = socket.getaddrinfo(addr, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)[0][0] host = socket.getfqdn(addr) for a in socket.getaddrinfo(host, 0, family, socket.SOCK_STREAM): try: return a[4][0] except Exception: pass return addr class SpeculativeExecutionPolicy(object): """ Interface for specifying speculative execution plans """ def new_plan(self, keyspace, statement): """ Returns :param keyspace: :param statement: :return: """ raise NotImplementedError() class SpeculativeExecutionPlan(object): def next_execution(self, host): raise NotImplementedError() class NoSpeculativeExecutionPlan(SpeculativeExecutionPlan): def next_execution(self, host): return -1 class NoSpeculativeExecutionPolicy(SpeculativeExecutionPolicy): def new_plan(self, keyspace, statement): return NoSpeculativeExecutionPlan() class ConstantSpeculativeExecutionPolicy(SpeculativeExecutionPolicy): """ A speculative execution policy that sends a new query every X seconds (**delay**) for a maximum of Y attempts (**max_attempts**). """ def __init__(self, delay, max_attempts): self.delay = delay self.max_attempts = max_attempts class ConstantSpeculativeExecutionPlan(SpeculativeExecutionPlan): def __init__(self, delay, max_attempts): self.delay = delay self.remaining = max_attempts def next_execution(self, host): if self.remaining > 0: self.remaining -= 1 return self.delay else: return -1 def new_plan(self, keyspace, statement): return self.ConstantSpeculativeExecutionPlan(self.delay, self.max_attempts) + + +class WrapperPolicy(LoadBalancingPolicy): + + def __init__(self, child_policy): + self._child_policy = child_policy + + def distance(self, *args, **kwargs): + return self._child_policy.distance(*args, **kwargs) + + def populate(self, cluster, hosts): + self._child_policy.populate(cluster, hosts) + + def on_up(self, *args, **kwargs): + return self._child_policy.on_up(*args, **kwargs) + + def on_down(self, *args, **kwargs): + return self._child_policy.on_down(*args, **kwargs) + + def on_add(self, *args, **kwargs): + return self._child_policy.on_add(*args, **kwargs) + + def on_remove(self, *args, **kwargs): + return self._child_policy.on_remove(*args, **kwargs) + + +class DefaultLoadBalancingPolicy(WrapperPolicy): + """ + A :class:`.LoadBalancingPolicy` wrapper that adds the ability to target a specific host first. + + If no host is set on the query, the child policy's query plan will be used as is. + """ + + _cluster_metadata = None + + def populate(self, cluster, hosts): + self._cluster_metadata = cluster.metadata + self._child_policy.populate(cluster, hosts) + + def make_query_plan(self, working_keyspace=None, query=None): + if query and query.keyspace: + keyspace = query.keyspace + else: + keyspace = working_keyspace + + # TODO remove next major since execute(..., host=XXX) is now available + addr = getattr(query, 'target_host', None) if query else None + target_host = self._cluster_metadata.get_host(addr) + + child = self._child_policy + if target_host and target_host.is_up: + yield target_host + for h in child.make_query_plan(keyspace, query): + if h != target_host: + yield h + else: + for h in child.make_query_plan(keyspace, query): + yield h + + +# TODO for backward compatibility, remove in next major +class DSELoadBalancingPolicy(DefaultLoadBalancingPolicy): + """ + *Deprecated:* This will be removed in the next major release, + consider using :class:`.DefaultLoadBalancingPolicy`. + """ + def __init__(self, *args, **kwargs): + super(DSELoadBalancingPolicy, self).__init__(*args, **kwargs) + warnings.warn("DSELoadBalancingPolicy will be removed in 4.0. Consider using " + "DefaultLoadBalancingPolicy.", DeprecationWarning) + + +class NeverRetryPolicy(RetryPolicy): + def _rethrow(self, *args, **kwargs): + return self.RETHROW, None + + on_read_timeout = _rethrow + on_write_timeout = _rethrow + on_unavailable = _rethrow diff --git a/cassandra/pool.py b/cassandra/pool.py index cd814ef..cd27656 100644 --- a/cassandra/pool.py +++ b/cassandra/pool.py @@ -1,818 +1,866 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Connection pooling and host management. """ from functools import total_ordering import logging import socket import time from threading import Lock, RLock, Condition import weakref try: from weakref import WeakSet except ImportError: from cassandra.util import WeakSet # NOQA from cassandra import AuthenticationFailed from cassandra.connection import ConnectionException, EndPoint, DefaultEndPoint from cassandra.policies import HostDistance log = logging.getLogger(__name__) class NoConnectionsAvailable(Exception): """ All existing connections to a given host are busy, or there are no open connections. """ pass @total_ordering class Host(object): """ Represents a single Cassandra node. """ endpoint = None """ The :class:`~.connection.EndPoint` to connect to the node. """ broadcast_address = None """ - broadcast address configured for the node, *if available* ('peer' in system.peers table). - This is not present in the ``system.local`` table for older versions of Cassandra. It is also not queried if - :attr:`~.Cluster.token_metadata_enabled` is ``False``. + broadcast address configured for the node, *if available*: + + 'system.local.broadcast_address' or 'system.peers.peer' (Cassandra 2-3) + 'system.local.broadcast_address' or 'system.peers_v2.peer' (Cassandra 4) + + This is not present in the ``system.local`` table for older versions of Cassandra. It + is also not queried if :attr:`~.Cluster.token_metadata_enabled` is ``False``. + """ + + broadcast_port = None + """ + broadcast port configured for the node, *if available*: + + 'system.local.broadcast_port' or 'system.peers_v2.peer_port' (Cassandra 4) + + It is also not queried if :attr:`~.Cluster.token_metadata_enabled` is ``False``. """ broadcast_rpc_address = None """ - The broadcast rpc address of the node (`native_address` or `rpc_address`). + The broadcast rpc address of the node: + + 'system.local.rpc_address' or 'system.peers.rpc_address' (Cassandra 3) + 'system.local.rpc_address' or 'system.peers.native_transport_address (DSE 6+)' + 'system.local.rpc_address' or 'system.peers_v2.native_address (Cassandra 4)' + """ + + broadcast_rpc_port = None + """ + The broadcast rpc port of the node, *if available*: + + 'system.local.rpc_port' or 'system.peers.native_transport_port' (DSE 6+) + 'system.local.rpc_port' or 'system.peers_v2.native_port' (Cassandra 4) """ listen_address = None """ - listen address configured for the node, *if available*. This is only available in the ``system.local`` table for newer - versions of Cassandra. It is also not queried if :attr:`~.Cluster.token_metadata_enabled` is ``False``. - Usually the same as ``broadcast_address`` unless configured differently in cassandra.yaml. + listen address configured for the node, *if available*: + + 'system.local.listen_address' + + This is only available in the ``system.local`` table for newer versions of Cassandra. It is also not + queried if :attr:`~.Cluster.token_metadata_enabled` is ``False``. Usually the same as ``broadcast_address`` + unless configured differently in cassandra.yaml. + """ + + listen_port = None + """ + listen port configured for the node, *if available*: + + 'system.local.listen_port' + + This is only available in the ``system.local`` table for newer versions of Cassandra. It is also not + queried if :attr:`~.Cluster.token_metadata_enabled` is ``False``. """ conviction_policy = None """ A :class:`~.ConvictionPolicy` instance for determining when this node should be marked up or down. """ is_up = None """ :const:`True` if the node is considered up, :const:`False` if it is considered down, and :const:`None` if it is not known if the node is up or down. """ release_version = None """ release_version as queried from the control connection system tables """ host_id = None """ The unique identifier of the cassandra node """ dse_version = None """ dse_version as queried from the control connection system tables. Only populated when connecting to DSE with this property available. Not queried if :attr:`~.Cluster.token_metadata_enabled` is ``False``. """ dse_workload = None """ DSE workload queried from the control connection system tables. Only populated when connecting to DSE with this property available. Not queried if :attr:`~.Cluster.token_metadata_enabled` is ``False``. + This is a legacy attribute that does not portray multiple workloads in a uniform fashion. + See also :attr:`~.Host.dse_workloads`. + """ + + dse_workloads = None + """ + DSE workloads set, queried from the control connection system tables. Only populated when connecting to + DSE with this property available (added in DSE 5.1). + Not queried if :attr:`~.Cluster.token_metadata_enabled` is ``False``. """ _datacenter = None _rack = None _reconnection_handler = None lock = None _currently_handling_node_up = False def __init__(self, endpoint, conviction_policy_factory, datacenter=None, rack=None, host_id=None): if endpoint is None: raise ValueError("endpoint may not be None") if conviction_policy_factory is None: raise ValueError("conviction_policy_factory may not be None") self.endpoint = endpoint if isinstance(endpoint, EndPoint) else DefaultEndPoint(endpoint) self.conviction_policy = conviction_policy_factory(self) self.host_id = host_id self.set_location_info(datacenter, rack) self.lock = RLock() @property def address(self): """ The IP address of the endpoint. This is the RPC address the driver uses when connecting to the node. """ # backward compatibility return self.endpoint.address @property def datacenter(self): """ The datacenter the node is in. """ return self._datacenter @property def rack(self): """ The rack the node is in. """ return self._rack def set_location_info(self, datacenter, rack): """ Sets the datacenter and rack for this node. Intended for internal use (by the control connection, which periodically checks the ring topology) only. """ self._datacenter = datacenter self._rack = rack def set_up(self): if not self.is_up: log.debug("Host %s is now marked up", self.endpoint) self.conviction_policy.reset() self.is_up = True def set_down(self): self.is_up = False def signal_connection_failure(self, connection_exc): return self.conviction_policy.add_failure(connection_exc) def is_currently_reconnecting(self): return self._reconnection_handler is not None def get_and_set_reconnection_handler(self, new_handler): """ Atomically replaces the reconnection handler for this host. Intended for internal use only. """ with self.lock: old = self._reconnection_handler self._reconnection_handler = new_handler return old def __eq__(self, other): if isinstance(other, Host): return self.endpoint == other.endpoint else: # TODO Backward compatibility, remove next major return self.endpoint.address == other def __hash__(self): return hash(self.endpoint) def __lt__(self, other): return self.endpoint < other.endpoint def __str__(self): return str(self.endpoint) def __repr__(self): dc = (" %s" % (self._datacenter,)) if self._datacenter else "" return "<%s: %s%s>" % (self.__class__.__name__, self.endpoint, dc) class _ReconnectionHandler(object): """ Abstract class for attempting reconnections with a given schedule and scheduler. """ _cancelled = False def __init__(self, scheduler, schedule, callback, *callback_args, **callback_kwargs): self.scheduler = scheduler self.schedule = schedule self.callback = callback self.callback_args = callback_args self.callback_kwargs = callback_kwargs def start(self): if self._cancelled: log.debug("Reconnection handler was cancelled before starting") return first_delay = next(self.schedule) self.scheduler.schedule(first_delay, self.run) def run(self): if self._cancelled: return conn = None try: conn = self.try_reconnect() except Exception as exc: try: next_delay = next(self.schedule) except StopIteration: # the schedule has been exhausted next_delay = None # call on_exception for logging purposes even if next_delay is None if self.on_exception(exc, next_delay): if next_delay is None: log.warning( "Will not continue to retry reconnection attempts " "due to an exhausted retry schedule") else: self.scheduler.schedule(next_delay, self.run) else: if not self._cancelled: self.on_reconnection(conn) self.callback(*(self.callback_args), **(self.callback_kwargs)) finally: if conn: conn.close() def cancel(self): self._cancelled = True def try_reconnect(self): """ Subclasses must implement this method. It should attempt to open a new Connection and return it; if a failure occurs, an Exception should be raised. """ raise NotImplementedError() def on_reconnection(self, connection): """ Called when a new Connection is successfully opened. Nothing is done by default. """ pass def on_exception(self, exc, next_delay): """ Called when an Exception is raised when trying to connect. `exc` is the Exception that was raised and `next_delay` is the number of seconds (as a float) that the handler will wait before attempting to connect again. Subclasses should return :const:`False` if no more attempts to connection should be made, :const:`True` otherwise. The default behavior is to always retry unless the error is an :exc:`.AuthenticationFailed` instance. """ if isinstance(exc, AuthenticationFailed): return False else: return True class _HostReconnectionHandler(_ReconnectionHandler): def __init__(self, host, connection_factory, is_host_addition, on_add, on_up, *args, **kwargs): _ReconnectionHandler.__init__(self, *args, **kwargs) self.is_host_addition = is_host_addition self.on_add = on_add self.on_up = on_up self.host = host self.connection_factory = connection_factory def try_reconnect(self): return self.connection_factory() def on_reconnection(self, connection): log.info("Successful reconnection to %s, marking node up if it isn't already", self.host) if self.is_host_addition: self.on_add(self.host) else: self.on_up(self.host) def on_exception(self, exc, next_delay): if isinstance(exc, AuthenticationFailed): return False else: log.warning("Error attempting to reconnect to %s, scheduling retry in %s seconds: %s", self.host, next_delay, exc) log.debug("Reconnection error details", exc_info=True) return True class HostConnection(object): """ When using v3 of the native protocol, this is used instead of a connection pool per host (HostConnectionPool) due to the increased in-flight capacity of individual connections. """ host = None host_distance = None is_shutdown = False shutdown_on_error = False _session = None _connection = None _lock = None _keyspace = None def __init__(self, host, host_distance, session): self.host = host self.host_distance = host_distance self._session = weakref.proxy(session) self._lock = Lock() # this is used in conjunction with the connection streams. Not using the connection lock because the connection can be replaced in the lifetime of the pool. self._stream_available_condition = Condition(self._lock) self._is_replacing = False if host_distance == HostDistance.IGNORED: log.debug("Not opening connection to ignored host %s", self.host) return elif host_distance == HostDistance.REMOTE and not session.cluster.connect_to_remote_hosts: log.debug("Not opening connection to remote host %s", self.host) return log.debug("Initializing connection for host %s", self.host) self._connection = session.cluster.connection_factory(host.endpoint) self._keyspace = session.keyspace if self._keyspace: self._connection.set_keyspace_blocking(self._keyspace) log.debug("Finished initializing connection for host %s", self.host) def borrow_connection(self, timeout): if self.is_shutdown: raise ConnectionException( "Pool for %s is shutdown" % (self.host,), self.host) conn = self._connection if not conn: raise NoConnectionsAvailable() start = time.time() remaining = timeout while True: with conn.lock: - if conn.in_flight <= conn.max_request_id: + if conn.in_flight < conn.max_request_id: conn.in_flight += 1 return conn, conn.get_request_id() if timeout is not None: remaining = timeout - time.time() + start if remaining < 0: break with self._stream_available_condition: self._stream_available_condition.wait(remaining) raise NoConnectionsAvailable("All request IDs are currently in use") def return_connection(self, connection): with connection.lock: connection.in_flight -= 1 with self._stream_available_condition: self._stream_available_condition.notify() if connection.is_defunct or connection.is_closed: if connection.signaled_error and not self.shutdown_on_error: return is_down = False if not connection.signaled_error: log.debug("Defunct or closed connection (%s) returned to pool, potentially " "marking host %s as down", id(connection), self.host) is_down = self._session.cluster.signal_connection_failure( self.host, connection.last_error, is_host_addition=False) connection.signaled_error = True if self.shutdown_on_error and not is_down: is_down = True self._session.cluster.on_down(self.host, is_host_addition=False) if is_down: self.shutdown() else: self._connection = None with self._lock: if self._is_replacing: return self._is_replacing = True self._session.submit(self._replace, connection) def _replace(self, connection): with self._lock: if self.is_shutdown: return log.debug("Replacing connection (%s) to %s", id(connection), self.host) try: - conn = self._session.cluster.connection_factory(self.host) + conn = self._session.cluster.connection_factory(self.host.endpoint) if self._keyspace: conn.set_keyspace_blocking(self._keyspace) self._connection = conn except Exception: log.warning("Failed reconnecting %s. Retrying." % (self.host.endpoint,)) self._session.submit(self._replace, connection) else: with self._lock: self._is_replacing = False self._stream_available_condition.notify() def shutdown(self): with self._lock: if self.is_shutdown: return else: self.is_shutdown = True self._stream_available_condition.notify_all() if self._connection: self._connection.close() self._connection = None def _set_keyspace_for_all_conns(self, keyspace, callback): if self.is_shutdown or not self._connection: return def connection_finished_setting_keyspace(conn, error): self.return_connection(conn) errors = [] if not error else [error] callback(self, errors) self._keyspace = keyspace self._connection.set_keyspace_async(keyspace, connection_finished_setting_keyspace) def get_connections(self): c = self._connection return [c] if c else [] def get_state(self): connection = self._connection open_count = 1 if connection and not (connection.is_closed or connection.is_defunct) else 0 in_flights = [connection.in_flight] if connection else [] return {'shutdown': self.is_shutdown, 'open_count': open_count, 'in_flights': in_flights} @property def open_count(self): connection = self._connection return 1 if connection and not (connection.is_closed or connection.is_defunct) else 0 _MAX_SIMULTANEOUS_CREATION = 1 _MIN_TRASH_INTERVAL = 10 class HostConnectionPool(object): """ Used to pool connections to a host for v1 and v2 native protocol. """ host = None host_distance = None is_shutdown = False open_count = 0 _scheduled_for_creation = 0 _next_trash_allowed_at = 0 _keyspace = None def __init__(self, host, host_distance, session): self.host = host self.host_distance = host_distance self._session = weakref.proxy(session) self._lock = RLock() self._conn_available_condition = Condition() log.debug("Initializing new connection pool for host %s", self.host) core_conns = session.cluster.get_core_connections_per_host(host_distance) self._connections = [session.cluster.connection_factory(host.endpoint) for i in range(core_conns)] self._keyspace = session.keyspace if self._keyspace: for conn in self._connections: conn.set_keyspace_blocking(self._keyspace) self._trash = set() self._next_trash_allowed_at = time.time() self.open_count = core_conns log.debug("Finished initializing new connection pool for host %s", self.host) def borrow_connection(self, timeout): if self.is_shutdown: raise ConnectionException( "Pool for %s is shutdown" % (self.host,), self.host) conns = self._connections if not conns: # handled specially just for simpler code log.debug("Detected empty pool, opening core conns to %s", self.host) core_conns = self._session.cluster.get_core_connections_per_host(self.host_distance) with self._lock: # we check the length of self._connections again # along with self._scheduled_for_creation while holding the lock # in case multiple threads hit this condition at the same time to_create = core_conns - (len(self._connections) + self._scheduled_for_creation) for i in range(to_create): self._scheduled_for_creation += 1 self._session.submit(self._create_new_connection) # in_flight is incremented by wait_for_conn conn = self._wait_for_conn(timeout) return conn else: # note: it would be nice to push changes to these config settings # to pools instead of doing a new lookup on every # borrow_connection() call max_reqs = self._session.cluster.get_max_requests_per_connection(self.host_distance) max_conns = self._session.cluster.get_max_connections_per_host(self.host_distance) least_busy = min(conns, key=lambda c: c.in_flight) request_id = None # to avoid another thread closing this connection while # trashing it (through the return_connection process), hold # the connection lock from this point until we've incremented # its in_flight count need_to_wait = False with least_busy.lock: if least_busy.in_flight < least_busy.max_request_id: least_busy.in_flight += 1 request_id = least_busy.get_request_id() else: # once we release the lock, wait for another connection need_to_wait = True if need_to_wait: # wait_for_conn will increment in_flight on the conn least_busy, request_id = self._wait_for_conn(timeout) # if we have too many requests on this connection but we still # have space to open a new connection against this host, go ahead # and schedule the creation of a new connection if least_busy.in_flight >= max_reqs and len(self._connections) < max_conns: self._maybe_spawn_new_connection() return least_busy, request_id def _maybe_spawn_new_connection(self): with self._lock: if self._scheduled_for_creation >= _MAX_SIMULTANEOUS_CREATION: return if self.open_count >= self._session.cluster.get_max_connections_per_host(self.host_distance): return self._scheduled_for_creation += 1 log.debug("Submitting task for creation of new Connection to %s", self.host) self._session.submit(self._create_new_connection) def _create_new_connection(self): try: self._add_conn_if_under_max() except (ConnectionException, socket.error) as exc: log.warning("Failed to create new connection to %s: %s", self.host, exc) except Exception: log.exception("Unexpectedly failed to create new connection") finally: with self._lock: self._scheduled_for_creation -= 1 def _add_conn_if_under_max(self): max_conns = self._session.cluster.get_max_connections_per_host(self.host_distance) with self._lock: if self.is_shutdown: return True if self.open_count >= max_conns: return True self.open_count += 1 log.debug("Going to open new connection to host %s", self.host) try: conn = self._session.cluster.connection_factory(self.host.endpoint) if self._keyspace: conn.set_keyspace_blocking(self._session.keyspace) self._next_trash_allowed_at = time.time() + _MIN_TRASH_INTERVAL with self._lock: new_connections = self._connections[:] + [conn] self._connections = new_connections log.debug("Added new connection (%s) to pool for host %s, signaling availablility", id(conn), self.host) self._signal_available_conn() return True except (ConnectionException, socket.error) as exc: log.warning("Failed to add new connection to pool for host %s: %s", self.host, exc) with self._lock: self.open_count -= 1 if self._session.cluster.signal_connection_failure(self.host, exc, is_host_addition=False): self.shutdown() return False except AuthenticationFailed: with self._lock: self.open_count -= 1 return False def _await_available_conn(self, timeout): with self._conn_available_condition: self._conn_available_condition.wait(timeout) def _signal_available_conn(self): with self._conn_available_condition: self._conn_available_condition.notify() def _signal_all_available_conn(self): with self._conn_available_condition: self._conn_available_condition.notify_all() def _wait_for_conn(self, timeout): start = time.time() remaining = timeout while remaining > 0: # wait on our condition for the possibility that a connection # is useable self._await_available_conn(remaining) # self.shutdown() may trigger the above Condition if self.is_shutdown: raise ConnectionException("Pool is shutdown") conns = self._connections if conns: least_busy = min(conns, key=lambda c: c.in_flight) with least_busy.lock: if least_busy.in_flight < least_busy.max_request_id: least_busy.in_flight += 1 return least_busy, least_busy.get_request_id() remaining = timeout - (time.time() - start) raise NoConnectionsAvailable() def return_connection(self, connection): with connection.lock: connection.in_flight -= 1 in_flight = connection.in_flight if connection.is_defunct or connection.is_closed: if not connection.signaled_error: log.debug("Defunct or closed connection (%s) returned to pool, potentially " "marking host %s as down", id(connection), self.host) is_down = self._session.cluster.signal_connection_failure( self.host, connection.last_error, is_host_addition=False) connection.signaled_error = True if is_down: self.shutdown() else: self._replace(connection) else: if connection in self._trash: with connection.lock: if connection.in_flight == 0: with self._lock: if connection in self._trash: self._trash.remove(connection) log.debug("Closing trashed connection (%s) to %s", id(connection), self.host) connection.close() return core_conns = self._session.cluster.get_core_connections_per_host(self.host_distance) min_reqs = self._session.cluster.get_min_requests_per_connection(self.host_distance) # we can use in_flight here without holding the connection lock # because the fact that in_flight dipped below the min at some # point is enough to start the trashing procedure if len(self._connections) > core_conns and in_flight <= min_reqs and \ time.time() >= self._next_trash_allowed_at: self._maybe_trash_connection(connection) else: self._signal_available_conn() def _maybe_trash_connection(self, connection): core_conns = self._session.cluster.get_core_connections_per_host(self.host_distance) did_trash = False with self._lock: if connection not in self._connections: return if self.open_count > core_conns: did_trash = True self.open_count -= 1 new_connections = self._connections[:] new_connections.remove(connection) self._connections = new_connections with connection.lock: if connection.in_flight == 0: log.debug("Skipping trash and closing unused connection (%s) to %s", id(connection), self.host) connection.close() # skip adding it to the trash if we're already closing it return self._trash.add(connection) if did_trash: self._next_trash_allowed_at = time.time() + _MIN_TRASH_INTERVAL log.debug("Trashed connection (%s) to %s", id(connection), self.host) def _replace(self, connection): should_replace = False with self._lock: if connection in self._connections: new_connections = self._connections[:] new_connections.remove(connection) self._connections = new_connections self.open_count -= 1 should_replace = True if should_replace: log.debug("Replacing connection (%s) to %s", id(connection), self.host) connection.close() self._session.submit(self._retrying_replace) else: log.debug("Closing connection (%s) to %s", id(connection), self.host) connection.close() def _retrying_replace(self): replaced = False try: replaced = self._add_conn_if_under_max() except Exception: log.exception("Failed replacing connection to %s", self.host) if not replaced: log.debug("Failed replacing connection to %s. Retrying.", self.host) self._session.submit(self._retrying_replace) def shutdown(self): with self._lock: if self.is_shutdown: return else: self.is_shutdown = True self._signal_all_available_conn() for conn in self._connections: conn.close() self.open_count -= 1 for conn in self._trash: conn.close() def ensure_core_connections(self): if self.is_shutdown: return core_conns = self._session.cluster.get_core_connections_per_host(self.host_distance) with self._lock: to_create = core_conns - (len(self._connections) + self._scheduled_for_creation) for i in range(to_create): self._scheduled_for_creation += 1 self._session.submit(self._create_new_connection) def _set_keyspace_for_all_conns(self, keyspace, callback): """ Asynchronously sets the keyspace for all connections. When all connections have been set, `callback` will be called with two arguments: this pool, and a list of any errors that occurred. """ remaining_callbacks = set(self._connections) errors = [] if not remaining_callbacks: callback(self, errors) return def connection_finished_setting_keyspace(conn, error): self.return_connection(conn) remaining_callbacks.remove(conn) if error: errors.append(error) if not remaining_callbacks: callback(self, errors) self._keyspace = keyspace for conn in self._connections: conn.set_keyspace_async(keyspace, connection_finished_setting_keyspace) def get_connections(self): return self._connections def get_state(self): in_flights = [c.in_flight for c in self._connections] return {'shutdown': self.is_shutdown, 'open_count': self.open_count, 'in_flights': in_flights} diff --git a/cassandra/protocol.py b/cassandra/protocol.py index 7e11779..ed92a76 100644 --- a/cassandra/protocol.py +++ b/cassandra/protocol.py @@ -1,1409 +1,1484 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import # to enable import io from stdlib from collections import namedtuple import logging import socket from uuid import UUID import six from six.moves import range import io from cassandra import ProtocolVersion from cassandra import type_codes, DriverException from cassandra import (Unavailable, WriteTimeout, ReadTimeout, WriteFailure, ReadFailure, FunctionFailure, AlreadyExists, InvalidRequest, Unauthorized, UnsupportedOperation, UserFunctionDescriptor, UserAggregateDescriptor, SchemaTargetType) from cassandra.marshal import (int32_pack, int32_unpack, uint16_pack, uint16_unpack, - int8_pack, int8_unpack, uint64_pack, header_pack, - v3_header_pack, uint32_pack) + uint8_pack, int8_unpack, uint64_pack, header_pack, + v3_header_pack, uint32_pack, uint32_le_unpack, uint32_le_pack) from cassandra.cqltypes import (AsciiType, BytesType, BooleanType, CounterColumnType, DateType, DecimalType, DoubleType, FloatType, Int32Type, InetAddressType, IntegerType, ListType, LongType, MapType, SetType, TimeUUIDType, UTF8Type, VarcharType, UUIDType, UserType, TupleType, lookup_casstype, SimpleDateType, TimeType, ByteType, ShortType, DurationType) from cassandra import WriteType from cassandra.cython_deps import HAVE_CYTHON, HAVE_NUMPY from cassandra import util log = logging.getLogger(__name__) class NotSupportedError(Exception): pass class InternalError(Exception): pass ColumnMetadata = namedtuple("ColumnMetadata", ['keyspace_name', 'table_name', 'name', 'type']) HEADER_DIRECTION_TO_CLIENT = 0x80 HEADER_DIRECTION_MASK = 0x80 COMPRESSED_FLAG = 0x01 TRACING_FLAG = 0x02 CUSTOM_PAYLOAD_FLAG = 0x04 WARNING_FLAG = 0x08 USE_BETA_FLAG = 0x10 USE_BETA_MASK = ~USE_BETA_FLAG _message_types_by_opcode = {} _UNSET_VALUE = object() def register_class(cls): _message_types_by_opcode[cls.opcode] = cls def get_registered_classes(): return _message_types_by_opcode.copy() class _RegisterMessageType(type): def __init__(cls, name, bases, dct): if not name.startswith('_'): register_class(cls) @six.add_metaclass(_RegisterMessageType) class _MessageType(object): tracing = False custom_payload = None warnings = None def update_custom_payload(self, other): if other: if not self.custom_payload: self.custom_payload = {} self.custom_payload.update(other) if len(self.custom_payload) > 65535: raise ValueError("Custom payload map exceeds max count allowed by protocol (65535)") def __repr__(self): return '<%s(%s)>' % (self.__class__.__name__, ', '.join('%s=%r' % i for i in _get_params(self))) def _get_params(message_obj): base_attrs = dir(_MessageType) return ( (n, a) for n, a in message_obj.__dict__.items() if n not in base_attrs and not n.startswith('_') and not callable(a) ) error_classes = {} class ErrorMessage(_MessageType, Exception): opcode = 0x00 name = 'ERROR' summary = 'Unknown' def __init__(self, code, message, info): self.code = code self.message = message self.info = info @classmethod def recv_body(cls, f, protocol_version, *args): code = read_int(f) msg = read_string(f) subcls = error_classes.get(code, cls) extra_info = subcls.recv_error_info(f, protocol_version) return subcls(code=code, message=msg, info=extra_info) def summary_msg(self): msg = 'Error from server: code=%04x [%s] message="%s"' \ % (self.code, self.summary, self.message) if six.PY2 and isinstance(msg, six.text_type): msg = msg.encode('utf-8') return msg def __str__(self): return '<%s>' % self.summary_msg() __repr__ = __str__ @staticmethod def recv_error_info(f, protocol_version): pass def to_exception(self): return self class ErrorMessageSubclass(_RegisterMessageType): def __init__(cls, name, bases, dct): if cls.error_code is not None: # Server has an error code of 0. error_classes[cls.error_code] = cls @six.add_metaclass(ErrorMessageSubclass) class ErrorMessageSub(ErrorMessage): error_code = None class RequestExecutionException(ErrorMessageSub): pass class RequestValidationException(ErrorMessageSub): pass class ServerError(ErrorMessageSub): summary = 'Server error' error_code = 0x0000 class ProtocolException(ErrorMessageSub): summary = 'Protocol error' error_code = 0x000A + @property + def is_beta_protocol_error(self): + return 'USE_BETA flag is unset' in str(self) + class BadCredentials(ErrorMessageSub): summary = 'Bad credentials' error_code = 0x0100 class UnavailableErrorMessage(RequestExecutionException): summary = 'Unavailable exception' error_code = 0x1000 @staticmethod def recv_error_info(f, protocol_version): return { 'consistency': read_consistency_level(f), 'required_replicas': read_int(f), 'alive_replicas': read_int(f), } def to_exception(self): return Unavailable(self.summary_msg(), **self.info) class OverloadedErrorMessage(RequestExecutionException): summary = 'Coordinator node overloaded' error_code = 0x1001 class IsBootstrappingErrorMessage(RequestExecutionException): summary = 'Coordinator node is bootstrapping' error_code = 0x1002 class TruncateError(RequestExecutionException): summary = 'Error during truncate' error_code = 0x1003 class WriteTimeoutErrorMessage(RequestExecutionException): summary = "Coordinator node timed out waiting for replica nodes' responses" error_code = 0x1100 @staticmethod def recv_error_info(f, protocol_version): return { 'consistency': read_consistency_level(f), 'received_responses': read_int(f), 'required_responses': read_int(f), 'write_type': WriteType.name_to_value[read_string(f)], } def to_exception(self): return WriteTimeout(self.summary_msg(), **self.info) class ReadTimeoutErrorMessage(RequestExecutionException): summary = "Coordinator node timed out waiting for replica nodes' responses" error_code = 0x1200 @staticmethod def recv_error_info(f, protocol_version): return { 'consistency': read_consistency_level(f), 'received_responses': read_int(f), 'required_responses': read_int(f), 'data_retrieved': bool(read_byte(f)), } def to_exception(self): return ReadTimeout(self.summary_msg(), **self.info) class ReadFailureMessage(RequestExecutionException): summary = "Replica(s) failed to execute read" error_code = 0x1300 @staticmethod def recv_error_info(f, protocol_version): consistency = read_consistency_level(f) received_responses = read_int(f) required_responses = read_int(f) if ProtocolVersion.uses_error_code_map(protocol_version): error_code_map = read_error_code_map(f) failures = len(error_code_map) else: error_code_map = None failures = read_int(f) data_retrieved = bool(read_byte(f)) return { 'consistency': consistency, 'received_responses': received_responses, 'required_responses': required_responses, 'failures': failures, 'error_code_map': error_code_map, 'data_retrieved': data_retrieved } def to_exception(self): return ReadFailure(self.summary_msg(), **self.info) class FunctionFailureMessage(RequestExecutionException): summary = "User Defined Function failure" error_code = 0x1400 @staticmethod def recv_error_info(f, protocol_version): return { 'keyspace': read_string(f), 'function': read_string(f), 'arg_types': [read_string(f) for _ in range(read_short(f))], } def to_exception(self): return FunctionFailure(self.summary_msg(), **self.info) class WriteFailureMessage(RequestExecutionException): summary = "Replica(s) failed to execute write" error_code = 0x1500 @staticmethod def recv_error_info(f, protocol_version): consistency = read_consistency_level(f) received_responses = read_int(f) required_responses = read_int(f) if ProtocolVersion.uses_error_code_map(protocol_version): error_code_map = read_error_code_map(f) failures = len(error_code_map) else: error_code_map = None failures = read_int(f) write_type = WriteType.name_to_value[read_string(f)] return { 'consistency': consistency, 'received_responses': received_responses, 'required_responses': required_responses, 'failures': failures, 'error_code_map': error_code_map, 'write_type': write_type } def to_exception(self): return WriteFailure(self.summary_msg(), **self.info) class CDCWriteException(RequestExecutionException): summary = 'Failed to execute write due to CDC space exhaustion.' error_code = 0x1600 class SyntaxException(RequestValidationException): summary = 'Syntax error in CQL query' error_code = 0x2000 class UnauthorizedErrorMessage(RequestValidationException): summary = 'Unauthorized' error_code = 0x2100 def to_exception(self): return Unauthorized(self.summary_msg()) class InvalidRequestException(RequestValidationException): summary = 'Invalid query' error_code = 0x2200 def to_exception(self): return InvalidRequest(self.summary_msg()) class ConfigurationException(RequestValidationException): summary = 'Query invalid because of configuration issue' error_code = 0x2300 class PreparedQueryNotFound(RequestValidationException): summary = 'Matching prepared statement not found on this node' error_code = 0x2500 @staticmethod def recv_error_info(f, protocol_version): # return the query ID return read_binary_string(f) class AlreadyExistsException(ConfigurationException): summary = 'Item already exists' error_code = 0x2400 @staticmethod def recv_error_info(f, protocol_version): return { 'keyspace': read_string(f), 'table': read_string(f), } def to_exception(self): return AlreadyExists(**self.info) +class ClientWriteError(RequestExecutionException): + summary = 'Client write failure.' + error_code = 0x8000 + + class StartupMessage(_MessageType): opcode = 0x01 name = 'STARTUP' KNOWN_OPTION_KEYS = set(( 'CQL_VERSION', 'COMPRESSION', 'NO_COMPACT' )) def __init__(self, cqlversion, options): self.cqlversion = cqlversion self.options = options def send_body(self, f, protocol_version): optmap = self.options.copy() optmap['CQL_VERSION'] = self.cqlversion write_stringmap(f, optmap) class ReadyMessage(_MessageType): opcode = 0x02 name = 'READY' @classmethod def recv_body(cls, *args): return cls() class AuthenticateMessage(_MessageType): opcode = 0x03 name = 'AUTHENTICATE' def __init__(self, authenticator): self.authenticator = authenticator @classmethod def recv_body(cls, f, *args): authname = read_string(f) return cls(authenticator=authname) class CredentialsMessage(_MessageType): opcode = 0x04 name = 'CREDENTIALS' def __init__(self, creds): self.creds = creds def send_body(self, f, protocol_version): if protocol_version > 1: raise UnsupportedOperation( "Credentials-based authentication is not supported with " "protocol version 2 or higher. Use the SASL authentication " "mechanism instead.") write_short(f, len(self.creds)) for credkey, credval in self.creds.items(): write_string(f, credkey) write_string(f, credval) class AuthChallengeMessage(_MessageType): opcode = 0x0E name = 'AUTH_CHALLENGE' def __init__(self, challenge): self.challenge = challenge @classmethod def recv_body(cls, f, *args): return cls(read_binary_longstring(f)) class AuthResponseMessage(_MessageType): opcode = 0x0F name = 'AUTH_RESPONSE' def __init__(self, response): self.response = response def send_body(self, f, protocol_version): write_longstring(f, self.response) class AuthSuccessMessage(_MessageType): opcode = 0x10 name = 'AUTH_SUCCESS' def __init__(self, token): self.token = token @classmethod def recv_body(cls, f, *args): return cls(read_longstring(f)) class OptionsMessage(_MessageType): opcode = 0x05 name = 'OPTIONS' def send_body(self, f, protocol_version): pass class SupportedMessage(_MessageType): opcode = 0x06 name = 'SUPPORTED' def __init__(self, cql_versions, options): self.cql_versions = cql_versions self.options = options @classmethod def recv_body(cls, f, *args): options = read_stringmultimap(f) cql_versions = options.pop('CQL_VERSION') return cls(cql_versions=cql_versions, options=options) # used for QueryMessage and ExecuteMessage _VALUES_FLAG = 0x01 _SKIP_METADATA_FLAG = 0x02 _PAGE_SIZE_FLAG = 0x04 _WITH_PAGING_STATE_FLAG = 0x08 _WITH_SERIAL_CONSISTENCY_FLAG = 0x10 -_PROTOCOL_TIMESTAMP = 0x20 +_PROTOCOL_TIMESTAMP_FLAG = 0x20 +_NAMES_FOR_VALUES_FLAG = 0x40 # not used here _WITH_KEYSPACE_FLAG = 0x80 _PREPARED_WITH_KEYSPACE_FLAG = 0x01 +_PAGE_SIZE_BYTES_FLAG = 0x40000000 +_PAGING_OPTIONS_FLAG = 0x80000000 -class QueryMessage(_MessageType): - opcode = 0x07 - name = 'QUERY' +class _QueryMessage(_MessageType): - def __init__(self, query, consistency_level, serial_consistency_level=None, - fetch_size=None, paging_state=None, timestamp=None, keyspace=None): - self.query = query + def __init__(self, query_params, consistency_level, + serial_consistency_level=None, fetch_size=None, + paging_state=None, timestamp=None, skip_meta=False, + continuous_paging_options=None, keyspace=None): + self.query_params = query_params self.consistency_level = consistency_level self.serial_consistency_level = serial_consistency_level self.fetch_size = fetch_size self.paging_state = paging_state self.timestamp = timestamp + self.skip_meta = skip_meta + self.continuous_paging_options = continuous_paging_options self.keyspace = keyspace - self._query_params = None # only used internally. May be set to a list of native-encoded values to have them sent with the request. - def send_body(self, f, protocol_version): - write_longstring(f, self.query) + def _write_query_params(self, f, protocol_version): write_consistency_level(f, self.consistency_level) flags = 0x00 - if self._query_params is not None: + if self.query_params is not None: flags |= _VALUES_FLAG # also v2+, but we're only setting params internally right now if self.serial_consistency_level: if protocol_version >= 2: flags |= _WITH_SERIAL_CONSISTENCY_FLAG else: raise UnsupportedOperation( "Serial consistency levels require the use of protocol version " "2 or higher. Consider setting Cluster.protocol_version to 2 " "to support serial consistency levels.") if self.fetch_size: if protocol_version >= 2: flags |= _PAGE_SIZE_FLAG else: raise UnsupportedOperation( "Automatic query paging may only be used with protocol version " "2 or higher. Consider setting Cluster.protocol_version to 2.") if self.paging_state: if protocol_version >= 2: flags |= _WITH_PAGING_STATE_FLAG else: raise UnsupportedOperation( "Automatic query paging may only be used with protocol version " "2 or higher. Consider setting Cluster.protocol_version to 2.") if self.timestamp is not None: - flags |= _PROTOCOL_TIMESTAMP + flags |= _PROTOCOL_TIMESTAMP_FLAG + + if self.continuous_paging_options: + if ProtocolVersion.has_continuous_paging_support(protocol_version): + flags |= _PAGING_OPTIONS_FLAG + else: + raise UnsupportedOperation( + "Continuous paging may only be used with protocol version " + "ProtocolVersion.DSE_V1 or higher. Consider setting Cluster.protocol_version to ProtocolVersion.DSE_V1.") if self.keyspace is not None: if ProtocolVersion.uses_keyspace_flag(protocol_version): flags |= _WITH_KEYSPACE_FLAG else: raise UnsupportedOperation( "Keyspaces may only be set on queries with protocol version " - "5 or higher. Consider setting Cluster.protocol_version to 5.") + "5 or DSE_V2 or higher. Consider setting Cluster.protocol_version.") if ProtocolVersion.uses_int_query_flags(protocol_version): write_uint(f, flags) else: write_byte(f, flags) - if self._query_params is not None: - write_short(f, len(self._query_params)) - for param in self._query_params: + if self.query_params is not None: + write_short(f, len(self.query_params)) + for param in self.query_params: write_value(f, param) - if self.fetch_size: write_int(f, self.fetch_size) if self.paging_state: write_longstring(f, self.paging_state) if self.serial_consistency_level: write_consistency_level(f, self.serial_consistency_level) if self.timestamp is not None: write_long(f, self.timestamp) if self.keyspace is not None: write_string(f, self.keyspace) + if self.continuous_paging_options: + self._write_paging_options(f, self.continuous_paging_options, protocol_version) + + def _write_paging_options(self, f, paging_options, protocol_version): + write_int(f, paging_options.max_pages) + write_int(f, paging_options.max_pages_per_second) + if ProtocolVersion.has_continuous_paging_next_pages(protocol_version): + write_int(f, paging_options.max_queue_size) + + +class QueryMessage(_QueryMessage): + opcode = 0x07 + name = 'QUERY' + + def __init__(self, query, consistency_level, serial_consistency_level=None, + fetch_size=None, paging_state=None, timestamp=None, continuous_paging_options=None, keyspace=None): + self.query = query + super(QueryMessage, self).__init__(None, consistency_level, serial_consistency_level, fetch_size, + paging_state, timestamp, False, continuous_paging_options, keyspace) + + def send_body(self, f, protocol_version): + write_longstring(f, self.query) + self._write_query_params(f, protocol_version) + + +class ExecuteMessage(_QueryMessage): + opcode = 0x0A + name = 'EXECUTE' + + def __init__(self, query_id, query_params, consistency_level, + serial_consistency_level=None, fetch_size=None, + paging_state=None, timestamp=None, skip_meta=False, + continuous_paging_options=None, result_metadata_id=None): + self.query_id = query_id + self.result_metadata_id = result_metadata_id + super(ExecuteMessage, self).__init__(query_params, consistency_level, serial_consistency_level, fetch_size, + paging_state, timestamp, skip_meta, continuous_paging_options) + + def _write_query_params(self, f, protocol_version): + if protocol_version == 1: + if self.serial_consistency_level: + raise UnsupportedOperation( + "Serial consistency levels require the use of protocol version " + "2 or higher. Consider setting Cluster.protocol_version to 2 " + "to support serial consistency levels.") + if self.fetch_size or self.paging_state: + raise UnsupportedOperation( + "Automatic query paging may only be used with protocol version " + "2 or higher. Consider setting Cluster.protocol_version to 2.") + write_short(f, len(self.query_params)) + for param in self.query_params: + write_value(f, param) + write_consistency_level(f, self.consistency_level) + else: + super(ExecuteMessage, self)._write_query_params(f, protocol_version) + + def send_body(self, f, protocol_version): + write_string(f, self.query_id) + if ProtocolVersion.uses_prepared_metadata(protocol_version): + write_string(f, self.result_metadata_id) + self._write_query_params(f, protocol_version) CUSTOM_TYPE = object() RESULT_KIND_VOID = 0x0001 RESULT_KIND_ROWS = 0x0002 RESULT_KIND_SET_KEYSPACE = 0x0003 RESULT_KIND_PREPARED = 0x0004 RESULT_KIND_SCHEMA_CHANGE = 0x0005 class ResultMessage(_MessageType): opcode = 0x08 name = 'RESULT' kind = None results = None paging_state = None # Names match type name in module scope. Most are imported from cassandra.cqltypes (except CUSTOM_TYPE) type_codes = _cqltypes_by_code = dict((v, globals()[k]) for k, v in type_codes.__dict__.items() if not k.startswith('_')) _FLAGS_GLOBAL_TABLES_SPEC = 0x0001 _HAS_MORE_PAGES_FLAG = 0x0002 _NO_METADATA_FLAG = 0x0004 + _CONTINUOUS_PAGING_FLAG = 0x40000000 + _CONTINUOUS_PAGING_LAST_FLAG = 0x80000000 _METADATA_ID_FLAG = 0x0008 - def __init__(self, kind, results, paging_state=None, col_types=None): + kind = None + + # These are all the things a result message might contain. They are populated according to 'kind' + column_names = None + column_types = None + parsed_rows = None + paging_state = None + continuous_paging_seq = None + continuous_paging_last = None + new_keyspace = None + column_metadata = None + query_id = None + bind_metadata = None + pk_indexes = None + schema_change_event = None + + def __init__(self, kind): self.kind = kind - self.results = results - self.paging_state = paging_state - self.col_types = col_types + + def recv(self, f, protocol_version, user_type_map, result_metadata): + if self.kind == RESULT_KIND_VOID: + return + elif self.kind == RESULT_KIND_ROWS: + self.recv_results_rows(f, protocol_version, user_type_map, result_metadata) + elif self.kind == RESULT_KIND_SET_KEYSPACE: + self.new_keyspace = read_string(f) + elif self.kind == RESULT_KIND_PREPARED: + self.recv_results_prepared(f, protocol_version, user_type_map) + elif self.kind == RESULT_KIND_SCHEMA_CHANGE: + self.recv_results_schema_change(f, protocol_version) + else: + raise DriverException("Unknown RESULT kind: %d" % self.kind) @classmethod def recv_body(cls, f, protocol_version, user_type_map, result_metadata): kind = read_int(f) - paging_state = None - col_types = None - if kind == RESULT_KIND_VOID: - results = None - elif kind == RESULT_KIND_ROWS: - paging_state, col_types, results, result_metadata_id = cls.recv_results_rows( - f, protocol_version, user_type_map, result_metadata) - elif kind == RESULT_KIND_SET_KEYSPACE: - ksname = read_string(f) - results = ksname - elif kind == RESULT_KIND_PREPARED: - results = cls.recv_results_prepared(f, protocol_version, user_type_map) - elif kind == RESULT_KIND_SCHEMA_CHANGE: - results = cls.recv_results_schema_change(f, protocol_version) - else: - raise DriverException("Unknown RESULT kind: %d" % kind) - return cls(kind, results, paging_state, col_types) + msg = cls(kind) + msg.recv(f, protocol_version, user_type_map, result_metadata) + return msg - @classmethod - def recv_results_rows(cls, f, protocol_version, user_type_map, result_metadata): - paging_state, column_metadata, result_metadata_id = cls.recv_results_metadata(f, user_type_map) - column_metadata = column_metadata or result_metadata + def recv_results_rows(self, f, protocol_version, user_type_map, result_metadata): + self.recv_results_metadata(f, user_type_map) + column_metadata = self.column_metadata or result_metadata rowcount = read_int(f) - rows = [cls.recv_row(f, len(column_metadata)) for _ in range(rowcount)] - colnames = [c[2] for c in column_metadata] - coltypes = [c[3] for c in column_metadata] + rows = [self.recv_row(f, len(column_metadata)) for _ in range(rowcount)] + self.column_names = [c[2] for c in column_metadata] + self.column_types = [c[3] for c in column_metadata] try: - parsed_rows = [ + self.parsed_rows = [ tuple(ctype.from_binary(val, protocol_version) - for ctype, val in zip(coltypes, row)) + for ctype, val in zip(self.column_types, row)) for row in rows] except Exception: for row in rows: for i in range(len(row)): try: - coltypes[i].from_binary(row[i], protocol_version) + self.column_types[i].from_binary(row[i], protocol_version) except Exception as e: - raise DriverException('Failed decoding result column "%s" of type %s: %s' % (colnames[i], - coltypes[i].cql_parameterized_type(), + raise DriverException('Failed decoding result column "%s" of type %s: %s' % (self.column_names[i], + self.column_types[i].cql_parameterized_type(), str(e))) - return paging_state, coltypes, (colnames, parsed_rows), result_metadata_id - @classmethod - def recv_results_prepared(cls, f, protocol_version, user_type_map): - query_id = read_binary_string(f) + def recv_results_prepared(self, f, protocol_version, user_type_map): + self.query_id = read_binary_string(f) if ProtocolVersion.uses_prepared_metadata(protocol_version): - result_metadata_id = read_binary_string(f) + self.result_metadata_id = read_binary_string(f) else: - result_metadata_id = None - bind_metadata, pk_indexes, result_metadata, _ = cls.recv_prepared_metadata(f, protocol_version, user_type_map) - return query_id, bind_metadata, pk_indexes, result_metadata, result_metadata_id + self.result_metadata_id = None + self.recv_prepared_metadata(f, protocol_version, user_type_map) - @classmethod - def recv_results_metadata(cls, f, user_type_map): + def recv_results_metadata(self, f, user_type_map): flags = read_int(f) colcount = read_int(f) - if flags & cls._HAS_MORE_PAGES_FLAG: - paging_state = read_binary_longstring(f) - else: - paging_state = None + if flags & self._HAS_MORE_PAGES_FLAG: + self.paging_state = read_binary_longstring(f) - if flags & cls._METADATA_ID_FLAG: - result_metadata_id = read_binary_string(f) - else: - result_metadata_id = None - - no_meta = bool(flags & cls._NO_METADATA_FLAG) + no_meta = bool(flags & self._NO_METADATA_FLAG) if no_meta: - return paging_state, [], result_metadata_id + return + + if flags & self._CONTINUOUS_PAGING_FLAG: + self.continuous_paging_seq = read_int(f) + self.continuous_paging_last = flags & self._CONTINUOUS_PAGING_LAST_FLAG - glob_tblspec = bool(flags & cls._FLAGS_GLOBAL_TABLES_SPEC) + if flags & self._METADATA_ID_FLAG: + self.result_metadata_id = read_binary_string(f) + + glob_tblspec = bool(flags & self._FLAGS_GLOBAL_TABLES_SPEC) if glob_tblspec: ksname = read_string(f) cfname = read_string(f) column_metadata = [] for _ in range(colcount): if glob_tblspec: colksname = ksname colcfname = cfname else: colksname = read_string(f) colcfname = read_string(f) colname = read_string(f) - coltype = cls.read_type(f, user_type_map) + coltype = self.read_type(f, user_type_map) column_metadata.append((colksname, colcfname, colname, coltype)) - return paging_state, column_metadata, result_metadata_id - @classmethod - def recv_prepared_metadata(cls, f, protocol_version, user_type_map): + self.column_metadata = column_metadata + + def recv_prepared_metadata(self, f, protocol_version, user_type_map): flags = read_int(f) colcount = read_int(f) pk_indexes = None if protocol_version >= 4: num_pk_indexes = read_int(f) pk_indexes = [read_short(f) for _ in range(num_pk_indexes)] - glob_tblspec = bool(flags & cls._FLAGS_GLOBAL_TABLES_SPEC) + glob_tblspec = bool(flags & self._FLAGS_GLOBAL_TABLES_SPEC) if glob_tblspec: ksname = read_string(f) cfname = read_string(f) bind_metadata = [] for _ in range(colcount): if glob_tblspec: colksname = ksname colcfname = cfname else: colksname = read_string(f) colcfname = read_string(f) colname = read_string(f) - coltype = cls.read_type(f, user_type_map) + coltype = self.read_type(f, user_type_map) bind_metadata.append(ColumnMetadata(colksname, colcfname, colname, coltype)) if protocol_version >= 2: - _, result_metadata, result_metadata_id = cls.recv_results_metadata(f, user_type_map) - return bind_metadata, pk_indexes, result_metadata, result_metadata_id - else: - return bind_metadata, pk_indexes, None, None + self.recv_results_metadata(f, user_type_map) - @classmethod - def recv_results_schema_change(cls, f, protocol_version): - return EventMessage.recv_schema_change(f, protocol_version) + self.bind_metadata = bind_metadata + self.pk_indexes = pk_indexes + + def recv_results_schema_change(self, f, protocol_version): + self.schema_change_event = EventMessage.recv_schema_change(f, protocol_version) @classmethod def read_type(cls, f, user_type_map): optid = read_short(f) try: typeclass = cls.type_codes[optid] except KeyError: raise NotSupportedError("Unknown data type code 0x%04x. Have to skip" " entire result set." % (optid,)) if typeclass in (ListType, SetType): subtype = cls.read_type(f, user_type_map) typeclass = typeclass.apply_parameters((subtype,)) elif typeclass == MapType: keysubtype = cls.read_type(f, user_type_map) valsubtype = cls.read_type(f, user_type_map) typeclass = typeclass.apply_parameters((keysubtype, valsubtype)) elif typeclass == TupleType: num_items = read_short(f) types = tuple(cls.read_type(f, user_type_map) for _ in range(num_items)) typeclass = typeclass.apply_parameters(types) elif typeclass == UserType: ks = read_string(f) udt_name = read_string(f) num_fields = read_short(f) names, types = zip(*((read_string(f), cls.read_type(f, user_type_map)) for _ in range(num_fields))) specialized_type = typeclass.make_udt_class(ks, udt_name, names, types) specialized_type.mapped_class = user_type_map.get(ks, {}).get(udt_name) typeclass = specialized_type elif typeclass == CUSTOM_TYPE: classname = read_string(f) typeclass = lookup_casstype(classname) return typeclass @staticmethod def recv_row(f, colcount): return [read_value(f) for _ in range(colcount)] class PrepareMessage(_MessageType): opcode = 0x09 name = 'PREPARE' def __init__(self, query, keyspace=None): self.query = query self.keyspace = keyspace def send_body(self, f, protocol_version): write_longstring(f, self.query) flags = 0x00 if self.keyspace is not None: if ProtocolVersion.uses_keyspace_flag(protocol_version): flags |= _PREPARED_WITH_KEYSPACE_FLAG else: raise UnsupportedOperation( "Keyspaces may only be set on queries with protocol version " - "5 or higher. Consider setting Cluster.protocol_version to 5.") + "5 or DSE_V2 or higher. Consider setting Cluster.protocol_version.") if ProtocolVersion.uses_prepare_flags(protocol_version): write_uint(f, flags) else: # checks above should prevent this, but just to be safe... if flags: raise UnsupportedOperation( "Attempted to set flags with value {flags:0=#8x} on" "protocol version {pv}, which doesn't support flags" "in prepared statements." - "Consider setting Cluster.protocol_version to 5." + "Consider setting Cluster.protocol_version to 5 or DSE_V2." "".format(flags=flags, pv=protocol_version)) if ProtocolVersion.uses_keyspace_flag(protocol_version): if self.keyspace: write_string(f, self.keyspace) -class ExecuteMessage(_MessageType): - opcode = 0x0A - name = 'EXECUTE' - def __init__(self, query_id, query_params, consistency_level, - serial_consistency_level=None, fetch_size=None, - paging_state=None, timestamp=None, skip_meta=False, - result_metadata_id=None): - self.query_id = query_id - self.query_params = query_params - self.consistency_level = consistency_level - self.serial_consistency_level = serial_consistency_level - self.fetch_size = fetch_size - self.paging_state = paging_state - self.timestamp = timestamp - self.skip_meta = skip_meta - self.result_metadata_id = result_metadata_id - - def send_body(self, f, protocol_version): - write_string(f, self.query_id) - if ProtocolVersion.uses_prepared_metadata(protocol_version): - write_string(f, self.result_metadata_id) - if protocol_version == 1: - if self.serial_consistency_level: - raise UnsupportedOperation( - "Serial consistency levels require the use of protocol version " - "2 or higher. Consider setting Cluster.protocol_version to 2 " - "to support serial consistency levels.") - if self.fetch_size or self.paging_state: - raise UnsupportedOperation( - "Automatic query paging may only be used with protocol version " - "2 or higher. Consider setting Cluster.protocol_version to 2.") - write_short(f, len(self.query_params)) - for param in self.query_params: - write_value(f, param) - write_consistency_level(f, self.consistency_level) - else: - write_consistency_level(f, self.consistency_level) - flags = _VALUES_FLAG - if self.serial_consistency_level: - flags |= _WITH_SERIAL_CONSISTENCY_FLAG - if self.fetch_size: - flags |= _PAGE_SIZE_FLAG - if self.paging_state: - flags |= _WITH_PAGING_STATE_FLAG - if self.timestamp is not None: - if protocol_version >= 3: - flags |= _PROTOCOL_TIMESTAMP - else: - raise UnsupportedOperation( - "Protocol-level timestamps may only be used with protocol version " - "3 or higher. Consider setting Cluster.protocol_version to 3.") - if self.skip_meta: - flags |= _SKIP_METADATA_FLAG - - if ProtocolVersion.uses_int_query_flags(protocol_version): - write_uint(f, flags) - else: - write_byte(f, flags) - - write_short(f, len(self.query_params)) - for param in self.query_params: - write_value(f, param) - if self.fetch_size: - write_int(f, self.fetch_size) - if self.paging_state: - write_longstring(f, self.paging_state) - if self.serial_consistency_level: - write_consistency_level(f, self.serial_consistency_level) - if self.timestamp is not None: - write_long(f, self.timestamp) - - - class BatchMessage(_MessageType): opcode = 0x0D name = 'BATCH' def __init__(self, batch_type, queries, consistency_level, serial_consistency_level=None, timestamp=None, keyspace=None): self.batch_type = batch_type self.queries = queries self.consistency_level = consistency_level self.serial_consistency_level = serial_consistency_level self.timestamp = timestamp self.keyspace = keyspace def send_body(self, f, protocol_version): write_byte(f, self.batch_type.value) write_short(f, len(self.queries)) for prepared, string_or_query_id, params in self.queries: if not prepared: write_byte(f, 0) write_longstring(f, string_or_query_id) else: write_byte(f, 1) write_short(f, len(string_or_query_id)) f.write(string_or_query_id) write_short(f, len(params)) for param in params: write_value(f, param) write_consistency_level(f, self.consistency_level) if protocol_version >= 3: flags = 0 if self.serial_consistency_level: flags |= _WITH_SERIAL_CONSISTENCY_FLAG if self.timestamp is not None: - flags |= _PROTOCOL_TIMESTAMP + flags |= _PROTOCOL_TIMESTAMP_FLAG if self.keyspace: if ProtocolVersion.uses_keyspace_flag(protocol_version): flags |= _WITH_KEYSPACE_FLAG else: raise UnsupportedOperation( "Keyspaces may only be set on queries with protocol version " "5 or higher. Consider setting Cluster.protocol_version to 5.") if ProtocolVersion.uses_int_query_flags(protocol_version): write_int(f, flags) else: write_byte(f, flags) if self.serial_consistency_level: write_consistency_level(f, self.serial_consistency_level) if self.timestamp is not None: write_long(f, self.timestamp) if ProtocolVersion.uses_keyspace_flag(protocol_version): if self.keyspace is not None: write_string(f, self.keyspace) known_event_types = frozenset(( 'TOPOLOGY_CHANGE', 'STATUS_CHANGE', 'SCHEMA_CHANGE' )) class RegisterMessage(_MessageType): opcode = 0x0B name = 'REGISTER' def __init__(self, event_list): self.event_list = event_list def send_body(self, f, protocol_version): write_stringlist(f, self.event_list) class EventMessage(_MessageType): opcode = 0x0C name = 'EVENT' def __init__(self, event_type, event_args): self.event_type = event_type self.event_args = event_args @classmethod def recv_body(cls, f, protocol_version, *args): event_type = read_string(f).upper() if event_type in known_event_types: read_method = getattr(cls, 'recv_' + event_type.lower()) return cls(event_type=event_type, event_args=read_method(f, protocol_version)) raise NotSupportedError('Unknown event type %r' % event_type) @classmethod def recv_topology_change(cls, f, protocol_version): # "NEW_NODE" or "REMOVED_NODE" change_type = read_string(f) address = read_inet(f) return dict(change_type=change_type, address=address) @classmethod def recv_status_change(cls, f, protocol_version): # "UP" or "DOWN" change_type = read_string(f) address = read_inet(f) return dict(change_type=change_type, address=address) @classmethod def recv_schema_change(cls, f, protocol_version): # "CREATED", "DROPPED", or "UPDATED" change_type = read_string(f) if protocol_version >= 3: target = read_string(f) keyspace = read_string(f) event = {'target_type': target, 'change_type': change_type, 'keyspace': keyspace} if target != SchemaTargetType.KEYSPACE: target_name = read_string(f) if target == SchemaTargetType.FUNCTION: event['function'] = UserFunctionDescriptor(target_name, [read_string(f) for _ in range(read_short(f))]) elif target == SchemaTargetType.AGGREGATE: event['aggregate'] = UserAggregateDescriptor(target_name, [read_string(f) for _ in range(read_short(f))]) else: event[target.lower()] = target_name else: keyspace = read_string(f) table = read_string(f) if table: event = {'target_type': SchemaTargetType.TABLE, 'change_type': change_type, 'keyspace': keyspace, 'table': table} else: event = {'target_type': SchemaTargetType.KEYSPACE, 'change_type': change_type, 'keyspace': keyspace} return event +class ReviseRequestMessage(_MessageType): + + class RevisionType(object): + PAGING_CANCEL = 1 + PAGING_BACKPRESSURE = 2 + + opcode = 0xFF + name = 'REVISE_REQUEST' + + def __init__(self, op_type, op_id, next_pages=0): + self.op_type = op_type + self.op_id = op_id + self.next_pages = next_pages + + def send_body(self, f, protocol_version): + write_int(f, self.op_type) + write_int(f, self.op_id) + if self.op_type == ReviseRequestMessage.RevisionType.PAGING_BACKPRESSURE: + if self.next_pages <= 0: + raise UnsupportedOperation("Continuous paging backpressure requires next_pages > 0") + elif not ProtocolVersion.has_continuous_paging_next_pages(protocol_version): + raise UnsupportedOperation( + "Continuous paging backpressure may only be used with protocol version " + "ProtocolVersion.DSE_V2 or higher. Consider setting Cluster.protocol_version to ProtocolVersion.DSE_V2.") + else: + write_int(f, self.next_pages) + + class _ProtocolHandler(object): """ _ProtocolHander handles encoding and decoding messages. This class can be specialized to compose Handlers which implement alternative result decoding or type deserialization. Class definitions are passed to :class:`cassandra.cluster.Cluster` on initialization. Contracted class methods are :meth:`_ProtocolHandler.encode_message` and :meth:`_ProtocolHandler.decode_message`. """ message_types_by_opcode = _message_types_by_opcode.copy() """ Default mapping of opcode to Message implementation. The default ``decode_message`` implementation uses this to instantiate a message and populate using ``recv_body``. This mapping can be updated to inject specialized result decoding implementations. """ @classmethod def encode_message(cls, msg, stream_id, protocol_version, compressor, allow_beta_protocol_version): """ Encodes a message using the specified frame parameters, and compressor :param msg: the message, typically of cassandra.protocol._MessageType, generated by the driver :param stream_id: protocol stream id for the frame header :param protocol_version: version for the frame header, and used encoding contents :param compressor: optional compression function to be used on the body """ flags = 0 body = io.BytesIO() if msg.custom_payload: if protocol_version < 4: raise UnsupportedOperation("Custom key/value payloads can only be used with protocol version 4 or higher") flags |= CUSTOM_PAYLOAD_FLAG write_bytesmap(body, msg.custom_payload) msg.send_body(body, protocol_version) body = body.getvalue() - if compressor and len(body) > 0: + # With checksumming, the compression is done at the segment frame encoding + if (not ProtocolVersion.has_checksumming_support(protocol_version) + and compressor and len(body) > 0): body = compressor(body) flags |= COMPRESSED_FLAG if msg.tracing: flags |= TRACING_FLAG if allow_beta_protocol_version: flags |= USE_BETA_FLAG buff = io.BytesIO() cls._write_header(buff, protocol_version, flags, stream_id, msg.opcode, len(body)) buff.write(body) return buff.getvalue() @staticmethod def _write_header(f, version, flags, stream_id, opcode, length): """ Write a CQL protocol frame header. """ pack = v3_header_pack if version >= 3 else header_pack f.write(pack(version, flags, stream_id, opcode)) write_int(f, length) @classmethod def decode_message(cls, protocol_version, user_type_map, stream_id, flags, opcode, body, decompressor, result_metadata): """ Decodes a native protocol message body :param protocol_version: version to use decoding contents :param user_type_map: map[keyspace name] = map[type name] = custom type to instantiate when deserializing this type :param stream_id: native protocol stream id from the frame header :param flags: native protocol flags bitmap from the header :param opcode: native protocol opcode from the header :param body: frame body :param decompressor: optional decompression function to inflate the body :return: a message decoded from the body and frame attributes """ - if flags & COMPRESSED_FLAG: + if (not ProtocolVersion.has_checksumming_support(protocol_version) and + flags & COMPRESSED_FLAG): if decompressor is None: raise RuntimeError("No de-compressor available for compressed frame!") body = decompressor(body) flags ^= COMPRESSED_FLAG body = io.BytesIO(body) if flags & TRACING_FLAG: trace_id = UUID(bytes=body.read(16)) flags ^= TRACING_FLAG else: trace_id = None if flags & WARNING_FLAG: warnings = read_stringlist(body) flags ^= WARNING_FLAG else: warnings = None if flags & CUSTOM_PAYLOAD_FLAG: custom_payload = read_bytesmap(body) flags ^= CUSTOM_PAYLOAD_FLAG else: custom_payload = None - flags &= USE_BETA_MASK # will only be set if we asserted it in connection estabishment + flags &= USE_BETA_MASK # will only be set if we asserted it in connection estabishment if flags: log.warning("Unknown protocol flags set: %02x. May cause problems.", flags) msg_class = cls.message_types_by_opcode[opcode] msg = msg_class.recv_body(body, protocol_version, user_type_map, result_metadata) msg.stream_id = stream_id msg.trace_id = trace_id msg.custom_payload = custom_payload msg.warnings = warnings if msg.warnings: for w in msg.warnings: log.warning("Server warning: %s", w) return msg + def cython_protocol_handler(colparser): """ Given a column parser to deserialize ResultMessages, return a suitable Cython-based protocol handler. There are three Cython-based protocol handlers: - obj_parser.ListParser decodes result messages into a list of tuples - obj_parser.LazyParser decodes result messages lazily by returning an iterator - numpy_parser.NumPyParser decodes result messages into NumPy arrays The default is to use obj_parser.ListParser """ from cassandra.row_parser import make_recv_results_rows class FastResultMessage(ResultMessage): """ Cython version of Result Message that has a faster implementation of recv_results_row. """ # type_codes = ResultMessage.type_codes.copy() code_to_type = dict((v, k) for k, v in ResultMessage.type_codes.items()) - recv_results_rows = classmethod(make_recv_results_rows(colparser)) + recv_results_rows = make_recv_results_rows(colparser) class CythonProtocolHandler(_ProtocolHandler): """ Use FastResultMessage to decode query result message messages. """ my_opcodes = _ProtocolHandler.message_types_by_opcode.copy() my_opcodes[FastResultMessage.opcode] = FastResultMessage message_types_by_opcode = my_opcodes col_parser = colparser return CythonProtocolHandler if HAVE_CYTHON: from cassandra.obj_parser import ListParser, LazyParser ProtocolHandler = cython_protocol_handler(ListParser()) LazyProtocolHandler = cython_protocol_handler(LazyParser()) else: # Use Python-based ProtocolHandler ProtocolHandler = _ProtocolHandler LazyProtocolHandler = None if HAVE_CYTHON and HAVE_NUMPY: from cassandra.numpy_parser import NumpyParser NumpyProtocolHandler = cython_protocol_handler(NumpyParser()) else: NumpyProtocolHandler = None def read_byte(f): return int8_unpack(f.read(1)) def write_byte(f, b): - f.write(int8_pack(b)) + f.write(uint8_pack(b)) def read_int(f): return int32_unpack(f.read(4)) +def read_uint_le(f, size=4): + """ + Read a sequence of little endian bytes and return an unsigned integer. + """ + + if size == 4: + value = uint32_le_unpack(f.read(4)) + else: + value = 0 + for i in range(size): + value |= (read_byte(f) & 0xFF) << 8 * i + + return value + + +def write_uint_le(f, i, size=4): + """ + Write an unsigned integer on a sequence of little endian bytes. + """ + if size == 4: + f.write(uint32_le_pack(i)) + else: + for j in range(size): + shift = j * 8 + write_byte(f, i >> shift & 0xFF) + + def write_int(f, i): f.write(int32_pack(i)) def write_uint(f, i): f.write(uint32_pack(i)) def write_long(f, i): f.write(uint64_pack(i)) def read_short(f): return uint16_unpack(f.read(2)) def write_short(f, s): f.write(uint16_pack(s)) def read_consistency_level(f): return read_short(f) def write_consistency_level(f, cl): write_short(f, cl) def read_string(f): size = read_short(f) contents = f.read(size) return contents.decode('utf8') def read_binary_string(f): size = read_short(f) contents = f.read(size) return contents def write_string(f, s): if isinstance(s, six.text_type): s = s.encode('utf8') write_short(f, len(s)) f.write(s) def read_binary_longstring(f): size = read_int(f) contents = f.read(size) return contents def read_longstring(f): return read_binary_longstring(f).decode('utf8') def write_longstring(f, s): if isinstance(s, six.text_type): s = s.encode('utf8') write_int(f, len(s)) f.write(s) def read_stringlist(f): numstrs = read_short(f) return [read_string(f) for _ in range(numstrs)] def write_stringlist(f, stringlist): write_short(f, len(stringlist)) for s in stringlist: write_string(f, s) def read_stringmap(f): numpairs = read_short(f) strmap = {} for _ in range(numpairs): k = read_string(f) strmap[k] = read_string(f) return strmap def write_stringmap(f, strmap): write_short(f, len(strmap)) for k, v in strmap.items(): write_string(f, k) write_string(f, v) def read_bytesmap(f): numpairs = read_short(f) bytesmap = {} for _ in range(numpairs): k = read_string(f) bytesmap[k] = read_value(f) return bytesmap def write_bytesmap(f, bytesmap): write_short(f, len(bytesmap)) for k, v in bytesmap.items(): write_string(f, k) write_value(f, v) def read_stringmultimap(f): numkeys = read_short(f) strmmap = {} for _ in range(numkeys): k = read_string(f) strmmap[k] = read_stringlist(f) return strmmap def write_stringmultimap(f, strmmap): write_short(f, len(strmmap)) for k, v in strmmap.items(): write_string(f, k) write_stringlist(f, v) def read_error_code_map(f): numpairs = read_int(f) error_code_map = {} for _ in range(numpairs): endpoint = read_inet_addr_only(f) error_code_map[endpoint] = read_short(f) return error_code_map def read_value(f): size = read_int(f) if size < 0: return None return f.read(size) def write_value(f, v): if v is None: write_int(f, -1) elif v is _UNSET_VALUE: write_int(f, -2) else: write_int(f, len(v)) f.write(v) def read_inet_addr_only(f): size = read_byte(f) addrbytes = f.read(size) if size == 4: addrfam = socket.AF_INET elif size == 16: addrfam = socket.AF_INET6 else: raise InternalError("bad inet address: %r" % (addrbytes,)) return util.inet_ntop(addrfam, addrbytes) def read_inet(f): addr = read_inet_addr_only(f) port = read_int(f) return (addr, port) def write_inet(f, addrtuple): addr, port = addrtuple if ':' in addr: addrfam = socket.AF_INET6 else: addrfam = socket.AF_INET addrbytes = util.inet_pton(addrfam, addr) write_byte(f, len(addrbytes)) f.write(addrbytes) write_int(f, port) diff --git a/cassandra/query.py b/cassandra/query.py index 74a9896..0e7a41d 100644 --- a/cassandra/query.py +++ b/cassandra/query.py @@ -1,1089 +1,1102 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This module holds classes for working with prepared statements and specifying consistency levels and retry policies for individual queries. """ from collections import namedtuple from datetime import datetime, timedelta import re import struct import time import six from six.moves import range, zip import warnings from cassandra import ConsistencyLevel, OperationTimedOut from cassandra.util import unix_time_from_uuid1 from cassandra.encoder import Encoder import cassandra.encoder from cassandra.protocol import _UNSET_VALUE from cassandra.util import OrderedDict, _sanitize_identifiers import logging log = logging.getLogger(__name__) UNSET_VALUE = _UNSET_VALUE """ Specifies an unset value when binding a prepared statement. Unset values are ignored, allowing prepared statements to be used without specify See https://issues.apache.org/jira/browse/CASSANDRA-7304 for further details on semantics. .. versionadded:: 2.6.0 Only valid when using native protocol v4+ """ NON_ALPHA_REGEX = re.compile('[^a-zA-Z0-9]') START_BADCHAR_REGEX = re.compile('^[^a-zA-Z0-9]*') END_BADCHAR_REGEX = re.compile('[^a-zA-Z0-9_]*$') _clean_name_cache = {} def _clean_column_name(name): try: return _clean_name_cache[name] except KeyError: clean = NON_ALPHA_REGEX.sub("_", START_BADCHAR_REGEX.sub("", END_BADCHAR_REGEX.sub("", name))) _clean_name_cache[name] = clean return clean def tuple_factory(colnames, rows): """ Returns each row as a tuple Example:: >>> from cassandra.query import tuple_factory >>> session = cluster.connect('mykeyspace') >>> session.row_factory = tuple_factory >>> rows = session.execute("SELECT name, age FROM users LIMIT 1") >>> print rows[0] ('Bob', 42) .. versionchanged:: 2.0.0 moved from ``cassandra.decoder`` to ``cassandra.query`` """ return rows class PseudoNamedTupleRow(object): """ Helper class for pseudo_named_tuple_factory. These objects provide an __iter__ interface, as well as index- and attribute-based access to values, but otherwise do not attempt to implement the full namedtuple or iterable interface. """ def __init__(self, ordered_dict): self._dict = ordered_dict self._tuple = tuple(ordered_dict.values()) def __getattr__(self, name): return self._dict[name] def __getitem__(self, idx): return self._tuple[idx] def __iter__(self): return iter(self._tuple) def __repr__(self): return '{t}({od})'.format(t=self.__class__.__name__, od=self._dict) def pseudo_namedtuple_factory(colnames, rows): """ Returns each row as a :class:`.PseudoNamedTupleRow`. This is the fallback factory for cases where :meth:`.named_tuple_factory` fails to create rows. """ return [PseudoNamedTupleRow(od) for od in ordered_dict_factory(colnames, rows)] def named_tuple_factory(colnames, rows): """ Returns each row as a `namedtuple `_. This is the default row factory. Example:: >>> from cassandra.query import named_tuple_factory >>> session = cluster.connect('mykeyspace') >>> session.row_factory = named_tuple_factory >>> rows = session.execute("SELECT name, age FROM users LIMIT 1") >>> user = rows[0] >>> # you can access field by their name: >>> print "name: %s, age: %d" % (user.name, user.age) name: Bob, age: 42 >>> # or you can access fields by their position (like a tuple) >>> name, age = user >>> print "name: %s, age: %d" % (name, age) name: Bob, age: 42 >>> name = user[0] >>> age = user[1] >>> print "name: %s, age: %d" % (name, age) name: Bob, age: 42 .. versionchanged:: 2.0.0 moved from ``cassandra.decoder`` to ``cassandra.query`` """ clean_column_names = map(_clean_column_name, colnames) try: Row = namedtuple('Row', clean_column_names) except SyntaxError: warnings.warn( "Failed creating namedtuple for a result because there were too " "many columns. This is due to a Python limitation that affects " "namedtuple in Python 3.0-3.6 (see issue18896). The row will be " "created with {substitute_factory_name}, which lacks some namedtuple " "features and is slower. To avoid slower performance accessing " "values on row objects, Upgrade to Python 3.7, or use a different " "row factory. (column names: {colnames})".format( substitute_factory_name=pseudo_namedtuple_factory.__name__, colnames=colnames ) ) return pseudo_namedtuple_factory(colnames, rows) except Exception: clean_column_names = list(map(_clean_column_name, colnames)) # create list because py3 map object will be consumed by first attempt log.warning("Failed creating named tuple for results with column names %s (cleaned: %s) " "(see Python 'namedtuple' documentation for details on name rules). " "Results will be returned with positional names. " "Avoid this by choosing different names, using SELECT \"\" AS aliases, " "or specifying a different row_factory on your Session" % (colnames, clean_column_names)) Row = namedtuple('Row', _sanitize_identifiers(clean_column_names)) return [Row(*row) for row in rows] def dict_factory(colnames, rows): """ Returns each row as a dict. Example:: >>> from cassandra.query import dict_factory >>> session = cluster.connect('mykeyspace') >>> session.row_factory = dict_factory >>> rows = session.execute("SELECT name, age FROM users LIMIT 1") >>> print rows[0] {u'age': 42, u'name': u'Bob'} .. versionchanged:: 2.0.0 moved from ``cassandra.decoder`` to ``cassandra.query`` """ return [dict(zip(colnames, row)) for row in rows] def ordered_dict_factory(colnames, rows): """ Like :meth:`~cassandra.query.dict_factory`, but returns each row as an OrderedDict, so the order of the columns is preserved. .. versionchanged:: 2.0.0 moved from ``cassandra.decoder`` to ``cassandra.query`` """ return [OrderedDict(zip(colnames, row)) for row in rows] FETCH_SIZE_UNSET = object() class Statement(object): """ An abstract class representing a single query. There are three subclasses: :class:`.SimpleStatement`, :class:`.BoundStatement`, and :class:`.BatchStatement`. These can be passed to :meth:`.Session.execute()`. """ retry_policy = None """ An instance of a :class:`cassandra.policies.RetryPolicy` or one of its subclasses. This controls when a query will be retried and how it will be retried. """ consistency_level = None """ The :class:`.ConsistencyLevel` to be used for this operation. Defaults to :const:`None`, which means that the default consistency level for the Session this is executed in will be used. """ fetch_size = FETCH_SIZE_UNSET """ How many rows will be fetched at a time. This overrides the default of :attr:`.Session.default_fetch_size` This only takes effect when protocol version 2 or higher is used. See :attr:`.Cluster.protocol_version` for details. .. versionadded:: 2.0.0 """ keyspace = None """ The string name of the keyspace this query acts on. This is used when - :class:`~.TokenAwarePolicy` is configured for - :attr:`.Cluster.load_balancing_policy` + :class:`~.TokenAwarePolicy` is configured in the profile load balancing policy. It is set implicitly on :class:`.BoundStatement`, and :class:`.BatchStatement`, but must be set explicitly on :class:`.SimpleStatement`. .. versionadded:: 2.1.3 """ custom_payload = None """ :ref:`custom_payload` to be passed to the server. These are only allowed when using protocol version 4 or higher. .. versionadded:: 2.6.0 """ is_idempotent = False """ Flag indicating whether this statement is safe to run multiple times in speculative execution. """ _serial_consistency_level = None _routing_key = None def __init__(self, retry_policy=None, consistency_level=None, routing_key=None, serial_consistency_level=None, fetch_size=FETCH_SIZE_UNSET, keyspace=None, custom_payload=None, is_idempotent=False): if retry_policy and not hasattr(retry_policy, 'on_read_timeout'): # just checking one method to detect positional parameter errors raise ValueError('retry_policy should implement cassandra.policies.RetryPolicy') if retry_policy is not None: self.retry_policy = retry_policy if consistency_level is not None: self.consistency_level = consistency_level self._routing_key = routing_key if serial_consistency_level is not None: self.serial_consistency_level = serial_consistency_level if fetch_size is not FETCH_SIZE_UNSET: self.fetch_size = fetch_size if keyspace is not None: self.keyspace = keyspace if custom_payload is not None: self.custom_payload = custom_payload self.is_idempotent = is_idempotent def _key_parts_packed(self, parts): for p in parts: l = len(p) yield struct.pack(">H%dsB" % l, l, p, 0) def _get_routing_key(self): return self._routing_key def _set_routing_key(self, key): if isinstance(key, (list, tuple)): if len(key) == 1: self._routing_key = key[0] else: self._routing_key = b"".join(self._key_parts_packed(key)) else: self._routing_key = key def _del_routing_key(self): self._routing_key = None routing_key = property( _get_routing_key, _set_routing_key, _del_routing_key, """ The :attr:`~.TableMetadata.partition_key` portion of the primary key, which can be used to determine which nodes are replicas for the query. If the partition key is a composite, a list or tuple must be passed in. Each key component should be in its packed (binary) format, so all components should be strings. """) def _get_serial_consistency_level(self): return self._serial_consistency_level def _set_serial_consistency_level(self, serial_consistency_level): if (serial_consistency_level is not None and not ConsistencyLevel.is_serial(serial_consistency_level)): raise ValueError( "serial_consistency_level must be either ConsistencyLevel.SERIAL " "or ConsistencyLevel.LOCAL_SERIAL") self._serial_consistency_level = serial_consistency_level def _del_serial_consistency_level(self): self._serial_consistency_level = None serial_consistency_level = property( _get_serial_consistency_level, _set_serial_consistency_level, _del_serial_consistency_level, """ The serial consistency level is only used by conditional updates (``INSERT``, ``UPDATE`` and ``DELETE`` with an ``IF`` condition). For those, the ``serial_consistency_level`` defines the consistency level of the serial phase (or "paxos" phase) while the normal :attr:`~.consistency_level` defines the consistency for the "learn" phase, i.e. what type of reads will be guaranteed to see the update right away. For example, if a conditional write has a :attr:`~.consistency_level` of :attr:`~.ConsistencyLevel.QUORUM` (and is successful), then a :attr:`~.ConsistencyLevel.QUORUM` read is guaranteed to see that write. But if the regular :attr:`~.consistency_level` of that write is :attr:`~.ConsistencyLevel.ANY`, then only a read with a :attr:`~.consistency_level` of :attr:`~.ConsistencyLevel.SERIAL` is guaranteed to see it (even a read with consistency :attr:`~.ConsistencyLevel.ALL` is not guaranteed to be enough). The serial consistency can only be one of :attr:`~.ConsistencyLevel.SERIAL` or :attr:`~.ConsistencyLevel.LOCAL_SERIAL`. While ``SERIAL`` guarantees full linearizability (with other ``SERIAL`` updates), ``LOCAL_SERIAL`` only guarantees it in the local data center. The serial consistency level is ignored for any query that is not a conditional update. Serial reads should use the regular :attr:`consistency_level`. Serial consistency levels may only be used against Cassandra 2.0+ and the :attr:`~.Cluster.protocol_version` must be set to 2 or higher. See :doc:`/lwt` for a discussion on how to work with results returned from conditional statements. .. versionadded:: 2.0.0 """) class SimpleStatement(Statement): """ A simple, un-prepared query. """ def __init__(self, query_string, retry_policy=None, consistency_level=None, routing_key=None, serial_consistency_level=None, fetch_size=FETCH_SIZE_UNSET, keyspace=None, custom_payload=None, is_idempotent=False): """ `query_string` should be a literal CQL statement with the exception of parameter placeholders that will be filled through the `parameters` argument of :meth:`.Session.execute()`. See :class:`Statement` attributes for a description of the other parameters. """ Statement.__init__(self, retry_policy, consistency_level, routing_key, serial_consistency_level, fetch_size, keyspace, custom_payload, is_idempotent) self._query_string = query_string @property def query_string(self): return self._query_string def __str__(self): consistency = ConsistencyLevel.value_to_name.get(self.consistency_level, 'Not Set') return (u'' % (self.query_string, consistency)) __repr__ = __str__ class PreparedStatement(object): """ A statement that has been prepared against at least one Cassandra node. Instances of this class should not be created directly, but through :meth:`.Session.prepare()`. A :class:`.PreparedStatement` should be prepared only once. Re-preparing a statement may affect performance (as the operation requires a network roundtrip). |prepared_stmt_head|: Do not use ``*`` in prepared statements if you might change the schema of the table being queried. The driver and server each maintain a map between metadata for a schema and statements that were prepared against that schema. When a user changes a schema, e.g. by adding or removing a column, the server invalidates its mappings involving that schema. However, there is currently no way to propagate that invalidation to drivers. Thus, after a schema change, the driver will incorrectly interpret the results of ``SELECT *`` queries prepared before the schema change. This is currently being addressed in `CASSANDRA-10786 `_. .. |prepared_stmt_head| raw:: html A note about * in prepared statements """ column_metadata = None #TODO: make this bind_metadata in next major retry_policy = None consistency_level = None custom_payload = None fetch_size = FETCH_SIZE_UNSET keyspace = None # change to prepared_keyspace in major release protocol_version = None query_id = None query_string = None result_metadata = None result_metadata_id = None routing_key_indexes = None _routing_key_index_set = None serial_consistency_level = None # TODO never used? def __init__(self, column_metadata, query_id, routing_key_indexes, query, keyspace, protocol_version, result_metadata, result_metadata_id): self.column_metadata = column_metadata self.query_id = query_id self.routing_key_indexes = routing_key_indexes self.query_string = query self.keyspace = keyspace self.protocol_version = protocol_version self.result_metadata = result_metadata self.result_metadata_id = result_metadata_id self.is_idempotent = False @classmethod def from_message(cls, query_id, column_metadata, pk_indexes, cluster_metadata, query, prepared_keyspace, protocol_version, result_metadata, result_metadata_id): if not column_metadata: return PreparedStatement(column_metadata, query_id, None, query, prepared_keyspace, protocol_version, result_metadata, result_metadata_id) if pk_indexes: routing_key_indexes = pk_indexes else: routing_key_indexes = None first_col = column_metadata[0] ks_meta = cluster_metadata.keyspaces.get(first_col.keyspace_name) if ks_meta: table_meta = ks_meta.tables.get(first_col.table_name) if table_meta: partition_key_columns = table_meta.partition_key # make a map of {column_name: index} for each column in the statement statement_indexes = dict((c.name, i) for i, c in enumerate(column_metadata)) # a list of which indexes in the statement correspond to partition key items try: routing_key_indexes = [statement_indexes[c.name] for c in partition_key_columns] except KeyError: # we're missing a partition key component in the prepared pass # statement; just leave routing_key_indexes as None return PreparedStatement(column_metadata, query_id, routing_key_indexes, query, prepared_keyspace, protocol_version, result_metadata, result_metadata_id) def bind(self, values): """ Creates and returns a :class:`BoundStatement` instance using `values`. See :meth:`BoundStatement.bind` for rules on input ``values``. """ return BoundStatement(self).bind(values) def is_routing_key_index(self, i): if self._routing_key_index_set is None: self._routing_key_index_set = set(self.routing_key_indexes) if self.routing_key_indexes else set() return i in self._routing_key_index_set def __str__(self): consistency = ConsistencyLevel.value_to_name.get(self.consistency_level, 'Not Set') return (u'' % (self.query_string, consistency)) __repr__ = __str__ class BoundStatement(Statement): """ A prepared statement that has been bound to a particular set of values. These may be created directly or through :meth:`.PreparedStatement.bind()`. """ prepared_statement = None """ The :class:`PreparedStatement` instance that this was created from. """ values = None """ The sequence of values that were bound to the prepared statement. """ def __init__(self, prepared_statement, retry_policy=None, consistency_level=None, routing_key=None, serial_consistency_level=None, fetch_size=FETCH_SIZE_UNSET, keyspace=None, custom_payload=None): """ `prepared_statement` should be an instance of :class:`PreparedStatement`. See :class:`Statement` attributes for a description of the other parameters. """ self.prepared_statement = prepared_statement self.retry_policy = prepared_statement.retry_policy self.consistency_level = prepared_statement.consistency_level self.serial_consistency_level = prepared_statement.serial_consistency_level self.fetch_size = prepared_statement.fetch_size self.custom_payload = prepared_statement.custom_payload self.is_idempotent = prepared_statement.is_idempotent self.values = [] meta = prepared_statement.column_metadata if meta: self.keyspace = meta[0].keyspace_name Statement.__init__(self, retry_policy, consistency_level, routing_key, serial_consistency_level, fetch_size, keyspace, custom_payload, prepared_statement.is_idempotent) def bind(self, values): """ Binds a sequence of values for the prepared statement parameters and returns this instance. Note that `values` *must* be: * a sequence, even if you are only binding one value, or * a dict that relates 1-to-1 between dict keys and columns .. versionchanged:: 2.6.0 :data:`~.UNSET_VALUE` was introduced. These can be bound as positional parameters in a sequence, or by name in a dict. Additionally, when using protocol v4+: * short sequences will be extended to match bind parameters with UNSET_VALUE * names may be omitted from a dict with UNSET_VALUE implied. .. versionchanged:: 3.0.0 method will not throw if extra keys are present in bound dict (PYTHON-178) """ if values is None: values = () proto_version = self.prepared_statement.protocol_version col_meta = self.prepared_statement.column_metadata # special case for binding dicts if isinstance(values, dict): values_dict = values values = [] # sort values accordingly for col in col_meta: try: values.append(values_dict[col.name]) except KeyError: if proto_version >= 4: values.append(UNSET_VALUE) else: raise KeyError( 'Column name `%s` not found in bound dict.' % (col.name)) value_len = len(values) col_meta_len = len(col_meta) if value_len > col_meta_len: raise ValueError( "Too many arguments provided to bind() (got %d, expected %d)" % (len(values), len(col_meta))) # this is fail-fast for clarity pre-v4. When v4 can be assumed, # the error will be better reported when UNSET_VALUE is implicitly added. if proto_version < 4 and self.prepared_statement.routing_key_indexes and \ value_len < len(self.prepared_statement.routing_key_indexes): raise ValueError( "Too few arguments provided to bind() (got %d, required %d for routing key)" % (value_len, len(self.prepared_statement.routing_key_indexes))) self.raw_values = values self.values = [] for value, col_spec in zip(values, col_meta): if value is None: self.values.append(None) elif value is UNSET_VALUE: if proto_version >= 4: self._append_unset_value() else: raise ValueError("Attempt to bind UNSET_VALUE while using unsuitable protocol version (%d < 4)" % proto_version) else: try: self.values.append(col_spec.type.serialize(value, proto_version)) except (TypeError, struct.error) as exc: actual_type = type(value) message = ('Received an argument of invalid type for column "%s". ' 'Expected: %s, Got: %s; (%s)' % (col_spec.name, col_spec.type, actual_type, exc)) raise TypeError(message) if proto_version >= 4: diff = col_meta_len - len(self.values) if diff: for _ in range(diff): self._append_unset_value() return self def _append_unset_value(self): next_index = len(self.values) if self.prepared_statement.is_routing_key_index(next_index): col_meta = self.prepared_statement.column_metadata[next_index] raise ValueError("Cannot bind UNSET_VALUE as a part of the routing key '%s'" % col_meta.name) self.values.append(UNSET_VALUE) @property def routing_key(self): if not self.prepared_statement.routing_key_indexes: return None if self._routing_key is not None: return self._routing_key routing_indexes = self.prepared_statement.routing_key_indexes if len(routing_indexes) == 1: self._routing_key = self.values[routing_indexes[0]] else: self._routing_key = b"".join(self._key_parts_packed(self.values[i] for i in routing_indexes)) return self._routing_key def __str__(self): consistency = ConsistencyLevel.value_to_name.get(self.consistency_level, 'Not Set') return (u'' % (self.prepared_statement.query_string, self.raw_values, consistency)) __repr__ = __str__ class BatchType(object): """ A BatchType is used with :class:`.BatchStatement` instances to control the atomicity of the batch operation. .. versionadded:: 2.0.0 """ LOGGED = None """ Atomic batch operation. """ UNLOGGED = None """ Non-atomic batch operation. """ COUNTER = None """ Batches of counter operations. """ def __init__(self, name, value): self.name = name self.value = value def __str__(self): return self.name def __repr__(self): return "BatchType.%s" % (self.name, ) BatchType.LOGGED = BatchType("LOGGED", 0) BatchType.UNLOGGED = BatchType("UNLOGGED", 1) BatchType.COUNTER = BatchType("COUNTER", 2) class BatchStatement(Statement): """ A protocol-level batch of operations which are applied atomically by default. .. versionadded:: 2.0.0 """ batch_type = None """ The :class:`.BatchType` for the batch operation. Defaults to :attr:`.BatchType.LOGGED`. """ serial_consistency_level = None """ The same as :attr:`.Statement.serial_consistency_level`, but is only supported when using protocol version 3 or higher. """ _statements_and_parameters = None _session = None def __init__(self, batch_type=BatchType.LOGGED, retry_policy=None, consistency_level=None, serial_consistency_level=None, session=None, custom_payload=None): """ `batch_type` specifies The :class:`.BatchType` for the batch operation. Defaults to :attr:`.BatchType.LOGGED`. `retry_policy` should be a :class:`~.RetryPolicy` instance for controlling retries on the operation. `consistency_level` should be a :class:`~.ConsistencyLevel` value to be used for all operations in the batch. `custom_payload` is a :ref:`custom_payload` passed to the server. Note: as Statement objects are added to the batch, this map is updated with any values found in their custom payloads. These are only allowed when using protocol version 4 or higher. Example usage: .. code-block:: python insert_user = session.prepare("INSERT INTO users (name, age) VALUES (?, ?)") batch = BatchStatement(consistency_level=ConsistencyLevel.QUORUM) for (name, age) in users_to_insert: batch.add(insert_user, (name, age)) session.execute(batch) You can also mix different types of operations within a batch: .. code-block:: python batch = BatchStatement() batch.add(SimpleStatement("INSERT INTO users (name, age) VALUES (%s, %s)"), (name, age)) batch.add(SimpleStatement("DELETE FROM pending_users WHERE name=%s"), (name,)) session.execute(batch) .. versionadded:: 2.0.0 .. versionchanged:: 2.1.0 Added `serial_consistency_level` as a parameter .. versionchanged:: 2.6.0 Added `custom_payload` as a parameter """ self.batch_type = batch_type self._statements_and_parameters = [] self._session = session Statement.__init__(self, retry_policy=retry_policy, consistency_level=consistency_level, serial_consistency_level=serial_consistency_level, custom_payload=custom_payload) def clear(self): """ This is a convenience method to clear a batch statement for reuse. *Note:* it should not be used concurrently with uncompleted execution futures executing the same ``BatchStatement``. """ del self._statements_and_parameters[:] self.keyspace = None self.routing_key = None if self.custom_payload: self.custom_payload.clear() def add(self, statement, parameters=None): """ Adds a :class:`.Statement` and optional sequence of parameters to be used with the statement to the batch. Like with other statements, parameters must be a sequence, even if there is only one item. """ if isinstance(statement, six.string_types): if parameters: encoder = Encoder() if self._session is None else self._session.encoder statement = bind_params(statement, parameters, encoder) self._add_statement_and_params(False, statement, ()) elif isinstance(statement, PreparedStatement): query_id = statement.query_id bound_statement = statement.bind(() if parameters is None else parameters) self._update_state(bound_statement) self._add_statement_and_params(True, query_id, bound_statement.values) elif isinstance(statement, BoundStatement): if parameters: raise ValueError( "Parameters cannot be passed with a BoundStatement " "to BatchStatement.add()") self._update_state(statement) self._add_statement_and_params(True, statement.prepared_statement.query_id, statement.values) else: # it must be a SimpleStatement query_string = statement.query_string if parameters: encoder = Encoder() if self._session is None else self._session.encoder query_string = bind_params(query_string, parameters, encoder) self._update_state(statement) self._add_statement_and_params(False, query_string, ()) return self def add_all(self, statements, parameters): """ Adds a sequence of :class:`.Statement` objects and a matching sequence of parameters to the batch. Statement and parameter sequences must be of equal length or one will be truncated. :const:`None` can be used in the parameters position where are needed. """ for statement, value in zip(statements, parameters): self.add(statement, value) def _add_statement_and_params(self, is_prepared, statement, parameters): if len(self._statements_and_parameters) >= 0xFFFF: raise ValueError("Batch statement cannot contain more than %d statements." % 0xFFFF) self._statements_and_parameters.append((is_prepared, statement, parameters)) def _maybe_set_routing_attributes(self, statement): if self.routing_key is None: if statement.keyspace and statement.routing_key: self.routing_key = statement.routing_key self.keyspace = statement.keyspace def _update_custom_payload(self, statement): if statement.custom_payload: if self.custom_payload is None: self.custom_payload = {} self.custom_payload.update(statement.custom_payload) def _update_state(self, statement): self._maybe_set_routing_attributes(statement) self._update_custom_payload(statement) def __len__(self): return len(self._statements_and_parameters) def __str__(self): consistency = ConsistencyLevel.value_to_name.get(self.consistency_level, 'Not Set') return (u'' % (self.batch_type, len(self), consistency)) __repr__ = __str__ ValueSequence = cassandra.encoder.ValueSequence """ A wrapper class that is used to specify that a sequence of values should be treated as a CQL list of values instead of a single column collection when used as part of the `parameters` argument for :meth:`.Session.execute()`. This is typically needed when supplying a list of keys to select. For example:: >>> my_user_ids = ('alice', 'bob', 'charles') >>> query = "SELECT * FROM users WHERE user_id IN %s" >>> session.execute(query, parameters=[ValueSequence(my_user_ids)]) """ def bind_params(query, params, encoder): if six.PY2 and isinstance(query, six.text_type): query = query.encode('utf-8') if isinstance(params, dict): return query % dict((k, encoder.cql_encode_all_types(v)) for k, v in six.iteritems(params)) else: return query % tuple(encoder.cql_encode_all_types(v) for v in params) class TraceUnavailable(Exception): """ Raised when complete trace details cannot be fetched from Cassandra. """ pass class QueryTrace(object): """ A trace of the duration and events that occurred when executing an operation. """ trace_id = None """ :class:`uuid.UUID` unique identifier for this tracing session. Matches the ``session_id`` column in ``system_traces.sessions`` and ``system_traces.events``. """ request_type = None """ A string that very generally describes the traced operation. """ duration = None """ A :class:`datetime.timedelta` measure of the duration of the query. """ client = None """ The IP address of the client that issued this request This is only available when using Cassandra 2.2+ """ coordinator = None """ The IP address of the host that acted as coordinator for this request. """ parameters = None """ A :class:`dict` of parameters for the traced operation, such as the specific query string. """ started_at = None """ A UTC :class:`datetime.datetime` object describing when the operation was started. """ events = None """ A chronologically sorted list of :class:`.TraceEvent` instances representing the steps the traced operation went through. This corresponds to the rows in ``system_traces.events`` for this tracing session. """ _session = None _SELECT_SESSIONS_FORMAT = "SELECT * FROM system_traces.sessions WHERE session_id = %s" _SELECT_EVENTS_FORMAT = "SELECT * FROM system_traces.events WHERE session_id = %s" _BASE_RETRY_SLEEP = 0.003 def __init__(self, trace_id, session): self.trace_id = trace_id self._session = session def populate(self, max_wait=2.0, wait_for_complete=True, query_cl=None): """ Retrieves the actual tracing details from Cassandra and populates the attributes of this instance. Because tracing details are stored asynchronously by Cassandra, this may need to retry the session detail fetch. If the trace is still not available after `max_wait` seconds, :exc:`.TraceUnavailable` will be raised; if `max_wait` is :const:`None`, this will retry forever. `wait_for_complete=False` bypasses the wait for duration to be populated. This can be used to query events from partial sessions. `query_cl` specifies a consistency level to use for polling the trace tables, if it should be different than the session default. """ attempt = 0 start = time.time() while True: time_spent = time.time() - start if max_wait is not None and time_spent >= max_wait: raise TraceUnavailable( "Trace information was not available within %f seconds. Consider raising Session.max_trace_wait." % (max_wait,)) log.debug("Attempting to fetch trace info for trace ID: %s", self.trace_id) session_results = self._execute( SimpleStatement(self._SELECT_SESSIONS_FORMAT, consistency_level=query_cl), (self.trace_id,), time_spent, max_wait) # PYTHON-730: There is race condition that the duration mutation is written before started_at the for fast queries is_complete = session_results and session_results[0].duration is not None and session_results[0].started_at is not None if not session_results or (wait_for_complete and not is_complete): time.sleep(self._BASE_RETRY_SLEEP * (2 ** attempt)) attempt += 1 continue if is_complete: log.debug("Fetched trace info for trace ID: %s", self.trace_id) else: log.debug("Fetching parital trace info for trace ID: %s", self.trace_id) session_row = session_results[0] self.request_type = session_row.request self.duration = timedelta(microseconds=session_row.duration) if is_complete else None self.started_at = session_row.started_at self.coordinator = session_row.coordinator self.parameters = session_row.parameters # since C* 2.2 self.client = getattr(session_row, 'client', None) log.debug("Attempting to fetch trace events for trace ID: %s", self.trace_id) time_spent = time.time() - start event_results = self._execute( SimpleStatement(self._SELECT_EVENTS_FORMAT, consistency_level=query_cl), (self.trace_id,), time_spent, max_wait) log.debug("Fetched trace events for trace ID: %s", self.trace_id) self.events = tuple(TraceEvent(r.activity, r.event_id, r.source, r.source_elapsed, r.thread) for r in event_results) break def _execute(self, query, parameters, time_spent, max_wait): timeout = (max_wait - time_spent) if max_wait is not None else None future = self._session._create_response_future(query, parameters, trace=False, custom_payload=None, timeout=timeout) # in case the user switched the row factory, set it to namedtuple for this query future.row_factory = named_tuple_factory future.send_request() try: return future.result() except OperationTimedOut: raise TraceUnavailable("Trace information was not available within %f seconds" % (max_wait,)) def __str__(self): return "%s [%s] coordinator: %s, started at: %s, duration: %s, parameters: %s" \ % (self.request_type, self.trace_id, self.coordinator, self.started_at, self.duration, self.parameters) class TraceEvent(object): """ Representation of a single event within a query trace. """ description = None """ A brief description of the event. """ datetime = None """ A UTC :class:`datetime.datetime` marking when the event occurred. """ source = None """ The IP address of the node this event occurred on. """ source_elapsed = None """ A :class:`datetime.timedelta` measuring the amount of time until this event occurred starting from when :attr:`.source` first received the query. """ thread_name = None """ The name of the thread that this event occurred on. """ def __init__(self, description, timeuuid, source, source_elapsed, thread_name): self.description = description self.datetime = datetime.utcfromtimestamp(unix_time_from_uuid1(timeuuid)) self.source = source if source_elapsed is not None: self.source_elapsed = timedelta(microseconds=source_elapsed) else: self.source_elapsed = None self.thread_name = thread_name def __str__(self): return "%s on %s[%s] at %s" % (self.description, self.source, self.thread_name, self.datetime) + + +# TODO remove next major since we can target using the `host` attribute of session.execute +class HostTargetingStatement(object): + """ + Wraps any query statement and attaches a target host, making + it usable in a targeted LBP without modifying the user's statement. + """ + def __init__(self, inner_statement, target_host): + self.__class__ = type(inner_statement.__class__.__name__, + (self.__class__, inner_statement.__class__), + {}) + self.__dict__ = inner_statement.__dict__ + self.target_host = target_host diff --git a/cassandra/row_parser.pyx b/cassandra/row_parser.pyx index 49fafd3..3a4b2f4 100644 --- a/cassandra/row_parser.pyx +++ b/cassandra/row_parser.pyx @@ -1,50 +1,48 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from cassandra.parsing cimport ParseDesc, ColumnParser from cassandra.obj_parser import TupleRowParser from cassandra.deserializers import make_deserializers include "ioutils.pyx" def make_recv_results_rows(ColumnParser colparser): - def recv_results_rows(cls, f, int protocol_version, user_type_map, result_metadata): + def recv_results_rows(self, f, int protocol_version, user_type_map, result_metadata): """ Parse protocol data given as a BytesIO f into a set of columns (e.g. list of tuples) This is used as the recv_results_rows method of (Fast)ResultMessage """ - paging_state, column_metadata, result_metadata_id = cls.recv_results_metadata(f, user_type_map) + self.recv_results_metadata(f, user_type_map) - column_metadata = column_metadata or result_metadata + column_metadata = self.column_metadata or result_metadata - colnames = [c[2] for c in column_metadata] - coltypes = [c[3] for c in column_metadata] + self.column_names = [c[2] for c in column_metadata] + self.column_types = [c[3] for c in column_metadata] - desc = ParseDesc(colnames, coltypes, make_deserializers(coltypes), + desc = ParseDesc(self.column_names, self.column_types, make_deserializers(self.column_types), protocol_version) reader = BytesIOReader(f.read()) try: - parsed_rows = colparser.parse_rows(reader, desc) + self.parsed_rows = colparser.parse_rows(reader, desc) except Exception as e: # Use explicitly the TupleRowParser to display better error messages for column decoding failures rowparser = TupleRowParser() reader.buf_ptr = reader.buf reader.pos = 0 rowcount = read_int(reader) for i in range(rowcount): rowparser.unpack_row(reader, desc) - return (paging_state, coltypes, (colnames, parsed_rows), result_metadata_id) - return recv_results_rows diff --git a/cassandra/segment.py b/cassandra/segment.py new file mode 100644 index 0000000..e3881c4 --- /dev/null +++ b/cassandra/segment.py @@ -0,0 +1,224 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import zlib +import six + +from cassandra import DriverException +from cassandra.marshal import int32_pack +from cassandra.protocol import write_uint_le, read_uint_le + +CRC24_INIT = 0x875060 +CRC24_POLY = 0x1974F0B +CRC24_LENGTH = 3 +CRC32_LENGTH = 4 +CRC32_INITIAL = zlib.crc32(b"\xfa\x2d\x55\xca") + + +class CrcException(Exception): + """ + CRC mismatch error. + + TODO: here to avoid import cycles with cassandra.connection. In the next + major, the exceptions should be declared in a separated exceptions.py + file. + """ + pass + + +def compute_crc24(data, length): + crc = CRC24_INIT + + for _ in range(length): + crc ^= (data & 0xff) << 16 + data >>= 8 + + for i in range(8): + crc <<= 1 + if crc & 0x1000000 != 0: + crc ^= CRC24_POLY + + return crc + + +def compute_crc32(data, value): + crc32 = zlib.crc32(data, value) + if six.PY2: + crc32 &= 0xffffffff + + return crc32 + + +class SegmentHeader(object): + + payload_length = None + uncompressed_payload_length = None + is_self_contained = None + + def __init__(self, payload_length, uncompressed_payload_length, is_self_contained): + self.payload_length = payload_length + self.uncompressed_payload_length = uncompressed_payload_length + self.is_self_contained = is_self_contained + + @property + def segment_length(self): + """ + Return the total length of the segment, including the CRC. + """ + hl = SegmentCodec.UNCOMPRESSED_HEADER_LENGTH if self.uncompressed_payload_length < 1 \ + else SegmentCodec.COMPRESSED_HEADER_LENGTH + return hl + CRC24_LENGTH + self.payload_length + CRC32_LENGTH + + +class Segment(object): + + MAX_PAYLOAD_LENGTH = 128 * 1024 - 1 + + payload = None + is_self_contained = None + + def __init__(self, payload, is_self_contained): + self.payload = payload + self.is_self_contained = is_self_contained + + +class SegmentCodec(object): + + COMPRESSED_HEADER_LENGTH = 5 + UNCOMPRESSED_HEADER_LENGTH = 3 + FLAG_OFFSET = 17 + + compressor = None + decompressor = None + + def __init__(self, compressor=None, decompressor=None): + self.compressor = compressor + self.decompressor = decompressor + + @property + def header_length(self): + return self.COMPRESSED_HEADER_LENGTH if self.compression \ + else self.UNCOMPRESSED_HEADER_LENGTH + + @property + def header_length_with_crc(self): + return (self.COMPRESSED_HEADER_LENGTH if self.compression + else self.UNCOMPRESSED_HEADER_LENGTH) + CRC24_LENGTH + + @property + def compression(self): + return self.compressor and self.decompressor + + def compress(self, data): + # the uncompressed length is already encoded in the header, so + # we remove it here + return self.compressor(data)[4:] + + def decompress(self, encoded_data, uncompressed_length): + return self.decompressor(int32_pack(uncompressed_length) + encoded_data) + + def encode_header(self, buffer, payload_length, uncompressed_length, is_self_contained): + if payload_length > Segment.MAX_PAYLOAD_LENGTH: + raise DriverException('Payload length exceed Segment.MAX_PAYLOAD_LENGTH') + + header_data = payload_length + + flag_offset = self.FLAG_OFFSET + if self.compression: + header_data |= uncompressed_length << flag_offset + flag_offset += 17 + + if is_self_contained: + header_data |= 1 << flag_offset + + write_uint_le(buffer, header_data, size=self.header_length) + header_crc = compute_crc24(header_data, self.header_length) + write_uint_le(buffer, header_crc, size=CRC24_LENGTH) + + def _encode_segment(self, buffer, payload, is_self_contained): + """ + Encode a message to a single segment. + """ + uncompressed_payload = payload + uncompressed_payload_length = len(payload) + + if self.compression: + compressed_payload = self.compress(uncompressed_payload) + if len(compressed_payload) >= uncompressed_payload_length: + encoded_payload = uncompressed_payload + uncompressed_payload_length = 0 + else: + encoded_payload = compressed_payload + else: + encoded_payload = uncompressed_payload + + payload_length = len(encoded_payload) + self.encode_header(buffer, payload_length, uncompressed_payload_length, is_self_contained) + payload_crc = compute_crc32(encoded_payload, CRC32_INITIAL) + buffer.write(encoded_payload) + write_uint_le(buffer, payload_crc) + + def encode(self, buffer, msg): + """ + Encode a message to one of more segments. + """ + msg_length = len(msg) + + if msg_length > Segment.MAX_PAYLOAD_LENGTH: + payloads = [] + for i in range(0, msg_length, Segment.MAX_PAYLOAD_LENGTH): + payloads.append(msg[i:i + Segment.MAX_PAYLOAD_LENGTH]) + else: + payloads = [msg] + + is_self_contained = len(payloads) == 1 + for payload in payloads: + self._encode_segment(buffer, payload, is_self_contained) + + def decode_header(self, buffer): + header_data = read_uint_le(buffer, self.header_length) + + expected_header_crc = read_uint_le(buffer, CRC24_LENGTH) + actual_header_crc = compute_crc24(header_data, self.header_length) + if actual_header_crc != expected_header_crc: + raise CrcException('CRC mismatch on header {:x}. Received {:x}", computed {:x}.'.format( + header_data, expected_header_crc, actual_header_crc)) + + payload_length = header_data & Segment.MAX_PAYLOAD_LENGTH + header_data >>= 17 + + if self.compression: + uncompressed_payload_length = header_data & Segment.MAX_PAYLOAD_LENGTH + header_data >>= 17 + else: + uncompressed_payload_length = -1 + + is_self_contained = (header_data & 1) == 1 + + return SegmentHeader(payload_length, uncompressed_payload_length, is_self_contained) + + def decode(self, buffer, header): + encoded_payload = buffer.read(header.payload_length) + expected_payload_crc = read_uint_le(buffer) + + actual_payload_crc = compute_crc32(encoded_payload, CRC32_INITIAL) + if actual_payload_crc != expected_payload_crc: + raise CrcException('CRC mismatch on payload. Received {:x}", computed {:x}.'.format( + expected_payload_crc, actual_payload_crc)) + + payload = encoded_payload + if self.compression and header.uncompressed_payload_length > 0: + payload = self.decompress(encoded_payload, header.uncompressed_payload_length) + + return Segment(payload, header.is_self_contained) diff --git a/cassandra/util.py b/cassandra/util.py index efb3a95..f896ff4 100644 --- a/cassandra/util.py +++ b/cassandra/util.py @@ -1,1328 +1,2039 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement import calendar import datetime from functools import total_ordering +import logging +from itertools import chain import random +import re import six import uuid import sys +_HAS_GEOMET = True +try: + from geomet import wkt +except: + _HAS_GEOMET = False + + +from cassandra import DriverException + DATETIME_EPOC = datetime.datetime(1970, 1, 1) +UTC_DATETIME_EPOC = datetime.datetime.utcfromtimestamp(0) + +_nan = float('nan') + +log = logging.getLogger(__name__) assert sys.byteorder in ('little', 'big') is_little_endian = sys.byteorder == 'little' + def datetime_from_timestamp(timestamp): """ Creates a timezone-agnostic datetime from timestamp (in seconds) in a consistent manner. Works around a Windows issue with large negative timestamps (PYTHON-119), and rounding differences in Python 3.4 (PYTHON-340). :param timestamp: a unix timestamp, in seconds """ dt = DATETIME_EPOC + datetime.timedelta(seconds=timestamp) return dt +def utc_datetime_from_ms_timestamp(timestamp): + """ + Creates a UTC datetime from a timestamp in milliseconds. See + :meth:`datetime_from_timestamp`. + + Raises an `OverflowError` if the timestamp is out of range for + :class:`~datetime.datetime`. + + :param timestamp: timestamp, in milliseconds + """ + return UTC_DATETIME_EPOC + datetime.timedelta(milliseconds=timestamp) + + +def ms_timestamp_from_datetime(dt): + """ + Converts a datetime to a timestamp expressed in milliseconds. + + :param dt: a :class:`datetime.datetime` + """ + return int(round((dt - UTC_DATETIME_EPOC).total_seconds() * 1000)) + + def unix_time_from_uuid1(uuid_arg): """ Converts a version 1 :class:`uuid.UUID` to a timestamp with the same precision as :meth:`time.time()` returns. This is useful for examining the results of queries returning a v1 :class:`~uuid.UUID`. :param uuid_arg: a version 1 :class:`~uuid.UUID` """ return (uuid_arg.time - 0x01B21DD213814000) / 1e7 def datetime_from_uuid1(uuid_arg): """ Creates a timezone-agnostic datetime from the timestamp in the specified type-1 UUID. :param uuid_arg: a version 1 :class:`~uuid.UUID` """ return datetime_from_timestamp(unix_time_from_uuid1(uuid_arg)) def min_uuid_from_time(timestamp): """ Generates the minimum TimeUUID (type 1) for a given timestamp, as compared by Cassandra. See :func:`uuid_from_time` for argument and return types. """ return uuid_from_time(timestamp, 0x808080808080, 0x80) # Cassandra does byte-wise comparison; fill with min signed bytes (0x80 = -128) def max_uuid_from_time(timestamp): """ Generates the maximum TimeUUID (type 1) for a given timestamp, as compared by Cassandra. See :func:`uuid_from_time` for argument and return types. """ return uuid_from_time(timestamp, 0x7f7f7f7f7f7f, 0x3f7f) # Max signed bytes (0x7f = 127) def uuid_from_time(time_arg, node=None, clock_seq=None): """ Converts a datetime or timestamp to a type 1 :class:`uuid.UUID`. :param time_arg: The time to use for the timestamp portion of the UUID. This can either be a :class:`datetime` object or a timestamp in seconds (as returned from :meth:`time.time()`). :type datetime: :class:`datetime` or timestamp :param node: None integer for the UUID (up to 48 bits). If not specified, this field is randomized. :type node: long :param clock_seq: Clock sequence field for the UUID (up to 14 bits). If not specified, a random sequence is generated. :type clock_seq: int :rtype: :class:`uuid.UUID` """ if hasattr(time_arg, 'utctimetuple'): seconds = int(calendar.timegm(time_arg.utctimetuple())) microseconds = (seconds * 1e6) + time_arg.time().microsecond else: microseconds = int(time_arg * 1e6) # 0x01b21dd213814000 is the number of 100-ns intervals between the # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. intervals = int(microseconds * 10) + 0x01b21dd213814000 time_low = intervals & 0xffffffff time_mid = (intervals >> 32) & 0xffff time_hi_version = (intervals >> 48) & 0x0fff if clock_seq is None: clock_seq = random.getrandbits(14) else: if clock_seq > 0x3fff: raise ValueError('clock_seq is out of range (need a 14-bit value)') clock_seq_low = clock_seq & 0xff clock_seq_hi_variant = 0x80 | ((clock_seq >> 8) & 0x3f) if node is None: node = random.getrandbits(48) return uuid.UUID(fields=(time_low, time_mid, time_hi_version, clock_seq_hi_variant, clock_seq_low, node), version=1) LOWEST_TIME_UUID = uuid.UUID('00000000-0000-1000-8080-808080808080') """ The lowest possible TimeUUID, as sorted by Cassandra. """ HIGHEST_TIME_UUID = uuid.UUID('ffffffff-ffff-1fff-bf7f-7f7f7f7f7f7f') """ The highest possible TimeUUID, as sorted by Cassandra. """ +def _addrinfo_or_none(contact_point, port): + """ + A helper function that wraps socket.getaddrinfo and returns None + when it fails to, e.g. resolve one of the hostnames. Used to address + PYTHON-895. + """ + try: + value = socket.getaddrinfo(contact_point, port, + socket.AF_UNSPEC, socket.SOCK_STREAM) + return value + except socket.gaierror: + log.debug('Could not resolve hostname "{}" ' + 'with port {}'.format(contact_point, port)) + return None + + +def _addrinfo_to_ip_strings(addrinfo): + """ + Helper function that consumes the data output by socket.getaddrinfo and + extracts the IP address from the sockaddr portion of the result. + + Since this is meant to be used in conjunction with _addrinfo_or_none, + this will pass None and EndPoint instances through unaffected. + """ + if addrinfo is None: + return None + return [(entry[4][0], entry[4][1]) for entry in addrinfo] + + +def _resolve_contact_points_to_string_map(contact_points): + return OrderedDict( + ('{cp}:{port}'.format(cp=cp, port=port), _addrinfo_to_ip_strings(_addrinfo_or_none(cp, port))) + for cp, port in contact_points + ) + + try: from collections import OrderedDict except ImportError: # OrderedDict from Python 2.7+ # Copyright (c) 2009 Raymond Hettinger # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. from UserDict import DictMixin class OrderedDict(dict, DictMixin): # noqa """ A dictionary which maintains the insertion order of keys. """ def __init__(self, *args, **kwds): """ A dictionary which maintains the insertion order of keys. """ if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__end except AttributeError: self.clear() self.update(*args, **kwds) def clear(self): self.__end = end = [] end += [None, end, end] # sentinel node for doubly linked list self.__map = {} # key --> [key, prev, next] dict.clear(self) def __setitem__(self, key, value): if key not in self: end = self.__end curr = end[1] curr[2] = end[1] = self.__map[key] = [key, curr, end] dict.__setitem__(self, key, value) def __delitem__(self, key): dict.__delitem__(self, key) key, prev, next = self.__map.pop(key) prev[2] = next next[1] = prev def __iter__(self): end = self.__end curr = end[2] while curr is not end: yield curr[0] curr = curr[2] def __reversed__(self): end = self.__end curr = end[1] while curr is not end: yield curr[0] curr = curr[1] def popitem(self, last=True): if not self: raise KeyError('dictionary is empty') if last: key = next(reversed(self)) else: key = next(iter(self)) value = self.pop(key) return key, value def __reduce__(self): items = [[k, self[k]] for k in self] tmp = self.__map, self.__end del self.__map, self.__end inst_dict = vars(self).copy() self.__map, self.__end = tmp if inst_dict: return (self.__class__, (items,), inst_dict) return self.__class__, (items,) def keys(self): return list(self) setdefault = DictMixin.setdefault update = DictMixin.update pop = DictMixin.pop values = DictMixin.values items = DictMixin.items iterkeys = DictMixin.iterkeys itervalues = DictMixin.itervalues iteritems = DictMixin.iteritems def __repr__(self): if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.items()) def copy(self): return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): d = cls() for key in iterable: d[key] = value return d def __eq__(self, other): if isinstance(other, OrderedDict): if len(self) != len(other): return False for p, q in zip(self.items(), other.items()): if p != q: return False return True return dict.__eq__(self, other) def __ne__(self, other): return not self == other # WeakSet from Python 2.7+ (https://code.google.com/p/weakrefset) from _weakref import ref class _IterationGuard(object): # This context manager registers itself in the current iterators of the # weak container, such as to delay all removals until the context manager # exits. # This technique should be relatively thread-safe (since sets are). def __init__(self, weakcontainer): # Don't create cycles self.weakcontainer = ref(weakcontainer) def __enter__(self): w = self.weakcontainer() if w is not None: w._iterating.add(self) return self def __exit__(self, e, t, b): w = self.weakcontainer() if w is not None: s = w._iterating s.remove(self) if not s: w._commit_removals() class WeakSet(object): def __init__(self, data=None): self.data = set() def _remove(item, selfref=ref(self)): self = selfref() if self is not None: if self._iterating: self._pending_removals.append(item) else: self.data.discard(item) self._remove = _remove # A list of keys to be removed self._pending_removals = [] self._iterating = set() if data is not None: self.update(data) def _commit_removals(self): l = self._pending_removals discard = self.data.discard while l: discard(l.pop()) def __iter__(self): with _IterationGuard(self): for itemref in self.data: item = itemref() if item is not None: yield item def __len__(self): return sum(x() is not None for x in self.data) def __contains__(self, item): return ref(item) in self.data def __reduce__(self): return (self.__class__, (list(self),), getattr(self, '__dict__', None)) __hash__ = None def add(self, item): if self._pending_removals: self._commit_removals() self.data.add(ref(item, self._remove)) def clear(self): if self._pending_removals: self._commit_removals() self.data.clear() def copy(self): return self.__class__(self) def pop(self): if self._pending_removals: self._commit_removals() while True: try: itemref = self.data.pop() except KeyError: raise KeyError('pop from empty WeakSet') item = itemref() if item is not None: return item def remove(self, item): if self._pending_removals: self._commit_removals() self.data.remove(ref(item)) def discard(self, item): if self._pending_removals: self._commit_removals() self.data.discard(ref(item)) def update(self, other): if self._pending_removals: self._commit_removals() if isinstance(other, self.__class__): self.data.update(other.data) else: for element in other: self.add(element) def __ior__(self, other): self.update(other) return self # Helper functions for simple delegating methods. def _apply(self, other, method): if not isinstance(other, self.__class__): other = self.__class__(other) newdata = method(other.data) newset = self.__class__() newset.data = newdata return newset def difference(self, other): return self._apply(other, self.data.difference) __sub__ = difference def difference_update(self, other): if self._pending_removals: self._commit_removals() if self is other: self.data.clear() else: self.data.difference_update(ref(item) for item in other) def __isub__(self, other): if self._pending_removals: self._commit_removals() if self is other: self.data.clear() else: self.data.difference_update(ref(item) for item in other) return self def intersection(self, other): return self._apply(other, self.data.intersection) __and__ = intersection def intersection_update(self, other): if self._pending_removals: self._commit_removals() self.data.intersection_update(ref(item) for item in other) def __iand__(self, other): if self._pending_removals: self._commit_removals() self.data.intersection_update(ref(item) for item in other) return self def issubset(self, other): return self.data.issubset(ref(item) for item in other) __lt__ = issubset def __le__(self, other): return self.data <= set(ref(item) for item in other) def issuperset(self, other): return self.data.issuperset(ref(item) for item in other) __gt__ = issuperset def __ge__(self, other): return self.data >= set(ref(item) for item in other) def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return self.data == set(ref(item) for item in other) def symmetric_difference(self, other): return self._apply(other, self.data.symmetric_difference) __xor__ = symmetric_difference def symmetric_difference_update(self, other): if self._pending_removals: self._commit_removals() if self is other: self.data.clear() else: self.data.symmetric_difference_update(ref(item) for item in other) def __ixor__(self, other): if self._pending_removals: self._commit_removals() if self is other: self.data.clear() else: self.data.symmetric_difference_update(ref(item) for item in other) return self def union(self, other): return self._apply(other, self.data.union) __or__ = union def isdisjoint(self, other): return len(self.intersection(other)) == 0 class SortedSet(object): ''' A sorted set based on sorted list A sorted set implementation is used in this case because it does not require its elements to be immutable/hashable. #Not implemented: update functions, inplace operators ''' def __init__(self, iterable=()): self._items = [] self.update(iterable) def __len__(self): return len(self._items) def __getitem__(self, i): return self._items[i] def __iter__(self): return iter(self._items) def __reversed__(self): return reversed(self._items) def __repr__(self): return '%s(%r)' % ( self.__class__.__name__, self._items) def __reduce__(self): return self.__class__, (self._items,) def __eq__(self, other): if isinstance(other, self.__class__): return self._items == other._items else: try: return len(other) == len(self._items) and all(item in self for item in other) except TypeError: return NotImplemented def __ne__(self, other): if isinstance(other, self.__class__): return self._items != other._items else: try: return len(other) != len(self._items) or any(item not in self for item in other) except TypeError: return NotImplemented def __le__(self, other): return self.issubset(other) def __lt__(self, other): return len(other) > len(self._items) and self.issubset(other) def __ge__(self, other): return self.issuperset(other) def __gt__(self, other): return len(self._items) > len(other) and self.issuperset(other) def __and__(self, other): return self._intersect(other) __rand__ = __and__ def __iand__(self, other): isect = self._intersect(other) self._items = isect._items return self def __or__(self, other): return self.union(other) __ror__ = __or__ def __ior__(self, other): union = self.union(other) self._items = union._items return self def __sub__(self, other): return self._diff(other) def __rsub__(self, other): return sortedset(other) - self def __isub__(self, other): diff = self._diff(other) self._items = diff._items return self def __xor__(self, other): return self.symmetric_difference(other) __rxor__ = __xor__ def __ixor__(self, other): sym_diff = self.symmetric_difference(other) self._items = sym_diff._items return self def __contains__(self, item): i = self._find_insertion(item) return i < len(self._items) and self._items[i] == item def __delitem__(self, i): del self._items[i] def __delslice__(self, i, j): del self._items[i:j] def add(self, item): i = self._find_insertion(item) if i < len(self._items): if self._items[i] != item: self._items.insert(i, item) else: self._items.append(item) def update(self, iterable): for i in iterable: self.add(i) def clear(self): del self._items[:] def copy(self): new = sortedset() new._items = list(self._items) return new def isdisjoint(self, other): return len(self._intersect(other)) == 0 def issubset(self, other): return len(self._intersect(other)) == len(self._items) def issuperset(self, other): return len(self._intersect(other)) == len(other) def pop(self): if not self._items: raise KeyError("pop from empty set") return self._items.pop() def remove(self, item): i = self._find_insertion(item) if i < len(self._items): if self._items[i] == item: self._items.pop(i) return raise KeyError('%r' % item) def union(self, *others): union = sortedset() union._items = list(self._items) for other in others: for item in other: union.add(item) return union def intersection(self, *others): isect = self.copy() for other in others: isect = isect._intersect(other) if not isect: break return isect def difference(self, *others): diff = self.copy() for other in others: diff = diff._diff(other) if not diff: break return diff def symmetric_difference(self, other): diff_self_other = self._diff(other) diff_other_self = other.difference(self) return diff_self_other.union(diff_other_self) def _diff(self, other): diff = sortedset() for item in self._items: if item not in other: diff.add(item) return diff def _intersect(self, other): isect = sortedset() for item in self._items: if item in other: isect.add(item) return isect def _find_insertion(self, x): # this uses bisect_left algorithm unless it has elements it can't compare, # in which case it defaults to grouping non-comparable items at the beginning or end, # and scanning sequentially to find an insertion point a = self._items lo = 0 hi = len(a) try: while lo < hi: mid = (lo + hi) // 2 if a[mid] < x: lo = mid + 1 else: hi = mid except TypeError: # could not compare a[mid] with x # start scanning to find insertion point while swallowing type errors lo = 0 compared_one = False # flag is used to determine whether uncomparables are grouped at the front or back while lo < hi: try: if a[lo] == x or a[lo] >= x: break compared_one = True except TypeError: if compared_one: break lo += 1 return lo sortedset = SortedSet # backwards-compatibility from cassandra.compat import Mapping from six.moves import cPickle class OrderedMap(Mapping): ''' An ordered map that accepts non-hashable types for keys. It also maintains the insertion order of items, behaving as OrderedDict in that regard. These maps are constructed and read just as normal mapping types, exept that they may contain arbitrary collections and other non-hashable items as keys:: >>> od = OrderedMap([({'one': 1, 'two': 2}, 'value'), ... ({'three': 3, 'four': 4}, 'value2')]) >>> list(od.keys()) [{'two': 2, 'one': 1}, {'three': 3, 'four': 4}] >>> list(od.values()) ['value', 'value2'] These constructs are needed to support nested collections in Cassandra 2.1.3+, where frozen collections can be specified as parameters to others:: CREATE TABLE example ( ... value map>, double> ... ) This class derives from the (immutable) Mapping API. Objects in these maps are not intended be modified. - - Note: Because of the way Cassandra encodes nested types, when using the - driver with nested collections, :attr:`~.Cluster.protocol_version` must be 3 - or higher. - ''' def __init__(self, *args, **kwargs): if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) self._items = [] self._index = {} if args: e = args[0] if callable(getattr(e, 'keys', None)): for k in e.keys(): self._insert(k, e[k]) else: for k, v in e: self._insert(k, v) for k, v in six.iteritems(kwargs): self._insert(k, v) def _insert(self, key, value): flat_key = self._serialize_key(key) i = self._index.get(flat_key, -1) if i >= 0: self._items[i] = (key, value) else: self._items.append((key, value)) self._index[flat_key] = len(self._items) - 1 __setitem__ = _insert def __getitem__(self, key): try: index = self._index[self._serialize_key(key)] return self._items[index][1] except KeyError: raise KeyError(str(key)) def __delitem__(self, key): # not efficient -- for convenience only try: index = self._index.pop(self._serialize_key(key)) self._index = dict((k, i if i < index else i - 1) for k, i in self._index.items()) self._items.pop(index) except KeyError: raise KeyError(str(key)) def __iter__(self): for i in self._items: yield i[0] def __len__(self): return len(self._items) def __eq__(self, other): if isinstance(other, OrderedMap): return self._items == other._items try: d = dict(other) return len(d) == len(self._items) and all(i[1] == d[i[0]] for i in self._items) except KeyError: return False except TypeError: pass return NotImplemented def __repr__(self): return '%s([%s])' % ( self.__class__.__name__, ', '.join("(%r, %r)" % (k, v) for k, v in self._items)) def __str__(self): return '{%s}' % ', '.join("%r: %r" % (k, v) for k, v in self._items) def popitem(self): try: kv = self._items.pop() del self._index[self._serialize_key(kv[0])] return kv except IndexError: raise KeyError() def _serialize_key(self, key): return cPickle.dumps(key) class OrderedMapSerializedKey(OrderedMap): def __init__(self, cass_type, protocol_version): super(OrderedMapSerializedKey, self).__init__() self.cass_key_type = cass_type self.protocol_version = protocol_version def _insert_unchecked(self, key, flat_key, value): self._items.append((key, value)) self._index[flat_key] = len(self._items) - 1 def _serialize_key(self, key): return self.cass_key_type.serialize(key, self.protocol_version) import datetime import time if six.PY3: long = int @total_ordering class Time(object): ''' Idealized time, independent of day. Up to nanosecond resolution ''' MICRO = 1000 MILLI = 1000 * MICRO SECOND = 1000 * MILLI MINUTE = 60 * SECOND HOUR = 60 * MINUTE DAY = 24 * HOUR nanosecond_time = 0 def __init__(self, value): """ Initializer value can be: - integer_type: absolute nanoseconds in the day - datetime.time: built-in time - string_type: a string time of the form "HH:MM:SS[.mmmuuunnn]" """ if isinstance(value, six.integer_types): self._from_timestamp(value) elif isinstance(value, datetime.time): self._from_time(value) elif isinstance(value, six.string_types): self._from_timestring(value) else: raise TypeError('Time arguments must be a whole number, datetime.time, or string') @property def hour(self): """ The hour component of this time (0-23) """ return self.nanosecond_time // Time.HOUR @property def minute(self): """ The minute component of this time (0-59) """ minutes = self.nanosecond_time // Time.MINUTE return minutes % 60 @property def second(self): """ The second component of this time (0-59) """ seconds = self.nanosecond_time // Time.SECOND return seconds % 60 @property def nanosecond(self): """ The fractional seconds component of the time, in nanoseconds """ return self.nanosecond_time % Time.SECOND def time(self): """ Return a built-in datetime.time (nanosecond precision truncated to micros). """ return datetime.time(hour=self.hour, minute=self.minute, second=self.second, microsecond=self.nanosecond // Time.MICRO) def _from_timestamp(self, t): if t >= Time.DAY: raise ValueError("value must be less than number of nanoseconds in a day (%d)" % Time.DAY) self.nanosecond_time = t def _from_timestring(self, s): try: parts = s.split('.') base_time = time.strptime(parts[0], "%H:%M:%S") self.nanosecond_time = (base_time.tm_hour * Time.HOUR + base_time.tm_min * Time.MINUTE + base_time.tm_sec * Time.SECOND) if len(parts) > 1: # right pad to 9 digits nano_time_str = parts[1] + "0" * (9 - len(parts[1])) self.nanosecond_time += int(nano_time_str) except ValueError: raise ValueError("can't interpret %r as a time" % (s,)) def _from_time(self, t): self.nanosecond_time = (t.hour * Time.HOUR + t.minute * Time.MINUTE + t.second * Time.SECOND + t.microsecond * Time.MICRO) def __hash__(self): return self.nanosecond_time def __eq__(self, other): if isinstance(other, Time): return self.nanosecond_time == other.nanosecond_time if isinstance(other, six.integer_types): return self.nanosecond_time == other return self.nanosecond_time % Time.MICRO == 0 and \ datetime.time(hour=self.hour, minute=self.minute, second=self.second, microsecond=self.nanosecond // Time.MICRO) == other def __ne__(self, other): return not self.__eq__(other) def __lt__(self, other): if not isinstance(other, Time): return NotImplemented return self.nanosecond_time < other.nanosecond_time def __repr__(self): return "Time(%s)" % self.nanosecond_time def __str__(self): return "%02d:%02d:%02d.%09d" % (self.hour, self.minute, self.second, self.nanosecond) @total_ordering class Date(object): ''' Idealized date: year, month, day Offers wider year range than datetime.date. For Dates that cannot be represented as a datetime.date (because datetime.MINYEAR, datetime.MAXYEAR), this type falls back to printing days_from_epoch offset. ''' MINUTE = 60 HOUR = 60 * MINUTE DAY = 24 * HOUR date_format = "%Y-%m-%d" days_from_epoch = 0 def __init__(self, value): """ Initializer value can be: - integer_type: absolute days from epoch (1970, 1, 1). Can be negative. - datetime.date: built-in date - string_type: a string time of the form "yyyy-mm-dd" """ if isinstance(value, six.integer_types): self.days_from_epoch = value elif isinstance(value, (datetime.date, datetime.datetime)): self._from_timetuple(value.timetuple()) elif isinstance(value, six.string_types): self._from_datestring(value) else: raise TypeError('Date arguments must be a whole number, datetime.date, or string') @property def seconds(self): """ Absolute seconds from epoch (can be negative) """ return self.days_from_epoch * Date.DAY def date(self): """ Return a built-in datetime.date for Dates falling in the years [datetime.MINYEAR, datetime.MAXYEAR] ValueError is raised for Dates outside this range. """ try: dt = datetime_from_timestamp(self.seconds) return datetime.date(dt.year, dt.month, dt.day) except Exception: raise ValueError("%r exceeds ranges for built-in datetime.date" % self) def _from_timetuple(self, t): self.days_from_epoch = calendar.timegm(t) // Date.DAY def _from_datestring(self, s): if s[0] == '+': s = s[1:] dt = datetime.datetime.strptime(s, self.date_format) self._from_timetuple(dt.timetuple()) def __hash__(self): return self.days_from_epoch def __eq__(self, other): if isinstance(other, Date): return self.days_from_epoch == other.days_from_epoch if isinstance(other, six.integer_types): return self.days_from_epoch == other try: return self.date() == other except Exception: return False def __ne__(self, other): return not self.__eq__(other) def __lt__(self, other): if not isinstance(other, Date): return NotImplemented return self.days_from_epoch < other.days_from_epoch def __repr__(self): return "Date(%s)" % self.days_from_epoch def __str__(self): try: dt = datetime_from_timestamp(self.seconds) return "%04d-%02d-%02d" % (dt.year, dt.month, dt.day) except: # If we overflow datetime.[MIN|MAX] return str(self.days_from_epoch) import socket if hasattr(socket, 'inet_pton'): inet_pton = socket.inet_pton inet_ntop = socket.inet_ntop else: """ Windows doesn't have socket.inet_pton and socket.inet_ntop until Python 3.4 This is an alternative impl using ctypes, based on this win_inet_pton project: https://github.com/hickeroar/win_inet_pton """ import ctypes class sockaddr(ctypes.Structure): """ Shared struct for ipv4 and ipv6. https://msdn.microsoft.com/en-us/library/windows/desktop/ms740496(v=vs.85).aspx ``__pad1`` always covers the port. When being used for ``sockaddr_in6``, ``ipv4_addr`` actually covers ``sin6_flowinfo``, resulting in proper alignment for ``ipv6_addr``. """ _fields_ = [("sa_family", ctypes.c_short), ("__pad1", ctypes.c_ushort), ("ipv4_addr", ctypes.c_byte * 4), ("ipv6_addr", ctypes.c_byte * 16), ("__pad2", ctypes.c_ulong)] if hasattr(ctypes, 'windll'): WSAStringToAddressA = ctypes.windll.ws2_32.WSAStringToAddressA WSAAddressToStringA = ctypes.windll.ws2_32.WSAAddressToStringA else: def not_windows(*args): raise OSError("IPv6 addresses cannot be handled on Windows. " "Missing ctypes.windll") WSAStringToAddressA = not_windows WSAAddressToStringA = not_windows def inet_pton(address_family, ip_string): if address_family == socket.AF_INET: return socket.inet_aton(ip_string) addr = sockaddr() addr.sa_family = address_family addr_size = ctypes.c_int(ctypes.sizeof(addr)) if WSAStringToAddressA( ip_string, address_family, None, ctypes.byref(addr), ctypes.byref(addr_size) ) != 0: raise socket.error(ctypes.FormatError()) if address_family == socket.AF_INET6: return ctypes.string_at(addr.ipv6_addr, 16) raise socket.error('unknown address family') def inet_ntop(address_family, packed_ip): if address_family == socket.AF_INET: return socket.inet_ntoa(packed_ip) addr = sockaddr() addr.sa_family = address_family addr_size = ctypes.c_int(ctypes.sizeof(addr)) ip_string = ctypes.create_string_buffer(128) ip_string_size = ctypes.c_int(ctypes.sizeof(ip_string)) if address_family == socket.AF_INET6: if len(packed_ip) != ctypes.sizeof(addr.ipv6_addr): raise socket.error('packed IP wrong length for inet_ntoa') ctypes.memmove(addr.ipv6_addr, packed_ip, 16) else: raise socket.error('unknown address family') if WSAAddressToStringA( ctypes.byref(addr), addr_size, None, ip_string, ctypes.byref(ip_string_size) ) != 0: raise socket.error(ctypes.FormatError()) return ip_string[:ip_string_size.value - 1] import keyword # similar to collections.namedtuple, reproduced here because Python 2.6 did not have the rename logic def _positional_rename_invalid_identifiers(field_names): names_out = list(field_names) for index, name in enumerate(field_names): if (not all(c.isalnum() or c == '_' for c in name) or keyword.iskeyword(name) or not name or name[0].isdigit() or name.startswith('_')): names_out[index] = 'field_%d_' % index return names_out def _sanitize_identifiers(field_names): names_out = _positional_rename_invalid_identifiers(field_names) if len(names_out) != len(set(names_out)): observed_names = set() for index, name in enumerate(names_out): while names_out[index] in observed_names: names_out[index] = "%s_" % (names_out[index],) observed_names.add(names_out[index]) return names_out +def list_contents_to_tuple(to_convert): + if isinstance(to_convert, list): + for n, i in enumerate(to_convert): + if isinstance(to_convert[n], list): + to_convert[n] = tuple(to_convert[n]) + return tuple(to_convert) + else: + return to_convert + + +class Point(object): + """ + Represents a point geometry for DSE + """ + + x = None + """ + x coordinate of the point + """ + + y = None + """ + y coordinate of the point + """ + + def __init__(self, x=_nan, y=_nan): + self.x = x + self.y = y + + def __eq__(self, other): + return isinstance(other, Point) and self.x == other.x and self.y == other.y + + def __hash__(self): + return hash((self.x, self.y)) + + def __str__(self): + """ + Well-known text representation of the point + """ + return "POINT (%r %r)" % (self.x, self.y) + + def __repr__(self): + return "%s(%r, %r)" % (self.__class__.__name__, self.x, self.y) + + @staticmethod + def from_wkt(s): + """ + Parse a Point geometry from a wkt string and return a new Point object. + """ + if not _HAS_GEOMET: + raise DriverException("Geomet is required to deserialize a wkt geometry.") + + try: + geom = wkt.loads(s) + except ValueError: + raise ValueError("Invalid WKT geometry: '{0}'".format(s)) + + if geom['type'] != 'Point': + raise ValueError("Invalid WKT geometry type. Expected 'Point', got '{0}': '{1}'".format(geom['type'], s)) + + coords = geom['coordinates'] + if len(coords) < 2: + x = y = _nan + else: + x = coords[0] + y = coords[1] + + return Point(x=x, y=y) + + +class LineString(object): + """ + Represents a linestring geometry for DSE + """ + + coords = None + """ + Tuple of (x, y) coordinates in the linestring + """ + def __init__(self, coords=tuple()): + """ + 'coords`: a sequence of (x, y) coordinates of points in the linestring + """ + self.coords = tuple(coords) + + def __eq__(self, other): + return isinstance(other, LineString) and self.coords == other.coords + + def __hash__(self): + return hash(self.coords) + + def __str__(self): + """ + Well-known text representation of the LineString + """ + if not self.coords: + return "LINESTRING EMPTY" + return "LINESTRING (%s)" % ', '.join("%r %r" % (x, y) for x, y in self.coords) + + def __repr__(self): + return "%s(%r)" % (self.__class__.__name__, self.coords) + + @staticmethod + def from_wkt(s): + """ + Parse a LineString geometry from a wkt string and return a new LineString object. + """ + if not _HAS_GEOMET: + raise DriverException("Geomet is required to deserialize a wkt geometry.") + + try: + geom = wkt.loads(s) + except ValueError: + raise ValueError("Invalid WKT geometry: '{0}'".format(s)) + + if geom['type'] != 'LineString': + raise ValueError("Invalid WKT geometry type. Expected 'LineString', got '{0}': '{1}'".format(geom['type'], s)) + + geom['coordinates'] = list_contents_to_tuple(geom['coordinates']) + + return LineString(coords=geom['coordinates']) + + +class _LinearRing(object): + # no validation, no implicit closing; just used for poly composition, to + # mimic that of shapely.geometry.Polygon + def __init__(self, coords=tuple()): + self.coords = list_contents_to_tuple(coords) + + def __eq__(self, other): + return isinstance(other, _LinearRing) and self.coords == other.coords + + def __hash__(self): + return hash(self.coords) + + def __str__(self): + if not self.coords: + return "LINEARRING EMPTY" + return "LINEARRING (%s)" % ', '.join("%r %r" % (x, y) for x, y in self.coords) + + def __repr__(self): + return "%s(%r)" % (self.__class__.__name__, self.coords) + + +class Polygon(object): + """ + Represents a polygon geometry for DSE + """ + + exterior = None + """ + _LinearRing representing the exterior of the polygon + """ + + interiors = None + """ + Tuple of _LinearRings representing interior holes in the polygon + """ + + def __init__(self, exterior=tuple(), interiors=None): + """ + 'exterior`: a sequence of (x, y) coordinates of points in the linestring + `interiors`: None, or a sequence of sequences or (x, y) coordinates of points describing interior linear rings + """ + self.exterior = _LinearRing(exterior) + self.interiors = tuple(_LinearRing(e) for e in interiors) if interiors else tuple() + + def __eq__(self, other): + return isinstance(other, Polygon) and self.exterior == other.exterior and self.interiors == other.interiors + + def __hash__(self): + return hash((self.exterior, self.interiors)) + + def __str__(self): + """ + Well-known text representation of the polygon + """ + if not self.exterior.coords: + return "POLYGON EMPTY" + rings = [ring.coords for ring in chain((self.exterior,), self.interiors)] + rings = ["(%s)" % ', '.join("%r %r" % (x, y) for x, y in ring) for ring in rings] + return "POLYGON (%s)" % ', '.join(rings) + + def __repr__(self): + return "%s(%r, %r)" % (self.__class__.__name__, self.exterior.coords, [ring.coords for ring in self.interiors]) + + @staticmethod + def from_wkt(s): + """ + Parse a Polygon geometry from a wkt string and return a new Polygon object. + """ + if not _HAS_GEOMET: + raise DriverException("Geomet is required to deserialize a wkt geometry.") + + try: + geom = wkt.loads(s) + except ValueError: + raise ValueError("Invalid WKT geometry: '{0}'".format(s)) + + if geom['type'] != 'Polygon': + raise ValueError("Invalid WKT geometry type. Expected 'Polygon', got '{0}': '{1}'".format(geom['type'], s)) + + coords = geom['coordinates'] + exterior = coords[0] if len(coords) > 0 else tuple() + interiors = coords[1:] if len(coords) > 1 else None + + return Polygon(exterior=exterior, interiors=interiors) + + +_distance_wkt_pattern = re.compile("distance *\\( *\\( *([\\d\\.-]+) *([\\d+\\.-]+) *\\) *([\\d+\\.-]+) *\\) *$", re.IGNORECASE) + + +class Distance(object): + """ + Represents a Distance geometry for DSE + """ + + x = None + """ + x coordinate of the center point + """ + + y = None + """ + y coordinate of the center point + """ + + radius = None + """ + radius to represent the distance from the center point + """ + + def __init__(self, x=_nan, y=_nan, radius=_nan): + self.x = x + self.y = y + self.radius = radius + + def __eq__(self, other): + return isinstance(other, Distance) and self.x == other.x and self.y == other.y and self.radius == other.radius + + def __hash__(self): + return hash((self.x, self.y, self.radius)) + + def __str__(self): + """ + Well-known text representation of the point + """ + return "DISTANCE ((%r %r) %r)" % (self.x, self.y, self.radius) + + def __repr__(self): + return "%s(%r, %r, %r)" % (self.__class__.__name__, self.x, self.y, self.radius) + + @staticmethod + def from_wkt(s): + """ + Parse a Distance geometry from a wkt string and return a new Distance object. + """ + + distance_match = _distance_wkt_pattern.match(s) + + if distance_match is None: + raise ValueError("Invalid WKT geometry: '{0}'".format(s)) + + x, y, radius = distance_match.groups() + return Distance(x, y, radius) + + class Duration(object): """ Cassandra Duration Type """ months = 0 + "" days = 0 + "" nanoseconds = 0 + "" def __init__(self, months=0, days=0, nanoseconds=0): self.months = months self.days = days self.nanoseconds = nanoseconds def __eq__(self, other): return isinstance(other, self.__class__) and self.months == other.months and self.days == other.days and self.nanoseconds == other.nanoseconds def __repr__(self): return "Duration({0}, {1}, {2})".format(self.months, self.days, self.nanoseconds) def __str__(self): has_negative_values = self.months < 0 or self.days < 0 or self.nanoseconds < 0 return '%s%dmo%dd%dns' % ( '-' if has_negative_values else '', abs(self.months), abs(self.days), abs(self.nanoseconds) ) +class DateRangePrecision(object): + """ + An "enum" representing the valid values for :attr:`DateRange.precision`. + """ + YEAR = 'YEAR' + """ + """ + + MONTH = 'MONTH' + """ + """ + + DAY = 'DAY' + """ + """ + + HOUR = 'HOUR' + """ + """ + + MINUTE = 'MINUTE' + """ + """ + + SECOND = 'SECOND' + """ + """ + + MILLISECOND = 'MILLISECOND' + """ + """ + + PRECISIONS = (YEAR, MONTH, DAY, HOUR, + MINUTE, SECOND, MILLISECOND) + """ + """ + + @classmethod + def _to_int(cls, precision): + return cls.PRECISIONS.index(precision.upper()) + + @classmethod + def _round_to_precision(cls, ms, precision, default_dt): + try: + dt = utc_datetime_from_ms_timestamp(ms) + except OverflowError: + return ms + precision_idx = cls._to_int(precision) + replace_kwargs = {} + if precision_idx <= cls._to_int(DateRangePrecision.YEAR): + replace_kwargs['month'] = default_dt.month + if precision_idx <= cls._to_int(DateRangePrecision.MONTH): + replace_kwargs['day'] = default_dt.day + if precision_idx <= cls._to_int(DateRangePrecision.DAY): + replace_kwargs['hour'] = default_dt.hour + if precision_idx <= cls._to_int(DateRangePrecision.HOUR): + replace_kwargs['minute'] = default_dt.minute + if precision_idx <= cls._to_int(DateRangePrecision.MINUTE): + replace_kwargs['second'] = default_dt.second + if precision_idx <= cls._to_int(DateRangePrecision.SECOND): + # truncate to nearest 1000 so we deal in ms, not us + replace_kwargs['microsecond'] = (default_dt.microsecond // 1000) * 1000 + if precision_idx == cls._to_int(DateRangePrecision.MILLISECOND): + replace_kwargs['microsecond'] = int(round(dt.microsecond, -3)) + return ms_timestamp_from_datetime(dt.replace(**replace_kwargs)) + + @classmethod + def round_up_to_precision(cls, ms, precision): + # PYTHON-912: this is the only case in which we can't take as upper bound + # datetime.datetime.max because the month from ms may be February and we'd + # be setting 31 as the month day + if precision == cls.MONTH: + date_ms = utc_datetime_from_ms_timestamp(ms) + upper_date = datetime.datetime.max.replace(year=date_ms.year, month=date_ms.month, + day=calendar.monthrange(date_ms.year, date_ms.month)[1]) + else: + upper_date = datetime.datetime.max + return cls._round_to_precision(ms, precision, upper_date) + + @classmethod + def round_down_to_precision(cls, ms, precision): + return cls._round_to_precision(ms, precision, datetime.datetime.min) + + +@total_ordering +class DateRangeBound(object): + """DateRangeBound(value, precision) + Represents a single date value and its precision for :class:`DateRange`. + + .. attribute:: milliseconds + + Integer representing milliseconds since the UNIX epoch. May be negative. + + .. attribute:: precision + + String representing the precision of a bound. Must be a valid + :class:`DateRangePrecision` member. + + :class:`DateRangeBound` uses a millisecond offset from the UNIX epoch to + allow :class:`DateRange` to represent values `datetime.datetime` cannot. + For such values, string representions will show this offset rather than the + CQL representation. + """ + milliseconds = None + precision = None + + def __init__(self, value, precision): + """ + :param value: a value representing ms since the epoch. Accepts an + integer or a datetime. + :param precision: a string representing precision + """ + if precision is not None: + try: + self.precision = precision.upper() + except AttributeError: + raise TypeError('precision must be a string; got %r' % precision) + + if value is None: + milliseconds = None + elif isinstance(value, six.integer_types): + milliseconds = value + elif isinstance(value, datetime.datetime): + value = value.replace( + microsecond=int(round(value.microsecond, -3)) + ) + milliseconds = ms_timestamp_from_datetime(value) + else: + raise ValueError('%r is not a valid value for DateRangeBound' % value) + + self.milliseconds = milliseconds + self.validate() + + def __eq__(self, other): + if not isinstance(other, self.__class__): + return NotImplemented + return (self.milliseconds == other.milliseconds and + self.precision == other.precision) + + def __lt__(self, other): + return ((str(self.milliseconds), str(self.precision)) < + (str(other.milliseconds), str(other.precision))) + + def datetime(self): + """ + Return :attr:`milliseconds` as a :class:`datetime.datetime` if possible. + Raises an `OverflowError` if the value is out of range. + """ + return utc_datetime_from_ms_timestamp(self.milliseconds) + + def validate(self): + attrs = self.milliseconds, self.precision + if attrs == (None, None): + return + if None in attrs: + raise TypeError( + ("%s.datetime and %s.precision must not be None unless both " + "are None; Got: %r") % (self.__class__.__name__, + self.__class__.__name__, + self) + ) + if self.precision not in DateRangePrecision.PRECISIONS: + raise ValueError( + "%s.precision: expected value in %r; got %r" % ( + self.__class__.__name__, + DateRangePrecision.PRECISIONS, + self.precision + ) + ) + + @classmethod + def from_value(cls, value): + """ + Construct a new :class:`DateRangeBound` from a given value. If + possible, use the `value['milliseconds']` and `value['precision']` keys + of the argument. Otherwise, use the argument as a `(milliseconds, + precision)` iterable. + + :param value: a dictlike or iterable object + """ + if isinstance(value, cls): + return value + + # if possible, use as a mapping + try: + milliseconds, precision = value.get('milliseconds'), value.get('precision') + except AttributeError: + milliseconds = precision = None + if milliseconds is not None and precision is not None: + return DateRangeBound(value=milliseconds, precision=precision) + + # otherwise, use as an iterable + return DateRangeBound(*value) + + def round_up(self): + if self.milliseconds is None or self.precision is None: + return self + self.milliseconds = DateRangePrecision.round_up_to_precision( + self.milliseconds, self.precision + ) + return self + + def round_down(self): + if self.milliseconds is None or self.precision is None: + return self + self.milliseconds = DateRangePrecision.round_down_to_precision( + self.milliseconds, self.precision + ) + return self + + _formatter_map = { + DateRangePrecision.YEAR: '%Y', + DateRangePrecision.MONTH: '%Y-%m', + DateRangePrecision.DAY: '%Y-%m-%d', + DateRangePrecision.HOUR: '%Y-%m-%dT%HZ', + DateRangePrecision.MINUTE: '%Y-%m-%dT%H:%MZ', + DateRangePrecision.SECOND: '%Y-%m-%dT%H:%M:%SZ', + DateRangePrecision.MILLISECOND: '%Y-%m-%dT%H:%M:%S', + } + + def __str__(self): + if self == OPEN_BOUND: + return '*' + + try: + dt = self.datetime() + except OverflowError: + return '%sms' % (self.milliseconds,) + + formatted = dt.strftime(self._formatter_map[self.precision]) + + if self.precision == DateRangePrecision.MILLISECOND: + # we'd like to just format with '%Y-%m-%dT%H:%M:%S.%fZ', but %f + # gives us more precision than we want, so we strftime up to %S and + # do the rest ourselves + return '%s.%03dZ' % (formatted, dt.microsecond / 1000) + + return formatted + + def __repr__(self): + return '%s(milliseconds=%r, precision=%r)' % ( + self.__class__.__name__, self.milliseconds, self.precision + ) + + +OPEN_BOUND = DateRangeBound(value=None, precision=None) +""" +Represents `*`, an open value or bound for :class:`DateRange`. +""" + + +@total_ordering +class DateRange(object): + """DateRange(lower_bound=None, upper_bound=None, value=None) + DSE DateRange Type + + .. attribute:: lower_bound + + :class:`~DateRangeBound` representing the lower bound of a bounded range. + + .. attribute:: upper_bound + + :class:`~DateRangeBound` representing the upper bound of a bounded range. + + .. attribute:: value + + :class:`~DateRangeBound` representing the value of a single-value range. + + As noted in its documentation, :class:`DateRangeBound` uses a millisecond + offset from the UNIX epoch to allow :class:`DateRange` to represent values + `datetime.datetime` cannot. For such values, string representions will show + this offset rather than the CQL representation. + """ + lower_bound = None + upper_bound = None + value = None + + def __init__(self, lower_bound=None, upper_bound=None, value=None): + """ + :param lower_bound: a :class:`DateRangeBound` or object accepted by + :meth:`DateRangeBound.from_value` to be used as a + :attr:`lower_bound`. Mutually exclusive with `value`. If + `upper_bound` is specified and this is not, the :attr:`lower_bound` + will be open. + :param upper_bound: a :class:`DateRangeBound` or object accepted by + :meth:`DateRangeBound.from_value` to be used as a + :attr:`upper_bound`. Mutually exclusive with `value`. If + `lower_bound` is specified and this is not, the :attr:`upper_bound` + will be open. + :param value: a :class:`DateRangeBound` or object accepted by + :meth:`DateRangeBound.from_value` to be used as :attr:`value`. Mutually + exclusive with `lower_bound` and `lower_bound`. + """ + + # if necessary, transform non-None args to DateRangeBounds + lower_bound = (DateRangeBound.from_value(lower_bound).round_down() + if lower_bound else lower_bound) + upper_bound = (DateRangeBound.from_value(upper_bound).round_up() + if upper_bound else upper_bound) + value = (DateRangeBound.from_value(value).round_down() + if value else value) + + # if we're using a 2-ended range but one bound isn't specified, specify + # an open bound + if lower_bound is None and upper_bound is not None: + lower_bound = OPEN_BOUND + if upper_bound is None and lower_bound is not None: + upper_bound = OPEN_BOUND + + self.lower_bound, self.upper_bound, self.value = ( + lower_bound, upper_bound, value + ) + self.validate() + + def validate(self): + if self.value is None: + if self.lower_bound is None or self.upper_bound is None: + raise ValueError( + '%s instances where value attribute is None must set ' + 'lower_bound or upper_bound; got %r' % ( + self.__class__.__name__, + self + ) + ) + else: # self.value is not None + if self.lower_bound is not None or self.upper_bound is not None: + raise ValueError( + '%s instances where value attribute is not None must not ' + 'set lower_bound or upper_bound; got %r' % ( + self.__class__.__name__, + self + ) + ) + + def __eq__(self, other): + if not isinstance(other, self.__class__): + return NotImplemented + return (self.lower_bound == other.lower_bound and + self.upper_bound == other.upper_bound and + self.value == other.value) + + def __lt__(self, other): + return ((str(self.lower_bound), str(self.upper_bound), str(self.value)) < + (str(other.lower_bound), str(other.upper_bound), str(other.value))) + + def __str__(self): + if self.value: + return str(self.value) + else: + return '[%s TO %s]' % (self.lower_bound, self.upper_bound) + + def __repr__(self): + return '%s(lower_bound=%r, upper_bound=%r, value=%r)' % ( + self.__class__.__name__, + self.lower_bound, self.upper_bound, self.value + ) + + @total_ordering class Version(object): """ Internal minimalist class to compare versions. A valid version is: .... TODO: when python2 support is removed, use packaging.version. """ _version = None major = None minor = 0 patch = 0 build = 0 prerelease = 0 def __init__(self, version): self._version = version if '-' in version: version_without_prerelease, self.prerelease = version.split('-', 1) else: version_without_prerelease = version parts = list(reversed(version_without_prerelease.split('.'))) if len(parts) > 4: - raise ValueError("Invalid version: {}. Only 4 " - "components plus prerelease are supported".format(version)) + prerelease_string = "-{}".format(self.prerelease) if self.prerelease else "" + log.warning("Unrecognized version: {}. Only 4 components plus prerelease are supported. " + "Assuming version as {}{}".format(version, '.'.join(parts[:-5:-1]), prerelease_string)) - self.major = int(parts.pop()) - self.minor = int(parts.pop()) if parts else 0 - self.patch = int(parts.pop()) if parts else 0 + try: + self.major = int(parts.pop()) + except ValueError: + six.reraise( + ValueError, + ValueError("Couldn't parse version {}. Version should start with a number".format(version)), + sys.exc_info()[2] + ) + try: + self.minor = int(parts.pop()) if parts else 0 + self.patch = int(parts.pop()) if parts else 0 - if parts: # we have a build version - build = parts.pop() - try: - self.build = int(build) - except ValueError: - self.build = build + if parts: # we have a build version + build = parts.pop() + try: + self.build = int(build) + except ValueError: + self.build = build + except ValueError: + assumed_version = "{}.{}.{}.{}-{}".format(self.major, self.minor, self.patch, self.build, self.prerelease) + log.warning("Unrecognized version {}. Assuming version as {}".format(version, assumed_version)) def __hash__(self): return self._version def __repr__(self): version_string = "Version({0}, {1}, {2}".format(self.major, self.minor, self.patch) if self.build: version_string += ", {}".format(self.build) if self.prerelease: version_string += ", {}".format(self.prerelease) version_string += ")" return version_string def __str__(self): return self._version @staticmethod def _compare_version_part(version, other_version, cmp): if not (isinstance(version, six.integer_types) and isinstance(other_version, six.integer_types)): version = str(version) other_version = str(other_version) return cmp(version, other_version) def __eq__(self, other): if not isinstance(other, Version): return NotImplemented return (self.major == other.major and self.minor == other.minor and self.patch == other.patch and self._compare_version_part(self.build, other.build, lambda s, o: s == o) and self._compare_version_part(self.prerelease, other.prerelease, lambda s, o: s == o) ) def __gt__(self, other): if not isinstance(other, Version): return NotImplemented is_major_ge = self.major >= other.major is_minor_ge = self.minor >= other.minor is_patch_ge = self.patch >= other.patch is_build_gt = self._compare_version_part(self.build, other.build, lambda s, o: s > o) is_build_ge = self._compare_version_part(self.build, other.build, lambda s, o: s >= o) # By definition, a prerelease comes BEFORE the actual release, so if a version # doesn't have a prerelease, it's automatically greater than anything that does if self.prerelease and not other.prerelease: is_prerelease_gt = False elif other.prerelease and not self.prerelease: is_prerelease_gt = True else: is_prerelease_gt = self._compare_version_part(self.prerelease, other.prerelease, lambda s, o: s > o) \ return (self.major > other.major or (is_major_ge and self.minor > other.minor) or (is_major_ge and is_minor_ge and self.patch > other.patch) or (is_major_ge and is_minor_ge and is_patch_ge and is_build_gt) or (is_major_ge and is_minor_ge and is_patch_ge and is_build_ge and is_prerelease_gt) ) diff --git a/docs.yaml b/docs.yaml index 6212699..8e29b94 100644 --- a/docs.yaml +++ b/docs.yaml @@ -1,65 +1,75 @@ -title: DataStax Python Driver for Apache Cassandra -summary: DataStax Python Driver for Apache Cassandra Documentation +title: DataStax Python Driver +summary: DataStax Python Driver for Apache Cassandra® output: docs/_build/ swiftype_drivers: pythondrivers checks: external_links: exclude: - 'http://aka.ms/vcpython27' sections: - title: N/A prefix: / type: sphinx directory: docs virtualenv_init: | set -x - CASS_DRIVER_NO_CYTHON=1 pip install -r test-requirements.txt + CASS_DRIVER_NO_CYTHON=1 pip install -r test-datastax-requirements.txt # for newer versions this is redundant, but in older versions we need to # install, e.g., the cassandra driver, and those versions don't specify # the cassandra driver version in requirements files CASS_DRIVER_NO_CYTHON=1 python setup.py develop pip install "jinja2==2.8.1;python_version<'3.6'" "sphinx>=1.3,<2" geomet # build extensions like libev CASS_DRIVER_NO_CYTHON=1 python setup.py build_ext --inplace --force versions: + - name: '3.25' + ref: a83c36a5 + - name: '3.24' + ref: 21cac12b + - name: '3.23' + ref: a40a2af7 + - name: '3.22' + ref: 1ccd5b99 + - name: '3.21' + ref: 5589d96b - name: '3.20' ref: d30d166f - name: '3.19' ref: ac2471f9 - name: '3.18' ref: ec36b957 - name: '3.17' ref: 38e359e1 - name: '3.16' ref: '3.16.0' - name: '3.15' ref: '2ce0bd97' - name: '3.14' ref: '9af8bd19' - name: '3.13' ref: '3.13.0' - name: '3.12' ref: '43b9c995' - name: '3.11' ref: '3.11.0' - name: '3.10' ref: 64572368 - name: 3.9 ref: 3.9-doc - name: 3.8 ref: 3.8-doc - name: 3.7 ref: 3.7-doc - name: 3.6 ref: 3.6-doc - name: 3.5 ref: 3.5-doc redirects: - \A\/(.*)/\Z: /\1.html rewrites: - search: cassandra.apache.org/doc/cql3/CQL.html replace: cassandra.apache.org/doc/cql3/CQL-3.0.html - search: http://www.datastax.com/documentation/cql/3.1/ replace: https://docs.datastax.com/en/archived/cql/3.1/ - search: http://www.datastax.com/docs/1.2/cql_cli/cql/BATCH replace: https://docs.datastax.com/en/dse/6.7/cql/cql/cql_reference/cql_commands/cqlBatch.html diff --git a/docs/.nav b/docs/.nav index 7b39d90..375f058 100644 --- a/docs/.nav +++ b/docs/.nav @@ -1,14 +1,18 @@ installation getting_started execution_profiles lwt object_mapper +geo_types +graph +graph_fluent +classic_graph performance query_paging security upgrading user_defined_types dates_and_times cloud faq api diff --git a/docs/CHANGELOG.rst b/docs/CHANGELOG.rst new file mode 100644 index 0000000..592a2c0 --- /dev/null +++ b/docs/CHANGELOG.rst @@ -0,0 +1,5 @@ +********* +CHANGELOG +********* + +.. include:: ../CHANGELOG.rst diff --git a/docs/api/cassandra/cluster.rst b/docs/api/cassandra/cluster.rst index 81cf1f0..2b3d782 100644 --- a/docs/api/cassandra/cluster.rst +++ b/docs/api/cassandra/cluster.rst @@ -1,209 +1,228 @@ ``cassandra.cluster`` - Clusters and Sessions ============================================= .. module:: cassandra.cluster .. autoclass:: Cluster ([contact_points=('127.0.0.1',)][, port=9042][, executor_threads=2], **attr_kwargs) .. autoattribute:: contact_points .. autoattribute:: port .. autoattribute:: cql_version .. autoattribute:: protocol_version .. autoattribute:: compression .. autoattribute:: auth_provider .. autoattribute:: load_balancing_policy .. autoattribute:: reconnection_policy .. autoattribute:: default_retry_policy :annotation: = .. autoattribute:: conviction_policy_factory .. autoattribute:: address_translator .. autoattribute:: metrics_enabled .. autoattribute:: metrics .. autoattribute:: ssl_context .. autoattribute:: ssl_options .. autoattribute:: sockopts .. autoattribute:: max_schema_agreement_wait .. autoattribute:: metadata .. autoattribute:: connection_class .. autoattribute:: control_connection_timeout .. autoattribute:: idle_heartbeat_interval .. autoattribute:: idle_heartbeat_timeout .. autoattribute:: schema_event_refresh_window .. autoattribute:: topology_event_refresh_window .. autoattribute:: status_event_refresh_window .. autoattribute:: prepare_on_all_hosts .. autoattribute:: reprepare_on_up .. autoattribute:: connect_timeout .. autoattribute:: schema_metadata_enabled :annotation: = True .. autoattribute:: token_metadata_enabled :annotation: = True .. autoattribute:: timestamp_generator .. autoattribute:: endpoint_factory .. autoattribute:: cloud .. automethod:: connect .. automethod:: shutdown .. automethod:: register_user_type .. automethod:: register_listener .. automethod:: unregister_listener .. automethod:: add_execution_profile .. automethod:: set_max_requests_per_connection .. automethod:: get_max_requests_per_connection .. automethod:: set_min_requests_per_connection .. automethod:: get_min_requests_per_connection .. automethod:: get_core_connections_per_host .. automethod:: set_core_connections_per_host .. automethod:: get_max_connections_per_host .. automethod:: set_max_connections_per_host .. automethod:: get_control_connection_host .. automethod:: refresh_schema_metadata .. automethod:: refresh_keyspace_metadata .. automethod:: refresh_table_metadata .. automethod:: refresh_user_type_metadata .. automethod:: refresh_user_function_metadata .. automethod:: refresh_user_aggregate_metadata .. automethod:: refresh_nodes .. automethod:: set_meta_refresh_enabled -.. autoclass:: ExecutionProfile (load_balancing_policy=, retry_policy=None, consistency_level=LOCAL_ONE, serial_consistency_level=None, request_timeout=10.0, row_factory=, speculative_execution_policy=None) +.. autoclass:: ExecutionProfile (load_balancing_policy=, retry_policy=None, consistency_level=ConsistencyLevel.LOCAL_ONE, serial_consistency_level=None, request_timeout=10.0, row_factory=, speculative_execution_policy=None) :members: :exclude-members: consistency_level .. autoattribute:: consistency_level :annotation: = LOCAL_ONE +.. autoclass:: GraphExecutionProfile (load_balancing_policy=_NOT_SET, retry_policy=None, consistency_level=ConsistencyLevel.LOCAL_ONE, serial_consistency_level=None, request_timeout=30.0, row_factory=None, graph_options=None, continuous_paging_options=_NOT_SET) + :members: + +.. autoclass:: GraphAnalyticsExecutionProfile (load_balancing_policy=None, retry_policy=None, consistency_level=ConsistencyLevel.LOCAL_ONE, serial_consistency_level=None, request_timeout=3600. * 24. * 7., row_factory=None, graph_options=None) + :members: + .. autodata:: EXEC_PROFILE_DEFAULT :annotation: +.. autodata:: EXEC_PROFILE_GRAPH_DEFAULT + :annotation: + +.. autodata:: EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT + :annotation: + +.. autodata:: EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT + :annotation: + .. autoclass:: Session () .. autoattribute:: default_timeout :annotation: = 10.0 .. autoattribute:: default_consistency_level :annotation: = LOCAL_ONE .. autoattribute:: default_serial_consistency_level :annotation: = None .. autoattribute:: row_factory :annotation: = .. autoattribute:: default_fetch_size .. autoattribute:: use_client_timestamp .. autoattribute:: timestamp_generator .. autoattribute:: encoder .. autoattribute:: client_protocol_handler - .. automethod:: execute(statement[, parameters][, timeout][, trace][, custom_payload][, paging_state][, host]) + .. automethod:: execute(statement[, parameters][, timeout][, trace][, custom_payload][, paging_state][, host][, execute_as]) + + .. automethod:: execute_async(statement[, parameters][, trace][, custom_payload][, paging_state][, host][, execute_as]) + + .. automethod:: execute_graph(statement[, parameters][, trace][, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT][, execute_as]) - .. automethod:: execute_async(statement[, parameters][, trace][, custom_payload][, paging_state][, host]) + .. automethod:: execute_graph_async(statement[, parameters][, trace][, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT][, execute_as]) .. automethod:: prepare(statement) .. automethod:: shutdown() .. automethod:: set_keyspace(keyspace) .. automethod:: get_execution_profile .. automethod:: execution_profile_clone_update .. automethod:: add_request_init_listener .. automethod:: remove_request_init_listener .. autoclass:: ResponseFuture () .. autoattribute:: query .. automethod:: result() .. automethod:: get_query_trace() .. automethod:: get_all_query_traces() .. autoattribute:: custom_payload() .. autoattribute:: is_schema_agreed .. autoattribute:: has_more_pages .. autoattribute:: warnings .. automethod:: start_fetching_next_page() .. automethod:: add_callback(fn, *args, **kwargs) .. automethod:: add_errback(fn, *args, **kwargs) .. automethod:: add_callbacks(callback, errback, callback_args=(), callback_kwargs=None, errback_args=(), errback_args=None) .. autoclass:: ResultSet () :members: .. autoexception:: QueryExhausted () .. autoexception:: NoHostAvailable () :members: .. autoexception:: UserTypeDoesNotExist () diff --git a/docs/api/cassandra/cqlengine/models.rst b/docs/api/cassandra/cqlengine/models.rst index fbcec06..60b1471 100644 --- a/docs/api/cassandra/cqlengine/models.rst +++ b/docs/api/cassandra/cqlengine/models.rst @@ -1,198 +1,197 @@ ``cassandra.cqlengine.models`` - Table models for object mapping ================================================================ .. module:: cassandra.cqlengine.models Model ----- .. autoclass:: Model(\*\*kwargs) The initializer creates an instance of the model. Pass in keyword arguments for columns you've defined on the model. .. code-block:: python class Person(Model): id = columns.UUID(primary_key=True) first_name = columns.Text() last_name = columns.Text() person = Person(first_name='Blake', last_name='Eggleston') person.first_name #returns 'Blake' person.last_name #returns 'Eggleston' Model attributes define how the model maps to tables in the database. These are class variables that should be set when defining Model deriviatives. .. autoattribute:: __abstract__ :annotation: = False .. autoattribute:: __table_name__ .. autoattribute:: __table_name_case_sensitive__ .. autoattribute:: __keyspace__ .. autoattribute:: __connection__ .. attribute:: __default_ttl__ :annotation: = None Will be deprecated in release 4.0. You can set the default ttl by configuring the table ``__options__``. See :ref:`ttl-change` for more details. .. autoattribute:: __discriminator_value__ See :ref:`model_inheritance` for usage examples. Each table can have its own set of configuration options, including compaction. Unspecified, these default to sensible values in the server. To override defaults, set options using the model ``__options__`` attribute, which allows options specified a dict. When a table is synced, it will be altered to match the options set on your table. This means that if you are changing settings manually they will be changed back on resync. Do not use the options settings of cqlengine if you want to manage your compaction settings manually. See the `list of supported table properties for more information `_. .. attribute:: __options__ For example: .. code-block:: python class User(Model): __options__ = {'compaction': {'class': 'LeveledCompactionStrategy', 'sstable_size_in_mb': '64', 'tombstone_threshold': '.2'}, - 'read_repair_chance': '0.5', 'comment': 'User data stored here'} user_id = columns.UUID(primary_key=True) name = columns.Text() or : .. code-block:: python class TimeData(Model): __options__ = {'compaction': {'class': 'SizeTieredCompactionStrategy', 'bucket_low': '.3', 'bucket_high': '2', 'min_threshold': '2', 'max_threshold': '64', 'tombstone_compaction_interval': '86400'}, 'gc_grace_seconds': '0'} .. autoattribute:: __compute_routing_key__ The base methods allow creating, storing, and querying modeled objects. .. automethod:: create .. method:: if_not_exists() Check the existence of an object before insertion. The existence of an object is determined by its primary key(s). And please note using this flag would incur performance cost. If the insertion isn't applied, a :class:`~cassandra.cqlengine.query.LWTException` is raised. .. code-block:: python try: TestIfNotExistsModel.if_not_exists().create(id=id, count=9, text='111111111111') except LWTException as e: # handle failure case print e.existing # dict containing LWT result fields This method is supported on Cassandra 2.0 or later. .. method:: if_exists() Check the existence of an object before an update or delete. The existence of an object is determined by its primary key(s). And please note using this flag would incur performance cost. If the update or delete isn't applied, a :class:`~cassandra.cqlengine.query.LWTException` is raised. .. code-block:: python try: TestIfExistsModel.objects(id=id).if_exists().update(count=9, text='111111111111') except LWTException as e: # handle failure case pass This method is supported on Cassandra 2.0 or later. .. automethod:: save .. automethod:: update .. method:: iff(**values) Checks to ensure that the values specified are correct on the Cassandra cluster. Simply specify the column(s) and the expected value(s). As with if_not_exists, this incurs a performance cost. If the insertion isn't applied, a :class:`~cassandra.cqlengine.query.LWTException` is raised. .. code-block:: python t = TestTransactionModel(text='some text', count=5) try: t.iff(count=5).update('other text') except LWTException as e: # handle failure case print e.existing # existing object .. automethod:: get .. automethod:: filter .. automethod:: all .. automethod:: delete .. method:: batch(batch_object) Sets the batch object to run instance updates and inserts queries with. See :doc:`/cqlengine/batches` for usage examples .. automethod:: timeout .. method:: timestamp(timedelta_or_datetime) Sets the timestamp for the query .. method:: ttl(ttl_in_sec) Sets the ttl values to run instance updates and inserts queries with. .. method:: using(connection=None) Change the context on the fly of the model instance (keyspace, connection) .. automethod:: column_family_name Models also support dict-like access: .. method:: len(m) Returns the number of columns defined in the model .. method:: m[col_name] Returns the value of column ``col_name`` .. method:: m[col_name] = value Set ``m[col_name]`` to value .. automethod:: keys .. automethod:: values .. automethod:: items diff --git a/docs/api/cassandra/datastax/graph/fluent/index.rst b/docs/api/cassandra/datastax/graph/fluent/index.rst new file mode 100644 index 0000000..5547e0f --- /dev/null +++ b/docs/api/cassandra/datastax/graph/fluent/index.rst @@ -0,0 +1,24 @@ +:mod:`cassandra.datastax.graph.fluent` +====================================== + +.. module:: cassandra.datastax.graph.fluent + +.. autoclass:: DseGraph + + .. autoattribute:: DSE_GRAPH_QUERY_LANGUAGE + + .. automethod:: create_execution_profile + + .. automethod:: query_from_traversal + + .. automethod:: traversal_source(session=None, graph_name=None, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT, traversal_class=None) + + .. automethod:: batch(session=None, execution_profile=None) + +.. autoclass:: DSESessionRemoteGraphConnection(session[, graph_name, execution_profile]) + +.. autoclass:: BaseGraphRowFactory + +.. autoclass:: graph_traversal_row_factory + +.. autoclass:: graph_traversal_dse_object_row_factory diff --git a/docs/api/cassandra/datastax/graph/fluent/predicates.rst b/docs/api/cassandra/datastax/graph/fluent/predicates.rst new file mode 100644 index 0000000..f6e86f6 --- /dev/null +++ b/docs/api/cassandra/datastax/graph/fluent/predicates.rst @@ -0,0 +1,14 @@ +:mod:`cassandra.datastax.graph.fluent.predicates` +================================================= + +.. module:: cassandra.datastax.graph.fluent.predicates + + +.. autoclass:: Search + :members: + +.. autoclass:: CqlCollection + :members: + +.. autoclass:: Geo + :members: diff --git a/docs/api/cassandra/datastax/graph/fluent/query.rst b/docs/api/cassandra/datastax/graph/fluent/query.rst new file mode 100644 index 0000000..3dd859f --- /dev/null +++ b/docs/api/cassandra/datastax/graph/fluent/query.rst @@ -0,0 +1,8 @@ +:mod:`cassandra.datastax.graph.fluent.query` +============================================ + +.. module:: cassandra.datastax.graph.fluent.query + + +.. autoclass:: TraversalBatch + :members: diff --git a/docs/api/cassandra/datastax/graph/index.rst b/docs/api/cassandra/datastax/graph/index.rst new file mode 100644 index 0000000..dafd5f6 --- /dev/null +++ b/docs/api/cassandra/datastax/graph/index.rst @@ -0,0 +1,121 @@ +``cassandra.datastax.graph`` - Graph Statements, Options, and Row Factories +=========================================================================== + +.. _api-datastax-graph: + +.. module:: cassandra.datastax.graph + +.. autofunction:: single_object_row_factory + +.. autofunction:: graph_result_row_factory + +.. autofunction:: graph_object_row_factory + +.. autofunction:: graph_graphson2_row_factory + +.. autofunction:: graph_graphson3_row_factory + +.. function:: to_int(value) + + Wraps a value to be explicitly serialized as a graphson Int. + +.. function:: to_bigint(value) + + Wraps a value to be explicitly serialized as a graphson Bigint. + +.. function:: to_smallint(value) + + Wraps a value to be explicitly serialized as a graphson Smallint. + +.. function:: to_float(value) + + Wraps a value to be explicitly serialized as a graphson Float. + +.. function:: to_double(value) + + Wraps a value to be explicitly serialized as a graphson Double. + +.. autoclass:: GraphProtocol + :members: + +.. autoclass:: GraphOptions + + .. autoattribute:: graph_name + + .. autoattribute:: graph_source + + .. autoattribute:: graph_language + + .. autoattribute:: graph_read_consistency_level + + .. autoattribute:: graph_write_consistency_level + + .. autoattribute:: is_default_source + + .. autoattribute:: is_analytics_source + + .. autoattribute:: is_graph_source + + .. automethod:: set_source_default + + .. automethod:: set_source_analytics + + .. automethod:: set_source_graph + + +.. autoclass:: SimpleGraphStatement + :members: + +.. autoclass:: Result + :members: + +.. autoclass:: Vertex + :members: + +.. autoclass:: VertexProperty + :members: + +.. autoclass:: Edge + :members: + +.. autoclass:: Path + :members: + +.. autoclass:: T + :members: + +.. autoclass:: GraphSON1Serializer + :members: + +.. autoclass:: GraphSON1Deserializer + + .. automethod:: deserialize_date + + .. automethod:: deserialize_timestamp + + .. automethod:: deserialize_time + + .. automethod:: deserialize_duration + + .. automethod:: deserialize_int + + .. automethod:: deserialize_bigint + + .. automethod:: deserialize_double + + .. automethod:: deserialize_float + + .. automethod:: deserialize_uuid + + .. automethod:: deserialize_blob + + .. automethod:: deserialize_decimal + + .. automethod:: deserialize_point + + .. automethod:: deserialize_linestring + + .. automethod:: deserialize_polygon + +.. autoclass:: GraphSON2Reader + :members: diff --git a/docs/api/cassandra/graph.rst b/docs/api/cassandra/graph.rst new file mode 100644 index 0000000..43ddd30 --- /dev/null +++ b/docs/api/cassandra/graph.rst @@ -0,0 +1,121 @@ +``cassandra.graph`` - Graph Statements, Options, and Row Factories +================================================================== + +.. note:: This module is only for backward compatibility for dse-driver users. Consider using :ref:`cassandra.datastax.graph `. + +.. module:: cassandra.graph + +.. autofunction:: single_object_row_factory + +.. autofunction:: graph_result_row_factory + +.. autofunction:: graph_object_row_factory + +.. autofunction:: graph_graphson2_row_factory + +.. autofunction:: graph_graphson3_row_factory + +.. function:: to_int(value) + + Wraps a value to be explicitly serialized as a graphson Int. + +.. function:: to_bigint(value) + + Wraps a value to be explicitly serialized as a graphson Bigint. + +.. function:: to_smallint(value) + + Wraps a value to be explicitly serialized as a graphson Smallint. + +.. function:: to_float(value) + + Wraps a value to be explicitly serialized as a graphson Float. + +.. function:: to_double(value) + + Wraps a value to be explicitly serialized as a graphson Double. + +.. autoclass:: GraphProtocol + :members: + +.. autoclass:: GraphOptions + + .. autoattribute:: graph_name + + .. autoattribute:: graph_source + + .. autoattribute:: graph_language + + .. autoattribute:: graph_read_consistency_level + + .. autoattribute:: graph_write_consistency_level + + .. autoattribute:: is_default_source + + .. autoattribute:: is_analytics_source + + .. autoattribute:: is_graph_source + + .. automethod:: set_source_default + + .. automethod:: set_source_analytics + + .. automethod:: set_source_graph + + +.. autoclass:: SimpleGraphStatement + :members: + +.. autoclass:: Result + :members: + +.. autoclass:: Vertex + :members: + +.. autoclass:: VertexProperty + :members: + +.. autoclass:: Edge + :members: + +.. autoclass:: Path + :members: + +.. autoclass:: GraphSON1Serializer + :members: + +.. autoclass:: GraphSON1Deserializer + + .. automethod:: deserialize_date + + .. automethod:: deserialize_timestamp + + .. automethod:: deserialize_time + + .. automethod:: deserialize_duration + + .. automethod:: deserialize_int + + .. automethod:: deserialize_bigint + + .. automethod:: deserialize_double + + .. automethod:: deserialize_float + + .. automethod:: deserialize_uuid + + .. automethod:: deserialize_blob + + .. automethod:: deserialize_decimal + + .. automethod:: deserialize_point + + .. automethod:: deserialize_linestring + + .. automethod:: deserialize_polygon + +.. autoclass:: GraphSON2Reader + :members: + +.. autoclass:: GraphSON3Reader + :members: diff --git a/docs/api/cassandra/metadata.rst b/docs/api/cassandra/metadata.rst index ed79d04..91fe39f 100644 --- a/docs/api/cassandra/metadata.rst +++ b/docs/api/cassandra/metadata.rst @@ -1,76 +1,92 @@ ``cassandra.metadata`` - Schema and Ring Topology ================================================= .. module:: cassandra.metadata .. autodata:: cql_keywords :annotation: .. autodata:: cql_keywords_unreserved :annotation: .. autodata:: cql_keywords_reserved :annotation: .. autoclass:: Metadata () :members: :exclude-members: rebuild_schema, rebuild_token_map, add_host, remove_host Schemas ------- .. autoclass:: KeyspaceMetadata () :members: .. autoclass:: UserType () :members: .. autoclass:: Function () :members: .. autoclass:: Aggregate () :members: .. autoclass:: TableMetadata () :members: +.. autoclass:: TableMetadataV3 () + :members: + +.. autoclass:: TableMetadataDSE68 () + :members: + .. autoclass:: ColumnMetadata () :members: .. autoclass:: IndexMetadata () :members: .. autoclass:: MaterializedViewMetadata () :members: +.. autoclass:: VertexMetadata () + :members: + +.. autoclass:: EdgeMetadata () + :members: + Tokens and Ring Topology ------------------------ .. autoclass:: TokenMap () :members: .. autoclass:: Token () :members: .. autoclass:: Murmur3Token :members: .. autoclass:: MD5Token :members: .. autoclass:: BytesToken :members: .. autoclass:: ReplicationStrategy :members: +.. autoclass:: ReplicationFactor + :members: + :exclude-members: create + .. autoclass:: SimpleStrategy :members: .. autoclass:: NetworkTopologyStrategy :members: .. autoclass:: LocalStrategy :members: .. autofunction:: group_keys_by_replica diff --git a/docs/api/cassandra/policies.rst b/docs/api/cassandra/policies.rst index b662755..387b19e 100644 --- a/docs/api/cassandra/policies.rst +++ b/docs/api/cassandra/policies.rst @@ -1,90 +1,96 @@ ``cassandra.policies`` - Load balancing and Failure Handling Policies ===================================================================== .. module:: cassandra.policies Load Balancing -------------- .. autoclass:: HostDistance :members: .. autoclass:: LoadBalancingPolicy :members: .. autoclass:: RoundRobinPolicy :members: .. autoclass:: DCAwareRoundRobinPolicy :members: .. autoclass:: WhiteListRoundRobinPolicy :members: .. autoclass:: TokenAwarePolicy :members: .. autoclass:: HostFilterPolicy .. we document these methods manually so we can specify a param to predicate .. automethod:: predicate(host) .. automethod:: distance .. automethod:: make_query_plan +.. autoclass:: DefaultLoadBalancingPolicy + :members: + +.. autoclass:: DSELoadBalancingPolicy + :members: + Translating Server Node Addresses --------------------------------- .. autoclass:: AddressTranslator :members: .. autoclass:: IdentityTranslator :members: .. autoclass:: EC2MultiRegionTranslator :members: Marking Hosts Up or Down ------------------------ .. autoclass:: ConvictionPolicy :members: .. autoclass:: SimpleConvictionPolicy :members: Reconnecting to Dead Hosts -------------------------- .. autoclass:: ReconnectionPolicy :members: .. autoclass:: ConstantReconnectionPolicy :members: .. autoclass:: ExponentialReconnectionPolicy :members: Retrying Failed Operations -------------------------- .. autoclass:: WriteType :members: .. autoclass:: RetryPolicy :members: .. autoclass:: FallthroughRetryPolicy :members: .. autoclass:: DowngradingConsistencyRetryPolicy :members: Retrying Idempotent Operations ------------------------------ .. autoclass:: SpeculativeExecutionPolicy :members: .. autoclass:: ConstantSpeculativeExecutionPolicy :members: diff --git a/docs/api/index.rst b/docs/api/index.rst index cf79228..9e778d5 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -1,43 +1,54 @@ API Documentation ================= Core Driver ----------- .. toctree:: :maxdepth: 2 cassandra cassandra/cluster cassandra/policies cassandra/auth + cassandra/graph cassandra/metadata cassandra/metrics cassandra/query cassandra/pool cassandra/protocol cassandra/encoder cassandra/decoder cassandra/concurrent cassandra/connection cassandra/util cassandra/timestamps cassandra/io/asyncioreactor cassandra/io/asyncorereactor cassandra/io/eventletreactor cassandra/io/libevreactor cassandra/io/geventreactor cassandra/io/twistedreactor .. _om_api: Object Mapper ------------- .. toctree:: :maxdepth: 1 cassandra/cqlengine/models cassandra/cqlengine/columns cassandra/cqlengine/query cassandra/cqlengine/connection cassandra/cqlengine/management cassandra/cqlengine/usertype + +DataStax Graph +-------------- +.. toctree:: + :maxdepth: 1 + + cassandra/datastax/graph/index + cassandra/datastax/graph/fluent/index + cassandra/datastax/graph/fluent/query + cassandra/datastax/graph/fluent/predicates diff --git a/docs/classic_graph.rst b/docs/classic_graph.rst new file mode 100644 index 0000000..ef68c86 --- /dev/null +++ b/docs/classic_graph.rst @@ -0,0 +1,299 @@ +DataStax Classic Graph Queries +============================== + +Getting Started +~~~~~~~~~~~~~~~ + +First, we need to create a graph in the system. To access the system API, we +use the system execution profile :: + + from cassandra.cluster import Cluster, EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT + + cluster = Cluster() + session = cluster.connect() + + graph_name = 'movies' + session.execute_graph("system.graph(name).ifNotExists().engine(Classic).create()", {'name': graph_name}, + execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT) + + +To execute requests on our newly created graph, we need to setup an execution +profile. Additionally, we also need to set the schema_mode to `development` +for the schema creation:: + + + from cassandra.cluster import Cluster, GraphExecutionProfile, EXEC_PROFILE_GRAPH_DEFAULT + from cassandra.graph import GraphOptions + + graph_name = 'movies' + ep = GraphExecutionProfile(graph_options=GraphOptions(graph_name=graph_name)) + + cluster = Cluster(execution_profiles={EXEC_PROFILE_GRAPH_DEFAULT: ep}) + session = cluster.connect() + + session.execute_graph("schema.config().option('graph.schema_mode').set('development')") + + +We are ready to configure our graph schema. We will create a simple one for movies:: + + # properties are used to define a vertex + properties = """ + schema.propertyKey("genreId").Text().create(); + schema.propertyKey("personId").Text().create(); + schema.propertyKey("movieId").Text().create(); + schema.propertyKey("name").Text().create(); + schema.propertyKey("title").Text().create(); + schema.propertyKey("year").Int().create(); + schema.propertyKey("country").Text().create(); + """ + + session.execute_graph(properties) # we can execute multiple statements in a single request + + # A Vertex represents a "thing" in the world. + vertices = """ + schema.vertexLabel("genre").properties("genreId","name").create(); + schema.vertexLabel("person").properties("personId","name").create(); + schema.vertexLabel("movie").properties("movieId","title","year","country").create(); + """ + + session.execute_graph(vertices) + + # An edge represents a relationship between two vertices + edges = """ + schema.edgeLabel("belongsTo").single().connection("movie","genre").create(); + schema.edgeLabel("actor").connection("movie","person").create(); + """ + + session.execute_graph(edges) + + # Indexes to execute graph requests efficiently + indexes = """ + schema.vertexLabel("genre").index("genresById").materialized().by("genreId").add(); + schema.vertexLabel("genre").index("genresByName").materialized().by("name").add(); + schema.vertexLabel("person").index("personsById").materialized().by("personId").add(); + schema.vertexLabel("person").index("personsByName").materialized().by("name").add(); + schema.vertexLabel("movie").index("moviesById").materialized().by("movieId").add(); + schema.vertexLabel("movie").index("moviesByTitle").materialized().by("title").add(); + schema.vertexLabel("movie").index("moviesByYear").secondary().by("year").add(); + """ + +Next, we'll add some data:: + + session.execute_graph(""" + g.addV('genre').property('genreId', 1).property('name', 'Action').next(); + g.addV('genre').property('genreId', 2).property('name', 'Drama').next(); + g.addV('genre').property('genreId', 3).property('name', 'Comedy').next(); + g.addV('genre').property('genreId', 4).property('name', 'Horror').next(); + """) + + session.execute_graph(""" + g.addV('person').property('personId', 1).property('name', 'Mark Wahlberg').next(); + g.addV('person').property('personId', 2).property('name', 'Leonardo DiCaprio').next(); + g.addV('person').property('personId', 3).property('name', 'Iggy Pop').next(); + """) + + session.execute_graph(""" + g.addV('movie').property('movieId', 1).property('title', 'The Happening'). + property('year', 2008).property('country', 'United States').next(); + g.addV('movie').property('movieId', 2).property('title', 'The Italian Job'). + property('year', 2003).property('country', 'United States').next(); + + g.addV('movie').property('movieId', 3).property('title', 'Revolutionary Road'). + property('year', 2008).property('country', 'United States').next(); + g.addV('movie').property('movieId', 4).property('title', 'The Man in the Iron Mask'). + property('year', 1998).property('country', 'United States').next(); + + g.addV('movie').property('movieId', 5).property('title', 'Dead Man'). + property('year', 1995).property('country', 'United States').next(); + """) + +Now that our genre, actor and movie vertices are added, we'll create the relationships (edges) between them:: + + session.execute_graph(""" + genre_horror = g.V().hasLabel('genre').has('name', 'Horror').next(); + genre_drama = g.V().hasLabel('genre').has('name', 'Drama').next(); + genre_action = g.V().hasLabel('genre').has('name', 'Action').next(); + + leo = g.V().hasLabel('person').has('name', 'Leonardo DiCaprio').next(); + mark = g.V().hasLabel('person').has('name', 'Mark Wahlberg').next(); + iggy = g.V().hasLabel('person').has('name', 'Iggy Pop').next(); + + the_happening = g.V().hasLabel('movie').has('title', 'The Happening').next(); + the_italian_job = g.V().hasLabel('movie').has('title', 'The Italian Job').next(); + rev_road = g.V().hasLabel('movie').has('title', 'Revolutionary Road').next(); + man_mask = g.V().hasLabel('movie').has('title', 'The Man in the Iron Mask').next(); + dead_man = g.V().hasLabel('movie').has('title', 'Dead Man').next(); + + the_happening.addEdge('belongsTo', genre_horror); + the_italian_job.addEdge('belongsTo', genre_action); + rev_road.addEdge('belongsTo', genre_drama); + man_mask.addEdge('belongsTo', genre_drama); + man_mask.addEdge('belongsTo', genre_action); + dead_man.addEdge('belongsTo', genre_drama); + + the_happening.addEdge('actor', mark); + the_italian_job.addEdge('actor', mark); + rev_road.addEdge('actor', leo); + man_mask.addEdge('actor', leo); + dead_man.addEdge('actor', iggy); + """) + +We are all set. You can now query your graph. Here are some examples:: + + # Find all movies of the genre Drama + for r in session.execute_graph(""" + g.V().has('genre', 'name', 'Drama').in('belongsTo').valueMap();"""): + print(r) + + # Find all movies of the same genre than the movie 'Dead Man' + for r in session.execute_graph(""" + g.V().has('movie', 'title', 'Dead Man').out('belongsTo').in('belongsTo').valueMap();"""): + print(r) + + # Find all movies of Mark Wahlberg + for r in session.execute_graph(""" + g.V().has('person', 'name', 'Mark Wahlberg').in('actor').valueMap();"""): + print(r) + +To see a more graph examples, see `DataStax Graph Examples `_. + +Graph Types +~~~~~~~~~~~ + +Here are the supported graph types with their python representations: + +========== ================ +DSE Graph Python +========== ================ +boolean bool +bigint long, int (PY3) +int int +smallint int +varint int +float float +double double +uuid uuid.UUID +Decimal Decimal +inet str +timestamp datetime.datetime +date datetime.date +time datetime.time +duration datetime.timedelta +point Point +linestring LineString +polygon Polygon +blob bytearray, buffer (PY2), memoryview (PY3), bytes (PY3) +========== ================ + +Graph Row Factory +~~~~~~~~~~~~~~~~~ + +By default (with :class:`.GraphExecutionProfile.row_factory` set to :func:`.graph.graph_object_row_factory`), known graph result +types are unpacked and returned as specialized types (:class:`.Vertex`, :class:`.Edge`). If the result is not one of these +types, a :class:`.graph.Result` is returned, containing the graph result parsed from JSON and removed from its outer dict. +The class has some accessor convenience methods for accessing top-level properties by name (`type`, `properties` above), +or lists by index:: + + # dicts with `__getattr__` or `__getitem__` + result = session.execute_graph("[[key_str: 'value', key_int: 3]]", execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT)[0] # Using system exec just because there is no graph defined + result # dse.graph.Result({u'key_str': u'value', u'key_int': 3}) + result.value # {u'key_int': 3, u'key_str': u'value'} (dict) + result.key_str # u'value' + result.key_int # 3 + result['key_str'] # u'value' + result['key_int'] # 3 + + # lists with `__getitem__` + result = session.execute_graph('[[0, 1, 2]]', execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT)[0] + result # dse.graph.Result([0, 1, 2]) + result.value # [0, 1, 2] (list) + result[1] # 1 (list[1]) + +You can use a different row factory by setting :attr:`.Session.default_graph_row_factory` or passing it to +:meth:`.Session.execute_graph`. For example, :func:`.graph.single_object_row_factory` returns the JSON result string`, +unparsed. :func:`.graph.graph_result_row_factory` returns parsed, but unmodified results (such that all metadata is retained, +unlike :func:`.graph.graph_object_row_factory`, which sheds some as attributes and properties are unpacked). These results +also provide convenience methods for converting to known types (:meth:`~.Result.as_vertex`, :meth:`~.Result.as_edge`, :meth:`~.Result.as_path`). + +Vertex and Edge properties are never unpacked since their types are unknown. If you know your graph schema and want to +deserialize properties, use the :class:`.GraphSON1Deserializer`. It provides convenient methods to deserialize by types (e.g. +deserialize_date, deserialize_uuid, deserialize_polygon etc.) Example:: + + # ... + from cassandra.graph import GraphSON1Deserializer + + row = session.execute_graph("g.V().toList()")[0] + value = row.properties['my_property_key'][0].value # accessing the VertexProperty value + value = GraphSON1Deserializer.deserialize_timestamp(value) + + print(value) # 2017-06-26 08:27:05 + print(type(value)) # + + +Named Parameters +~~~~~~~~~~~~~~~~ + +Named parameters are passed in a dict to :meth:`.cluster.Session.execute_graph`:: + + result_set = session.execute_graph('[a, b]', {'a': 1, 'b': 2}, execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT) + [r.value for r in result_set] # [1, 2] + +All python types listed in `Graph Types`_ can be passed as named parameters and will be serialized +automatically to their graph representation: + +Example:: + + session.execute_graph(""" + g.addV('person'). + property('name', text_value). + property('age', integer_value). + property('birthday', timestamp_value). + property('house_yard', polygon_value).toList() + """, { + 'text_value': 'Mike Smith', + 'integer_value': 34, + 'timestamp_value': datetime.datetime(1967, 12, 30), + 'polygon_value': Polygon(((30, 10), (40, 40), (20, 40), (10, 20), (30, 10))) + }) + + +As with all Execution Profile parameters, graph options can be set in the cluster default (as shown in the first example) +or specified per execution:: + + ep = session.execution_profile_clone_update(EXEC_PROFILE_GRAPH_DEFAULT, + graph_options=GraphOptions(graph_name='something-else')) + session.execute_graph(statement, execution_profile=ep) + +Using GraphSON2 Protocol +~~~~~~~~~~~~~~~~~~~~~~~~ + +The default graph protocol used is GraphSON1. However GraphSON1 may +cause problems of type conversion happening during the serialization +of the query to the DSE Graph server, or the deserialization of the +responses back from a string Gremlin query. GraphSON2 offers better +support for the complex data types handled by DSE Graph. + +DSE >=5.0.4 now offers the possibility to use the GraphSON2 protocol +for graph queries. Enabling GraphSON2 can be done by `changing the +graph protocol of the execution profile` and `setting the graphson2 row factory`:: + + from cassandra.cluster import Cluster, GraphExecutionProfile, EXEC_PROFILE_GRAPH_DEFAULT + from cassandra.graph import GraphOptions, GraphProtocol, graph_graphson2_row_factory + + # Create a GraphSON2 execution profile + ep = GraphExecutionProfile(graph_options=GraphOptions(graph_name='types', + graph_protocol=GraphProtocol.GRAPHSON_2_0), + row_factory=graph_graphson2_row_factory) + + cluster = Cluster(execution_profiles={EXEC_PROFILE_GRAPH_DEFAULT: ep}) + session = cluster.connect() + session.execute_graph(...) + +Using GraphSON2, all properties will be automatically deserialized to +its Python representation. Note that it may bring significant +behavioral change at runtime. + +It is generally recommended to switch to GraphSON2 as it brings more +consistent support for complex data types in the Graph driver and will +be activated by default in the next major version (Python dse-driver +driver 3.0). diff --git a/docs/cloud.rst b/docs/cloud.rst index a7e2fb9..3607ef8 100644 --- a/docs/cloud.rst +++ b/docs/cloud.rst @@ -1,38 +1,89 @@ Cloud ----- Connecting ========== -To connect to a DataStax Apollo cluster: +To connect to a DataStax Astra cluster: -1. Download the secure connect bundle from your Apollo account. +1. Download the secure connect bundle from your Astra account. 2. Connect to your cluster with .. code-block:: python from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider cloud_config = { 'secure_connect_bundle': '/path/to/secure-connect-dbname.zip' } auth_provider = PlainTextAuthProvider(username='user', password='pass') cluster = Cluster(cloud=cloud_config, auth_provider=auth_provider) session = cluster.connect() -Apollo Differences +Cloud Config Options +==================== + +use_default_tempdir ++++++++++++++++++++ + +The secure connect bundle needs to be extracted to load the certificates into the SSLContext. +By default, the zip location is used as the base dir for the extraction. In some environments, +the zip location file system is read-only (e.g Azure Function). With *use_default_tempdir* set to *True*, +the default temporary directory of the system will be used as base dir. + +.. code:: python + + cloud_config = { + 'secure_connect_bundle': '/path/to/secure-connect-dbname.zip', + 'use_default_tempdir': True + } + ... + +Astra Differences ================== -In most circumstances, the client code for interacting with an Apollo cluster will be the same as interacting with any other Cassandra cluster. The exceptions being: +In most circumstances, the client code for interacting with an Astra cluster will be the same as interacting with any other Cassandra cluster. The exceptions being: * A cloud configuration must be passed to a :class:`~.Cluster` instance via the `cloud` attribute (as demonstrated above). * An SSL connection will be established automatically. Manual SSL configuration is not allowed, and using `ssl_context` or `ssl_options` will result in an exception. * A :class:`~.Cluster`'s `contact_points` attribute should not be used. The cloud config contains all of the necessary contact information. * If a consistency level is not specified for an execution profile or query, then :attr:`.ConsistencyLevel.LOCAL_QUORUM` will be used as the default. Limitations =========== Event loops ^^^^^^^^^^^ -Twisted and Evenlet aren't supported yet. These event loops are still using the old way to configure -SSL (ssl_options), which is not compatible with the secure connect bundle provided by Apollo. +Evenlet isn't yet supported for python 3.7+ due to an `issue in Eventlet `_. + + +CqlEngine +========= + +When using the object mapper, you can configure cqlengine with :func:`~.cqlengine.connection.set_session`: + +.. code:: python + + from cassandra.cqlengine import connection + ... + + c = Cluster(cloud={'secure_connect_bundle':'/path/to/secure-connect-test.zip'}, + auth_provider=PlainTextAuthProvider('user', 'pass')) + s = c.connect('myastrakeyspace') + connection.set_session(s) + ... + +If you are using some third-party libraries (flask, django, etc.), you might not be able to change the +configuration mechanism. For this reason, the `hosts` argument of the default +:func:`~.cqlengine.connection.setup` function will be ignored if a `cloud` config is provided: + +.. code:: python + + from cassandra.cqlengine import connection + ... + + connection.setup( + None, # or anything else + "myastrakeyspace", cloud={ + 'secure_connect_bundle':'/path/to/secure-connect-test.zip' + }, + auth_provider=PlainTextAuthProvider('user', 'pass')) diff --git a/docs/conf.py b/docs/conf.py index b2bfbe0..4c0dfb5 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,227 +1,227 @@ # -*- coding: utf-8 -*- # # Cassandra Driver documentation build configuration file, created by # sphinx-quickstart on Mon Jul 1 11:40:09 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) import cassandra # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Cassandra Driver' copyright = u'2013-2017 DataStax' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = cassandra.__version__ # The full version, including alpha/beta/rc tags. release = cassandra.__version__ autodoc_member_order = 'bysource' autoclass_content = 'both' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'custom' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['./themes'] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { '**': [ 'about.html', 'navigation.html', 'relations.html', 'searchbox.html' ] } # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. -#html_use_index = True +html_use_index = False # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'CassandraDriverdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'cassandra-driver.tex', u'Cassandra Driver Documentation', u'DataStax', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'cassandra-driver', u'Cassandra Driver Documentation', - [u'Tyler Hobbs'], 1) + [u'DataStax'], 1) ] diff --git a/docs/execution_profiles.rst b/docs/execution_profiles.rst index 698f3db..7be1a85 100644 --- a/docs/execution_profiles.rst +++ b/docs/execution_profiles.rst @@ -1,156 +1,156 @@ Execution Profiles ================== Execution profiles aim at making it easier to execute requests in different ways within a single connected ``Session``. Execution profiles are being introduced to deal with the exploding number of configuration options, especially as the database platform evolves more complex workloads. The legacy configuration remains intact, but legacy and Execution Profile APIs cannot be used simultaneously on the same client ``Cluster``. Legacy configuration will be removed in the next major release (4.0). An execution profile and its parameters should be unique across ``Cluster`` instances. For example, an execution profile and its ``LoadBalancingPolicy`` should not be applied to more than one ``Cluster`` instance. This document explains how Execution Profiles relate to existing settings, and shows how to use the new profiles for request execution. Mapping Legacy Parameters to Profiles ------------------------------------- Execution profiles can inherit from :class:`.cluster.ExecutionProfile`, and currently provide the following options, previously input from the noted attributes: - load_balancing_policy - :attr:`.Cluster.load_balancing_policy` - request_timeout - :attr:`.Session.default_timeout`, optional :meth:`.Session.execute` parameter - retry_policy - :attr:`.Cluster.default_retry_policy`, optional :attr:`.Statement.retry_policy` attribute - consistency_level - :attr:`.Session.default_consistency_level`, optional :attr:`.Statement.consistency_level` attribute - serial_consistency_level - :attr:`.Session.default_serial_consistency_level`, optional :attr:`.Statement.serial_consistency_level` attribute - row_factory - :attr:`.Session.row_factory` attribute When using the new API, these parameters can be defined by instances of :class:`.cluster.ExecutionProfile`. Using Execution Profiles ------------------------ Default ~~~~~~~ .. code:: python from cassandra.cluster import Cluster cluster = Cluster() session = cluster.connect() local_query = 'SELECT rpc_address FROM system.local' for _ in cluster.metadata.all_hosts(): print session.execute(local_query)[0] .. parsed-literal:: Row(rpc_address='127.0.0.2') Row(rpc_address='127.0.0.1') The default execution profile is built from Cluster parameters and default Session attributes. This profile matches existing default parameters. Initializing cluster with profiles ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code:: python from cassandra.cluster import ExecutionProfile from cassandra.policies import WhiteListRoundRobinPolicy node1_profile = ExecutionProfile(load_balancing_policy=WhiteListRoundRobinPolicy(['127.0.0.1'])) node2_profile = ExecutionProfile(load_balancing_policy=WhiteListRoundRobinPolicy(['127.0.0.2'])) profiles = {'node1': node1_profile, 'node2': node2_profile} session = Cluster(execution_profiles=profiles).connect() for _ in cluster.metadata.all_hosts(): print session.execute(local_query, execution_profile='node1')[0] .. parsed-literal:: Row(rpc_address='127.0.0.1') Row(rpc_address='127.0.0.1') .. code:: python for _ in cluster.metadata.all_hosts(): print session.execute(local_query, execution_profile='node2')[0] .. parsed-literal:: Row(rpc_address='127.0.0.2') Row(rpc_address='127.0.0.2') .. code:: python for _ in cluster.metadata.all_hosts(): print session.execute(local_query)[0] .. parsed-literal:: Row(rpc_address='127.0.0.2') Row(rpc_address='127.0.0.1') Note that, even when custom profiles are injected, the default ``TokenAwarePolicy(DCAwareRoundRobinPolicy())`` is still present. To override the default, specify a policy with the :data:`~.cluster.EXEC_PROFILE_DEFAULT` key. .. code:: python from cassandra.cluster import EXEC_PROFILE_DEFAULT profile = ExecutionProfile(request_timeout=30) cluster = Cluster(execution_profiles={EXEC_PROFILE_DEFAULT: profile}) Adding named profiles ~~~~~~~~~~~~~~~~~~~~~ New profiles can be added constructing from scratch, or deriving from default: .. code:: python locked_execution = ExecutionProfile(load_balancing_policy=WhiteListRoundRobinPolicy(['127.0.0.1'])) node1_profile = 'node1_whitelist' cluster.add_execution_profile(node1_profile, locked_execution) - + for _ in cluster.metadata.all_hosts(): print session.execute(local_query, execution_profile=node1_profile)[0] .. parsed-literal:: Row(rpc_address='127.0.0.1') Row(rpc_address='127.0.0.1') See :meth:`.Cluster.add_execution_profile` for details and optional parameters. Passing a profile instance without mapping ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We also have the ability to pass profile instances to be used for execution, but not added to the mapping: .. code:: python from cassandra.query import tuple_factory - + tmp = session.execution_profile_clone_update('node1', request_timeout=100, row_factory=tuple_factory) print session.execute(local_query, execution_profile=tmp)[0] print session.execute(local_query, execution_profile='node1')[0] .. parsed-literal:: ('127.0.0.1',) Row(rpc_address='127.0.0.1') The new profile is a shallow copy, so the ``tmp`` profile shares a load balancing policy with one managed by the cluster. If reference objects are to be updated in the clone, one would typically set those attributes to a new instance. diff --git a/docs/geo_types.rst b/docs/geo_types.rst new file mode 100644 index 0000000..f8750d6 --- /dev/null +++ b/docs/geo_types.rst @@ -0,0 +1,39 @@ +DSE Geometry Types +================== +This section shows how to query and work with the geometric types provided by DSE. + +These types are enabled implicitly by creating the Session from :class:`cassandra.cluster.Cluster`. +This module implicitly registers these types for use in the driver. This extension provides +some simple representative types in :mod:`cassandra.util` for inserting and retrieving data:: + + from cassandra.cluster import Cluster + from cassandra.util import Point, LineString, Polygon + session = Cluster().connect() + + session.execute("INSERT INTO ks.geo (k, point, line, poly) VALUES (%s, %s, %s, %s)", + 0, Point(1, 2), LineString(((1, 2), (3, 4))), Polygon(((1, 2), (3, 4), (5, 6)))) + +Queries returning geometric types return the :mod:`dse.util` types. Note that these can easily be used to construct +types from third-party libraries using the common attributes:: + + from shapely.geometry import LineString + shapely_linestrings = [LineString(res.line.coords) for res in session.execute("SELECT line FROM ks.geo")] + +For prepared statements, shapely geometry types can be used interchangeably with the built-in types because their +defining attributes are the same:: + + from shapely.geometry import Point + prepared = session.prepare("UPDATE ks.geo SET point = ? WHERE k = ?") + session.execute(prepared, (0, Point(1.2, 3.4))) + +In order to use shapely types in a CQL-interpolated (non-prepared) query, one must update the encoder with those types, specifying +the same string encoder as set for the internal types:: + + from cassandra import util + from shapely.geometry import Point, LineString, Polygon + + encoder_func = session.encoder.mapping[util.Point] + for t in (Point, LineString, Polygon): + session.encoder.mapping[t] = encoder_func + + session.execute("UPDATE ks.geo SET point = %s where k = %s", (0, Point(1.2, 3.4))) diff --git a/docs/getting_started.rst b/docs/getting_started.rst index 2dc32e6..ce31ca5 100644 --- a/docs/getting_started.rst +++ b/docs/getting_started.rst @@ -1,405 +1,502 @@ Getting Started =============== First, make sure you have the driver properly :doc:`installed `. -Connecting to Cassandra +Connecting to a Cluster ----------------------- Before we can start executing any queries against a Cassandra cluster we need to setup an instance of :class:`~.Cluster`. As the name suggests, you will typically have one instance of :class:`~.Cluster` for each Cassandra cluster you want to interact with. +First, make sure you have the Cassandra driver properly :doc:`installed `. + +Connecting to Astra ++++++++++++++++++++ + +If you are a DataStax `Astra `_ user, +here is how to connect to your cluster: + +1. Download the secure connect bundle from your Astra account. +2. Connect to your cluster with + +.. code-block:: python + + from cassandra.cluster import Cluster + from cassandra.auth import PlainTextAuthProvider + + cloud_config = { + 'secure_connect_bundle': '/path/to/secure-connect-dbname.zip' + } + auth_provider = PlainTextAuthProvider(username='user', password='pass') + cluster = Cluster(cloud=cloud_config, auth_provider=auth_provider) + session = cluster.connect() + +See `Astra `_ and :doc:`cloud` for more details. + +Connecting to Cassandra ++++++++++++++++++++++++ The simplest way to create a :class:`~.Cluster` is like this: .. code-block:: python from cassandra.cluster import Cluster cluster = Cluster() This will attempt to connection to a Cassandra instance on your local machine (127.0.0.1). You can also specify a list of IP addresses for nodes in your cluster: .. code-block:: python from cassandra.cluster import Cluster cluster = Cluster(['192.168.0.1', '192.168.0.2']) The set of IP addresses we pass to the :class:`~.Cluster` is simply an initial set of contact points. After the driver connects to one of these nodes it will *automatically discover* the rest of the nodes in the cluster and connect to them, so you don't need to list every node in your cluster. If you need to use a non-standard port, use SSL, or customize the driver's behavior in some other way, this is the place to do it: .. code-block:: python from cassandra.cluster import Cluster - from cassandra.policies import DCAwareRoundRobinPolicy - - cluster = Cluster( - ['10.1.1.3', '10.1.1.4', '10.1.1.5'], - load_balancing_policy=DCAwareRoundRobinPolicy(local_dc='US_EAST'), - port=9042) - - -You can find a more complete list of options in the :class:`~.Cluster` documentation. + cluster = Cluster(['192.168.0.1', '192.168.0.2'], port=..., ssl_context=...) Instantiating a :class:`~.Cluster` does not actually connect us to any nodes. To establish connections and begin executing queries we need a :class:`~.Session`, which is created by calling :meth:`.Cluster.connect()`: .. code-block:: python cluster = Cluster() session = cluster.connect() +Session Keyspace +---------------- The :meth:`~.Cluster.connect()` method takes an optional ``keyspace`` argument which sets the default keyspace for all queries made through that :class:`~.Session`: .. code-block:: python cluster = Cluster() session = cluster.connect('mykeyspace') - You can always change a Session's keyspace using :meth:`~.Session.set_keyspace` or by executing a ``USE `` query: .. code-block:: python session.set_keyspace('users') # or you can do this instead session.execute('USE users') +Execution Profiles +------------------ +Profiles are passed in by ``execution_profiles`` dict. + +In this case we can construct the base ``ExecutionProfile`` passing all attributes: + +.. code-block:: python + + from cassandra.cluster import Cluster, ExecutionProfile, EXEC_PROFILE_DEFAULT + from cassandra.policies import WhiteListRoundRobinPolicy, DowngradingConsistencyRetryPolicy + from cassandra.query import tuple_factory + + profile = ExecutionProfile( + load_balancing_policy=WhiteListRoundRobinPolicy(['127.0.0.1']), + retry_policy=DowngradingConsistencyRetryPolicy(), + consistency_level=ConsistencyLevel.LOCAL_QUORUM, + serial_consistency_level=ConsistencyLevel.LOCAL_SERIAL, + request_timeout=15, + row_factory=tuple_factory + ) + cluster = Cluster(execution_profiles={EXEC_PROFILE_DEFAULT: profile}) + session = cluster.connect() + + print(session.execute("SELECT release_version FROM system.local").one()) + +Users are free to setup additional profiles to be used by name: + +.. code-block:: python + + profile_long = ExecutionProfile(request_timeout=30) + cluster = Cluster(execution_profiles={'long': profile_long}) + session = cluster.connect() + session.execute(statement, execution_profile='long') + +Also, parameters passed to ``Session.execute`` or attached to ``Statement``\s are still honored as before. Executing Queries ----------------- Now that we have a :class:`.Session` we can begin to execute queries. The simplest way to execute a query is to use :meth:`~.Session.execute()`: .. code-block:: python rows = session.execute('SELECT name, age, email FROM users') for user_row in rows: print user_row.name, user_row.age, user_row.email This will transparently pick a Cassandra node to execute the query against and handle any retries that are necessary if the operation fails. By default, each row in the result set will be a `namedtuple `_. Each row will have a matching attribute for each column defined in the schema, such as ``name``, ``age``, and so on. You can also treat them as normal tuples by unpacking them or accessing fields by position. The following three examples are equivalent: .. code-block:: python rows = session.execute('SELECT name, age, email FROM users') for row in rows: print row.name, row.age, row.email .. code-block:: python rows = session.execute('SELECT name, age, email FROM users') for (name, age, email) in rows: print name, age, email .. code-block:: python rows = session.execute('SELECT name, age, email FROM users') for row in rows: print row[0], row[1], row[2] If you prefer another result format, such as a ``dict`` per row, you can change the :attr:`~.Session.row_factory` attribute. -For queries that will be run repeatedly, you should use -`Prepared statements <#prepared-statements>`_. +As mentioned in our `Drivers Best Practices Guide `_, +it is highly recommended to use `Prepared statements <#prepared-statement>`_ for your +frequently run queries. + +.. _prepared-statement: + +Prepared Statements +------------------- +Prepared statements are queries that are parsed by Cassandra and then saved +for later use. When the driver uses a prepared statement, it only needs to +send the values of parameters to bind. This lowers network traffic +and CPU utilization within Cassandra because Cassandra does not have to +re-parse the query each time. + +To prepare a query, use :meth:`.Session.prepare()`: + +.. code-block:: python + + user_lookup_stmt = session.prepare("SELECT * FROM users WHERE user_id=?") + + users = [] + for user_id in user_ids_to_query: + user = session.execute(user_lookup_stmt, [user_id]) + users.append(user) + +:meth:`~.Session.prepare()` returns a :class:`~.PreparedStatement` instance +which can be used in place of :class:`~.SimpleStatement` instances or literal +string queries. It is automatically prepared against all nodes, and the driver +handles re-preparing against new nodes and restarted nodes when necessary. + +Note that the placeholders for prepared statements are ``?`` characters. This +is different than for simple, non-prepared statements (although future versions +of the driver may use the same placeholders for both). Passing Parameters to CQL Queries ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -When executing non-prepared statements, the driver supports two forms of -parameter place-holders: positional and named. +Althought it is not recommended, you can also pass parameters to non-prepared +statements. The driver supports two forms of parameter place-holders: positional +and named. Positional parameters are used with a ``%s`` placeholder. For example, when you execute: .. code-block:: python session.execute( """ INSERT INTO users (name, credits, user_id) VALUES (%s, %s, %s) """, ("John O'Reilly", 42, uuid.uuid1()) ) It is translated to the following CQL query:: INSERT INTO users (name, credits, user_id) VALUES ('John O''Reilly', 42, 2644bada-852c-11e3-89fb-e0b9a54a6d93) Note that you should use ``%s`` for all types of arguments, not just strings. For example, this would be **wrong**: .. code-block:: python session.execute("INSERT INTO USERS (name, age) VALUES (%s, %d)", ("bob", 42)) # wrong Instead, use ``%s`` for the age placeholder. If you need to use a literal ``%`` character, use ``%%``. **Note**: you must always use a sequence for the second argument, even if you are only passing in a single variable: .. code-block:: python session.execute("INSERT INTO foo (bar) VALUES (%s)", "blah") # wrong session.execute("INSERT INTO foo (bar) VALUES (%s)", ("blah")) # wrong session.execute("INSERT INTO foo (bar) VALUES (%s)", ("blah", )) # right session.execute("INSERT INTO foo (bar) VALUES (%s)", ["blah"]) # right Note that the second line is incorrect because in Python, single-element tuples require a comma. Named place-holders use the ``%(name)s`` form: .. code-block:: python session.execute( """ INSERT INTO users (name, credits, user_id, username) VALUES (%(name)s, %(credits)s, %(user_id)s, %(name)s) """, {'name': "John O'Reilly", 'credits': 42, 'user_id': uuid.uuid1()} ) Note that you can repeat placeholders with the same name, such as ``%(name)s`` in the above example. Only data values should be supplied this way. Other items, such as keyspaces, table names, and column names should be set ahead of time (typically using normal string formatting). .. _type-conversions: Type Conversions ^^^^^^^^^^^^^^^^ For non-prepared statements, Python types are cast to CQL literals in the following way: .. table:: +--------------------+-------------------------+ | Python Type | CQL Literal Type | +====================+=========================+ | ``None`` | ``NULL`` | +--------------------+-------------------------+ | ``bool`` | ``boolean`` | +--------------------+-------------------------+ | ``float`` | | ``float`` | | | | ``double`` | +--------------------+-------------------------+ | | ``int`` | | ``int`` | | | ``long`` | | ``bigint`` | | | | ``varint`` | | | | ``smallint`` | | | | ``tinyint`` | | | | ``counter`` | +--------------------+-------------------------+ | ``decimal.Decimal``| ``decimal`` | +--------------------+-------------------------+ | | ``str`` | | ``ascii`` | | | ``unicode`` | | ``varchar`` | | | | ``text`` | +--------------------+-------------------------+ | | ``buffer`` | ``blob`` | | | ``bytearray`` | | +--------------------+-------------------------+ | ``date`` | ``date`` | +--------------------+-------------------------+ | ``datetime`` | ``timestamp`` | +--------------------+-------------------------+ | ``time`` | ``time`` | +--------------------+-------------------------+ | | ``list`` | ``list`` | | | ``tuple`` | | | | generator | | +--------------------+-------------------------+ | | ``set`` | ``set`` | | | ``frozenset`` | | +--------------------+-------------------------+ | | ``dict`` | ``map`` | | | ``OrderedDict`` | | +--------------------+-------------------------+ | ``uuid.UUID`` | | ``timeuuid`` | | | | ``uuid`` | +--------------------+-------------------------+ Asynchronous Queries ^^^^^^^^^^^^^^^^^^^^ The driver supports asynchronous query execution through :meth:`~.Session.execute_async()`. Instead of waiting for the query to complete and returning rows directly, this method almost immediately returns a :class:`~.ResponseFuture` object. There are two ways of getting the final result from this object. The first is by calling :meth:`~.ResponseFuture.result()` on it. If the query has not yet completed, this will block until it has and then return the result or raise an Exception if an error occurred. For example: .. code-block:: python from cassandra import ReadTimeout query = "SELECT * FROM users WHERE user_id=%s" future = session.execute_async(query, [user_id]) # ... do some other work try: rows = future.result() user = rows[0] print user.name, user.age except ReadTimeout: log.exception("Query timed out:") This works well for executing many queries concurrently: .. code-block:: python # build a list of futures futures = [] query = "SELECT * FROM users WHERE user_id=%s" for user_id in ids_to_fetch: futures.append(session.execute_async(query, [user_id]) # wait for them to complete and use the results for future in futures: rows = future.result() print rows[0].name Alternatively, instead of calling :meth:`~.ResponseFuture.result()`, you can attach callback and errback functions through the :meth:`~.ResponseFuture.add_callback()`, :meth:`~.ResponseFuture.add_errback()`, and :meth:`~.ResponseFuture.add_callbacks()`, methods. If you have used Twisted Python before, this is designed to be a lightweight version of that: .. code-block:: python def handle_success(rows): user = rows[0] try: process_user(user.name, user.age, user.id) except Exception: log.error("Failed to process user %s", user.id) # don't re-raise errors in the callback def handle_error(exception): log.error("Failed to fetch user info: %s", exception) future = session.execute_async(query) future.add_callbacks(handle_success, handle_error) There are a few important things to remember when working with callbacks: * **Exceptions that are raised inside the callback functions will be logged and then ignored.** * Your callback will be run on the event loop thread, so any long-running operations will prevent other requests from being handled Setting a Consistency Level --------------------------- The consistency level used for a query determines how many of the replicas of the data you are interacting with need to respond for the query to be considered a success. By default, :attr:`.ConsistencyLevel.LOCAL_ONE` will be used for all queries. -You can specify a different default for the session on :attr:`.Session.default_consistency_level` -if the cluster is configured in legacy mode (not using execution profiles). Otherwise this can -be done by setting the :attr:`.ExecutionProfile.consistency_level` for the execution profile with key -:data:`~.cluster.EXEC_PROFILE_DEFAULT`. +You can specify a different default by setting the :attr:`.ExecutionProfile.consistency_level` +for the execution profile with key :data:`~.cluster.EXEC_PROFILE_DEFAULT`. To specify a different consistency level per request, wrap queries in a :class:`~.SimpleStatement`: .. code-block:: python from cassandra import ConsistencyLevel from cassandra.query import SimpleStatement query = SimpleStatement( "INSERT INTO users (name, age) VALUES (%s, %s)", consistency_level=ConsistencyLevel.QUORUM) session.execute(query, ('John', 42)) -Prepared Statements -------------------- -Prepared statements are queries that are parsed by Cassandra and then saved -for later use. When the driver uses a prepared statement, it only needs to -send the values of parameters to bind. This lowers network traffic -and CPU utilization within Cassandra because Cassandra does not have to -re-parse the query each time. - -To prepare a query, use :meth:`.Session.prepare()`: - -.. code-block:: python - - user_lookup_stmt = session.prepare("SELECT * FROM users WHERE user_id=?") - - users = [] - for user_id in user_ids_to_query: - user = session.execute(user_lookup_stmt, [user_id]) - users.append(user) - -:meth:`~.Session.prepare()` returns a :class:`~.PreparedStatement` instance -which can be used in place of :class:`~.SimpleStatement` instances or literal -string queries. It is automatically prepared against all nodes, and the driver -handles re-preparing against new nodes and restarted nodes when necessary. - -Note that the placeholders for prepared statements are ``?`` characters. This -is different than for simple, non-prepared statements (although future versions -of the driver may use the same placeholders for both). - Setting a Consistency Level with Prepared Statements ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To specify a consistency level for prepared statements, you have two options. The first is to set a default consistency level for every execution of the prepared statement: .. code-block:: python from cassandra import ConsistencyLevel cluster = Cluster() session = cluster.connect("mykeyspace") user_lookup_stmt = session.prepare("SELECT * FROM users WHERE user_id=?") user_lookup_stmt.consistency_level = ConsistencyLevel.QUORUM # these will both use QUORUM user1 = session.execute(user_lookup_stmt, [user_id1])[0] user2 = session.execute(user_lookup_stmt, [user_id2])[0] The second option is to create a :class:`~.BoundStatement` from the :class:`~.PreparedStatement` and binding parameters and set a consistency level on that: .. code-block:: python # override the QUORUM default user3_lookup = user_lookup_stmt.bind([user_id3]) user3_lookup.consistency_level = ConsistencyLevel.ALL user3 = session.execute(user3_lookup) + +Speculative Execution +^^^^^^^^^^^^^^^^^^^^^ + +Speculative execution is a way to minimize latency by preemptively executing several +instances of the same query against different nodes. For more details about this +technique, see `Speculative Execution with DataStax Drivers `_. + +To enable speculative execution: + +* Configure a :class:`~.policies.SpeculativeExecutionPolicy` with the ExecutionProfile +* Mark your query as idempotent, which mean it can be applied multiple + times without changing the result of the initial application. + See `Query Idempotence `_ for more details. + + +Example: + +.. code-block:: python + + from cassandra.cluster import Cluster, ExecutionProfile, EXEC_PROFILE_DEFAULT + from cassandra.policies import ConstantSpeculativeExecutionPolicy + from cassandra.query import SimpleStatement + + # Configure the speculative execution policy + ep = ExecutionProfile( + speculative_execution_policy=ConstantSpeculativeExecutionPolicy(delay=.5, max_attempts=10) + ) + cluster = Cluster(..., execution_profiles={EXEC_PROFILE_DEFAULT: ep}) + session = cluster.connect() + + # Mark the query idempotent + query = SimpleStatement( + "UPDATE my_table SET list_col = [1] WHERE pk = 1", + is_idempotent=True + ) + + # Execute. A new query will be sent to the server every 0.5 second + # until we receive a response, for a max number attempts of 10. + session.execute(query) diff --git a/docs/graph.rst b/docs/graph.rst new file mode 100644 index 0000000..47dc53d --- /dev/null +++ b/docs/graph.rst @@ -0,0 +1,434 @@ +DataStax Graph Queries +====================== + +The driver executes graph queries over the Cassandra native protocol. Use +:meth:`.Session.execute_graph` or :meth:`.Session.execute_graph_async` for +executing gremlin queries in DataStax Graph. + +The driver defines three Execution Profiles suitable for graph execution: + +* :data:`~.cluster.EXEC_PROFILE_GRAPH_DEFAULT` +* :data:`~.cluster.EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT` +* :data:`~.cluster.EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT` + +See :doc:`getting_started` and :doc:`execution_profiles` +for more detail on working with profiles. + +In DSE 6.8.0, the Core graph engine has been introduced and is now the default. It +provides a better unified multi-model, performance and scale. This guide +is for graphs that use the core engine. If you work with previous versions of +DSE or existing graphs, see :doc:`classic_graph`. + +Getting Started with Graph and the Core Engine +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +First, we need to create a graph in the system. To access the system API, we +use the system execution profile :: + + from cassandra.cluster import Cluster, EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT + + cluster = Cluster() + session = cluster.connect() + + graph_name = 'movies' + session.execute_graph("system.graph(name).create()", {'name': graph_name}, + execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT) + + +Graphs that use the core engine only support GraphSON3. Since they are Cassandra tables under +the hood, we can automatically configure the execution profile with the proper options +(row_factory and graph_protocol) when executing queries. You only need to make sure that +the `graph_name` is set and GraphSON3 will be automatically used:: + + from cassandra.cluster import Cluster, GraphExecutionProfile, EXEC_PROFILE_GRAPH_DEFAULT + + graph_name = 'movies' + ep = GraphExecutionProfile(graph_options=GraphOptions(graph_name=graph_name)) + cluster = Cluster(execution_profiles={EXEC_PROFILE_GRAPH_DEFAULT: ep}) + session = cluster.connect() + session.execute_graph("g.addV(...)") + + +Note that this graph engine detection is based on the metadata. You might experience +some query errors if the graph has been newly created and is not yet in the metadata. This +would result to a badly configured execution profile. If you really want to avoid that, +configure your execution profile explicitly:: + + from cassandra.cluster import Cluster, GraphExecutionProfile, EXEC_PROFILE_GRAPH_DEFAULT + from cassandra.graph import GraphOptions, GraphProtocol, graph_graphson3_row_factory + + graph_name = 'movies' + ep_graphson3 = GraphExecutionProfile( + row_factory=graph_graphson3_row_factory, + graph_options=GraphOptions( + graph_protocol=GraphProtocol.GRAPHSON_3_0, + graph_name=graph_name)) + + cluster = Cluster(execution_profiles={'core': ep_graphson3}) + session = cluster.connect() + session.execute_graph("g.addV(...)", execution_profile='core') + + +We are ready to configure our graph schema. We will create a simple one for movies:: + + # A Vertex represents a "thing" in the world. + # Create the genre vertex + query = """ + schema.vertexLabel('genre') + .partitionBy('genreId', Int) + .property('name', Text) + .create() + """ + session.execute_graph(query) + + # Create the person vertex + query = """ + schema.vertexLabel('person') + .partitionBy('personId', Int) + .property('name', Text) + .create() + """ + session.execute_graph(query) + + # Create the movie vertex + query = """ + schema.vertexLabel('movie') + .partitionBy('movieId', Int) + .property('title', Text) + .property('year', Int) + .property('country', Text) + .create() + """ + session.execute_graph(query) + + # An edge represents a relationship between two vertices + # Create our edges + queries = """ + schema.edgeLabel('belongsTo').from('movie').to('genre').create(); + schema.edgeLabel('actor').from('movie').to('person').create(); + """ + session.execute_graph(queries) + + # Indexes to execute graph requests efficiently + + # If you have a node with the search workload enabled (solr), use the following: + indexes = """ + schema.vertexLabel('genre').searchIndex() + .by("name") + .create(); + + schema.vertexLabel('person').searchIndex() + .by("name") + .create(); + + schema.vertexLabel('movie').searchIndex() + .by('title') + .by("year") + .create(); + """ + session.execute_graph(indexes) + + # Otherwise, use secondary indexes: + indexes = """ + schema.vertexLabel('genre') + .secondaryIndex('by_genre') + .by('name') + .create() + + schema.vertexLabel('person') + .secondaryIndex('by_name') + .by('name') + .create() + + schema.vertexLabel('movie') + .secondaryIndex('by_title') + .by('title') + .create() + """ + session.execute_graph(indexes) + +Add some edge indexes (materialized views):: + + indexes = """ + schema.edgeLabel('belongsTo') + .from('movie') + .to('genre') + .materializedView('movie__belongsTo__genre_by_in_genreId') + .ifNotExists() + .partitionBy(IN, 'genreId') + .clusterBy(OUT, 'movieId', Asc) + .create() + + schema.edgeLabel('actor') + .from('movie') + .to('person') + .materializedView('movie__actor__person_by_in_personId') + .ifNotExists() + .partitionBy(IN, 'personId') + .clusterBy(OUT, 'movieId', Asc) + .create() + """ + session.execute_graph(indexes) + +Next, we'll add some data:: + + session.execute_graph(""" + g.addV('genre').property('genreId', 1).property('name', 'Action').next(); + g.addV('genre').property('genreId', 2).property('name', 'Drama').next(); + g.addV('genre').property('genreId', 3).property('name', 'Comedy').next(); + g.addV('genre').property('genreId', 4).property('name', 'Horror').next(); + """) + + session.execute_graph(""" + g.addV('person').property('personId', 1).property('name', 'Mark Wahlberg').next(); + g.addV('person').property('personId', 2).property('name', 'Leonardo DiCaprio').next(); + g.addV('person').property('personId', 3).property('name', 'Iggy Pop').next(); + """) + + session.execute_graph(""" + g.addV('movie').property('movieId', 1).property('title', 'The Happening'). + property('year', 2008).property('country', 'United States').next(); + g.addV('movie').property('movieId', 2).property('title', 'The Italian Job'). + property('year', 2003).property('country', 'United States').next(); + + g.addV('movie').property('movieId', 3).property('title', 'Revolutionary Road'). + property('year', 2008).property('country', 'United States').next(); + g.addV('movie').property('movieId', 4).property('title', 'The Man in the Iron Mask'). + property('year', 1998).property('country', 'United States').next(); + + g.addV('movie').property('movieId', 5).property('title', 'Dead Man'). + property('year', 1995).property('country', 'United States').next(); + """) + +Now that our genre, actor and movie vertices are added, we'll create the relationships (edges) between them:: + + session.execute_graph(""" + genre_horror = g.V().hasLabel('genre').has('name', 'Horror').id().next(); + genre_drama = g.V().hasLabel('genre').has('name', 'Drama').id().next(); + genre_action = g.V().hasLabel('genre').has('name', 'Action').id().next(); + + leo = g.V().hasLabel('person').has('name', 'Leonardo DiCaprio').id().next(); + mark = g.V().hasLabel('person').has('name', 'Mark Wahlberg').id().next(); + iggy = g.V().hasLabel('person').has('name', 'Iggy Pop').id().next(); + + the_happening = g.V().hasLabel('movie').has('title', 'The Happening').id().next(); + the_italian_job = g.V().hasLabel('movie').has('title', 'The Italian Job').id().next(); + rev_road = g.V().hasLabel('movie').has('title', 'Revolutionary Road').id().next(); + man_mask = g.V().hasLabel('movie').has('title', 'The Man in the Iron Mask').id().next(); + dead_man = g.V().hasLabel('movie').has('title', 'Dead Man').id().next(); + + g.addE('belongsTo').from(__.V(the_happening)).to(__.V(genre_horror)).next(); + g.addE('belongsTo').from(__.V(the_italian_job)).to(__.V(genre_action)).next(); + g.addE('belongsTo').from(__.V(rev_road)).to(__.V(genre_drama)).next(); + g.addE('belongsTo').from(__.V(man_mask)).to(__.V(genre_drama)).next(); + g.addE('belongsTo').from(__.V(man_mask)).to(__.V(genre_action)).next(); + g.addE('belongsTo').from(__.V(dead_man)).to(__.V(genre_drama)).next(); + + g.addE('actor').from(__.V(the_happening)).to(__.V(mark)).next(); + g.addE('actor').from(__.V(the_italian_job)).to(__.V(mark)).next(); + g.addE('actor').from(__.V(rev_road)).to(__.V(leo)).next(); + g.addE('actor').from(__.V(man_mask)).to(__.V(leo)).next(); + g.addE('actor').from(__.V(dead_man)).to(__.V(iggy)).next(); + """) + +We are all set. You can now query your graph. Here are some examples:: + + # Find all movies of the genre Drama + for r in session.execute_graph(""" + g.V().has('genre', 'name', 'Drama').in('belongsTo').valueMap();"""): + print(r) + + # Find all movies of the same genre than the movie 'Dead Man' + for r in session.execute_graph(""" + g.V().has('movie', 'title', 'Dead Man').out('belongsTo').in('belongsTo').valueMap();"""): + print(r) + + # Find all movies of Mark Wahlberg + for r in session.execute_graph(""" + g.V().has('person', 'name', 'Mark Wahlberg').in('actor').valueMap();"""): + print(r) + +To see a more graph examples, see `DataStax Graph Examples `_. + +Graph Types for the Core Engine +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Here are the supported graph types with their python representations: + +============ ================= +DSE Graph Python Driver +============ ================= +text str +boolean bool +bigint long +int int +smallint int +varint long +double float +float float +uuid UUID +bigdecimal Decimal +duration Duration (cassandra.util) +inet str or IPV4Address/IPV6Address (if available) +timestamp datetime.datetime +date datetime.date +time datetime.time +polygon Polygon +point Point +linestring LineString +blob bytearray, buffer (PY2), memoryview (PY3), bytes (PY3) +list list +map dict +set set or list + (Can return a list due to numerical values returned by Java) +tuple tuple +udt class or namedtuple +============ ================= + +Named Parameters +~~~~~~~~~~~~~~~~ + +Named parameters are passed in a dict to :meth:`.cluster.Session.execute_graph`:: + + result_set = session.execute_graph('[a, b]', {'a': 1, 'b': 2}, execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT) + [r.value for r in result_set] # [1, 2] + +All python types listed in `Graph Types for the Core Engine`_ can be passed as named parameters and will be serialized +automatically to their graph representation: + +Example:: + + session.execute_graph(""" + g.addV('person'). + property('name', text_value). + property('age', integer_value). + property('birthday', timestamp_value). + property('house_yard', polygon_value).next() + """, { + 'text_value': 'Mike Smith', + 'integer_value': 34, + 'timestamp_value': datetime.datetime(1967, 12, 30), + 'polygon_value': Polygon(((30, 10), (40, 40), (20, 40), (10, 20), (30, 10))) + }) + + +As with all Execution Profile parameters, graph options can be set in the cluster default (as shown in the first example) +or specified per execution:: + + ep = session.execution_profile_clone_update(EXEC_PROFILE_GRAPH_DEFAULT, + graph_options=GraphOptions(graph_name='something-else')) + session.execute_graph(statement, execution_profile=ep) + +CQL collections, Tuple and UDT +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This is a very interesting feature of the core engine: we can use all CQL data types, including +list, map, set, tuple and udt. Here is an example using all these types:: + + query = """ + schema.type('address') + .property('address', Text) + .property('city', Text) + .property('state', Text) + .create(); + """ + session.execute_graph(query) + + # It works the same way than normal CQL UDT, so we + # can create an udt class and register it + class Address(object): + def __init__(self, address, city, state): + self.address = address + self.city = city + self.state = state + + session.cluster.register_user_type(graph_name, 'address', Address) + + query = """ + schema.vertexLabel('person') + .partitionBy('personId', Int) + .property('address', typeOf('address')) + .property('friends', listOf(Text)) + .property('skills', setOf(Text)) + .property('scores', mapOf(Text, Int)) + .property('last_workout', tupleOf(Text, Date)) + .create() + """ + session.execute_graph(query) + + # insertion example + query = """ + g.addV('person') + .property('personId', pid) + .property('address', address) + .property('friends', friends) + .property('skills', skills) + .property('scores', scores) + .property('last_workout', last_workout) + .next() + """ + + session.execute_graph(query, { + 'pid': 3, + 'address': Address('42 Smith St', 'Quebec', 'QC'), + 'friends': ['Al', 'Mike', 'Cathy'], + 'skills': {'food', 'fight', 'chess'}, + 'scores': {'math': 98, 'french': 3}, + 'last_workout': ('CrossFit', datetime.date(2018, 11, 20)) + }) + +Limitations +----------- + +Since Python is not a strongly-typed language and the UDT/Tuple graphson representation is, you might +get schema errors when trying to write numerical data. Example:: + + session.execute_graph(""" + schema.vertexLabel('test_tuple').partitionBy('id', Int).property('t', tupleOf(Text, Bigint)).create() + """) + + session.execute_graph(""" + g.addV('test_tuple').property('id', 0).property('t', t) + """, + {'t': ('Test', 99))} + ) + + # error: [Invalid query] message="Value component 1 is of type int, not bigint" + +This is because the server requires the client to include a GraphSON schema definition +with every UDT or tuple query. In the general case, the driver can't determine what Graph type +is meant by, e.g., an int value, and so it can't serialize the value with the correct type in the schema. +The driver provides some numerical type-wrapper factories that you can use to specify types: + +* :func:`~.to_int` +* :func:`~.to_bigint` +* :func:`~.to_smallint` +* :func:`~.to_float` +* :func:`~.to_double` + +Here's the working example of the case above:: + + from cassandra.graph import to_bigint + + session.execute_graph(""" + g.addV('test_tuple').property('id', 0).property('t', t) + """, + {'t': ('Test', to_bigint(99))} + ) + +Continuous Paging +~~~~~~~~~~~~~~~~~ + +This is another nice feature that comes with the core engine: continuous paging with +graph queries. If all nodes of the cluster are >= DSE 6.8.0, it is automatically +enabled under the hood to get the best performance. If you want to explicitly +enable/disable it, you can do it through the execution profile:: + + # Disable it + ep = GraphExecutionProfile(..., continuous_paging_options=None)) + cluster = Cluster(execution_profiles={EXEC_PROFILE_GRAPH_DEFAULT: ep}) + + # Enable with a custom max_pages option + ep = GraphExecutionProfile(..., + continuous_paging_options=ContinuousPagingOptions(max_pages=10))) + cluster = Cluster(execution_profiles={EXEC_PROFILE_GRAPH_DEFAULT: ep}) diff --git a/docs/graph_fluent.rst b/docs/graph_fluent.rst new file mode 100644 index 0000000..03cf8d3 --- /dev/null +++ b/docs/graph_fluent.rst @@ -0,0 +1,415 @@ +DataStax Graph Fluent API +========================= + +The fluent API adds graph features to the core driver: + +* A TinkerPop GraphTraversalSource builder to execute traversals on a DSE cluster +* The ability to execution traversal queries explicitly using execute_graph +* GraphSON serializers for all DSE Graph types. +* DSE Search predicates + +The Graph fluent API depends on Apache TinkerPop and is not installed by default. Make sure +you have the Graph requirements are properly :ref:`installed `. + +You might be interested in reading the :doc:`DataStax Graph Getting Started documentation ` to +understand the basics of creating a graph and its schema. + +Graph Traversal Queries +~~~~~~~~~~~~~~~~~~~~~~~ + +The driver provides :meth:`.Session.execute_graph`, which allows users to execute traversal +query strings. Here is a simple example:: + + session.execute_graph("g.addV('genre').property('genreId', 1).property('name', 'Action').next();") + +Since graph queries can be very complex, working with strings is not very convenient and is +hard to maintain. This fluent API allows you to build Gremlin traversals and write your graph +queries directly in Python. These native traversal queries can be executed explicitly, with +a `Session` object, or implicitly:: + + from cassandra.cluster import Cluster, EXEC_PROFILE_GRAPH_DEFAULT + from cassandra.datastax.graph import GraphProtocol + from cassandra.datastax.graph.fluent import DseGraph + + # Create an execution profile, using GraphSON3 for Core graphs + ep_graphson3 = DseGraph.create_execution_profile( + 'my_core_graph_name', + graph_protocol=GraphProtocol.GRAPHSON_3_0) + cluster = Cluster(execution_profiles={EXEC_PROFILE_GRAPH_DEFAULT: ep_graphson3}) + session = cluster.connect() + + # Execute a fluent graph query + g = DseGraph.traversal_source(session=session) + g.addV('genre').property('genreId', 1).property('name', 'Action').next() + + # implicit execution caused by iterating over results + for v in g.V().has('genre', 'name', 'Drama').in_('belongsTo').valueMap(): + print(v) + +These :ref:`Python types ` are also supported transparently:: + + g.addV('person').property('name', 'Mike').property('birthday', datetime(1984, 3, 11)). \ + property('house_yard', Polygon(((30, 10), (40, 40), (20, 40), (10, 20), (30, 10))) + +More readings about Gremlin: + +* `DataStax Drivers Fluent API `_ +* `gremlin-python documentation `_ + +Configuring a Traversal Execution Profile +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The fluent api takes advantage of *configuration profiles* to allow +different execution configurations for the various query handlers. Graph traversal +execution requires a custom execution profile to enable Gremlin-bytecode as +query language. With Core graphs, it is important to use GraphSON3. Here is how +to accomplish this configuration: + +.. code-block:: python + + from cassandra.cluster import Cluster, EXEC_PROFILE_GRAPH_DEFAULT + from cassandra.datastax.graph import GraphProtocol + from cassandra.datastax.graph.fluent import DseGraph + + # Using GraphSON3 as graph protocol is a requirement with Core graphs. + ep = DseGraph.create_execution_profile( + 'graph_name', + graph_protocol=GraphProtocol.GRAPHSON_3_0) + + # For Classic graphs, GraphSON1, GraphSON2 and GraphSON3 (DSE 6.8+) are supported. + ep_classic = DseGraph.create_execution_profile('classic_graph_name') # default is GraphSON2 + + cluster = Cluster(execution_profiles={EXEC_PROFILE_GRAPH_DEFAULT: ep, 'classic': ep_classic}) + session = cluster.connect() + + g = DseGraph.traversal_source(session) # Build the GraphTraversalSource + print g.V().toList() # Traverse the Graph + +Note that the execution profile created with :meth:`DseGraph.create_execution_profile <.datastax.graph.fluent.DseGraph.create_execution_profile>` cannot +be used for any groovy string queries. + +If you want to change execution property defaults, please see the :doc:`Execution Profile documentation ` +for a more generalized discussion of the API. Graph traversal queries use the same execution profile defined for DSE graph. If you +need to change the default properties, please refer to the :doc:`DSE Graph query documentation page ` + +Explicit Graph Traversal Execution with a DSE Session +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Traversal queries can be executed explicitly using `session.execute_graph` or `session.execute_graph_async`. These functions +return results as DSE graph types. If you are familiar with DSE queries or need async execution, you might prefer that way. +Below is an example of explicit execution. For this example, assume the schema has been generated as above: + +.. code-block:: python + + from cassandra.cluster import Cluster, EXEC_PROFILE_GRAPH_DEFAULT + from cassandra.datastax.graph import GraphProtocol + from cassandra.datastax.graph.fluent import DseGraph + from pprint import pprint + + ep = DseGraph.create_execution_profile( + 'graph_name', + graph_protocol=GraphProtocol.GRAPHSON_3_0) + cluster = Cluster(execution_profiles={EXEC_PROFILE_GRAPH_DEFAULT: ep}) + session = cluster.connect() + + g = DseGraph.traversal_source(session=session) + +Convert a traversal to a bytecode query for classic graphs:: + + addV_query = DseGraph.query_from_traversal( + g.addV('genre').property('genreId', 1).property('name', 'Action'), + graph_protocol=GraphProtocol.GRAPHSON_3_0 + ) + v_query = DseGraph.query_from_traversal( + g.V(), + graph_protocol=GraphProtocol.GRAPHSON_3_0) + + for result in session.execute_graph(addV_query): + pprint(result.value) + for result in session.execute_graph(v_query): + pprint(result.value) + +Converting a traversal to a bytecode query for core graphs require some more work, because we +need the cluster context for UDT and tuple types: + +.. code-block:: python + context = { + 'cluster': cluster, + 'graph_name': 'the_graph_for_the_query' + } + addV_query = DseGraph.query_from_traversal( + g.addV('genre').property('genreId', 1).property('name', 'Action'), + graph_protocol=GraphProtocol.GRAPHSON_3_0, + context=context + ) + + for result in session.execute_graph(addV_query): + pprint(result.value) + +Implicit Graph Traversal Execution with TinkerPop +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Using the :class:`DseGraph <.datastax.graph.fluent.DseGraph>` class, you can build a GraphTraversalSource +that will execute queries on a DSE session without explicitly passing anything to +that session. We call this *implicit execution* because the `Session` is not +explicitly involved. Everything is managed internally by TinkerPop while +traversing the graph and the results are TinkerPop types as well. + +Synchronous Example +------------------- + +.. code-block:: python + + # Build the GraphTraversalSource + g = DseGraph.traversal_source(session) + # implicitly execute the query by traversing the TraversalSource + g.addV('genre').property('genreId', 1).property('name', 'Action').next() + + # blocks until the query is completed and return the results + results = g.V().toList() + pprint(results) + +Asynchronous Exemple +-------------------- + +You can execute a graph traversal query asynchronously by using `.promise()`. It returns a +python `Future `_. + +.. code-block:: python + + # Build the GraphTraversalSource + g = DseGraph.traversal_source(session) + # implicitly execute the query by traversing the TraversalSource + g.addV('genre').property('genreId', 1).property('name', 'Action').next() # not async + + # get a future and wait + future = g.V().promise() + results = list(future.result()) + pprint(results) + + # or set a callback + def cb(f): + results = list(f.result()) + pprint(results) + future = g.V().promise() + future.add_done_callback(cb) + # do other stuff... + +Specify the Execution Profile explicitly +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you don't want to change the default graph execution profile (`EXEC_PROFILE_GRAPH_DEFAULT`), you can register a new +one as usual and use it explicitly. Here is an example: + +.. code-block:: python + + from cassandra.cluster import Cluster + from cassandra.datastax.graph.fluent import DseGraph + + cluster = Cluster() + ep = DseGraph.create_execution_profile('graph_name', graph_protocol=GraphProtocol.GRAPHSON_3_0) + cluster.add_execution_profile('graph_traversal', ep) + session = cluster.connect() + + g = DseGraph.traversal_source() + query = DseGraph.query_from_traversal(g.V()) + session.execute_graph(query, execution_profile='graph_traversal') + +You can also create multiple GraphTraversalSources and use them with +the same execution profile (for different graphs): + +.. code-block:: python + + g_movies = DseGraph.traversal_source(session, graph_name='movies', ep) + g_series = DseGraph.traversal_source(session, graph_name='series', ep) + + print(g_movies.V().toList()) # Traverse the movies Graph + print(g_series.V().toList()) # Traverse the series Graph + +Batch Queries +~~~~~~~~~~~~~ + +DSE Graph supports batch queries using a :class:`TraversalBatch <.datastax.graph.fluent.query.TraversalBatch>` object +instantiated with :meth:`DseGraph.batch <.datastax.graph.fluent.DseGraph.batch>`. A :class:`TraversalBatch <.datastax.graph.fluent.query.TraversalBatch>` allows +you to execute multiple graph traversals in a single atomic transaction. A +traversal batch is executed with :meth:`.Session.execute_graph` or using +:meth:`TraversalBatch.execute <.datastax.graph.fluent.query.TraversalBatch.execute>` if bounded to a DSE session. + +Either way you choose to execute the traversal batch, you need to configure +the execution profile accordingly. Here is a example:: + + from cassandra.cluster import Cluster + from cassandra.datastax.graph.fluent import DseGraph + + ep = DseGraph.create_execution_profile( + 'graph_name', + graph_protocol=GraphProtocol.GRAPHSON_3_0) + cluster = Cluster(execution_profiles={'graphson3': ep}) + session = cluster.connect() + + g = DseGraph.traversal_source() + +To execute the batch using :meth:`.Session.execute_graph`, you need to convert +the batch to a GraphStatement:: + + batch = DseGraph.batch() + + batch.add( + g.addV('genre').property('genreId', 1).property('name', 'Action')) + batch.add( + g.addV('genre').property('genreId', 2).property('name', 'Drama')) # Don't use `.next()` with a batch + + graph_statement = batch.as_graph_statement(graph_protocol=GraphProtocol.GRAPHSON_3_0) + graph_statement.is_idempotent = True # configure any Statement parameters if needed... + session.execute_graph(graph_statement, execution_profile='graphson3') + +To execute the batch using :meth:`TraversalBatch.execute <.datastax.graph.fluent.query.TraversalBatch.execute>`, you need to bound the batch to a DSE session:: + + batch = DseGraph.batch(session, 'graphson3') # bound the session and execution profile + + batch.add( + g.addV('genre').property('genreId', 1).property('name', 'Action')) + batch.add( + g.addV('genre').property('genreId', 2).property('name', 'Drama')) # Don't use `.next()` with a batch + + batch.execute() + +DSL (Domain Specific Languages) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +DSL are very useful to write better domain-specific APIs and avoiding +code duplication. Let's say we have a graph of `People` and we produce +a lot of statistics based on age. All graph traversal queries of our +application would look like:: + + g.V().hasLabel("people").has("age", P.gt(21))... + + +which is not really verbose and quite annoying to repeat in a code base. Let's create a DSL:: + + from gremlin_python.process.graph_traversal import GraphTraversal, GraphTraversalSource + + class MyAppTraversal(GraphTraversal): + + def younger_than(self, age): + return self.has("age", P.lt(age)) + + def older_than(self, age): + return self.has("age", P.gt(age)) + + + class MyAppTraversalSource(GraphTraversalSource): + + def __init__(self, *args, **kwargs): + super(MyAppTraversalSource, self).__init__(*args, **kwargs) + self.graph_traversal = MyAppTraversal + + def people(self): + return self.get_graph_traversal().V().hasLabel("people") + +Now, we can use our DSL that is a lot cleaner:: + + from cassandra.datastax.graph.fluent import DseGraph + + # ... + g = DseGraph.traversal_source(session=session, traversal_class=MyAppTraversalsource) + + g.people().younger_than(21)... + g.people().older_than(30)... + +To see a more complete example of DSL, see the `Python killrvideo DSL app `_ + +Search +~~~~~~ + +DSE Graph can use search indexes that take advantage of DSE Search functionality for +efficient traversal queries. Here are the list of additional search predicates: + +Text tokenization: + +* :meth:`token <.datastax.graph.fluent.predicates.Search.token>` +* :meth:`token_prefix <.datastax.graph.fluent.predicates.Search.token_prefix>` +* :meth:`token_regex <.datastax.graph.fluent.predicates.Search.token_regex>` +* :meth:`token_fuzzy <.datastax.graph.fluent.predicates.Search.token_fuzzy>` + +Text match: + +* :meth:`prefix <.datastax.graph.fluent.predicates.Search.prefix>` +* :meth:`regex <.datastax.graph.fluent.predicates.Search.regex>` +* :meth:`fuzzy <.datastax.graph.fluent.predicates.Search.fuzzy>` +* :meth:`phrase <.datastax.graph.fluent.predicates.Search.phrase>` + +Geo: + +* :meth:`inside <.datastax.graph.fluent.predicates.Geo.inside>` + +Create search indexes +--------------------- + +For text tokenization: + +.. code-block:: python + + + s.execute_graph("schema.vertexLabel('my_vertex_label').index('search').search().by('text_field').asText().add()") + +For text match: + +.. code-block:: python + + + s.execute_graph("schema.vertexLabel('my_vertex_label').index('search').search().by('text_field').asString().add()") + + +For geospatial: + +You can create a geospatial index on Point and LineString fields. + +.. code-block:: python + + + s.execute_graph("schema.vertexLabel('my_vertex_label').index('search').search().by('point_field').add()") + + +Using search indexes +-------------------- + +Token: + +.. code-block:: python + + from cassandra.datastax.graph.fluent.predicates import Search + # ... + + g = DseGraph.traversal_source() + query = DseGraph.query_from_traversal( + g.V().has('my_vertex_label','text_field', Search.token_regex('Hello.+World')).values('text_field')) + session.execute_graph(query) + +Text: + +.. code-block:: python + + from cassandra.datastax.graph.fluent.predicates import Search + # ... + + g = DseGraph.traversal_source() + query = DseGraph.query_from_traversal( + g.V().has('my_vertex_label','text_field', Search.prefix('Hello')).values('text_field')) + session.execute_graph(query) + +Geospatial: + +.. code-block:: python + + from cassandra.datastax.graph.fluent.predicates import Geo + from cassandra.util import Distance + # ... + + g = DseGraph.traversal_source() + query = DseGraph.query_from_traversal( + g.V().has('my_vertex_label','point_field', Geo.inside(Distance(46, 71, 100)).values('point_field')) + session.execute_graph(query) + + +For more details, please refer to the official `DSE Search Indexes Documentation `_ diff --git a/docs/index.rst b/docs/index.rst index 13fca18..978faa1 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,90 +1,109 @@ -Python Cassandra Driver -======================= -A Python client driver for `Apache Cassandra `_. +DataStax Python Driver for Apache Cassandra® +============================================ +A Python client driver for `Apache Cassandra® `_. This driver works exclusively with the Cassandra Query Language v3 (CQL3) -and Cassandra's native protocol. Cassandra 2.1+ is supported. +and Cassandra's native protocol. Cassandra 2.1+ is supported, including DSE 4.7+. -The driver supports Python 2.7, 3.4, 3.5, 3.6 and 3.7. +The driver supports Python 2.7, 3.5, 3.6, 3.7 and 3.8. This driver is open source under the `Apache v2 License `_. The source code for this driver can be found on `GitHub `_. **Note:** DataStax products do not support big-endian systems. Contents -------- :doc:`installation` How to install the driver. :doc:`getting_started` A guide through the first steps of connecting to Cassandra and executing queries :doc:`execution_profiles` An introduction to a more flexible way of configuring request execution :doc:`lwt` Working with results of conditional requests :doc:`object_mapper` Introduction to the integrated object mapper, cqlengine :doc:`performance` Tips for getting good performance. :doc:`query_paging` Notes on paging large query results :doc:`security` An overview of the security features of the driver :doc:`upgrading` A guide to upgrading versions of the driver :doc:`user_defined_types` Working with Cassandra 2.1's user-defined types :doc:`dates_and_times` Some discussion on the driver's approach to working with timestamp, date, time types :doc:`cloud` - A guide to connecting to Datastax Apollo + A guide to connecting to Datastax Astra + +:doc:`geo_types` + Working with DSE geometry types + +:doc:`graph` + Graph queries with the Core engine + +:doc:`classic_graph` + Graph queries with the Classic engine + +:doc:`graph_fluent` + DataStax Graph Fluent API + +:doc:`CHANGELOG` + Log of changes to the driver, organized by version. :doc:`faq` A collection of Frequently Asked Questions :doc:`api/index` The API documentation. .. toctree:: :hidden: api/index installation getting_started upgrading execution_profiles performance query_paging lwt security user_defined_types object_mapper + geo_types + graph + classic_graph + graph_fluent dates_and_times cloud faq Getting Help ------------ Visit the :doc:`FAQ section ` in this documentation. Please send questions to the `mailing list `_. -Alternatively, you can use the `#datastax-drivers` channel in the DataStax Acadamy Slack to ask questions in real time. +Alternatively, you can use the `DataStax Community `_. Reporting Issues ---------------- Please report any bugs and make any feature requests on the `JIRA `_ issue tracker. If you would like to contribute, please feel free to open a pull request. diff --git a/docs/installation.rst b/docs/installation.rst index a6eedf4..3855383 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -1,247 +1,236 @@ Installation ============ Supported Platforms ------------------- -Python 2.7, 3.4, 3.5, 3.6 and 3.7 are supported. Both CPython (the standard Python +Python 2.7, 3.5, 3.6, 3.7 and 3.8 are supported. Both CPython (the standard Python implementation) and `PyPy `_ are supported and tested. Linux, OSX, and Windows are supported. Installation through pip ------------------------ `pip `_ is the suggested tool for installing packages. It will handle installing all Python dependencies for the driver at the same time as the driver itself. To install the driver*:: pip install cassandra-driver You can use ``pip install --pre cassandra-driver`` if you need to install a beta version. ***Note**: if intending to use optional extensions, install the `dependencies <#optional-non-python-dependencies>`_ first. The driver may need to be reinstalled if dependencies are added after the initial installation. +Verifying your Installation +--------------------------- +To check if the installation was successful, you can run:: + + python -c 'import cassandra; print cassandra.__version__' + +It should print something like "3.22.0". + +.. _installation-datastax-graph: + +(*Optional*) DataStax Graph +--------------------------- +The driver provides an optional fluent graph API that depends on Apache TinkerPop (gremlinpython). It is +not installed by default. To be able to build Gremlin traversals, you need to install +the `graph` requirements:: + + pip install cassandra-driver[graph] + +See :doc:`graph_fluent` for more details about this API. + +(*Optional*) Compression Support +-------------------------------- +Compression can optionally be used for communication between the driver and +Cassandra. There are currently two supported compression algorithms: +snappy (in Cassandra 1.2+) and LZ4 (only in Cassandra 2.0+). If either is +available for the driver and Cassandra also supports it, it will +be used automatically. + +For lz4 support:: + + pip install lz4 + +For snappy support:: + + pip install python-snappy + +(If using a Debian Linux derivative such as Ubuntu, it may be easier to +just run ``apt-get install python-snappy``.) + +(*Optional*) Metrics Support +---------------------------- +The driver has built-in support for capturing :attr:`.Cluster.metrics` about +the queries you run. However, the ``scales`` library is required to +support this:: + + pip install scales + + Speeding Up Installation ^^^^^^^^^^^^^^^^^^^^^^^^ -By default, installing the driver through ``pip`` uses Cython to compile -certain parts of the driver. +By default, installing the driver through ``pip`` uses a pre-compiled, platform-specific wheel when available. +If using a source distribution rather than a wheel, Cython is used to compile certain parts of the driver. This makes those hot paths faster at runtime, but the Cython compilation process can take a long time -- as long as 10 minutes in some environments. In environments where performance is less important, it may be worth it to :ref:`disable Cython as documented below `. You can also use ``CASS_DRIVER_BUILD_CONCURRENCY`` to increase the number of threads used to build the driver and any C extensions: .. code-block:: bash $ # installing from source $ CASS_DRIVER_BUILD_CONCURRENCY=8 python setup.py install $ # installing from pip $ CASS_DRIVER_BUILD_CONCURRENCY=8 pip install cassandra-driver -Finally, you can `build a wheel `_ from the driver's source and distribute that to computers -that depend on it. For example: - -.. code-block:: bash - - $ git clone https://github.com/datastax/python-driver.git - $ cd python-driver - $ git checkout 3.14.0 # or other desired tag - $ pip install wheel - $ python setup.py bdist_wheel - $ # build wheel with optional concurrency settings - $ CASS_DRIVER_BUILD_CONCURRENCY=8 python setup.py bdist_wheel - $ scp ./dist/cassandra_driver-3.14.0-cp27-cp27mu-linux_x86_64.whl user@host:/remote_dir - -Then, on the remote machine or machines, simply - -.. code-block:: bash - - $ pip install /remote_dir/cassandra_driver-3.14.0-cp27-cp27mu-linux_x86_64.whl - -Note that the wheel created this way is a `platform wheel -`_ -and as such will not work across platforms or architectures. - OSX Installation Error ^^^^^^^^^^^^^^^^^^^^^^ If you're installing on OSX and have XCode 5.1 installed, you may see an error like this:: clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] To fix this, re-run the installation with an extra compilation flag: .. code-block:: bash ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install cassandra-driver .. _windows_build: Windows Installation Notes -------------------------- Installing the driver with extensions in Windows sometimes presents some challenges. A few notes about common hang-ups: Setup requires a compiler. When using Python 2, this is as simple as installing `this package `_ (this link is also emitted during install if setuptools is unable to find the resources it needs). Depending on your system settings, this package may install as a user-specific application. Make sure to install for everyone, or at least as the user that will be building the Python environment. It is also possible to run the build with your compiler of choice. Just make sure to have your environment setup with the proper paths. Make sure the compiler target architecture matches the bitness of your Python runtime. Perhaps the easiest way to do this is to run the build/install from a Visual Studio Command Prompt (a shortcut installed with Visual Studio that sources the appropriate environment and presents a shell). Manual Installation ------------------- You can always install the driver directly from a source checkout or tarball. When installing manually, ensure the python dependencies are already installed. You can find the list of dependencies in `requirements.txt `_. Once the dependencies are installed, simply run:: python setup.py install -Verifying your Installation ---------------------------- -To check if the installation was successful, you can run:: - - python -c 'import cassandra; print cassandra.__version__' - -It should print something like "2.7.0". - -(*Optional*) Compression Support --------------------------------- -Compression can optionally be used for communication between the driver and -Cassandra. There are currently two supported compression algorithms: -snappy (in Cassandra 1.2+) and LZ4 (only in Cassandra 2.0+). If either is -available for the driver and Cassandra also supports it, it will -be used automatically. - -For lz4 support:: - - pip install lz4 - -For snappy support:: - - pip install python-snappy - -(If using a Debian Linux derivative such as Ubuntu, it may be easier to -just run ``apt-get install python-snappy``.) - -(*Optional*) Metrics Support ----------------------------- -The driver has built-in support for capturing :attr:`.Cluster.metrics` about -the queries you run. However, the ``scales`` library is required to -support this:: - - pip install scales - (*Optional*) Non-python Dependencies ------------------------------------ The driver has several **optional** features that have non-Python dependencies. C Extensions ^^^^^^^^^^^^ By default, a number of extensions are compiled, providing faster hashing for token-aware routing with the ``Murmur3Partitioner``, `libev `_ event loop integration, and Cython optimized extensions. When installing manually through setup.py, you can disable both with the ``--no-extensions`` option, or selectively disable them with with ``--no-murmur3``, ``--no-libev``, or ``--no-cython``. To compile the extensions, ensure that GCC and the Python headers are available. On Ubuntu and Debian, this can be accomplished by running:: $ sudo apt-get install gcc python-dev On RedHat and RedHat-based systems like CentOS and Fedora:: $ sudo yum install gcc python-devel On OS X, homebrew installations of Python should provide the necessary headers. See :ref:`windows_build` for notes on configuring the build environment on Windows. .. _cython-extensions: Cython-based Extensions ~~~~~~~~~~~~~~~~~~~~~~~ By default, this package uses `Cython `_ to optimize core modules and build custom extensions. This is not a hard requirement, but is engaged by default to build extensions offering better performance than the pure Python implementation. This is a costly build phase, especially in clean environments where the Cython compiler must be built This build phase can be avoided using the build switch, or an environment variable:: python setup.py install --no-cython Alternatively, an environment variable can be used to switch this option regardless of context:: CASS_DRIVER_NO_CYTHON=1 - or, to disable all extensions: CASS_DRIVER_NO_EXTENSIONS=1 This method is required when using pip, which provides no other way of injecting user options in a single command:: CASS_DRIVER_NO_CYTHON=1 pip install cassandra-driver CASS_DRIVER_NO_CYTHON=1 sudo -E pip install ~/python-driver The environment variable is the preferred option because it spans all invocations of setup.py, and will prevent Cython from being materialized as a setup requirement. If your sudo configuration does not allow SETENV, you must push the option flag down via pip. However, pip applies these options to all dependencies (which break on the custom flag). Therefore, you must first install dependencies, then use install-option:: sudo pip install six futures sudo pip install --install-option="--no-cython" libev support ^^^^^^^^^^^^^ The driver currently uses Python's ``asyncore`` module for its default event loop. For better performance, ``libev`` is also supported through a C extension. If you're on Linux, you should be able to install libev through a package manager. For example, on Debian/Ubuntu:: $ sudo apt-get install libev4 libev-dev On RHEL/CentOS/Fedora:: $ sudo yum install libev libev-devel If you're on Mac OS X, you should be able to install libev through `Homebrew `_. For example, on Mac OS X:: $ brew install libev The libev extension is not built for Windows (the build process is complex, and the Windows implementation uses select anyway). If successful, you should be able to build and install the extension (just using ``setup.py build`` or ``setup.py install``) and then use the libev event loop by doing the following: .. code-block:: python >>> from cassandra.io.libevreactor import LibevConnection >>> from cassandra.cluster import Cluster >>> cluster = Cluster() >>> cluster.connection_class = LibevConnection >>> session = cluster.connect() (*Optional*) Configuring SSL ----------------------------- Andrew Mussey has published a thorough guide on `Using SSL with the DataStax Python driver `_. diff --git a/docs/query_paging.rst b/docs/query_paging.rst index 0b97de4..23ee2c1 100644 --- a/docs/query_paging.rst +++ b/docs/query_paging.rst @@ -1,95 +1,95 @@ .. _query-paging: Paging Large Queries ==================== Cassandra 2.0+ offers support for automatic query paging. Starting with version 2.0 of the driver, if :attr:`~.Cluster.protocol_version` is greater than :const:`2` (it is by default), queries returning large result sets will be automatically paged. Controlling the Page Size ------------------------- By default, :attr:`.Session.default_fetch_size` controls how many rows will be fetched per page. This can be overridden per-query by setting :attr:`~.fetch_size` on a :class:`~.Statement`. By default, each page will contain at most 5000 rows. Handling Paged Results ---------------------- Whenever the number of result rows for are query exceed the page size, an instance of :class:`~.PagedResult` will be returned instead of a normal list. This class implements the iterator interface, so you can treat it like a normal iterator over rows:: from cassandra.query import SimpleStatement query = "SELECT * FROM users" # users contains 100 rows statement = SimpleStatement(query, fetch_size=10) for user_row in session.execute(statement): process_user(user_row) Whenever there are no more rows in the current page, the next page will be fetched transparently. However, note that it *is* possible for an :class:`Exception` to be raised while fetching the next page, just like you might see on a normal call to ``session.execute()``. If you use :meth:`.Session.execute_async()` along with, :meth:`.ResponseFuture.result()`, the first page will be fetched before :meth:`~.ResponseFuture.result()` returns, but latter pages will be transparently fetched synchronously while iterating the result. Handling Paged Results with Callbacks ------------------------------------- If callbacks are attached to a query that returns a paged result, the callback will be called once per page with a normal list of rows. Use :attr:`.ResponseFuture.has_more_pages` and :meth:`.ResponseFuture.start_fetching_next_page()` to continue fetching pages. For example:: class PagedResultHandler(object): def __init__(self, future): self.error = None self.finished_event = Event() self.future = future self.future.add_callbacks( callback=self.handle_page, errback=self.handle_err) def handle_page(self, rows): for row in rows: process_row(row) if self.future.has_more_pages: self.future.start_fetching_next_page() else: self.finished_event.set() def handle_error(self, exc): self.error = exc self.finished_event.set() future = session.execute_async("SELECT * FROM users") handler = PagedResultHandler(future) handler.finished_event.wait() if handler.error: raise handler.error Resume Paged Results -------------------- You can resume the pagination when executing a new query by using the :attr:`.ResultSet.paging_state`. This can be useful if you want to provide some stateless pagination capabilities to your application (ie. via http). For example:: from cassandra.query import SimpleStatement query = "SELECT * FROM users" statement = SimpleStatement(query, fetch_size=10) results = session.execute(statement) # save the paging_state somewhere and return current results - session['paging_stage'] = results.paging_state + web_session['paging_state'] = results.paging_state # resume the pagination sometime later... statement = SimpleStatement(query, fetch_size=10) - ps = session['paging_state'] + ps = web_session['paging_state'] results = session.execute(statement, paging_state=ps) diff --git a/docs/security.rst b/docs/security.rst index 0353091..6dd2624 100644 --- a/docs/security.rst +++ b/docs/security.rst @@ -1,278 +1,421 @@ .. _security: Security ======== The two main security components you will use with the Python driver are Authentication and SSL. Authentication -------------- Versions 2.0 and higher of the driver support a SASL-based authentication mechanism when :attr:`~.Cluster.protocol_version` is set to 2 or higher. To use this authentication, set :attr:`~.Cluster.auth_provider` to an instance of a subclass of :class:`~cassandra.auth.AuthProvider`. When working with Cassandra's ``PasswordAuthenticator``, you can use the :class:`~cassandra.auth.PlainTextAuthProvider` class. For example, suppose Cassandra is setup with its default 'cassandra' user with a password of 'cassandra': .. code-block:: python from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider auth_provider = PlainTextAuthProvider(username='cassandra', password='cassandra') cluster = Cluster(auth_provider=auth_provider, protocol_version=2) Custom Authenticators ^^^^^^^^^^^^^^^^^^^^^ If you're using something other than Cassandra's ``PasswordAuthenticator``, :class:`~.SaslAuthProvider` is provided for generic SASL authentication mechanisms, utilizing the ``pure-sasl`` package. If these do not suit your needs, you may need to create your own subclasses of :class:`~.AuthProvider` and :class:`~.Authenticator`. You can use the Sasl classes as example implementations. Protocol v1 Authentication ^^^^^^^^^^^^^^^^^^^^^^^^^^ When working with Cassandra 1.2 (or a higher version with :attr:`~.Cluster.protocol_version` set to ``1``), you will not pass in an :class:`~.AuthProvider` instance. Instead, you should pass in a function that takes one argument, the IP address of a host, and returns a dict of credentials with a ``username`` and ``password`` key: .. code-block:: python from cassandra.cluster import Cluster def get_credentials(host_address): return {'username': 'joe', 'password': '1234'} cluster = Cluster(auth_provider=get_credentials, protocol_version=1) SSL --- SSL should be used when client encryption is enabled in Cassandra. To give you as much control as possible over your SSL configuration, our SSL API takes a user-created `SSLContext` instance from the Python standard library. These docs will include some examples for how to achieve common configurations, -but the `ssl.SSLContext` documentation gives a more complete description of -what is possible. +but the `ssl.SSLContext `_ documentation +gives a more complete description of what is possible. To enable SSL with version 3.17.0 and higher, you will need to set :attr:`.Cluster.ssl_context` to a ``ssl.SSLContext`` instance to enable SSL. Optionally, you can also set :attr:`.Cluster.ssl_options` to a dict of options. These will be passed as kwargs to ``ssl.SSLContext.wrap_socket()`` when new sockets are created. +If you create your SSLContext using `ssl.create_default_context `_, +be aware that SSLContext.check_hostname is set to True by default, so the hostname validation will be done +by Python and not the driver. For this reason, we need to set the server_hostname at best effort, which is the +resolved ip address. If this validation needs to be done against the FQDN, consider enabling it using the ssl_options +as described in the following examples or implement your own :class:`~.connection.EndPoint` and +:class:`~.connection.EndPointFactory`. + + The following examples assume you have generated your Cassandra certificate and keystore files with these intructions: * `Setup SSL Cert `_ It might be also useful to learn about the different levels of identity verification to understand the examples: * `Using SSL in DSE drivers `_ +SSL with Twisted or Eventlet +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Twisted and Eventlet both use an alternative SSL implementation called pyOpenSSL, so if your `Cluster`'s connection class is +:class:`~cassandra.io.twistedreactor.TwistedConnection` or :class:`~cassandra.io.eventletreactor.EventletConnection`, you must pass a +`pyOpenSSL context `_ instead. +An example is provided in these docs, and more details can be found in the +`documentation `_. +pyOpenSSL is not installed by the driver and must be installed separately. + SSL Configuration Examples ^^^^^^^^^^^^^^^^^^^^^^^^^^ Here, we'll describe the server and driver configuration necessary to set up SSL to meet various goals, such as the client verifying the server and the server verifying the client. We'll also include Python code demonstrating how to use servers and drivers configured in these ways. -**No identity verification** +.. _ssl-no-identify-verification: + +No identity verification +++++++++++++++++++++++++ No identity verification at all. Note that this is not recommended for for production deployments. The Cassandra configuration:: client_encryption_options: enabled: true keystore: /path/to/127.0.0.1.keystore keystore_password: myStorePass require_client_auth: false The driver configuration: .. code-block:: python from cassandra.cluster import Cluster, Session - from ssl import SSLContext, PROTOCOL_TLSv1 + from ssl import SSLContext, PROTOCOL_TLS - ssl_context = SSLContext(PROTOCOL_TLSv1) + ssl_context = SSLContext(PROTOCOL_TLS) cluster = Cluster(['127.0.0.1'], ssl_context=ssl_context) session = cluster.connect() -**Client verifies server** +.. _ssl-client-verifies-server: + +Client verifies server +++++++++++++++++++++++ Ensure the python driver verifies the identity of the server. The Cassandra configuration:: client_encryption_options: enabled: true keystore: /path/to/127.0.0.1.keystore keystore_password: myStorePass require_client_auth: false For the driver configuration, it's very important to set `ssl_context.verify_mode` to `CERT_REQUIRED`. Otherwise, the loaded verify certificate will have no effect: .. code-block:: python from cassandra.cluster import Cluster, Session - from ssl import SSLContext, PROTOCOL_TLSv1, CERT_REQUIRED + from ssl import SSLContext, PROTOCOL_TLS, CERT_REQUIRED - ssl_context = SSLContext(PROTOCOL_TLSv1) + ssl_context = SSLContext(PROTOCOL_TLS) ssl_context.load_verify_locations('/path/to/rootca.crt') ssl_context.verify_mode = CERT_REQUIRED cluster = Cluster(['127.0.0.1'], ssl_context=ssl_context) session = cluster.connect() Additionally, you can also force the driver to verify the `hostname` of the server by passing additional options to `ssl_context.wrap_socket` via the `ssl_options` kwarg: .. code-block:: python from cassandra.cluster import Cluster, Session - from ssl import SSLContext, PROTOCOL_TLSv1, CERT_REQUIRED + from ssl import SSLContext, PROTOCOL_TLS, CERT_REQUIRED - ssl_context = SSLContext(PROTOCOL_TLSv1) + ssl_context = SSLContext(PROTOCOL_TLS) ssl_context.load_verify_locations('/path/to/rootca.crt') ssl_context.verify_mode = CERT_REQUIRED ssl_context.check_hostname = True ssl_options = {'server_hostname': '127.0.0.1'} cluster = Cluster(['127.0.0.1'], ssl_context=ssl_context, ssl_options=ssl_options) session = cluster.connect() -**Server verifies client** +.. _ssl-server-verifies-client: + +Server verifies client +++++++++++++++++++++++ If Cassandra is configured to verify clients (``require_client_auth``), you need to generate SSL key and certificate files. The cassandra configuration:: client_encryption_options: enabled: true keystore: /path/to/127.0.0.1.keystore keystore_password: myStorePass require_client_auth: true truststore: /path/to/dse-truststore.jks truststore_password: myStorePass The Python ``ssl`` APIs require the certificate in PEM format. First, create a certificate conf file: .. code-block:: bash cat > gen_client_cert.conf <`_ for more details about ``SSLContext`` configuration. +**Server verifies client and client verifies server using Twisted and pyOpenSSL** + +.. code-block:: python + + from OpenSSL import SSL, crypto + from cassandra.cluster import Cluster + from cassandra.io.twistedreactor import TwistedConnection + + ssl_context = SSL.Context(SSL.TLSv1_2_METHOD) + ssl_context.set_verify(SSL.VERIFY_PEER, callback=lambda _1, _2, _3, _4, ok: ok) + ssl_context.use_certificate_file('/path/to/client.crt_signed') + ssl_context.use_privatekey_file('/path/to/client.key') + ssl_context.load_verify_locations('/path/to/rootca.crt') + + cluster = Cluster( + contact_points=['127.0.0.1'], + connection_class=TwistedConnection, + ssl_context=ssl_context, + ssl_options={'check_hostname': True} + ) + session = cluster.connect() + + +Connecting using Eventlet would look similar except instead of importing and using ``TwistedConnection``, you would +import and use ``EventletConnection``, including the appropriate monkey-patching. + Versions 3.16.0 and lower ^^^^^^^^^^^^^^^^^^^^^^^^^ To enable SSL you will need to set :attr:`.Cluster.ssl_options` to a dict of options. These will be passed as kwargs to ``ssl.wrap_socket()`` when new sockets are created. Note that this use of ssl_options will be deprecated in the next major release. By default, a ``ca_certs`` value should be supplied (the value should be a string pointing to the location of the CA certs file), and you probably -want to specify ``ssl_version`` as ``ssl.PROTOCOL_TLSv1`` to match +want to specify ``ssl_version`` as ``ssl.PROTOCOL_TLS`` to match Cassandra's default protocol. For example: .. code-block:: python from cassandra.cluster import Cluster - from ssl import PROTOCOL_TLSv1, CERT_REQUIRED + from ssl import PROTOCOL_TLS, CERT_REQUIRED ssl_opts = { 'ca_certs': '/path/to/my/ca.certs', - 'ssl_version': PROTOCOL_TLSv1, + 'ssl_version': PROTOCOL_TLS, 'cert_reqs': CERT_REQUIRED # Certificates are required and validated } cluster = Cluster(ssl_options=ssl_opts) This is only an example to show how to pass the ssl parameters. Consider reading the `python ssl documentation `_ for your configuration. For further reading, Andrew Mussey has published a thorough guide on `Using SSL with the DataStax Python driver `_. SSL with Twisted ++++++++++++++++ In case the twisted event loop is used pyOpenSSL must be installed or an exception will be risen. Also to set the ``ssl_version`` and ``cert_reqs`` in ``ssl_opts`` the appropriate constants from pyOpenSSL are expected. + +DSE Authentication +------------------ +When authenticating against DSE, the Cassandra driver provides two auth providers that work both with legacy kerberos and Cassandra authenticators, +as well as the new DSE Unified Authentication. This allows client to configure this auth provider independently, +and in advance of any server upgrade. These auth providers are configured in the same way as any previous implementation:: + + from cassandra.auth import DSEGSSAPIAuthProvider + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"]) + cluster = Cluster(auth_provider=auth_provider) + session = cluster.connect() + +Implementations are :attr:`.DSEPlainTextAuthProvider`, :class:`.DSEGSSAPIAuthProvider` and :class:`.SaslAuthProvider`. + +DSE Unified Authentication +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +With DSE (>=5.1), unified Authentication allows you to: + +* Proxy Login: Authenticate using a fixed set of authentication credentials but allow authorization of resources based another user id. +* Proxy Execute: Authenticate using a fixed set of authentication credentials but execute requests based on another user id. + +Proxy Login ++++++++++++ + +Proxy login allows you to authenticate with a user but act as another one. You need to ensure the authenticated user has the permission to use the authorization of resources of the other user. ie. this example will allow the `server` user to authenticate as usual but use the authorization of `user1`: + +.. code-block:: text + + GRANT PROXY.LOGIN on role user1 to server + +then you can do the proxy authentication.... + +.. code-block:: python + + from cassandra.cluster import Cluster + from cassandra.auth import SaslAuthProvider + + sasl_kwargs = { + "service": 'dse', + "mechanism":"PLAIN", + "username": 'server', + 'password': 'server', + 'authorization_id': 'user1' + } + + auth_provider = SaslAuthProvider(**sasl_kwargs) + c = Cluster(auth_provider=auth_provider) + s = c.connect() + s.execute(...) # all requests will be executed as 'user1' + +If you are using kerberos, you can use directly :class:`.DSEGSSAPIAuthProvider` and pass the authorization_id, like this: + +.. code-block:: python + + from cassandra.cluster import Cluster + from cassandra.auth import DSEGSSAPIAuthProvider + + # Ensure the kerberos ticket of the server user is set with the kinit utility. + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"], principal="server@DATASTAX.COM", + authorization_id='user1@DATASTAX.COM') + c = Cluster(auth_provider=auth_provider) + s = c.connect() + s.execute(...) # all requests will be executed as 'user1' + + +Proxy Execute ++++++++++++++ + +Proxy execute allows you to execute requests as another user than the authenticated one. You need to ensure the authenticated user has the permission to use the authorization of resources of the specified user. ie. this example will allow the `server` user to execute requests as `user1`: + +.. code-block:: text + + GRANT PROXY.EXECUTE on role user1 to server + +then you can do a proxy execute... + +.. code-block:: python + + from cassandra.cluster import Cluster + from cassandra.auth import DSEPlainTextAuthProvider, + + auth_provider = DSEPlainTextAuthProvider('server', 'server') + + c = Cluster(auth_provider=auth_provider) + s = c.connect() + s.execute('select * from k.t;', execute_as='user1') # the request will be executed as 'user1' + +Please see the `official documentation `_ for more details on the feature and configuration process. diff --git a/docs/upgrading.rst b/docs/upgrading.rst index 9ab8eb3..3a600e9 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -1,309 +1,388 @@ Upgrading ========= .. toctree:: :maxdepth: 1 +Upgrading from dse-driver +------------------------- + +Since 3.21.0, cassandra-driver fully supports DataStax products. dse-driver and +dse-graph users should now migrate to cassandra-driver to benefit from latest bug fixes +and new features. The upgrade to this new unified driver version is straightforward +with no major API changes. + +Installation +^^^^^^^^^^^^ + +Only the `cassandra-driver` package should be installed. `dse-driver` and `dse-graph` +are not required anymore:: + + pip install cassandra-driver + +If you need the Graph *Fluent* API (features provided by dse-graph):: + + pip install cassandra-driver[graph] + +See :doc:`installation` for more details. + +Import from the cassandra module +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +There is no `dse` module, so you should import from the `cassandra` module. You +need to change only the first module of your import statements, not the submodules. + +.. code-block:: python + + from dse.cluster import Cluster, EXEC_PROFILE_GRAPH_DEFAULT + from dse.auth import PlainTextAuthProvider + from dse.policies import WhiteListRoundRobinPolicy + + # becomes + + from cassandra.cluster import Cluster, EXEC_PROFILE_GRAPH_DEFAULT + from cassandra.auth import PlainTextAuthProvider + from cassandra.policies import WhiteListRoundRobinPolicy + +Also note that the cassandra.hosts module doesn't exist in cassandra-driver. This +module is named cassandra.pool. + +dse-graph +^^^^^^^^^ + +dse-graph features are now built-in in cassandra-driver. The only change you need +to do is your import statements: + +.. code-block:: python + + from dse_graph import .. + from dse_graph.query import .. + + # becomes + + from cassandra.datastax.graph.fluent import .. + from cassandra.datastax.graph.fluent.query import .. + +See :mod:`~.datastax.graph.fluent`. + +Session.execute and Session.execute_async API +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Although it is not common to use this API with positional arguments, it is +important to be aware that the `host` and `execute_as` parameters have had +their positional order swapped. This is only because `execute_as` was added +in dse-driver before `host`. + +See :meth:`.Session.execute`. + +Deprecations +^^^^^^^^^^^^ + +These changes are optional, but recommended: + +* Importing from `cassandra.graph` is deprecated. Consider importing from `cassandra.datastax.graph`. +* Use :class:`~.policies.DefaultLoadBalancingPolicy` instead of DSELoadBalancingPolicy. + Upgrading to 3.0 ---------------- Version 3.0 of the DataStax Python driver for Apache Cassandra adds support for Cassandra 3.0 while maintaining support for previously supported versions. In addition to substantial internal rework, there are several updates to the API that integrators will need to consider: Default consistency is now ``LOCAL_ONE`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Previous value was ``ONE``. The new value is introduced to mesh with the default DC-aware load balancing policy and to match other drivers. Execution API Updates ^^^^^^^^^^^^^^^^^^^^^ Result return normalization ~~~~~~~~~~~~~~~~~~~~~~~~~~~ `PYTHON-368 `_ Previously results would be returned as a ``list`` of rows for result rows up to ``fetch_size``, and ``PagedResult`` afterward. This could break application code that assumed one type and got another. Now, all results are returned as an iterable :class:`~.ResultSet`. The preferred way to consume results of unknown size is to iterate through them, letting automatic paging occur as they are consumed. .. code-block:: python results = session.execute("SELECT * FROM system.local") for row in results: process(row) If the expected size of the results is known, it is still possible to materialize a list using the iterator: .. code-block:: python results = session.execute("SELECT * FROM system.local") row_list = list(results) -For backward compatability, :class:`~.ResultSet` supports indexing. When +For backward compatibility, :class:`~.ResultSet` supports indexing. When accessed at an index, a `~.ResultSet` object will materialize all its pages: .. code-block:: python results = session.execute("SELECT * FROM system.local") first_result = results[0] # materializes results, fetching all pages This can send requests and load (possibly large) results into memory, so `~.ResultSet` will log a warning on implicit materialization. Trace information is not attached to executed Statements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ `PYTHON-318 `_ Previously trace data was attached to Statements if tracing was enabled. This could lead to confusion if the same statement was used for multiple executions. Now, trace data is associated with the ``ResponseFuture`` and ``ResultSet`` returned for each query: :meth:`.ResponseFuture.get_query_trace()` :meth:`.ResponseFuture.get_all_query_traces()` :meth:`.ResultSet.get_query_trace()` :meth:`.ResultSet.get_all_query_traces()` Binding named parameters now ignores extra names ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ `PYTHON-178 `_ Previously, :meth:`.BoundStatement.bind()` would raise if a mapping was passed with extra names not found in the prepared statement. Behavior in 3.0+ is to ignore extra names. blist removed as soft dependency ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `PYTHON-385 `_ Previously the driver had a soft dependency on ``blist sortedset``, using that where available and using an internal fallback where possible. Now, the driver never chooses the ``blist`` variant, instead returning the internal :class:`.util.SortedSet` for all ``set`` results. The class implements all standard set operations, so no integration code should need to change unless it explicitly checks for ``sortedset`` type. Metadata API Updates ^^^^^^^^^^^^^^^^^^^^ `PYTHON-276 `_, `PYTHON-408 `_, `PYTHON-400 `_, `PYTHON-422 `_ Cassandra 3.0 brought a substantial overhaul to the internal schema metadata representation. This version of the driver supports that metadata in addition to the legacy version. Doing so also brought some changes to the metadata model. The present API is documented: :any:`cassandra.metadata`. Changes highlighted below: * All types are now exposed as CQL types instead of types derived from the internal server implementation * Some metadata attributes have changed names to match current nomenclature (for example, :attr:`.Index.kind` in place of ``Index.type``). * Some metadata attributes removed * ``TableMetadata.keyspace`` reference replaced with :attr:`.TableMetadata.keyspace_name` * ``ColumnMetadata.index`` is removed table- and keyspace-level mappings are still maintained Several deprecated features are removed ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `PYTHON-292 `_ * ``ResponseFuture.result`` timeout parameter is removed, use ``Session.execute`` timeout instead (`031ebb0 `_) * ``Cluster.refresh_schema`` removed, use ``Cluster.refresh_*_metadata`` instead (`419fcdf `_) * ``Cluster.submit_schema_refresh`` removed (`574266d `_) * ``cqltypes`` time/date functions removed, use ``util`` entry points instead (`bb984ee `_) * ``decoder`` module removed (`e16a073 `_) * ``TableMetadata.keyspace`` attribute replaced with ``keyspace_name`` (`cc94073 `_) * ``cqlengine.columns.TimeUUID.from_datetime`` removed, use ``util`` variant instead (`96489cc `_) * ``cqlengine.columns.Float(double_precision)`` parameter removed, use ``columns.Double`` instead (`a2d3a98 `_) * ``cqlengine`` keyspace management functions are removed in favor of the strategy-specific entry points (`4bd5909 `_) * ``cqlengine.Model.__polymorphic_*__`` attributes removed, use ``__discriminator*`` attributes instead (`9d98c8e `_) * ``cqlengine.statements`` will no longer warn about list list prepend behavior (`79efe97 `_) Upgrading to 2.1 from 2.0 ------------------------- Version 2.1 of the DataStax Python driver for Apache Cassandra adds support for Cassandra 2.1 and version 3 of the native protocol. Cassandra 1.2, 2.0, and 2.1 are all supported. However, 1.2 only supports protocol version 1, and 2.0 only supports versions 1 and 2, so some features may not be available. Using the v3 Native Protocol ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ By default, the driver will attempt to use version 2 of the native protocol. To use version 3, you must explicitly set the :attr:`~.Cluster.protocol_version`: .. code-block:: python from cassandra.cluster import Cluster cluster = Cluster(protocol_version=3) Note that protocol version 3 is only supported by Cassandra 2.1+. In future releases, the driver may default to using protocol version 3. Working with User-Defined Types ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Cassandra 2.1 introduced the ability to define new types:: USE KEYSPACE mykeyspace; CREATE TYPE address (street text, city text, zip int); The driver generally expects you to use instances of a specific class to represent column values of this type. You can let the driver know what class to use with :meth:`.Cluster.register_user_type`: .. code-block:: python cluster = Cluster() class Address(object): def __init__(self, street, city, zipcode): self.street = street self.city = text self.zipcode = zipcode cluster.register_user_type('mykeyspace', 'address', Address) When inserting data for ``address`` columns, you should pass in instances of ``Address``. When querying data, ``address`` column values will be instances of ``Address``. If no class is registered for a user-defined type, query results will use a ``namedtuple`` class and data may only be inserted though prepared statements. See :ref:`udts` for more details. Customizing Encoders for Non-prepared Statements ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Starting with version 2.1 of the driver, it is possible to customize how Python types are converted to CQL literals when working with non-prepared statements. This is done on a per-:class:`~.Session` basis through :attr:`.Session.encoder`: .. code-block:: python cluster = Cluster() session = cluster.connect() session.encoder.mapping[tuple] = session.encoder.cql_encode_tuple See :ref:`type-conversions` for the table of default CQL literal conversions. Using Client-Side Protocol-Level Timestamps ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ With version 3 of the native protocol, timestamps may be supplied by the client at the protocol level. (Normally, if they are not specified within the CQL query itself, a timestamp is generated server-side.) When :attr:`~.Cluster.protocol_version` is set to 3 or higher, the driver will automatically use client-side timestamps with microsecond precision unless :attr:`.Session.use_client_timestamp` is changed to :const:`False`. If a timestamp is specified within the CQL query, it will override the timestamp generated by the driver. Upgrading to 2.0 from 1.x ------------------------- Version 2.0 of the DataStax Python driver for Apache Cassandra includes some notable improvements over version 1.x. This version of the driver supports Cassandra 1.2, 2.0, and 2.1. However, not all features may be used with Cassandra 1.2, and some new features in 2.1 are not yet supported. Using the v2 Native Protocol ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ By default, the driver will attempt to use version 2 of Cassandra's native protocol. You can explicitly set the protocol version to 2, though: .. code-block:: python from cassandra.cluster import Cluster cluster = Cluster(protocol_version=2) When working with Cassandra 1.2, you will need to explicitly set the :attr:`~.Cluster.protocol_version` to 1: .. code-block:: python from cassandra.cluster import Cluster cluster = Cluster(protocol_version=1) Automatic Query Paging ^^^^^^^^^^^^^^^^^^^^^^ Version 2 of the native protocol adds support for automatic query paging, which can make dealing with large result sets much simpler. See :ref:`query-paging` for full details. Protocol-Level Batch Statements ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ With version 1 of the native protocol, batching of statements required using a `BATCH cql query `_. With version 2 of the native protocol, you can now batch statements at the protocol level. This allows you to use many different prepared statements within a single batch. See :class:`~.query.BatchStatement` for details and usage examples. SASL-based Authentication ^^^^^^^^^^^^^^^^^^^^^^^^^ Also new in version 2 of the native protocol is SASL-based authentication. See the section on :ref:`security` for details and examples. Lightweight Transactions ^^^^^^^^^^^^^^^^^^^^^^^^ `Lightweight transactions `_ are another new feature. To use lightweight transactions, add ``IF`` clauses to your CQL queries and set the :attr:`~.Statement.serial_consistency_level` on your statements. Calling Cluster.shutdown() ^^^^^^^^^^^^^^^^^^^^^^^^^^ In order to fix some issues around garbage collection and unclean interpreter shutdowns, version 2.0 of the driver requires you to call :meth:`.Cluster.shutdown()` on your :class:`~.Cluster` objects when you are through with them. This helps to guarantee a clean shutdown. Deprecations ^^^^^^^^^^^^ The following functions have moved from ``cassandra.decoder`` to ``cassandra.query``. The original functions have been left in place with a :exc:`DeprecationWarning` for now: * :attr:`cassandra.decoder.tuple_factory` has moved to :attr:`cassandra.query.tuple_factory` * :attr:`cassandra.decoder.named_tuple_factory` has moved to :attr:`cassandra.query.named_tuple_factory` * :attr:`cassandra.decoder.dict_factory` has moved to :attr:`cassandra.query.dict_factory` * :attr:`cassandra.decoder.ordered_dict_factory` has moved to :attr:`cassandra.query.ordered_dict_factory` Dependency Changes ^^^^^^^^^^^^^^^^^^ The following dependencies have officially been made optional: * ``scales`` * ``blist`` And one new dependency has been added (to enable Python 3 support): * ``six`` diff --git a/docs/user_defined_types.rst b/docs/user_defined_types.rst index fd95b09..32c03e3 100644 --- a/docs/user_defined_types.rst +++ b/docs/user_defined_types.rst @@ -1,92 +1,118 @@ .. _udts: User Defined Types ================== Cassandra 2.1 introduced user-defined types (UDTs). You can create a new type through ``CREATE TYPE`` statements in CQL:: CREATE TYPE address (street text, zip int); Version 2.1 of the Python driver adds support for user-defined types. -Registering a Class to Map to a UDT ------------------------------------ +Registering a UDT +----------------- You can tell the Python driver to return columns of a specific UDT as -instances of a class by registering them with your :class:`~.Cluster` +instances of a class or a dict by registering them with your :class:`~.Cluster` instance through :meth:`.Cluster.register_user_type`: + +Map a Class to a UDT +++++++++++++++++++++ + .. code-block:: python cluster = Cluster(protocol_version=3) session = cluster.connect() session.set_keyspace('mykeyspace') session.execute("CREATE TYPE address (street text, zipcode int)") session.execute("CREATE TABLE users (id int PRIMARY KEY, location frozen
)") # create a class to map to the "address" UDT class Address(object): def __init__(self, street, zipcode): self.street = street self.zipcode = zipcode cluster.register_user_type('mykeyspace', 'address', Address) # insert a row using an instance of Address session.execute("INSERT INTO users (id, location) VALUES (%s, %s)", (0, Address("123 Main St.", 78723))) # results will include Address instances results = session.execute("SELECT * FROM users") row = results[0] - print row.id, row.location.street, row.location.zipcode + print(row.id, row.location.street, row.location.zipcode) + +Map a dict to a UDT ++++++++++++++++++++ + +.. code-block:: python + + cluster = Cluster(protocol_version=3) + session = cluster.connect() + session.set_keyspace('mykeyspace') + session.execute("CREATE TYPE address (street text, zipcode int)") + session.execute("CREATE TABLE users (id int PRIMARY KEY, location frozen
)") + + cluster.register_user_type('mykeyspace', 'address', dict) + + # insert a row using a prepared statement and a tuple + insert_statement = session.prepare("INSERT INTO mykeyspace.users (id, location) VALUES (?, ?)") + session.execute(insert_statement, [0, ("123 Main St.", 78723)]) + + # results will include dict instances + results = session.execute("SELECT * FROM users") + row = results[0] + print(row.id, row.location['street'], row.location['zipcode']) Using UDTs Without Registering Them ----------------------------------- Although it is recommended to register your types with :meth:`.Cluster.register_user_type`, the driver gives you some options for working with unregistered UDTS. When you use prepared statements, the driver knows what data types to expect for each placeholder. This allows you to pass any object you want for a UDT, as long as it has attributes that match the field names for the UDT: .. code-block:: python cluster = Cluster(protocol_version=3) session = cluster.connect() session.set_keyspace('mykeyspace') session.execute("CREATE TYPE address (street text, zipcode int)") session.execute("CREATE TABLE users (id int PRIMARY KEY, location frozen
)") class Foo(object): def __init__(self, street, zipcode, otherstuff): self.street = street self.zipcode = zipcode self.otherstuff = otherstuff insert_statement = session.prepare("INSERT INTO users (id, location) VALUES (?, ?)") # since we're using a prepared statement, we don't *have* to register # a class to map to the UDT to insert data. The object just needs to have # "street" and "zipcode" attributes (which Foo does): session.execute(insert_statement, [0, Foo("123 Main St.", 78723, "some other stuff")]) # when we query data, UDT columns that don't have a class registered # will be returned as namedtuples: results = session.execute("SELECT * FROM users") first_row = results[0] address = first_row.location - print address # prints "Address(street='123 Main St.', zipcode=78723)" + print(address) # prints "Address(street='123 Main St.', zipcode=78723)" street = address.street zipcode = address.street As shown in the code example, inserting data for UDT columns without registering a class works fine for prepared statements. However, **you must register a class to insert UDT columns with unprepared statements**.\* You can still query UDT columns without registered classes using unprepared statements, they will simply return ``namedtuple`` instances (just like prepared statements do). \* this applies to *parameterized* unprepared statements, in which the driver will be formatting parameters -- not statements with interpolated UDT literals. diff --git a/requirements.txt b/requirements.txt index 25c0d62..f784fba 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ +geomet>=0.1,<0.3 six >=1.9 futures <=2.2.0 # Futures is not required for Python 3, but it works up through 2.2.0 (after which it introduced breaking syntax). # This is left here to make sure install -r works with any runtime. When installing via setup.py, futures is omitted # for Python 3, in favor of the standard library implementation. # see PYTHON-393 diff --git a/setup.py b/setup.py index 1259092..aaaa1b4 100644 --- a/setup.py +++ b/setup.py @@ -1,448 +1,462 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import os import sys import warnings if __name__ == '__main__' and sys.argv[1] == "gevent_nosetests": print("Running gevent tests") from gevent.monkey import patch_all patch_all() if __name__ == '__main__' and sys.argv[1] == "eventlet_nosetests": print("Running eventlet tests") from eventlet import monkey_patch monkey_patch() import ez_setup ez_setup.use_setuptools() from setuptools import setup from distutils.command.build_ext import build_ext from distutils.core import Extension from distutils.errors import (CCompilerError, DistutilsPlatformError, DistutilsExecError) from distutils.cmd import Command PY3 = sys.version_info[0] == 3 try: import subprocess has_subprocess = True except ImportError: has_subprocess = False from cassandra import __version__ long_description = "" with open("README.rst") as f: long_description = f.read() try: from nose.commands import nosetests except ImportError: gevent_nosetests = None eventlet_nosetests = None else: class gevent_nosetests(nosetests): description = "run nosetests with gevent monkey patching" class eventlet_nosetests(nosetests): description = "run nosetests with eventlet monkey patching" has_cqlengine = False if __name__ == '__main__' and sys.argv[1] == "install": try: import cqlengine has_cqlengine = True except ImportError: pass PROFILING = False class DocCommand(Command): description = "generate or test documentation" user_options = [("test", "t", "run doctests instead of generating documentation")] boolean_options = ["test"] def initialize_options(self): self.test = False def finalize_options(self): pass def run(self): if self.test: path = "docs/_build/doctest" mode = "doctest" else: path = "docs/_build/%s" % __version__ mode = "html" try: os.makedirs(path) except: pass if has_subprocess: # Prevent run with in-place extensions because cython-generated objects do not carry docstrings # http://docs.cython.org/src/userguide/special_methods.html#docstrings import glob for f in glob.glob("cassandra/*.so"): print("Removing '%s' to allow docs to run on pure python modules." %(f,)) os.unlink(f) # Build io extension to make import and docstrings work try: output = subprocess.check_output( ["python", "setup.py", "build_ext", "--inplace", "--force", "--no-murmur3", "--no-cython"], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: raise RuntimeError("Documentation step '%s' failed: %s: %s" % ("build_ext", exc, exc.output)) else: print(output) try: output = subprocess.check_output( ["sphinx-build", "-b", mode, "docs", path], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: raise RuntimeError("Documentation step '%s' failed: %s: %s" % (mode, exc, exc.output)) else: print(output) print("") print("Documentation step '%s' performed, results here:" % mode) print(" file://%s/%s/index.html" % (os.path.dirname(os.path.realpath(__file__)), path)) class BuildFailed(Exception): def __init__(self, ext): self.ext = ext murmur3_ext = Extension('cassandra.cmurmur3', sources=['cassandra/cmurmur3.c']) libev_ext = Extension('cassandra.io.libevwrapper', sources=['cassandra/io/libevwrapper.c'], include_dirs=['/usr/include/libev', '/usr/local/include', '/opt/local/include'], libraries=['ev'], library_dirs=['/usr/local/lib', '/opt/local/lib']) platform_unsupported_msg = \ """ =============================================================================== The optional C extensions are not supported on this platform. =============================================================================== """ arch_unsupported_msg = \ """ =============================================================================== The optional C extensions are not supported on big-endian systems. =============================================================================== """ pypy_unsupported_msg = \ """ ================================================================================= Some optional C extensions are not supported in PyPy. Only murmur3 will be built. ================================================================================= """ is_windows = os.name == 'nt' is_pypy = "PyPy" in sys.version if is_pypy: sys.stderr.write(pypy_unsupported_msg) is_supported_platform = sys.platform != "cli" and not sys.platform.startswith("java") is_supported_arch = sys.byteorder != "big" if not is_supported_platform: sys.stderr.write(platform_unsupported_msg) elif not is_supported_arch: sys.stderr.write(arch_unsupported_msg) try_extensions = "--no-extensions" not in sys.argv and is_supported_platform and is_supported_arch and not os.environ.get('CASS_DRIVER_NO_EXTENSIONS') try_murmur3 = try_extensions and "--no-murmur3" not in sys.argv try_libev = try_extensions and "--no-libev" not in sys.argv and not is_pypy and not is_windows try_cython = try_extensions and "--no-cython" not in sys.argv and not is_pypy and not os.environ.get('CASS_DRIVER_NO_CYTHON') try_cython &= 'egg_info' not in sys.argv # bypass setup_requires for pip egg_info calls, which will never have --install-option"--no-cython" coming fomr pip sys.argv = [a for a in sys.argv if a not in ("--no-murmur3", "--no-libev", "--no-cython", "--no-extensions")] build_concurrency = int(os.environ.get('CASS_DRIVER_BUILD_CONCURRENCY', '0')) class NoPatchExtension(Extension): # Older versions of setuptools.extension has a static flag which is set False before our # setup_requires lands Cython. It causes our *.pyx sources to be renamed to *.c in # the initializer. # The other workaround would be to manually generate sources, but that bypasses a lot # of the niceness cythonize embodies (setup build dir, conditional build, etc). # Newer setuptools does not have this problem because it checks for cython dynamically. # https://bitbucket.org/pypa/setuptools/commits/714c3144e08fd01a9f61d1c88411e76d2538b2e4 def __init__(self, *args, **kwargs): # bypass the patched init if possible if Extension.__bases__: base, = Extension.__bases__ base.__init__(self, *args, **kwargs) else: Extension.__init__(self, *args, **kwargs) class build_extensions(build_ext): error_message = """ =============================================================================== WARNING: could not compile %s. The C extensions are not required for the driver to run, but they add support for token-aware routing with the Murmur3Partitioner. On Windows, make sure Visual Studio or an SDK is installed, and your environment is configured to build for the appropriate architecture (matching your Python runtime). This is often a matter of using vcvarsall.bat from your install directory, or running from a command prompt in the Visual Studio Tools Start Menu. =============================================================================== """ if is_windows else """ =============================================================================== WARNING: could not compile %s. The C extensions are not required for the driver to run, but they add support for libev and token-aware routing with the Murmur3Partitioner. Linux users should ensure that GCC and the Python headers are available. On Ubuntu and Debian, this can be accomplished by running: $ sudo apt-get install build-essential python-dev On RedHat and RedHat-based systems like CentOS and Fedora: $ sudo yum install gcc python-devel On OSX, homebrew installations of Python should provide the necessary headers. libev Support ------------- For libev support, you will also need to install libev and its headers. On Debian/Ubuntu: $ sudo apt-get install libev4 libev-dev On RHEL/CentOS/Fedora: $ sudo yum install libev libev-devel On OSX, via homebrew: $ brew install libev =============================================================================== """ def run(self): try: self._setup_extensions() build_ext.run(self) except DistutilsPlatformError as exc: sys.stderr.write('%s\n' % str(exc)) warnings.warn(self.error_message % "C extensions.") def build_extensions(self): if build_concurrency > 1: self.check_extensions_list(self.extensions) import multiprocessing.pool multiprocessing.pool.ThreadPool(processes=build_concurrency).map(self.build_extension, self.extensions) else: build_ext.build_extensions(self) def build_extension(self, ext): try: build_ext.build_extension(self, ext) except (CCompilerError, DistutilsExecError, DistutilsPlatformError, IOError) as exc: sys.stderr.write('%s\n' % str(exc)) name = "The %s extension" % (ext.name,) warnings.warn(self.error_message % (name,)) def _setup_extensions(self): # We defer extension setup until this command to leveraage 'setup_requires' pulling in Cython before we # attempt to import anything self.extensions = [] if try_murmur3: self.extensions.append(murmur3_ext) if try_libev: self.extensions.append(libev_ext) if try_cython: try: from Cython.Build import cythonize cython_candidates = ['cluster', 'concurrent', 'connection', 'cqltypes', 'metadata', 'pool', 'protocol', 'query', 'util'] compile_args = [] if is_windows else ['-Wno-unused-function'] self.extensions.extend(cythonize( [Extension('cassandra.%s' % m, ['cassandra/%s.py' % m], extra_compile_args=compile_args) for m in cython_candidates], nthreads=build_concurrency, exclude_failures=True)) self.extensions.extend(cythonize(NoPatchExtension("*", ["cassandra/*.pyx"], extra_compile_args=compile_args), nthreads=build_concurrency)) except Exception: sys.stderr.write("Failed to cythonize one or more modules. These will not be compiled as extensions (optional).\n") def pre_build_check(): """ Try to verify build tools """ if os.environ.get('CASS_DRIVER_NO_PRE_BUILD_CHECK'): return True try: from distutils.ccompiler import new_compiler from distutils.sysconfig import customize_compiler from distutils.dist import Distribution # base build_ext just to emulate compiler option setup be = build_ext(Distribution()) be.initialize_options() be.finalize_options() # First, make sure we have a Python include directory have_python_include = any(os.path.isfile(os.path.join(p, 'Python.h')) for p in be.include_dirs) if not have_python_include: sys.stderr.write("Did not find 'Python.h' in %s.\n" % (be.include_dirs,)) return False compiler = new_compiler(compiler=be.compiler) customize_compiler(compiler) try: # We must be able to initialize the compiler if it has that method if hasattr(compiler, "initialize"): compiler.initialize() except: return False executables = [] if compiler.compiler_type in ('unix', 'cygwin'): executables = [compiler.executables[exe][0] for exe in ('compiler_so', 'linker_so')] elif compiler.compiler_type == 'nt': executables = [getattr(compiler, exe) for exe in ('cc', 'linker')] if executables: from distutils.spawn import find_executable for exe in executables: if not find_executable(exe): sys.stderr.write("Failed to find %s for compiler type %s.\n" % (exe, compiler.compiler_type)) return False except Exception as exc: sys.stderr.write('%s\n' % str(exc)) sys.stderr.write("Failed pre-build check. Attempting anyway.\n") # if we are unable to positively id the compiler type, or one of these assumptions fails, # just proceed as we would have without the check return True def run_setup(extensions): kw = {'cmdclass': {'doc': DocCommand}} if gevent_nosetests is not None: kw['cmdclass']['gevent_nosetests'] = gevent_nosetests if eventlet_nosetests is not None: kw['cmdclass']['eventlet_nosetests'] = eventlet_nosetests kw['cmdclass']['build_ext'] = build_extensions kw['ext_modules'] = [Extension('DUMMY', [])] # dummy extension makes sure build_ext is called for install if try_cython: # precheck compiler before adding to setup_requires # we don't actually negate try_cython because: # 1.) build_ext eats errors at compile time, letting the install complete while producing useful feedback # 2.) there could be a case where the python environment has cython installed but the system doesn't have build tools if pre_build_check(): cython_dep = 'Cython>=0.20,!=0.25,<0.30' user_specified_cython_version = os.environ.get('CASS_DRIVER_ALLOWED_CYTHON_VERSION') if user_specified_cython_version is not None: cython_dep = 'Cython==%s' % (user_specified_cython_version,) kw['setup_requires'] = [cython_dep] else: sys.stderr.write("Bypassing Cython setup requirement\n") - dependencies = ['six >=1.9'] + dependencies = ['six >=1.9', + 'geomet>=0.1,<0.3'] if not PY3: dependencies.append('futures') + _EXTRAS_REQUIRE = { + 'graph': ['gremlinpython==3.4.6'] + } + setup( name='cassandra-driver', version=__version__, - description='Python driver for Cassandra', + description=' DataStax Driver for Apache Cassandra', long_description=long_description, url='http://github.com/datastax/python-driver', - author='Tyler Hobbs', - author_email='tyler@datastax.com', - packages=['cassandra', 'cassandra.io', 'cassandra.cqlengine', 'cassandra.datastax', - 'cassandra.datastax.cloud'], - keywords='cassandra,cql,orm', + project_urls={ + 'Documentation': 'https://docs.datastax.com/en/developer/python-driver/latest/', + 'Source': 'https://github.com/datastax/python-driver/', + 'Issues': 'https://datastax-oss.atlassian.net/browse/PYTHON', + }, + author='DataStax', + packages=[ + 'cassandra', 'cassandra.io', 'cassandra.cqlengine', 'cassandra.graph', + 'cassandra.datastax', 'cassandra.datastax.insights', 'cassandra.datastax.graph', + 'cassandra.datastax.graph.fluent', 'cassandra.datastax.cloud' + ], + keywords='cassandra,cql,orm,dse,graph', include_package_data=True, install_requires=dependencies, + extras_require=_EXTRAS_REQUIRE, tests_require=['nose', 'mock>=2.0.0', 'PyYAML', 'pytz', 'sure'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Libraries :: Python Modules' ], **kw) + run_setup(None) if has_cqlengine: warnings.warn("\n#######\n'cqlengine' package is present on path: %s\n" "cqlengine is now an integrated sub-package of this driver.\n" "It is recommended to remove this package to reduce the chance for conflicting usage" % cqlengine.__file__) diff --git a/test-datastax-requirements.txt b/test-datastax-requirements.txt new file mode 100644 index 0000000..3a47b8d --- /dev/null +++ b/test-datastax-requirements.txt @@ -0,0 +1,3 @@ +-r test-requirements.txt +kerberos +gremlinpython==3.4.6 diff --git a/test-requirements.txt b/test-requirements.txt index 0eafa67..9e62bfd 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -1,17 +1,19 @@ -r requirements.txt scales nose -mock!=1.1.* -ccm>=2.0 +mock>1.1 +ccm>=2.1.2 unittest2 pytz sure pure-sasl -twisted; python_version >= '3.5' +twisted[tls]; python_version >= '3.5' twisted[tls]==19.2.1; python_version < '3.5' gevent>=1.0 eventlet cython>=0.20,<0.30 packaging +backports.ssl_match_hostname; python_version < '2.7.9' futurist; python_version >= '3.7' -asynctest; python_version > '3.4' +asynctest; python_version >= '3.5' +ipaddress; python_version < '3.3.0' diff --git a/tests/__init__.py b/tests/__init__.py index 6260583..cea5a87 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,116 +1,111 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa import logging import sys import socket import platform import os from concurrent.futures import ThreadPoolExecutor log = logging.getLogger() log.setLevel('DEBUG') # if nose didn't already attach a log handler, add one here if not log.handlers: handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s [%(module)s:%(lineno)s]: %(message)s')) log.addHandler(handler) def is_eventlet_monkey_patched(): if 'eventlet.patcher' not in sys.modules: return False import eventlet.patcher return eventlet.patcher.is_monkey_patched('socket') def is_gevent_monkey_patched(): if 'gevent.monkey' not in sys.modules: return False import gevent.socket return socket.socket is gevent.socket.socket -def is_gevent_time_monkey_patched(): - import gevent.monkey - return "time" in gevent.monkey.saved +def is_monkey_patched(): + return is_gevent_monkey_patched() or is_eventlet_monkey_patched() +MONKEY_PATCH_LOOP = bool(os.getenv('MONKEY_PATCH_LOOP', False)) +EVENT_LOOP_MANAGER = os.getenv('EVENT_LOOP_MANAGER', "libev") -def is_eventlet_time_monkey_patched(): - import eventlet - return eventlet.patcher.is_monkey_patched('time') +# If set to to true this will force the Cython tests to run regardless of whether they are installed +cython_env = os.getenv('VERIFY_CYTHON', "False") -def is_monkey_patched(): - return is_gevent_monkey_patched() or is_eventlet_monkey_patched() +VERIFY_CYTHON = False +if(cython_env == 'True'): + VERIFY_CYTHON = True thread_pool_executor_class = ThreadPoolExecutor -EVENT_LOOP_MANAGER = os.getenv('EVENT_LOOP_MANAGER', "libev") if "gevent" in EVENT_LOOP_MANAGER: import gevent.monkey gevent.monkey.patch_all() from cassandra.io.geventreactor import GeventConnection connection_class = GeventConnection elif "eventlet" in EVENT_LOOP_MANAGER: from eventlet import monkey_patch monkey_patch() from cassandra.io.eventletreactor import EventletConnection connection_class = EventletConnection try: from futurist import GreenThreadPoolExecutor thread_pool_executor_class = GreenThreadPoolExecutor except: # futurist is installed only with python >=3.7 pass elif "asyncore" in EVENT_LOOP_MANAGER: from cassandra.io.asyncorereactor import AsyncoreConnection connection_class = AsyncoreConnection elif "twisted" in EVENT_LOOP_MANAGER: from cassandra.io.twistedreactor import TwistedConnection connection_class = TwistedConnection elif "asyncio" in EVENT_LOOP_MANAGER: from cassandra.io.asyncioreactor import AsyncioConnection connection_class = AsyncioConnection else: try: from cassandra.io.libevreactor import LibevConnection connection_class = LibevConnection - except ImportError: + except ImportError as e: + log.debug('Could not import LibevConnection, ' + 'using connection_class=None; ' + 'failed with error:\n {}'.format( + repr(e) + )) connection_class = None -# If set to to true this will force the Cython tests to run regardless of whether they are installed -cython_env = os.getenv('VERIFY_CYTHON', "False") - - -VERIFY_CYTHON = False - -if(cython_env == 'True'): - VERIFY_CYTHON = True - - def is_windows(): return "Windows" in platform.system() notwindows = unittest.skipUnless(not is_windows(), "This test is not adequate for windows") notpypy = unittest.skipUnless(not platform.python_implementation() == 'PyPy', "This tests is not suitable for pypy") diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py index c087200..9d350af 100644 --- a/tests/integration/__init__.py +++ b/tests/integration/__init__.py @@ -1,835 +1,1005 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + import os from cassandra.cluster import Cluster from tests import connection_class, EVENT_LOOP_MANAGER Cluster.connection_class = connection_class try: import unittest2 as unittest except ImportError: import unittest # noqa + from packaging.version import Version import logging import socket import sys import time import traceback import platform from threading import Event from subprocess import call from itertools import groupby import six import shutil -from cassandra import OperationTimedOut, ReadTimeout, ReadFailure, WriteTimeout, WriteFailure, AlreadyExists, \ +from cassandra import OperationTimedOut, ReadTimeout, ReadFailure, WriteTimeout, WriteFailure, AlreadyExists,\ InvalidRequest -from cassandra.cluster import NoHostAvailable - from cassandra.protocol import ConfigurationException +from cassandra import ProtocolVersion try: from ccmlib.dse_cluster import DseCluster from ccmlib.cluster import Cluster as CCMCluster from ccmlib.cluster_factory import ClusterFactory as CCMClusterFactory from ccmlib import common except ImportError as e: CCMClusterFactory = None log = logging.getLogger(__name__) CLUSTER_NAME = 'test_cluster' SINGLE_NODE_CLUSTER_NAME = 'single_node' MULTIDC_CLUSTER_NAME = 'multidc_test_cluster' CCM_CLUSTER = None path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'ccm') if not os.path.exists(path): os.mkdir(path) cass_version = None cql_version = None def get_server_versions(): """ Probe system.local table to determine Cassandra and CQL version. Returns a tuple of (cassandra_version, cql_version). """ global cass_version, cql_version if cass_version is not None: return (cass_version, cql_version) - c = Cluster() + c = TestCluster() s = c.connect() row = s.execute('SELECT cql_version, release_version FROM system.local')[0] cass_version = _tuple_version(row.release_version) cql_version = _tuple_version(row.cql_version) c.shutdown() return (cass_version, cql_version) def _tuple_version(version_string): if '-' in version_string: version_string = version_string[:version_string.index('-')] return tuple([int(p) for p in version_string.split('.')]) def cmd_line_args_to_dict(env_var): cmd_args_env = os.environ.get(env_var, None) args = {} if cmd_args_env: cmd_args = cmd_args_env.strip().split(' ') while cmd_args: cmd_arg = cmd_args.pop(0) cmd_arg_value = True if cmd_arg.startswith('--') else cmd_args.pop(0) args[cmd_arg.lstrip('-')] = cmd_arg_value return args +def _get_cass_version_from_dse(dse_version): + if dse_version.startswith('4.6') or dse_version.startswith('4.5'): + raise Exception("Cassandra Version 2.0 not supported anymore") + elif dse_version.startswith('4.7') or dse_version.startswith('4.8'): + cass_ver = "2.1" + elif dse_version.startswith('5.0'): + cass_ver = "3.0" + elif dse_version.startswith('5.1'): + # TODO: refactor this method to use packaging.Version everywhere + if Version(dse_version) >= Version('5.1.2'): + cass_ver = "3.11" + else: + cass_ver = "3.10" + elif dse_version.startswith('6.0'): + if dse_version == '6.0.0': + cass_ver = '4.0.0.2284' + elif dse_version == '6.0.1': + cass_ver = '4.0.0.2349' + else: + cass_ver = '4.0.0.' + ''.join(dse_version.split('.')) + elif Version(dse_version) >= Version('6.7'): + if dse_version == '6.7.0': + cass_ver = "4.0.0.67" + else: + cass_ver = '4.0.0.' + ''.join(dse_version.split('.')) + elif dse_version.startswith('6.8'): + if dse_version == '6.8.0': + cass_ver = "4.0.0.68" + else: + cass_ver = '4.0.0.' + ''.join(dse_version.split('.')) + else: + log.error("Unknown dse version found {0}, defaulting to 2.1".format(dse_version)) + cass_ver = "2.1" + return Version(cass_ver) + + def _get_dse_version_from_cass(cass_version): if cass_version.startswith('2.1'): dse_ver = "4.8.15" elif cass_version.startswith('3.0'): dse_ver = "5.0.12" elif cass_version.startswith('3.10') or cass_version.startswith('3.11'): dse_ver = "5.1.7" elif cass_version.startswith('4.0'): dse_ver = "6.0" else: log.error("Unknown cassandra version found {0}, defaulting to 2.1".format(cass_version)) dse_ver = "2.1" return dse_ver USE_CASS_EXTERNAL = bool(os.getenv('USE_CASS_EXTERNAL', False)) KEEP_TEST_CLUSTER = bool(os.getenv('KEEP_TEST_CLUSTER', False)) SIMULACRON_JAR = os.getenv('SIMULACRON_JAR', None) CLOUD_PROXY_PATH = os.getenv('CLOUD_PROXY_PATH', None) -CASSANDRA_IP = os.getenv('CASSANDRA_IP', '127.0.0.1') -CASSANDRA_DIR = os.getenv('CASSANDRA_DIR', None) - -default_cassandra_version = '3.11.4' -cv_string = os.getenv('CASSANDRA_VERSION', default_cassandra_version) -mcv_string = os.getenv('MAPPED_CASSANDRA_VERSION', None) -try: - cassandra_version = Version(cv_string) # env var is set to test-dse -except: - # fallback to MAPPED_CASSANDRA_VERSION - cassandra_version = Version(mcv_string) -CASSANDRA_VERSION = Version(mcv_string) if mcv_string else cassandra_version -CCM_VERSION = cassandra_version if mcv_string else CASSANDRA_VERSION +# Supported Clusters: Cassandra, DDAC, DSE +DSE_VERSION = None +if os.getenv('DSE_VERSION', None): # we are testing against DSE + DSE_VERSION = Version(os.getenv('DSE_VERSION', None)) + DSE_CRED = os.getenv('DSE_CREDS', None) + CASSANDRA_VERSION = _get_cass_version_from_dse(DSE_VERSION.base_version) + CCM_VERSION = DSE_VERSION.base_version +else: # we are testing against Cassandra or DDAC + cv_string = os.getenv('CASSANDRA_VERSION', None) + mcv_string = os.getenv('MAPPED_CASSANDRA_VERSION', None) + try: + cassandra_version = Version(cv_string) # env var is set to test-dse for DDAC + except: + # fallback to MAPPED_CASSANDRA_VERSION + cassandra_version = Version(mcv_string) -default_dse_version = _get_dse_version_from_cass(CASSANDRA_VERSION.base_version) + CASSANDRA_VERSION = Version(mcv_string) if mcv_string else cassandra_version + CCM_VERSION = mcv_string if mcv_string else cv_string -DSE_VERSION = Version(os.getenv('DSE_VERSION', default_dse_version)) +CASSANDRA_IP = os.getenv('CLUSTER_IP', '127.0.0.1') +CASSANDRA_DIR = os.getenv('CASSANDRA_DIR', None) CCM_KWARGS = {} -if CASSANDRA_DIR: +if DSE_VERSION: + log.info('Using DSE version: %s', DSE_VERSION) + if not CASSANDRA_DIR: + CCM_KWARGS['version'] = DSE_VERSION + if DSE_CRED: + log.info("Using DSE credentials file located at {0}".format(DSE_CRED)) + CCM_KWARGS['dse_credentials_file'] = DSE_CRED +elif CASSANDRA_DIR: log.info("Using Cassandra dir: %s", CASSANDRA_DIR) CCM_KWARGS['install_dir'] = CASSANDRA_DIR - else: - log.info('Using Cassandra version: %s', CASSANDRA_VERSION) - log.info('Using CCM version: %s', CCM_VERSION) + log.info('Using Cassandra version: %s', CCM_VERSION) CCM_KWARGS['version'] = CCM_VERSION -#This changes the default contact_point parameter in Cluster -def set_default_cass_ip(): - if CASSANDRA_IP.startswith("127.0.0."): - return - defaults = list(Cluster.__init__.__defaults__) - defaults = [[CASSANDRA_IP]] + defaults[1:] - try: - Cluster.__init__.__defaults__ = tuple(defaults) - except: - Cluster.__init__.__func__.__defaults__ = tuple(defaults) - -def set_default_beta_flag_true(): - defaults = list(Cluster.__init__.__defaults__) - defaults = (defaults[:28] + [True] + defaults[29:]) - try: - Cluster.__init__.__defaults__ = tuple(defaults) - except: - Cluster.__init__.__func__.__defaults__ = tuple(defaults) +ALLOW_BETA_PROTOCOL = False def get_default_protocol(): - if CASSANDRA_VERSION >= Version('4.0'): - set_default_beta_flag_true() - return 5 - elif CASSANDRA_VERSION >= Version('2.2'): + if CASSANDRA_VERSION >= Version('4.0-a'): + if DSE_VERSION: + return ProtocolVersion.DSE_V2 + else: + return ProtocolVersion.V5 + if CASSANDRA_VERSION >= Version('3.10'): + if DSE_VERSION: + return ProtocolVersion.DSE_V1 + else: + return 4 + if CASSANDRA_VERSION >= Version('2.2'): return 4 elif CASSANDRA_VERSION >= Version('2.1'): return 3 elif CASSANDRA_VERSION >= Version('2.0'): return 2 else: - return 1 + raise Exception("Running tests with an unsupported Cassandra version: {0}".format(CASSANDRA_VERSION)) def get_supported_protocol_versions(): """ 1.2 -> 1 2.0 -> 2, 1 2.1 -> 3, 2, 1 2.2 -> 4, 3, 2, 1 3.X -> 4, 3 - 3.10 -> 5(beta),4,3 + 3.10(C*) -> 5(beta),4,3 + 3.10(DSE) -> DSE_V1,4,3 + 4.0(C*) -> 6(beta),5,4,3 + 4.0(DSE) -> DSE_v2, DSE_V1,4,3 ` """ - if CASSANDRA_VERSION >= Version('4.0'): - return (3, 4, 5) + if CASSANDRA_VERSION >= Version('4.0-beta5'): + if not DSE_VERSION: + return (3, 4, 5, 6) + if CASSANDRA_VERSION >= Version('4.0-a'): + if DSE_VERSION: + return (3, 4, ProtocolVersion.DSE_V1, ProtocolVersion.DSE_V2) + else: + return (3, 4, 5) elif CASSANDRA_VERSION >= Version('3.10'): - return (3, 4) + if DSE_VERSION: + return (3, 4, ProtocolVersion.DSE_V1) + else: + return (3, 4) elif CASSANDRA_VERSION >= Version('3.0'): return (3, 4) elif CASSANDRA_VERSION >= Version('2.2'): - return (1, 2, 3, 4) + return (1,2, 3, 4) elif CASSANDRA_VERSION >= Version('2.1'): return (1, 2, 3) elif CASSANDRA_VERSION >= Version('2.0'): return (1, 2) else: - return (1, ) + return (1,) def get_unsupported_lower_protocol(): """ This is used to determine the lowest protocol version that is NOT supported by the version of C* running """ - if CASSANDRA_VERSION >= Version('3.0'): return 2 else: return None def get_unsupported_upper_protocol(): """ This is used to determine the highest protocol version that is NOT supported by the version of C* running """ + if CASSANDRA_VERSION >= Version('4.0-a'): + if DSE_VERSION: + return None + else: + return ProtocolVersion.DSE_V1 + if CASSANDRA_VERSION >= Version('3.10'): + if DSE_VERSION: + return ProtocolVersion.DSE_V2 + else: + return 5 if CASSANDRA_VERSION >= Version('2.2'): - return None - if CASSANDRA_VERSION >= Version('2.1'): + return 5 + elif CASSANDRA_VERSION >= Version('2.1'): return 4 elif CASSANDRA_VERSION >= Version('2.0'): return 3 else: - return None + return 2 default_protocol_version = get_default_protocol() PROTOCOL_VERSION = int(os.getenv('PROTOCOL_VERSION', default_protocol_version)) def local_decorator_creator(): if USE_CASS_EXTERNAL or not CASSANDRA_IP.startswith("127.0.0."): return unittest.skip('Tests only runs against local C*') def _id_and_mark(f): f.local = True return f return _id_and_mark local = local_decorator_creator() notprotocolv1 = unittest.skipUnless(PROTOCOL_VERSION > 1, 'Protocol v1 not supported') lessthenprotocolv4 = unittest.skipUnless(PROTOCOL_VERSION < 4, 'Protocol versions 4 or greater not supported') greaterthanprotocolv3 = unittest.skipUnless(PROTOCOL_VERSION >= 4, 'Protocol versions less than 4 are not supported') -protocolv5 = unittest.skipUnless(5 in get_supported_protocol_versions(), 'Protocol versions less than 5 are not supported') - +protocolv6 = unittest.skipUnless(6 in get_supported_protocol_versions(), 'Protocol versions less than 6 are not supported') greaterthancass20 = unittest.skipUnless(CASSANDRA_VERSION >= Version('2.1'), 'Cassandra version 2.1 or greater required') greaterthancass21 = unittest.skipUnless(CASSANDRA_VERSION >= Version('2.2'), 'Cassandra version 2.2 or greater required') greaterthanorequalcass30 = unittest.skipUnless(CASSANDRA_VERSION >= Version('3.0'), 'Cassandra version 3.0 or greater required') +greaterthanorequalcass31 = unittest.skipUnless(CASSANDRA_VERSION >= Version('3.1'), 'Cassandra version 3.1 or greater required') greaterthanorequalcass36 = unittest.skipUnless(CASSANDRA_VERSION >= Version('3.6'), 'Cassandra version 3.6 or greater required') greaterthanorequalcass3_10 = unittest.skipUnless(CASSANDRA_VERSION >= Version('3.10'), 'Cassandra version 3.10 or greater required') -greaterthanorequalcass3_11 = unittest.skipUnless(CASSANDRA_VERSION >= Version('3.11'), 'Cassandra version 3.10 or greater required') -greaterthanorequalcass40 = unittest.skipUnless(CASSANDRA_VERSION >= Version('4.0'), 'Cassandra version 4.0 or greater required') -lessthanorequalcass40 = unittest.skipIf(CASSANDRA_VERSION >= Version('4.0'), 'Cassandra version 4.0 or greater required') +greaterthanorequalcass3_11 = unittest.skipUnless(CASSANDRA_VERSION >= Version('3.11'), 'Cassandra version 3.11 or greater required') +greaterthanorequalcass40 = unittest.skipUnless(CASSANDRA_VERSION >= Version('4.0-a'), 'Cassandra version 4.0 or greater required') +lessthanorequalcass40 = unittest.skipUnless(CASSANDRA_VERSION <= Version('4.0-a'), 'Cassandra version less or equal to 4.0 required') +lessthancass40 = unittest.skipUnless(CASSANDRA_VERSION < Version('4.0-a'), 'Cassandra version less than 4.0 required') lessthancass30 = unittest.skipUnless(CASSANDRA_VERSION < Version('3.0'), 'Cassandra version less then 3.0 required') +greaterthanorequaldse68 = unittest.skipUnless(DSE_VERSION and DSE_VERSION >= Version('6.8'), "DSE 6.8 or greater required for this test") +greaterthanorequaldse67 = unittest.skipUnless(DSE_VERSION and DSE_VERSION >= Version('6.7'), "DSE 6.7 or greater required for this test") +greaterthanorequaldse60 = unittest.skipUnless(DSE_VERSION and DSE_VERSION >= Version('6.0'), "DSE 6.0 or greater required for this test") +greaterthanorequaldse51 = unittest.skipUnless(DSE_VERSION and DSE_VERSION >= Version('5.1'), "DSE 5.1 or greater required for this test") +greaterthanorequaldse50 = unittest.skipUnless(DSE_VERSION and DSE_VERSION >= Version('5.0'), "DSE 5.0 or greater required for this test") +lessthandse51 = unittest.skipUnless(DSE_VERSION and DSE_VERSION < Version('5.1'), "DSE version less than 5.1 required") +lessthandse60 = unittest.skipUnless(DSE_VERSION and DSE_VERSION < Version('6.0'), "DSE version less than 6.0 required") + pypy = unittest.skipUnless(platform.python_implementation() == "PyPy", "Test is skipped unless it's on PyPy") notpy3 = unittest.skipIf(sys.version_info >= (3, 0), "Test not applicable for Python 3.x runtime") requiresmallclockgranularity = unittest.skipIf("Windows" in platform.system() or "asyncore" in EVENT_LOOP_MANAGER, "This test is not suitible for environments with large clock granularity") requiressimulacron = unittest.skipIf(SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"), "Simulacron jar hasn't been specified or C* version is 2.0") +requirecassandra = unittest.skipIf(DSE_VERSION, "Cassandra required") +notdse = unittest.skipIf(DSE_VERSION, "DSE not supported") +requiredse = unittest.skipUnless(DSE_VERSION, "DSE required") requirescloudproxy = unittest.skipIf(CLOUD_PROXY_PATH is None, "Cloud Proxy path hasn't been specified") +libevtest = unittest.skipUnless(EVENT_LOOP_MANAGER=="libev", "Test timing designed for libev loop") def wait_for_node_socket(node, timeout): binary_itf = node.network_interfaces['binary'] if not common.check_socket_listening(binary_itf, timeout=timeout): log.warning("Unable to connect to binary socket for node " + node.name) else: log.debug("Node %s is up and listening " % (node.name,)) def check_socket_listening(itf, timeout=60): end = time.time() + timeout while time.time() <= end: try: sock = socket.socket() sock.connect(itf) sock.close() return True except socket.error: # Try again in another 200ms time.sleep(.2) continue return False +USE_SINGLE_INTERFACE = os.getenv('USE_SINGLE_INTERFACE', False) + + def get_cluster(): return CCM_CLUSTER def get_node(node_id): return CCM_CLUSTER.nodes['node%s' % node_id] def use_multidc(dc_list, workloads=[]): use_cluster(MULTIDC_CLUSTER_NAME, dc_list, start=True, workloads=workloads) -def use_singledc(start=True, workloads=[]): - use_cluster(CLUSTER_NAME, [3], start=start, workloads=workloads) +def use_singledc(start=True, workloads=[], use_single_interface=USE_SINGLE_INTERFACE): + use_cluster(CLUSTER_NAME, [3], start=start, workloads=workloads, use_single_interface=use_single_interface) + +def use_single_node(start=True, workloads=[], configuration_options={}, dse_options={}): + use_cluster(SINGLE_NODE_CLUSTER_NAME, [1], start=start, workloads=workloads, + configuration_options=configuration_options, dse_options=dse_options) -def use_single_node(start=True, workloads=[]): - use_cluster(SINGLE_NODE_CLUSTER_NAME, [1], start=start, workloads=workloads) + +def check_log_error(): + global CCM_CLUSTER + log.debug("Checking log error of cluster {0}".format(CCM_CLUSTER.name)) + for node in CCM_CLUSTER.nodelist(): + errors = node.grep_log_for_errors() + for error in errors: + for line in error: + print(line) def remove_cluster(): if USE_CASS_EXTERNAL or KEEP_TEST_CLUSTER: return global CCM_CLUSTER if CCM_CLUSTER: + check_log_error() log.debug("Removing cluster {0}".format(CCM_CLUSTER.name)) tries = 0 while tries < 100: try: CCM_CLUSTER.remove() CCM_CLUSTER = None return except OSError: ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb tries += 1 time.sleep(1) raise RuntimeError("Failed to remove cluster after 100 attempts") -def is_current_cluster(cluster_name, node_counts): +def is_current_cluster(cluster_name, node_counts, workloads): global CCM_CLUSTER if CCM_CLUSTER and CCM_CLUSTER.name == cluster_name: if [len(list(nodes)) for dc, nodes in groupby(CCM_CLUSTER.nodelist(), lambda n: n.data_center)] == node_counts: + for node in CCM_CLUSTER.nodelist(): + if set(node.workloads) != set(workloads): + print("node workloads don't match creating new cluster") + return False return True return False +def start_cluster_wait_for_up(cluster): + cluster.start(wait_for_binary_proto=True) + # Added to wait for slow nodes to start up + log.debug("Cluster started waiting for binary ports") + for node in CCM_CLUSTER.nodes.values(): + wait_for_node_socket(node, 300) + log.debug("Binary port are open") + + def use_cluster(cluster_name, nodes, ipformat=None, start=True, workloads=None, set_keyspace=True, ccm_options=None, - configuration_options={}, dse_cluster=False, dse_options={}, - dse_version=None): + configuration_options={}, dse_options={}, use_single_interface=USE_SINGLE_INTERFACE): + dse_cluster = True if DSE_VERSION else False if not workloads: workloads = [] - if (dse_version and not dse_cluster): - raise ValueError('specified dse_version {} but not dse_cluster'.format(dse_version)) - set_default_cass_ip() - if ccm_options is None and dse_cluster: - ccm_options = {"version": dse_version or DSE_VERSION} + if ccm_options is None and DSE_VERSION: + ccm_options = {"version": CCM_VERSION} elif ccm_options is None: ccm_options = CCM_KWARGS.copy() - if 'version' in ccm_options and not isinstance(ccm_options['version'], Version): - ccm_options['version'] = Version(ccm_options['version']) - cassandra_version = ccm_options.get('version', CCM_VERSION) dse_version = ccm_options.get('version', DSE_VERSION) - if 'version' in ccm_options: - ccm_options['version'] = ccm_options['version'].base_version - global CCM_CLUSTER if USE_CASS_EXTERNAL: if CCM_CLUSTER: log.debug("Using external CCM cluster {0}".format(CCM_CLUSTER.name)) else: - log.debug("Using unnamed external cluster") + ccm_path = os.getenv("CCM_PATH", None) + ccm_name = os.getenv("CCM_NAME", None) + if ccm_path and ccm_name: + CCM_CLUSTER = CCMClusterFactory.load(ccm_path, ccm_name) + log.debug("Using external CCM cluster {0}".format(CCM_CLUSTER.name)) + else: + log.debug("Using unnamed external cluster") if set_keyspace and start: setup_keyspace(ipformat=ipformat, wait=False) return - if is_current_cluster(cluster_name, nodes): + if is_current_cluster(cluster_name, nodes, workloads): log.debug("Using existing cluster, matching topology: {0}".format(cluster_name)) else: if CCM_CLUSTER: log.debug("Stopping existing cluster, topology mismatch: {0}".format(CCM_CLUSTER.name)) CCM_CLUSTER.stop() try: CCM_CLUSTER = CCMClusterFactory.load(path, cluster_name) log.debug("Found existing CCM cluster, {0}; clearing.".format(cluster_name)) CCM_CLUSTER.clear() CCM_CLUSTER.set_install_dir(**ccm_options) CCM_CLUSTER.set_configuration_options(configuration_options) + CCM_CLUSTER.set_dse_configuration_options(dse_options) except Exception: ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb ccm_options.update(cmd_line_args_to_dict('CCM_ARGS')) log.debug("Creating new CCM cluster, {0}, with args {1}".format(cluster_name, ccm_options)) # Make sure we cleanup old cluster dir if it exists cluster_path = os.path.join(path, cluster_name) if os.path.exists(cluster_path): shutil.rmtree(cluster_path) if dse_cluster: CCM_CLUSTER = DseCluster(path, cluster_name, **ccm_options) CCM_CLUSTER.set_configuration_options({'start_native_transport': True}) CCM_CLUSTER.set_configuration_options({'batch_size_warn_threshold_in_kb': 5}) - if dse_version >= Version('5.0'): + if Version(dse_version) >= Version('5.0'): CCM_CLUSTER.set_configuration_options({'enable_user_defined_functions': True}) CCM_CLUSTER.set_configuration_options({'enable_scripted_user_defined_functions': True}) + if Version(dse_version) >= Version('5.1'): + # For Inet4Address + CCM_CLUSTER.set_dse_configuration_options({ + 'graph': { + 'gremlin_server': { + 'scriptEngines': { + 'gremlin-groovy': { + 'config': { + 'sandbox_rules': { + 'whitelist_packages': ['java.net'] + } + } + } + } + } + } + }) if 'spark' in workloads: - config_options = {"initial_spark_worker_resources": 0.1} + if Version(dse_version) >= Version('6.8'): + config_options = { + "resource_manager_options": { + "worker_options": { + "cores_total": 0.1, + "memory_total": "64M" + } + } + } + else: + config_options = {"initial_spark_worker_resources": 0.1} + + if Version(dse_version) >= Version('6.7'): + log.debug("Disabling AlwaysON SQL for a DSE 6.7 Cluster") + config_options['alwayson_sql_options'] = {'enabled': False} CCM_CLUSTER.set_dse_configuration_options(config_options) common.switch_cluster(path, cluster_name) CCM_CLUSTER.set_configuration_options(configuration_options) CCM_CLUSTER.populate(nodes, ipformat=ipformat) CCM_CLUSTER.set_dse_configuration_options(dse_options) else: CCM_CLUSTER = CCMCluster(path, cluster_name, **ccm_options) CCM_CLUSTER.set_configuration_options({'start_native_transport': True}) - if cassandra_version >= Version('2.2'): + if Version(cassandra_version) >= Version('2.2'): CCM_CLUSTER.set_configuration_options({'enable_user_defined_functions': True}) - if cassandra_version >= Version('3.0'): + if Version(cassandra_version) >= Version('3.0'): CCM_CLUSTER.set_configuration_options({'enable_scripted_user_defined_functions': True}) + if Version(cassandra_version) >= Version('4.0-a'): + CCM_CLUSTER.set_configuration_options({ + 'enable_materialized_views': True, + 'enable_sasi_indexes': True, + 'enable_transient_replication': True, + }) common.switch_cluster(path, cluster_name) CCM_CLUSTER.set_configuration_options(configuration_options) - CCM_CLUSTER.populate(nodes, ipformat=ipformat) + CCM_CLUSTER.populate(nodes, ipformat=ipformat, use_single_interface=use_single_interface) try: jvm_args = [] + # This will enable the Mirroring query handler which will echo our custom payload k,v pairs back - if 'graph' not in workloads: + if 'graph' in workloads: + jvm_args += ['-Xms1500M', '-Xmx1500M'] + else: if PROTOCOL_VERSION >= 4: jvm_args = [" -Dcassandra.custom_query_handler_class=org.apache.cassandra.cql3.CustomPayloadMirroringQueryHandler"] if len(workloads) > 0: for node in CCM_CLUSTER.nodes.values(): node.set_workloads(workloads) if start: log.debug("Starting CCM cluster: {0}".format(cluster_name)) - CCM_CLUSTER.start(wait_for_binary_proto=True, wait_other_notice=True, jvm_args=jvm_args) + CCM_CLUSTER.start(jvm_args=jvm_args, wait_for_binary_proto=True) # Added to wait for slow nodes to start up + log.debug("Cluster started waiting for binary ports") for node in CCM_CLUSTER.nodes.values(): - wait_for_node_socket(node, 120) + wait_for_node_socket(node, 300) + log.debug("Binary ports are open") if set_keyspace: setup_keyspace(ipformat=ipformat) except Exception: log.exception("Failed to start CCM cluster; removing cluster.") if os.name == "nt": if CCM_CLUSTER: for node in six.itervalues(CCM_CLUSTER.nodes): os.system("taskkill /F /PID " + str(node.pid)) else: call(["pkill", "-9", "-f", ".ccm"]) remove_cluster() raise return CCM_CLUSTER def teardown_package(): if USE_CASS_EXTERNAL or KEEP_TEST_CLUSTER: return # when multiple modules are run explicitly, this runs between them # need to make sure CCM_CLUSTER is properly cleared for that case remove_cluster() for cluster_name in [CLUSTER_NAME, MULTIDC_CLUSTER_NAME]: try: cluster = CCMClusterFactory.load(path, cluster_name) try: cluster.remove() log.info('Removed cluster: %s' % cluster_name) except Exception: log.exception('Failed to remove cluster: %s' % cluster_name) except Exception: log.warning('Did not find cluster: %s' % cluster_name) def execute_until_pass(session, query): tries = 0 while tries < 100: try: return session.execute(query) except (ConfigurationException, AlreadyExists, InvalidRequest): log.warning("Received already exists from query {0} not exiting".format(query)) # keyspace/table was already created/dropped return except (OperationTimedOut, ReadTimeout, ReadFailure, WriteTimeout, WriteFailure): ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb tries += 1 raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(query)) def execute_with_long_wait_retry(session, query, timeout=30): tries = 0 while tries < 10: try: return session.execute(query, timeout=timeout) except (ConfigurationException, AlreadyExists): log.warning("Received already exists from query {0} not exiting".format(query)) # keyspace/table was already created/dropped return except (OperationTimedOut, ReadTimeout, ReadFailure, WriteTimeout, WriteFailure): ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb tries += 1 raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(query)) def execute_with_retry_tolerant(session, query, retry_exceptions, escape_exception): # TODO refactor above methods into this one for code reuse tries = 0 while tries < 100: try: tries += 1 rs = session.execute(query) return rs except escape_exception: return except retry_exceptions: time.sleep(.1) raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(query)) def drop_keyspace_shutdown_cluster(keyspace_name, session, cluster): try: execute_with_long_wait_retry(session, "DROP KEYSPACE {0}".format(keyspace_name)) except: log.warning("Error encountered when droping keyspace {0}".format(keyspace_name)) ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb finally: log.warning("Shutting down cluster") cluster.shutdown() -def setup_keyspace(ipformat=None, wait=True): +def setup_keyspace(ipformat=None, wait=True, protocol_version=None): # wait for nodes to startup if wait: time.sleep(10) + if protocol_version: + _protocol_version = protocol_version + else: + _protocol_version = PROTOCOL_VERSION + if not ipformat: - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster(protocol_version=_protocol_version) else: - cluster = Cluster(contact_points=["::1"], protocol_version=PROTOCOL_VERSION) + cluster = TestCluster(contact_points=["::1"], protocol_version=_protocol_version) session = cluster.connect() try: for ksname in ('test1rf', 'test2rf', 'test3rf'): if ksname in cluster.metadata.keyspaces: execute_until_pass(session, "DROP KEYSPACE %s" % ksname) ddl = ''' CREATE KEYSPACE test3rf WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '3'}''' execute_with_long_wait_retry(session, ddl) ddl = ''' CREATE KEYSPACE test2rf WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '2'}''' execute_with_long_wait_retry(session, ddl) ddl = ''' CREATE KEYSPACE test1rf WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}''' execute_with_long_wait_retry(session, ddl) ddl_3f = ''' CREATE TABLE test3rf.test ( k int PRIMARY KEY, v int )''' execute_with_long_wait_retry(session, ddl_3f) ddl_1f = ''' CREATE TABLE test1rf.test ( k int PRIMARY KEY, v int )''' execute_with_long_wait_retry(session, ddl_1f) except Exception: traceback.print_exc() raise finally: cluster.shutdown() class UpDownWaiter(object): def __init__(self, host): self.down_event = Event() self.up_event = Event() host.monitor.register(self) def on_up(self, host): self.up_event.set() def on_down(self, host): self.down_event.set() def wait_for_down(self): self.down_event.wait() def wait_for_up(self): self.up_event.wait() class BasicKeyspaceUnitTestCase(unittest.TestCase): """ This is basic unit test case that provides various utility methods that can be leveraged for testcase setup and tear down """ @property def keyspace_name(self): return self.ks_name @property def class_table_name(self): return self.ks_name @property def function_table_name(self): return self._testMethodName.lower() @property def keyspace_table_name(self): return "{0}.{1}".format(self.keyspace_name, self._testMethodName.lower()) @classmethod def drop_keyspace(cls): execute_with_long_wait_retry(cls.session, "DROP KEYSPACE {0}".format(cls.ks_name)) @classmethod def create_keyspace(cls, rf): ddl = "CREATE KEYSPACE {0} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor': '{1}'}}".format(cls.ks_name, rf) execute_with_long_wait_retry(cls.session, ddl) @classmethod - def common_setup(cls, rf, keyspace_creation=True, create_class_table=False, metrics=False): - cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION, metrics_enabled=metrics) + def common_setup(cls, rf, keyspace_creation=True, create_class_table=False, **cluster_kwargs): + cls.cluster = TestCluster(**cluster_kwargs) cls.session = cls.cluster.connect(wait_for_all_pools=True) cls.ks_name = cls.__name__.lower() if keyspace_creation: cls.create_keyspace(rf) cls.cass_version, cls.cql_version = get_server_versions() if create_class_table: ddl = ''' CREATE TABLE {0}.{1} ( k int PRIMARY KEY, v int )'''.format(cls.ks_name, cls.ks_name) execute_until_pass(cls.session, ddl) def create_function_table(self): ddl = ''' CREATE TABLE {0}.{1} ( k int PRIMARY KEY, v int )'''.format(self.keyspace_name, self.function_table_name) execute_until_pass(self.session, ddl) def drop_function_table(self): ddl = "DROP TABLE {0}.{1} ".format(self.keyspace_name, self.function_table_name) execute_until_pass(self.session, ddl) class MockLoggingHandler(logging.Handler): """Mock logging handler to check for expected logs.""" def __init__(self, *args, **kwargs): self.reset() logging.Handler.__init__(self, *args, **kwargs) def emit(self, record): self.messages[record.levelname.lower()].append(record.getMessage()) def reset(self): self.messages = { 'debug': [], 'info': [], 'warning': [], 'error': [], 'critical': [], } def get_message_count(self, level, sub_string): count = 0 for msg in self.messages.get(level): if sub_string in msg: count+=1 return count def set_module_name(self, module_name): """ This is intended to be used doing: with MockLoggingHandler().set_module_name(connection.__name__) as mock_handler: """ self.module_name = module_name return self def __enter__(self): self.logger = logging.getLogger(self.module_name) self.logger.addHandler(self) return self def __exit__(self, *args): pass class BasicExistingKeyspaceUnitTestCase(BasicKeyspaceUnitTestCase): """ This is basic unit test defines class level teardown and setup methods. It assumes that keyspace is already defined, or created as part of the test. """ @classmethod def setUpClass(cls): cls.common_setup(1, keyspace_creation=False) @classmethod def tearDownClass(cls): cls.cluster.shutdown() class BasicSharedKeyspaceUnitTestCase(BasicKeyspaceUnitTestCase): """ This is basic unit test case that can be leveraged to scope a keyspace to a specific test class. creates a keyspace named after the testclass with a rf of 1. """ @classmethod def setUpClass(cls): cls.common_setup(1) @classmethod def tearDownClass(cls): drop_keyspace_shutdown_cluster(cls.ks_name, cls.session, cls.cluster) class BasicSharedKeyspaceUnitTestCaseRF1(BasicSharedKeyspaceUnitTestCase): """ This is basic unit test case that can be leveraged to scope a keyspace to a specific test class. creates a keyspace named after the testclass with a rf of 1 """ @classmethod def setUpClass(self): self.common_setup(1, True) class BasicSharedKeyspaceUnitTestCaseRF2(BasicSharedKeyspaceUnitTestCase): """ This is basic unit test case that can be leveraged to scope a keyspace to a specific test class. creates a keyspace named after the test class with a rf of 2, and a table named after the class """ @classmethod def setUpClass(self): self.common_setup(2) class BasicSharedKeyspaceUnitTestCaseRF3(BasicSharedKeyspaceUnitTestCase): """ This is basic unit test case that can be leveraged to scope a keyspace to a specific test class. creates a keyspace named after the test class with a rf of 3 """ @classmethod def setUpClass(self): self.common_setup(3) class BasicSharedKeyspaceUnitTestCaseRF3WM(BasicSharedKeyspaceUnitTestCase): """ This is basic unit test case that can be leveraged to scope a keyspace to a specific test class. creates a keyspace named after the test class with a rf of 3 with metrics enabled """ @classmethod def setUpClass(self): - self.common_setup(3, True, True, True) + self.common_setup(3, True, True, metrics_enabled=True) + + @classmethod + def tearDownClass(cls): + drop_keyspace_shutdown_cluster(cls.ks_name, cls.session, cls.cluster) class BasicSharedKeyspaceUnitTestCaseWFunctionTable(BasicSharedKeyspaceUnitTestCase): """" This is basic unit test case that can be leveraged to scope a keyspace to a specific test class. creates a keyspace named after the test class with a rf of 3 and a table named after the class the table is scoped to just the unit test and will be removed. """ def setUp(self): self.create_function_table() def tearDown(self): self.drop_function_table() class BasicSegregatedKeyspaceUnitTestCase(BasicKeyspaceUnitTestCase): """ This unit test will create and teardown a keyspace for each individual unit tests. It has overhead and should only be used with complex unit test were sharing a keyspace will cause issues. """ def setUp(self): self.common_setup(1) def tearDown(self): drop_keyspace_shutdown_cluster(self.ks_name, self.session, self.cluster) class BasicExistingSegregatedKeyspaceUnitTestCase(BasicKeyspaceUnitTestCase): """ This unit test will create and teardown or each individual unit tests. It assumes that keyspace is existing or created as part of a test. It has some overhead and should only be used when sharing cluster/session is not feasible. """ def setUp(self): self.common_setup(1, keyspace_creation=False) def tearDown(self): self.cluster.shutdown() + + +def assert_startswith(s, prefix): + if not s.startswith(prefix): + raise AssertionError( + '{} does not start with {}'.format(repr(s), repr(prefix)) + ) + + +class TestCluster(object): + DEFAULT_PROTOCOL_VERSION = default_protocol_version + DEFAULT_CASSANDRA_IP = CASSANDRA_IP + DEFAULT_ALLOW_BETA = ALLOW_BETA_PROTOCOL + + def __new__(cls, **kwargs): + if 'protocol_version' not in kwargs: + kwargs['protocol_version'] = cls.DEFAULT_PROTOCOL_VERSION + if 'contact_points' not in kwargs: + kwargs['contact_points'] = [cls.DEFAULT_CASSANDRA_IP] + if 'allow_beta_protocol_version' not in kwargs: + kwargs['allow_beta_protocol_version'] = cls.DEFAULT_ALLOW_BETA + return Cluster(**kwargs) + diff --git a/tests/integration/advanced/__init__.py b/tests/integration/advanced/__init__.py index 662f5b8..b2820e0 100644 --- a/tests/integration/advanced/__init__.py +++ b/tests/integration/advanced/__init__.py @@ -1,23 +1,165 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License +# limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) +from six.moves.urllib.request import build_opener, Request, HTTPHandler +import re +import os +import time +from os.path import expanduser + +from ccmlib import common + +from tests.integration import get_server_versions, BasicKeyspaceUnitTestCase, \ + drop_keyspace_shutdown_cluster, get_node, USE_CASS_EXTERNAL, TestCluster +from tests.integration import use_singledc, use_single_node, wait_for_node_socket, CASSANDRA_IP + +home = expanduser('~') + +# Home directory of the Embedded Apache Directory Server to use +ADS_HOME = os.getenv('ADS_HOME', home) + + +def find_spark_master(session): + + # Iterate over the nodes the one with port 7080 open is the spark master + for host in session.hosts: + ip = host.address + port = 7077 + spark_master = (ip, port) + if common.check_socket_listening(spark_master, timeout=3): + return spark_master[0] + return None + + +def wait_for_spark_workers(num_of_expected_workers, timeout): + """ + This queries the spark master and checks for the expected number of workers + """ + start_time = time.time() + while True: + opener = build_opener(HTTPHandler) + request = Request("http://{0}:7080".format(CASSANDRA_IP)) + request.get_method = lambda: 'GET' + connection = opener.open(request) + match = re.search('Alive Workers:.*(\d+)', connection.read().decode('utf-8')) + num_workers = int(match.group(1)) + if num_workers == num_of_expected_workers: + match = True + break + elif time.time() - start_time > timeout: + match = True + break + time.sleep(1) + return match + + +def use_single_node_with_graph(start=True, options={}, dse_options={}): + use_single_node(start=start, workloads=['graph'], configuration_options=options, dse_options=dse_options) + + +def use_single_node_with_graph_and_spark(start=True, options={}): + use_single_node(start=start, workloads=['graph', 'spark'], configuration_options=options) + + +def use_single_node_with_graph_and_solr(start=True, options={}): + use_single_node(start=start, workloads=['graph', 'solr'], configuration_options=options) + + +def use_singledc_wth_graph(start=True): + use_singledc(start=start, workloads=['graph']) + + +def use_singledc_wth_graph_and_spark(start=True): + use_cluster_with_graph(3) + + +def use_cluster_with_graph(num_nodes): + """ + This is a work around to account for the fact that spark nodes will conflict over master assignment + when started all at once. + """ + if USE_CASS_EXTERNAL: + return + + # Create the cluster but don't start it. + use_singledc(start=False, workloads=['graph', 'spark']) + # Start first node. + get_node(1).start(wait_for_binary_proto=True) + # Wait binary protocol port to open + wait_for_node_socket(get_node(1), 120) + # Wait for spark master to start up + spark_master_http = ("localhost", 7080) + common.check_socket_listening(spark_master_http, timeout=60) + tmp_cluster = TestCluster() + + # Start up remaining nodes. + try: + session = tmp_cluster.connect() + statement = "ALTER KEYSPACE dse_leases WITH REPLICATION = {'class': 'NetworkTopologyStrategy', 'dc1': '%d'}" % (num_nodes) + session.execute(statement) + finally: + tmp_cluster.shutdown() + + for i in range(1, num_nodes+1): + if i is not 1: + node = get_node(i) + node.start(wait_for_binary_proto=True) + wait_for_node_socket(node, 120) + + # Wait for workers to show up as Alive on master + wait_for_spark_workers(3, 120) + + +class BasicGeometricUnitTestCase(BasicKeyspaceUnitTestCase): + """ + This base test class is used by all the geomteric tests. It contains class level teardown and setup + methods. It also contains the test fixtures used by those tests + """ + + @classmethod + def common_dse_setup(cls, rf, keyspace_creation=True): + cls.cluster = TestCluster() + cls.session = cls.cluster.connect() + cls.ks_name = cls.__name__.lower() + if keyspace_creation: + cls.create_keyspace(rf) + cls.cass_version, cls.cql_version = get_server_versions() + cls.session.set_keyspace(cls.ks_name) + + @classmethod + def setUpClass(cls): + cls.common_dse_setup(1) + cls.initalizeTables() + + @classmethod + def tearDownClass(cls): + drop_keyspace_shutdown_cluster(cls.ks_name, cls.session, cls.cluster) + + @classmethod + def initalizeTables(cls): + udt_type = "CREATE TYPE udt1 (g {0})".format(cls.cql_type_name) + large_table = "CREATE TABLE tbl (k uuid PRIMARY KEY, g {0}, l list<{0}>, s set<{0}>, m0 map<{0},int>, m1 map, t tuple<{0},{0},{0}>, u frozen)".format( + cls.cql_type_name) + simple_table = "CREATE TABLE tblpk (k {0} primary key, v int)".format(cls.cql_type_name) + cluster_table = "CREATE TABLE tblclustering (k0 int, k1 {0}, v int, primary key (k0, k1))".format( + cls.cql_type_name) + cls.session.execute(udt_type) + cls.session.execute(large_table) + cls.session.execute(simple_table) + cls.session.execute(cluster_table) diff --git a/tests/integration/advanced/graph/__init__.py b/tests/integration/advanced/graph/__init__.py new file mode 100644 index 0000000..6c9458d --- /dev/null +++ b/tests/integration/advanced/graph/__init__.py @@ -0,0 +1,1205 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +import logging +import inspect +from packaging.version import Version +import ipaddress +from uuid import UUID +from decimal import Decimal +import datetime + +from cassandra.util import Point, LineString, Polygon, Duration +import six + +from cassandra.cluster import EXEC_PROFILE_GRAPH_DEFAULT, EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT +from cassandra.cluster import GraphAnalyticsExecutionProfile, GraphExecutionProfile, EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT, \ + default_lbp_factory +from cassandra.policies import DSELoadBalancingPolicy + +from cassandra.graph import GraphSON1Deserializer +from cassandra.graph.graphson import InetTypeIO, GraphSON2Deserializer, GraphSON3Deserializer +from cassandra.graph import Edge, Vertex, Path +from cassandra.graph.query import GraphOptions, GraphProtocol, graph_graphson2_row_factory, \ + graph_graphson3_row_factory + +from tests.integration import DSE_VERSION +from tests.integration.advanced import * + + +def setup_module(): + if DSE_VERSION: + dse_options = {'graph': {'realtime_evaluation_timeout_in_seconds': 60}} + use_single_node_with_graph(dse_options=dse_options) + + +log = logging.getLogger(__name__) + +MAX_LONG = 9223372036854775807 +MIN_LONG = -9223372036854775808 +ZERO_LONG = 0 + +if sys.version_info < (3, 0): + MAX_LONG = long(MAX_LONG) + MIN_LONG = long(MIN_LONG) + ZERO_LONG = long(ZERO_LONG) + +MAKE_STRICT = "schema.config().option('graph.schema_mode').set('production')" +MAKE_NON_STRICT = "schema.config().option('graph.schema_mode').set('development')" +ALLOW_SCANS = "schema.config().option('graph.allow_scan').set('true')" + +deserializer_plus_to_ipaddressv4 = lambda x: ipaddress.IPv4Address(GraphSON1Deserializer.deserialize_inet(x)) +deserializer_plus_to_ipaddressv6 = lambda x: ipaddress.IPv6Address(GraphSON1Deserializer.deserialize_inet(x)) + + +def generic_ip_deserializer(string_ip_address): + if ":" in string_ip_address: + return deserializer_plus_to_ipaddressv6(string_ip_address) + return deserializer_plus_to_ipaddressv4(string_ip_address) + + +class GenericIpAddressIO(InetTypeIO): + @classmethod + def deserialize(cls, value, reader=None): + return generic_ip_deserializer(value) + +GraphSON2Deserializer._deserializers[GenericIpAddressIO.graphson_type] = GenericIpAddressIO +GraphSON3Deserializer._deserializers[GenericIpAddressIO.graphson_type] = GenericIpAddressIO + +if DSE_VERSION: + if DSE_VERSION >= Version('6.8.0'): + CREATE_CLASSIC_GRAPH = "system.graph(name).engine(Classic).create()" + else: + CREATE_CLASSIC_GRAPH = "system.graph(name).create()" + + +def reset_graph(session, graph_name): + ks = list(session.execute( + "SELECT * FROM system_schema.keyspaces WHERE keyspace_name = '{}';".format(graph_name))) + if ks: + try: + session.execute_graph('system.graph(name).drop()', {'name': graph_name}, + execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT) + except: + pass + + session.execute_graph(CREATE_CLASSIC_GRAPH, {'name': graph_name}, + execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT) + wait_for_graph_inserted(session, graph_name) + + +def wait_for_graph_inserted(session, graph_name): + count = 0 + exists = session.execute_graph('system.graph(name).exists()', {'name': graph_name}, + execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT)[0].value + while not exists and count < 50: + time.sleep(1) + exists = session.execute_graph('system.graph(name).exists()', {'name': graph_name}, + execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT)[0].value + return exists + + +class BasicGraphUnitTestCase(BasicKeyspaceUnitTestCase): + """ + This is basic graph unit test case that provides various utility methods that can be leveraged for testcase setup and tear + down + """ + + @property + def graph_name(self): + return self._testMethodName.lower() + + def session_setup(self): + lbp = DSELoadBalancingPolicy(default_lbp_factory()) + + ep_graphson2 = GraphExecutionProfile( + request_timeout=60, + load_balancing_policy=lbp, + graph_options=GraphOptions( + graph_name=self.graph_name, + graph_protocol=GraphProtocol.GRAPHSON_2_0 + ), + row_factory=graph_graphson2_row_factory) + + ep_graphson3 = GraphExecutionProfile( + request_timeout=60, + load_balancing_policy=lbp, + graph_options=GraphOptions( + graph_name=self.graph_name, + graph_protocol=GraphProtocol.GRAPHSON_3_0 + ), + row_factory=graph_graphson3_row_factory) + + ep_graphson1 = GraphExecutionProfile( + request_timeout=60, + load_balancing_policy=lbp, + graph_options=GraphOptions( + graph_name=self.graph_name + ) + ) + + ep_analytics = GraphAnalyticsExecutionProfile( + request_timeout=60, + load_balancing_policy=lbp, + graph_options=GraphOptions( + graph_source=b'a', + graph_language=b'gremlin-groovy', + graph_name=self.graph_name + ) + ) + + self.cluster = TestCluster(execution_profiles={ + EXEC_PROFILE_GRAPH_DEFAULT: ep_graphson1, + EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT: ep_analytics, + "graphson1": ep_graphson1, + "graphson2": ep_graphson2, + "graphson3": ep_graphson3 + }) + + self.session = self.cluster.connect() + self.ks_name = self._testMethodName.lower() + self.cass_version, self.cql_version = get_server_versions() + + def setUp(self): + self.session_setup() + self.reset_graph() + self.clear_schema() + # enable dev and scan modes + self.session.execute_graph(MAKE_NON_STRICT) + self.session.execute_graph(ALLOW_SCANS) + + def tearDown(self): + self.cluster.shutdown() + + def clear_schema(self): + self.session.execute_graph(""" + schema.clear(); + """) + + def reset_graph(self): + reset_graph(self.session, self.graph_name) + + def wait_for_graph_inserted(self): + wait_for_graph_inserted(self.session, self.graph_name) + + def _execute(self, query, graphson, params=None, execution_profile_options=None, **kwargs): + queries = query if isinstance(query, list) else [query] + ep = self.get_execution_profile(graphson) + if execution_profile_options: + ep = self.session.execution_profile_clone_update(ep, **execution_profile_options) + + results = [] + for query in queries: + log.debug(query) + rf = self.session.execute_graph_async(query, parameters=params, execution_profile=ep, **kwargs) + results.append(rf.result()) + self.assertEqual(rf.message.custom_payload['graph-results'], graphson) + + return results[0] if len(results) == 1 else results + + def get_execution_profile(self, graphson, traversal=False): + ep = 'graphson1' + if graphson == GraphProtocol.GRAPHSON_2_0: + ep = 'graphson2' + elif graphson == GraphProtocol.GRAPHSON_3_0: + ep = 'graphson3' + + return ep if traversal is False else 'traversal_' + ep + + def resultset_to_list(self, rs): + results_list = [] + for result in rs: + try: + results_list.append(result.value) + except: + results_list.append(result) + + return results_list + + +class GraphUnitTestCase(BasicKeyspaceUnitTestCase): + + @property + def graph_name(self): + return self._testMethodName.lower() + + def session_setup(self): + lbp = DSELoadBalancingPolicy(default_lbp_factory()) + + ep_graphson2 = GraphExecutionProfile( + request_timeout=60, + load_balancing_policy=lbp, + graph_options=GraphOptions( + graph_name=self.graph_name, + graph_protocol=GraphProtocol.GRAPHSON_2_0 + ), + row_factory=graph_graphson2_row_factory) + + ep_graphson3 = GraphExecutionProfile( + request_timeout=60, + load_balancing_policy=lbp, + graph_options=GraphOptions( + graph_name=self.graph_name, + graph_protocol=GraphProtocol.GRAPHSON_3_0 + ), + row_factory=graph_graphson3_row_factory) + + ep_graphson1 = GraphExecutionProfile( + request_timeout=60, + load_balancing_policy=lbp, + graph_options=GraphOptions( + graph_name=self.graph_name, + graph_language='gremlin-groovy' + ) + ) + + ep_analytics = GraphAnalyticsExecutionProfile( + request_timeout=60, + load_balancing_policy=lbp, + graph_options=GraphOptions( + graph_source=b'a', + graph_language=b'gremlin-groovy', + graph_name=self.graph_name + ) + ) + + self.cluster = TestCluster(execution_profiles={ + EXEC_PROFILE_GRAPH_DEFAULT: ep_graphson1, + EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT: ep_analytics, + "graphson1": ep_graphson1, + "graphson2": ep_graphson2, + "graphson3": ep_graphson3 + }) + + self.session = self.cluster.connect() + self.ks_name = self._testMethodName.lower() + self.cass_version, self.cql_version = get_server_versions() + + def setUp(self): + """basic setup only""" + self.session_setup() + + def setup_graph(self, schema): + """Config dependant setup""" + schema.drop_graph(self.session, self.graph_name) + schema.create_graph(self.session, self.graph_name) + schema.clear(self.session) + if schema is ClassicGraphSchema: + # enable dev and scan modes + self.session.execute_graph(MAKE_NON_STRICT) + self.session.execute_graph(ALLOW_SCANS) + + def teardown_graph(self, schema): + schema.drop_graph(self.session, self.graph_name) + + def tearDown(self): + self.cluster.shutdown() + + def execute_graph_queries(self, queries, params=None, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT, + verify_graphson=False, **kwargs): + results = [] + for query in queries: + log.debug(query) + rf = self.session.execute_graph_async(query, parameters=params, + execution_profile=execution_profile, **kwargs) + if verify_graphson: + self.assertEqual(rf.message.custom_payload['graph-results'], verify_graphson) + results.append(rf.result()) + + return results + + def execute_graph(self, query, graphson, params=None, execution_profile_options=None, traversal=False, **kwargs): + queries = query if isinstance(query, list) else [query] + ep = self.get_execution_profile(graphson) + if traversal: + ep = 'traversal_' + ep + if execution_profile_options: + ep = self.session.execution_profile_clone_update(ep, **execution_profile_options) + + results = self.execute_graph_queries(queries, params, ep, verify_graphson=graphson, **kwargs) + + return results[0] if len(results) == 1 else results + + def get_execution_profile(self, graphson, traversal=False): + ep = 'graphson1' + if graphson == GraphProtocol.GRAPHSON_2_0: + ep = 'graphson2' + elif graphson == GraphProtocol.GRAPHSON_3_0: + ep = 'graphson3' + + return ep if traversal is False else 'traversal_' + ep + + def resultset_to_list(self, rs): + results_list = [] + for result in rs: + try: + results_list.append(result.value) + except: + results_list.append(result) + + return results_list + + +class BasicSharedGraphUnitTestCase(BasicKeyspaceUnitTestCase): + """ + This is basic graph unit test case that provides various utility methods that can be leveraged for testcase setup and tear + down + """ + + @classmethod + def session_setup(cls): + cls.cluster = TestCluster() + cls.session = cls.cluster.connect() + cls.ks_name = cls.__name__.lower() + cls.cass_version, cls.cql_version = get_server_versions() + cls.graph_name = cls.__name__.lower() + + @classmethod + def setUpClass(cls): + if DSE_VERSION: + cls.session_setup() + cls.reset_graph() + profiles = cls.cluster.profile_manager.profiles + profiles[EXEC_PROFILE_GRAPH_DEFAULT].request_timeout = 60 + profiles[EXEC_PROFILE_GRAPH_DEFAULT].graph_options.graph_name = cls.graph_name + profiles[EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT].request_timeout = 60 + profiles[EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT].graph_options.graph_name = cls.graph_name + + @classmethod + def tearDownClass(cls): + if DSE_VERSION: + cls.cluster.shutdown() + + @classmethod + def clear_schema(self): + self.session.execute_graph('schema.clear()') + + @classmethod + def reset_graph(self): + reset_graph(self.session, self.graph_name) + + def wait_for_graph_inserted(self): + wait_for_graph_inserted(self.session, self.graph_name) + + +class GraphFixtures(object): + + @staticmethod + def line(length, single_script=True): + raise NotImplementedError() + + @staticmethod + def classic(): + raise NotImplementedError() + + @staticmethod + def multiple_fields(): + raise NotImplementedError() + + @staticmethod + def large(): + raise NotImplementedError() + + +class ClassicGraphFixtures(GraphFixtures): + + @staticmethod + def datatypes(): + data = { + "boolean1": ["Boolean()", True, None], + "boolean2": ["Boolean()", False, None], + "point1": ["Point()", Point(.5, .13), GraphSON1Deserializer.deserialize_point], + "point2": ["Point()", Point(-5, .0), GraphSON1Deserializer.deserialize_point], + + "linestring1": ["Linestring()", LineString(((1.0, 2.0), (3.0, 4.0), (-89.0, 90.0))), + GraphSON1Deserializer.deserialize_linestring], + "polygon1": ["Polygon()", Polygon([(10.0, 10.0), (80.0, 10.0), (80., 88.0), (10., 89.0), (10., 10.0)], + [[(20., 20.0), (20., 30.0), (30., 30.0), (30., 20.0), (20., 20.0)], + [(40., 20.0), (40., 30.0), (50., 30.0), (50., 20.0), (40., 20.0)]]), + GraphSON1Deserializer.deserialize_polygon], + "int1": ["Int()", 2, GraphSON1Deserializer.deserialize_int], + "smallint1": ["Smallint()", 1, GraphSON1Deserializer.deserialize_smallint], + "bigint1": ["Bigint()", MAX_LONG, GraphSON1Deserializer.deserialize_bigint], + "bigint2": ["Bigint()", MIN_LONG, GraphSON1Deserializer.deserialize_bigint], + "bigint3": ["Bigint()", ZERO_LONG, GraphSON1Deserializer.deserialize_bigint], + "varint1": ["Varint()", 2147483647, GraphSON1Deserializer.deserialize_varint], + "int1": ["Int()", 100, GraphSON1Deserializer.deserialize_int], + "float1": ["Float()", 0.3415681, GraphSON1Deserializer.deserialize_float], + "double1": ["Double()", 0.34156811237335205, GraphSON1Deserializer.deserialize_double], + "uuid1": ["Uuid()", UUID('12345678123456781234567812345678'), GraphSON1Deserializer.deserialize_uuid], + "decimal1": ["Decimal()", Decimal(10), GraphSON1Deserializer.deserialize_decimal], + "blob1": ["Blob()", bytearray(b"Hello World"), GraphSON1Deserializer.deserialize_blob], + + "timestamp1": ["Timestamp()", datetime.datetime.utcnow().replace(microsecond=0), + GraphSON1Deserializer.deserialize_timestamp], + "timestamp2": ["Timestamp()", datetime.datetime.max.replace(microsecond=0), + GraphSON1Deserializer.deserialize_timestamp], + # These are valid values but are pending for DSP-14093 to be fixed + #"timestamp3": ["Timestamp()", datetime.datetime(159, 1, 1, 23, 59, 59), + # GraphSON1TypeDeserializer.deserialize_timestamp], + #"timestamp4": ["Timestamp()", datetime.datetime.min, + # GraphSON1TypeDeserializer.deserialize_timestamp], + "inet1": ["Inet()", ipaddress.IPv4Address(u"127.0.0.1"), deserializer_plus_to_ipaddressv4], + "inet2": ["Inet()", ipaddress.IPv6Address(u"2001:db8:85a3:8d3:1319:8a2e:370:7348"), + deserializer_plus_to_ipaddressv6], + "duration1": ["Duration()", datetime.timedelta(1, 16, 0), + GraphSON1Deserializer.deserialize_duration], + "duration2": ["Duration()", datetime.timedelta(days=1, seconds=16, milliseconds=15), + GraphSON1Deserializer.deserialize_duration] + } + + if six.PY2: + data["blob2"] = ["Blob()", buffer(b"Hello World"), GraphSON1Deserializer.deserialize_blob] + else: + data["blob3"] = ["Blob()", bytes(b"Hello World Again"), GraphSON1Deserializer.deserialize_blob] + data["blob4"] = ["Blob()", memoryview(b"And Again Hello World"), GraphSON1Deserializer.deserialize_blob] + + if DSE_VERSION >= Version("5.1"): + data["time1"] = ["Time()", datetime.time(12, 6, 12, 444), GraphSON1Deserializer.deserialize_time] + data["time2"] = ["Time()", datetime.time(12, 6, 12), GraphSON1Deserializer.deserialize_time] + data["time3"] = ["Time()", datetime.time(12, 6), GraphSON1Deserializer.deserialize_time] + data["time4"] = ["Time()", datetime.time.min, GraphSON1Deserializer.deserialize_time] + data["time5"] = ["Time()", datetime.time.max, GraphSON1Deserializer.deserialize_time] + data["blob5"] = ["Blob()", bytearray(b"AKDLIElksadlaswqA" * 10000), GraphSON1Deserializer.deserialize_blob] + data["datetime1"] = ["Date()", datetime.date.today(), GraphSON1Deserializer.deserialize_date] + data["datetime2"] = ["Date()", datetime.date(159, 1, 3), GraphSON1Deserializer.deserialize_date] + data["datetime3"] = ["Date()", datetime.date.min, GraphSON1Deserializer.deserialize_date] + data["datetime4"] = ["Date()", datetime.date.max, GraphSON1Deserializer.deserialize_date] + data["time1"] = ["Time()", datetime.time(12, 6, 12, 444), GraphSON1Deserializer.deserialize_time] + data["time2"] = ["Time()", datetime.time(12, 6, 12), GraphSON1Deserializer.deserialize_time] + data["time3"] = ["Time()", datetime.time(12, 6), GraphSON1Deserializer.deserialize_time] + data["time4"] = ["Time()", datetime.time.min, GraphSON1Deserializer.deserialize_time] + data["time5"] = ["Time()", datetime.time.max, GraphSON1Deserializer.deserialize_time] + + return data + + @staticmethod + def line(length, single_script=False): + queries = [ALLOW_SCANS + ';', + """schema.propertyKey('index').Int().ifNotExists().create(); + schema.propertyKey('distance').Int().ifNotExists().create(); + schema.vertexLabel('lp').properties('index').ifNotExists().create(); + schema.edgeLabel('goesTo').properties('distance').connection('lp', 'lp').ifNotExists().create();"""] + + vertex_script = ["Vertex vertex0 = graph.addVertex(label, 'lp', 'index', 0);"] + for index in range(1, length): + if not single_script and len(vertex_script) > 25: + queries.append("\n".join(vertex_script)) + vertex_script = [ + "Vertex vertex{pindex} = g.V().hasLabel('lp').has('index', {pindex}).next()".format( + pindex=index-1)] + + vertex_script.append(''' + Vertex vertex{vindex} = graph.addVertex(label, 'lp', 'index', {vindex}); + vertex{pindex}.addEdge('goesTo', vertex{vindex}, 'distance', 5); '''.format( + vindex=index, pindex=index - 1)) + + queries.append("\n".join(vertex_script)) + return queries + + @staticmethod + def classic(): + queries = [ALLOW_SCANS, + '''schema.propertyKey('name').Text().ifNotExists().create(); + schema.propertyKey('age').Int().ifNotExists().create(); + schema.propertyKey('lang').Text().ifNotExists().create(); + schema.propertyKey('weight').Float().ifNotExists().create(); + schema.vertexLabel('person').properties('name', 'age').ifNotExists().create(); + schema.vertexLabel('software').properties('name', 'lang').ifNotExists().create(); + schema.edgeLabel('created').properties('weight').connection('person', 'software').ifNotExists().create(); + schema.edgeLabel('created').connection('software', 'software').add(); + schema.edgeLabel('knows').properties('weight').connection('person', 'person').ifNotExists().create();''', + + '''Vertex marko = graph.addVertex(label, 'person', 'name', 'marko', 'age', 29); + Vertex vadas = graph.addVertex(label, 'person', 'name', 'vadas', 'age', 27); + Vertex lop = graph.addVertex(label, 'software', 'name', 'lop', 'lang', 'java'); + Vertex josh = graph.addVertex(label, 'person', 'name', 'josh', 'age', 32); + Vertex ripple = graph.addVertex(label, 'software', 'name', 'ripple', 'lang', 'java'); + Vertex peter = graph.addVertex(label, 'person', 'name', 'peter', 'age', 35); + Vertex carl = graph.addVertex(label, 'person', 'name', 'carl', 'age', 35); + marko.addEdge('knows', vadas, 'weight', 0.5f); + marko.addEdge('knows', josh, 'weight', 1.0f); + marko.addEdge('created', lop, 'weight', 0.4f); + josh.addEdge('created', ripple, 'weight', 1.0f); + josh.addEdge('created', lop, 'weight', 0.4f); + peter.addEdge('created', lop, 'weight', 0.2f);'''] + + return "\n".join(queries) + + @staticmethod + def multiple_fields(): + query_params = {} + queries= [ALLOW_SCANS, + '''schema.propertyKey('shortvalue').Smallint().ifNotExists().create(); + schema.vertexLabel('shortvertex').properties('shortvalue').ifNotExists().create(); + short s1 = 5000; graph.addVertex(label, "shortvertex", "shortvalue", s1); + schema.propertyKey('intvalue').Int().ifNotExists().create(); + schema.vertexLabel('intvertex').properties('intvalue').ifNotExists().create(); + int i1 = 1000000000; graph.addVertex(label, "intvertex", "intvalue", i1); + schema.propertyKey('intvalue2').Int().ifNotExists().create(); + schema.vertexLabel('intvertex2').properties('intvalue2').ifNotExists().create(); + Integer i2 = 100000000; graph.addVertex(label, "intvertex2", "intvalue2", i2); + schema.propertyKey('longvalue').Bigint().ifNotExists().create(); + schema.vertexLabel('longvertex').properties('longvalue').ifNotExists().create(); + long l1 = 9223372036854775807; graph.addVertex(label, "longvertex", "longvalue", l1); + schema.propertyKey('longvalue2').Bigint().ifNotExists().create(); + schema.vertexLabel('longvertex2').properties('longvalue2').ifNotExists().create(); + Long l2 = 100000000000000000L; graph.addVertex(label, "longvertex2", "longvalue2", l2); + schema.propertyKey('floatvalue').Float().ifNotExists().create(); + schema.vertexLabel('floatvertex').properties('floatvalue').ifNotExists().create(); + float f1 = 3.5f; graph.addVertex(label, "floatvertex", "floatvalue", f1); + schema.propertyKey('doublevalue').Double().ifNotExists().create(); + schema.vertexLabel('doublevertex').properties('doublevalue').ifNotExists().create(); + double d1 = 3.5e40; graph.addVertex(label, "doublevertex", "doublevalue", d1); + schema.propertyKey('doublevalue2').Double().ifNotExists().create(); + schema.vertexLabel('doublevertex2').properties('doublevalue2').ifNotExists().create(); + Double d2 = 3.5e40d; graph.addVertex(label, "doublevertex2", "doublevalue2", d2);'''] + + if DSE_VERSION >= Version('5.1'): + queries.append('''schema.propertyKey('datevalue1').Date().ifNotExists().create(); + schema.vertexLabel('datevertex1').properties('datevalue1').ifNotExists().create(); + schema.propertyKey('negdatevalue2').Date().ifNotExists().create(); + schema.vertexLabel('negdatevertex2').properties('negdatevalue2').ifNotExists().create();''') + + for i in range(1, 4): + queries.append('''schema.propertyKey('timevalue{0}').Time().ifNotExists().create(); + schema.vertexLabel('timevertex{0}').properties('timevalue{0}').ifNotExists().create();'''.format( + i)) + + queries.append('graph.addVertex(label, "datevertex1", "datevalue1", date1);') + query_params['date1'] = '1999-07-29' + + queries.append('graph.addVertex(label, "negdatevertex2", "negdatevalue2", date2);') + query_params['date2'] = '-1999-07-28' + + queries.append('graph.addVertex(label, "timevertex1", "timevalue1", time1);') + query_params['time1'] = '14:02' + queries.append('graph.addVertex(label, "timevertex2", "timevalue2", time2);') + query_params['time2'] = '14:02:20' + queries.append('graph.addVertex(label, "timevertex3", "timevalue3", time3);') + query_params['time3'] = '14:02:20.222' + + return queries, query_params + + @staticmethod + def large(): + query_parts = [''' + int size = 2000; + List ids = new ArrayList(); + schema.propertyKey('ts').Int().single().ifNotExists().create(); + schema.propertyKey('sin').Int().single().ifNotExists().create(); + schema.propertyKey('cos').Int().single().ifNotExists().create(); + schema.propertyKey('ii').Int().single().ifNotExists().create(); + schema.vertexLabel('lcg').properties('ts', 'sin', 'cos', 'ii').ifNotExists().create(); + schema.edgeLabel('linked').connection('lcg', 'lcg').ifNotExists().create(); + Vertex v = graph.addVertex(label, 'lcg'); + v.property("ts", 100001); + v.property("sin", 0); + v.property("cos", 1); + v.property("ii", 0); + ids.add(v.id()); + Random rand = new Random(); + for (int ii = 1; ii < size; ii++) { + v = graph.addVertex(label, 'lcg'); + v.property("ii", ii); + v.property("ts", 100001 + ii); + v.property("sin", Math.sin(ii/5.0)); + v.property("cos", Math.cos(ii/5.0)); + Vertex u = g.V(ids.get(rand.nextInt(ids.size()))).next(); + v.addEdge("linked", u); + ids.add(v.id()); + } + g.V().count();'''] + + return "\n".join(query_parts) + + @staticmethod + def address_book(): + p1 = "Point()" + p2 = "Point()" + if DSE_VERSION >= Version('5.1'): + p1 = "Point().withBounds(-100, -100, 100, 100)" + p2 = "Point().withGeoBounds()" + + queries = [ + ALLOW_SCANS, + "schema.propertyKey('name').Text().ifNotExists().create()", + "schema.propertyKey('pointPropWithBoundsWithSearchIndex').{}.ifNotExists().create()".format(p1), + "schema.propertyKey('pointPropWithBounds').{}.ifNotExists().create()".format(p1), + "schema.propertyKey('pointPropWithGeoBoundsWithSearchIndex').{}.ifNotExists().create()".format(p2), + "schema.propertyKey('pointPropWithGeoBounds').{}.ifNotExists().create()".format(p2), + "schema.propertyKey('city').Text().ifNotExists().create()", + "schema.propertyKey('state').Text().ifNotExists().create()", + "schema.propertyKey('description').Text().ifNotExists().create()", + "schema.vertexLabel('person').properties('name', 'city', 'state', 'description', 'pointPropWithBoundsWithSearchIndex', 'pointPropWithBounds', 'pointPropWithGeoBoundsWithSearchIndex', 'pointPropWithGeoBounds').ifNotExists().create()", + "schema.vertexLabel('person').index('searchPointWithBounds').secondary().by('pointPropWithBounds').ifNotExists().add()", + "schema.vertexLabel('person').index('searchPointWithGeoBounds').secondary().by('pointPropWithGeoBounds').ifNotExists().add()", + + "g.addV('person').property('name', 'Paul Thomas Joe').property('city', 'Rochester').property('state', 'MN').property('pointPropWithBoundsWithSearchIndex', Geo.point(-92.46295, 44.0234)).property('pointPropWithBounds', Geo.point(-92.46295, 44.0234)).property('pointPropWithGeoBoundsWithSearchIndex', Geo.point(-92.46295, 44.0234)).property('pointPropWithGeoBounds', Geo.point(-92.46295, 44.0234)).property('description', 'Lives by the hospital').next()", + "g.addV('person').property('name', 'George Bill Steve').property('city', 'Minneapolis').property('state', 'MN').property('pointPropWithBoundsWithSearchIndex', Geo.point(-93.266667, 44.093333)).property('pointPropWithBounds', Geo.point(-93.266667, 44.093333)).property('pointPropWithGeoBoundsWithSearchIndex', Geo.point(-93.266667, 44.093333)).property('pointPropWithGeoBounds', Geo.point(-93.266667, 44.093333)).property('description', 'A cold dude').next()", + "g.addV('person').property('name', 'James Paul Smith').property('city', 'Chicago').property('state', 'IL').property('pointPropWithBoundsWithSearchIndex', Geo.point(-87.684722, 41.836944)).property('description', 'Likes to hang out').next()", + "g.addV('person').property('name', 'Jill Alice').property('city', 'Atlanta').property('state', 'GA').property('pointPropWithBoundsWithSearchIndex', Geo.point(-84.39, 33.755)).property('description', 'Enjoys a nice cold coca cola').next()" + ] + + if not Version('5.0') <= DSE_VERSION < Version('5.1'): + queries.append("schema.vertexLabel('person').index('search').search().by('pointPropWithBoundsWithSearchIndex').withError(0.00001, 0.0).by('pointPropWithGeoBoundsWithSearchIndex').withError(0.00001, 0.0).ifNotExists().add()") + + return "\n".join(queries) + + +class CoreGraphFixtures(GraphFixtures): + + @staticmethod + def datatypes(): + data = ClassicGraphFixtures.datatypes() + del data['duration1'] + del data['duration2'] + + # Core Graphs only types + data["map1"] = ["mapOf(Text, Text)", {'test': 'test'}, None] + data["map2"] = ["mapOf(Text, Point)", {'test': Point(.5, .13)}, None] + data["map3"] = ["frozen(mapOf(Int, Varchar))", {42: 'test'}, None] + + data["list1"] = ["listOf(Text)", ['test', 'hello', 'world'], None] + data["list2"] = ["listOf(Int)", [42, 632, 32], None] + data["list3"] = ["listOf(Point)", [Point(.5, .13), Point(42.5, .13)], None] + data["list4"] = ["frozen(listOf(Int))", [42, 55, 33], None] + + data["set1"] = ["setOf(Text)", {'test', 'hello', 'world'}, None] + data["set2"] = ["setOf(Int)", {42, 632, 32}, None] + data["set3"] = ["setOf(Point)", {Point(.5, .13), Point(42.5, .13)}, None] + data["set4"] = ["frozen(setOf(Int))", {42, 55, 33}, None] + + data["tuple1"] = ["tupleOf(Int, Text)", (42, "world"), None] + data["tuple2"] = ["tupleOf(Int, tupleOf(Text, tupleOf(Text, Point)))", (42, ("world", ('this', Point(.5, .13)))), None] + data["tuple3"] = ["tupleOf(Int, tupleOf(Text, frozen(mapOf(Text, Text))))", (42, ("world", {'test': 'test'})), None] + data["tuple4"] = ["tupleOf(Int, tupleOf(Text, frozen(listOf(Int))))", (42, ("world", [65, 89])), None] + data["tuple5"] = ["tupleOf(Int, tupleOf(Text, frozen(setOf(Int))))", (42, ("world", {65, 55})), None] + data["tuple6"] = ["tupleOf(Int, tupleOf(Text, tupleOf(Text, LineString)))", + (42, ("world", ('this', LineString(((1.0, 2.0), (3.0, 4.0), (-89.0, 90.0)))))), None] + + data["tuple7"] = ["tupleOf(Int, tupleOf(Text, tupleOf(Text, Polygon)))", + (42, ("world", ('this', Polygon([(10.0, 10.0), (80.0, 10.0), (80., 88.0), (10., 89.0), (10., 10.0)], + [[(20., 20.0), (20., 30.0), (30., 30.0), (30., 20.0), (20., 20.0)], + [(40., 20.0), (40., 30.0), (50., 30.0), (50., 20.0), (40., 20.0)]])))), None] + data["dse_duration1"] = ["Duration()", Duration(42, 12, 10303312), None] + data["dse_duration2"] = ["Duration()", Duration(50, 32, 11), None] + + return data + + @staticmethod + def line(length, single_script=False): + queries = [""" + schema.vertexLabel('lp').ifNotExists().partitionBy('index', Int).create(); + schema.edgeLabel('goesTo').ifNotExists().from('lp').to('lp').property('distance', Int).create(); + """] + + vertex_script = ["g.addV('lp').property('index', 0).next();"] + for index in range(1, length): + if not single_script and len(vertex_script) > 25: + queries.append("\n".join(vertex_script)) + vertex_script = [] + + vertex_script.append(''' + g.addV('lp').property('index', {index}).next(); + g.V().hasLabel('lp').has('index', {pindex}).as('pp').V().hasLabel('lp').has('index', {index}).as('p'). + addE('goesTo').from('pp').to('p').property('distance', 5).next(); + '''.format( + index=index, pindex=index - 1)) + + queries.append("\n".join(vertex_script)) + return queries + + @staticmethod + def classic(): + queries = [ + ''' + schema.vertexLabel('person').ifNotExists().partitionBy('name', Text).property('age', Int).create(); + schema.vertexLabel('software')ifNotExists().partitionBy('name', Text).property('lang', Text).create(); + schema.edgeLabel('created').ifNotExists().from('person').to('software').property('weight', Double).create(); + schema.edgeLabel('knows').ifNotExists().from('person').to('person').property('weight', Double).create(); + ''', + + ''' + Vertex marko = g.addV('person').property('name', 'marko').property('age', 29).next(); + Vertex vadas = g.addV('person').property('name', 'vadas').property('age', 27).next(); + Vertex lop = g.addV('software').property('name', 'lop').property('lang', 'java').next(); + Vertex josh = g.addV('person').property('name', 'josh').property('age', 32).next(); + Vertex peter = g.addV('person').property('name', 'peter').property('age', 35).next(); + Vertex carl = g.addV('person').property('name', 'carl').property('age', 35).next(); + Vertex ripple = g.addV('software').property('name', 'ripple').property('lang', 'java').next(); + + // TODO, switch to VertexReference and use v.id() + g.V().hasLabel('person').has('name', 'vadas').as('v').V().hasLabel('person').has('name', 'marko').as('m').addE('knows').from('m').to('v').property('weight', 0.5d).next(); + g.V().hasLabel('person').has('name', 'josh').as('j').V().hasLabel('person').has('name', 'marko').as('m').addE('knows').from('m').to('j').property('weight', 1.0d).next(); + g.V().hasLabel('software').has('name', 'lop').as('l').V().hasLabel('person').has('name', 'marko').as('m').addE('created').from('m').to('l').property('weight', 0.4d).next(); + g.V().hasLabel('software').has('name', 'ripple').as('r').V().hasLabel('person').has('name', 'josh').as('j').addE('created').from('j').to('r').property('weight', 1.0d).next(); + g.V().hasLabel('software').has('name', 'lop').as('l').V().hasLabel('person').has('name', 'josh').as('j').addE('created').from('j').to('l').property('weight', 0.4d).next(); + g.V().hasLabel('software').has('name', 'lop').as('l').V().hasLabel('person').has('name', 'peter').as('p').addE('created').from('p').to('l').property('weight', 0.2d).next(); + + '''] + + return queries + + @staticmethod + def multiple_fields(): + ## no generic test currently needs this + raise NotImplementedError() + + @staticmethod + def large(): + query_parts = [ + ''' + schema.vertexLabel('lcg').ifNotExists().partitionBy('ts', Int).property('sin', Double). + property('cos', Double).property('ii', Int).create(); + schema.edgeLabel('linked').ifNotExists().from('lcg').to('lcg').create(); + ''', + + ''' + int size = 2000; + List ids = new ArrayList(); + v = g.addV('lcg').property('ts', 100001).property('sin', 0d).property('cos', 1d).property('ii', 0).next(); + ids.add(v.id()); + Random rand = new Random(); + for (int ii = 1; ii < size; ii++) { + v = g.addV('lcg').property('ts', 100001 + ii).property('sin', Math.sin(ii/5.0)).property('cos', Math.cos(ii/5.0)).property('ii', ii).next(); + + uid = ids.get(rand.nextInt(ids.size())) + g.V(v.id()).as('v').V(uid).as('u').addE('linked').from('v').to('u').next(); + ids.add(v.id()); + } + g.V().count();''' + ] + + return query_parts + + @staticmethod + def address_book(): + queries = [ + "schema.vertexLabel('person').ifNotExists().partitionBy('name', Text)." + "property('pointPropWithBoundsWithSearchIndex', Point)." + "property('pointPropWithBounds', Point)." + "property('pointPropWithGeoBoundsWithSearchIndex', Point)." + "property('pointPropWithGeoBounds', Point)." + "property('city', Text)." + "property('state', Text)." + "property('description', Text).create()", + "schema.vertexLabel('person').searchIndex().by('name').by('pointPropWithBounds').by('pointPropWithGeoBounds').by('description').asText().create()", + "g.addV('person').property('name', 'Paul Thomas Joe').property('city', 'Rochester').property('state', 'MN').property('pointPropWithBoundsWithSearchIndex', Geo.point(-92.46295, 44.0234)).property('pointPropWithBounds', Geo.point(-92.46295, 44.0234)).property('pointPropWithGeoBoundsWithSearchIndex', Geo.point(-92.46295, 44.0234)).property('pointPropWithGeoBounds', Geo.point(-92.46295, 44.0234)).property('description', 'Lives by the hospital').next()", + "g.addV('person').property('name', 'George Bill Steve').property('city', 'Minneapolis').property('state', 'MN').property('pointPropWithBoundsWithSearchIndex', Geo.point(-93.266667, 44.093333)).property('pointPropWithBounds', Geo.point(-93.266667, 44.093333)).property('pointPropWithGeoBoundsWithSearchIndex', Geo.point(-93.266667, 44.093333)).property('pointPropWithGeoBounds', Geo.point(-93.266667, 44.093333)).property('description', 'A cold dude').next()", + "g.addV('person').property('name', 'James Paul Smith').property('city', 'Chicago').property('state', 'IL').property('pointPropWithBoundsWithSearchIndex', Geo.point(-87.684722, 41.836944)).property('description', 'Likes to hang out').next()", + "g.addV('person').property('name', 'Jill Alice').property('city', 'Atlanta').property('state', 'GA').property('pointPropWithBoundsWithSearchIndex', Geo.point(-84.39, 33.755)).property('description', 'Enjoys a nice cold coca cola').next()" + ] + + if not Version('5.0') <= DSE_VERSION < Version('5.1'): + queries.append("schema.vertexLabel('person').searchIndex().by('pointPropWithBoundsWithSearchIndex').by('pointPropWithGeoBounds')" + ".by('pointPropWithGeoBoundsWithSearchIndex').create()") + + return queries + + +def validate_classic_vertex(test, vertex): + vertex_props = vertex.properties.keys() + test.assertEqual(len(vertex_props), 2) + test.assertIn('name', vertex_props) + test.assertTrue('lang' in vertex_props or 'age' in vertex_props) + + +def validate_classic_vertex_return_type(test, vertex): + validate_generic_vertex_result_type(vertex) + vertex_props = vertex.properties + test.assertIn('name', vertex_props) + test.assertTrue('lang' in vertex_props or 'age' in vertex_props) + + +def validate_generic_vertex_result_type(test, vertex): + test.assertIsInstance(vertex, Vertex) + for attr in ('id', 'type', 'label', 'properties'): + test.assertIsNotNone(getattr(vertex, attr)) + + +def validate_classic_edge_properties(test, edge_properties): + test.assertEqual(len(edge_properties.keys()), 1) + test.assertIn('weight', edge_properties) + test.assertIsInstance(edge_properties, dict) + + +def validate_classic_edge(test, edge): + validate_generic_edge_result_type(test, edge) + validate_classic_edge_properties(test, edge.properties) + + +def validate_line_edge(test, edge): + validate_generic_edge_result_type(test, edge) + edge_props = edge.properties + test.assertEqual(len(edge_props.keys()), 1) + test.assertIn('distance', edge_props) + + +def validate_generic_edge_result_type(test, edge): + test.assertIsInstance(edge, Edge) + for attr in ('properties', 'outV', 'outVLabel', 'inV', 'inVLabel', 'label', 'type', 'id'): + test.assertIsNotNone(getattr(edge, attr)) + + +def validate_path_result_type(test, path): + test.assertIsInstance(path, Path) + test.assertIsNotNone(path.labels) + for obj in path.objects: + if isinstance(obj, Edge): + validate_classic_edge(test, obj) + elif isinstance(obj, Vertex): + validate_classic_vertex(test, obj) + else: + test.fail("Invalid object found in path " + str(object.type)) + + +class GraphTestConfiguration(object): + """Possible Configurations: + ClassicGraphSchema: + graphson1 + graphson2 + graphson3 + + CoreGraphSchema + graphson3 + """ + + @classmethod + def schemas(cls): + schemas = [ClassicGraphSchema] + if DSE_VERSION >= Version("6.8"): + schemas.append(CoreGraphSchema) + return schemas + + @classmethod + def graphson_versions(cls): + graphson_versions = [GraphProtocol.GRAPHSON_1_0] + if DSE_VERSION >= Version("6.0"): + graphson_versions.append(GraphProtocol.GRAPHSON_2_0) + if DSE_VERSION >= Version("6.8"): + graphson_versions.append(GraphProtocol.GRAPHSON_3_0) + return graphson_versions + + @classmethod + def schema_configurations(cls, schema=None): + schemas = cls.schemas() if schema is None else [schema] + configurations = [] + for s in schemas: + configurations.append(s) + + return configurations + + @classmethod + def configurations(cls, schema=None, graphson=None): + schemas = cls.schemas() if schema is None else [schema] + graphson_versions = cls.graphson_versions() if graphson is None else [graphson] + + configurations = [] + for s in schemas: + for g in graphson_versions: + if s is CoreGraphSchema and g != GraphProtocol.GRAPHSON_3_0: + continue + configurations.append((s, g)) + + return configurations + + @staticmethod + def _make_graph_schema_test_method(func, schema): + def test_input(self): + self.setup_graph(schema) + try: + func(self, schema) + except: + raise + finally: + self.teardown_graph(schema) + + schema_name = 'classic' if schema is ClassicGraphSchema else 'core' + test_input.__name__ = '{func}_{schema}'.format( + func=func.__name__.lstrip('_'), schema=schema_name) + return test_input + + @staticmethod + def _make_graph_test_method(func, schema, graphson): + def test_input(self): + self.setup_graph(schema) + try: + func(self, schema, graphson) + except: + raise + finally: + self.teardown_graph(schema) + + graphson_name = 'graphson1' + if graphson == GraphProtocol.GRAPHSON_2_0: + graphson_name = 'graphson2' + elif graphson == GraphProtocol.GRAPHSON_3_0: + graphson_name = 'graphson3' + + schema_name = 'classic' if schema is ClassicGraphSchema else 'core' + + # avoid keyspace name too long issue + if DSE_VERSION < Version('6.7'): + schema_name = schema_name[0] + graphson_name = 'g' + graphson_name[-1] + + test_input.__name__ = '{func}_{schema}_{graphson}'.format( + func=func.__name__.lstrip('_'), schema=schema_name, graphson=graphson_name) + return test_input + + @classmethod + def generate_tests(cls, schema=None, graphson=None, traversal=False): + """Generate tests for a graph configuration""" + def decorator(klass): + if DSE_VERSION: + predicate = inspect.ismethod if six.PY2 else inspect.isfunction + for name, func in inspect.getmembers(klass, predicate=predicate): + if not name.startswith('_test'): + continue + for _schema, _graphson in cls.configurations(schema, graphson): + if traversal and _graphson == GraphProtocol.GRAPHSON_1_0: + continue + test_input = cls._make_graph_test_method(func, _schema, _graphson) + log.debug("Generated test '{}.{}'".format(klass.__name__, test_input.__name__)) + setattr(klass, test_input.__name__, test_input) + return klass + + return decorator + + @classmethod + def generate_schema_tests(cls, schema=None): + """Generate schema tests for a graph configuration""" + def decorator(klass): + if DSE_VERSION: + predicate = inspect.ismethod if six.PY2 else inspect.isfunction + for name, func in inspect.getmembers(klass, predicate=predicate): + if not name.startswith('_test'): + continue + for _schema in cls.schema_configurations(schema): + test_input = cls._make_graph_schema_test_method(func, _schema) + log.debug("Generated test '{}.{}'".format(klass.__name__, test_input.__name__)) + setattr(klass, test_input.__name__, test_input) + return klass + + return decorator + + +class VertexLabel(object): + """ + Helper that represents a new VertexLabel: + + VertexLabel(['Int()', 'Float()']) # a vertex with 2 properties named property1 and property2 + VertexLabel([('int1', 'Int()'), 'Float()']) # a vertex with 2 properties named int1 and property1 + """ + + id = 0 + label = None + properties = None + + def __init__(self, properties): + VertexLabel.id += 1 + self.id = VertexLabel.id + self.label = "vertex{}".format(self.id) + self.properties = {'pkid': self.id} + property_count = 0 + for p in properties: + if isinstance(p, tuple): + name, typ = p + else: + property_count += 1 + name = "property-v{}-{}".format(self.id, property_count) + typ = p + self.properties[name] = typ + + @property + def non_pk_properties(self): + return {p: v for p, v in six.iteritems(self.properties) if p != 'pkid'} + + +class GraphSchema(object): + + has_geo_bounds = DSE_VERSION and DSE_VERSION >= Version('5.1') + fixtures = GraphFixtures + + @classmethod + def sanitize_type(cls, typ): + if typ.lower().startswith("point"): + return cls.sanitize_point_type() + elif typ.lower().startswith("line"): + return cls.sanitize_line_type() + elif typ.lower().startswith("poly"): + return cls.sanitize_polygon_type() + else: + return typ + + @classmethod + def sanitize_point_type(cls): + return "Point().withGeoBounds()" if cls.has_geo_bounds else "Point()" + + @classmethod + def sanitize_line_type(cls): + return "Linestring().withGeoBounds()" if cls.has_geo_bounds else "Linestring()" + + @classmethod + def sanitize_polygon_type(cls): + return "Polygon().withGeoBounds()" if cls.has_geo_bounds else "Polygon()" + + @staticmethod + def drop_graph(session, graph_name): + ks = list(session.execute( + "SELECT * FROM system_schema.keyspaces WHERE keyspace_name = '{}';".format(graph_name))) + if not ks: + return + + try: + session.execute_graph('system.graph(name).drop()', {'name': graph_name}, + execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT) + except: + pass + + @staticmethod + def create_graph(session, graph_name): + raise NotImplementedError() + + @staticmethod + def clear(session): + pass + + @staticmethod + def create_vertex_label(session, vertex_label, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT): + raise NotImplementedError() + + @staticmethod + def add_vertex(session, vertex_label, name, value, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT): + raise NotImplementedError() + + @classmethod + def ensure_properties(cls, session, obj, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT): + if not isinstance(obj, (Vertex, Edge)): + return + + # This pre-processing is due to a change in TinkerPop + # properties are not returned automatically anymore + # with some queries. + if not obj.properties: + if isinstance(obj, Edge): + obj.properties = {} + for p in cls.get_edge_properties(session, obj, execution_profile=execution_profile): + obj.properties.update(p) + elif isinstance(obj, Vertex): + obj.properties = { + p.label: p + for p in cls.get_vertex_properties(session, obj, execution_profile=execution_profile) + } + + @staticmethod + def get_vertex_properties(session, vertex, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT): + return session.execute_graph("g.V(vertex_id).properties().toList()", {'vertex_id': vertex.id}, + execution_profile=execution_profile) + + @staticmethod + def get_edge_properties(session, edge, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT): + v = session.execute_graph("g.E(edge_id).properties().toList()", {'edge_id': edge.id}, + execution_profile=execution_profile) + return v + + +class ClassicGraphSchema(GraphSchema): + + fixtures = ClassicGraphFixtures + + @staticmethod + def create_graph(session, graph_name): + session.execute_graph(CREATE_CLASSIC_GRAPH, {'name': graph_name}, + execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT) + wait_for_graph_inserted(session, graph_name) + + @staticmethod + def clear(session): + session.execute_graph('schema.clear()') + + @classmethod + def create_vertex_label(cls, session, vertex_label, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT): + statements = ["schema.propertyKey('pkid').Int().ifNotExists().create();"] + for k, v in six.iteritems(vertex_label.non_pk_properties): + typ = cls.sanitize_type(v) + statements.append("schema.propertyKey('{name}').{type}.create();".format( + name=k, type=typ + )) + + statements.append("schema.vertexLabel('{label}').partitionKey('pkid').properties(".format( + label=vertex_label.label)) + property_names = [name for name in six.iterkeys(vertex_label.non_pk_properties)] + statements.append(", ".join(["'{}'".format(p) for p in property_names])) + statements.append(").create();") + + to_run = "\n".join(statements) + session.execute_graph(to_run, execution_profile=execution_profile) + + @staticmethod + def add_vertex(session, vertex_label, name, value, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT): + statement = "g.addV('{label}').property('pkid', {pkid}).property('{property_name}', val);".format( + pkid=vertex_label.id, label=vertex_label.label, property_name=name) + parameters = {'val': value} + return session.execute_graph(statement, parameters, execution_profile=execution_profile) + + +class CoreGraphSchema(GraphSchema): + + fixtures = CoreGraphFixtures + + @classmethod + def sanitize_type(cls, typ): + typ = super(CoreGraphSchema, cls).sanitize_type(typ) + return typ.replace('()', '') + + @classmethod + def sanitize_point_type(cls): + return "Point" + + @classmethod + def sanitize_line_type(cls): + return "LineString" + + @classmethod + def sanitize_polygon_type(cls): + return "Polygon" + + @staticmethod + def create_graph(session, graph_name): + session.execute_graph('system.graph(name).create()', {'name': graph_name}, + execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT) + wait_for_graph_inserted(session, graph_name) + + @classmethod + def create_vertex_label(cls, session, vertex_label, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT): + statements = ["schema.vertexLabel('{label}').partitionBy('pkid', Int)".format( + label=vertex_label.label)] + + for name, typ in six.iteritems(vertex_label.non_pk_properties): + typ = cls.sanitize_type(typ) + statements.append(".property('{name}', {type})".format(name=name, type=typ)) + statements.append(".create();") + + to_run = "\n".join(statements) + session.execute_graph(to_run, execution_profile=execution_profile) + + @staticmethod + def add_vertex(session, vertex_label, name, value, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT): + statement = "g.addV('{label}').property('pkid', {pkid}).property('{property_name}', val);".format( + pkid=vertex_label.id, label=vertex_label.label, property_name=name) + parameters = {'val': value} + return session.execute_graph(statement, parameters, execution_profile=execution_profile) diff --git a/tests/integration/advanced/graph/fluent/__init__.py b/tests/integration/advanced/graph/fluent/__init__.py new file mode 100644 index 0000000..3bb81e7 --- /dev/null +++ b/tests/integration/advanced/graph/fluent/__init__.py @@ -0,0 +1,722 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +import datetime +import six +import time +from collections import namedtuple +from packaging.version import Version + +from cassandra.datastax.graph.fluent import DseGraph +from cassandra.graph import VertexProperty, GraphProtocol +from cassandra.util import Point, Polygon, LineString + +from gremlin_python.process.graph_traversal import GraphTraversal, GraphTraversalSource +from gremlin_python.process.traversal import P +from gremlin_python.structure.graph import Edge as TravEdge +from gremlin_python.structure.graph import Vertex as TravVertex, VertexProperty as TravVertexProperty + +from tests.util import wait_until_not_raised +from tests.integration import DSE_VERSION +from tests.integration.advanced.graph import ( + GraphUnitTestCase, ClassicGraphSchema, CoreGraphSchema, + VertexLabel) +from tests.integration import requiredse + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + + +import ipaddress + + +def check_equality_base(testcase, original, read_value): + if isinstance(original, float): + testcase.assertAlmostEqual(original, read_value, delta=.01) + elif isinstance(original, ipaddress.IPv4Address): + testcase.assertAlmostEqual(original, ipaddress.IPv4Address(read_value)) + elif isinstance(original, ipaddress.IPv6Address): + testcase.assertAlmostEqual(original, ipaddress.IPv6Address(read_value)) + else: + testcase.assertEqual(original, read_value) + + +def create_traversal_profiles(cluster, graph_name): + ep_graphson2 = DseGraph().create_execution_profile( + graph_name, graph_protocol=GraphProtocol.GRAPHSON_2_0) + ep_graphson3 = DseGraph().create_execution_profile( + graph_name, graph_protocol=GraphProtocol.GRAPHSON_3_0) + + cluster.add_execution_profile('traversal_graphson2', ep_graphson2) + cluster.add_execution_profile('traversal_graphson3', ep_graphson3) + + return ep_graphson2, ep_graphson3 + + +class _AbstractTraversalTest(GraphUnitTestCase): + + def setUp(self): + super(_AbstractTraversalTest, self).setUp() + self.ep_graphson2, self.ep_graphson3 = create_traversal_profiles(self.cluster, self.graph_name) + + def _test_basic_query(self, schema, graphson): + """ + Test to validate that basic graph queries works + + Creates a simple classic tinkerpot graph, and attempts to preform a basic query + using Tinkerpop's GLV with both explicit and implicit execution + ensuring that each one is correct. See reference graph here + http://www.tinkerpop.com/docs/3.0.0.M1/ + + @since 1.0.0 + @jira_ticket PYTHON-641 + @expected_result graph should generate and all vertices and edge results should be + + @test_category dse graph + """ + + g = self.fetch_traversal_source(graphson) + self.execute_graph(schema.fixtures.classic(), graphson) + traversal = g.V().has('name', 'marko').out('knows').values('name') + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 2) + self.assertIn('vadas', results_list) + self.assertIn('josh', results_list) + + def _test_classic_graph(self, schema, graphson): + """ + Test to validate that basic graph generation, and vertex and edges are surfaced correctly + + Creates a simple classic tinkerpot graph, and iterates over the the vertices and edges + using Tinkerpop's GLV with both explicit and implicit execution + ensuring that each one iscorrect. See reference graph here + http://www.tinkerpop.com/docs/3.0.0.M1/ + + @since 1.0.0 + @jira_ticket PYTHON-641 + @expected_result graph should generate and all vertices and edge results should be + + @test_category dse graph + """ + + self.execute_graph(schema.fixtures.classic(), graphson) + ep = self.get_execution_profile(graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.V() + vert_list = self.execute_traversal(traversal, graphson) + + for vertex in vert_list: + schema.ensure_properties(self.session, vertex, execution_profile=ep) + self._validate_classic_vertex(g, vertex) + traversal = g.E() + edge_list = self.execute_traversal(traversal, graphson) + for edge in edge_list: + schema.ensure_properties(self.session, edge, execution_profile=ep) + self._validate_classic_edge(g, edge) + + def _test_graph_classic_path(self, schema, graphson): + """ + Test to validate that the path version of the result type is generated correctly. It also + tests basic path results as that is not covered elsewhere + + @since 1.0.0 + @jira_ticket PYTHON-641 + @expected_result path object should be unpacked correctly including all nested edges and vertices + @test_category dse graph + """ + self.execute_graph(schema.fixtures.classic(), graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.V().hasLabel('person').has('name', 'marko').as_('a').outE('knows').inV().as_('c', 'd').outE('created').as_('e', 'f', 'g').inV().path() + path_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(path_list), 2) + for path in path_list: + self._validate_path_result_type(g, path) + + def _test_range_query(self, schema, graphson): + """ + Test to validate range queries are handled correctly. + + Creates a very large line graph script and executes it. Then proceeds to to a range + limited query against it, and ensure that the results are formated correctly and that + the result set is properly sized. + + @since 1.0.0 + @jira_ticket PYTHON-641 + @expected_result result set should be properly formated and properly sized + + @test_category dse graph + """ + + self.execute_graph(schema.fixtures.line(150), graphson) + ep = self.get_execution_profile(graphson) + g = self.fetch_traversal_source(graphson) + + traversal = g.E().range(0, 10) + edges = self.execute_traversal(traversal, graphson) + self.assertEqual(len(edges), 10) + for edge in edges: + schema.ensure_properties(self.session, edge, execution_profile=ep) + self._validate_line_edge(g, edge) + + def _test_result_types(self, schema, graphson): + """ + Test to validate that the edge and vertex version of results are constructed correctly. + + @since 1.0.0 + @jira_ticket PYTHON-641 + @expected_result edge/vertex result types should be unpacked correctly. + @test_category dse graph + """ + self.execute_graph(schema.fixtures.line(150), graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.V() + vertices = self.execute_traversal(traversal, graphson) + for vertex in vertices: + self._validate_type(g, vertex) + + def _test_large_result_set(self, schema, graphson): + """ + Test to validate that large result sets return correctly. + + Creates a very large graph. Ensures that large result sets are handled appropriately. + + @since 1.0.0 + @jira_ticket PYTHON-641 + @expected_result when limits of result sets are hit errors should be surfaced appropriately + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.large(), graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.V() + vertices = self.execute_traversal(traversal, graphson) + for vertex in vertices: + self._validate_generic_vertex_result_type(g, vertex) + + def _test_vertex_meta_properties(self, schema, graphson): + """ + Test verifying vertex property properties + + @since 1.0.0 + @jira_ticket PYTHON-641 + + @test_category dse graph + """ + if schema is not ClassicGraphSchema: + raise unittest.SkipTest('skipped because multiple properties are only supported with classic graphs') + + s = self.session + s.execute_graph("schema.propertyKey('k0').Text().ifNotExists().create();") + s.execute_graph("schema.propertyKey('k1').Text().ifNotExists().create();") + s.execute_graph("schema.propertyKey('key').Text().properties('k0', 'k1').ifNotExists().create();") + s.execute_graph("schema.vertexLabel('MLP').properties('key').ifNotExists().create();") + s.execute_graph("schema.config().option('graph.allow_scan').set('true');") + v = s.execute_graph('''v = graph.addVertex('MLP') + v.property('key', 'meta_prop', 'k0', 'v0', 'k1', 'v1') + v''')[0] + + g = self.fetch_traversal_source(graphson) + + traversal = g.V() + # This should contain key, and value where value is a property + # This should be a vertex property and should contain sub properties + results = self.execute_traversal(traversal, graphson) + self._validate_meta_property(g, results[0]) + + def _test_vertex_multiple_properties(self, schema, graphson): + """ + Test verifying vertex property form for various Cardinality + + All key types are encoded as a list, regardless of cardinality + + Single cardinality properties have only one value -- the last one added + + Default is single (this is config dependent) + + @since 1.0.0 + @jira_ticket PYTHON-641 + + @test_category dse graph + """ + if schema is not ClassicGraphSchema: + raise unittest.SkipTest('skipped because multiple properties are only supported with classic graphs') + + s = self.session + s.execute_graph('''Schema schema = graph.schema(); + schema.propertyKey('mult_key').Text().multiple().ifNotExists().create(); + schema.propertyKey('single_key').Text().single().ifNotExists().create(); + schema.vertexLabel('MPW1').properties('mult_key').ifNotExists().create(); + schema.vertexLabel('MPW2').properties('mult_key').ifNotExists().create(); + schema.vertexLabel('SW1').properties('single_key').ifNotExists().create();''') + + mpw1v = s.execute_graph('''v = graph.addVertex('MPW1') + v.property('mult_key', 'value') + v''')[0] + + mpw2v = s.execute_graph('''g.addV('MPW2').property('mult_key', 'value0').property('mult_key', 'value1')''')[0] + + g = self.fetch_traversal_source(graphson) + traversal = g.V(mpw1v.id).properties() + + vertex_props = self.execute_traversal(traversal, graphson) + + self.assertEqual(len(vertex_props), 1) + + self.assertEqual(self.fetch_key_from_prop(vertex_props[0]), "mult_key") + self.assertEqual(vertex_props[0].value, "value") + + # multiple_with_two_values + #v = s.execute_graph('''g.addV(label, 'MPW2', 'mult_key', 'value0', 'mult_key', 'value1')''')[0] + traversal = g.V(mpw2v.id).properties() + + vertex_props = self.execute_traversal(traversal, graphson) + + self.assertEqual(len(vertex_props), 2) + self.assertEqual(self.fetch_key_from_prop(vertex_props[0]), 'mult_key') + self.assertEqual(self.fetch_key_from_prop(vertex_props[1]), 'mult_key') + self.assertEqual(vertex_props[0].value, 'value0') + self.assertEqual(vertex_props[1].value, 'value1') + + # single_with_one_value + v = s.execute_graph('''v = graph.addVertex('SW1') + v.property('single_key', 'value') + v''')[0] + traversal = g.V(v.id).properties() + vertex_props = self.execute_traversal(traversal, graphson) + self.assertEqual(len(vertex_props), 1) + self.assertEqual(self.fetch_key_from_prop(vertex_props[0]), "single_key") + self.assertEqual(vertex_props[0].value, "value") + + def should_parse_meta_properties(self): + g = self.fetch_traversal_source() + g.addV("meta_v").property("meta_prop", "hello", "sub_prop", "hi", "sub_prop2", "hi2") + + def _test_all_graph_types_with_schema(self, schema, graphson): + """ + Exhaustively goes through each type that is supported by dse_graph. + creates a vertex for each type using a dse-tinkerpop traversal, + It then attempts to fetch it from the server and compares it to what was inserted + Prime the graph with the correct schema first + + @since 1.0.0 + @jira_ticket PYTHON-641 + @expected_result inserted objects are equivalent to those retrieved + + @test_category dse graph + """ + self._write_and_read_data_types(schema, graphson) + + def _test_all_graph_types_without_schema(self, schema, graphson): + """ + Exhaustively goes through each type that is supported by dse_graph. + creates a vertex for each type using a dse-tinkerpop traversal, + It then attempts to fetch it from the server and compares it to what was inserted + Do not prime the graph with the correct schema first + @since 1.0.0 + @jira_ticket PYTHON-641 + @expected_result inserted objects are equivalent to those retrieved + @test_category dse graph + """ + if schema is not ClassicGraphSchema: + raise unittest.SkipTest('schema-less is only for classic graphs') + self._write_and_read_data_types(schema, graphson, use_schema=False) + + def _test_dsl(self, schema, graphson): + """ + The test creates a SocialTraversal and a SocialTraversalSource as part of + a DSL. Then calls it's method and checks the results to verify + we have the expected results + + @since @since 1.1.0a1 + @jira_ticket PYTHON-790 + @expected_result only the vertex corresponding to marko is in the result + + @test_category dse graph + """ + class SocialTraversal(GraphTraversal): + def knows(self, person_name): + return self.out("knows").hasLabel("person").has("name", person_name).in_() + + class SocialTraversalSource(GraphTraversalSource): + def __init__(self, *args, **kwargs): + super(SocialTraversalSource, self).__init__(*args, **kwargs) + self.graph_traversal = SocialTraversal + + def people(self, *names): + return self.get_graph_traversal().V().has("name", P.within(*names)) + + self.execute_graph(schema.fixtures.classic(), graphson) + if schema is CoreGraphSchema: + self.execute_graph(""" + schema.edgeLabel('knows').from('person').to('person').materializedView('person__knows__person_by_in_name'). + ifNotExists().partitionBy('in_name').clusterBy('out_name', Asc).create() + """, graphson) + time.sleep(1) # give some time to the MV to be populated + g = self.fetch_traversal_source(graphson, traversal_class=SocialTraversalSource) + + traversal = g.people("marko", "albert").knows("vadas") + results = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results), 1) + only_vertex = results[0] + schema.ensure_properties(self.session, only_vertex, + execution_profile=self.get_execution_profile(graphson)) + self._validate_classic_vertex(g, only_vertex) + + def _test_bulked_results(self, schema, graphson): + """ + Send a query expecting a bulked result and the driver "undoes" + the bulk and returns the expected list + + @since 1.1.0a1 + @jira_ticket PYTHON-771 + @expected_result the expanded list + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.classic(), graphson) + g = self.fetch_traversal_source(graphson) + barrier_traversal = g.E().label().barrier() + results = self.execute_traversal(barrier_traversal, graphson) + self.assertEqual(sorted(["created", "created", "created", "created", "knows", "knows"]), sorted(results)) + + def _test_udt_with_classes(self, schema, graphson): + class Address(object): + + def __init__(self, address, city, state): + self.address = address + self.city = city + self.state = state + + def __eq__(self, other): + return self.address == other.address and self.city == other.city and self.state == other.state + + class AddressWithTags(object): + + def __init__(self, address, city, state, tags): + self.address = address + self.city = city + self.state = state + self.tags = tags + + def __eq__(self, other): + return (self.address == other.address and self.city == other.city + and self.state == other.state and self.tags == other.tags) + + class ComplexAddress(object): + + def __init__(self, address, address_tags, city, state, props): + self.address = address + self.address_tags = address_tags + self.city = city + self.state = state + self.props = props + + def __eq__(self, other): + return (self.address == other.address and self.address_tags == other.address_tags + and self.city == other.city and self.state == other.state + and self.props == other.props) + + class ComplexAddressWithOwners(object): + + def __init__(self, address, address_tags, city, state, props, owners): + self.address = address + self.address_tags = address_tags + self.city = city + self.state = state + self.props = props + self.owners = owners + + def __eq__(self, other): + return (self.address == other.address and self.address_tags == other.address_tags + and self.city == other.city and self.state == other.state + and self.props == other.props and self.owners == other.owners) + + self.__test_udt(schema, graphson, Address, AddressWithTags, ComplexAddress, ComplexAddressWithOwners) + + def _test_udt_with_namedtuples(self, schema, graphson): + AddressTuple = namedtuple('Address', ('address', 'city', 'state')) + AddressWithTagsTuple = namedtuple('AddressWithTags', ('address', 'city', 'state', 'tags')) + ComplexAddressTuple = namedtuple('ComplexAddress', ('address', 'address_tags', 'city', 'state', 'props')) + ComplexAddressWithOwnersTuple = namedtuple('ComplexAddressWithOwners', ('address', 'address_tags', 'city', + 'state', 'props', 'owners')) + + self.__test_udt(schema, graphson, AddressTuple, AddressWithTagsTuple, + ComplexAddressTuple, ComplexAddressWithOwnersTuple) + + def _write_and_read_data_types(self, schema, graphson, use_schema=True): + g = self.fetch_traversal_source(graphson) + ep = self.get_execution_profile(graphson) + for data in six.itervalues(schema.fixtures.datatypes()): + typ, value, deserializer = data + vertex_label = VertexLabel([typ]) + property_name = next(six.iterkeys(vertex_label.non_pk_properties)) + if use_schema or schema is CoreGraphSchema: + schema.create_vertex_label(self.session, vertex_label, execution_profile=ep) + + write_traversal = g.addV(str(vertex_label.label)).property('pkid', vertex_label.id).\ + property(property_name, value) + self.execute_traversal(write_traversal, graphson) + + read_traversal = g.V().hasLabel(str(vertex_label.label)).has(property_name).properties() + results = self.execute_traversal(read_traversal, graphson) + + for result in results: + if result.label == 'pkid': + continue + self._check_equality(g, value, result.value) + + def __test_udt(self, schema, graphson, address_class, address_with_tags_class, + complex_address_class, complex_address_with_owners_class): + if schema is not CoreGraphSchema or DSE_VERSION < Version('6.8'): + raise unittest.SkipTest("Graph UDT is only supported with DSE 6.8+ and Core graphs.") + + ep = self.get_execution_profile(graphson) + + Address = address_class + AddressWithTags = address_with_tags_class + ComplexAddress = complex_address_class + ComplexAddressWithOwners = complex_address_with_owners_class + + # setup udt + self.session.execute_graph(""" + schema.type('address').property('address', Text).property('city', Text).property('state', Text).create(); + schema.type('addressTags').property('address', Text).property('city', Text).property('state', Text). + property('tags', setOf(Text)).create(); + schema.type('complexAddress').property('address', Text).property('address_tags', frozen(typeOf('addressTags'))). + property('city', Text).property('state', Text).property('props', mapOf(Text, Int)).create(); + schema.type('complexAddressWithOwners').property('address', Text). + property('address_tags', frozen(typeOf('addressTags'))). + property('city', Text).property('state', Text).property('props', mapOf(Text, Int)). + property('owners', frozen(listOf(tupleOf(Text, Int)))).create(); + """, execution_profile=ep) + + # wait max 10 seconds to get the UDT discovered. + wait_until_not_raised( + lambda: self.session.cluster.register_user_type(self.graph_name, 'address', Address), + 1, 10) + wait_until_not_raised( + lambda: self.session.cluster.register_user_type(self.graph_name, 'addressTags', AddressWithTags), + 1, 10) + wait_until_not_raised( + lambda: self.session.cluster.register_user_type(self.graph_name, 'complexAddress', ComplexAddress), + 1, 10) + wait_until_not_raised( + lambda: self.session.cluster.register_user_type(self.graph_name, 'complexAddressWithOwners', ComplexAddressWithOwners), + 1, 10) + + data = { + "udt1": ["typeOf('address')", Address('1440 Rd Smith', 'Quebec', 'QC')], + "udt2": ["tupleOf(typeOf('address'), Text)", (Address('1440 Rd Smith', 'Quebec', 'QC'), 'hello')], + "udt3": ["tupleOf(frozen(typeOf('address')), Text)", (Address('1440 Rd Smith', 'Quebec', 'QC'), 'hello')], + "udt4": ["tupleOf(tupleOf(Int, typeOf('address')), Text)", + ((42, Address('1440 Rd Smith', 'Quebec', 'QC')), 'hello')], + "udt5": ["tupleOf(tupleOf(Int, typeOf('addressTags')), Text)", + ((42, AddressWithTags('1440 Rd Smith', 'Quebec', 'QC', {'t1', 't2'})), 'hello')], + "udt6": ["tupleOf(tupleOf(Int, typeOf('complexAddress')), Text)", + ((42, ComplexAddress('1440 Rd Smith', + AddressWithTags('1440 Rd Smith', 'Quebec', 'QC', {'t1', 't2'}), + 'Quebec', 'QC', {'p1': 42, 'p2': 33})), 'hello')], + "udt7": ["tupleOf(tupleOf(Int, frozen(typeOf('complexAddressWithOwners'))), Text)", + ((42, ComplexAddressWithOwners( + '1440 Rd Smith', + AddressWithTags('1440 CRd Smith', 'Quebec', 'QC', {'t1', 't2'}), + 'Quebec', 'QC', {'p1': 42, 'p2': 33}, [('Mike', 43), ('Gina', 39)]) + ), 'hello')] + } + + g = self.fetch_traversal_source(graphson) + for typ, value in six.itervalues(data): + vertex_label = VertexLabel([typ]) + property_name = next(six.iterkeys(vertex_label.non_pk_properties)) + schema.create_vertex_label(self.session, vertex_label, execution_profile=ep) + + write_traversal = g.addV(str(vertex_label.label)).property('pkid', vertex_label.id). \ + property(property_name, value) + self.execute_traversal(write_traversal, graphson) + + #vertex = list(schema.add_vertex(self.session, vertex_label, property_name, value, execution_profile=ep))[0] + #vertex_properties = list(schema.get_vertex_properties( + # self.session, vertex, execution_profile=ep)) + + read_traversal = g.V().hasLabel(str(vertex_label.label)).has(property_name).properties() + vertex_properties = self.execute_traversal(read_traversal, graphson) + + self.assertEqual(len(vertex_properties), 2) # include pkid + for vp in vertex_properties: + if vp.label == 'pkid': + continue + + self.assertIsInstance(vp, (VertexProperty, TravVertexProperty)) + self.assertEqual(vp.label, property_name) + self.assertEqual(vp.value, value) + + @staticmethod + def fetch_edge_props(g, edge): + edge_props = g.E(edge.id).properties().toList() + return edge_props + + @staticmethod + def fetch_vertex_props(g, vertex): + + vertex_props = g.V(vertex.id).properties().toList() + return vertex_props + + def _check_equality(self, g, original, read_value): + return check_equality_base(self, original, read_value) + + +def _validate_prop(key, value, unittest): + if key == 'index': + return + + if any(key.startswith(t) for t in ('int', 'short')): + typ = int + + elif any(key.startswith(t) for t in ('long',)): + if sys.version_info >= (3, 0): + typ = int + else: + typ = long + elif any(key.startswith(t) for t in ('float', 'double')): + typ = float + elif any(key.startswith(t) for t in ('polygon',)): + typ = Polygon + elif any(key.startswith(t) for t in ('point',)): + typ = Point + elif any(key.startswith(t) for t in ('Linestring',)): + typ = LineString + elif any(key.startswith(t) for t in ('neg',)): + typ = six.string_types + elif any(key.startswith(t) for t in ('date',)): + typ = datetime.date + elif any(key.startswith(t) for t in ('time',)): + typ = datetime.time + else: + unittest.fail("Received unexpected type: %s" % key) + + +@requiredse +class BaseImplicitExecutionTest(GraphUnitTestCase): + """ + This test class will execute all tests of the AbstractTraversalTestClass using implicit execution + This all traversal will be run directly using toList() + """ + def setUp(self): + super(BaseImplicitExecutionTest, self).setUp() + if DSE_VERSION: + self.ep = DseGraph().create_execution_profile(self.graph_name) + self.cluster.add_execution_profile(self.graph_name, self.ep) + + @staticmethod + def fetch_key_from_prop(property): + return property.key + + def fetch_traversal_source(self, graphson, **kwargs): + ep = self.get_execution_profile(graphson, traversal=True) + return DseGraph().traversal_source(self.session, self.graph_name, execution_profile=ep, **kwargs) + + def execute_traversal(self, traversal, graphson=None): + return traversal.toList() + + def _validate_classic_vertex(self, g, vertex): + # Checks the properties on a classic vertex for correctness + vertex_props = self.fetch_vertex_props(g, vertex) + vertex_prop_keys = [vp.key for vp in vertex_props] + self.assertEqual(len(vertex_prop_keys), 2) + self.assertIn('name', vertex_prop_keys) + self.assertTrue('lang' in vertex_prop_keys or 'age' in vertex_prop_keys) + + def _validate_generic_vertex_result_type(self, g, vertex): + # Checks a vertex object for it's generic properties + properties = self.fetch_vertex_props(g, vertex) + for attr in ('id', 'label'): + self.assertIsNotNone(getattr(vertex, attr)) + self.assertTrue(len(properties) > 2) + + def _validate_classic_edge_properties(self, g, edge): + # Checks the properties on a classic edge for correctness + edge_props = self.fetch_edge_props(g, edge) + edge_prop_keys = [ep.key for ep in edge_props] + self.assertEqual(len(edge_prop_keys), 1) + self.assertIn('weight', edge_prop_keys) + + def _validate_classic_edge(self, g, edge): + self._validate_generic_edge_result_type(edge) + self._validate_classic_edge_properties(g, edge) + + def _validate_line_edge(self, g, edge): + self._validate_generic_edge_result_type(edge) + edge_props = self.fetch_edge_props(g, edge) + edge_prop_keys = [ep.key for ep in edge_props] + self.assertEqual(len(edge_prop_keys), 1) + self.assertIn('distance', edge_prop_keys) + + def _validate_generic_edge_result_type(self, edge): + self.assertIsInstance(edge, TravEdge) + + for attr in ('outV', 'inV', 'label', 'id'): + self.assertIsNotNone(getattr(edge, attr)) + + def _validate_path_result_type(self, g, objects_path): + for obj in objects_path: + if isinstance(obj, TravEdge): + self._validate_classic_edge(g, obj) + elif isinstance(obj, TravVertex): + self._validate_classic_vertex(g, obj) + else: + self.fail("Invalid object found in path " + str(obj.type)) + + def _validate_meta_property(self, g, vertex): + meta_props = g.V(vertex.id).properties().toList() + self.assertEqual(len(meta_props), 1) + meta_prop = meta_props[0] + self.assertEqual(meta_prop.value, "meta_prop") + self.assertEqual(meta_prop.key, "key") + + nested_props = g.V(vertex.id).properties().properties().toList() + self.assertEqual(len(nested_props), 2) + for nested_prop in nested_props: + self.assertTrue(nested_prop.key in ['k0', 'k1']) + self.assertTrue(nested_prop.value in ['v0', 'v1']) + + def _validate_type(self, g, vertex): + props = self.fetch_vertex_props(g, vertex) + for prop in props: + value = prop.value + key = prop.key + _validate_prop(key, value, self) + + +class BaseExplicitExecutionTest(GraphUnitTestCase): + + def fetch_traversal_source(self, graphson, **kwargs): + ep = self.get_execution_profile(graphson, traversal=True) + return DseGraph().traversal_source(self.session, self.graph_name, execution_profile=ep, **kwargs) + + def execute_traversal(self, traversal, graphson): + ep = self.get_execution_profile(graphson, traversal=True) + ep = self.session.get_execution_profile(ep) + context = None + if graphson == GraphProtocol.GRAPHSON_3_0: + context = { + 'cluster': self.cluster, + 'graph_name': ep.graph_options.graph_name.decode('utf-8') if ep.graph_options.graph_name else None + } + query = DseGraph.query_from_traversal(traversal, graphson, context=context) + # Use an ep that is configured with the correct row factory, and bytecode-json language flat set + result_set = self.execute_graph(query, graphson, traversal=True) + return list(result_set) diff --git a/tests/integration/advanced/graph/fluent/test_graph.py b/tests/integration/advanced/graph/fluent/test_graph.py new file mode 100644 index 0000000..02611c1 --- /dev/null +++ b/tests/integration/advanced/graph/fluent/test_graph.py @@ -0,0 +1,246 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import six + +from cassandra import cluster +from cassandra.cluster import ContinuousPagingOptions +from cassandra.datastax.graph.fluent import DseGraph +from cassandra.graph import VertexProperty + +from tests.integration import greaterthanorequaldse68 +from tests.integration.advanced.graph import ( + GraphUnitTestCase, ClassicGraphSchema, CoreGraphSchema, + VertexLabel, GraphTestConfiguration +) +from tests.integration import greaterthanorequaldse60 +from tests.integration.advanced.graph.fluent import ( + BaseExplicitExecutionTest, create_traversal_profiles, check_equality_base) + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + + +@greaterthanorequaldse60 +@GraphTestConfiguration.generate_tests(traversal=True) +class BatchStatementTests(BaseExplicitExecutionTest): + + def setUp(self): + super(BatchStatementTests, self).setUp() + self.ep_graphson2, self.ep_graphson3 = create_traversal_profiles(self.cluster, self.graph_name) + + def _test_batch_with_schema(self, schema, graphson): + """ + Sends a Batch statement and verifies it has succeeded with a schema created + + @since 1.1.0 + @jira_ticket PYTHON-789 + @expected_result ValueError is arisen + + @test_category dse graph + """ + self._send_batch_and_read_results(schema, graphson) + + def _test_batch_without_schema(self, schema, graphson): + """ + Sends a Batch statement and verifies it has succeeded without a schema created + + @since 1.1.0 + @jira_ticket PYTHON-789 + @expected_result ValueError is arisen + + @test_category dse graph + """ + if schema is not ClassicGraphSchema: + raise unittest.SkipTest('schema-less is only for classic graphs') + self._send_batch_and_read_results(schema, graphson, use_schema=False) + + def _test_batch_with_schema_add_all(self, schema, graphson): + """ + Sends a Batch statement and verifies it has succeeded with a schema created. + Uses :method:`dse_graph.query._BatchGraphStatement.add_all` to add the statements + instead of :method:`dse_graph.query._BatchGraphStatement.add` + + @since 1.1.0 + @jira_ticket PYTHON-789 + @expected_result ValueError is arisen + + @test_category dse graph + """ + self._send_batch_and_read_results(schema, graphson, add_all=True) + + def _test_batch_without_schema_add_all(self, schema, graphson): + """ + Sends a Batch statement and verifies it has succeeded without a schema created + Uses :method:`dse_graph.query._BatchGraphStatement.add_all` to add the statements + instead of :method:`dse_graph.query._BatchGraphStatement.add` + + @since 1.1.0 + @jira_ticket PYTHON-789 + @expected_result ValueError is arisen + + @test_category dse graph + """ + if schema is not ClassicGraphSchema: + raise unittest.SkipTest('schema-less is only for classic graphs') + self._send_batch_and_read_results(schema, graphson, add_all=True, use_schema=False) + + def test_only_graph_traversals_are_accepted(self): + """ + Verifies that ValueError is risen if the parameter add is not a traversal + + @since 1.1.0 + @jira_ticket PYTHON-789 + @expected_result ValueError is arisen + + @test_category dse graph + """ + batch = DseGraph.batch() + self.assertRaises(ValueError, batch.add, '{"@value":{"step":[["addV","poc_int"],' + '["property","bigint1value",{"@value":12,"@type":"g:Int32"}]]},' + '"@type":"g:Bytecode"}') + another_batch = DseGraph.batch() + self.assertRaises(ValueError, batch.add, another_batch) + + def _send_batch_and_read_results(self, schema, graphson, add_all=False, use_schema=True): + traversals = [] + datatypes = schema.fixtures.datatypes() + values = {} + g = self.fetch_traversal_source(graphson) + ep = self.get_execution_profile(graphson) + batch = DseGraph.batch(session=self.session, + execution_profile=self.get_execution_profile(graphson, traversal=True)) + for data in six.itervalues(datatypes): + typ, value, deserializer = data + vertex_label = VertexLabel([typ]) + property_name = next(six.iterkeys(vertex_label.non_pk_properties)) + values[property_name] = value + if use_schema or schema is CoreGraphSchema: + schema.create_vertex_label(self.session, vertex_label, execution_profile=ep) + + traversal = g.addV(str(vertex_label.label)).property('pkid', vertex_label.id).property(property_name, value) + if not add_all: + batch.add(traversal) + traversals.append(traversal) + + if add_all: + batch.add_all(traversals) + + self.assertEqual(len(datatypes), len(batch)) + + batch.execute() + + vertices = self.execute_traversal(g.V(), graphson) + self.assertEqual(len(vertices), len(datatypes), "g.V() returned {}".format(vertices)) + + # Iterate over all the vertices and check that they match the original input + for vertex in vertices: + schema.ensure_properties(self.session, vertex, execution_profile=ep) + key = [k for k in list(vertex.properties.keys()) if k != 'pkid'][0].replace("value", "") + original = values[key] + self._check_equality(original, vertex) + + def _check_equality(self, original, vertex): + for key in vertex.properties: + if key == 'pkid': + continue + value = vertex.properties[key].value \ + if isinstance(vertex.properties[key], VertexProperty) else vertex.properties[key][0].value + check_equality_base(self, original, value) + + +class ContinuousPagingOptionsForTests(ContinuousPagingOptions): + def __init__(self, + page_unit=ContinuousPagingOptions.PagingUnit.ROWS, max_pages=1, # max_pages=1 + max_pages_per_second=0, max_queue_size=4): + super(ContinuousPagingOptionsForTests, self).__init__(page_unit, max_pages, max_pages_per_second, + max_queue_size) + + +def reset_paging_options(): + cluster.ContinuousPagingOptions = ContinuousPagingOptions + + +@greaterthanorequaldse68 +@GraphTestConfiguration.generate_tests(schema=CoreGraphSchema) +class GraphPagingTest(GraphUnitTestCase): + + def setUp(self): + super(GraphPagingTest, self).setUp() + self.addCleanup(reset_paging_options) + self.ep_graphson2, self.ep_graphson3 = create_traversal_profiles(self.cluster, self.graph_name) + + def _setup_data(self, schema, graphson): + self.execute_graph( + "schema.vertexLabel('person').ifNotExists().partitionBy('name', Text).property('age', Int).create();", + graphson) + for i in range(100): + self.execute_graph("g.addV('person').property('name', 'batman-{}')".format(i), graphson) + + def _test_cont_paging_is_enabled_by_default(self, schema, graphson): + """ + Test that graph paging is automatically enabled with a >=6.8 cluster. + + @jira_ticket PYTHON-1045 + @expected_result the default continuous paging options are used + + @test_category dse graph + """ + # with traversals... I don't have access to the response future... so this is a hack to ensure paging is on + cluster.ContinuousPagingOptions = ContinuousPagingOptionsForTests + ep = self.get_execution_profile(graphson, traversal=True) + self._setup_data(schema, graphson) + self.session.default_fetch_size = 10 + g = DseGraph.traversal_source(self.session, execution_profile=ep) + results = g.V().toList() + self.assertEqual(len(results), 10) # only 10 results due to our hack + + def _test_cont_paging_can_be_disabled(self, schema, graphson): + """ + Test that graph paging can be disabled. + + @jira_ticket PYTHON-1045 + @expected_result the default continuous paging options are not used + + @test_category dse graph + """ + # with traversals... I don't have access to the response future... so this is a hack to ensure paging is on + cluster.ContinuousPagingOptions = ContinuousPagingOptionsForTests + ep = self.get_execution_profile(graphson, traversal=True) + ep = self.session.execution_profile_clone_update(ep, continuous_paging_options=None) + self._setup_data(schema, graphson) + self.session.default_fetch_size = 10 + g = DseGraph.traversal_source(self.session, execution_profile=ep) + results = g.V().toList() + self.assertEqual(len(results), 100) # 100 results since paging is disabled + + def _test_cont_paging_with_custom_options(self, schema, graphson): + """ + Test that we can specify custom paging options. + + @jira_ticket PYTHON-1045 + @expected_result we get only the desired number of results + + @test_category dse graph + """ + ep = self.get_execution_profile(graphson, traversal=True) + ep = self.session.execution_profile_clone_update(ep, + continuous_paging_options=ContinuousPagingOptions(max_pages=1)) + self._setup_data(schema, graphson) + self.session.default_fetch_size = 10 + g = DseGraph.traversal_source(self.session, execution_profile=ep) + results = g.V().toList() + self.assertEqual(len(results), 10) # only 10 results since paging is disabled diff --git a/tests/integration/advanced/graph/fluent/test_graph_explicit_execution.py b/tests/integration/advanced/graph/fluent/test_graph_explicit_execution.py new file mode 100644 index 0000000..1a58462 --- /dev/null +++ b/tests/integration/advanced/graph/fluent/test_graph_explicit_execution.py @@ -0,0 +1,96 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from cassandra.graph import Vertex, Edge + +from tests.integration.advanced.graph import ( + validate_classic_vertex, validate_classic_edge, validate_generic_vertex_result_type, + validate_classic_edge_properties, validate_line_edge, + validate_generic_edge_result_type, validate_path_result_type) + +from tests.integration import requiredse, DSE_VERSION +from tests.integration.advanced import use_single_node_with_graph +from tests.integration.advanced.graph import GraphTestConfiguration +from tests.integration.advanced.graph.fluent import ( + BaseExplicitExecutionTest, _AbstractTraversalTest, _validate_prop) + + +def setup_module(): + if DSE_VERSION: + dse_options = {'graph': {'realtime_evaluation_timeout_in_seconds': 60}} + use_single_node_with_graph(dse_options=dse_options) + + +@requiredse +@GraphTestConfiguration.generate_tests(traversal=True) +class ExplicitExecutionTest(BaseExplicitExecutionTest, _AbstractTraversalTest): + """ + This test class will execute all tests of the AbstractTraversalTestClass using Explicit execution + All queries will be run by converting them to byte code, and calling execute graph explicitly with a generated ep. + """ + @staticmethod + def fetch_key_from_prop(property): + return property.label + + def _validate_classic_vertex(self, g, vertex): + validate_classic_vertex(self, vertex) + + def _validate_generic_vertex_result_type(self, g, vertex): + validate_generic_vertex_result_type(self, vertex) + + def _validate_classic_edge_properties(self, g, edge): + validate_classic_edge_properties(self, edge) + + def _validate_classic_edge(self, g, edge): + validate_classic_edge(self, edge) + + def _validate_line_edge(self, g, edge): + validate_line_edge(self, edge) + + def _validate_generic_edge_result_type(self, edge): + validate_generic_edge_result_type(self, edge) + + def _validate_type(self, g, vertex): + for key in vertex.properties: + value = vertex.properties[key][0].value + _validate_prop(key, value, self) + + def _validate_path_result_type(self, g, path_obj): + # This pre-processing is due to a change in TinkerPop + # properties are not returned automatically anymore + # with some queries. + for obj in path_obj.objects: + if not obj.properties: + props = [] + if isinstance(obj, Edge): + obj.properties = { + p.key: p.value + for p in self.fetch_edge_props(g, obj) + } + elif isinstance(obj, Vertex): + obj.properties = { + p.label: p.value + for p in self.fetch_vertex_props(g, obj) + } + + validate_path_result_type(self, path_obj) + + def _validate_meta_property(self, g, vertex): + + self.assertEqual(len(vertex.properties), 1) + self.assertEqual(len(vertex.properties['key']), 1) + p = vertex.properties['key'][0] + self.assertEqual(p.label, 'key') + self.assertEqual(p.value, 'meta_prop') + self.assertEqual(p.properties, {'k0': 'v0', 'k1': 'v1'}) diff --git a/tests/integration/advanced/graph/fluent/test_graph_implicit_execution.py b/tests/integration/advanced/graph/fluent/test_graph_implicit_execution.py new file mode 100644 index 0000000..50e6795 --- /dev/null +++ b/tests/integration/advanced/graph/fluent/test_graph_implicit_execution.py @@ -0,0 +1,108 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from concurrent.futures import Future +from cassandra.datastax.graph.fluent import DseGraph + +from tests.integration import requiredse, DSE_VERSION +from tests.integration.advanced import use_single_node_with_graph +from tests.integration.advanced.graph import GraphTestConfiguration +from tests.integration.advanced.graph.fluent import ( + BaseImplicitExecutionTest, create_traversal_profiles, _AbstractTraversalTest) + + +def setup_module(): + if DSE_VERSION: + dse_options = {'graph': {'realtime_evaluation_timeout_in_seconds': 60}} + use_single_node_with_graph(dse_options=dse_options) + + +@requiredse +@GraphTestConfiguration.generate_tests(traversal=True) +class ImplicitExecutionTest(BaseImplicitExecutionTest, _AbstractTraversalTest): + def _test_iterate_step(self, schema, graphson): + """ + Test to validate that the iterate() step work on all dse versions. + @jira_ticket PYTHON-1155 + @expected_result iterate step works + @test_category dse graph + """ + + g = self.fetch_traversal_source(graphson) + self.execute_graph(schema.fixtures.classic(), graphson) + g.addV('person').property('name', 'Person1').iterate() + + +@requiredse +@GraphTestConfiguration.generate_tests(traversal=True) +class ImplicitAsyncExecutionTest(BaseImplicitExecutionTest): + """ + Test to validate that the traversal async execution works properly. + + @since 3.21.0 + @jira_ticket PYTHON-1129 + + @test_category dse graph + """ + + def setUp(self): + super(ImplicitAsyncExecutionTest, self).setUp() + self.ep_graphson2, self.ep_graphson3 = create_traversal_profiles(self.cluster, self.graph_name) + + def _validate_results(self, results): + results = list(results) + self.assertEqual(len(results), 2) + self.assertIn('vadas', results) + self.assertIn('josh', results) + + def _test_promise(self, schema, graphson): + self.execute_graph(schema.fixtures.classic(), graphson) + g = self.fetch_traversal_source(graphson) + traversal_future = g.V().has('name', 'marko').out('knows').values('name').promise() + self._validate_results(traversal_future.result()) + + def _test_promise_error_is_propagated(self, schema, graphson): + self.execute_graph(schema.fixtures.classic(), graphson) + g = DseGraph().traversal_source(self.session, 'wrong_graph', execution_profile=self.ep) + traversal_future = g.V().has('name', 'marko').out('knows').values('name').promise() + with self.assertRaises(Exception): + traversal_future.result() + + def _test_promise_callback(self, schema, graphson): + self.execute_graph(schema.fixtures.classic(), graphson) + g = self.fetch_traversal_source(graphson) + future = Future() + + def cb(f): + future.set_result(f.result()) + + traversal_future = g.V().has('name', 'marko').out('knows').values('name').promise() + traversal_future.add_done_callback(cb) + self._validate_results(future.result()) + + def _test_promise_callback_on_error(self, schema, graphson): + self.execute_graph(schema.fixtures.classic(), graphson) + g = DseGraph().traversal_source(self.session, 'wrong_graph', execution_profile=self.ep) + future = Future() + + def cb(f): + try: + f.result() + except Exception as e: + future.set_exception(e) + + traversal_future = g.V().has('name', 'marko').out('knows').values('name').promise() + traversal_future.add_done_callback(cb) + with self.assertRaises(Exception): + future.result() diff --git a/tests/integration/advanced/graph/fluent/test_search.py b/tests/integration/advanced/graph/fluent/test_search.py new file mode 100644 index 0000000..d50016d --- /dev/null +++ b/tests/integration/advanced/graph/fluent/test_search.py @@ -0,0 +1,539 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from cassandra.util import Distance +from cassandra import InvalidRequest +from cassandra.graph import GraphProtocol +from cassandra.datastax.graph.fluent import DseGraph +from cassandra.datastax.graph.fluent.predicates import Search, Geo, GeoUnit, CqlCollection + +from tests.integration.advanced import use_single_node_with_graph_and_solr +from tests.integration.advanced.graph import GraphUnitTestCase, CoreGraphSchema, ClassicGraphSchema, GraphTestConfiguration +from tests.integration import greaterthanorequaldse51, DSE_VERSION, requiredse + + +def setup_module(): + if DSE_VERSION: + use_single_node_with_graph_and_solr() + + +class AbstractSearchTest(GraphUnitTestCase): + + def setUp(self): + super(AbstractSearchTest, self).setUp() + self.ep_graphson2 = DseGraph().create_execution_profile(self.graph_name, + graph_protocol=GraphProtocol.GRAPHSON_2_0) + self.ep_graphson3 = DseGraph().create_execution_profile(self.graph_name, + graph_protocol=GraphProtocol.GRAPHSON_3_0) + + self.cluster.add_execution_profile('traversal_graphson2', self.ep_graphson2) + self.cluster.add_execution_profile('traversal_graphson3', self.ep_graphson3) + + def fetch_traversal_source(self, graphson): + ep = self.get_execution_profile(graphson, traversal=True) + return DseGraph().traversal_source(self.session, self.graph_name, execution_profile=ep) + + def _test_search_by_prefix(self, schema, graphson): + """ + Test to validate that solr searches by prefix function. + + @since 1.0.0 + @jira_ticket PYTHON-660 + @expected_result all names starting with Paul should be returned + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.address_book(), graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.V().has("person", "name", Search.prefix("Paul")).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 1) + self.assertEqual(results_list[0], "Paul Thomas Joe") + + def _test_search_by_regex(self, schema, graphson): + """ + Test to validate that solr searches by regex function. + + @since 1.0.0 + @jira_ticket PYTHON-660 + @expected_result all names containing Paul should be returned + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.address_book(), graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.V().has("person", "name", Search.regex(".*Paul.*")).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 2) + self.assertIn("Paul Thomas Joe", results_list) + self.assertIn("James Paul Smith", results_list) + + def _test_search_by_token(self, schema, graphson): + """ + Test to validate that solr searches by token. + + @since 1.0.0 + @jira_ticket PYTHON-660 + @expected_result all names with description containing could shoud be returned + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.address_book(), graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.V().has("person", "description", Search.token("cold")).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 2) + self.assertIn("Jill Alice", results_list) + self.assertIn("George Bill Steve", results_list) + + def _test_search_by_token_prefix(self, schema, graphson): + """ + Test to validate that solr searches by token prefix. + + @since 1.0.0 + @jira_ticket PYTHON-660 + @expected_result all names with description containing a token starting with h are returned + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.address_book(), graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.V().has("person", "description", Search.token_prefix("h")).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 2) + self.assertIn("Paul Thomas Joe", results_list) + self.assertIn( "James Paul Smith", results_list) + + def _test_search_by_token_regex(self, schema, graphson): + """ + Test to validate that solr searches by token regex. + + @since 1.0.0 + @jira_ticket PYTHON-660 + @expected_result all names with description containing nice or hospital are returned + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.address_book(), graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.V().has("person", "description", Search.token_regex("(nice|hospital)")).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 2) + self.assertIn("Paul Thomas Joe", results_list ) + self.assertIn( "Jill Alice", results_list ) + + def _assert_in_distance(self, schema, graphson, inside, names): + """ + Helper function that asserts that an exception is arisen if geodetic predicates are used + in cartesian geometry. Also asserts that the expected list is equal to the returned from + the transversal using different search indexes. + """ + def assert_equal_list(L1, L2): + return len(L1) == len(L2) and sorted(L1) == sorted(L2) + + self.execute_graph(schema.fixtures.address_book(), graphson) + g = self.fetch_traversal_source(graphson) + + traversal = g.V().has("person", "pointPropWithBoundsWithSearchIndex", inside).values("name") + if schema is ClassicGraphSchema: + # throws an exception because of a SOLR/Search limitation in the indexing process + # may be resolved in the future + self.assertRaises(InvalidRequest, self.execute_traversal, traversal, graphson) + else: + traversal = g.V().has("person", "pointPropWithBoundsWithSearchIndex", inside).values("name") + results_list = self.execute_traversal(traversal, graphson) + assert_equal_list(names, results_list) + + traversal = g.V().has("person", "pointPropWithBounds", inside).values("name") + results_list = self.execute_traversal(traversal, graphson) + assert_equal_list(names, results_list) + + traversal = g.V().has("person", "pointPropWithGeoBoundsWithSearchIndex", inside).values("name") + results_list = self.execute_traversal(traversal, graphson) + assert_equal_list(names, results_list) + + traversal = g.V().has("person", "pointPropWithGeoBounds", inside).values("name") + results_list = self.execute_traversal(traversal, graphson) + assert_equal_list(names, results_list) + + @greaterthanorequaldse51 + def _test_search_by_distance(self, schema, graphson): + """ + Test to validate that solr searches by distance. + + @since 1.0.0 + @jira_ticket PYTHON-660 + @expected_result all names with a geo location within a 2 degree distance of -92,44 are returned + + @test_category dse graph + """ + self._assert_in_distance(schema, graphson, + Geo.inside(Distance(-92, 44, 2)), + ["Paul Thomas Joe", "George Bill Steve"] + ) + + @greaterthanorequaldse51 + def _test_search_by_distance_meters_units(self, schema, graphson): + """ + Test to validate that solr searches by distance. + + @since 2.0.0 + @jira_ticket PYTHON-698 + @expected_result all names with a geo location within a 56k-meter radius of -92,44 are returned + + @test_category dse graph + """ + self._assert_in_distance(schema, graphson, + Geo.inside(Distance(-92, 44, 56000), GeoUnit.METERS), + ["Paul Thomas Joe"] + ) + + @greaterthanorequaldse51 + def _test_search_by_distance_miles_units(self, schema, graphson): + """ + Test to validate that solr searches by distance. + + @since 2.0.0 + @jira_ticket PYTHON-698 + @expected_result all names with a geo location within a 70-mile radius of -92,44 are returned + + @test_category dse graph + """ + self._assert_in_distance(schema, graphson, + Geo.inside(Distance(-92, 44, 70), GeoUnit.MILES), + ["Paul Thomas Joe", "George Bill Steve"] + ) + + @greaterthanorequaldse51 + def _test_search_by_distance_check_limit(self, schema, graphson): + """ + Test to validate that solr searches by distance using several units. It will also validate + that and exception is arisen if geodetic predicates are used against cartesian geometry + + @since 2.0.0 + @jira_ticket PYTHON-698 + @expected_result if the search distance is below the real distance only one + name will be in the list, otherwise, two + + @test_category dse graph + """ + # Paul Thomas Joe and George Bill Steve are 64.6923761881464 km apart + self._assert_in_distance(schema, graphson, + Geo.inside(Distance(-92.46295, 44.0234, 65), GeoUnit.KILOMETERS), + ["George Bill Steve", "Paul Thomas Joe"] + ) + + self._assert_in_distance(schema, graphson, + Geo.inside(Distance(-92.46295, 44.0234, 64), GeoUnit.KILOMETERS), + ["Paul Thomas Joe"] + ) + + # Paul Thomas Joe and George Bill Steve are 40.19797892069464 miles apart + self._assert_in_distance(schema, graphson, + Geo.inside(Distance(-92.46295, 44.0234, 41), GeoUnit.MILES), + ["George Bill Steve", "Paul Thomas Joe"] + ) + + self._assert_in_distance(schema, graphson, + Geo.inside(Distance(-92.46295, 44.0234, 40), GeoUnit.MILES), + ["Paul Thomas Joe"] + ) + + @greaterthanorequaldse51 + def _test_search_by_fuzzy(self, schema, graphson): + """ + Test to validate that solr searches by distance. + + @since 1.0.0 + @jira_ticket PYTHON-664 + @expected_result all names with a geo location within a 2 radius distance of -92,44 are returned + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.address_book(), graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.V().has("person", "name", Search.fuzzy("Paul Thamas Joe", 1)).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 1) + self.assertIn("Paul Thomas Joe", results_list) + + traversal = g.V().has("person", "name", Search.fuzzy("Paul Thames Joe", 1)).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 0) + + @greaterthanorequaldse51 + def _test_search_by_fuzzy_token(self, schema, graphson): + """ + Test to validate that fuzzy searches. + + @since 1.0.0 + @jira_ticket PYTHON-664 + @expected_result all names with that differ from the search criteria by one letter should be returned + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.address_book(), graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.V().has("person", "description", Search.token_fuzzy("lives", 1)).values("name") + # Should match 'Paul Thomas Joe' since description contains 'Lives' + # Should match 'James Paul Joe' since description contains 'Likes' + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 2) + self.assertIn("Paul Thomas Joe", results_list) + self.assertIn("James Paul Smith", results_list) + + traversal = g.V().has("person", "description", Search.token_fuzzy("loues", 1)).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 0) + + @greaterthanorequaldse51 + def _test_search_by_phrase(self, schema, graphson): + """ + Test to validate that phrase searches. + + @since 1.0.0 + @jira_ticket PYTHON-664 + @expected_result all names with that differ from the search phrase criteria by two letter should be returned + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.address_book(), graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.V().has("person", "description", Search.phrase("a cold", 2)).values("name") + #Should match 'George Bill Steve' since 'A cold dude' is at distance of 0 for 'a cold'. + #Should match 'Jill Alice' since 'Enjoys a very nice cold coca cola' is at distance of 2 for 'a cold'. + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 2) + self.assertIn('George Bill Steve', results_list) + self.assertIn('Jill Alice', results_list) + + traversal = g.V().has("person", "description", Search.phrase("a bald", 2)).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 0) + + +@requiredse +@GraphTestConfiguration.generate_tests(traversal=True) +class ImplicitSearchTest(AbstractSearchTest): + """ + This test class will execute all tests of the AbstractSearchTest using implicit execution + All traversals will be run directly using toList() + """ + def fetch_key_from_prop(self, property): + return property.key + + def execute_traversal(self, traversal, graphson=None): + return traversal.toList() + + +@requiredse +@GraphTestConfiguration.generate_tests(traversal=True) +class ExplicitSearchTest(AbstractSearchTest): + """ + This test class will execute all tests of the AbstractSearchTest using implicit execution + All traversals will be converted to byte code then they will be executed explicitly. + """ + + def execute_traversal(self, traversal, graphson): + ep = self.get_execution_profile(graphson, traversal=True) + ep = self.session.get_execution_profile(ep) + context = None + if graphson == GraphProtocol.GRAPHSON_3_0: + context = { + 'cluster': self.cluster, + 'graph_name': ep.graph_options.graph_name.decode('utf-8') if ep.graph_options.graph_name else None + } + query = DseGraph.query_from_traversal(traversal, graphson, context=context) + #Use an ep that is configured with the correct row factory, and bytecode-json language flat set + result_set = self.execute_graph(query, graphson, traversal=True) + return list(result_set) + + +@requiredse +class BaseCqlCollectionPredicatesTest(GraphUnitTestCase): + + def setUp(self): + super(BaseCqlCollectionPredicatesTest, self).setUp() + self.ep_graphson3 = DseGraph().create_execution_profile(self.graph_name, + graph_protocol=GraphProtocol.GRAPHSON_3_0) + self.cluster.add_execution_profile('traversal_graphson3', self.ep_graphson3) + + def fetch_traversal_source(self, graphson): + ep = self.get_execution_profile(graphson, traversal=True) + return DseGraph().traversal_source(self.session, self.graph_name, execution_profile=ep) + + def setup_vertex_label(self, graphson): + ep = self.get_execution_profile(graphson) + self.session.execute_graph(""" + schema.vertexLabel('cqlcollections').ifNotExists().partitionBy('name', Varchar) + .property('list', listOf(Text)) + .property('frozen_list', frozen(listOf(Text))) + .property('set', setOf(Text)) + .property('frozen_set', frozen(setOf(Text))) + .property('map_keys', mapOf(Int, Text)) + .property('map_values', mapOf(Int, Text)) + .property('map_entries', mapOf(Int, Text)) + .property('frozen_map', frozen(mapOf(Int, Text))) + .create() + """, execution_profile=ep) + + self.session.execute_graph(""" + schema.vertexLabel('cqlcollections').secondaryIndex('list').by('list').create(); + schema.vertexLabel('cqlcollections').secondaryIndex('frozen_list').by('frozen_list').indexFull().create(); + schema.vertexLabel('cqlcollections').secondaryIndex('set').by('set').create(); + schema.vertexLabel('cqlcollections').secondaryIndex('frozen_set').by('frozen_set').indexFull().create(); + schema.vertexLabel('cqlcollections').secondaryIndex('map_keys').by('map_keys').indexKeys().create(); + schema.vertexLabel('cqlcollections').secondaryIndex('map_values').by('map_values').indexValues().create(); + schema.vertexLabel('cqlcollections').secondaryIndex('map_entries').by('map_entries').indexEntries().create(); + schema.vertexLabel('cqlcollections').secondaryIndex('frozen_map').by('frozen_map').indexFull().create(); + """, execution_profile=ep) + + def _test_contains_list(self, schema, graphson): + """ + Test to validate that the cql predicate contains works with list + + @since TODO dse 6.8 + @jira_ticket PYTHON-1039 + @expected_result contains predicate work on a list + + @test_category dse graph + """ + self.setup_vertex_label(graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.addV("cqlcollections").property("name", "list1").property("list", ['item1', 'item2']) + self.execute_traversal(traversal, graphson) + traversal = g.addV("cqlcollections").property("name", "list2").property("list", ['item3', 'item4']) + self.execute_traversal(traversal, graphson) + traversal = g.V().has("cqlcollections", "list", CqlCollection.contains("item1")).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 1) + self.assertIn("list1", results_list) + + def _test_contains_set(self, schema, graphson): + """ + Test to validate that the cql predicate contains works with set + + @since TODO dse 6.8 + @jira_ticket PYTHON-1039 + @expected_result contains predicate work on a set + + @test_category dse graph + """ + self.setup_vertex_label(graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.addV("cqlcollections").property("name", "set1").property("set", {'item1', 'item2'}) + self.execute_traversal(traversal, graphson) + traversal = g.addV("cqlcollections").property("name", "set2").property("set", {'item3', 'item4'}) + self.execute_traversal(traversal, graphson) + traversal = g.V().has("cqlcollections", "set", CqlCollection.contains("item1")).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 1) + self.assertIn("set1", results_list) + + def _test_contains_key_map(self, schema, graphson): + """ + Test to validate that the cql predicate contains_key works with map + + @since TODO dse 6.8 + @jira_ticket PYTHON-1039 + @expected_result contains_key predicate work on a map + + @test_category dse graph + """ + self.setup_vertex_label(graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.addV("cqlcollections").property("name", "map1").property("map_keys", {0: 'item1', 1: 'item2'}) + self.execute_traversal(traversal, graphson) + traversal = g.addV("cqlcollections").property("name", "map2").property("map_keys", {2: 'item3', 3: 'item4'}) + self.execute_traversal(traversal, graphson) + traversal = g.V().has("cqlcollections", "map_keys", CqlCollection.contains_key(0)).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 1) + self.assertIn("map1", results_list) + + def _test_contains_value_map(self, schema, graphson): + """ + Test to validate that the cql predicate contains_value works with map + + @since TODO dse 6.8 + @jira_ticket PYTHON-1039 + @expected_result contains_value predicate work on a map + + @test_category dse graph + """ + self.setup_vertex_label(graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.addV("cqlcollections").property("name", "map1").property("map_values", {0: 'item1', 1: 'item2'}) + self.execute_traversal(traversal, graphson) + traversal = g.addV("cqlcollections").property("name", "map2").property("map_values", {2: 'item3', 3: 'item4'}) + self.execute_traversal(traversal, graphson) + traversal = g.V().has("cqlcollections", "map_values", CqlCollection.contains_value('item3')).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 1) + self.assertIn("map2", results_list) + + def _test_entry_eq_map(self, schema, graphson): + """ + Test to validate that the cql predicate entry_eq works with map + + @since TODO dse 6.8 + @jira_ticket PYTHON-1039 + @expected_result entry_eq predicate work on a map + + @test_category dse graph + """ + self.setup_vertex_label(graphson) + g = self.fetch_traversal_source(graphson) + traversal = g.addV("cqlcollections").property("name", "map1").property("map_entries", {0: 'item1', 1: 'item2'}) + self.execute_traversal(traversal, graphson) + traversal = g.addV("cqlcollections").property("name", "map2").property("map_entries", {2: 'item3', 3: 'item4'}) + self.execute_traversal(traversal, graphson) + traversal = g.V().has("cqlcollections", "map_entries", CqlCollection.entry_eq([2, 'item3'])).values("name") + results_list = self.execute_traversal(traversal, graphson) + self.assertEqual(len(results_list), 1) + self.assertIn("map2", results_list) + + +@requiredse +@GraphTestConfiguration.generate_tests(traversal=True, schema=CoreGraphSchema) +class ImplicitCqlCollectionPredicatesTest(BaseCqlCollectionPredicatesTest): + """ + This test class will execute all tests of the BaseCqlCollectionTest using implicit execution + All traversals will be run directly using toList() + """ + + def execute_traversal(self, traversal, graphson=None): + return traversal.toList() + + +@requiredse +@GraphTestConfiguration.generate_tests(traversal=True, schema=CoreGraphSchema) +class ExplicitCqlCollectionPredicatesTest(BaseCqlCollectionPredicatesTest): + """ + This test class will execute all tests of the AbstractSearchTest using implicit execution + All traversals will be converted to byte code then they will be executed explicitly. + """ + + def execute_traversal(self, traversal, graphson): + ep = self.get_execution_profile(graphson, traversal=True) + ep = self.session.get_execution_profile(ep) + context = None + if graphson == GraphProtocol.GRAPHSON_3_0: + context = { + 'cluster': self.cluster, + 'graph_name': ep.graph_options.graph_name.decode('utf-8') if ep.graph_options.graph_name else None + } + query = DseGraph.query_from_traversal(traversal, graphson, context=context) + result_set = self.execute_graph(query, graphson, traversal=True) + return list(result_set) diff --git a/tests/integration/advanced/graph/test_graph.py b/tests/integration/advanced/graph/test_graph.py new file mode 100644 index 0000000..a0b6534 --- /dev/null +++ b/tests/integration/advanced/graph/test_graph.py @@ -0,0 +1,271 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import six +import re + +from cassandra import OperationTimedOut, InvalidRequest +from cassandra.protocol import SyntaxException +from cassandra.policies import WhiteListRoundRobinPolicy +from cassandra.cluster import NoHostAvailable +from cassandra.cluster import EXEC_PROFILE_GRAPH_DEFAULT, GraphExecutionProfile +from cassandra.graph import single_object_row_factory, Vertex, graph_object_row_factory, \ + graph_graphson2_row_factory, graph_graphson3_row_factory +from cassandra.util import SortedSet + +from tests.integration import DSE_VERSION, greaterthanorequaldse51, greaterthanorequaldse68, \ + requiredse, TestCluster +from tests.integration.advanced.graph import BasicGraphUnitTestCase, GraphUnitTestCase, \ + GraphProtocol, ClassicGraphSchema, CoreGraphSchema, use_single_node_with_graph + + +def setup_module(): + if DSE_VERSION: + dse_options = {'graph': {'realtime_evaluation_timeout_in_seconds': 60}} + use_single_node_with_graph(dse_options=dse_options) + + +@requiredse +class GraphTimeoutTests(BasicGraphUnitTestCase): + + def test_should_wait_indefinitely_by_default(self): + """ + Tests that by default the client should wait indefinitely for server timeouts + + @since 1.0.0 + @jira_ticket PYTHON-589 + + @test_category dse graph + """ + desired_timeout = 1000 + + graph_source = "test_timeout_1" + ep_name = graph_source + ep = self.session.execution_profile_clone_update(EXEC_PROFILE_GRAPH_DEFAULT) + ep.graph_options = ep.graph_options.copy() + ep.graph_options.graph_source = graph_source + self.cluster.add_execution_profile(ep_name, ep) + + to_run = '''graph.schema().config().option("graph.traversal_sources.{0}.evaluation_timeout").set('{1} ms')'''.format( + graph_source, desired_timeout) + self.session.execute_graph(to_run, execution_profile=ep_name) + with self.assertRaises(InvalidRequest) as ir: + self.session.execute_graph("java.util.concurrent.TimeUnit.MILLISECONDS.sleep(35000L);1+1", + execution_profile=ep_name) + self.assertTrue("evaluation exceeded the configured threshold of 1000" in str(ir.exception) or + "evaluation exceeded the configured threshold of evaluation_timeout at 1000" in str( + ir.exception)) + + def test_request_timeout_less_then_server(self): + """ + Tests that with explicit request_timeouts set, that a server timeout is honored if it's relieved prior to the + client timeout + + @since 1.0.0 + @jira_ticket PYTHON-589 + + @test_category dse graph + """ + desired_timeout = 1000 + graph_source = "test_timeout_2" + ep_name = graph_source + ep = self.session.execution_profile_clone_update(EXEC_PROFILE_GRAPH_DEFAULT, request_timeout=32) + ep.graph_options = ep.graph_options.copy() + ep.graph_options.graph_source = graph_source + self.cluster.add_execution_profile(ep_name, ep) + + to_run = '''graph.schema().config().option("graph.traversal_sources.{0}.evaluation_timeout").set('{1} ms')'''.format( + graph_source, desired_timeout) + self.session.execute_graph(to_run, execution_profile=ep_name) + with self.assertRaises(InvalidRequest) as ir: + self.session.execute_graph("java.util.concurrent.TimeUnit.MILLISECONDS.sleep(35000L);1+1", + execution_profile=ep_name) + self.assertTrue("evaluation exceeded the configured threshold of 1000" in str(ir.exception) or + "evaluation exceeded the configured threshold of evaluation_timeout at 1000" in str( + ir.exception)) + + def test_server_timeout_less_then_request(self): + """ + Tests that with explicit request_timeouts set, that a client timeout is honored if it's triggered prior to the + server sending a timeout. + + @since 1.0.0 + @jira_ticket PYTHON-589 + + @test_category dse graph + """ + graph_source = "test_timeout_3" + ep_name = graph_source + ep = self.session.execution_profile_clone_update(EXEC_PROFILE_GRAPH_DEFAULT, request_timeout=1) + ep.graph_options = ep.graph_options.copy() + ep.graph_options.graph_source = graph_source + self.cluster.add_execution_profile(ep_name, ep) + server_timeout = 10000 + to_run = '''graph.schema().config().option("graph.traversal_sources.{0}.evaluation_timeout").set('{1} ms')'''.format( + graph_source, server_timeout) + self.session.execute_graph(to_run, execution_profile=ep_name) + + with self.assertRaises(Exception) as e: + self.session.execute_graph("java.util.concurrent.TimeUnit.MILLISECONDS.sleep(35000L);1+1", + execution_profile=ep_name) + self.assertTrue(isinstance(e, InvalidRequest) or isinstance(e, OperationTimedOut)) + + +@requiredse +class GraphProfileTests(BasicGraphUnitTestCase): + def test_graph_profile(self): + """ + Test verifying various aspects of graph config properties. + + @since 1.0.0 + @jira_ticket PYTHON-570 + + @test_category dse graph + """ + hosts = self.cluster.metadata.all_hosts() + first_host = hosts[0].address + second_hosts = "1.2.3.4" + + self._execute(ClassicGraphSchema.fixtures.classic(), graphson=GraphProtocol.GRAPHSON_1_0) + # Create various execution policies + exec_dif_factory = GraphExecutionProfile(row_factory=single_object_row_factory) + exec_dif_factory.graph_options.graph_name = self.graph_name + exec_dif_lbp = GraphExecutionProfile(load_balancing_policy=WhiteListRoundRobinPolicy([first_host])) + exec_dif_lbp.graph_options.graph_name = self.graph_name + exec_bad_lbp = GraphExecutionProfile(load_balancing_policy=WhiteListRoundRobinPolicy([second_hosts])) + exec_dif_lbp.graph_options.graph_name = self.graph_name + exec_short_timeout = GraphExecutionProfile(request_timeout=1, + load_balancing_policy=WhiteListRoundRobinPolicy([first_host])) + exec_short_timeout.graph_options.graph_name = self.graph_name + + # Add a single execution policy on cluster creation + local_cluster = TestCluster(execution_profiles={"exec_dif_factory": exec_dif_factory}) + local_session = local_cluster.connect() + self.addCleanup(local_cluster.shutdown) + + rs1 = self.session.execute_graph('g.V()') + rs2 = local_session.execute_graph('g.V()', execution_profile='exec_dif_factory') + + # Verify default and non default policy works + self.assertFalse(isinstance(rs2[0], Vertex)) + self.assertTrue(isinstance(rs1[0], Vertex)) + # Add other policies validate that lbp are honored + local_cluster.add_execution_profile("exec_dif_ldp", exec_dif_lbp) + local_session.execute_graph('g.V()', execution_profile="exec_dif_ldp") + local_cluster.add_execution_profile("exec_bad_lbp", exec_bad_lbp) + with self.assertRaises(NoHostAvailable): + local_session.execute_graph('g.V()', execution_profile="exec_bad_lbp") + + # Try with missing EP + with self.assertRaises(ValueError): + local_session.execute_graph('g.V()', execution_profile='bad_exec_profile') + + # Validate that timeout is honored + local_cluster.add_execution_profile("exec_short_timeout", exec_short_timeout) + with self.assertRaises(Exception) as e: + self.assertTrue(isinstance(e, InvalidRequest) or isinstance(e, OperationTimedOut)) + local_session.execute_graph('java.util.concurrent.TimeUnit.MILLISECONDS.sleep(2000L);', + execution_profile='exec_short_timeout') + + +@requiredse +class GraphMetadataTest(BasicGraphUnitTestCase): + + @greaterthanorequaldse51 + def test_dse_workloads(self): + """ + Test to ensure dse_workloads is populated appropriately. + Field added in DSE 5.1 + + @since DSE 2.0 + @jira_ticket PYTHON-667 + @expected_result dse_workloads set is set on host model + + @test_category metadata + """ + for host in self.cluster.metadata.all_hosts(): + self.assertIsInstance(host.dse_workloads, SortedSet) + self.assertIn("Cassandra", host.dse_workloads) + self.assertIn("Graph", host.dse_workloads) + + +@requiredse +class GraphExecutionProfileOptionsResolveTest(GraphUnitTestCase): + """ + Test that the execution profile options are properly resolved for graph queries. + + @since DSE 6.8 + @jira_ticket PYTHON-1004 PYTHON-1056 + @expected_result execution profile options are properly determined following the rules. + """ + + def test_default_options(self): + ep = self.session.get_execution_profile(EXEC_PROFILE_GRAPH_DEFAULT) + self.assertEqual(ep.graph_options.graph_protocol, None) + self.assertEqual(ep.row_factory, None) + self.session._resolve_execution_profile_options(ep) + self.assertEqual(ep.graph_options.graph_protocol, GraphProtocol.GRAPHSON_1_0) + self.assertEqual(ep.row_factory, graph_object_row_factory) + + def test_default_options_when_not_groovy(self): + ep = self.session.get_execution_profile(EXEC_PROFILE_GRAPH_DEFAULT) + self.assertEqual(ep.graph_options.graph_protocol, None) + self.assertEqual(ep.row_factory, None) + ep.graph_options.graph_language = 'whatever' + self.session._resolve_execution_profile_options(ep) + self.assertEqual(ep.graph_options.graph_protocol, GraphProtocol.GRAPHSON_2_0) + self.assertEqual(ep.row_factory, graph_graphson2_row_factory) + + def test_default_options_when_explicitly_specified(self): + ep = self.session.get_execution_profile(EXEC_PROFILE_GRAPH_DEFAULT) + self.assertEqual(ep.graph_options.graph_protocol, None) + self.assertEqual(ep.row_factory, None) + obj = object() + ep.graph_options.graph_protocol = obj + ep.row_factory = obj + self.session._resolve_execution_profile_options(ep) + self.assertEqual(ep.graph_options.graph_protocol, obj) + self.assertEqual(ep.row_factory, obj) + + @greaterthanorequaldse68 + def test_graph_protocol_default_for_core_is_graphson3(self): + """Test that graphson3 is automatically resolved for a core graph query""" + self.setup_graph(CoreGraphSchema) + ep = self.session.get_execution_profile(EXEC_PROFILE_GRAPH_DEFAULT) + self.assertEqual(ep.graph_options.graph_protocol, None) + self.assertEqual(ep.row_factory, None) + # Ensure we have the graph metadata + self.session.cluster.refresh_schema_metadata() + self.session._resolve_execution_profile_options(ep) + self.assertEqual(ep.graph_options.graph_protocol, GraphProtocol.GRAPHSON_3_0) + self.assertEqual(ep.row_factory, graph_graphson3_row_factory) + + self.execute_graph_queries(CoreGraphSchema.fixtures.classic(), verify_graphson=GraphProtocol.GRAPHSON_3_0) + + @greaterthanorequaldse68 + def test_graph_protocol_default_for_core_fallback_to_graphson1_if_no_graph_name(self): + """Test that graphson1 is set when we cannot detect if it's a core graph""" + self.setup_graph(CoreGraphSchema) + default_ep = self.session.get_execution_profile(EXEC_PROFILE_GRAPH_DEFAULT) + graph_options = default_ep.graph_options.copy() + graph_options.graph_name = None + ep = self.session.execution_profile_clone_update(EXEC_PROFILE_GRAPH_DEFAULT, graph_options=graph_options) + self.session._resolve_execution_profile_options(ep) + self.assertEqual(ep.graph_options.graph_protocol, GraphProtocol.GRAPHSON_1_0) + self.assertEqual(ep.row_factory, graph_object_row_factory) + + regex = re.compile(".*Variable.*is unknown.*", re.S) + with six.assertRaisesRegex(self, SyntaxException, regex): + self.execute_graph_queries(CoreGraphSchema.fixtures.classic(), + execution_profile=ep, verify_graphson=GraphProtocol.GRAPHSON_1_0) diff --git a/tests/integration/advanced/graph/test_graph_cont_paging.py b/tests/integration/advanced/graph/test_graph_cont_paging.py new file mode 100644 index 0000000..065d01d --- /dev/null +++ b/tests/integration/advanced/graph/test_graph_cont_paging.py @@ -0,0 +1,78 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from cassandra.cluster import ContinuousPagingOptions + +from tests.integration import greaterthanorequaldse68 +from tests.integration.advanced.graph import GraphUnitTestCase, CoreGraphSchema, GraphTestConfiguration + + +@greaterthanorequaldse68 +@GraphTestConfiguration.generate_tests(schema=CoreGraphSchema) +class GraphPagingTest(GraphUnitTestCase): + + def _setup_data(self, schema, graphson): + self.execute_graph("schema.vertexLabel('person').ifNotExists().partitionBy('name', Text).property('age', Int).create();", graphson) + for i in range(100): + self.execute_graph("g.addV('person').property('name', 'batman-{}')".format(i), graphson) + + def _test_cont_paging_is_enabled_by_default(self, schema, graphson): + """ + Test that graph paging is automatically enabled with a >=6.8 cluster. + + @jira_ticket PYTHON-1045 + @expected_result the response future has a continuous_paging_session since graph paging is enabled + + @test_category dse graph + """ + ep = self.get_execution_profile(graphson) + self._setup_data(schema, graphson) + rf = self.session.execute_graph_async("g.V()", execution_profile=ep) + results = list(rf.result()) + self.assertIsNotNone(rf._continuous_paging_session) + self.assertEqual(len(results), 100) + + def _test_cont_paging_can_be_disabled(self, schema, graphson): + """ + Test that graph paging can be disabled. + + @jira_ticket PYTHON-1045 + @expected_result the response future doesn't have a continuous_paging_session since graph paging is disabled + + @test_category dse graph + """ + ep = self.get_execution_profile(graphson) + new_ep = self.session.execution_profile_clone_update(ep, continuous_paging_options=None) + self._setup_data(schema, graphson) + rf = self.session.execute_graph_async("g.V()", execution_profile=new_ep) + results = list(rf.result()) + self.assertIsNone(rf._continuous_paging_session) + self.assertEqual(len(results), 100) + + def _test_cont_paging_with_custom_options(self, schema, graphson): + """ + Test that we can specify custom paging options. + + @jira_ticket PYTHON-1045 + @expected_result we get only the desired number of results + + @test_category dse graph + """ + ep = self.get_execution_profile(graphson) + new_ep = self.session.execution_profile_clone_update( + ep, continuous_paging_options=ContinuousPagingOptions(max_pages=1)) + self._setup_data(schema, graphson) + self.session.default_fetch_size = 10 + results = list(self.session.execute_graph("g.V()", execution_profile=new_ep)) + self.assertEqual(len(results), 10) diff --git a/tests/integration/advanced/graph/test_graph_datatype.py b/tests/integration/advanced/graph/test_graph_datatype.py new file mode 100644 index 0000000..222b1f5 --- /dev/null +++ b/tests/integration/advanced/graph/test_graph_datatype.py @@ -0,0 +1,270 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +import time +import six +import logging +from packaging.version import Version +from collections import namedtuple + +from cassandra.cluster import EXEC_PROFILE_GRAPH_DEFAULT +from cassandra.graph import graph_result_row_factory +from cassandra.graph.query import GraphProtocol +from cassandra.graph.types import VertexProperty + +from tests.util import wait_until +from tests.integration.advanced.graph import BasicGraphUnitTestCase, ClassicGraphFixtures, \ + ClassicGraphSchema, CoreGraphSchema +from tests.integration.advanced.graph import VertexLabel, GraphTestConfiguration, GraphUnitTestCase +from tests.integration import DSE_VERSION, requiredse + +log = logging.getLogger(__name__) + + +@requiredse +class GraphBasicDataTypesTests(BasicGraphUnitTestCase): + + def test_result_types(self): + """ + Test to validate that the edge and vertex version of results are constructed correctly. + + @since 1.0.0 + @jira_ticket PYTHON-479 + @expected_result edge/vertex result types should be unpacked correctly. + @test_category dse graph + """ + queries, params = ClassicGraphFixtures.multiple_fields() + for query in queries: + self.session.execute_graph(query, params) + + prof = self.session.execution_profile_clone_update(EXEC_PROFILE_GRAPH_DEFAULT, row_factory=graph_result_row_factory) # requires simplified row factory to avoid shedding id/~type information used for validation below + rs = self.session.execute_graph("g.V()", execution_profile=prof) + + for result in rs: + self._validate_type(result) + + def _validate_type(self, vertex): + for properties in vertex.properties.values(): + prop = properties[0] + + if DSE_VERSION >= Version("5.1"): + type_indicator = prop['id']['~label'] + else: + type_indicator = prop['id']['~type'] + + if any(type_indicator.startswith(t) for t in + ('int', 'short', 'long', 'bigint', 'decimal', 'smallint', 'varint')): + typ = six.integer_types + elif any(type_indicator.startswith(t) for t in ('float', 'double')): + typ = float + elif any(type_indicator.startswith(t) for t in ('duration', 'date', 'negdate', 'time', + 'blob', 'timestamp', 'point', 'linestring', 'polygon', + 'inet', 'uuid')): + typ = six.text_type + else: + pass + self.fail("Received unexpected type: %s" % type_indicator) + self.assertIsInstance(prop['value'], typ) + + +class GenericGraphDataTypeTest(GraphUnitTestCase): + + def _test_all_datatypes(self, schema, graphson): + ep = self.get_execution_profile(graphson) + + for data in six.itervalues(schema.fixtures.datatypes()): + typ, value, deserializer = data + vertex_label = VertexLabel([typ]) + property_name = next(six.iterkeys(vertex_label.non_pk_properties)) + schema.create_vertex_label(self.session, vertex_label, execution_profile=ep) + vertex = list(schema.add_vertex(self.session, vertex_label, property_name, value, execution_profile=ep))[0] + + def get_vertex_properties(): + return list(schema.get_vertex_properties( + self.session, vertex, execution_profile=ep)) + + prop_returned = 1 if DSE_VERSION < Version('5.1') else 2 # include pkid >=5.1 + wait_until( + lambda: len(get_vertex_properties()) == prop_returned, 0.2, 15) + + vertex_properties = get_vertex_properties() + if graphson == GraphProtocol.GRAPHSON_1_0: + vertex_properties = [vp.as_vertex_property() for vp in vertex_properties] + + for vp in vertex_properties: + if vp.label == 'pkid': + continue + + self.assertIsInstance(vp, VertexProperty) + self.assertEqual(vp.label, property_name) + if graphson == GraphProtocol.GRAPHSON_1_0: + deserialized_value = deserializer(vp.value) if deserializer else vp.value + self.assertEqual(deserialized_value, value) + else: + self.assertEqual(vp.value, value) + + def __test_udt(self, schema, graphson, address_class, address_with_tags_class, + complex_address_class, complex_address_with_owners_class): + if schema is not CoreGraphSchema or DSE_VERSION < Version('6.8'): + raise unittest.SkipTest("Graph UDT is only supported with DSE 6.8+ and Core graphs.") + + ep = self.get_execution_profile(graphson) + + Address = address_class + AddressWithTags = address_with_tags_class + ComplexAddress = complex_address_class + ComplexAddressWithOwners = complex_address_with_owners_class + + # setup udt + self.session.execute_graph(""" + schema.type('address').property('address', Text).property('city', Text).property('state', Text).create(); + schema.type('addressTags').property('address', Text).property('city', Text).property('state', Text). + property('tags', setOf(Text)).create(); + schema.type('complexAddress').property('address', Text).property('address_tags', frozen(typeOf('addressTags'))). + property('city', Text).property('state', Text).property('props', mapOf(Text, Int)).create(); + schema.type('complexAddressWithOwners').property('address', Text). + property('address_tags', frozen(typeOf('addressTags'))). + property('city', Text).property('state', Text).property('props', mapOf(Text, Int)). + property('owners', frozen(listOf(tupleOf(Text, Int)))).create(); + """, execution_profile=ep) + + time.sleep(2) # wait the UDT to be discovered + self.session.cluster.register_user_type(self.graph_name, 'address', Address) + self.session.cluster.register_user_type(self.graph_name, 'addressTags', AddressWithTags) + self.session.cluster.register_user_type(self.graph_name, 'complexAddress', ComplexAddress) + self.session.cluster.register_user_type(self.graph_name, 'complexAddressWithOwners', ComplexAddressWithOwners) + + data = { + "udt1": ["typeOf('address')", Address('1440 Rd Smith', 'Quebec', 'QC')], + "udt2": ["tupleOf(typeOf('address'), Text)", (Address('1440 Rd Smith', 'Quebec', 'QC'), 'hello')], + "udt3": ["tupleOf(frozen(typeOf('address')), Text)", (Address('1440 Rd Smith', 'Quebec', 'QC'), 'hello')], + "udt4": ["tupleOf(tupleOf(Int, typeOf('address')), Text)", + ((42, Address('1440 Rd Smith', 'Quebec', 'QC')), 'hello')], + "udt5": ["tupleOf(tupleOf(Int, typeOf('addressTags')), Text)", + ((42, AddressWithTags('1440 Rd Smith', 'Quebec', 'QC', {'t1', 't2'})), 'hello')], + "udt6": ["tupleOf(tupleOf(Int, typeOf('complexAddress')), Text)", + ((42, ComplexAddress('1440 Rd Smith', + AddressWithTags('1440 Rd Smith', 'Quebec', 'QC', {'t1', 't2'}), + 'Quebec', 'QC', {'p1': 42, 'p2': 33})), 'hello')], + "udt7": ["tupleOf(tupleOf(Int, frozen(typeOf('complexAddressWithOwners'))), Text)", + ((42, ComplexAddressWithOwners( + '1440 Rd Smith', + AddressWithTags('1440 CRd Smith', 'Quebec', 'QC', {'t1', 't2'}), + 'Quebec', 'QC', {'p1': 42, 'p2': 33}, [('Mike', 43), ('Gina', 39)]) + ), 'hello')] + } + + for typ, value in six.itervalues(data): + vertex_label = VertexLabel([typ]) + property_name = next(six.iterkeys(vertex_label.non_pk_properties)) + schema.create_vertex_label(self.session, vertex_label, execution_profile=ep) + + vertex = list(schema.add_vertex(self.session, vertex_label, property_name, value, execution_profile=ep))[0] + + def get_vertex_properties(): + return list(schema.get_vertex_properties( + self.session, vertex, execution_profile=ep)) + + wait_until( + lambda: len(get_vertex_properties()) == 2, 0.2, 15) + + vertex_properties = get_vertex_properties() + for vp in vertex_properties: + if vp.label == 'pkid': + continue + + self.assertIsInstance(vp, VertexProperty) + self.assertEqual(vp.label, property_name) + self.assertEqual(vp.value, value) + + def _test_udt_with_classes(self, schema, graphson): + class Address(object): + + def __init__(self, address, city, state): + self.address = address + self.city = city + self.state = state + + def __eq__(self, other): + return self.address == other.address and self.city == other.city and self.state == other.state + + class AddressWithTags(object): + + def __init__(self, address, city, state, tags): + self.address = address + self.city = city + self.state = state + self.tags = tags + + def __eq__(self, other): + return (self.address == other.address and self.city == other.city + and self.state == other.state and self.tags == other.tags) + + class ComplexAddress(object): + + def __init__(self, address, address_tags, city, state, props): + self.address = address + self.address_tags = address_tags + self.city = city + self.state = state + self.props = props + + def __eq__(self, other): + return (self.address == other.address and self.address_tags == other.address_tags + and self.city == other.city and self.state == other.state + and self.props == other.props) + + class ComplexAddressWithOwners(object): + + def __init__(self, address, address_tags, city, state, props, owners): + self.address = address + self.address_tags = address_tags + self.city = city + self.state = state + self.props = props + self.owners = owners + + def __eq__(self, other): + return (self.address == other.address and self.address_tags == other.address_tags + and self.city == other.city and self.state == other.state + and self.props == other.props and self.owners == other.owners) + + self.__test_udt(schema, graphson, Address, AddressWithTags, ComplexAddress, ComplexAddressWithOwners) + + def _test_udt_with_namedtuples(self, schema, graphson): + AddressTuple = namedtuple('Address', ('address', 'city', 'state')) + AddressWithTagsTuple = namedtuple('AddressWithTags', ('address', 'city', 'state', 'tags')) + ComplexAddressTuple = namedtuple('ComplexAddress', ('address', 'address_tags', 'city', 'state', 'props')) + ComplexAddressWithOwnersTuple = namedtuple('ComplexAddressWithOwners', ('address', 'address_tags', 'city', + 'state', 'props', 'owners')) + + self.__test_udt(schema, graphson, AddressTuple, AddressWithTagsTuple, + ComplexAddressTuple, ComplexAddressWithOwnersTuple) + + +@requiredse +@GraphTestConfiguration.generate_tests(schema=ClassicGraphSchema) +class ClassicGraphDataTypeTest(GenericGraphDataTypeTest): + pass + + +@requiredse +@GraphTestConfiguration.generate_tests(schema=CoreGraphSchema) +class CoreGraphDataTypeTest(GenericGraphDataTypeTest): + pass diff --git a/tests/integration/advanced/graph/test_graph_query.py b/tests/integration/advanced/graph/test_graph_query.py new file mode 100644 index 0000000..0eda678 --- /dev/null +++ b/tests/integration/advanced/graph/test_graph_query.py @@ -0,0 +1,598 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import sys +import six +from packaging.version import Version + +from copy import copy +from itertools import chain +import json +import time + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +from cassandra import OperationTimedOut, ConsistencyLevel, InvalidRequest +from cassandra.cluster import EXEC_PROFILE_GRAPH_DEFAULT, NoHostAvailable +from cassandra.protocol import ServerError, SyntaxException +from cassandra.query import QueryTrace +from cassandra.util import Point +from cassandra.graph import (SimpleGraphStatement, single_object_row_factory, + Result, GraphOptions, GraphProtocol, to_bigint) +from cassandra.datastax.graph.query import _graph_options +from cassandra.datastax.graph.types import T + +from tests.integration import DSE_VERSION, requiredse, greaterthanorequaldse68 +from tests.integration.advanced.graph import BasicGraphUnitTestCase, GraphTestConfiguration, \ + validate_classic_vertex, GraphUnitTestCase, validate_classic_edge, validate_path_result_type, \ + validate_line_edge, validate_generic_vertex_result_type, \ + ClassicGraphSchema, CoreGraphSchema, VertexLabel + + +@requiredse +class BasicGraphQueryTest(BasicGraphUnitTestCase): + + def test_consistency_passing(self): + """ + Test to validated that graph consistency levels are properly surfaced to the base driver + + @since 1.0.0 + @jira_ticket PYTHON-509 + @expected_result graph consistency levels are surfaced correctly + @test_category dse graph + """ + cl_attrs = ('graph_read_consistency_level', 'graph_write_consistency_level') + + # Iterates over the graph options and constructs an array containing + # The graph_options that correlate to graoh read and write consistency levels + graph_params = [a[2] for a in _graph_options if a[0] in cl_attrs] + + s = self.session + default_profile = s.cluster.profile_manager.profiles[EXEC_PROFILE_GRAPH_DEFAULT] + default_graph_opts = default_profile.graph_options + try: + # Checks the default graph attributes and ensures that both graph_read_consistency_level and graph_write_consistency_level + # Are None by default + for attr in cl_attrs: + self.assertIsNone(getattr(default_graph_opts, attr)) + + res = s.execute_graph("null") + for param in graph_params: + self.assertNotIn(param, res.response_future.message.custom_payload) + + # session defaults are passed + opts = GraphOptions() + opts.update(default_graph_opts) + cl = {0: ConsistencyLevel.ONE, 1: ConsistencyLevel.LOCAL_QUORUM} + for k, v in cl.items(): + setattr(opts, cl_attrs[k], v) + default_profile.graph_options = opts + + res = s.execute_graph("null") + + for k, v in cl.items(): + self.assertEqual(res.response_future.message.custom_payload[graph_params[k]], six.b(ConsistencyLevel.value_to_name[v])) + + # passed profile values override session defaults + cl = {0: ConsistencyLevel.ALL, 1: ConsistencyLevel.QUORUM} + opts = GraphOptions() + opts.update(default_graph_opts) + for k, v in cl.items(): + attr_name = cl_attrs[k] + setattr(opts, attr_name, v) + self.assertNotEqual(getattr(default_profile.graph_options, attr_name), getattr(opts, attr_name)) + tmp_profile = s.execution_profile_clone_update(EXEC_PROFILE_GRAPH_DEFAULT, graph_options=opts) + res = s.execute_graph("null", execution_profile=tmp_profile) + + for k, v in cl.items(): + self.assertEqual(res.response_future.message.custom_payload[graph_params[k]], six.b(ConsistencyLevel.value_to_name[v])) + finally: + default_profile.graph_options = default_graph_opts + + def test_execute_graph_row_factory(self): + s = self.session + + # default Results + default_profile = s.cluster.profile_manager.profiles[EXEC_PROFILE_GRAPH_DEFAULT] + self.assertEqual(default_profile.row_factory, None) # will be resolved to graph_object_row_factory + result = s.execute_graph("123")[0] + self.assertIsInstance(result, Result) + self.assertEqual(result.value, 123) + + # other via parameter + prof = s.execution_profile_clone_update(EXEC_PROFILE_GRAPH_DEFAULT, row_factory=single_object_row_factory) + rs = s.execute_graph("123", execution_profile=prof) + self.assertEqual(rs.response_future.row_factory, single_object_row_factory) + self.assertEqual(json.loads(rs[0]), {'result': 123}) + + def test_execute_graph_timeout(self): + s = self.session + + value = [1, 2, 3] + query = "[%r]" % (value,) + + # default is passed down + default_graph_profile = s.cluster.profile_manager.profiles[EXEC_PROFILE_GRAPH_DEFAULT] + rs = self.session.execute_graph(query) + self.assertEqual(rs[0].value, value) + self.assertEqual(rs.response_future.timeout, default_graph_profile.request_timeout) + + # tiny timeout times out as expected + tmp_profile = copy(default_graph_profile) + tmp_profile.request_timeout = sys.float_info.min + + max_retry_count = 10 + for _ in range(max_retry_count): + start = time.time() + try: + with self.assertRaises(OperationTimedOut): + s.execute_graph(query, execution_profile=tmp_profile) + break + except: + end = time.time() + self.assertAlmostEqual(start, end, 1) + else: + raise Exception("session.execute_graph didn't time out in {0} tries".format(max_retry_count)) + + def test_profile_graph_options(self): + s = self.session + statement = SimpleGraphStatement("true") + ep = self.session.execution_profile_clone_update(EXEC_PROFILE_GRAPH_DEFAULT) + self.assertTrue(s.execute_graph(statement, execution_profile=ep)[0].value) + + # bad graph name to verify it's passed + ep.graph_options = ep.graph_options.copy() + ep.graph_options.graph_name = "definitely_not_correct" + try: + s.execute_graph(statement, execution_profile=ep) + except NoHostAvailable: + self.assertTrue(DSE_VERSION >= Version("6.0")) + except InvalidRequest: + self.assertTrue(DSE_VERSION >= Version("5.0")) + else: + if DSE_VERSION < Version("6.8"): # >6.8 returns true + self.fail("Should have risen ServerError or InvalidRequest") + + def test_additional_custom_payload(self): + s = self.session + custom_payload = {'some': 'example'.encode('utf-8'), 'items': 'here'.encode('utf-8')} + sgs = SimpleGraphStatement("null", custom_payload=custom_payload) + future = s.execute_graph_async(sgs) + + default_profile = s.cluster.profile_manager.profiles[EXEC_PROFILE_GRAPH_DEFAULT] + default_graph_opts = default_profile.graph_options + for k, v in chain(custom_payload.items(), default_graph_opts.get_options_map().items()): + self.assertEqual(future.message.custom_payload[k], v) + + +class GenericGraphQueryTest(GraphUnitTestCase): + + def _test_basic_query(self, schema, graphson): + """ + Test to validate that basic graph query results can be executed with a sane result set. + + Creates a simple classic tinkerpot graph, and attempts to find all vertices + related the vertex marco, that have a label of knows. + See reference graph here + http://www.tinkerpop.com/docs/3.0.0.M1/ + + @since 1.0.0 + @jira_ticket PYTHON-457 + @expected_result graph should find two vertices related to marco via 'knows' edges. + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.classic(), graphson) + rs = self.execute_graph('''g.V().has('name','marko').out('knows').values('name')''', graphson) + self.assertFalse(rs.has_more_pages) + results_list = self.resultset_to_list(rs) + self.assertEqual(len(results_list), 2) + self.assertIn('vadas', results_list) + self.assertIn('josh', results_list) + + def _test_geometric_graph_types(self, schema, graphson): + """ + Test to validate that geometric types function correctly + + Creates a very simple graph, and tries to insert a simple point type + + @since 1.0.0 + @jira_ticket DSP-8087 + @expected_result json types associated with insert is parsed correctly + + @test_category dse graph + """ + vertex_label = VertexLabel([('pointP', "Point()")]) + ep = self.get_execution_profile(graphson) + schema.create_vertex_label(self.session, vertex_label, ep) + # import org.apache.cassandra.db.marshal.geometry.Point; + rs = schema.add_vertex(self.session, vertex_label, 'pointP', Point(0, 1), ep) + + # if result set is not parsed correctly this will throw an exception + self.assertIsNotNone(rs) + + def _test_execute_graph_trace(self, schema, graphson): + value = [1, 2, 3] + query = "[%r]" % (value,) + + # default is no trace + rs = self.execute_graph(query, graphson) + results = self.resultset_to_list(rs) + self.assertEqual(results[0], value) + self.assertIsNone(rs.get_query_trace()) + + # request trace + rs = self.execute_graph(query, graphson, trace=True) + results = self.resultset_to_list(rs) + self.assertEqual(results[0], value) + qt = rs.get_query_trace(max_wait_sec=10) + self.assertIsInstance(qt, QueryTrace) + self.assertIsNotNone(qt.duration) + + def _test_range_query(self, schema, graphson): + """ + Test to validate range queries are handled correctly. + + Creates a very large line graph script and executes it. Then proceeds to to a range + limited query against it, and ensure that the results are formatted correctly and that + the result set is properly sized. + + @since 1.0.0 + @jira_ticket PYTHON-457 + @expected_result result set should be properly formatted and properly sized + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.line(150), graphson) + rs = self.execute_graph("g.E().range(0,10)", graphson) + self.assertFalse(rs.has_more_pages) + results = self.resultset_to_list(rs) + self.assertEqual(len(results), 10) + ep = self.get_execution_profile(graphson) + for result in results: + schema.ensure_properties(self.session, result, execution_profile=ep) + validate_line_edge(self, result) + + def _test_classic_graph(self, schema, graphson): + """ + Test to validate that basic graph generation, and vertex and edges are surfaced correctly + + Creates a simple classic tinkerpot graph, and iterates over the the vertices and edges + ensureing that each one is correct. See reference graph here + http://www.tinkerpop.com/docs/3.0.0.M1/ + + @since 1.0.0 + @jira_ticket PYTHON-457 + @expected_result graph should generate and all vertices and edge results should be + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.classic(), graphson) + rs = self.execute_graph('g.V()', graphson) + ep = self.get_execution_profile(graphson) + for vertex in rs: + schema.ensure_properties(self.session, vertex, execution_profile=ep) + validate_classic_vertex(self, vertex) + rs = self.execute_graph('g.E()', graphson) + for edge in rs: + schema.ensure_properties(self.session, edge, execution_profile=ep) + validate_classic_edge(self, edge) + + def _test_graph_classic_path(self, schema, graphson): + """ + Test to validate that the path version of the result type is generated correctly. It also + tests basic path results as that is not covered elsewhere + + @since 1.0.0 + @jira_ticket PYTHON-479 + @expected_result path object should be unpacked correctly including all nested edges and verticies + @test_category dse graph + """ + self.execute_graph(schema.fixtures.classic(), graphson) + rs = self.execute_graph("g.V().hasLabel('person').has('name', 'marko').as('a').outE('knows').inV().as('c', 'd')." + " outE('created').as('e', 'f', 'g').inV().path()", + graphson) + rs_list = list(rs) + self.assertEqual(len(rs_list), 2) + for result in rs_list: + try: + path = result.as_path() + except: + path = result + + ep = self.get_execution_profile(graphson) + for obj in path.objects: + schema.ensure_properties(self.session, obj, ep) + + validate_path_result_type(self, path) + + def _test_large_create_script(self, schema, graphson): + """ + Test to validate that server errors due to large groovy scripts are properly surfaced + + Creates a very large line graph script and executes it. Then proceeds to create a line graph script + that is to large for the server to handle expects a server error to be returned + + @since 1.0.0 + @jira_ticket PYTHON-457 + @expected_result graph should generate and all vertices and edge results should be + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.line(150), graphson) + self.execute_graph(schema.fixtures.line(300), graphson) # This should passed since the queries are splitted + self.assertRaises(SyntaxException, self.execute_graph, schema.fixtures.line(300, single_script=True), graphson) # this is not and too big + + def _test_large_result_set(self, schema, graphson): + """ + Test to validate that large result sets return correctly. + + Creates a very large graph. Ensures that large result sets are handled appropriately. + + @since 1.0.0 + @jira_ticket PYTHON-457 + @expected_result when limits of result sets are hit errors should be surfaced appropriately + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.large(), graphson, execution_profile_options={'request_timeout': 32}) + rs = self.execute_graph("g.V()", graphson) + for result in rs: + validate_generic_vertex_result_type(self, result) + + def _test_param_passing(self, schema, graphson): + """ + Test to validate that parameter passing works as expected + + @since 1.0.0 + @jira_ticket PYTHON-457 + @expected_result parameters work as expected + + @test_category dse graph + """ + + # unused parameters are passed, but ignored + self.execute_graph("null", graphson, params={"doesn't": "matter", "what's": "passed"}) + + # multiple params + rs = self.execute_graph("[a, b]", graphson, params={'a': 0, 'b': 1}) + results = self.resultset_to_list(rs) + self.assertEqual(results[0], 0) + self.assertEqual(results[1], 1) + + if graphson == GraphProtocol.GRAPHSON_1_0: + # different value types + for param in (None, "string", 1234, 5.678, True, False): + result = self.resultset_to_list(self.execute_graph('x', graphson, params={'x': param}))[0] + self.assertEqual(result, param) + + def _test_vertex_property_properties(self, schema, graphson): + """ + Test verifying vertex property properties + + @since 1.0.0 + @jira_ticket PYTHON-487 + + @test_category dse graph + """ + if schema is not ClassicGraphSchema: + raise unittest.SkipTest('skipped because rich properties are only supported with classic graphs') + + self.execute_graph("schema.propertyKey('k0').Text().ifNotExists().create();", graphson) + self.execute_graph("schema.propertyKey('k1').Text().ifNotExists().create();", graphson) + self.execute_graph("schema.propertyKey('key').Text().properties('k0', 'k1').ifNotExists().create();", graphson) + self.execute_graph("schema.vertexLabel('MLP').properties('key').ifNotExists().create();", graphson) + v = self.execute_graph('''v = graph.addVertex('MLP') + v.property('key', 'value', 'k0', 'v0', 'k1', 'v1') + v''', graphson)[0] + self.assertEqual(len(v.properties), 1) + self.assertEqual(len(v.properties['key']), 1) + p = v.properties['key'][0] + self.assertEqual(p.label, 'key') + self.assertEqual(p.value, 'value') + self.assertEqual(p.properties, {'k0': 'v0', 'k1': 'v1'}) + + def _test_vertex_multiple_properties(self, schema, graphson): + """ + Test verifying vertex property form for various Cardinality + + All key types are encoded as a list, regardless of cardinality + + Single cardinality properties have only one value -- the last one added + + Default is single (this is config dependent) + + @since 1.0.0 + @jira_ticket PYTHON-487 + + @test_category dse graph + """ + if schema is not ClassicGraphSchema: + raise unittest.SkipTest('skipped because multiple properties are only supported with classic graphs') + + self.execute_graph('''Schema schema = graph.schema(); + schema.propertyKey('mult_key').Text().multiple().ifNotExists().create(); + schema.propertyKey('single_key').Text().single().ifNotExists().create(); + schema.vertexLabel('MPW1').properties('mult_key').ifNotExists().create(); + schema.vertexLabel('SW1').properties('single_key').ifNotExists().create();''', graphson) + + v = self.execute_graph('''v = graph.addVertex('MPW1') + v.property('mult_key', 'value') + v''', graphson)[0] + self.assertEqual(len(v.properties), 1) + self.assertEqual(len(v.properties['mult_key']), 1) + self.assertEqual(v.properties['mult_key'][0].label, 'mult_key') + self.assertEqual(v.properties['mult_key'][0].value, 'value') + + # multiple_with_two_values + v = self.execute_graph('''g.addV('MPW1').property('mult_key', 'value0').property('mult_key', 'value1')''', graphson)[0] + self.assertEqual(len(v.properties), 1) + self.assertEqual(len(v.properties['mult_key']), 2) + self.assertEqual(v.properties['mult_key'][0].label, 'mult_key') + self.assertEqual(v.properties['mult_key'][1].label, 'mult_key') + self.assertEqual(v.properties['mult_key'][0].value, 'value0') + self.assertEqual(v.properties['mult_key'][1].value, 'value1') + + # single_with_one_value + v = self.execute_graph('''v = graph.addVertex('SW1') + v.property('single_key', 'value') + v''', graphson)[0] + self.assertEqual(len(v.properties), 1) + self.assertEqual(len(v.properties['single_key']), 1) + self.assertEqual(v.properties['single_key'][0].label, 'single_key') + self.assertEqual(v.properties['single_key'][0].value, 'value') + + if DSE_VERSION < Version('6.8'): + # single_with_two_values + with self.assertRaises(InvalidRequest): + v = self.execute_graph(''' + v = graph.addVertex('SW1') + v.property('single_key', 'value0').property('single_key', 'value1').next() + v + ''', graphson)[0] + else: + # >=6.8 single_with_two_values, first one wins + v = self.execute_graph('''v = graph.addVertex('SW1') + v.property('single_key', 'value0').property('single_key', 'value1') + v''', graphson)[0] + self.assertEqual(v.properties['single_key'][0].value, 'value0') + + def _test_result_forms(self, schema, graphson): + """ + Test to validate that geometric types function correctly + + Creates a very simple graph, and tries to insert a simple point type + + @since 1.0.0 + @jira_ticket DSP-8087 + @expected_result json types associated with insert is parsed correctly + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.classic(), graphson) + ep = self.get_execution_profile(graphson) + + results = self.resultset_to_list(self.session.execute_graph('g.V()', execution_profile=ep)) + self.assertGreater(len(results), 0, "Result set was empty this was not expected") + for v in results: + schema.ensure_properties(self.session, v, ep) + validate_classic_vertex(self, v) + + results = self.resultset_to_list(self.session.execute_graph('g.E()', execution_profile=ep)) + self.assertGreater(len(results), 0, "Result set was empty this was not expected") + for e in results: + schema.ensure_properties(self.session, e, ep) + validate_classic_edge(self, e) + + def _test_query_profile(self, schema, graphson): + """ + Test to validate profiling results are deserialized properly. + + @since 1.6.0 + @jira_ticket PYTHON-1057 + @expected_result TraversalMetrics and Metrics are deserialized properly + + @test_category dse graph + """ + if graphson == GraphProtocol.GRAPHSON_1_0: + raise unittest.SkipTest('skipped because there is no metrics deserializer with graphson1') + + ep = self.get_execution_profile(graphson) + results = list(self.session.execute_graph("g.V().profile()", execution_profile=ep)) + self.assertEqual(len(results), 1) + self.assertIn('metrics', results[0]) + self.assertIn('dur', results[0]) + self.assertEqual(len(results[0]['metrics']), 2) + self.assertIn('dur', results[0]['metrics'][0]) + + def _test_query_bulkset(self, schema, graphson): + """ + Test to validate bulkset results are deserialized properly. + + @since 1.6.0 + @jira_ticket PYTHON-1060 + @expected_result BulkSet is deserialized properly to a list + + @test_category dse graph + """ + self.execute_graph(schema.fixtures.classic(), graphson) + ep = self.get_execution_profile(graphson) + results = list(self.session.execute_graph( + 'g.V().hasLabel("person").aggregate("x").by("age").cap("x")', + execution_profile=ep)) + self.assertEqual(len(results), 1) + results = results[0] + if type(results) is Result: + results = results.value + else: + self.assertEqual(len(results), 5) + self.assertEqual(results.count(35), 2) + + @greaterthanorequaldse68 + def _test_elementMap_query(self, schema, graphson): + """ + Test to validate that an elementMap can be serialized properly. + """ + self.execute_graph(schema.fixtures.classic(), graphson) + rs = self.execute_graph('''g.V().has('name','marko').elementMap()''', graphson) + results_list = self.resultset_to_list(rs) + self.assertEqual(len(results_list), 1) + row = results_list[0] + if graphson == GraphProtocol.GRAPHSON_3_0: + self.assertIn(T.id, row) + self.assertIn(T.label, row) + if schema is CoreGraphSchema: + self.assertEqual(row[T.id], 'dseg:/person/marko') + self.assertEqual(row[T.label], 'person') + else: + self.assertIn('id', row) + self.assertIn('label', row) + + +@GraphTestConfiguration.generate_tests(schema=ClassicGraphSchema) +class ClassicGraphQueryTest(GenericGraphQueryTest): + pass + + +@GraphTestConfiguration.generate_tests(schema=CoreGraphSchema) +class CoreGraphQueryTest(GenericGraphQueryTest): + pass + + +@GraphTestConfiguration.generate_tests(schema=CoreGraphSchema) +class CoreGraphQueryWithTypeWrapperTest(GraphUnitTestCase): + + def _test_basic_query_with_type_wrapper(self, schema, graphson): + """ + Test to validate that a query using a type wrapper works. + + @since 2.8.0 + @jira_ticket PYTHON-1051 + @expected_result graph query works and doesn't raise an exception + + @test_category dse graph + """ + ep = self.get_execution_profile(graphson) + vl = VertexLabel(['tupleOf(Int, Bigint)']) + schema.create_vertex_label(self.session, vl, execution_profile=ep) + + prop_name = next(six.iterkeys(vl.non_pk_properties)) + with self.assertRaises(InvalidRequest): + schema.add_vertex(self.session, vl, prop_name, (1, 42), execution_profile=ep) + + schema.add_vertex(self.session, vl, prop_name, (1, to_bigint(42)), execution_profile=ep) diff --git a/tests/integration/advanced/test_adv_metadata.py b/tests/integration/advanced/test_adv_metadata.py new file mode 100644 index 0000000..b3af6fa --- /dev/null +++ b/tests/integration/advanced/test_adv_metadata.py @@ -0,0 +1,395 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from packaging.version import Version + +from tests.integration import (BasicExistingKeyspaceUnitTestCase, BasicSharedKeyspaceUnitTestCase, + BasicSharedKeyspaceUnitTestCaseRF1, + greaterthanorequaldse51, greaterthanorequaldse60, + greaterthanorequaldse68, use_single_node, + DSE_VERSION, requiredse, TestCluster) + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +import logging +import time + + +log = logging.getLogger(__name__) + + +def setup_module(): + if DSE_VERSION: + use_single_node() + + +@requiredse +@greaterthanorequaldse60 +class FunctionAndAggregateMetadataTests(BasicSharedKeyspaceUnitTestCaseRF1): + + @classmethod + def setUpClass(cls): + if DSE_VERSION: + super(FunctionAndAggregateMetadataTests, cls).setUpClass() + + @classmethod + def tearDownClass(cls): + if DSE_VERSION: + super(FunctionAndAggregateMetadataTests, cls).setUpClass() + + def setUp(self): + self.func_name = self.function_table_name + '_func' + self.agg_name = self.function_table_name + '_agg(int)' + + def _populated_ks_meta_attr(self, attr_name): + val, start_time = None, time.time() + while not val: + self.cluster.refresh_schema_metadata() + val = getattr(self.cluster.metadata.keyspaces[self.keyspace_name], + attr_name) + self.assertLess(time.time(), start_time + 30, + 'did not see func in metadata in 30s') + log.debug('done blocking; dict is populated: {}'.format(val)) + return val + + def test_monotonic_on_and_deterministic_function(self): + self.session.execute(""" + CREATE FUNCTION {ksn}.{ftn}(key int, val int) + RETURNS NULL ON NULL INPUT + RETURNS int + DETERMINISTIC + MONOTONIC ON val + LANGUAGE java AS 'return key+val;'; + """.format(ksn=self.keyspace_name, + ftn=self.func_name)) + fn = self._populated_ks_meta_attr('functions')[ + '{}(int,int)'.format(self.func_name) + ] + self.assertEqual(fn.monotonic_on, ['val']) + # monotonic is not set by MONOTONIC ON + self.assertFalse(fn.monotonic) + self.assertTrue(fn.deterministic) + self.assertEqual('CREATE FUNCTION {ksn}.{ftn}(key int, val int) ' + 'RETURNS NULL ON NULL INPUT ' + 'RETURNS int DETERMINISTIC MONOTONIC ON val ' + 'LANGUAGE java AS $$return key+val;$$' + ''.format(ksn=self.keyspace_name, + ftn=self.func_name), + fn.as_cql_query()) + self.session.execute('DROP FUNCTION {}.{}'.format(self.keyspace_name, + self.func_name)) + self.session.execute(fn.as_cql_query()) + + def test_monotonic_all_and_nondeterministic_function(self): + self.session.execute(""" + CREATE FUNCTION {ksn}.{ftn}(key int, val int) + RETURNS NULL ON NULL INPUT + RETURNS int + MONOTONIC + LANGUAGE java AS 'return key+val;'; + """.format(ksn=self.keyspace_name, + ftn=self.func_name)) + fn = self._populated_ks_meta_attr('functions')[ + '{}(int,int)'.format(self.func_name) + ] + self.assertEqual(set(fn.monotonic_on), {'key', 'val'}) + self.assertTrue(fn.monotonic) + self.assertFalse(fn.deterministic) + self.assertEqual('CREATE FUNCTION {ksn}.{ftn}(key int, val int) ' + 'RETURNS NULL ON NULL INPUT RETURNS int MONOTONIC ' + 'LANGUAGE java AS $$return key+val;$$' + ''.format(ksn=self.keyspace_name, + ftn=self.func_name), + fn.as_cql_query()) + self.session.execute('DROP FUNCTION {}.{}'.format(self.keyspace_name, + self.func_name)) + self.session.execute(fn.as_cql_query()) + + def _create_func_for_aggregate(self): + self.session.execute(""" + CREATE FUNCTION {ksn}.{ftn}(key int, val int) + RETURNS NULL ON NULL INPUT + RETURNS int + DETERMINISTIC + LANGUAGE java AS 'return key+val;'; + """.format(ksn=self.keyspace_name, + ftn=self.func_name)) + + def test_deterministic_aggregate(self): + self._create_func_for_aggregate() + self.session.execute(""" + CREATE AGGREGATE {ksn}.{an} + SFUNC {ftn} + STYPE int + INITCOND 0 + DETERMINISTIC + """.format(ksn=self.keyspace_name, + ftn=self.func_name, + an=self.agg_name)) + ag = self._populated_ks_meta_attr('aggregates')[self.agg_name] + self.assertTrue(ag.deterministic) + self.assertEqual( + 'CREATE AGGREGATE {ksn}.{an} SFUNC ' + '{ftn} STYPE int INITCOND 0 DETERMINISTIC' + ''.format(ksn=self.keyspace_name, + ftn=self.func_name, + an=self.agg_name), + ag.as_cql_query()) + self.session.execute('DROP AGGREGATE {}.{}'.format(self.keyspace_name, + self.agg_name)) + self.session.execute(ag.as_cql_query()) + + def test_nondeterministic_aggregate(self): + self._create_func_for_aggregate() + self.session.execute(""" + CREATE AGGREGATE {ksn}.{an} + SFUNC {ftn} + STYPE int + INITCOND 0 + """.format(ksn=self.keyspace_name, + ftn=self.func_name, + an=self.agg_name)) + ag = self._populated_ks_meta_attr('aggregates')[self.agg_name] + self.assertFalse(ag.deterministic) + self.assertEqual( + 'CREATE AGGREGATE {ksn}.{an} SFUNC ' + '{ftn} STYPE int INITCOND 0' + ''.format(ksn=self.keyspace_name, + ftn=self.func_name, + an=self.agg_name), + ag.as_cql_query()) + self.session.execute('DROP AGGREGATE {}.{}'.format(self.keyspace_name, + self.agg_name)) + self.session.execute(ag.as_cql_query()) + + +@requiredse +class RLACMetadataTests(BasicSharedKeyspaceUnitTestCase): + + @classmethod + def setUpClass(cls): + if DSE_VERSION: + super(RLACMetadataTests, cls).setUpClass() + + @classmethod + def tearDownClass(cls): + if DSE_VERSION: + super(RLACMetadataTests, cls).setUpClass() + + @greaterthanorequaldse51 + def test_rlac_on_table(self): + """ + Checks to ensure that the RLAC table extension appends the proper cql on export to tables + + @since 3.20 + @jira_ticket PYTHON-638 + @expected_result Invalid hosts on the contact list should be excluded + + @test_category metadata + """ + self.session.execute("CREATE TABLE {0}.reports (" + " report_user text, " + " report_number int, " + " report_month int, " + " report_year int, " + " report_text text," + " PRIMARY KEY (report_user, report_number))".format(self.keyspace_name)) + restrict_cql = "RESTRICT ROWS ON {0}.reports USING report_user".format(self.keyspace_name) + self.session.execute(restrict_cql) + table_meta = self.cluster.metadata.keyspaces[self.keyspace_name].tables['reports'] + self.assertTrue(restrict_cql in table_meta.export_as_string()) + + @unittest.skip("Dse 5.1 doesn't support MV and RLAC remove after update") + @greaterthanorequaldse51 + def test_rlac_on_mv(self): + """ + Checks to ensure that the RLAC table extension appends the proper cql to export on mV's + + @since 3.20 + @jira_ticket PYTHON-682 + @expected_result Invalid hosts on the contact list should be excluded + + @test_category metadata + """ + self.session.execute("CREATE TABLE {0}.reports2 (" + " report_user text, " + " report_number int, " + " report_month int, " + " report_year int, " + " report_text text," + " PRIMARY KEY (report_user, report_number))".format(self.keyspace_name)) + self.session.execute("CREATE MATERIALIZED VIEW {0}.reports_by_year AS " + " SELECT report_year, report_user, report_number, report_text FROM {0}.reports2 " + " WHERE report_user IS NOT NULL AND report_number IS NOT NULL AND report_year IS NOT NULL " + " PRIMARY KEY ((report_year, report_user), report_number)".format(self.keyspace_name)) + + restrict_cql_table = "RESTRICT ROWS ON {0}.reports2 USING report_user".format(self.keyspace_name) + self.session.execute(restrict_cql_table) + restrict_cql_view = "RESTRICT ROWS ON {0}.reports_by_year USING report_user".format(self.keyspace_name) + self.session.execute(restrict_cql_view) + table_cql = self.cluster.metadata.keyspaces[self.keyspace_name].tables['reports2'].export_as_string() + view_cql = self.cluster.metadata.keyspaces[self.keyspace_name].tables['reports2'].views["reports_by_year"].export_as_string() + self.assertTrue(restrict_cql_table in table_cql) + self.assertTrue(restrict_cql_view in table_cql) + self.assertTrue(restrict_cql_view in view_cql) + self.assertTrue(restrict_cql_table not in view_cql) + + +@requiredse +class NodeSyncMetadataTests(BasicSharedKeyspaceUnitTestCase): + + @classmethod + def setUpClass(cls): + if DSE_VERSION: + super(NodeSyncMetadataTests, cls).setUpClass() + + @classmethod + def tearDownClass(cls): + if DSE_VERSION: + super(NodeSyncMetadataTests, cls).setUpClass() + + @greaterthanorequaldse60 + def test_nodesync_on_table(self): + """ + Checks to ensure that nodesync is visible through driver metadata + + @since 3.20 + @jira_ticket PYTHON-799 + @expected_result nodesync should be enabled + + @test_category metadata + """ + self.session.execute("CREATE TABLE {0}.reports (" + " report_user text PRIMARY KEY" + ") WITH nodesync = {{" + "'enabled': 'true', 'deadline_target_sec' : 86400 }};".format( + self.keyspace_name + )) + table_meta = self.cluster.metadata.keyspaces[self.keyspace_name].tables['reports'] + self.assertIn('nodesync =', table_meta.export_as_string()) + self.assertIn('nodesync', table_meta.options) + + +@greaterthanorequaldse68 +class GraphMetadataTests(BasicExistingKeyspaceUnitTestCase): + """ + Various tests to ensure that graph metadata are visible through driver metadata + @since DSE6.8 + @jira_ticket PYTHON-996 + @expected_result graph metadata are fetched + @test_category metadata + """ + + @classmethod + def setUpClass(cls): + if DSE_VERSION and DSE_VERSION >= Version('6.8'): + super(GraphMetadataTests, cls).setUpClass() + cls.session.execute(""" + CREATE KEYSPACE ks_no_graph_engine WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}; + """) + cls.session.execute(""" + CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1} and graph_engine = 'Core'; + """ % (cls.ks_name,)) + + cls.session.execute(""" + CREATE TABLE %s.person (name text PRIMARY KEY) WITH VERTEX LABEL; + """ % (cls.ks_name,)) + + cls.session.execute(""" + CREATE TABLE %s.software(company text, name text, version int, PRIMARY KEY((company, name), version)) WITH VERTEX LABEL rocksolidsoftware; + """ % (cls.ks_name,)) + + cls.session.execute(""" + CREATE TABLE %s.contributors (contributor text, company_name text, software_name text, software_version int, + PRIMARY KEY (contributor, company_name, software_name, software_version) ) + WITH CLUSTERING ORDER BY (company_name ASC, software_name ASC, software_version ASC) + AND EDGE LABEL contrib FROM person(contributor) TO rocksolidsoftware((company_name, software_name), software_version); + """ % (cls.ks_name,)) + + @classmethod + def tearDownClass(cls): + if DSE_VERSION and DSE_VERSION >= Version('6.8'): + cls.session.execute('DROP KEYSPACE {0}'.format('ks_no_graph_engine')) + cls.session.execute('DROP KEYSPACE {0}'.format(cls.ks_name)) + cls.cluster.shutdown() + + def test_keyspace_metadata(self): + self.assertIsNone(self.cluster.metadata.keyspaces['ks_no_graph_engine'].graph_engine, None) + self.assertEqual(self.cluster.metadata.keyspaces[self.ks_name].graph_engine, 'Core') + + def test_keyspace_metadata_alter_graph_engine(self): + self.session.execute("ALTER KEYSPACE %s WITH graph_engine = 'Tinker'" % (self.ks_name,)) + self.assertEqual(self.cluster.metadata.keyspaces[self.ks_name].graph_engine, 'Tinker') + self.session.execute("ALTER KEYSPACE %s WITH graph_engine = 'Core'" % (self.ks_name,)) + self.assertEqual(self.cluster.metadata.keyspaces[self.ks_name].graph_engine, 'Core') + + def test_vertex_metadata(self): + vertex_meta = self.cluster.metadata.keyspaces[self.ks_name].tables['person'].vertex + self.assertEqual(vertex_meta.keyspace_name, self.ks_name) + self.assertEqual(vertex_meta.table_name, 'person') + self.assertEqual(vertex_meta.label_name, 'person') + + vertex_meta = self.cluster.metadata.keyspaces[self.ks_name].tables['software'].vertex + self.assertEqual(vertex_meta.keyspace_name, self.ks_name) + self.assertEqual(vertex_meta.table_name, 'software') + self.assertEqual(vertex_meta.label_name, 'rocksolidsoftware') + + def test_edge_metadata(self): + edge_meta = self.cluster.metadata.keyspaces[self.ks_name].tables['contributors'].edge + self.assertEqual(edge_meta.keyspace_name, self.ks_name) + self.assertEqual(edge_meta.table_name, 'contributors') + self.assertEqual(edge_meta.label_name, 'contrib') + self.assertEqual(edge_meta.from_table, 'person') + self.assertEqual(edge_meta.from_label, 'person') + self.assertEqual(edge_meta.from_partition_key_columns, ['contributor']) + self.assertEqual(edge_meta.from_clustering_columns, []) + self.assertEqual(edge_meta.to_table, 'software') + self.assertEqual(edge_meta.to_label, 'rocksolidsoftware') + self.assertEqual(edge_meta.to_partition_key_columns, ['company_name', 'software_name']) + self.assertEqual(edge_meta.to_clustering_columns, ['software_version']) + + +@greaterthanorequaldse68 +class GraphMetadataSchemaErrorTests(BasicExistingKeyspaceUnitTestCase): + """ + Test that we can connect when the graph schema is broken. + """ + + def test_connection_on_graph_schema_error(self): + self.session = self.cluster.connect() + + self.session.execute(""" + CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1} and graph_engine = 'Core'; + """ % (self.ks_name,)) + + self.session.execute(""" + CREATE TABLE %s.person (name text PRIMARY KEY) WITH VERTEX LABEL; + """ % (self.ks_name,)) + + self.session.execute(""" + CREATE TABLE %s.software(company text, name text, version int, PRIMARY KEY((company, name), version)) WITH VERTEX LABEL rocksolidsoftware; + """ % (self.ks_name,)) + + self.session.execute(""" + CREATE TABLE %s.contributors (contributor text, company_name text, software_name text, software_version int, + PRIMARY KEY (contributor, company_name, software_name, software_version) ) + WITH CLUSTERING ORDER BY (company_name ASC, software_name ASC, software_version ASC) + AND EDGE LABEL contrib FROM person(contributor) TO rocksolidsoftware((company_name, software_name), software_version); + """ % (self.ks_name,)) + + self.session.execute('TRUNCATE system_schema.vertices') + TestCluster().connect().shutdown() diff --git a/tests/integration/advanced/test_auth.py b/tests/integration/advanced/test_auth.py new file mode 100644 index 0000000..7e9aa8c --- /dev/null +++ b/tests/integration/advanced/test_auth.py @@ -0,0 +1,535 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa +import logging +import os +import subprocess +import time + +from ccmlib.dse_cluster import DseCluster +from nose.plugins.attrib import attr +from packaging.version import Version + +from cassandra.auth import (DSEGSSAPIAuthProvider, DSEPlainTextAuthProvider, + SaslAuthProvider, TransitionalModePlainTextAuthProvider) +from cassandra.cluster import EXEC_PROFILE_GRAPH_DEFAULT, NoHostAvailable +from cassandra.protocol import Unauthorized +from cassandra.query import SimpleStatement +from tests.integration import (get_cluster, greaterthanorequaldse51, + remove_cluster, requiredse, DSE_VERSION, TestCluster) +from tests.integration.advanced import ADS_HOME, use_single_node_with_graph +from tests.integration.advanced.graph import reset_graph, ClassicGraphFixtures + + +log = logging.getLogger(__name__) + + +def setup_module(): + if DSE_VERSION: + use_single_node_with_graph() + + +def teardown_module(): + if DSE_VERSION: + remove_cluster() # this test messes with config + + +def wait_role_manager_setup_then_execute(session, statements): + for s in statements: + exc = None + for attempt in range(3): + try: + session.execute(s) + break + except Exception as e: + exc = e + time.sleep(5) + else: # if we didn't reach `break` + if exc is not None: + raise exc + + +@attr('long') +@requiredse +class BasicDseAuthTest(unittest.TestCase): + + @classmethod + def setUpClass(self): + """ + This will setup the necessary infrastructure to run our authentication tests. It requres the ADS_HOME environment variable + and our custom embedded apache directory server jar in order to run. + """ + if not DSE_VERSION: + return + + clear_kerberos_tickets() + self.cluster = None + + # Setup variables for various keytab and other files + self.conf_file_dir = os.path.join(ADS_HOME, "conf/") + self.krb_conf = os.path.join(self.conf_file_dir, "krb5.conf") + self.dse_keytab = os.path.join(self.conf_file_dir, "dse.keytab") + self.dseuser_keytab = os.path.join(self.conf_file_dir, "dseuser.keytab") + self.cassandra_keytab = os.path.join(self.conf_file_dir, "cassandra.keytab") + self.bob_keytab = os.path.join(self.conf_file_dir, "bob.keytab") + self.charlie_keytab = os.path.join(self.conf_file_dir, "charlie.keytab") + actual_jar = os.path.join(ADS_HOME, "embedded-ads.jar") + + # Create configuration directories if they don't already exists + if not os.path.exists(self.conf_file_dir): + os.makedirs(self.conf_file_dir) + if not os.path.exists(actual_jar): + raise RuntimeError('could not find {}'.format(actual_jar)) + log.warning("Starting adserver") + # Start the ADS, this will create the keytab con configuration files listed above + self.proc = subprocess.Popen(['java', '-jar', actual_jar, '-k', '--confdir', self.conf_file_dir], shell=False) + time.sleep(10) + # TODO poll for server to come up + + log.warning("Starting adserver started") + ccm_cluster = get_cluster() + log.warning("fetching tickets") + # Stop cluster if running and configure it with the correct options + ccm_cluster.stop() + if isinstance(ccm_cluster, DseCluster): + # Setup kerberos options in cassandra.yaml + config_options = {'kerberos_options': {'keytab': self.dse_keytab, + 'service_principal': 'dse/_HOST@DATASTAX.COM', + 'qop': 'auth'}, + 'authentication_options': {'enabled': 'true', + 'default_scheme': 'kerberos', + 'scheme_permissions': 'true', + 'allow_digest_with_kerberos': 'true', + 'plain_text_without_ssl': 'warn', + 'transitional_mode': 'disabled'}, + 'authorization_options': {'enabled': 'true'}} + + krb5java = "-Djava.security.krb5.conf=" + self.krb_conf + # Setup dse authenticator in cassandra.yaml + ccm_cluster.set_configuration_options({ + 'authenticator': 'com.datastax.bdp.cassandra.auth.DseAuthenticator', + 'authorizer': 'com.datastax.bdp.cassandra.auth.DseAuthorizer' + }) + ccm_cluster.set_dse_configuration_options(config_options) + ccm_cluster.start(wait_for_binary_proto=True, wait_other_notice=True, jvm_args=[krb5java]) + else: + log.error("Cluster is not dse cluster test will fail") + + @classmethod + def tearDownClass(self): + """ + Terminates running ADS (Apache directory server). + """ + if not DSE_VERSION: + return + + self.proc.terminate() + + def tearDown(self): + """ + This will clear any existing kerberos tickets by using kdestroy + """ + clear_kerberos_tickets() + if self.cluster: + self.cluster.shutdown() + + def refresh_kerberos_tickets(self, keytab_file, user_name, krb_conf): + """ + Fetches a new ticket for using the keytab file and username provided. + """ + self.ads_pid = subprocess.call(['kinit', '-t', keytab_file, user_name], env={'KRB5_CONFIG': krb_conf}, shell=False) + + def connect_and_query(self, auth_provider, query=None): + """ + Runs a simple system query with the auth_provided specified. + """ + os.environ['KRB5_CONFIG'] = self.krb_conf + self.cluster = TestCluster(auth_provider=auth_provider) + self.session = self.cluster.connect() + query = query if query else "SELECT * FROM system.local" + statement = SimpleStatement(query) + rs = self.session.execute(statement) + return rs + + def test_should_not_authenticate_with_bad_user_ticket(self): + """ + This tests will attempt to authenticate with a user that has a valid ticket, but is not a valid dse user. + @since 3.20 + @jira_ticket PYTHON-457 + @test_category dse auth + @expected_result NoHostAvailable exception should be thrown + + """ + self.refresh_kerberos_tickets(self.dseuser_keytab, "dseuser@DATASTAX.COM", self.krb_conf) + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"]) + self.assertRaises(NoHostAvailable, self.connect_and_query, auth_provider) + + def test_should_not_athenticate_without_ticket(self): + """ + This tests will attempt to authenticate with a user that is valid but has no ticket + @since 3.20 + @jira_ticket PYTHON-457 + @test_category dse auth + @expected_result NoHostAvailable exception should be thrown + + """ + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"]) + self.assertRaises(NoHostAvailable, self.connect_and_query, auth_provider) + + def test_connect_with_kerberos(self): + """ + This tests will attempt to authenticate with a user that is valid and has a ticket + @since 3.20 + @jira_ticket PYTHON-457 + @test_category dse auth + @expected_result Client should be able to connect and run a basic query + + """ + self.refresh_kerberos_tickets(self.cassandra_keytab, "cassandra@DATASTAX.COM", self.krb_conf) + auth_provider = DSEGSSAPIAuthProvider() + rs = self.connect_and_query(auth_provider) + self.assertIsNotNone(rs) + connections = [c for holders in self.cluster.get_connection_holders() for c in holders.get_connections()] + # Check to make sure our server_authenticator class is being set appropriate + for connection in connections: + self.assertTrue('DseAuthenticator' in connection.authenticator.server_authenticator_class) + + def test_connect_with_kerberos_and_graph(self): + """ + This tests will attempt to authenticate with a user and execute a graph query + @since 3.20 + @jira_ticket PYTHON-457 + @test_category dse auth + @expected_result Client should be able to connect and run a basic graph query with authentication + + """ + self.refresh_kerberos_tickets(self.cassandra_keytab, "cassandra@DATASTAX.COM", self.krb_conf) + + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"]) + rs = self.connect_and_query(auth_provider) + self.assertIsNotNone(rs) + reset_graph(self.session, self._testMethodName.lower()) + profiles = self.cluster.profile_manager.profiles + profiles[EXEC_PROFILE_GRAPH_DEFAULT].graph_options.graph_name = self._testMethodName.lower() + self.session.execute_graph(ClassicGraphFixtures.classic()) + + rs = self.session.execute_graph('g.V()') + self.assertIsNotNone(rs) + + def test_connect_with_kerberos_host_not_resolved(self): + """ + This tests will attempt to authenticate with IP, this will fail on osx. + The success or failure of this test is dependent on a reverse dns lookup which can be impacted by your environment + if it fails don't panic. + @since 3.20 + @jira_ticket PYTHON-566 + @test_category dse auth + @expected_result Client should error when ip is used + + """ + self.refresh_kerberos_tickets(self.cassandra_keytab, "cassandra@DATASTAX.COM", self.krb_conf) + DSEGSSAPIAuthProvider(service='dse', qops=["auth"], resolve_host_name=False) + + def test_connect_with_explicit_principal(self): + """ + This tests will attempt to authenticate using valid and invalid user principals + @since 3.20 + @jira_ticket PYTHON-574 + @test_category dse auth + @expected_result Client principals should be used by the underlying mechanism + + """ + + # Connect with valid principal + self.refresh_kerberos_tickets(self.cassandra_keytab, "cassandra@DATASTAX.COM", self.krb_conf) + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"], principal="cassandra@DATASTAX.COM") + self.connect_and_query(auth_provider) + connections = [c for holders in self.cluster.get_connection_holders() for c in holders.get_connections()] + + # Check to make sure our server_authenticator class is being set appropriate + for connection in connections: + self.assertTrue('DseAuthenticator' in connection.authenticator.server_authenticator_class) + + # Use invalid principal + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"], principal="notauser@DATASTAX.COM") + self.assertRaises(NoHostAvailable, self.connect_and_query, auth_provider) + + @greaterthanorequaldse51 + def test_proxy_login_with_kerberos(self): + """ + Test that the proxy login works with kerberos. + """ + # Set up users for proxy login test + self._setup_for_proxy() + + query = "select * from testkrbproxy.testproxy" + + # Try normal login with Charlie + self.refresh_kerberos_tickets(self.charlie_keytab, "charlie@DATASTAX.COM", self.krb_conf) + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"], principal="charlie@DATASTAX.COM") + self.connect_and_query(auth_provider, query=query) + + # Try proxy login with bob + self.refresh_kerberos_tickets(self.bob_keytab, "bob@DATASTAX.COM", self.krb_conf) + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"], principal="bob@DATASTAX.COM", + authorization_id='charlie@DATASTAX.COM') + self.connect_and_query(auth_provider, query=query) + + # Try logging with bob without mentioning charlie + self.refresh_kerberos_tickets(self.bob_keytab, "bob@DATASTAX.COM", self.krb_conf) + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"], principal="bob@DATASTAX.COM") + self.assertRaises(Unauthorized, self.connect_and_query, auth_provider, query=query) + + self._remove_proxy_setup() + + @greaterthanorequaldse51 + def test_proxy_login_with_kerberos_forbidden(self): + """ + Test that the proxy login fail when proxy role is not granted + """ + # Set up users for proxy login test + self._setup_for_proxy(False) + query = "select * from testkrbproxy.testproxy" + + # Try normal login with Charlie + self.refresh_kerberos_tickets(self.bob_keytab, "bob@DATASTAX.COM", self.krb_conf) + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"], principal="bob@DATASTAX.COM", + authorization_id='charlie@DATASTAX.COM') + self.assertRaises(NoHostAvailable, self.connect_and_query, auth_provider, query=query) + + self.refresh_kerberos_tickets(self.bob_keytab, "bob@DATASTAX.COM", self.krb_conf) + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"], principal="bob@DATASTAX.COM") + self.assertRaises(Unauthorized, self.connect_and_query, auth_provider, query=query) + + self._remove_proxy_setup() + + def _remove_proxy_setup(self): + os.environ['KRB5_CONFIG'] = self.krb_conf + self.refresh_kerberos_tickets(self.cassandra_keytab, "cassandra@DATASTAX.COM", self.krb_conf) + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"], principal='cassandra@DATASTAX.COM') + cluster = TestCluster(auth_provider=auth_provider) + session = cluster.connect() + + session.execute("REVOKE PROXY.LOGIN ON ROLE '{0}' FROM '{1}'".format('charlie@DATASTAX.COM', 'bob@DATASTAX.COM')) + + session.execute("DROP ROLE IF EXISTS '{0}';".format('bob@DATASTAX.COM')) + session.execute("DROP ROLE IF EXISTS '{0}';".format('charlie@DATASTAX.COM')) + + # Create a keyspace and allow only charlie to query it. + + session.execute("DROP KEYSPACE testkrbproxy") + + cluster.shutdown() + + def _setup_for_proxy(self, grant=True): + os.environ['KRB5_CONFIG'] = self.krb_conf + self.refresh_kerberos_tickets(self.cassandra_keytab, "cassandra@DATASTAX.COM", self.krb_conf) + auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"], principal='cassandra@DATASTAX.COM') + cluster = TestCluster(auth_provider=auth_provider) + session = cluster.connect() + + stmts = [ + "CREATE ROLE IF NOT EXISTS '{0}' WITH LOGIN = TRUE;".format('bob@DATASTAX.COM'), + "CREATE ROLE IF NOT EXISTS '{0}' WITH LOGIN = TRUE;".format('bob@DATASTAX.COM'), + "GRANT EXECUTE ON ALL AUTHENTICATION SCHEMES to 'bob@DATASTAX.COM'", + "CREATE ROLE IF NOT EXISTS '{0}' WITH LOGIN = TRUE;".format('charlie@DATASTAX.COM'), + "GRANT EXECUTE ON ALL AUTHENTICATION SCHEMES to 'charlie@DATASTAX.COM'", + # Create a keyspace and allow only charlie to query it. + "CREATE KEYSPACE testkrbproxy WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", + "CREATE TABLE testkrbproxy.testproxy (id int PRIMARY KEY, value text)", + "GRANT ALL PERMISSIONS ON KEYSPACE testkrbproxy to '{0}'".format('charlie@DATASTAX.COM'), + ] + + if grant: + stmts.append("GRANT PROXY.LOGIN ON ROLE '{0}' to '{1}'".format('charlie@DATASTAX.COM', 'bob@DATASTAX.COM')) + + wait_role_manager_setup_then_execute(session, stmts) + + cluster.shutdown() + + +def clear_kerberos_tickets(): + subprocess.call(['kdestroy'], shell=False) + + +@attr('long') +@requiredse +class BaseDseProxyAuthTest(unittest.TestCase): + + @classmethod + def setUpClass(self): + """ + This will setup the necessary infrastructure to run unified authentication tests. + """ + if not DSE_VERSION or DSE_VERSION < Version('5.1'): + return + self.cluster = None + + ccm_cluster = get_cluster() + # Stop cluster if running and configure it with the correct options + ccm_cluster.stop() + if isinstance(ccm_cluster, DseCluster): + # Setup dse options in dse.yaml + config_options = {'authentication_options': {'enabled': 'true', + 'default_scheme': 'internal', + 'scheme_permissions': 'true', + 'transitional_mode': 'normal'}, + 'authorization_options': {'enabled': 'true'} + } + + # Setup dse authenticator in cassandra.yaml + ccm_cluster.set_configuration_options({ + 'authenticator': 'com.datastax.bdp.cassandra.auth.DseAuthenticator', + 'authorizer': 'com.datastax.bdp.cassandra.auth.DseAuthorizer' + }) + ccm_cluster.set_dse_configuration_options(config_options) + ccm_cluster.start(wait_for_binary_proto=True, wait_other_notice=True) + else: + log.error("Cluster is not dse cluster test will fail") + + # Create users and test keyspace + self.user_role = 'user1' + self.server_role = 'server' + self.root_cluster = TestCluster(auth_provider=DSEPlainTextAuthProvider('cassandra', 'cassandra')) + self.root_session = self.root_cluster.connect() + + stmts = [ + "CREATE USER {0} WITH PASSWORD '{1}'".format(self.server_role, self.server_role), + "CREATE USER {0} WITH PASSWORD '{1}'".format(self.user_role, self.user_role), + "CREATE KEYSPACE testproxy WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", + "CREATE TABLE testproxy.testproxy (id int PRIMARY KEY, value text)", + "GRANT ALL PERMISSIONS ON KEYSPACE testproxy to {0}".format(self.user_role) + ] + + wait_role_manager_setup_then_execute(self.root_session, stmts) + + @classmethod + def tearDownClass(self): + """ + Shutdown the root session. + """ + if not DSE_VERSION or DSE_VERSION < Version('5.1'): + return + self.root_session.execute('DROP KEYSPACE testproxy;') + self.root_session.execute('DROP USER {0}'.format(self.user_role)) + self.root_session.execute('DROP USER {0}'.format(self.server_role)) + self.root_cluster.shutdown() + + def tearDown(self): + """ + Shutdown the cluster and reset proxy permissions + """ + self.cluster.shutdown() + + self.root_session.execute("REVOKE PROXY.LOGIN ON ROLE {0} from {1}".format(self.user_role, self.server_role)) + self.root_session.execute("REVOKE PROXY.EXECUTE ON ROLE {0} from {1}".format(self.user_role, self.server_role)) + + def grant_proxy_login(self): + """ + Grant PROXY.LOGIN permission on a role to a specific user. + """ + self.root_session.execute("GRANT PROXY.LOGIN on role {0} to {1}".format(self.user_role, self.server_role)) + + def grant_proxy_execute(self): + """ + Grant PROXY.EXECUTE permission on a role to a specific user. + """ + self.root_session.execute("GRANT PROXY.EXECUTE on role {0} to {1}".format(self.user_role, self.server_role)) + + +@attr('long') +@greaterthanorequaldse51 +class DseProxyAuthTest(BaseDseProxyAuthTest): + """ + Tests Unified Auth. Proxy Login using SASL and Proxy Execute. + """ + + @classmethod + def get_sasl_options(self, mechanism='PLAIN'): + sasl_options = { + "service": 'dse', + "username": 'server', + "mechanism": mechanism, + 'password': self.server_role, + 'authorization_id': self.user_role + } + return sasl_options + + def connect_and_query(self, auth_provider, execute_as=None, query="SELECT * FROM testproxy.testproxy"): + self.cluster = TestCluster(auth_provider=auth_provider) + self.session = self.cluster.connect() + rs = self.session.execute(query, execute_as=execute_as) + return rs + + def test_proxy_login_forbidden(self): + """ + Test that a proxy login is forbidden by default for a user. + @since 3.20 + @jira_ticket PYTHON-662 + @test_category dse auth + @expected_result connect and query should not be allowed + """ + auth_provider = SaslAuthProvider(**self.get_sasl_options()) + with self.assertRaises(Unauthorized): + self.connect_and_query(auth_provider) + + def test_proxy_login_allowed(self): + """ + Test that a proxy login is allowed with proper permissions. + @since 3.20 + @jira_ticket PYTHON-662 + @test_category dse auth + @expected_result connect and query should be allowed + """ + auth_provider = SaslAuthProvider(**self.get_sasl_options()) + self.grant_proxy_login() + self.connect_and_query(auth_provider) + + def test_proxy_execute_forbidden(self): + """ + Test that a proxy execute is forbidden by default for a user. + @since 3.20 + @jira_ticket PYTHON-662 + @test_category dse auth + @expected_result connect and query should not be allowed + """ + auth_provider = DSEPlainTextAuthProvider(self.server_role, self.server_role) + with self.assertRaises(Unauthorized): + self.connect_and_query(auth_provider, execute_as=self.user_role) + + def test_proxy_execute_allowed(self): + """ + Test that a proxy execute is allowed with proper permissions. + @since 3.20 + @jira_ticket PYTHON-662 + @test_category dse auth + @expected_result connect and query should be allowed + """ + auth_provider = DSEPlainTextAuthProvider(self.server_role, self.server_role) + self.grant_proxy_execute() + self.connect_and_query(auth_provider, execute_as=self.user_role) + + def test_connection_with_transitional_mode(self): + """ + Test that the driver can connect using TransitionalModePlainTextAuthProvider + @since 3.20 + @jira_ticket PYTHON-831 + @test_category dse auth + @expected_result connect and query should be allowed + """ + auth_provider = TransitionalModePlainTextAuthProvider() + self.assertIsNotNone(self.connect_and_query(auth_provider, query="SELECT * from system.local")) diff --git a/tests/integration/advanced/test_cont_paging.py b/tests/integration/advanced/test_cont_paging.py new file mode 100644 index 0000000..c5f1cbf --- /dev/null +++ b/tests/integration/advanced/test_cont_paging.py @@ -0,0 +1,247 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from tests.integration import use_singledc, greaterthanorequaldse51, BasicSharedKeyspaceUnitTestCaseRF3WM, \ + DSE_VERSION, ProtocolVersion, greaterthanorequaldse60, requiredse, TestCluster + +import logging +log = logging.getLogger(__name__) + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +from itertools import cycle, count +from six.moves import range +from packaging.version import Version +import time + +from cassandra.cluster import ExecutionProfile, ContinuousPagingOptions +from cassandra.concurrent import execute_concurrent +from cassandra.query import SimpleStatement + + +def setup_module(): + if DSE_VERSION: + use_singledc() + + +@requiredse +class BaseContPagingTests(): + @classmethod + def setUpClass(cls): + if not DSE_VERSION or DSE_VERSION < cls.required_dse_version: + return + + cls.execution_profiles = {"CONTDEFAULT": ExecutionProfile(continuous_paging_options=ContinuousPagingOptions()), + "ONEPAGE": ExecutionProfile( + continuous_paging_options=ContinuousPagingOptions(max_pages=1)), + "MANYPAGES": ExecutionProfile( + continuous_paging_options=ContinuousPagingOptions(max_pages=10)), + "BYTES": ExecutionProfile(continuous_paging_options=ContinuousPagingOptions( + page_unit=ContinuousPagingOptions.PagingUnit.BYTES)), + "SLOW": ExecutionProfile( + continuous_paging_options=ContinuousPagingOptions(max_pages_per_second=1)), } + cls.sane_eps = ["CONTDEFAULT", "BYTES"] + + @classmethod + def tearDownClass(cls): + if not DSE_VERSION or DSE_VERSION < cls.required_dse_version: + return + + @classmethod + def create_cluster(cls): + + cls.cluster_with_profiles = TestCluster(protocol_version=cls.protocol_version, execution_profiles=cls.execution_profiles) + + cls.session_with_profiles = cls.cluster_with_profiles.connect(wait_for_all_pools=True) + statements_and_params = zip( + cycle(["INSERT INTO " + cls.ks_name + "." + cls.ks_name + " (k, v) VALUES (%s, 0)"]), + [(i,) for i in range(150)]) + execute_concurrent(cls.session_with_profiles, list(statements_and_params)) + + cls.select_all_statement = "SELECT * FROM {0}.{0}".format(cls.ks_name) + + def test_continous_paging(self): + """ + Test to ensure that various continuous paging schemes return the full set of results. + @since 3.20 + @jira_ticket PYTHON-615 + @expected_result various continous paging options should fetch all the results + + @test_category queries + """ + for ep in self.execution_profiles.keys(): + results = list(self.session_with_profiles.execute(self.select_all_statement, execution_profile= ep)) + self.assertEqual(len(results), 150) + + + def test_page_fetch_size(self): + """ + Test to ensure that continuous paging works appropriately with fetch size. + @since 3.20 + @jira_ticket PYTHON-615 + @expected_result continuous paging options should work sensibly with various fetch size + + @test_category queries + """ + + # Since we fetch one page at a time results should match fetch size + for fetch_size in (2, 3, 7, 10, 99, 100, 101, 150): + self.session_with_profiles.default_fetch_size = fetch_size + results = list(self.session_with_profiles.execute(self.select_all_statement, execution_profile= "ONEPAGE")) + self.assertEqual(len(results), fetch_size) + + # Since we fetch ten pages at a time results should match fetch size * 10 + for fetch_size in (2, 3, 7, 10, 15): + self.session_with_profiles.default_fetch_size = fetch_size + results = list(self.session_with_profiles.execute(self.select_all_statement, execution_profile= "MANYPAGES")) + self.assertEqual(len(results), fetch_size*10) + + # Default settings for continuous paging should be able to fetch all results regardless of fetch size + # Changing the units should, not affect the number of results, if max_pages is not set + for profile in self.sane_eps: + for fetch_size in (2, 3, 7, 10, 15): + self.session_with_profiles.default_fetch_size = fetch_size + results = list(self.session_with_profiles.execute(self.select_all_statement, execution_profile= profile)) + self.assertEqual(len(results), 150) + + # This should take around 3 seconds to fetch but should still complete with all results + self.session_with_profiles.default_fetch_size = 50 + results = list(self.session_with_profiles.execute(self.select_all_statement, execution_profile= "SLOW")) + self.assertEqual(len(results), 150) + + def test_paging_cancel(self): + """ + Test to ensure we can cancel a continuous paging session once it's started + @since 3.20 + @jira_ticket PYTHON-615 + @expected_result This query should be canceled before any sizable amount of results can be returned + @test_category queries + """ + + self.session_with_profiles.default_fetch_size = 1 + # This combination should fetch one result a second. We should see a very few results + results = self.session_with_profiles.execute_async(self.select_all_statement, execution_profile= "SLOW") + result_set =results.result() + result_set.cancel_continuous_paging() + result_lst =list(result_set) + self.assertLess(len(result_lst), 2, "Cancel should have aborted fetch immediately") + + def test_con_paging_verify_writes(self): + """ + Test to validate results with a few continuous paging options + @since 3.20 + @jira_ticket PYTHON-615 + @expected_result all results should be returned correctly + @test_category queries + """ + prepared = self.session_with_profiles.prepare(self.select_all_statement) + + + for ep in self.sane_eps: + for fetch_size in (2, 3, 7, 10, 99, 100, 101, 10000): + self.session_with_profiles.default_fetch_size = fetch_size + results = self.session_with_profiles.execute(self.select_all_statement, execution_profile=ep) + result_array = set() + result_set = set() + for result in results: + result_array.add(result.k) + result_set.add(result.v) + + self.assertEqual(set(range(150)), result_array) + self.assertEqual(set([0]), result_set) + + statement = SimpleStatement(self.select_all_statement) + results = self.session_with_profiles.execute(statement, execution_profile=ep) + result_array = set() + result_set = set() + for result in results: + result_array.add(result.k) + result_set.add(result.v) + + self.assertEqual(set(range(150)), result_array) + self.assertEqual(set([0]), result_set) + + results = self.session_with_profiles.execute(prepared, execution_profile=ep) + result_array = set() + result_set = set() + for result in results: + result_array.add(result.k) + result_set.add(result.v) + + self.assertEqual(set(range(150)), result_array) + self.assertEqual(set([0]), result_set) + + def test_can_get_results_when_no_more_pages(self): + """ + Test to validate that the resutls can be fetched when + has_more_pages is False + @since 3.20 + @jira_ticket PYTHON-946 + @expected_result the results can be fetched + @test_category queries + """ + generator_expanded = [] + def get_all_rows(generator, future, generator_expanded): + self.assertFalse(future.has_more_pages) + + generator_expanded.extend(list(generator)) + print("Setting generator_expanded to True") + + future = self.session_with_profiles.execute_async("SELECT * from system.local LIMIT 10", + execution_profile="CONTDEFAULT") + future.add_callback(get_all_rows, future, generator_expanded) + time.sleep(5) + self.assertTrue(generator_expanded) + + +@requiredse +@greaterthanorequaldse51 +class ContPagingTestsDSEV1(BaseContPagingTests, BasicSharedKeyspaceUnitTestCaseRF3WM): + @classmethod + def setUpClass(cls): + cls.required_dse_version = BaseContPagingTests.required_dse_version = Version('5.1') + if not DSE_VERSION or DSE_VERSION < cls.required_dse_version: + return + + BasicSharedKeyspaceUnitTestCaseRF3WM.setUpClass() + BaseContPagingTests.setUpClass() + + cls.protocol_version = ProtocolVersion.DSE_V1 + cls.create_cluster() + + +@requiredse +@greaterthanorequaldse60 +class ContPagingTestsDSEV2(BaseContPagingTests, BasicSharedKeyspaceUnitTestCaseRF3WM): + @classmethod + def setUpClass(cls): + cls.required_dse_version = BaseContPagingTests.required_dse_version = Version('6.0') + if not DSE_VERSION or DSE_VERSION < cls.required_dse_version: + return + + BasicSharedKeyspaceUnitTestCaseRF3WM.setUpClass() + BaseContPagingTests.setUpClass() + + more_profiles = { + "SMALL_QUEUE": ExecutionProfile(continuous_paging_options=ContinuousPagingOptions(max_queue_size=2)), + "BIG_QUEUE": ExecutionProfile(continuous_paging_options=ContinuousPagingOptions(max_queue_size=400)) + } + cls.sane_eps += ["SMALL_QUEUE", "BIG_QUEUE"] + cls.execution_profiles.update(more_profiles) + + cls.protocol_version = ProtocolVersion.DSE_V2 + cls.create_cluster() diff --git a/tests/integration/advanced/test_cqlengine_where_operators.py b/tests/integration/advanced/test_cqlengine_where_operators.py new file mode 100644 index 0000000..8ade3db --- /dev/null +++ b/tests/integration/advanced/test_cqlengine_where_operators.py @@ -0,0 +1,113 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +import os +import time + +from cassandra.cqlengine import columns, connection, models +from cassandra.cqlengine.management import (CQLENG_ALLOW_SCHEMA_MANAGEMENT, + create_keyspace_simple, drop_table, + sync_table) +from cassandra.cqlengine.statements import IsNotNull +from tests.integration import DSE_VERSION, requiredse, CASSANDRA_IP, greaterthanorequaldse60, TestCluster +from tests.integration.advanced import use_single_node_with_graph_and_solr +from tests.integration.cqlengine import DEFAULT_KEYSPACE + + +class SimpleNullableModel(models.Model): + __keyspace__ = DEFAULT_KEYSPACE + partition = columns.Integer(primary_key=True) + nullable = columns.Integer(required=False) + # nullable = columns.Integer(required=False, custom_index=True) + + +def setup_module(): + if DSE_VERSION: + os.environ[CQLENG_ALLOW_SCHEMA_MANAGEMENT] = '1' + use_single_node_with_graph_and_solr() + setup_connection(DEFAULT_KEYSPACE) + create_keyspace_simple(DEFAULT_KEYSPACE, 1) + sync_table(SimpleNullableModel) + + +def setup_connection(keyspace_name): + connection.setup([CASSANDRA_IP], + # consistency=ConsistencyLevel.ONE, + # protocol_version=PROTOCOL_VERSION, + default_keyspace=keyspace_name) + + +def teardown_module(): + if DSE_VERSION: + drop_table(SimpleNullableModel) + + +@requiredse +class IsNotNullTests(unittest.TestCase): + + @classmethod + def setUpClass(cls): + if DSE_VERSION: + cls.cluster = TestCluster() + + @greaterthanorequaldse60 + def test_is_not_null_execution(self): + """ + Verify that CQL statements have correct syntax when executed + If we wanted them to return something meaningful and not a InvalidRequest + we'd have to create an index in search for the column we are using + IsNotNull + + @since 3.20 + @jira_ticket PYTHON-968 + @expected_result InvalidRequest is arisen + + @test_category cqlengine + """ + cluster = TestCluster() + self.addCleanup(cluster.shutdown) + session = cluster.connect() + + SimpleNullableModel.create(partition=1, nullable=2) + SimpleNullableModel.create(partition=2, nullable=None) + + self.addCleanup(session.execute, "DROP SEARCH INDEX ON {}".format( + SimpleNullableModel.column_family_name())) + create_index_stmt = ( + "CREATE SEARCH INDEX ON {} WITH COLUMNS nullable " + "".format(SimpleNullableModel.column_family_name())) + session.execute(create_index_stmt) + + SimpleNullableModel.create(partition=1, nullable=1) + SimpleNullableModel.create(partition=2, nullable=None) + + # TODO: block on indexing more precisely + time.sleep(5) + + self.assertEqual(len(list(SimpleNullableModel.objects.all())), 2) + self.assertEqual( + len(list( + SimpleNullableModel.filter(IsNotNull("nullable"), partition__eq=2) + )), + 0) + self.assertEqual( + len(list( + SimpleNullableModel.filter(IsNotNull("nullable"), partition__eq=1) + )), + 1) diff --git a/tests/integration/advanced/test_geometry.py b/tests/integration/advanced/test_geometry.py new file mode 100644 index 0000000..8bee144 --- /dev/null +++ b/tests/integration/advanced/test_geometry.py @@ -0,0 +1,252 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from tests.integration import DSE_VERSION, requiredse +from tests.integration.advanced import BasicGeometricUnitTestCase, use_single_node_with_graph +from cassandra.util import OrderedMap, sortedset +from collections import namedtuple + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa +from uuid import uuid1 +from cassandra.util import Point, LineString, Polygon +from cassandra.cqltypes import LineStringType, PointType, PolygonType + + +def setup_module(): + if DSE_VERSION: + use_single_node_with_graph() + + +class AbstractGeometricTypeTest(): + + original_value = "" + + def test_should_insert_simple(self): + """ + This tests will attempt to insert a point, polygon, or line, using simple inline formating. + @since 3.20 + @jira_ticket PYTHON-456 + @test_category dse geometric + @expected_result geometric types should be able to be inserted and queried. + """ + uuid_key = uuid1() + self.session.execute("INSERT INTO tbl (k, g) VALUES (%s, %s)", [uuid_key, self.original_value]) + self.validate('g', uuid_key, self.original_value) + + def test_should_insert_simple_prepared(self): + """ + This tests will attempt to insert a point, polygon, or line, using prepared statements. + @since 3.20 + @jira_ticket PYTHON-456 + @test_category dse geometric + @expected_result geometric types should be able to be inserted and queried. + """ + uuid_key = uuid1() + prepared = self.session.prepare("INSERT INTO tbl (k, g) VALUES (?, ?)") + self.session.execute(prepared, (uuid_key, self.original_value)) + self.validate('g', uuid_key, self.original_value) + + def test_should_insert_simple_prepared_with_bound(self): + """ + This tests will attempt to insert a point, polygon, or line, using prepared statements and bind. + @since 3.20 + @jira_ticket PYTHON-456 + @test_category dse geometric + @expected_result geometric types should be able to be inserted and queried. + """ + uuid_key = uuid1() + prepared = self.session.prepare("INSERT INTO tbl (k, g) VALUES (?, ?)") + bound_statement = prepared.bind((uuid_key, self.original_value)) + self.session.execute(bound_statement) + self.validate('g', uuid_key, self.original_value) + + def test_should_insert_as_list(self): + """ + This tests will attempt to insert a point, polygon, or line, as values of list. + @since 3.20 + @jira_ticket PYTHON-456 + @test_category dse geometric + @expected_result geometric types should be able to be inserted and queried as a list. + """ + uuid_key = uuid1() + prepared = self.session.prepare("INSERT INTO tbl (k, l) VALUES (?, ?)") + bound_statement = prepared.bind((uuid_key, [self.original_value])) + self.session.execute(bound_statement) + self.validate('l', uuid_key, [self.original_value]) + + def test_should_insert_as_set(self): + """ + This tests will attempt to insert a point, polygon, or line, as values of set. + @since 3.20 + @jira_ticket PYTHON-456 + @test_category dse geometric + @expected_result geometric types should be able to be inserted and queried as a set. + """ + uuid_key = uuid1() + prepared = self.session.prepare("INSERT INTO tbl (k, s) VALUES (?, ?)") + bound_statement = prepared.bind((uuid_key, sortedset([self.original_value]))) + self.session.execute(bound_statement) + self.validate('s', uuid_key, sortedset([self.original_value])) + + def test_should_insert_as_map_keys(self): + """ + This tests will attempt to insert a point, polygon, or line, as keys of a map. + @since 3.20 + @jira_ticket PYTHON-456 + @test_category dse geometric + @expected_result geometric types should be able to be inserted and queried as keys of a map. + """ + uuid_key = uuid1() + prepared = self.session.prepare("INSERT INTO tbl (k, m0) VALUES (?, ?)") + bound_statement = prepared.bind((uuid_key, OrderedMap(zip([self.original_value], [1])))) + self.session.execute(bound_statement) + self.validate('m0', uuid_key, OrderedMap(zip([self.original_value], [1]))) + + def test_should_insert_as_map_values(self): + """ + This tests will attempt to insert a point, polygon, or line, as values of a map. + @since 3.20 + @jira_ticket PYTHON-456 + @test_category dse geometric + @expected_result geometric types should be able to be inserted and queried as values of a map. + """ + uuid_key = uuid1() + prepared = self.session.prepare("INSERT INTO tbl (k, m1) VALUES (?, ?)") + bound_statement = prepared.bind((uuid_key, OrderedMap(zip([1], [self.original_value])))) + self.session.execute(bound_statement) + self.validate('m1', uuid_key, OrderedMap(zip([1], [self.original_value]))) + + def test_should_insert_as_tuple(self): + """ + This tests will attempt to insert a point, polygon, or line, as values of a tuple. + @since 3.20 + @jira_ticket PYTHON-456 + @test_category dse geometric + @expected_result geometric types should be able to be inserted and queried as values of a tuple. + """ + uuid_key = uuid1() + prepared = self.session.prepare("INSERT INTO tbl (k, t) VALUES (?, ?)") + bound_statement = prepared.bind((uuid_key, (self.original_value, self.original_value, self.original_value))) + self.session.execute(bound_statement) + self.validate('t', uuid_key, (self.original_value, self.original_value, self.original_value)) + + def test_should_insert_as_udt(self): + """ + This tests will attempt to insert a point, polygon, or line, as members of a udt. + @since 3.20 + @jira_ticket PYTHON-456 + @test_category dse geometric + @expected_result geometric types should be able to be inserted and queried as members of a udt. + """ + UDT1 = namedtuple('udt1', ('g')) + self.cluster.register_user_type(self.ks_name, 'udt1', UDT1) + uuid_key = uuid1() + prepared = self.session.prepare("INSERT INTO tbl (k, u) values (?, ?)") + bound_statement = prepared.bind((uuid_key, UDT1(self.original_value))) + self.session.execute(bound_statement) + rs = self.session.execute("SELECT {0} from {1} where k={2}".format('u', 'tbl', uuid_key)) + retrieved_udt = rs[0]._asdict()['u'] + + self.assertEqual(retrieved_udt.g, self.original_value) + + def test_should_accept_as_partition_key(self): + """ + This tests will attempt to insert a point, polygon, or line, as a partition key. + @since 3.20 + @jira_ticket PYTHON-456 + @test_category dse geometric + @expected_result geometric types should be able to be inserted and queried as a partition key. + """ + prepared = self.session.prepare("INSERT INTO tblpk (k, v) VALUES (?, ?)") + bound_statement = prepared.bind((self.original_value, 1)) + self.session.execute(bound_statement) + rs = self.session.execute("SELECT k, v FROM tblpk") + foundpk = rs[0]._asdict()['k'] + self.assertEqual(foundpk, self.original_value) + + def validate(self, value, key, expected): + """ + Simple utility method used for validation of inserted types. + """ + rs = self.session.execute("SELECT {0} from tbl where k={1}".format(value, key)) + retrieved = rs[0]._asdict()[value] + self.assertEqual(expected, retrieved) + + def test_insert_empty_with_string(self): + """ + This tests will attempt to insert a point, polygon, or line, as Empty + @since 3.20 + @jira_ticket PYTHON-481 + @test_category dse geometric + @expected_result EMPTY as a keyword should be honored + """ + uuid_key = uuid1() + self.session.execute("INSERT INTO tbl (k, g) VALUES (%s, %s)", [uuid_key, self.empty_statement]) + self.validate('g', uuid_key, self.empty_value) + + def test_insert_empty_with_object(self): + """ + This tests will attempt to insert a point, polygon, or line, as Empty + @since 3.20 + @jira_ticket PYTHON-481 + @test_category dse geometric + @expected_result EMPTY as a keyword should be used with empty objects + """ + uuid_key = uuid1() + prepared = self.session.prepare("INSERT INTO tbl (k, g) VALUES (?, ?)") + self.session.execute(prepared, (uuid_key, self.empty_value)) + self.validate('g', uuid_key, self.empty_value) + + +@requiredse +class BasicGeometricPointTypeTest(AbstractGeometricTypeTest, BasicGeometricUnitTestCase): + """ + Runs all the geometric tests against PointType + """ + cql_type_name = "'{0}'".format(PointType.typename) + original_value = Point(.5, .13) + + @unittest.skip("Empty String") + def test_insert_empty_with_string(self): + pass + + @unittest.skip("Empty String") + def test_insert_empty_with_object(self): + pass + + +@requiredse +class BasicGeometricLineStringTypeTest(AbstractGeometricTypeTest, BasicGeometricUnitTestCase): + """ + Runs all the geometric tests against LineStringType + """ + cql_type_name = cql_type_name = "'{0}'".format(LineStringType.typename) + original_value = LineString(((1, 2), (3, 4), (9871234, 1235487215))) + empty_statement = 'LINESTRING EMPTY' + empty_value = LineString() + + +@requiredse +class BasicGeometricPolygonTypeTest(AbstractGeometricTypeTest, BasicGeometricUnitTestCase): + """ + Runs all the geometric tests against PolygonType + """ + cql_type_name = cql_type_name = "'{0}'".format(PolygonType.typename) + original_value = Polygon([(10.0, 10.0), (110.0, 10.0), (110., 110.0), (10., 110.0), (10., 10.0)], [[(20., 20.0), (20., 30.0), (30., 30.0), (30., 20.0), (20., 20.0)], [(40., 20.0), (40., 30.0), (50., 30.0), (50., 20.0), (40., 20.0)]]) + empty_statement = 'POLYGON EMPTY' + empty_value = Polygon() diff --git a/tests/integration/advanced/test_spark.py b/tests/integration/advanced/test_spark.py new file mode 100644 index 0000000..a307913 --- /dev/null +++ b/tests/integration/advanced/test_spark.py @@ -0,0 +1,50 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +from cassandra.cluster import EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT +from cassandra.graph import SimpleGraphStatement +from tests.integration import DSE_VERSION, requiredse +from tests.integration.advanced import use_singledc_wth_graph_and_spark, find_spark_master +from tests.integration.advanced.graph import BasicGraphUnitTestCase, ClassicGraphFixtures +log = logging.getLogger(__name__) + + +def setup_module(): + if DSE_VERSION: + use_singledc_wth_graph_and_spark() + + +@requiredse +class SparkLBTests(BasicGraphUnitTestCase): + """ + Test to validate that analtics query can run in a multi-node enviroment. Also check to to ensure + that the master spark node is correctly targeted when OLAP queries are run + + @since 3.20 + @jira_ticket PYTHON-510 + @expected_result OLAP results should come back correctly, master spark coordinator should always be picked. + @test_category dse graph + """ + def test_spark_analytic_query(self): + self.session.execute_graph(ClassicGraphFixtures.classic()) + spark_master = find_spark_master(self.session) + + # Run multipltle times to ensure we don't round robin + for i in range(3): + to_run = SimpleGraphStatement("g.V().count()") + rs = self.session.execute_graph(to_run, execution_profile=EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT) + self.assertEqual(rs[0].value, 7) + self.assertEqual(rs.response_future._current_host.address, spark_master) diff --git a/tests/integration/advanced/test_unixsocketendpoint.py b/tests/integration/advanced/test_unixsocketendpoint.py index e435314..10cbc1b 100644 --- a/tests/integration/advanced/test_unixsocketendpoint.py +++ b/tests/integration/advanced/test_unixsocketendpoint.py @@ -1,77 +1,77 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License try: import unittest2 as unittest except ImportError: import unittest # noqa import time import subprocess import logging -from cassandra.cluster import Cluster, ExecutionProfile, EXEC_PROFILE_DEFAULT +from cassandra.cluster import ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.connection import UnixSocketEndPoint from cassandra.policies import WhiteListRoundRobinPolicy, RoundRobinPolicy from tests import notwindows -from tests.integration import use_single_node +from tests.integration import use_single_node, TestCluster log = logging.getLogger() log.setLevel('DEBUG') UNIX_SOCKET_PATH = '/tmp/cass.sock' def setup_module(): use_single_node() class UnixSocketWhiteListRoundRobinPolicy(WhiteListRoundRobinPolicy): def __init__(self, hosts): self._allowed_hosts = self._allowed_hosts_resolved = tuple(hosts) RoundRobinPolicy.__init__(self) @notwindows class UnixSocketTest(unittest.TestCase): @classmethod def setUpClass(cls): log.debug("Starting socat...") cls.proc = subprocess.Popen( ['socat', 'UNIX-LISTEN:%s,fork' % UNIX_SOCKET_PATH, 'TCP:localhost:9042'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) time.sleep(1) if cls.proc.poll() is not None: for line in cls.proc.stdout.readlines(): log.debug("socat: " + line.decode('utf-8')) raise Exception("Error while starting socat. Return code: %d" % cls.proc.returncode) lbp = UnixSocketWhiteListRoundRobinPolicy([UNIX_SOCKET_PATH]) ep = ExecutionProfile(load_balancing_policy=lbp) endpoint = UnixSocketEndPoint(UNIX_SOCKET_PATH) - cls.cluster = Cluster([endpoint], execution_profiles={EXEC_PROFILE_DEFAULT: ep}) + cls.cluster = TestCluster(contact_points=[endpoint], execution_profiles={EXEC_PROFILE_DEFAULT: ep}) @classmethod def tearDownClass(cls): cls.cluster.shutdown() cls.proc.terminate() def test_unix_socket_connection(self): s = self.cluster.connect() s.execute('select * from system.local') diff --git a/tests/integration/advanced/cloud/__init__.py b/tests/integration/cloud/__init__.py similarity index 99% rename from tests/integration/advanced/cloud/__init__.py rename to tests/integration/cloud/__init__.py index 83f5e21..ca05ae4 100644 --- a/tests/integration/advanced/cloud/__init__.py +++ b/tests/integration/cloud/__init__.py @@ -1,117 +1,116 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License +from cassandra.cluster import Cluster try: import unittest2 as unittest except ImportError: import unittest # noqa import os import subprocess -from cassandra.cluster import Cluster - from tests.integration import CLOUD_PROXY_PATH, USE_CASS_EXTERNAL def setup_package(): if CLOUD_PROXY_PATH and not USE_CASS_EXTERNAL: start_cloud_proxy() def teardown_package(): if not USE_CASS_EXTERNAL: stop_cloud_proxy() class CloudProxyCluster(unittest.TestCase): creds_dir = os.path.join(os.path.abspath(CLOUD_PROXY_PATH or ''), 'certs/bundles/') creds = os.path.join(creds_dir, 'creds-v1.zip') creds_no_auth = os.path.join(creds_dir, 'creds-v1-wo-creds.zip') creds_unreachable = os.path.join(creds_dir, 'creds-v1-unreachable.zip') creds_invalid_ca = os.path.join(creds_dir, 'creds-v1-invalid-ca.zip') cluster, connect = None, False session = None @classmethod def connect(cls, creds, **kwargs): cloud_config = { 'secure_connect_bundle': creds, } cls.cluster = Cluster(cloud=cloud_config, protocol_version=4, **kwargs) cls.session = cls.cluster.connect(wait_for_all_pools=True) def tearDown(self): if self.cluster: self.cluster.shutdown() class CloudProxyServer(object): """ Class for starting and stopping the proxy (sni_single_endpoint) """ ccm_command = 'docker exec $(docker ps -a -q --filter ancestor=single_endpoint) ccm {}' def __init__(self, CLOUD_PROXY_PATH): self.CLOUD_PROXY_PATH = CLOUD_PROXY_PATH self.running = False def start(self): return_code = subprocess.call( ['REQUIRE_CLIENT_CERTIFICATE=true ./run.sh'], cwd=self.CLOUD_PROXY_PATH, shell=True) if return_code != 0: raise Exception("Error while starting proxy server") self.running = True def stop(self): if self.is_running(): subprocess.call( ["docker kill $(docker ps -a -q --filter ancestor=single_endpoint)"], shell=True) self.running = False def is_running(self): return self.running def start_node(self, id): subcommand = 'node{} start --jvm_arg "-Ddse.product_type=DATASTAX_APOLLO" --root --wait-for-binary-proto'.format(id) subprocess.call( [self.ccm_command.format(subcommand)], shell=True) def stop_node(self, id): subcommand = 'node{} stop'.format(id) subprocess.call( [self.ccm_command.format(subcommand)], shell=True) CLOUD_PROXY_SERVER = CloudProxyServer(CLOUD_PROXY_PATH) def start_cloud_proxy(): """ Starts and waits for the proxy to run """ CLOUD_PROXY_SERVER.stop() CLOUD_PROXY_SERVER.start() def stop_cloud_proxy(): CLOUD_PROXY_SERVER.stop() diff --git a/tests/integration/advanced/cloud/test_cloud.py b/tests/integration/cloud/test_cloud.py similarity index 84% rename from tests/integration/advanced/cloud/test_cloud.py rename to tests/integration/cloud/test_cloud.py index 0ad8ea7..e0b9e2d 100644 --- a/tests/integration/advanced/cloud/test_cloud.py +++ b/tests/integration/cloud/test_cloud.py @@ -1,227 +1,251 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License from cassandra.datastax.cloud import parse_metadata_info from cassandra.query import SimpleStatement +from cassandra.cqlengine import connection +from cassandra.cqlengine.management import sync_table, create_keyspace_simple +from cassandra.cqlengine.models import Model +from cassandra.cqlengine import columns try: import unittest2 as unittest except ImportError: import unittest # noqa import six -from ssl import SSLContext, PROTOCOL_TLSv1 +from ssl import SSLContext, PROTOCOL_TLS from cassandra import DriverException, ConsistencyLevel, InvalidRequest -from cassandra.cluster import NoHostAvailable, ExecutionProfile, Cluster +from cassandra.cluster import NoHostAvailable, ExecutionProfile, Cluster, _execution_profile_to_string from cassandra.connection import SniEndPoint from cassandra.auth import PlainTextAuthProvider from cassandra.policies import TokenAwarePolicy, DCAwareRoundRobinPolicy, ConstantReconnectionPolicy from mock import patch from tests.integration import requirescloudproxy -from tests.integration.util import wait_until_not_raised -from tests.integration.advanced.cloud import CloudProxyCluster, CLOUD_PROXY_SERVER +from tests.util import wait_until_not_raised +from tests.integration.cloud import CloudProxyCluster, CLOUD_PROXY_SERVER DISALLOWED_CONSISTENCIES = [ ConsistencyLevel.ANY, ConsistencyLevel.ONE, ConsistencyLevel.LOCAL_ONE ] @requirescloudproxy class CloudTests(CloudProxyCluster): def hosts_up(self): return [h for h in self.cluster.metadata.all_hosts() if h.is_up] def test_resolve_and_connect(self): self.connect(self.creds) self.assertEqual(len(self.hosts_up()), 3) for host in self.cluster.metadata.all_hosts(): self.assertTrue(host.is_up) self.assertIsInstance(host.endpoint, SniEndPoint) self.assertEqual(str(host.endpoint), "{}:{}:{}".format( host.endpoint.address, host.endpoint.port, host.host_id)) self.assertIn(host.endpoint._resolved_address, ("127.0.0.1", '::1')) def test_match_system_local(self): self.connect(self.creds) self.assertEqual(len(self.hosts_up()), 3) for host in self.cluster.metadata.all_hosts(): row = self.session.execute('SELECT * FROM system.local', host=host).one() self.assertEqual(row.host_id, host.host_id) self.assertEqual(row.rpc_address, host.broadcast_rpc_address) def test_set_auth_provider(self): self.connect(self.creds) self.assertIsInstance(self.cluster.auth_provider, PlainTextAuthProvider) - self.assertEqual(self.cluster.auth_provider.username, 'cassandra') - self.assertEqual(self.cluster.auth_provider.password, 'cassandra') + self.assertEqual(self.cluster.auth_provider.username, 'user1') + self.assertEqual(self.cluster.auth_provider.password, 'user1') def test_support_leaving_the_auth_unset(self): with self.assertRaises(NoHostAvailable): self.connect(self.creds_no_auth) self.assertIsNone(self.cluster.auth_provider) def test_support_overriding_auth_provider(self): try: self.connect(self.creds, auth_provider=PlainTextAuthProvider('invalid', 'invalid')) except: pass # this will fail soon when sni_single_endpoint is updated self.assertIsInstance(self.cluster.auth_provider, PlainTextAuthProvider) self.assertEqual(self.cluster.auth_provider.username, 'invalid') self.assertEqual(self.cluster.auth_provider.password, 'invalid') def test_error_overriding_ssl_context(self): with self.assertRaises(ValueError) as cm: - self.connect(self.creds, ssl_context=SSLContext(PROTOCOL_TLSv1)) + self.connect(self.creds, ssl_context=SSLContext(PROTOCOL_TLS)) self.assertIn('cannot be specified with a cloud configuration', str(cm.exception)) def test_error_overriding_ssl_options(self): with self.assertRaises(ValueError) as cm: self.connect(self.creds, ssl_options={'check_hostname': True}) self.assertIn('cannot be specified with a cloud configuration', str(cm.exception)) def _bad_hostname_metadata(self, config, http_data): config = parse_metadata_info(config, http_data) config.sni_host = "127.0.0.1" return config def test_verify_hostname(self): with patch('cassandra.datastax.cloud.parse_metadata_info', wraps=self._bad_hostname_metadata): with self.assertRaises(NoHostAvailable) as e: self.connect(self.creds) - self.assertIn("hostname", str(e.exception)) + self.assertIn("hostname", str(e.exception).lower()) def test_error_when_bundle_doesnt_exist(self): try: self.connect('/invalid/path/file.zip') except Exception as e: if six.PY2: self.assertIsInstance(e, IOError) else: self.assertIsInstance(e, FileNotFoundError) def test_load_balancing_policy_is_dcawaretokenlbp(self): self.connect(self.creds) self.assertIsInstance(self.cluster.profile_manager.default.load_balancing_policy, TokenAwarePolicy) self.assertIsInstance(self.cluster.profile_manager.default.load_balancing_policy._child_policy, DCAwareRoundRobinPolicy) def test_resolve_and_reconnect_on_node_down(self): self.connect(self.creds, idle_heartbeat_interval=1, idle_heartbeat_timeout=1, reconnection_policy=ConstantReconnectionPolicy(120)) self.assertEqual(len(self.hosts_up()), 3) CLOUD_PROXY_SERVER.stop_node(1) wait_until_not_raised( lambda: self.assertEqual(len(self.hosts_up()), 2), 0.02, 250) host = [h for h in self.cluster.metadata.all_hosts() if not h.is_up][0] with patch.object(SniEndPoint, "resolve", wraps=host.endpoint.resolve) as mocked_resolve: CLOUD_PROXY_SERVER.start_node(1) wait_until_not_raised( lambda: self.assertEqual(len(self.hosts_up()), 3), 0.02, 250) - mocked_resolve.assert_called_once() + mocked_resolve.assert_called() def test_metadata_unreachable(self): with self.assertRaises(DriverException) as cm: self.connect(self.creds_unreachable, connect_timeout=1) self.assertIn('Unable to connect to the metadata service', str(cm.exception)) def test_metadata_ssl_error(self): with self.assertRaises(DriverException) as cm: self.connect(self.creds_invalid_ca) self.assertIn('Unable to connect to the metadata', str(cm.exception)) def test_default_consistency(self): self.connect(self.creds) self.assertEqual(self.session.default_consistency_level, ConsistencyLevel.LOCAL_QUORUM) - self.assertEqual(self.cluster.profile_manager.default.consistency_level, ConsistencyLevel.LOCAL_QUORUM) + # Verify EXEC_PROFILE_DEFAULT, EXEC_PROFILE_GRAPH_DEFAULT, + # EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT, EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT + for ep_key in six.iterkeys(self.cluster.profile_manager.profiles): + ep = self.cluster.profile_manager.profiles[ep_key] + self.assertEqual( + ep.consistency_level, + ConsistencyLevel.LOCAL_QUORUM, + "Expecting LOCAL QUORUM for profile {}, but got {} instead".format( + _execution_profile_to_string(ep_key), ConsistencyLevel.value_to_name[ep.consistency_level] + )) def test_default_consistency_of_execution_profiles(self): cloud_config = {'secure_connect_bundle': self.creds} self.cluster = Cluster(cloud=cloud_config, protocol_version=4, execution_profiles={ 'pre_create_default_ep': ExecutionProfile(), 'pre_create_changed_ep': ExecutionProfile( consistency_level=ConsistencyLevel.LOCAL_ONE, ), }) self.cluster.add_execution_profile('pre_connect_default_ep', ExecutionProfile()) self.cluster.add_execution_profile( 'pre_connect_changed_ep', ExecutionProfile( consistency_level=ConsistencyLevel.LOCAL_ONE, ) ) session = self.cluster.connect(wait_for_all_pools=True) self.cluster.add_execution_profile('post_connect_default_ep', ExecutionProfile()) self.cluster.add_execution_profile( 'post_connect_changed_ep', ExecutionProfile( consistency_level=ConsistencyLevel.LOCAL_ONE, ) ) for default in ['pre_create_default_ep', 'pre_connect_default_ep', 'post_connect_default_ep']: cl = self.cluster.profile_manager.profiles[default].consistency_level self.assertEqual( cl, ConsistencyLevel.LOCAL_QUORUM, "Expecting LOCAL QUORUM for profile {}, but got {} instead".format(default, cl) ) for changed in ['pre_create_changed_ep', 'pre_connect_changed_ep', 'post_connect_changed_ep']: cl = self.cluster.profile_manager.profiles[changed].consistency_level self.assertEqual( cl, ConsistencyLevel.LOCAL_ONE, "Expecting LOCAL ONE for profile {}, but got {} instead".format(default, cl) ) def test_consistency_guardrails(self): self.connect(self.creds) self.session.execute( "CREATE KEYSPACE IF NOT EXISTS test_consistency_guardrails " "with replication={'class': 'SimpleStrategy', 'replication_factor': 1}" ) self.session.execute("CREATE TABLE IF NOT EXISTS test_consistency_guardrails.guardrails (id int primary key)") for consistency in DISALLOWED_CONSISTENCIES: statement = SimpleStatement( "INSERT INTO test_consistency_guardrails.guardrails (id) values (1)", consistency_level=consistency ) with self.assertRaises(InvalidRequest) as e: self.session.execute(statement) self.assertIn('not allowed for Write Consistency Level', str(e.exception)) # Sanity check to make sure we can do a normal insert statement = SimpleStatement( "INSERT INTO test_consistency_guardrails.guardrails (id) values (1)", consistency_level=ConsistencyLevel.LOCAL_QUORUM ) try: self.session.execute(statement) except InvalidRequest: self.fail("InvalidRequest was incorrectly raised for write query at LOCAL QUORUM!") + + def test_cqlengine_can_connect(self): + class TestModel(Model): + id = columns.Integer(primary_key=True) + val = columns.Text() + + connection.setup(None, "test", cloud={'secure_connect_bundle': self.creds}) + create_keyspace_simple('test', 1) + sync_table(TestModel) + TestModel.objects.create(id=42, value='test') + self.assertEqual(len(TestModel.objects.all()), 1) diff --git a/tests/integration/advanced/cloud/test_cloud_schema.py b/tests/integration/cloud/test_cloud_schema.py similarity index 98% rename from tests/integration/advanced/cloud/test_cloud_schema.py rename to tests/integration/cloud/test_cloud_schema.py index 0a70fd0..1d52e8e 100644 --- a/tests/integration/advanced/cloud/test_cloud_schema.py +++ b/tests/integration/cloud/test_cloud_schema.py @@ -1,118 +1,118 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License """ This is mostly copypasta from integration/long/test_schema.py TODO: Come up with way to run cloud and local tests without duplication """ import logging import time from cassandra import ConsistencyLevel from cassandra.cluster import Cluster from cassandra.query import SimpleStatement from tests.integration import execute_until_pass -from tests.integration.advanced.cloud import CloudProxyCluster +from tests.integration.cloud import CloudProxyCluster log = logging.getLogger(__name__) class CloudSchemaTests(CloudProxyCluster): def test_recreates(self): """ Basic test for repeated schema creation and use, using many different keyspaces """ self.connect(self.creds) session = self.session for _ in self.cluster.metadata.all_hosts(): for keyspace_number in range(5): keyspace = "ks_{0}".format(keyspace_number) if keyspace in self.cluster.metadata.keyspaces.keys(): drop = "DROP KEYSPACE {0}".format(keyspace) log.debug(drop) execute_until_pass(session, drop) create = "CREATE KEYSPACE {0} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor': 3}}".format( keyspace) log.debug(create) execute_until_pass(session, create) create = "CREATE TABLE {0}.cf (k int PRIMARY KEY, i int)".format(keyspace) log.debug(create) execute_until_pass(session, create) use = "USE {0}".format(keyspace) log.debug(use) execute_until_pass(session, use) insert = "INSERT INTO cf (k, i) VALUES (0, 0)" log.debug(insert) ss = SimpleStatement(insert, consistency_level=ConsistencyLevel.QUORUM) execute_until_pass(session, ss) def test_for_schema_disagreement_attribute(self): """ Tests to ensure that schema disagreement is properly surfaced on the response future. Creates and destroys keyspaces/tables with various schema agreement timeouts set. First part runs cql create/drop cmds with schema agreement set in such away were it will be impossible for agreement to occur during timeout. It then validates that the correct value is set on the result. Second part ensures that when schema agreement occurs, that the result set reflects that appropriately @since 3.1.0 @jira_ticket PYTHON-458 @expected_result is_schema_agreed is set appropriately on response thefuture @test_category schema """ # This should yield a schema disagreement cloud_config = {'secure_connect_bundle': self.creds} cluster = Cluster(max_schema_agreement_wait=0.001, protocol_version=4, cloud=cloud_config) session = cluster.connect(wait_for_all_pools=True) rs = session.execute( "CREATE KEYSPACE test_schema_disagreement WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}") self.check_and_wait_for_agreement(session, rs, False) rs = session.execute( SimpleStatement("CREATE TABLE test_schema_disagreement.cf (key int PRIMARY KEY, value int)", consistency_level=ConsistencyLevel.ALL)) self.check_and_wait_for_agreement(session, rs, False) rs = session.execute("DROP KEYSPACE test_schema_disagreement") self.check_and_wait_for_agreement(session, rs, False) cluster.shutdown() # These should have schema agreement cluster = Cluster(protocol_version=4, max_schema_agreement_wait=100, cloud=cloud_config) session = cluster.connect() rs = session.execute( "CREATE KEYSPACE test_schema_disagreement WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}") self.check_and_wait_for_agreement(session, rs, True) rs = session.execute( SimpleStatement("CREATE TABLE test_schema_disagreement.cf (key int PRIMARY KEY, value int)", consistency_level=ConsistencyLevel.ALL)) self.check_and_wait_for_agreement(session, rs, True) rs = session.execute("DROP KEYSPACE test_schema_disagreement") self.check_and_wait_for_agreement(session, rs, True) cluster.shutdown() def check_and_wait_for_agreement(self, session, rs, exepected): # Wait for RESULT_KIND_SCHEMA_CHANGE message to arrive time.sleep(1) self.assertEqual(rs.response_future.is_schema_agreed, exepected) if not rs.response_future.is_schema_agreed: session.cluster.control_connection.wait_for_schema_agreement(wait_time=1000) \ No newline at end of file diff --git a/tests/integration/cqlengine/__init__.py b/tests/integration/cqlengine/__init__.py index d098ea7..e68baaa 100644 --- a/tests/integration/cqlengine/__init__.py +++ b/tests/integration/cqlengine/__init__.py @@ -1,116 +1,117 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import warnings try: import unittest2 as unittest except ImportError: import unittest # noqa from cassandra import ConsistencyLevel from cassandra.cqlengine import connection from cassandra.cqlengine.management import create_keyspace_simple, drop_keyspace, CQLENG_ALLOW_SCHEMA_MANAGEMENT import cassandra -from tests.integration import get_server_versions, use_single_node, PROTOCOL_VERSION, CASSANDRA_IP, set_default_cass_ip +from tests.integration import get_server_versions, use_single_node, PROTOCOL_VERSION, CASSANDRA_IP, ALLOW_BETA_PROTOCOL + DEFAULT_KEYSPACE = 'cqlengine_test' CQL_SKIP_EXECUTE = bool(os.getenv('CQL_SKIP_EXECUTE', False)) def setup_package(): warnings.simplefilter('always') # for testing warnings, make sure all are let through os.environ[CQLENG_ALLOW_SCHEMA_MANAGEMENT] = '1' - set_default_cass_ip() use_single_node() setup_connection(DEFAULT_KEYSPACE) create_keyspace_simple(DEFAULT_KEYSPACE, 1) def teardown_package(): connection.unregister_connection("default") def is_prepend_reversed(): # do we have https://issues.apache.org/jira/browse/CASSANDRA-8733 ? ver, _ = get_server_versions() return not (ver >= (2, 0, 13) or ver >= (2, 1, 3)) def setup_connection(keyspace_name): connection.setup([CASSANDRA_IP], consistency=ConsistencyLevel.ONE, protocol_version=PROTOCOL_VERSION, + allow_beta_protocol_version=ALLOW_BETA_PROTOCOL, default_keyspace=keyspace_name) class StatementCounter(object): """ Simple python object used to hold a count of the number of times the wrapped method has been invoked """ def __init__(self, patched_func): self.func = patched_func self.counter = 0 def wrapped_execute(self, *args, **kwargs): self.counter += 1 return self.func(*args, **kwargs) def get_counter(self): return self.counter def execute_count(expected): """ A decorator used wrap cassandra.cqlengine.connection.execute. It counts the number of times this method is invoked then compares it to the number expected. If they don't match it throws an assertion error. This function can be disabled by running the test harness with the env variable CQL_SKIP_EXECUTE=1 set """ def innerCounter(fn): def wrapped_function(*args, **kwargs): # Create a counter monkey patch into cassandra.cqlengine.connection.execute count = StatementCounter(cassandra.cqlengine.connection.execute) original_function = cassandra.cqlengine.connection.execute # Monkey patch in our StatementCounter wrapper cassandra.cqlengine.connection.execute = count.wrapped_execute # Invoked the underlying unit test to_return = fn(*args, **kwargs) # Get the count from our monkey patched counter count.get_counter() # DeMonkey Patch our code cassandra.cqlengine.connection.execute = original_function # Check to see if we have a pre-existing test case to work from. if len(args) is 0: test_case = unittest.TestCase("__init__") else: test_case = args[0] # Check to see if the count is what you expect test_case.assertEqual(count.get_counter(), expected, msg="Expected number of cassandra.cqlengine.connection.execute calls ({0}) doesn't match actual number invoked ({1})".format(expected, count.get_counter())) return to_return # Name of the wrapped function must match the original or unittest will error out. wrapped_function.__name__ = fn.__name__ wrapped_function.__doc__ = fn.__doc__ # Escape hatch if(CQL_SKIP_EXECUTE): return fn else: return wrapped_function return innerCounter diff --git a/tests/integration/advanced/__init__.py b/tests/integration/cqlengine/advanced/__init__.py similarity index 67% copy from tests/integration/advanced/__init__.py copy to tests/integration/cqlengine/advanced/__init__.py index 662f5b8..386372e 100644 --- a/tests/integration/advanced/__init__.py +++ b/tests/integration/cqlengine/advanced/__init__.py @@ -1,23 +1,14 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License +# limitations under the License. -try: - import unittest2 as unittest -except ImportError: - import unittest # noqa - -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) diff --git a/tests/integration/cqlengine/advanced/test_cont_paging.py b/tests/integration/cqlengine/advanced/test_cont_paging.py new file mode 100644 index 0000000..38b4355 --- /dev/null +++ b/tests/integration/cqlengine/advanced/test_cont_paging.py @@ -0,0 +1,170 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +from packaging.version import Version + +from cassandra.cluster import (EXEC_PROFILE_DEFAULT, + ContinuousPagingOptions, ExecutionProfile, + ProtocolVersion) +from cassandra.cqlengine import columns, connection, models +from cassandra.cqlengine.management import drop_table, sync_table +from tests.integration import (DSE_VERSION, greaterthanorequaldse51, + greaterthanorequaldse60, requiredse, TestCluster) + + +class TestMultiKeyModel(models.Model): + partition = columns.Integer(primary_key=True) + cluster = columns.Integer(primary_key=True) + count = columns.Integer(required=False) + text = columns.Text(required=False) + + +def setup_module(): + if DSE_VERSION: + sync_table(TestMultiKeyModel) + for i in range(1000): + TestMultiKeyModel.create(partition=i, cluster=i, count=5, text="text to write") + + +def teardown_module(): + if DSE_VERSION: + drop_table(TestMultiKeyModel) + + +@requiredse +class BasicConcurrentTests(): + required_dse_version = None + protocol_version = None + connections = set() + sane_connections = {"CONTDEFAULT"} + + @classmethod + def setUpClass(cls): + if DSE_VERSION: + cls._create_cluster_with_cp_options("CONTDEFAULT", ContinuousPagingOptions()) + cls._create_cluster_with_cp_options("ONEPAGE", ContinuousPagingOptions(max_pages=1)) + cls._create_cluster_with_cp_options("MANYPAGES", ContinuousPagingOptions(max_pages=10)) + cls._create_cluster_with_cp_options("SLOW", ContinuousPagingOptions(max_pages_per_second=1)) + + @classmethod + def tearDownClass(cls): + if not DSE_VERSION or DSE_VERSION < cls.required_dse_version: + return + + cls.cluster_default.shutdown() + connection.set_default_connection("default") + + @classmethod + def _create_cluster_with_cp_options(cls, name, cp_options): + execution_profiles = {EXEC_PROFILE_DEFAULT: + ExecutionProfile(continuous_paging_options=cp_options)} + cls.cluster_default = TestCluster(protocol_version=cls.protocol_version, + execution_profiles=execution_profiles) + cls.session_default = cls.cluster_default.connect(wait_for_all_pools=True) + connection.register_connection(name, default=True, session=cls.session_default) + cls.connections.add(name) + + def test_continuous_paging_basic(self): + """ + Test to ensure that various continuous paging works with cqlengine + for session + @since DSE 2.4 + @jira_ticket PYTHON-872 + @expected_result various continous paging options should fetch all the results + + @test_category queries + """ + for connection_name in self.sane_connections: + connection.set_default_connection(connection_name) + row = TestMultiKeyModel.get(partition=0, cluster=0) + self.assertEqual(row.partition, 0) + self.assertEqual(row.cluster, 0) + rows = TestMultiKeyModel.objects().allow_filtering() + self.assertEqual(len(rows), 1000) + + def test_fetch_size(self): + """ + Test to ensure that various continuous paging works with different fetch sizes + for session + @since DSE 2.4 + @jira_ticket PYTHON-872 + @expected_result various continous paging options should fetch all the results + + @test_category queries + """ + for connection_name in self.connections: + conn = connection._connections[connection_name] + initial_default = conn.session.default_fetch_size + self.addCleanup( + setattr, + conn.session, + "default_fetch_size", + initial_default + ) + + connection.set_default_connection("ONEPAGE") + for fetch_size in (2, 3, 7, 10, 99, 100, 101, 150): + connection._connections["ONEPAGE"].session.default_fetch_size = fetch_size + rows = TestMultiKeyModel.objects().allow_filtering() + self.assertEqual(fetch_size, len(rows)) + + connection.set_default_connection("MANYPAGES") + for fetch_size in (2, 3, 7, 10, 15): + connection._connections["MANYPAGES"].session.default_fetch_size = fetch_size + rows = TestMultiKeyModel.objects().allow_filtering() + self.assertEqual(fetch_size * 10, len(rows)) + + for connection_name in self.sane_connections: + connection.set_default_connection(connection_name) + for fetch_size in (2, 3, 7, 10, 99, 100, 101, 150): + connection._connections[connection_name].session.default_fetch_size = fetch_size + rows = TestMultiKeyModel.objects().allow_filtering() + self.assertEqual(1000, len(rows)) + + +@requiredse +@greaterthanorequaldse51 +class ContPagingTestsDSEV1(BasicConcurrentTests, unittest.TestCase): + @classmethod + def setUpClass(cls): + BasicConcurrentTests.required_dse_version = Version('5.1') + if not DSE_VERSION or DSE_VERSION < BasicConcurrentTests.required_dse_version: + return + + BasicConcurrentTests.protocol_version = ProtocolVersion.DSE_V1 + BasicConcurrentTests.setUpClass() + +@requiredse +@greaterthanorequaldse60 +class ContPagingTestsDSEV2(BasicConcurrentTests, unittest.TestCase): + @classmethod + def setUpClass(cls): + BasicConcurrentTests.required_dse_version = Version('6.0') + if not DSE_VERSION or DSE_VERSION < BasicConcurrentTests.required_dse_version: + return + BasicConcurrentTests.protocol_version = ProtocolVersion.DSE_V2 + BasicConcurrentTests.setUpClass() + + cls.connections = cls.connections.union({"SMALL_QUEUE", "BIG_QUEUE"}) + cls.sane_connections = cls.sane_connections.union({"SMALL_QUEUE", "BIG_QUEUE"}) + + cls._create_cluster_with_cp_options("SMALL_QUEUE", ContinuousPagingOptions(max_queue_size=2)) + cls._create_cluster_with_cp_options("BIG_QUEUE", ContinuousPagingOptions(max_queue_size=400)) diff --git a/tests/integration/cqlengine/connections/test_connection.py b/tests/integration/cqlengine/connections/test_connection.py index bbc0231..c46df31 100644 --- a/tests/integration/cqlengine/connections/test_connection.py +++ b/tests/integration/cqlengine/connections/test_connection.py @@ -1,198 +1,198 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from cassandra import ConsistencyLevel from cassandra.cqlengine.models import Model from cassandra.cqlengine import columns, connection, models from cassandra.cqlengine.management import sync_table -from cassandra.cluster import Cluster, ExecutionProfile, _clusters_for_shutdown, _ConfigMode, EXEC_PROFILE_DEFAULT +from cassandra.cluster import ExecutionProfile, _clusters_for_shutdown, _ConfigMode, EXEC_PROFILE_DEFAULT from cassandra.policies import RoundRobinPolicy from cassandra.query import dict_factory -from tests.integration import CASSANDRA_IP, PROTOCOL_VERSION, execute_with_long_wait_retry, local +from tests.integration import CASSANDRA_IP, PROTOCOL_VERSION, execute_with_long_wait_retry, local, TestCluster from tests.integration.cqlengine.base import BaseCassEngTestCase from tests.integration.cqlengine import DEFAULT_KEYSPACE, setup_connection class TestConnectModel(Model): id = columns.Integer(primary_key=True) keyspace = columns.Text() class ConnectionTest(unittest.TestCase): def tearDown(self): connection.unregister_connection("default") @local def test_connection_setup_with_setup(self): connection.setup(hosts=None, default_keyspace=None) self.assertIsNotNone(connection.get_connection("default").cluster.metadata.get_host("127.0.0.1")) @local def test_connection_setup_with_default(self): connection.default() self.assertIsNotNone(connection.get_connection("default").cluster.metadata.get_host("127.0.0.1")) def test_only_one_connection_is_created(self): """ Test to ensure that only one new connection is created by connection.register_connection @since 3.12 @jira_ticket PYTHON-814 @expected_result Only one connection is created @test_category object_mapper """ number_of_clusters_before = len(_clusters_for_shutdown) connection.default() number_of_clusters_after = len(_clusters_for_shutdown) self.assertEqual(number_of_clusters_after - number_of_clusters_before, 1) class SeveralConnectionsTest(BaseCassEngTestCase): @classmethod def setUpClass(cls): connection.unregister_connection('default') cls.keyspace1 = 'ctest1' cls.keyspace2 = 'ctest2' super(SeveralConnectionsTest, cls).setUpClass() - cls.setup_cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cls.setup_cluster = TestCluster() cls.setup_session = cls.setup_cluster.connect() ddl = "CREATE KEYSPACE {0} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor': '{1}'}}".format(cls.keyspace1, 1) execute_with_long_wait_retry(cls.setup_session, ddl) ddl = "CREATE KEYSPACE {0} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor': '{1}'}}".format(cls.keyspace2, 1) execute_with_long_wait_retry(cls.setup_session, ddl) @classmethod def tearDownClass(cls): execute_with_long_wait_retry(cls.setup_session, "DROP KEYSPACE {0}".format(cls.keyspace1)) execute_with_long_wait_retry(cls.setup_session, "DROP KEYSPACE {0}".format(cls.keyspace2)) models.DEFAULT_KEYSPACE = DEFAULT_KEYSPACE cls.setup_cluster.shutdown() setup_connection(DEFAULT_KEYSPACE) models.DEFAULT_KEYSPACE def setUp(self): - self.c = Cluster(protocol_version=PROTOCOL_VERSION) + self.c = TestCluster() self.session1 = self.c.connect(keyspace=self.keyspace1) self.session1.row_factory = dict_factory self.session2 = self.c.connect(keyspace=self.keyspace2) self.session2.row_factory = dict_factory def tearDown(self): self.c.shutdown() def test_connection_session_switch(self): """ Test to ensure that when the default keyspace is changed in a session and that session, is set in the connection class, that the new defaul keyspace is honored. @since 3.1 @jira_ticket PYTHON-486 @expected_result CQLENGINE adopts whatever keyspace is passed in vai the set_session method as default @test_category object_mapper """ connection.set_session(self.session1) sync_table(TestConnectModel) TCM1 = TestConnectModel.create(id=1, keyspace=self.keyspace1) connection.set_session(self.session2) sync_table(TestConnectModel) TCM2 = TestConnectModel.create(id=1, keyspace=self.keyspace2) connection.set_session(self.session1) self.assertEqual(1, TestConnectModel.objects.count()) self.assertEqual(TestConnectModel.objects.first(), TCM1) connection.set_session(self.session2) self.assertEqual(1, TestConnectModel.objects.count()) self.assertEqual(TestConnectModel.objects.first(), TCM2) class ConnectionModel(Model): key = columns.Integer(primary_key=True) some_data = columns.Text() class ConnectionInitTest(unittest.TestCase): def test_default_connection_uses_legacy(self): connection.default() conn = connection.get_connection() self.assertEqual(conn.cluster._config_mode, _ConfigMode.LEGACY) def test_connection_with_legacy_settings(self): connection.setup( hosts=[CASSANDRA_IP], default_keyspace=DEFAULT_KEYSPACE, consistency=ConsistencyLevel.LOCAL_ONE ) conn = connection.get_connection() self.assertEqual(conn.cluster._config_mode, _ConfigMode.LEGACY) def test_connection_from_session_with_execution_profile(self): - cluster = Cluster(execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=dict_factory)}) + cluster = TestCluster(execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=dict_factory)}) session = cluster.connect() connection.default() connection.set_session(session) conn = connection.get_connection() self.assertEqual(conn.cluster._config_mode, _ConfigMode.PROFILES) def test_connection_from_session_with_legacy_settings(self): - cluster = Cluster(load_balancing_policy=RoundRobinPolicy()) + cluster = TestCluster(load_balancing_policy=RoundRobinPolicy()) session = cluster.connect() session.row_factory = dict_factory connection.set_session(session) conn = connection.get_connection() self.assertEqual(conn.cluster._config_mode, _ConfigMode.LEGACY) def test_uncommitted_session_uses_legacy(self): - cluster = Cluster() + cluster = TestCluster() session = cluster.connect() session.row_factory = dict_factory connection.set_session(session) conn = connection.get_connection() self.assertEqual(conn.cluster._config_mode, _ConfigMode.LEGACY) def test_legacy_insert_query(self): connection.setup( hosts=[CASSANDRA_IP], default_keyspace=DEFAULT_KEYSPACE, consistency=ConsistencyLevel.LOCAL_ONE ) self.assertEqual(connection.get_connection().cluster._config_mode, _ConfigMode.LEGACY) sync_table(ConnectionModel) ConnectionModel.objects.create(key=0, some_data='text0') ConnectionModel.objects.create(key=1, some_data='text1') self.assertEqual(ConnectionModel.objects(key=0)[0].some_data, 'text0') def test_execution_profile_insert_query(self): - cluster = Cluster(execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=dict_factory)}) + cluster = TestCluster(execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=dict_factory)}) session = cluster.connect() connection.default() connection.set_session(session) self.assertEqual(connection.get_connection().cluster._config_mode, _ConfigMode.PROFILES) sync_table(ConnectionModel) ConnectionModel.objects.create(key=0, some_data='text0') ConnectionModel.objects.create(key=1, some_data='text1') self.assertEqual(ConnectionModel.objects(key=0)[0].some_data, 'text0') diff --git a/tests/integration/cqlengine/management/test_management.py b/tests/integration/cqlengine/management/test_management.py index 6b91760..7edb3e7 100644 --- a/tests/integration/cqlengine/management/test_management.py +++ b/tests/integration/cqlengine/management/test_management.py @@ -1,480 +1,489 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa import mock import logging from packaging.version import Version - from cassandra.cqlengine.connection import get_session, get_cluster from cassandra.cqlengine import CQLEngineException from cassandra.cqlengine import management from cassandra.cqlengine.management import _get_table_metadata, sync_table, drop_table, sync_type from cassandra.cqlengine.models import Model from cassandra.cqlengine import columns -from tests.integration import PROTOCOL_VERSION, greaterthancass20, MockLoggingHandler, CASSANDRA_VERSION +from tests.integration import DSE_VERSION, PROTOCOL_VERSION, greaterthancass20, MockLoggingHandler, CASSANDRA_VERSION from tests.integration.cqlengine.base import BaseCassEngTestCase from tests.integration.cqlengine.query.test_queryset import TestModel from cassandra.cqlengine.usertype import UserType from tests.integration.cqlengine import DEFAULT_KEYSPACE +INCLUDE_REPAIR = not CASSANDRA_VERSION >= Version('4-a') # This should cover DSE 6.0+ + + class KeyspaceManagementTest(BaseCassEngTestCase): def test_create_drop_succeeeds(self): cluster = get_cluster() keyspace_ss = 'test_ks_ss' self.assertNotIn(keyspace_ss, cluster.metadata.keyspaces) management.create_keyspace_simple(keyspace_ss, 2) self.assertIn(keyspace_ss, cluster.metadata.keyspaces) management.drop_keyspace(keyspace_ss) self.assertNotIn(keyspace_ss, cluster.metadata.keyspaces) keyspace_nts = 'test_ks_nts' self.assertNotIn(keyspace_nts, cluster.metadata.keyspaces) management.create_keyspace_network_topology(keyspace_nts, {'dc1': 1}) self.assertIn(keyspace_nts, cluster.metadata.keyspaces) management.drop_keyspace(keyspace_nts) self.assertNotIn(keyspace_nts, cluster.metadata.keyspaces) class DropTableTest(BaseCassEngTestCase): def test_multiple_deletes_dont_fail(self): sync_table(TestModel) drop_table(TestModel) drop_table(TestModel) class LowercaseKeyModel(Model): first_key = columns.Integer(primary_key=True) second_key = columns.Integer(primary_key=True) some_data = columns.Text() class CapitalizedKeyModel(Model): firstKey = columns.Integer(primary_key=True) secondKey = columns.Integer(primary_key=True) someData = columns.Text() class PrimaryKeysOnlyModel(Model): __table_name__ = "primary_keys_only" __options__ = {'compaction': {'class': 'LeveledCompactionStrategy'}} first_key = columns.Integer(primary_key=True) second_key = columns.Integer(primary_key=True) class PrimaryKeysModelChanged(Model): __table_name__ = "primary_keys_only" __options__ = {'compaction': {'class': 'LeveledCompactionStrategy'}} new_first_key = columns.Integer(primary_key=True) second_key = columns.Integer(primary_key=True) class PrimaryKeysModelTypeChanged(Model): __table_name__ = "primary_keys_only" __options__ = {'compaction': {'class': 'LeveledCompactionStrategy'}} first_key = columns.Float(primary_key=True) second_key = columns.Integer(primary_key=True) class PrimaryKeysRemovedPk(Model): __table_name__ = "primary_keys_only" __options__ = {'compaction': {'class': 'LeveledCompactionStrategy'}} second_key = columns.Integer(primary_key=True) class PrimaryKeysAddedClusteringKey(Model): __table_name__ = "primary_keys_only" __options__ = {'compaction': {'class': 'LeveledCompactionStrategy'}} new_first_key = columns.Float(primary_key=True) second_key = columns.Integer(primary_key=True) class CapitalizedKeyTest(BaseCassEngTestCase): def test_table_definition(self): """ Tests that creating a table with capitalized column names succeeds """ sync_table(LowercaseKeyModel) sync_table(CapitalizedKeyModel) drop_table(LowercaseKeyModel) drop_table(CapitalizedKeyModel) class FirstModel(Model): __table_name__ = 'first_model' first_key = columns.UUID(primary_key=True) second_key = columns.UUID() third_key = columns.Text() class SecondModel(Model): __table_name__ = 'first_model' first_key = columns.UUID(primary_key=True) second_key = columns.UUID() third_key = columns.Text() fourth_key = columns.Text() class ThirdModel(Model): __table_name__ = 'first_model' first_key = columns.UUID(primary_key=True) second_key = columns.UUID() third_key = columns.Text() # removed fourth key, but it should stay in the DB blah = columns.Map(columns.Text, columns.Text) class FourthModel(Model): __table_name__ = 'first_model' first_key = columns.UUID(primary_key=True) second_key = columns.UUID() third_key = columns.Text() # renamed model field, but map to existing column renamed = columns.Map(columns.Text, columns.Text, db_field='blah') class AddColumnTest(BaseCassEngTestCase): def setUp(self): drop_table(FirstModel) def test_add_column(self): sync_table(FirstModel) meta_columns = _get_table_metadata(FirstModel).columns self.assertEqual(set(meta_columns), set(FirstModel._columns)) sync_table(SecondModel) meta_columns = _get_table_metadata(FirstModel).columns self.assertEqual(set(meta_columns), set(SecondModel._columns)) sync_table(ThirdModel) meta_columns = _get_table_metadata(FirstModel).columns self.assertEqual(len(meta_columns), 5) self.assertEqual(len(ThirdModel._columns), 4) self.assertIn('fourth_key', meta_columns) self.assertNotIn('fourth_key', ThirdModel._columns) self.assertIn('blah', ThirdModel._columns) self.assertIn('blah', meta_columns) sync_table(FourthModel) meta_columns = _get_table_metadata(FirstModel).columns self.assertEqual(len(meta_columns), 5) self.assertEqual(len(ThirdModel._columns), 4) self.assertIn('fourth_key', meta_columns) self.assertNotIn('fourth_key', FourthModel._columns) self.assertIn('renamed', FourthModel._columns) self.assertNotIn('renamed', meta_columns) self.assertIn('blah', meta_columns) class ModelWithTableProperties(Model): __options__ = {'bloom_filter_fp_chance': '0.76328', 'comment': 'TxfguvBdzwROQALmQBOziRMbkqVGFjqcJfVhwGR', - 'gc_grace_seconds': '2063', - 'read_repair_chance': '0.17985', - 'dclocal_read_repair_chance': '0.50811'} + 'gc_grace_seconds': '2063'} + + if INCLUDE_REPAIR: + __options__.update( + {'read_repair_chance': '0.17985', + 'dclocal_read_repair_chance': '0.50811'} + ) key = columns.UUID(primary_key=True) class TablePropertiesTests(BaseCassEngTestCase): def setUp(self): drop_table(ModelWithTableProperties) def test_set_table_properties(self): sync_table(ModelWithTableProperties) expected = {'bloom_filter_fp_chance': 0.76328, 'comment': 'TxfguvBdzwROQALmQBOziRMbkqVGFjqcJfVhwGR', 'gc_grace_seconds': 2063, - 'read_repair_chance': 0.17985, # For some reason 'dclocal_read_repair_chance' in CQL is called # just 'local_read_repair_chance' in the schema table. # Source: https://issues.apache.org/jira/browse/CASSANDRA-6717 # TODO: due to a bug in the native driver i'm not seeing the local read repair chance show up # 'local_read_repair_chance': 0.50811, } + if INCLUDE_REPAIR: + expected.update({'read_repair_chance': 0.17985}) + options = management._get_table_metadata(ModelWithTableProperties).options self.assertEqual(dict([(k, options.get(k)) for k in expected.keys()]), expected) def test_table_property_update(self): ModelWithTableProperties.__options__['bloom_filter_fp_chance'] = 0.66778 ModelWithTableProperties.__options__['comment'] = 'xirAkRWZVVvsmzRvXamiEcQkshkUIDINVJZgLYSdnGHweiBrAiJdLJkVohdRy' ModelWithTableProperties.__options__['gc_grace_seconds'] = 96362 - ModelWithTableProperties.__options__['read_repair_chance'] = 0.2989 - ModelWithTableProperties.__options__['dclocal_read_repair_chance'] = 0.12732 + if INCLUDE_REPAIR: + ModelWithTableProperties.__options__['read_repair_chance'] = 0.2989 + ModelWithTableProperties.__options__['dclocal_read_repair_chance'] = 0.12732 sync_table(ModelWithTableProperties) table_options = management._get_table_metadata(ModelWithTableProperties).options self.assertDictContainsSubset(ModelWithTableProperties.__options__, table_options) def test_bogus_option_update(self): sync_table(ModelWithTableProperties) option = 'no way will this ever be an option' try: ModelWithTableProperties.__options__[option] = 'what was I thinking?' self.assertRaisesRegexp(KeyError, "Invalid table option.*%s.*" % option, sync_table, ModelWithTableProperties) finally: ModelWithTableProperties.__options__.pop(option, None) class SyncTableTests(BaseCassEngTestCase): def setUp(self): drop_table(PrimaryKeysOnlyModel) def test_sync_table_works_with_primary_keys_only_tables(self): sync_table(PrimaryKeysOnlyModel) # blows up with DoesNotExist if table does not exist table_meta = management._get_table_metadata(PrimaryKeysOnlyModel) self.assertIn('LeveledCompactionStrategy', table_meta.as_cql_query()) PrimaryKeysOnlyModel.__options__['compaction']['class'] = 'SizeTieredCompactionStrategy' sync_table(PrimaryKeysOnlyModel) table_meta = management._get_table_metadata(PrimaryKeysOnlyModel) self.assertIn('SizeTieredCompactionStrategy', table_meta.as_cql_query()) def test_primary_key_validation(self): """ Test to ensure that changes to primary keys throw CQLEngineExceptions @since 3.2 @jira_ticket PYTHON-532 @expected_result Attempts to modify primary keys throw an exception @test_category object_mapper """ sync_table(PrimaryKeysOnlyModel) self.assertRaises(CQLEngineException, sync_table, PrimaryKeysModelChanged) self.assertRaises(CQLEngineException, sync_table, PrimaryKeysAddedClusteringKey) self.assertRaises(CQLEngineException, sync_table, PrimaryKeysRemovedPk) class IndexModel(Model): __table_name__ = 'index_model' first_key = columns.UUID(primary_key=True) second_key = columns.Text(index=True) class IndexCaseSensitiveModel(Model): __table_name__ = 'IndexModel' __table_name_case_sensitive__ = True first_key = columns.UUID(primary_key=True) second_key = columns.Text(index=True) class BaseInconsistent(Model): __table_name__ = 'inconsistent' first_key = columns.UUID(primary_key=True) second_key = columns.Integer(index=True) third_key = columns.Integer(index=True) class ChangedInconsistent(Model): __table_name__ = 'inconsistent' __table_name_case_sensitive__ = True first_key = columns.UUID(primary_key=True) second_key = columns.Text(index=True) class BaseInconsistentType(UserType): __type_name__ = 'type_inconsistent' age = columns.Integer() name = columns.Text() class ChangedInconsistentType(UserType): __type_name__ = 'type_inconsistent' age = columns.Integer() name = columns.Integer() class InconsistentTable(BaseCassEngTestCase): def setUp(self): drop_table(IndexModel) def test_sync_warnings(self): """ Test to insure when inconsistent changes are made to a table, or type as part of a sync call that the proper logging messages are surfaced @since 3.2 @jira_ticket PYTHON-260 @expected_result warnings are logged @test_category object_mapper """ mock_handler = MockLoggingHandler() logger = logging.getLogger(management.__name__) logger.addHandler(mock_handler) sync_table(BaseInconsistent) sync_table(ChangedInconsistent) self.assertTrue('differing from the model type' in mock_handler.messages.get('warning')[0]) if CASSANDRA_VERSION >= Version('2.1'): sync_type(DEFAULT_KEYSPACE, BaseInconsistentType) mock_handler.reset() sync_type(DEFAULT_KEYSPACE, ChangedInconsistentType) self.assertTrue('differing from the model user type' in mock_handler.messages.get('warning')[0]) logger.removeHandler(mock_handler) class TestIndexSetModel(Model): partition = columns.UUID(primary_key=True) int_set = columns.Set(columns.Integer, index=True) int_list = columns.List(columns.Integer, index=True) text_map = columns.Map(columns.Text, columns.DateTime, index=True) mixed_tuple = columns.Tuple(columns.Text, columns.Integer, columns.Text, index=True) class IndexTests(BaseCassEngTestCase): def setUp(self): drop_table(IndexModel) drop_table(IndexCaseSensitiveModel) def test_sync_index(self): """ Tests the default table creation, and ensures the table_name is created and surfaced correctly in the table metadata @since 3.1 @jira_ticket PYTHON-337 @expected_result table_name is lower case @test_category object_mapper """ sync_table(IndexModel) table_meta = management._get_table_metadata(IndexModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'second_key')) # index already exists sync_table(IndexModel) table_meta = management._get_table_metadata(IndexModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'second_key')) def test_sync_index_case_sensitive(self): """ Tests the default table creation, and ensures the table_name is created correctly and surfaced correctly in table metadata @since 3.1 @jira_ticket PYTHON-337 @expected_result table_name is lower case @test_category object_mapper """ sync_table(IndexCaseSensitiveModel) table_meta = management._get_table_metadata(IndexCaseSensitiveModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'second_key')) # index already exists sync_table(IndexCaseSensitiveModel) table_meta = management._get_table_metadata(IndexCaseSensitiveModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'second_key')) @greaterthancass20 def test_sync_indexed_set(self): """ Tests that models that have container types with indices can be synced. @since 3.2 @jira_ticket PYTHON-533 @expected_result table_sync should complete without a server error. @test_category object_mapper """ sync_table(TestIndexSetModel) table_meta = management._get_table_metadata(TestIndexSetModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'int_set')) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'int_list')) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'text_map')) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'mixed_tuple')) class NonModelFailureTest(BaseCassEngTestCase): class FakeModel(object): pass def test_failure(self): with self.assertRaises(CQLEngineException): sync_table(self.FakeModel) class StaticColumnTests(BaseCassEngTestCase): def test_static_columns(self): if PROTOCOL_VERSION < 2: raise unittest.SkipTest("Native protocol 2+ required, currently using: {0}".format(PROTOCOL_VERSION)) class StaticModel(Model): id = columns.Integer(primary_key=True) c = columns.Integer(primary_key=True) name = columns.Text(static=True) drop_table(StaticModel) session = get_session() with mock.patch.object(session, "execute", wraps=session.execute) as m: sync_table(StaticModel) self.assertGreater(m.call_count, 0) statement = m.call_args[0][0].query_string self.assertIn('"name" text static', statement) # if we sync again, we should not apply an alter w/ a static sync_table(StaticModel) with mock.patch.object(session, "execute", wraps=session.execute) as m2: sync_table(StaticModel) self.assertEqual(len(m2.call_args_list), 0) diff --git a/tests/integration/cqlengine/model/test_model.py b/tests/integration/cqlengine/model/test_model.py index 81de0ea..bbd9e0c 100644 --- a/tests/integration/cqlengine/model/test_model.py +++ b/tests/integration/cqlengine/model/test_model.py @@ -1,268 +1,271 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from mock import patch from cassandra.cqlengine import columns, CQLEngineException from cassandra.cqlengine.management import sync_table, drop_table, create_keyspace_simple, drop_keyspace from cassandra.cqlengine import models from cassandra.cqlengine.models import Model, ModelDefinitionException from uuid import uuid1 from tests.integration import pypy from tests.integration.cqlengine.base import TestQueryUpdateModel class TestModel(unittest.TestCase): """ Tests the non-io functionality of models """ def test_instance_equality(self): """ tests the model equality functionality """ class EqualityModel(Model): pk = columns.Integer(primary_key=True) m0 = EqualityModel(pk=0) m1 = EqualityModel(pk=1) self.assertEqual(m0, m0) self.assertNotEqual(m0, m1) def test_model_equality(self): """ tests the model equality functionality """ class EqualityModel0(Model): pk = columns.Integer(primary_key=True) class EqualityModel1(Model): kk = columns.Integer(primary_key=True) m0 = EqualityModel0(pk=0) m1 = EqualityModel1(kk=1) self.assertEqual(m0, m0) self.assertNotEqual(m0, m1) def test_keywords_as_names(self): """ Test for CQL keywords as names test_keywords_as_names tests that CQL keywords are properly and automatically quoted in cqlengine. It creates a keyspace, keyspace, which should be automatically quoted to "keyspace" in CQL. It then creates a table, table, which should also be automatically quoted to "table". It then verfies that operations can be done on the "keyspace"."table" which has been created. It also verifies that table alternations work and operations can be performed on the altered table. @since 2.6.0 @jira_ticket PYTHON-244 @expected_result Cqlengine should quote CQL keywords properly when creating keyspaces and tables. @test_category schema:generation """ # If the keyspace exists, it will not be re-created create_keyspace_simple('keyspace', 1) class table(Model): __keyspace__ = 'keyspace' select = columns.Integer(primary_key=True) table = columns.Text() # In case the table already exists in keyspace drop_table(table) # Create should work sync_table(table) created = table.create(select=0, table='table') selected = table.objects(select=0)[0] self.assertEqual(created.select, selected.select) self.assertEqual(created.table, selected.table) # Alter should work class table(Model): __keyspace__ = 'keyspace' select = columns.Integer(primary_key=True) table = columns.Text() where = columns.Text() sync_table(table) created = table.create(select=1, table='table') selected = table.objects(select=1)[0] self.assertEqual(created.select, selected.select) self.assertEqual(created.table, selected.table) self.assertEqual(created.where, selected.where) drop_keyspace('keyspace') def test_column_family(self): class TestModel(Model): k = columns.Integer(primary_key=True) # no model keyspace uses default self.assertEqual(TestModel.column_family_name(), "%s.test_model" % (models.DEFAULT_KEYSPACE,)) # model keyspace overrides TestModel.__keyspace__ = "my_test_keyspace" self.assertEqual(TestModel.column_family_name(), "%s.test_model" % (TestModel.__keyspace__,)) # neither set should raise CQLEngineException before failing or formatting an invalid name del TestModel.__keyspace__ with patch('cassandra.cqlengine.models.DEFAULT_KEYSPACE', None): self.assertRaises(CQLEngineException, TestModel.column_family_name) # .. but we can still get the bare CF name self.assertEqual(TestModel.column_family_name(include_keyspace=False), "test_model") def test_column_family_case_sensitive(self): """ Test to ensure case sensitivity is honored when __table_name_case_sensitive__ flag is set @since 3.1 @jira_ticket PYTHON-337 @expected_result table_name case is respected @test_category object_mapper """ class TestModel(Model): __table_name__ = 'TestModel' __table_name_case_sensitive__ = True k = columns.Integer(primary_key=True) self.assertEqual(TestModel.column_family_name(), '%s."TestModel"' % (models.DEFAULT_KEYSPACE,)) TestModel.__keyspace__ = "my_test_keyspace" self.assertEqual(TestModel.column_family_name(), '%s."TestModel"' % (TestModel.__keyspace__,)) del TestModel.__keyspace__ with patch('cassandra.cqlengine.models.DEFAULT_KEYSPACE', None): self.assertRaises(CQLEngineException, TestModel.column_family_name) self.assertEqual(TestModel.column_family_name(include_keyspace=False), '"TestModel"') class BuiltInAttributeConflictTest(unittest.TestCase): """tests Model definitions that conflict with built-in attributes/methods""" def test_model_with_attribute_name_conflict(self): """should raise exception when model defines column that conflicts with built-in attribute""" with self.assertRaises(ModelDefinitionException): class IllegalTimestampColumnModel(Model): my_primary_key = columns.Integer(primary_key=True) timestamp = columns.BigInt() def test_model_with_method_name_conflict(self): """should raise exception when model defines column that conflicts with built-in method""" with self.assertRaises(ModelDefinitionException): class IllegalFilterColumnModel(Model): my_primary_key = columns.Integer(primary_key=True) filter = columns.Text() class ModelOverWriteTest(unittest.TestCase): def test_model_over_write(self): """ Test to ensure overwriting of primary keys in model inheritance is allowed This is currently only an issue in PyPy. When PYTHON-504 is introduced this should be updated error out and warn the user @since 3.6.0 @jira_ticket PYTHON-576 @expected_result primary keys can be overwritten via inheritance @test_category object_mapper """ class TimeModelBase(Model): uuid = columns.TimeUUID(primary_key=True) class DerivedTimeModel(TimeModelBase): __table_name__ = 'derived_time' uuid = columns.TimeUUID(primary_key=True, partition_key=True) value = columns.Text(required=False) # In case the table already exists in keyspace drop_table(DerivedTimeModel) sync_table(DerivedTimeModel) uuid_value = uuid1() uuid_value2 = uuid1() DerivedTimeModel.create(uuid=uuid_value, value="first") DerivedTimeModel.create(uuid=uuid_value2, value="second") DerivedTimeModel.objects.filter(uuid=uuid_value) class TestColumnComparison(unittest.TestCase): def test_comparison(self): l = [TestQueryUpdateModel.partition.column, TestQueryUpdateModel.cluster.column, TestQueryUpdateModel.count.column, TestQueryUpdateModel.text.column, TestQueryUpdateModel.text_set.column, TestQueryUpdateModel.text_list.column, TestQueryUpdateModel.text_map.column] self.assertEqual(l, sorted(l)) self.assertNotEqual(TestQueryUpdateModel.partition.column, TestQueryUpdateModel.cluster.column) self.assertLessEqual(TestQueryUpdateModel.partition.column, TestQueryUpdateModel.cluster.column) self.assertGreater(TestQueryUpdateModel.cluster.column, TestQueryUpdateModel.partition.column) self.assertGreaterEqual(TestQueryUpdateModel.cluster.column, TestQueryUpdateModel.partition.column) class TestDeprecationWarning(unittest.TestCase): def test_deprecation_warnings(self): """ Test to some deprecation warning have been added. It tests warnings for negative index, negative index slicing and table sensitive removal This test should be removed in 4.0, that's why the imports are in this test, so it's easier to remove @since 3.13 @jira_ticket PYTHON-877 @expected_result the deprecation warnings are emitted @test_category logs """ import warnings class SensitiveModel(Model): __table_name__ = 'SensitiveModel' __table_name_case_sensitive__ = True k = columns.Integer(primary_key=True) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") sync_table(SensitiveModel) self.addCleanup(drop_table, SensitiveModel) SensitiveModel.create(k=0) rows = SensitiveModel.objects().all().allow_filtering() rows[-1] rows[-1:] - self.assertEqual(len(w), 4) - self.assertIn("__table_name_case_sensitive__ will be removed in 4.0.", str(w[0].message)) - self.assertIn("__table_name_case_sensitive__ will be removed in 4.0.", str(w[1].message)) + # Asyncio complains loudly about old syntax on python 3.7+, so get rid of all of those + relevant_warnings = [warn for warn in w if "with (yield from lock)" not in str(warn.message)] + + self.assertEqual(len(relevant_warnings), 4) + self.assertIn("__table_name_case_sensitive__ will be removed in 4.0.", str(relevant_warnings[0].message)) + self.assertIn("__table_name_case_sensitive__ will be removed in 4.0.", str(relevant_warnings[1].message)) self.assertIn("ModelQuerySet indexing with negative indices support will be removed in 4.0.", - str(w[2].message)) + str(relevant_warnings[2].message)) self.assertIn("ModelQuerySet slicing with negative indices support will be removed in 4.0.", - str(w[3].message)) + str(relevant_warnings[3].message)) diff --git a/tests/integration/cqlengine/query/test_named.py b/tests/integration/cqlengine/query/test_named.py index 4907c26..3a6f83b 100644 --- a/tests/integration/cqlengine/query/test_named.py +++ b/tests/integration/cqlengine/query/test_named.py @@ -1,387 +1,387 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from cassandra import ConsistencyLevel from cassandra.cqlengine import operators from cassandra.cqlengine.named import NamedKeyspace from cassandra.cqlengine.operators import EqualsOperator, GreaterThanOrEqualOperator from cassandra.cqlengine.query import ResultObject from cassandra.concurrent import execute_concurrent_with_args from cassandra.cqlengine import models from tests.integration.cqlengine import setup_connection, execute_count from tests.integration.cqlengine.base import BaseCassEngTestCase from tests.integration.cqlengine.query.test_queryset import BaseQuerySetUsage from tests.integration import BasicSharedKeyspaceUnitTestCase, greaterthanorequalcass30 class TestQuerySetOperation(BaseCassEngTestCase): @classmethod def setUpClass(cls): super(TestQuerySetOperation, cls).setUpClass() cls.keyspace = NamedKeyspace('cqlengine_test') cls.table = cls.keyspace.table('test_model') def test_query_filter_parsing(self): """ Tests the queryset filter method parses it's kwargs properly """ query1 = self.table.objects(test_id=5) assert len(query1._where) == 1 op = query1._where[0] assert isinstance(op.operator, operators.EqualsOperator) assert op.value == 5 query2 = query1.filter(expected_result__gte=1) assert len(query2._where) == 2 op = query2._where[1] assert isinstance(op.operator, operators.GreaterThanOrEqualOperator) assert op.value == 1 def test_query_expression_parsing(self): """ Tests that query experessions are evaluated properly """ query1 = self.table.filter(self.table.column('test_id') == 5) assert len(query1._where) == 1 op = query1._where[0] assert isinstance(op.operator, operators.EqualsOperator) assert op.value == 5 query2 = query1.filter(self.table.column('expected_result') >= 1) assert len(query2._where) == 2 op = query2._where[1] assert isinstance(op.operator, operators.GreaterThanOrEqualOperator) assert op.value == 1 def test_filter_method_where_clause_generation(self): """ Tests the where clause creation """ query1 = self.table.objects(test_id=5) self.assertEqual(len(query1._where), 1) where = query1._where[0] self.assertEqual(where.field, 'test_id') self.assertEqual(where.value, 5) query2 = query1.filter(expected_result__gte=1) self.assertEqual(len(query2._where), 2) where = query2._where[0] self.assertEqual(where.field, 'test_id') self.assertIsInstance(where.operator, EqualsOperator) self.assertEqual(where.value, 5) where = query2._where[1] self.assertEqual(where.field, 'expected_result') self.assertIsInstance(where.operator, GreaterThanOrEqualOperator) self.assertEqual(where.value, 1) def test_query_expression_where_clause_generation(self): """ Tests the where clause creation """ query1 = self.table.objects(self.table.column('test_id') == 5) self.assertEqual(len(query1._where), 1) where = query1._where[0] self.assertEqual(where.field, 'test_id') self.assertEqual(where.value, 5) query2 = query1.filter(self.table.column('expected_result') >= 1) self.assertEqual(len(query2._where), 2) where = query2._where[0] self.assertEqual(where.field, 'test_id') self.assertIsInstance(where.operator, EqualsOperator) self.assertEqual(where.value, 5) where = query2._where[1] self.assertEqual(where.field, 'expected_result') self.assertIsInstance(where.operator, GreaterThanOrEqualOperator) self.assertEqual(where.value, 1) class TestQuerySetCountSelectionAndIteration(BaseQuerySetUsage): @classmethod def setUpClass(cls): super(TestQuerySetCountSelectionAndIteration, cls).setUpClass() from tests.integration.cqlengine.query.test_queryset import TestModel ks, tn = TestModel.column_family_name().split('.') cls.keyspace = NamedKeyspace(ks) cls.table = cls.keyspace.table(tn) @execute_count(2) def test_count(self): """ Tests that adding filtering statements affects the count query as expected """ assert self.table.objects.count() == 12 q = self.table.objects(test_id=0) assert q.count() == 4 @execute_count(2) def test_query_expression_count(self): """ Tests that adding query statements affects the count query as expected """ assert self.table.objects.count() == 12 q = self.table.objects(self.table.column('test_id') == 0) assert q.count() == 4 @execute_count(3) def test_iteration(self): """ Tests that iterating over a query set pulls back all of the expected results """ q = self.table.objects(test_id=0) # tuple of expected attempt_id, expected_result values compare_set = set([(0, 5), (1, 10), (2, 15), (3, 20)]) for t in q: val = t.attempt_id, t.expected_result assert val in compare_set compare_set.remove(val) assert len(compare_set) == 0 # test with regular filtering q = self.table.objects(attempt_id=3).allow_filtering() assert len(q) == 3 # tuple of expected test_id, expected_result values compare_set = set([(0, 20), (1, 20), (2, 75)]) for t in q: val = t.test_id, t.expected_result assert val in compare_set compare_set.remove(val) assert len(compare_set) == 0 # test with query method q = self.table.objects(self.table.column('attempt_id') == 3).allow_filtering() assert len(q) == 3 # tuple of expected test_id, expected_result values compare_set = set([(0, 20), (1, 20), (2, 75)]) for t in q: val = t.test_id, t.expected_result assert val in compare_set compare_set.remove(val) assert len(compare_set) == 0 @execute_count(2) def test_multiple_iterations_work_properly(self): """ Tests that iterating over a query set more than once works """ # test with both the filtering method and the query method for q in (self.table.objects(test_id=0), self.table.objects(self.table.column('test_id') == 0)): # tuple of expected attempt_id, expected_result values compare_set = set([(0, 5), (1, 10), (2, 15), (3, 20)]) for t in q: val = t.attempt_id, t.expected_result assert val in compare_set compare_set.remove(val) assert len(compare_set) == 0 # try it again compare_set = set([(0, 5), (1, 10), (2, 15), (3, 20)]) for t in q: val = t.attempt_id, t.expected_result assert val in compare_set compare_set.remove(val) assert len(compare_set) == 0 @execute_count(2) def test_multiple_iterators_are_isolated(self): """ tests that the use of one iterator does not affect the behavior of another """ for q in (self.table.objects(test_id=0), self.table.objects(self.table.column('test_id') == 0)): q = q.order_by('attempt_id') expected_order = [0, 1, 2, 3] iter1 = iter(q) iter2 = iter(q) for attempt_id in expected_order: assert next(iter1).attempt_id == attempt_id assert next(iter2).attempt_id == attempt_id @execute_count(3) def test_get_success_case(self): """ Tests that the .get() method works on new and existing querysets """ m = self.table.objects.get(test_id=0, attempt_id=0) assert isinstance(m, ResultObject) assert m.test_id == 0 assert m.attempt_id == 0 q = self.table.objects(test_id=0, attempt_id=0) m = q.get() assert isinstance(m, ResultObject) assert m.test_id == 0 assert m.attempt_id == 0 q = self.table.objects(test_id=0) m = q.get(attempt_id=0) assert isinstance(m, ResultObject) assert m.test_id == 0 assert m.attempt_id == 0 @execute_count(3) def test_query_expression_get_success_case(self): """ Tests that the .get() method works on new and existing querysets """ m = self.table.get(self.table.column('test_id') == 0, self.table.column('attempt_id') == 0) assert isinstance(m, ResultObject) assert m.test_id == 0 assert m.attempt_id == 0 q = self.table.objects(self.table.column('test_id') == 0, self.table.column('attempt_id') == 0) m = q.get() assert isinstance(m, ResultObject) assert m.test_id == 0 assert m.attempt_id == 0 q = self.table.objects(self.table.column('test_id') == 0) m = q.get(self.table.column('attempt_id') == 0) assert isinstance(m, ResultObject) assert m.test_id == 0 assert m.attempt_id == 0 @execute_count(1) def test_get_doesnotexist_exception(self): """ Tests that get calls that don't return a result raises a DoesNotExist error """ with self.assertRaises(self.table.DoesNotExist): self.table.objects.get(test_id=100) @execute_count(1) def test_get_multipleobjects_exception(self): """ Tests that get calls that return multiple results raise a MultipleObjectsReturned error """ with self.assertRaises(self.table.MultipleObjectsReturned): self.table.objects.get(test_id=1) class TestNamedWithMV(BasicSharedKeyspaceUnitTestCase): @classmethod def setUpClass(cls): super(TestNamedWithMV, cls).setUpClass() cls.default_keyspace = models.DEFAULT_KEYSPACE models.DEFAULT_KEYSPACE = cls.ks_name @classmethod def tearDownClass(cls): models.DEFAULT_KEYSPACE = cls.default_keyspace super(TestNamedWithMV, cls).tearDownClass() @greaterthanorequalcass30 @execute_count(5) def test_named_table_with_mv(self): """ Test NamedTable access to materialized views Creates some materialized views using Traditional CQL. Then ensures we can access those materialized view using the NamedKeyspace, and NamedTable interfaces. Tests basic filtering as well. @since 3.0.0 @jira_ticket PYTHON-406 @expected_result Named Tables should have access to materialized views @test_category materialized_view """ ks = models.DEFAULT_KEYSPACE self.session.execute("DROP MATERIALIZED VIEW IF EXISTS {0}.alltimehigh".format(ks)) self.session.execute("DROP MATERIALIZED VIEW IF EXISTS {0}.monthlyhigh".format(ks)) self.session.execute("DROP TABLE IF EXISTS {0}.scores".format(ks)) create_table = """CREATE TABLE {0}.scores( user TEXT, game TEXT, year INT, month INT, day INT, score INT, PRIMARY KEY (user, game, year, month, day) )""".format(ks) self.session.execute(create_table) create_mv = """CREATE MATERIALIZED VIEW {0}.monthlyhigh AS SELECT game, year, month, score, user, day FROM {0}.scores WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL PRIMARY KEY ((game, year, month), score, user, day) WITH CLUSTERING ORDER BY (score DESC, user ASC, day ASC)""".format(ks) self.session.execute(create_mv) create_mv_alltime = """CREATE MATERIALIZED VIEW {0}.alltimehigh AS SELECT * FROM {0}.scores WHERE game IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND day IS NOT NULL PRIMARY KEY (game, score, user, year, month, day) - WITH CLUSTERING ORDER BY (score DESC)""".format(ks) + WITH CLUSTERING ORDER BY (score DESC, user DESC, year DESC, month DESC, day DESC)""".format(ks) self.session.execute(create_mv_alltime) # Populate the base table with data prepared_insert = self.session.prepare("""INSERT INTO {0}.scores (user, game, year, month, day, score) VALUES (?, ?, ? ,? ,?, ?)""".format(ks)) parameters = (('pcmanus', 'Coup', 2015, 5, 1, 4000), ('jbellis', 'Coup', 2015, 5, 3, 1750), ('yukim', 'Coup', 2015, 5, 3, 2250), ('tjake', 'Coup', 2015, 5, 3, 500), ('iamaleksey', 'Coup', 2015, 6, 1, 2500), ('tjake', 'Coup', 2015, 6, 2, 1000), ('pcmanus', 'Coup', 2015, 6, 2, 2000), ('jmckenzie', 'Coup', 2015, 6, 9, 2700), ('jbellis', 'Coup', 2015, 6, 20, 3500), ('jbellis', 'Checkers', 2015, 6, 20, 1200), ('jbellis', 'Chess', 2015, 6, 21, 3500), ('pcmanus', 'Chess', 2015, 1, 25, 3200)) prepared_insert.consistency_level = ConsistencyLevel.ALL execute_concurrent_with_args(self.session, prepared_insert, parameters) # Attempt to query the data using Named Table interface # Also test filtering on mv's key_space = NamedKeyspace(ks) mv_monthly = key_space.table("monthlyhigh") mv_all_time = key_space.table("alltimehigh") self.assertTrue(self.check_table_size("scores", key_space, len(parameters))) self.assertTrue(self.check_table_size("monthlyhigh", key_space, len(parameters))) self.assertTrue(self.check_table_size("alltimehigh", key_space, len(parameters))) filtered_mv_monthly_objects = mv_monthly.objects.filter(game='Chess', year=2015, month=6) self.assertEqual(len(filtered_mv_monthly_objects), 1) self.assertEqual(filtered_mv_monthly_objects[0]['score'], 3500) self.assertEqual(filtered_mv_monthly_objects[0]['user'], 'jbellis') filtered_mv_alltime_objects = mv_all_time.objects.filter(game='Chess') self.assertEqual(len(filtered_mv_alltime_objects), 2) self.assertEqual(filtered_mv_alltime_objects[0]['score'], 3500) def check_table_size(self, table_name, key_space, expected_size): table = key_space.table(table_name) attempts = 0 while attempts < 10: attempts += 1 table_size = len(table.objects.all()) if(table_size is not expected_size): print("Table {0} size was {1} and was expected to be {2}".format(table_name, table_size, expected_size)) else: return True return False diff --git a/tests/integration/cqlengine/query/test_queryset.py b/tests/integration/cqlengine/query/test_queryset.py index e5a15b7..6bc9d70 100644 --- a/tests/integration/cqlengine/query/test_queryset.py +++ b/tests/integration/cqlengine/query/test_queryset.py @@ -1,1456 +1,1456 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import try: import unittest2 as unittest except ImportError: import unittest # noqa from datetime import datetime from uuid import uuid4 from packaging.version import Version import uuid -from cassandra.cluster import Cluster, Session +from cassandra.cluster import Session from cassandra import InvalidRequest from tests.integration.cqlengine.base import BaseCassEngTestCase from cassandra.cqlengine.connection import NOT_SET import mock from cassandra.cqlengine import functions from cassandra.cqlengine.management import sync_table, drop_table from cassandra.cqlengine.models import Model from cassandra.cqlengine import columns from cassandra.cqlengine import query from cassandra.cqlengine.query import QueryException, BatchQuery from datetime import timedelta from datetime import tzinfo from cassandra.cqlengine import statements from cassandra.cqlengine import operators from cassandra.util import uuid_from_time from cassandra.cqlengine.connection import get_session from tests.integration import PROTOCOL_VERSION, CASSANDRA_VERSION, greaterthancass20, greaterthancass21, \ - greaterthanorequalcass30 + greaterthanorequalcass30, TestCluster from tests.integration.cqlengine import execute_count, DEFAULT_KEYSPACE class TzOffset(tzinfo): """Minimal implementation of a timezone offset to help testing with timezone aware datetimes. """ def __init__(self, offset): self._offset = timedelta(hours=offset) def utcoffset(self, dt): return self._offset def tzname(self, dt): return 'TzOffset: {}'.format(self._offset.hours) def dst(self, dt): return timedelta(0) class TestModel(Model): test_id = columns.Integer(primary_key=True) attempt_id = columns.Integer(primary_key=True) description = columns.Text() expected_result = columns.Integer() test_result = columns.Integer() class IndexedTestModel(Model): test_id = columns.Integer(primary_key=True) attempt_id = columns.Integer(index=True) description = columns.Text() expected_result = columns.Integer() test_result = columns.Integer(index=True) class CustomIndexedTestModel(Model): test_id = columns.Integer(primary_key=True) description = columns.Text(custom_index=True) indexed = columns.Text(index=True) data = columns.Text() class IndexedCollectionsTestModel(Model): test_id = columns.Integer(primary_key=True) attempt_id = columns.Integer(index=True) description = columns.Text() expected_result = columns.Integer() test_result = columns.Integer(index=True) test_list = columns.List(columns.Integer, index=True) test_set = columns.Set(columns.Integer, index=True) test_map = columns.Map(columns.Text, columns.Integer, index=True) test_list_no_index = columns.List(columns.Integer, index=False) test_set_no_index = columns.Set(columns.Integer, index=False) test_map_no_index = columns.Map(columns.Text, columns.Integer, index=False) class TestMultiClusteringModel(Model): one = columns.Integer(primary_key=True) two = columns.Integer(primary_key=True) three = columns.Integer(primary_key=True) class TestQuerySetOperation(BaseCassEngTestCase): def test_query_filter_parsing(self): """ Tests the queryset filter method parses it's kwargs properly """ query1 = TestModel.objects(test_id=5) assert len(query1._where) == 1 op = query1._where[0] assert isinstance(op, statements.WhereClause) assert isinstance(op.operator, operators.EqualsOperator) assert op.value == 5 query2 = query1.filter(expected_result__gte=1) assert len(query2._where) == 2 op = query2._where[1] self.assertIsInstance(op, statements.WhereClause) self.assertIsInstance(op.operator, operators.GreaterThanOrEqualOperator) assert op.value == 1 def test_query_expression_parsing(self): """ Tests that query experessions are evaluated properly """ query1 = TestModel.filter(TestModel.test_id == 5) assert len(query1._where) == 1 op = query1._where[0] assert isinstance(op, statements.WhereClause) assert isinstance(op.operator, operators.EqualsOperator) assert op.value == 5 query2 = query1.filter(TestModel.expected_result >= 1) assert len(query2._where) == 2 op = query2._where[1] self.assertIsInstance(op, statements.WhereClause) self.assertIsInstance(op.operator, operators.GreaterThanOrEqualOperator) assert op.value == 1 def test_using_invalid_column_names_in_filter_kwargs_raises_error(self): """ Tests that using invalid or nonexistant column names for filter args raises an error """ with self.assertRaises(query.QueryException): TestModel.objects(nonsense=5) def test_using_nonexistant_column_names_in_query_args_raises_error(self): """ Tests that using invalid or nonexistant columns for query args raises an error """ with self.assertRaises(AttributeError): TestModel.objects(TestModel.nonsense == 5) def test_using_non_query_operators_in_query_args_raises_error(self): """ Tests that providing query args that are not query operator instances raises an error """ with self.assertRaises(query.QueryException): TestModel.objects(5) def test_queryset_is_immutable(self): """ Tests that calling a queryset function that changes it's state returns a new queryset """ query1 = TestModel.objects(test_id=5) assert len(query1._where) == 1 query2 = query1.filter(expected_result__gte=1) assert len(query2._where) == 2 assert len(query1._where) == 1 def test_queryset_limit_immutability(self): """ Tests that calling a queryset function that changes it's state returns a new queryset with same limit """ query1 = TestModel.objects(test_id=5).limit(1) assert query1._limit == 1 query2 = query1.filter(expected_result__gte=1) assert query2._limit == 1 query3 = query1.filter(expected_result__gte=1).limit(2) assert query1._limit == 1 assert query3._limit == 2 def test_the_all_method_duplicates_queryset(self): """ Tests that calling all on a queryset with previously defined filters duplicates queryset """ query1 = TestModel.objects(test_id=5) assert len(query1._where) == 1 query2 = query1.filter(expected_result__gte=1) assert len(query2._where) == 2 query3 = query2.all() assert query3 == query2 def test_queryset_with_distinct(self): """ Tests that calling distinct on a queryset w/without parameter are evaluated properly. """ query1 = TestModel.objects.distinct() self.assertEqual(len(query1._distinct_fields), 1) query2 = TestModel.objects.distinct(['test_id']) self.assertEqual(len(query2._distinct_fields), 1) query3 = TestModel.objects.distinct(['test_id', 'attempt_id']) self.assertEqual(len(query3._distinct_fields), 2) def test_defining_only_fields(self): """ Tests defining only fields @since 3.5 @jira_ticket PYTHON-560 @expected_result deferred fields should not be returned @test_category object_mapper """ # simple only definition q = TestModel.objects.only(['attempt_id', 'description']) self.assertEqual(q._select_fields(), ['attempt_id', 'description']) with self.assertRaises(query.QueryException): TestModel.objects.only(['nonexistent_field']) # Cannot define more than once only fields with self.assertRaises(query.QueryException): TestModel.objects.only(['description']).only(['attempt_id']) # only with defer fields q = TestModel.objects.only(['attempt_id', 'description']) q = q.defer(['description']) self.assertEqual(q._select_fields(), ['attempt_id']) # Eliminate all results confirm exception is thrown q = TestModel.objects.only(['description']) q = q.defer(['description']) with self.assertRaises(query.QueryException): q._select_fields() q = TestModel.objects.filter(test_id=0).only(['test_id', 'attempt_id', 'description']) self.assertEqual(q._select_fields(), ['attempt_id', 'description']) # no fields to select with self.assertRaises(query.QueryException): q = TestModel.objects.only(['test_id']).defer(['test_id']) q._select_fields() with self.assertRaises(query.QueryException): q = TestModel.objects.filter(test_id=0).only(['test_id']) q._select_fields() def test_defining_defer_fields(self): """ Tests defining defer fields @since 3.5 @jira_ticket PYTHON-560 @jira_ticket PYTHON-599 @expected_result deferred fields should not be returned @test_category object_mapper """ # simple defer definition q = TestModel.objects.defer(['attempt_id', 'description']) self.assertEqual(q._select_fields(), ['test_id', 'expected_result', 'test_result']) with self.assertRaises(query.QueryException): TestModel.objects.defer(['nonexistent_field']) # defer more than one q = TestModel.objects.defer(['attempt_id', 'description']) q = q.defer(['expected_result']) self.assertEqual(q._select_fields(), ['test_id', 'test_result']) # defer with only q = TestModel.objects.defer(['description', 'attempt_id']) q = q.only(['description', 'test_id']) self.assertEqual(q._select_fields(), ['test_id']) # Eliminate all results confirm exception is thrown q = TestModel.objects.defer(['description', 'attempt_id']) q = q.only(['description']) with self.assertRaises(query.QueryException): q._select_fields() # implicit defer q = TestModel.objects.filter(test_id=0) self.assertEqual(q._select_fields(), ['attempt_id', 'description', 'expected_result', 'test_result']) # when all fields are defered, it fallbacks select the partition keys q = TestModel.objects.defer(['test_id', 'attempt_id', 'description', 'expected_result', 'test_result']) self.assertEqual(q._select_fields(), ['test_id']) class BaseQuerySetUsage(BaseCassEngTestCase): @classmethod def setUpClass(cls): super(BaseQuerySetUsage, cls).setUpClass() drop_table(TestModel) drop_table(IndexedTestModel) drop_table(CustomIndexedTestModel) sync_table(TestModel) sync_table(IndexedTestModel) sync_table(CustomIndexedTestModel) sync_table(TestMultiClusteringModel) TestModel.objects.create(test_id=0, attempt_id=0, description='try1', expected_result=5, test_result=30) TestModel.objects.create(test_id=0, attempt_id=1, description='try2', expected_result=10, test_result=30) TestModel.objects.create(test_id=0, attempt_id=2, description='try3', expected_result=15, test_result=30) TestModel.objects.create(test_id=0, attempt_id=3, description='try4', expected_result=20, test_result=25) TestModel.objects.create(test_id=1, attempt_id=0, description='try5', expected_result=5, test_result=25) TestModel.objects.create(test_id=1, attempt_id=1, description='try6', expected_result=10, test_result=25) TestModel.objects.create(test_id=1, attempt_id=2, description='try7', expected_result=15, test_result=25) TestModel.objects.create(test_id=1, attempt_id=3, description='try8', expected_result=20, test_result=20) TestModel.objects.create(test_id=2, attempt_id=0, description='try9', expected_result=50, test_result=40) TestModel.objects.create(test_id=2, attempt_id=1, description='try10', expected_result=60, test_result=40) TestModel.objects.create(test_id=2, attempt_id=2, description='try11', expected_result=70, test_result=45) TestModel.objects.create(test_id=2, attempt_id=3, description='try12', expected_result=75, test_result=45) IndexedTestModel.objects.create(test_id=0, attempt_id=0, description='try1', expected_result=5, test_result=30) IndexedTestModel.objects.create(test_id=1, attempt_id=1, description='try2', expected_result=10, test_result=30) IndexedTestModel.objects.create(test_id=2, attempt_id=2, description='try3', expected_result=15, test_result=30) IndexedTestModel.objects.create(test_id=3, attempt_id=3, description='try4', expected_result=20, test_result=25) IndexedTestModel.objects.create(test_id=4, attempt_id=0, description='try5', expected_result=5, test_result=25) IndexedTestModel.objects.create(test_id=5, attempt_id=1, description='try6', expected_result=10, test_result=25) IndexedTestModel.objects.create(test_id=6, attempt_id=2, description='try7', expected_result=15, test_result=25) IndexedTestModel.objects.create(test_id=7, attempt_id=3, description='try8', expected_result=20, test_result=20) IndexedTestModel.objects.create(test_id=8, attempt_id=0, description='try9', expected_result=50, test_result=40) IndexedTestModel.objects.create(test_id=9, attempt_id=1, description='try10', expected_result=60, test_result=40) IndexedTestModel.objects.create(test_id=10, attempt_id=2, description='try11', expected_result=70, test_result=45) IndexedTestModel.objects.create(test_id=11, attempt_id=3, description='try12', expected_result=75, test_result=45) if CASSANDRA_VERSION >= Version('2.1'): drop_table(IndexedCollectionsTestModel) sync_table(IndexedCollectionsTestModel) IndexedCollectionsTestModel.objects.create(test_id=12, attempt_id=3, description='list12', expected_result=75, test_result=45, test_list=[1, 2, 42], test_set=set([1, 2, 3]), test_map={'1': 1, '2': 2, '3': 3}) IndexedCollectionsTestModel.objects.create(test_id=13, attempt_id=3, description='list13', expected_result=75, test_result=45, test_list=[3, 4, 5], test_set=set([4, 5, 42]), test_map={'1': 5, '2': 6, '3': 7}) IndexedCollectionsTestModel.objects.create(test_id=14, attempt_id=3, description='list14', expected_result=75, test_result=45, test_list=[1, 2, 3], test_set=set([1, 2, 3]), test_map={'1': 1, '2': 2, '3': 42}) IndexedCollectionsTestModel.objects.create(test_id=15, attempt_id=4, description='list14', expected_result=75, test_result=45, test_list_no_index=[1, 2, 3], test_set_no_index=set([1, 2, 3]), test_map_no_index={'1': 1, '2': 2, '3': 42}) @classmethod def tearDownClass(cls): super(BaseQuerySetUsage, cls).tearDownClass() drop_table(TestModel) drop_table(IndexedTestModel) drop_table(CustomIndexedTestModel) drop_table(TestMultiClusteringModel) class TestQuerySetCountSelectionAndIteration(BaseQuerySetUsage): @execute_count(2) def test_count(self): """ Tests that adding filtering statements affects the count query as expected """ assert TestModel.objects.count() == 12 q = TestModel.objects(test_id=0) assert q.count() == 4 @execute_count(2) def test_query_expression_count(self): """ Tests that adding query statements affects the count query as expected """ assert TestModel.objects.count() == 12 q = TestModel.objects(TestModel.test_id == 0) assert q.count() == 4 @execute_count(3) def test_iteration(self): """ Tests that iterating over a query set pulls back all of the expected results """ q = TestModel.objects(test_id=0) # tuple of expected attempt_id, expected_result values compare_set = set([(0, 5), (1, 10), (2, 15), (3, 20)]) for t in q: val = t.attempt_id, t.expected_result assert val in compare_set compare_set.remove(val) assert len(compare_set) == 0 # test with regular filtering q = TestModel.objects(attempt_id=3).allow_filtering() assert len(q) == 3 # tuple of expected test_id, expected_result values compare_set = set([(0, 20), (1, 20), (2, 75)]) for t in q: val = t.test_id, t.expected_result assert val in compare_set compare_set.remove(val) assert len(compare_set) == 0 # test with query method q = TestModel.objects(TestModel.attempt_id == 3).allow_filtering() assert len(q) == 3 # tuple of expected test_id, expected_result values compare_set = set([(0, 20), (1, 20), (2, 75)]) for t in q: val = t.test_id, t.expected_result assert val in compare_set compare_set.remove(val) assert len(compare_set) == 0 @execute_count(2) def test_multiple_iterations_work_properly(self): """ Tests that iterating over a query set more than once works """ # test with both the filtering method and the query method for q in (TestModel.objects(test_id=0), TestModel.objects(TestModel.test_id == 0)): # tuple of expected attempt_id, expected_result values compare_set = set([(0, 5), (1, 10), (2, 15), (3, 20)]) for t in q: val = t.attempt_id, t.expected_result assert val in compare_set compare_set.remove(val) assert len(compare_set) == 0 # try it again compare_set = set([(0, 5), (1, 10), (2, 15), (3, 20)]) for t in q: val = t.attempt_id, t.expected_result assert val in compare_set compare_set.remove(val) assert len(compare_set) == 0 @execute_count(2) def test_multiple_iterators_are_isolated(self): """ tests that the use of one iterator does not affect the behavior of another """ for q in (TestModel.objects(test_id=0), TestModel.objects(TestModel.test_id == 0)): q = q.order_by('attempt_id') expected_order = [0, 1, 2, 3] iter1 = iter(q) iter2 = iter(q) for attempt_id in expected_order: assert next(iter1).attempt_id == attempt_id assert next(iter2).attempt_id == attempt_id @execute_count(3) def test_get_success_case(self): """ Tests that the .get() method works on new and existing querysets """ m = TestModel.objects.get(test_id=0, attempt_id=0) assert isinstance(m, TestModel) assert m.test_id == 0 assert m.attempt_id == 0 q = TestModel.objects(test_id=0, attempt_id=0) m = q.get() assert isinstance(m, TestModel) assert m.test_id == 0 assert m.attempt_id == 0 q = TestModel.objects(test_id=0) m = q.get(attempt_id=0) assert isinstance(m, TestModel) assert m.test_id == 0 assert m.attempt_id == 0 @execute_count(3) def test_query_expression_get_success_case(self): """ Tests that the .get() method works on new and existing querysets """ m = TestModel.get(TestModel.test_id == 0, TestModel.attempt_id == 0) assert isinstance(m, TestModel) assert m.test_id == 0 assert m.attempt_id == 0 q = TestModel.objects(TestModel.test_id == 0, TestModel.attempt_id == 0) m = q.get() assert isinstance(m, TestModel) assert m.test_id == 0 assert m.attempt_id == 0 q = TestModel.objects(TestModel.test_id == 0) m = q.get(TestModel.attempt_id == 0) assert isinstance(m, TestModel) assert m.test_id == 0 assert m.attempt_id == 0 @execute_count(1) def test_get_doesnotexist_exception(self): """ Tests that get calls that don't return a result raises a DoesNotExist error """ with self.assertRaises(TestModel.DoesNotExist): TestModel.objects.get(test_id=100) @execute_count(1) def test_get_multipleobjects_exception(self): """ Tests that get calls that return multiple results raise a MultipleObjectsReturned error """ with self.assertRaises(TestModel.MultipleObjectsReturned): TestModel.objects.get(test_id=1) def test_allow_filtering_flag(self): """ """ @execute_count(4) def test_non_quality_filtering(): class NonEqualityFilteringModel(Model): example_id = columns.UUID(primary_key=True, default=uuid.uuid4) sequence_id = columns.Integer(primary_key=True) # sequence_id is a clustering key example_type = columns.Integer(index=True) created_at = columns.DateTime() drop_table(NonEqualityFilteringModel) sync_table(NonEqualityFilteringModel) # setup table, etc. NonEqualityFilteringModel.create(sequence_id=1, example_type=0, created_at=datetime.now()) NonEqualityFilteringModel.create(sequence_id=3, example_type=0, created_at=datetime.now()) NonEqualityFilteringModel.create(sequence_id=5, example_type=1, created_at=datetime.now()) qa = NonEqualityFilteringModel.objects(NonEqualityFilteringModel.sequence_id > 3).allow_filtering() num = qa.count() assert num == 1, num class TestQuerySetDistinct(BaseQuerySetUsage): @execute_count(1) def test_distinct_without_parameter(self): q = TestModel.objects.distinct() self.assertEqual(len(q), 3) @execute_count(1) def test_distinct_with_parameter(self): q = TestModel.objects.distinct(['test_id']) self.assertEqual(len(q), 3) @execute_count(1) def test_distinct_with_filter(self): q = TestModel.objects.distinct(['test_id']).filter(test_id__in=[1, 2]) self.assertEqual(len(q), 2) @execute_count(1) def test_distinct_with_non_partition(self): with self.assertRaises(InvalidRequest): q = TestModel.objects.distinct(['description']).filter(test_id__in=[1, 2]) len(q) @execute_count(1) def test_zero_result(self): q = TestModel.objects.distinct(['test_id']).filter(test_id__in=[52]) self.assertEqual(len(q), 0) @greaterthancass21 @execute_count(2) def test_distinct_with_explicit_count(self): q = TestModel.objects.distinct(['test_id']) self.assertEqual(q.count(), 3) q = TestModel.objects.distinct(['test_id']).filter(test_id__in=[1, 2]) self.assertEqual(q.count(), 2) class TestQuerySetOrdering(BaseQuerySetUsage): @execute_count(2) def test_order_by_success_case(self): q = TestModel.objects(test_id=0).order_by('attempt_id') expected_order = [0, 1, 2, 3] for model, expect in zip(q, expected_order): assert model.attempt_id == expect q = q.order_by('-attempt_id') expected_order.reverse() for model, expect in zip(q, expected_order): assert model.attempt_id == expect def test_ordering_by_non_second_primary_keys_fail(self): # kwarg filtering with self.assertRaises(query.QueryException): TestModel.objects(test_id=0).order_by('test_id') # kwarg filtering with self.assertRaises(query.QueryException): TestModel.objects(TestModel.test_id == 0).order_by('test_id') def test_ordering_by_non_primary_keys_fails(self): with self.assertRaises(query.QueryException): TestModel.objects(test_id=0).order_by('description') def test_ordering_on_indexed_columns_fails(self): with self.assertRaises(query.QueryException): IndexedTestModel.objects(test_id=0).order_by('attempt_id') @execute_count(8) def test_ordering_on_multiple_clustering_columns(self): TestMultiClusteringModel.create(one=1, two=1, three=4) TestMultiClusteringModel.create(one=1, two=1, three=2) TestMultiClusteringModel.create(one=1, two=1, three=5) TestMultiClusteringModel.create(one=1, two=1, three=1) TestMultiClusteringModel.create(one=1, two=1, three=3) results = TestMultiClusteringModel.objects.filter(one=1, two=1).order_by('-two', '-three') assert [r.three for r in results] == [5, 4, 3, 2, 1] results = TestMultiClusteringModel.objects.filter(one=1, two=1).order_by('two', 'three') assert [r.three for r in results] == [1, 2, 3, 4, 5] results = TestMultiClusteringModel.objects.filter(one=1, two=1).order_by('two').order_by('three') assert [r.three for r in results] == [1, 2, 3, 4, 5] class TestQuerySetSlicing(BaseQuerySetUsage): @execute_count(1) def test_out_of_range_index_raises_error(self): q = TestModel.objects(test_id=0).order_by('attempt_id') with self.assertRaises(IndexError): q[10] @execute_count(1) def test_array_indexing_works_properly(self): q = TestModel.objects(test_id=0).order_by('attempt_id') expected_order = [0, 1, 2, 3] for i in range(len(q)): assert q[i].attempt_id == expected_order[i] @execute_count(1) def test_negative_indexing_works_properly(self): q = TestModel.objects(test_id=0).order_by('attempt_id') expected_order = [0, 1, 2, 3] assert q[-1].attempt_id == expected_order[-1] assert q[-2].attempt_id == expected_order[-2] @execute_count(1) def test_slicing_works_properly(self): q = TestModel.objects(test_id=0).order_by('attempt_id') expected_order = [0, 1, 2, 3] for model, expect in zip(q[1:3], expected_order[1:3]): self.assertEqual(model.attempt_id, expect) for model, expect in zip(q[0:3:2], expected_order[0:3:2]): self.assertEqual(model.attempt_id, expect) @execute_count(1) def test_negative_slicing(self): q = TestModel.objects(test_id=0).order_by('attempt_id') expected_order = [0, 1, 2, 3] for model, expect in zip(q[-3:], expected_order[-3:]): self.assertEqual(model.attempt_id, expect) for model, expect in zip(q[:-1], expected_order[:-1]): self.assertEqual(model.attempt_id, expect) for model, expect in zip(q[1:-1], expected_order[1:-1]): self.assertEqual(model.attempt_id, expect) for model, expect in zip(q[-3:-1], expected_order[-3:-1]): self.assertEqual(model.attempt_id, expect) for model, expect in zip(q[-3:-1:2], expected_order[-3:-1:2]): self.assertEqual(model.attempt_id, expect) class TestQuerySetValidation(BaseQuerySetUsage): def test_primary_key_or_index_must_be_specified(self): """ Tests that queries that don't have an equals relation to a primary key or indexed field fail """ with self.assertRaises(query.QueryException): q = TestModel.objects(test_result=25) list([i for i in q]) def test_primary_key_or_index_must_have_equal_relation_filter(self): """ Tests that queries that don't have non equal (>,<, etc) relation to a primary key or indexed field fail """ with self.assertRaises(query.QueryException): q = TestModel.objects(test_id__gt=0) list([i for i in q]) @greaterthancass20 @execute_count(7) def test_indexed_field_can_be_queried(self): """ Tests that queries on an indexed field will work without any primary key relations specified """ q = IndexedTestModel.objects(test_result=25) self.assertEqual(q.count(), 4) q = IndexedCollectionsTestModel.objects.filter(test_list__contains=42) self.assertEqual(q.count(), 1) q = IndexedCollectionsTestModel.objects.filter(test_list__contains=13) self.assertEqual(q.count(), 0) q = IndexedCollectionsTestModel.objects.filter(test_set__contains=42) self.assertEqual(q.count(), 1) q = IndexedCollectionsTestModel.objects.filter(test_set__contains=13) self.assertEqual(q.count(), 0) q = IndexedCollectionsTestModel.objects.filter(test_map__contains=42) self.assertEqual(q.count(), 1) q = IndexedCollectionsTestModel.objects.filter(test_map__contains=13) self.assertEqual(q.count(), 0) def test_custom_indexed_field_can_be_queried(self): """ Tests that queries on an custom indexed field will work without any primary key relations specified """ with self.assertRaises(query.QueryException): list(CustomIndexedTestModel.objects.filter(data='test')) # not custom indexed # It should return InvalidRequest if target an indexed columns with self.assertRaises(InvalidRequest): list(CustomIndexedTestModel.objects.filter(indexed='test', data='test')) # It should return InvalidRequest if target an indexed columns with self.assertRaises(InvalidRequest): list(CustomIndexedTestModel.objects.filter(description='test', data='test')) # equals operator, server error since there is no real index, but it passes with self.assertRaises(InvalidRequest): list(CustomIndexedTestModel.objects.filter(description='test')) with self.assertRaises(InvalidRequest): list(CustomIndexedTestModel.objects.filter(test_id=1, description='test')) # gte operator, server error since there is no real index, but it passes # this can't work with a secondary index with self.assertRaises(InvalidRequest): list(CustomIndexedTestModel.objects.filter(description__gte='test')) - with Cluster().connect() as session: + with TestCluster().connect() as session: session.execute("CREATE INDEX custom_index_cqlengine ON {}.{} (description)". format(DEFAULT_KEYSPACE, CustomIndexedTestModel._table_name)) list(CustomIndexedTestModel.objects.filter(description='test')) list(CustomIndexedTestModel.objects.filter(test_id=1, description='test')) class TestQuerySetDelete(BaseQuerySetUsage): @execute_count(9) def test_delete(self): TestModel.objects.create(test_id=3, attempt_id=0, description='try9', expected_result=50, test_result=40) TestModel.objects.create(test_id=3, attempt_id=1, description='try10', expected_result=60, test_result=40) TestModel.objects.create(test_id=3, attempt_id=2, description='try11', expected_result=70, test_result=45) TestModel.objects.create(test_id=3, attempt_id=3, description='try12', expected_result=75, test_result=45) assert TestModel.objects.count() == 16 assert TestModel.objects(test_id=3).count() == 4 TestModel.objects(test_id=3).delete() assert TestModel.objects.count() == 12 assert TestModel.objects(test_id=3).count() == 0 def test_delete_without_partition_key(self): """ Tests that attempting to delete a model without defining a partition key fails """ with self.assertRaises(query.QueryException): TestModel.objects(attempt_id=0).delete() def test_delete_without_any_where_args(self): """ Tests that attempting to delete a whole table without any arguments will fail """ with self.assertRaises(query.QueryException): TestModel.objects(attempt_id=0).delete() @greaterthanorequalcass30 @execute_count(18) def test_range_deletion(self): """ Tests that range deletion work as expected """ for i in range(10): TestMultiClusteringModel.objects().create(one=1, two=i, three=i) TestMultiClusteringModel.objects(one=1, two__gte=0, two__lte=3).delete() self.assertEqual(6, len(TestMultiClusteringModel.objects.all())) TestMultiClusteringModel.objects(one=1, two__gt=3, two__lt=5).delete() self.assertEqual(5, len(TestMultiClusteringModel.objects.all())) TestMultiClusteringModel.objects(one=1, two__in=[8, 9]).delete() self.assertEqual(3, len(TestMultiClusteringModel.objects.all())) TestMultiClusteringModel.objects(one__in=[1], two__gte=0).delete() self.assertEqual(0, len(TestMultiClusteringModel.objects.all())) class TimeUUIDQueryModel(Model): partition = columns.UUID(primary_key=True) time = columns.TimeUUID(primary_key=True) data = columns.Text(required=False) class TestMinMaxTimeUUIDFunctions(BaseCassEngTestCase): @classmethod def setUpClass(cls): super(TestMinMaxTimeUUIDFunctions, cls).setUpClass() sync_table(TimeUUIDQueryModel) @classmethod def tearDownClass(cls): super(TestMinMaxTimeUUIDFunctions, cls).tearDownClass() drop_table(TimeUUIDQueryModel) @execute_count(7) def test_tzaware_datetime_support(self): """Test that using timezone aware datetime instances works with the MinTimeUUID/MaxTimeUUID functions. """ pk = uuid4() midpoint_utc = datetime.utcnow().replace(tzinfo=TzOffset(0)) midpoint_helsinki = midpoint_utc.astimezone(TzOffset(3)) # Assert pre-condition that we have the same logical point in time assert midpoint_utc.utctimetuple() == midpoint_helsinki.utctimetuple() assert midpoint_utc.timetuple() != midpoint_helsinki.timetuple() TimeUUIDQueryModel.create( partition=pk, time=uuid_from_time(midpoint_utc - timedelta(minutes=1)), data='1') TimeUUIDQueryModel.create( partition=pk, time=uuid_from_time(midpoint_utc), data='2') TimeUUIDQueryModel.create( partition=pk, time=uuid_from_time(midpoint_utc + timedelta(minutes=1)), data='3') assert ['1', '2'] == [o.data for o in TimeUUIDQueryModel.filter( TimeUUIDQueryModel.partition == pk, TimeUUIDQueryModel.time <= functions.MaxTimeUUID(midpoint_utc))] assert ['1', '2'] == [o.data for o in TimeUUIDQueryModel.filter( TimeUUIDQueryModel.partition == pk, TimeUUIDQueryModel.time <= functions.MaxTimeUUID(midpoint_helsinki))] assert ['2', '3'] == [o.data for o in TimeUUIDQueryModel.filter( TimeUUIDQueryModel.partition == pk, TimeUUIDQueryModel.time >= functions.MinTimeUUID(midpoint_utc))] assert ['2', '3'] == [o.data for o in TimeUUIDQueryModel.filter( TimeUUIDQueryModel.partition == pk, TimeUUIDQueryModel.time >= functions.MinTimeUUID(midpoint_helsinki))] @execute_count(8) def test_success_case(self): """ Test that the min and max time uuid functions work as expected """ pk = uuid4() startpoint = datetime.utcnow() TimeUUIDQueryModel.create(partition=pk, time=uuid_from_time(startpoint + timedelta(seconds=1)), data='1') TimeUUIDQueryModel.create(partition=pk, time=uuid_from_time(startpoint + timedelta(seconds=2)), data='2') midpoint = startpoint + timedelta(seconds=3) TimeUUIDQueryModel.create(partition=pk, time=uuid_from_time(startpoint + timedelta(seconds=4)), data='3') TimeUUIDQueryModel.create(partition=pk, time=uuid_from_time(startpoint + timedelta(seconds=5)), data='4') # test kwarg filtering q = TimeUUIDQueryModel.filter(partition=pk, time__lte=functions.MaxTimeUUID(midpoint)) q = [d for d in q] self.assertEqual(len(q), 2, msg="Got: %s" % q) datas = [d.data for d in q] assert '1' in datas assert '2' in datas q = TimeUUIDQueryModel.filter(partition=pk, time__gte=functions.MinTimeUUID(midpoint)) assert len(q) == 2 datas = [d.data for d in q] assert '3' in datas assert '4' in datas # test query expression filtering q = TimeUUIDQueryModel.filter( TimeUUIDQueryModel.partition == pk, TimeUUIDQueryModel.time <= functions.MaxTimeUUID(midpoint) ) q = [d for d in q] assert len(q) == 2 datas = [d.data for d in q] assert '1' in datas assert '2' in datas q = TimeUUIDQueryModel.filter( TimeUUIDQueryModel.partition == pk, TimeUUIDQueryModel.time >= functions.MinTimeUUID(midpoint) ) assert len(q) == 2 datas = [d.data for d in q] assert '3' in datas assert '4' in datas class TestInOperator(BaseQuerySetUsage): @execute_count(1) def test_kwarg_success_case(self): """ Tests the in operator works with the kwarg query method """ q = TestModel.filter(test_id__in=[0, 1]) assert q.count() == 8 @execute_count(1) def test_query_expression_success_case(self): """ Tests the in operator works with the query expression query method """ q = TestModel.filter(TestModel.test_id.in_([0, 1])) assert q.count() == 8 @execute_count(5) def test_bool(self): """ Adding coverage to cqlengine for bool types. @since 3.6 @jira_ticket PYTHON-596 @expected_result bool results should be filtered appropriately @test_category object_mapper """ class bool_model(Model): k = columns.Integer(primary_key=True) b = columns.Boolean(primary_key=True) v = columns.Integer(default=3) sync_table(bool_model) bool_model.create(k=0, b=True) bool_model.create(k=0, b=False) self.assertEqual(len(bool_model.objects.all()), 2) self.assertEqual(len(bool_model.objects.filter(k=0, b=True)), 1) self.assertEqual(len(bool_model.objects.filter(k=0, b=False)), 1) @execute_count(3) def test_bool_filter(self): """ Test to ensure that we don't translate boolean objects to String unnecessarily in filter clauses @since 3.6 @jira_ticket PYTHON-596 @expected_result We should not receive a server error @test_category object_mapper """ class bool_model2(Model): k = columns.Boolean(primary_key=True) b = columns.Integer(primary_key=True) v = columns.Text() drop_table(bool_model2) sync_table(bool_model2) bool_model2.create(k=True, b=1, v='a') bool_model2.create(k=False, b=1, v='b') self.assertEqual(len(list(bool_model2.objects(k__in=(True, False)))), 2) @greaterthancass20 class TestContainsOperator(BaseQuerySetUsage): @execute_count(6) def test_kwarg_success_case(self): """ Tests the CONTAINS operator works with the kwarg query method """ q = IndexedCollectionsTestModel.filter(test_list__contains=1) self.assertEqual(q.count(), 2) q = IndexedCollectionsTestModel.filter(test_list__contains=13) self.assertEqual(q.count(), 0) q = IndexedCollectionsTestModel.filter(test_set__contains=3) self.assertEqual(q.count(), 2) q = IndexedCollectionsTestModel.filter(test_set__contains=13) self.assertEqual(q.count(), 0) q = IndexedCollectionsTestModel.filter(test_map__contains=42) self.assertEqual(q.count(), 1) q = IndexedCollectionsTestModel.filter(test_map__contains=13) self.assertEqual(q.count(), 0) with self.assertRaises(QueryException): q = IndexedCollectionsTestModel.filter(test_list_no_index__contains=1) self.assertEqual(q.count(), 0) with self.assertRaises(QueryException): q = IndexedCollectionsTestModel.filter(test_set_no_index__contains=1) self.assertEqual(q.count(), 0) with self.assertRaises(QueryException): q = IndexedCollectionsTestModel.filter(test_map_no_index__contains=1) self.assertEqual(q.count(), 0) @execute_count(6) def test_query_expression_success_case(self): """ Tests the CONTAINS operator works with the query expression query method """ q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_list.contains_(1)) self.assertEqual(q.count(), 2) q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_list.contains_(13)) self.assertEqual(q.count(), 0) q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_set.contains_(3)) self.assertEqual(q.count(), 2) q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_set.contains_(13)) self.assertEqual(q.count(), 0) q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_map.contains_(42)) self.assertEqual(q.count(), 1) q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_map.contains_(13)) self.assertEqual(q.count(), 0) with self.assertRaises(QueryException): q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_map_no_index.contains_(1)) self.assertEqual(q.count(), 0) with self.assertRaises(QueryException): q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_map_no_index.contains_(1)) self.assertEqual(q.count(), 0) with self.assertRaises(QueryException): q = IndexedCollectionsTestModel.filter(IndexedCollectionsTestModel.test_map_no_index.contains_(1)) self.assertEqual(q.count(), 0) class TestValuesList(BaseQuerySetUsage): @execute_count(2) def test_values_list(self): q = TestModel.objects.filter(test_id=0, attempt_id=1) item = q.values_list('test_id', 'attempt_id', 'description', 'expected_result', 'test_result').first() assert item == [0, 1, 'try2', 10, 30] item = q.values_list('expected_result', flat=True).first() assert item == 10 class TestObjectsProperty(BaseQuerySetUsage): @execute_count(1) def test_objects_property_returns_fresh_queryset(self): assert TestModel.objects._result_cache is None len(TestModel.objects) # evaluate queryset assert TestModel.objects._result_cache is None class PageQueryTests(BaseCassEngTestCase): @execute_count(3) def test_paged_result_handling(self): if PROTOCOL_VERSION < 2: raise unittest.SkipTest("Paging requires native protocol 2+, currently using: {0}".format(PROTOCOL_VERSION)) # addresses #225 class PagingTest(Model): id = columns.Integer(primary_key=True) val = columns.Integer() sync_table(PagingTest) PagingTest.create(id=1, val=1) PagingTest.create(id=2, val=2) session = get_session() with mock.patch.object(session, 'default_fetch_size', 1): results = PagingTest.objects()[:] assert len(results) == 2 class ModelQuerySetTimeoutTestCase(BaseQuerySetUsage): def test_default_timeout(self): with mock.patch.object(Session, 'execute') as mock_execute: list(TestModel.objects()) self.assertEqual(mock_execute.call_args[-1]['timeout'], NOT_SET) def test_float_timeout(self): with mock.patch.object(Session, 'execute') as mock_execute: list(TestModel.objects().timeout(0.5)) self.assertEqual(mock_execute.call_args[-1]['timeout'], 0.5) def test_none_timeout(self): with mock.patch.object(Session, 'execute') as mock_execute: list(TestModel.objects().timeout(None)) self.assertEqual(mock_execute.call_args[-1]['timeout'], None) class DMLQueryTimeoutTestCase(BaseQuerySetUsage): def setUp(self): self.model = TestModel(test_id=1, attempt_id=1, description='timeout test') super(DMLQueryTimeoutTestCase, self).setUp() def test_default_timeout(self): with mock.patch.object(Session, 'execute') as mock_execute: self.model.save() self.assertEqual(mock_execute.call_args[-1]['timeout'], NOT_SET) def test_float_timeout(self): with mock.patch.object(Session, 'execute') as mock_execute: self.model.timeout(0.5).save() self.assertEqual(mock_execute.call_args[-1]['timeout'], 0.5) def test_none_timeout(self): with mock.patch.object(Session, 'execute') as mock_execute: self.model.timeout(None).save() self.assertEqual(mock_execute.call_args[-1]['timeout'], None) def test_timeout_then_batch(self): b = query.BatchQuery() m = self.model.timeout(None) with self.assertRaises(AssertionError): m.batch(b) def test_batch_then_timeout(self): b = query.BatchQuery() m = self.model.batch(b) with self.assertRaises(AssertionError): m.timeout(0.5) class DBFieldModel(Model): k0 = columns.Integer(partition_key=True, db_field='a') k1 = columns.Integer(partition_key=True, db_field='b') c0 = columns.Integer(primary_key=True, db_field='c') v0 = columns.Integer(db_field='d') v1 = columns.Integer(db_field='e', index=True) class DBFieldModelMixed1(Model): k0 = columns.Integer(partition_key=True, db_field='a') k1 = columns.Integer(partition_key=True) c0 = columns.Integer(primary_key=True, db_field='c') v0 = columns.Integer(db_field='d') v1 = columns.Integer(index=True) class DBFieldModelMixed2(Model): k0 = columns.Integer(partition_key=True) k1 = columns.Integer(partition_key=True, db_field='b') c0 = columns.Integer(primary_key=True) v0 = columns.Integer(db_field='d') v1 = columns.Integer(index=True, db_field='e') class TestModelQueryWithDBField(BaseCassEngTestCase): def setUp(cls): super(TestModelQueryWithDBField, cls).setUpClass() cls.model_list = [DBFieldModel, DBFieldModelMixed1, DBFieldModelMixed2] for model in cls.model_list: sync_table(model) def tearDown(cls): super(TestModelQueryWithDBField, cls).tearDownClass() for model in cls.model_list: drop_table(model) @execute_count(33) def test_basic_crud(self): """ Tests creation update and delete of object model queries that are using db_field mappings. @since 3.1 @jira_ticket PYTHON-351 @expected_result results are properly retrieved without errors @test_category object_mapper """ for model in self.model_list: values = {'k0': 1, 'k1': 2, 'c0': 3, 'v0': 4, 'v1': 5} # create i = model.create(**values) i = model.objects(k0=i.k0, k1=i.k1).first() self.assertEqual(i, model(**values)) # create values['v0'] = 101 i.update(v0=values['v0']) i = model.objects(k0=i.k0, k1=i.k1).first() self.assertEqual(i, model(**values)) # delete model.objects(k0=i.k0, k1=i.k1).delete() i = model.objects(k0=i.k0, k1=i.k1).first() self.assertIsNone(i) i = model.create(**values) i = model.objects(k0=i.k0, k1=i.k1).first() self.assertEqual(i, model(**values)) i.delete() model.objects(k0=i.k0, k1=i.k1).delete() i = model.objects(k0=i.k0, k1=i.k1).first() self.assertIsNone(i) @execute_count(21) def test_slice(self): """ Tests slice queries for object models that are using db_field mapping @since 3.1 @jira_ticket PYTHON-351 @expected_result results are properly retrieved without errors @test_category object_mapper """ for model in self.model_list: values = {'k0': 1, 'k1': 3, 'c0': 3, 'v0': 4, 'v1': 5} clustering_values = range(3) for c in clustering_values: values['c0'] = c i = model.create(**values) self.assertEqual(model.objects(k0=i.k0, k1=i.k1).count(), len(clustering_values)) self.assertEqual(model.objects(k0=i.k0, k1=i.k1, c0=i.c0).count(), 1) self.assertEqual(model.objects(k0=i.k0, k1=i.k1, c0__lt=i.c0).count(), len(clustering_values[:-1])) self.assertEqual(model.objects(k0=i.k0, k1=i.k1, c0__gt=0).count(), len(clustering_values[1:])) @execute_count(15) def test_order(self): """ Tests order by queries for object models that are using db_field mapping @since 3.1 @jira_ticket PYTHON-351 @expected_result results are properly retrieved without errors @test_category object_mapper """ for model in self.model_list: values = {'k0': 1, 'k1': 4, 'c0': 3, 'v0': 4, 'v1': 5} clustering_values = range(3) for c in clustering_values: values['c0'] = c i = model.create(**values) self.assertEqual(model.objects(k0=i.k0, k1=i.k1).order_by('c0').first().c0, clustering_values[0]) self.assertEqual(model.objects(k0=i.k0, k1=i.k1).order_by('-c0').first().c0, clustering_values[-1]) @execute_count(15) def test_index(self): """ Tests queries using index fields for object models using db_field mapping @since 3.1 @jira_ticket PYTHON-351 @expected_result results are properly retrieved without errors @test_category object_mapper """ for model in self.model_list: values = {'k0': 1, 'k1': 5, 'c0': 3, 'v0': 4, 'v1': 5} clustering_values = range(3) for c in clustering_values: values['c0'] = c values['v1'] = c i = model.create(**values) self.assertEqual(model.objects(k0=i.k0, k1=i.k1).count(), len(clustering_values)) self.assertEqual(model.objects(k0=i.k0, k1=i.k1, v1=0).count(), 1) @execute_count(1) def test_db_field_names_used(self): """ Tests to ensure that with generated cql update statements correctly utilize the db_field values. @since 3.2 @jira_ticket PYTHON-530 @expected_result resulting cql_statements will use the db_field values @test_category object_mapper """ values = ('k0', 'k1', 'c0', 'v0', 'v1') # Test QuerySet Path b = BatchQuery() DBFieldModel.objects(k0=1).batch(b).update( v0=0, v1=9, ) for value in values: self.assertTrue(value not in str(b.queries[0])) # Test DML path b2 = BatchQuery() dml_field_model = DBFieldModel.create(k0=1, k1=5, c0=3, v0=4, v1=5) dml_field_model.batch(b2).update( v0=0, v1=9, ) for value in values: self.assertTrue(value not in str(b2.queries[0])) def test_db_field_value_list(self): DBFieldModel.create(k0=0, k1=0, c0=0, v0=4, v1=5) self.assertEqual(DBFieldModel.objects.filter(c0=0, k0=0, k1=0).values_list('c0', 'v0')._defer_fields, {'a', 'c', 'b'}) self.assertEqual(DBFieldModel.objects.filter(c0=0, k0=0, k1=0).values_list('c0', 'v0')._only_fields, ['c', 'd']) list(DBFieldModel.objects.filter(c0=0, k0=0, k1=0).values_list('c0', 'v0')) class TestModelSmall(Model): test_id = columns.Integer(primary_key=True) class TestModelQueryWithFetchSize(BaseCassEngTestCase): """ Test FetchSize, and ensure that results are returned correctly regardless of the paging size @since 3.1 @jira_ticket PYTHON-324 @expected_result results are properly retrieved and the correct size @test_category object_mapper """ @classmethod def setUpClass(cls): super(TestModelQueryWithFetchSize, cls).setUpClass() sync_table(TestModelSmall) @classmethod def tearDownClass(cls): super(TestModelQueryWithFetchSize, cls).tearDownClass() drop_table(TestModelSmall) @execute_count(9) def test_defaultFetchSize(self): with BatchQuery() as b: for i in range(5100): TestModelSmall.batch(b).create(test_id=i) self.assertEqual(len(TestModelSmall.objects.fetch_size(1)), 5100) self.assertEqual(len(TestModelSmall.objects.fetch_size(500)), 5100) self.assertEqual(len(TestModelSmall.objects.fetch_size(4999)), 5100) self.assertEqual(len(TestModelSmall.objects.fetch_size(5000)), 5100) self.assertEqual(len(TestModelSmall.objects.fetch_size(5001)), 5100) self.assertEqual(len(TestModelSmall.objects.fetch_size(5100)), 5100) self.assertEqual(len(TestModelSmall.objects.fetch_size(5101)), 5100) self.assertEqual(len(TestModelSmall.objects.fetch_size(1)), 5100) with self.assertRaises(QueryException): TestModelSmall.objects.fetch_size(0) with self.assertRaises(QueryException): TestModelSmall.objects.fetch_size(-1) class People(Model): __table_name__ = "people" last_name = columns.Text(primary_key=True, partition_key=True) first_name = columns.Text(primary_key=True) birthday = columns.DateTime() class People2(Model): __table_name__ = "people" last_name = columns.Text(primary_key=True, partition_key=True) first_name = columns.Text(primary_key=True) middle_name = columns.Text() birthday = columns.DateTime() class TestModelQueryWithDifferedFeld(BaseCassEngTestCase): """ Tests that selects with filter will deffer population of known values until after the results are returned. I.E. Instead of generating SELECT * FROM People WHERE last_name="Smith" It will generate SELECT first_name, birthday FROM People WHERE last_name="Smith" Where last_name 'smith' will populated post query @since 3.2 @jira_ticket PYTHON-520 @expected_result only needed fields are included in the query @test_category object_mapper """ @classmethod def setUpClass(cls): super(TestModelQueryWithDifferedFeld, cls).setUpClass() sync_table(People) @classmethod def tearDownClass(cls): super(TestModelQueryWithDifferedFeld, cls).tearDownClass() drop_table(People) @execute_count(8) def test_defaultFetchSize(self): # Populate Table People.objects.create(last_name="Smith", first_name="John", birthday=datetime.now()) People.objects.create(last_name="Bestwater", first_name="Alan", birthday=datetime.now()) People.objects.create(last_name="Smith", first_name="Greg", birthday=datetime.now()) People.objects.create(last_name="Smith", first_name="Adam", birthday=datetime.now()) # Check query constructions expected_fields = ['first_name', 'birthday'] self.assertEqual(People.filter(last_name="Smith")._select_fields(), expected_fields) # Validate correct fields are fetched smiths = list(People.filter(last_name="Smith")) self.assertEqual(len(smiths), 3) self.assertTrue(smiths[0].last_name is not None) # Modify table with new value sync_table(People2) # populate new format People2.objects.create(last_name="Smith", first_name="Chris", middle_name="Raymond", birthday=datetime.now()) People2.objects.create(last_name="Smith", first_name="Andrew", middle_name="Micheal", birthday=datetime.now()) # validate query construction expected_fields = ['first_name', 'middle_name', 'birthday'] self.assertEqual(People2.filter(last_name="Smith")._select_fields(), expected_fields) # validate correct items are returneds smiths = list(People2.filter(last_name="Smith")) self.assertEqual(len(smiths), 5) self.assertTrue(smiths[0].last_name is not None) diff --git a/tests/integration/cqlengine/statements/test_base_statement.py b/tests/integration/cqlengine/statements/test_base_statement.py index db7d1eb..474c45d 100644 --- a/tests/integration/cqlengine/statements/test_base_statement.py +++ b/tests/integration/cqlengine/statements/test_base_statement.py @@ -1,159 +1,158 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from uuid import uuid4 import six from cassandra.query import FETCH_SIZE_UNSET -from cassandra.cluster import Cluster, ConsistencyLevel from cassandra.cqlengine.statements import BaseCQLStatement from cassandra.cqlengine.management import sync_table, drop_table from cassandra.cqlengine.statements import InsertStatement, UpdateStatement, SelectStatement, DeleteStatement, \ WhereClause from cassandra.cqlengine.operators import EqualsOperator, LikeOperator from cassandra.cqlengine.columns import Column from tests.integration.cqlengine.base import BaseCassEngTestCase, TestQueryUpdateModel from tests.integration.cqlengine import DEFAULT_KEYSPACE -from tests.integration import greaterthanorequalcass3_10 +from tests.integration import greaterthanorequalcass3_10, TestCluster from cassandra.cqlengine.connection import execute class BaseStatementTest(unittest.TestCase): def test_fetch_size(self): """ tests that fetch_size is correctly set """ stmt = BaseCQLStatement('table', None, fetch_size=1000) self.assertEqual(stmt.fetch_size, 1000) stmt = BaseCQLStatement('table', None, fetch_size=None) self.assertEqual(stmt.fetch_size, FETCH_SIZE_UNSET) stmt = BaseCQLStatement('table', None) self.assertEqual(stmt.fetch_size, FETCH_SIZE_UNSET) class ExecuteStatementTest(BaseCassEngTestCase): text = "text_for_db" @classmethod def setUpClass(cls): super(ExecuteStatementTest, cls).setUpClass() sync_table(TestQueryUpdateModel) cls.table_name = '{0}.test_query_update_model'.format(DEFAULT_KEYSPACE) @classmethod def tearDownClass(cls): super(ExecuteStatementTest, cls).tearDownClass() drop_table(TestQueryUpdateModel) def _verify_statement(self, original): st = SelectStatement(self.table_name) result = execute(st) response = result[0] for assignment in original.assignments: self.assertEqual(response[assignment.field], assignment.value) self.assertEqual(len(response), 7) def test_insert_statement_execute(self): """ Test to verify the execution of BaseCQLStatements using connection.execute @since 3.10 @jira_ticket PYTHON-505 @expected_result inserts a row in C*, updates the rows and then deletes all the rows using BaseCQLStatements @test_category data_types:object_mapper """ partition = uuid4() cluster = 1 self._insert_statement(partition, cluster) # Verifying update statement where = [WhereClause('partition', EqualsOperator(), partition), WhereClause('cluster', EqualsOperator(), cluster)] st = UpdateStatement(self.table_name, where=where) st.add_assignment(Column(db_field='count'), 2) st.add_assignment(Column(db_field='text'), "text_for_db_update") st.add_assignment(Column(db_field='text_set'), set(("foo_update", "bar_update"))) st.add_assignment(Column(db_field='text_list'), ["foo_update", "bar_update"]) st.add_assignment(Column(db_field='text_map'), {"foo": '3', "bar": '4'}) execute(st) self._verify_statement(st) # Verifying delete statement execute(DeleteStatement(self.table_name, where=where)) self.assertEqual(TestQueryUpdateModel.objects.count(), 0) @greaterthanorequalcass3_10 def test_like_operator(self): """ Test to verify the like operator works appropriately @since 3.13 @jira_ticket PYTHON-512 @expected_result the expected row is read using LIKE @test_category data_types:object_mapper """ - cluster = Cluster() + cluster = TestCluster() session = cluster.connect() self.addCleanup(cluster.shutdown) session.execute("""CREATE CUSTOM INDEX text_index ON {} (text) USING 'org.apache.cassandra.index.sasi.SASIIndex';""".format(self.table_name)) self.addCleanup(session.execute, "DROP INDEX {}.text_index".format(DEFAULT_KEYSPACE)) partition = uuid4() cluster = 1 self._insert_statement(partition, cluster) ss = SelectStatement(self.table_name) like_clause = "text_for_%" ss.add_where(Column(db_field='text'), LikeOperator(), like_clause) self.assertEqual(six.text_type(ss), 'SELECT * FROM {} WHERE "text" LIKE %(0)s'.format(self.table_name)) result = execute(ss) self.assertEqual(result[0]["text"], self.text) q = TestQueryUpdateModel.objects.filter(text__like=like_clause).allow_filtering() self.assertEqual(q[0].text, self.text) q = TestQueryUpdateModel.objects.filter(text__like=like_clause) self.assertEqual(q[0].text, self.text) def _insert_statement(self, partition, cluster): # Verifying insert statement st = InsertStatement(self.table_name) st.add_assignment(Column(db_field='partition'), partition) st.add_assignment(Column(db_field='cluster'), cluster) st.add_assignment(Column(db_field='count'), 1) st.add_assignment(Column(db_field='text'), self.text) st.add_assignment(Column(db_field='text_set'), set(("foo", "bar"))) st.add_assignment(Column(db_field='text_list'), ["foo", "bar"]) st.add_assignment(Column(db_field='text_map'), {"foo": '1', "bar": '2'}) execute(st) self._verify_statement(st) diff --git a/tests/integration/cqlengine/test_connections.py b/tests/integration/cqlengine/test_connections.py index 10dee66..15adff3 100644 --- a/tests/integration/cqlengine/test_connections.py +++ b/tests/integration/cqlengine/test_connections.py @@ -1,671 +1,670 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from cassandra import InvalidRequest -from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.cqlengine import columns, CQLEngineException from cassandra.cqlengine import connection as conn from cassandra.cqlengine.management import drop_keyspace, sync_table, drop_table, create_keyspace_simple from cassandra.cqlengine.models import Model, QuerySetDescriptor from cassandra.cqlengine.query import ContextQuery, BatchQuery, ModelQuerySet from tests.integration.cqlengine import setup_connection, DEFAULT_KEYSPACE from tests.integration.cqlengine.base import BaseCassEngTestCase from tests.integration.cqlengine.query import test_queryset -from tests.integration import local, CASSANDRA_IP +from tests.integration import local, CASSANDRA_IP, TestCluster class TestModel(Model): __keyspace__ = 'ks1' partition = columns.Integer(primary_key=True) cluster = columns.Integer(primary_key=True) count = columns.Integer() text = columns.Text() class AnotherTestModel(Model): __keyspace__ = 'ks1' partition = columns.Integer(primary_key=True) cluster = columns.Integer(primary_key=True) count = columns.Integer() text = columns.Text() class ContextQueryConnectionTests(BaseCassEngTestCase): @classmethod def setUpClass(cls): super(ContextQueryConnectionTests, cls).setUpClass() create_keyspace_simple('ks1', 1) conn.unregister_connection('default') conn.register_connection('fake_cluster', ['1.2.3.4'], lazy_connect=True, retry_connect=True, default=True) conn.register_connection('cluster', [CASSANDRA_IP]) with ContextQuery(TestModel, connection='cluster') as tm: sync_table(tm) @classmethod def tearDownClass(cls): super(ContextQueryConnectionTests, cls).tearDownClass() with ContextQuery(TestModel, connection='cluster') as tm: drop_table(tm) drop_keyspace('ks1', connections=['cluster']) # reset the default connection conn.unregister_connection('fake_cluster') conn.unregister_connection('cluster') setup_connection(DEFAULT_KEYSPACE) def setUp(self): super(BaseCassEngTestCase, self).setUp() def test_context_connection_priority(self): """ Tests to ensure the proper connection priority is honored. Explicit connection should have higest priority, Followed by context query connection Default connection should be honored last. @since 3.7 @jira_ticket PYTHON-613 @expected_result priorities should be honored @test_category object_mapper """ # model keyspace write/read # Set the default connection on the Model TestModel.__connection__ = 'cluster' with ContextQuery(TestModel) as tm: tm.objects.create(partition=1, cluster=1) # ContextQuery connection should have priority over default one with ContextQuery(TestModel, connection='fake_cluster') as tm: with self.assertRaises(NoHostAvailable): tm.objects.create(partition=1, cluster=1) # Explicit connection should have priority over ContextQuery one with ContextQuery(TestModel, connection='fake_cluster') as tm: tm.objects.using(connection='cluster').create(partition=1, cluster=1) # Reset the default conn of the model TestModel.__connection__ = None # No model connection and an invalid default connection with ContextQuery(TestModel) as tm: with self.assertRaises(NoHostAvailable): tm.objects.create(partition=1, cluster=1) def test_context_connection_with_keyspace(self): """ Tests to ensure keyspace param is honored @since 3.7 @jira_ticket PYTHON-613 @expected_result Invalid request is thrown @test_category object_mapper """ # ks2 doesn't exist with ContextQuery(TestModel, connection='cluster', keyspace='ks2') as tm: with self.assertRaises(InvalidRequest): tm.objects.create(partition=1, cluster=1) class ManagementConnectionTests(BaseCassEngTestCase): keyspaces = ['ks1', 'ks2'] conns = ['cluster'] @classmethod def setUpClass(cls): super(ManagementConnectionTests, cls).setUpClass() conn.unregister_connection('default') conn.register_connection('fake_cluster', ['127.0.0.100'], lazy_connect=True, retry_connect=True, default=True) conn.register_connection('cluster', [CASSANDRA_IP]) @classmethod def tearDownClass(cls): super(ManagementConnectionTests, cls).tearDownClass() # reset the default connection conn.unregister_connection('fake_cluster') conn.unregister_connection('cluster') setup_connection(DEFAULT_KEYSPACE) def setUp(self): super(BaseCassEngTestCase, self).setUp() def test_create_drop_keyspace(self): """ Tests drop and create keyspace with connections explicitly set @since 3.7 @jira_ticket PYTHON-613 @expected_result keyspaces should be created and dropped @test_category object_mapper """ # No connection (default is fake) with self.assertRaises(NoHostAvailable): create_keyspace_simple(self.keyspaces[0], 1) # Explicit connections for ks in self.keyspaces: create_keyspace_simple(ks, 1, connections=self.conns) for ks in self.keyspaces: drop_keyspace(ks, connections=self.conns) def test_create_drop_table(self): """ Tests drop and create Table with connections explicitly set @since 3.7 @jira_ticket PYTHON-613 @expected_result Tables should be created and dropped @test_category object_mapper """ for ks in self.keyspaces: create_keyspace_simple(ks, 1, connections=self.conns) # No connection (default is fake) with self.assertRaises(NoHostAvailable): sync_table(TestModel) # Explicit connections sync_table(TestModel, connections=self.conns) # Explicit drop drop_table(TestModel, connections=self.conns) # Model connection TestModel.__connection__ = 'cluster' sync_table(TestModel) TestModel.__connection__ = None # No connection (default is fake) with self.assertRaises(NoHostAvailable): drop_table(TestModel) # Model connection TestModel.__connection__ = 'cluster' drop_table(TestModel) TestModel.__connection__ = None # Model connection for ks in self.keyspaces: drop_keyspace(ks, connections=self.conns) def test_connection_creation_from_session(self): """ Test to ensure that you can register a connection from a session @since 3.8 @jira_ticket PYTHON-649 @expected_result queries should execute appropriately @test_category object_mapper """ - cluster = Cluster([CASSANDRA_IP]) + cluster = TestCluster() session = cluster.connect() connection_name = 'from_session' conn.register_connection(connection_name, session=session) self.assertIsNotNone(conn.get_connection(connection_name).cluster.metadata.get_host(CASSANDRA_IP)) self.addCleanup(conn.unregister_connection, connection_name) cluster.shutdown() def test_connection_from_hosts(self): """ Test to ensure that you can register a connection from a list of hosts @since 3.8 @jira_ticket PYTHON-692 @expected_result queries should execute appropriately @test_category object_mapper """ connection_name = 'from_hosts' conn.register_connection(connection_name, hosts=[CASSANDRA_IP]) self.assertIsNotNone(conn.get_connection(connection_name).cluster.metadata.get_host(CASSANDRA_IP)) self.addCleanup(conn.unregister_connection, connection_name) def test_connection_param_validation(self): """ Test to validate that invalid parameter combinations for registering connections via session are not tolerated @since 3.8 @jira_ticket PYTHON-649 @expected_result queries should execute appropriately @test_category object_mapper """ - cluster = Cluster([CASSANDRA_IP]) + cluster = TestCluster() session = cluster.connect() with self.assertRaises(CQLEngineException): conn.register_connection("bad_coonection1", session=session, consistency="not_null") with self.assertRaises(CQLEngineException): conn.register_connection("bad_coonection2", session=session, lazy_connect="not_null") with self.assertRaises(CQLEngineException): conn.register_connection("bad_coonection3", session=session, retry_connect="not_null") with self.assertRaises(CQLEngineException): conn.register_connection("bad_coonection4", session=session, cluster_options="not_null") with self.assertRaises(CQLEngineException): conn.register_connection("bad_coonection5", hosts="not_null", session=session) cluster.shutdown() cluster.shutdown() cluster.shutdown() class BatchQueryConnectionTests(BaseCassEngTestCase): conns = ['cluster'] @classmethod def setUpClass(cls): super(BatchQueryConnectionTests, cls).setUpClass() create_keyspace_simple('ks1', 1) sync_table(TestModel) sync_table(AnotherTestModel) conn.unregister_connection('default') conn.register_connection('fake_cluster', ['127.0.0.100'], lazy_connect=True, retry_connect=True, default=True) conn.register_connection('cluster', [CASSANDRA_IP]) @classmethod def tearDownClass(cls): super(BatchQueryConnectionTests, cls).tearDownClass() # reset the default connection conn.unregister_connection('fake_cluster') conn.unregister_connection('cluster') setup_connection(DEFAULT_KEYSPACE) drop_keyspace('ks1') def setUp(self): super(BaseCassEngTestCase, self).setUp() def test_basic_batch_query(self): """ Test Batch queries with connections explicitly set @since 3.7 @jira_ticket PYTHON-613 @expected_result queries should execute appropriately @test_category object_mapper """ # No connection with a QuerySet (default is a fake one) with self.assertRaises(NoHostAvailable): with BatchQuery() as b: TestModel.objects.batch(b).create(partition=1, cluster=1) # Explicit connection with a QuerySet with BatchQuery(connection='cluster') as b: TestModel.objects.batch(b).create(partition=1, cluster=1) # Get an object from the BD with ContextQuery(TestModel, connection='cluster') as tm: obj = tm.objects.get(partition=1, cluster=1) obj.__connection__ = None # No connection with a model (default is a fake one) with self.assertRaises(NoHostAvailable): with BatchQuery() as b: obj.count = 2 obj.batch(b).save() # Explicit connection with a model with BatchQuery(connection='cluster') as b: obj.count = 2 obj.batch(b).save() def test_batch_query_different_connection(self): """ Test BatchQuery with Models that have a different connection @since 3.7 @jira_ticket PYTHON-613 @expected_result queries should execute appropriately @test_category object_mapper """ # Testing on a model class TestModel.__connection__ = 'cluster' AnotherTestModel.__connection__ = 'cluster2' with self.assertRaises(CQLEngineException): with BatchQuery() as b: TestModel.objects.batch(b).create(partition=1, cluster=1) AnotherTestModel.objects.batch(b).create(partition=1, cluster=1) TestModel.__connection__ = None AnotherTestModel.__connection__ = None with BatchQuery(connection='cluster') as b: TestModel.objects.batch(b).create(partition=1, cluster=1) AnotherTestModel.objects.batch(b).create(partition=1, cluster=1) # Testing on a model instance with ContextQuery(TestModel, AnotherTestModel, connection='cluster') as (tm, atm): obj1 = tm.objects.get(partition=1, cluster=1) obj2 = atm.objects.get(partition=1, cluster=1) obj1.__connection__ = 'cluster' obj2.__connection__ = 'cluster2' obj1.count = 4 obj2.count = 4 with self.assertRaises(CQLEngineException): with BatchQuery() as b: obj1.batch(b).save() obj2.batch(b).save() def test_batch_query_connection_override(self): """ Test that we cannot override a BatchQuery connection per model @since 3.7 @jira_ticket PYTHON-613 @expected_result Proper exceptions should be raised @test_category object_mapper """ with self.assertRaises(CQLEngineException): with BatchQuery(connection='cluster') as b: TestModel.batch(b).using(connection='test').save() with self.assertRaises(CQLEngineException): with BatchQuery(connection='cluster') as b: TestModel.using(connection='test').batch(b).save() with ContextQuery(TestModel, AnotherTestModel, connection='cluster') as (tm, atm): obj1 = tm.objects.get(partition=1, cluster=1) obj1.__connection__ = None with self.assertRaises(CQLEngineException): with BatchQuery(connection='cluster') as b: obj1.using(connection='test').batch(b).save() with self.assertRaises(CQLEngineException): with BatchQuery(connection='cluster') as b: obj1.batch(b).using(connection='test').save() class UsingDescriptorTests(BaseCassEngTestCase): conns = ['cluster'] keyspaces = ['ks1', 'ks2'] @classmethod def setUpClass(cls): super(UsingDescriptorTests, cls).setUpClass() conn.unregister_connection('default') conn.register_connection('fake_cluster', ['127.0.0.100'], lazy_connect=True, retry_connect=True, default=True) conn.register_connection('cluster', [CASSANDRA_IP]) @classmethod def tearDownClass(cls): super(UsingDescriptorTests, cls).tearDownClass() # reset the default connection conn.unregister_connection('fake_cluster') conn.unregister_connection('cluster') setup_connection(DEFAULT_KEYSPACE) for ks in cls.keyspaces: drop_keyspace(ks) def setUp(self): super(BaseCassEngTestCase, self).setUp() def _reset_data(self): for ks in self.keyspaces: drop_keyspace(ks, connections=self.conns) for ks in self.keyspaces: create_keyspace_simple(ks, 1, connections=self.conns) sync_table(TestModel, keyspaces=self.keyspaces, connections=self.conns) def test_keyspace(self): """ Test keyspace segregation when same connection is used @since 3.7 @jira_ticket PYTHON-613 @expected_result Keyspace segration is honored @test_category object_mapper """ self._reset_data() with ContextQuery(TestModel, connection='cluster') as tm: # keyspace Model class tm.objects.using(keyspace='ks2').create(partition=1, cluster=1) tm.objects.using(keyspace='ks2').create(partition=2, cluster=2) with self.assertRaises(TestModel.DoesNotExist): tm.objects.get(partition=1, cluster=1) # default keyspace ks1 obj1 = tm.objects.using(keyspace='ks2').get(partition=1, cluster=1) obj1.count = 2 obj1.save() with self.assertRaises(NoHostAvailable): TestModel.objects.using(keyspace='ks2').get(partition=1, cluster=1) obj2 = TestModel.objects.using(connection='cluster', keyspace='ks2').get(partition=1, cluster=1) self.assertEqual(obj2.count, 2) # Update test TestModel.objects(partition=2, cluster=2).using(connection='cluster', keyspace='ks2').update(count=5) obj3 = TestModel.objects.using(connection='cluster', keyspace='ks2').get(partition=2, cluster=2) self.assertEqual(obj3.count, 5) TestModel.objects(partition=2, cluster=2).using(connection='cluster', keyspace='ks2').delete() with self.assertRaises(TestModel.DoesNotExist): TestModel.objects.using(connection='cluster', keyspace='ks2').get(partition=2, cluster=2) def test_connection(self): """ Test basic connection functionality @since 3.7 @jira_ticket PYTHON-613 @expected_result proper connection should be used @test_category object_mapper """ self._reset_data() # Model class with self.assertRaises(NoHostAvailable): TestModel.objects.create(partition=1, cluster=1) TestModel.objects.using(connection='cluster').create(partition=1, cluster=1) TestModel.objects(partition=1, cluster=1).using(connection='cluster').update(count=2) obj1 = TestModel.objects.using(connection='cluster').get(partition=1, cluster=1) self.assertEqual(obj1.count, 2) obj1.using(connection='cluster').update(count=5) obj1 = TestModel.objects.using(connection='cluster').get(partition=1, cluster=1) self.assertEqual(obj1.count, 5) obj1.using(connection='cluster').delete() with self.assertRaises(TestModel.DoesNotExist): TestModel.objects.using(connection='cluster').get(partition=1, cluster=1) class ModelQuerySetNew(ModelQuerySet): def __init__(self, *args, **kwargs): super(ModelQuerySetNew, self).__init__(*args, **kwargs) self._connection = "cluster" class BaseConnectionTestNoDefault(object): conns = ['cluster'] @classmethod def setUpClass(cls): conn.register_connection('cluster', [CASSANDRA_IP]) test_queryset.TestModel.__queryset__ = ModelQuerySetNew test_queryset.IndexedTestModel.__queryset__ = ModelQuerySetNew test_queryset.CustomIndexedTestModel.__queryset__ = ModelQuerySetNew test_queryset.IndexedCollectionsTestModel.__queryset__ = ModelQuerySetNew test_queryset.TestMultiClusteringModel.__queryset__ = ModelQuerySetNew super(BaseConnectionTestNoDefault, cls).setUpClass() conn.unregister_connection('default') @classmethod def tearDownClass(cls): conn.unregister_connection('cluster') setup_connection(DEFAULT_KEYSPACE) super(BaseConnectionTestNoDefault, cls).tearDownClass() # reset the default connection def setUp(self): super(BaseCassEngTestCase, self).setUp() class TestQuerySetOperationConnection(BaseConnectionTestNoDefault, test_queryset.TestQuerySetOperation): """ Execute test_queryset.TestQuerySetOperation using non default connection @since 3.7 @jira_ticket PYTHON-613 @expected_result proper connection should be used @test_category object_mapper """ pass class TestQuerySetDistinctNoDefault(BaseConnectionTestNoDefault, test_queryset.TestQuerySetDistinct): """ Execute test_queryset.TestQuerySetDistinct using non default connection @since 3.7 @jira_ticket PYTHON-613 @expected_result proper connection should be used @test_category object_mapper """ pass class TestQuerySetOrderingNoDefault(BaseConnectionTestNoDefault, test_queryset.TestQuerySetOrdering): """ Execute test_queryset.TestQuerySetOrdering using non default connection @since 3.7 @jira_ticket PYTHON-613 @expected_result proper connection should be used @test_category object_mapper """ pass class TestQuerySetCountSelectionAndIterationNoDefault(BaseConnectionTestNoDefault, test_queryset.TestQuerySetCountSelectionAndIteration): """ Execute test_queryset.TestQuerySetOrdering using non default connection @since 3.7 @jira_ticket PYTHON-613 @expected_result proper connection should be used @test_category object_mapper """ pass class TestQuerySetSlicingNoDefault(BaseConnectionTestNoDefault, test_queryset.TestQuerySetSlicing): """ Execute test_queryset.TestQuerySetOrdering using non default connection @since 3.7 @jira_ticket PYTHON-613 @expected_result proper connection should be used @test_category object_mapper """ pass class TestQuerySetValidationNoDefault(BaseConnectionTestNoDefault, test_queryset.TestQuerySetValidation): """ Execute test_queryset.TestQuerySetOrdering using non default connection @since 3.7 @jira_ticket PYTHON-613 @expected_result proper connection should be used @test_category object_mapper """ pass class TestQuerySetDeleteNoDefault(BaseConnectionTestNoDefault, test_queryset.TestQuerySetDelete): """ Execute test_queryset.TestQuerySetDelete using non default connection @since 3.7 @jira_ticket PYTHON-613 @expected_result proper connection should be used @test_category object_mapper """ pass class TestValuesListNoDefault(BaseConnectionTestNoDefault, test_queryset.TestValuesList): """ Execute test_queryset.TestValuesList using non default connection @since 3.7 @jira_ticket PYTHON-613 @expected_result proper connection should be used @test_category object_mapper """ pass class TestObjectsPropertyNoDefault(BaseConnectionTestNoDefault, test_queryset.TestObjectsProperty): """ Execute test_queryset.TestObjectsProperty using non default connection @since 3.7 @jira_ticket PYTHON-613 @expected_result proper connection should be used @test_category object_mapper """ pass diff --git a/tests/integration/long/ssl/.keystore b/tests/integration/long/ssl/.keystore deleted file mode 100644 index 58ab969..0000000 Binary files a/tests/integration/long/ssl/.keystore and /dev/null differ diff --git a/tests/integration/long/ssl/.truststore b/tests/integration/long/ssl/.truststore deleted file mode 100644 index 80bbc1f..0000000 Binary files a/tests/integration/long/ssl/.truststore and /dev/null differ diff --git a/tests/integration/long/ssl/127.0.0.1.keystore b/tests/integration/long/ssl/127.0.0.1.keystore new file mode 100644 index 0000000..98193ab Binary files /dev/null and b/tests/integration/long/ssl/127.0.0.1.keystore differ diff --git a/tests/integration/long/ssl/cassandra.pem b/tests/integration/long/ssl/cassandra.pem deleted file mode 100644 index 43c0a3e..0000000 --- a/tests/integration/long/ssl/cassandra.pem +++ /dev/null @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDnzCCAoegAwIBAgIEG7jtLDANBgkqhkiG9w0BAQsFADB/MQswCQYDVQQGEwJVUzETMBEGA1UE -CBMKQ2FsaWZvcm5pYTEUMBIGA1UEBxMLU2FudGEgQ2xhcmExFjAUBgNVBAoTDURhdGFTdGF4IElu -Yy4xGTAXBgNVBAsTEFBIUCBEcml2ZXIgVGVzdHMxEjAQBgNVBAMTCTEyNy4wLjAuMTAgFw0xNjA0 -MTkxNTIzNDBaGA8yMTE2MDMyNjE1MjM0MFowfzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlm -b3JuaWExFDASBgNVBAcTC1NhbnRhIENsYXJhMRYwFAYDVQQKEw1EYXRhU3RheCBJbmMuMRkwFwYD -VQQLExBQSFAgRHJpdmVyIFRlc3RzMRIwEAYDVQQDEwkxMjcuMC4wLjEwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQCkFMlcxnl+k5KAzt6g1GSQ/kXzHtQXcf0//x6BQTRYdOEeiBnMcI+o -HYefiwGpDslr3YxcWwJSfKjgUhGj+2wyl4O8PP0Up47tX5HUQuIlIjjBZd465VhQh6DqaJky3YHX -KD+8eHuVMnEyAImsNh9laQkUOHsGT/POpI77IBxS1hVVOu6A5bYz17D0RAzZBel3eZBWLSSgbkSG -jUPIDY+078qRJI56xY/6lEM5Zr6DJ96jTdqjRPFv3fHJJZnwCNz0ng0wB/gHYFkm2fdGAM2jrCdD -jC+VZK6uyXatRbFanPdlfZ4rWPrH7V0c6wrDssuUMlDIdaMyHC89axZLP5ZZAgMBAAGjITAfMB0G -A1UdDgQWBBR/0GR2jGRuP8rsmBept17gwXcRejANBgkqhkiG9w0BAQsFAAOCAQEAe33a2GITd7DP -WmDCFfsZqCDIbHdx1QwfcvWRpSnjXpN4Muzrt4TCRJAx6kNQZDnG2aNMdGWGjrQAXUMLkJfSnwJX -X1f3LteNfekWB/lN6kVbPy5lSuLT45q3xSLpTUE51S3zG/c+qyi3FZgYA729ieuDW8VTQdF9hClN -Ik8Wy5Gg87AdYY71DvG9IQkg9eAGVeZSnfMUDYpAiZaavsYJwFfYqIT/WCz9FNXPYN1tDNoV3u71 -GTPrywMLZlmmGn3EBvbh1mR25EmPkxAw6LkWyfbbzrskhXmzN+j9TZNN9MiYMNtisWBR9afsVpLq -Bw4ukuih6CyqUxwuVBNhns8iFA== ------END CERTIFICATE----- diff --git a/tests/integration/long/ssl/cassandra.truststore b/tests/integration/long/ssl/cassandra.truststore new file mode 100644 index 0000000..b31e34b Binary files /dev/null and b/tests/integration/long/ssl/cassandra.truststore differ diff --git a/tests/integration/long/ssl/client.crt_signed b/tests/integration/long/ssl/client.crt_signed new file mode 100644 index 0000000..db3d903 --- /dev/null +++ b/tests/integration/long/ssl/client.crt_signed @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDDjCCAfYCFAG4WryLorTXxNtrkEJ56zUg/XdDMA0GCSqGSIb3DQEBCwUAMEIx +CzAJBgNVBAYTAlVTMREwDwYDVQQKDAhkYXRhc3RheDEPMA0GA1UECwwGZmllbGRz +MQ8wDQYDVQQDDAZyb290Q2EwHhcNMjEwMzE3MTcwNTE4WhcNMjIwMzE3MTcwNTE4 +WjBFMQswCQYDVQQGEwJVUzERMA8GA1UECgwIZGF0YXN0YXgxDzANBgNVBAsMBmZp +ZWxkczESMBAGA1UEAwwJMTI3LjAuMC4xMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A +MIIBCgKCAQEAnrpE3g8pbQn2tVVidX2Ww1rh/6YIH6EGW9hXMO/F506ReMruv+Al +ilc7B2sPpGRDKXupy23IcpfMIe9+Lm74/yu7pW51rJ/r2jMqg+tViFa/GQxSQLKd +AxDAvwJaAM41kro0DKmcm4RwfYAltupwc6pC7AfBtT08PBuDK7WfaNnFbhGAWkHv +MbULNWAKbPWqITHbUEvLgS/uPj+/W4SHk5GaYk0Y2mU3aWypeDOBqEfKTi2W0ix1 +O7SpOHyfA0hvXS9IilF/HWURvr9u13mnvJNe8W+uqWqlQMdyFsbPCIhbVwVwGYQp +yoyBrgz6y5SPwSyugAb2F8Yk3UpvqH30yQIDAQABMA0GCSqGSIb3DQEBCwUAA4IB +AQB5XV+3NS5UpwpTXTYsadLL8XcdGsfITMs4MSv0N3oir++TUzTc3cOd2T6YVdEc +ypw5CKTYnFTK9oF2PZXeV+aLIjdvK4AukQurB8EdXq4Hu7y1b61OaGRqiKTVsIne +LwxCXpc42jqMFt4mMXpmU/hSCjRSvoumTcL1aHUzaPlSIasD2JDyLurO64gxQypi +wbD9gliPJ60pdhY0m9NfF5F2PdqBuJXrhF1VuxYx1/cfo/c1A4UK2slhsZCDls7/ +HbM8ri5Z74M1EtCGFcTNYvm0xlfF5arisGQSKhTw+06LnpUlQi5a8NRNBLeAmem/ +cuICJJbnSzjmq9skkp8i/ejH +-----END CERTIFICATE----- diff --git a/tests/integration/long/ssl/client.key b/tests/integration/long/ssl/client.key new file mode 100644 index 0000000..d6b8811 --- /dev/null +++ b/tests/integration/long/ssl/client.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCeukTeDyltCfa1 +VWJ1fZbDWuH/pggfoQZb2Fcw78XnTpF4yu6/4CWKVzsHaw+kZEMpe6nLbchyl8wh +734ubvj/K7ulbnWsn+vaMyqD61WIVr8ZDFJAsp0DEMC/AloAzjWSujQMqZybhHB9 +gCW26nBzqkLsB8G1PTw8G4MrtZ9o2cVuEYBaQe8xtQs1YAps9aohMdtQS8uBL+4+ +P79bhIeTkZpiTRjaZTdpbKl4M4GoR8pOLZbSLHU7tKk4fJ8DSG9dL0iKUX8dZRG+ +v27Xeae8k17xb66paqVAx3IWxs8IiFtXBXAZhCnKjIGuDPrLlI/BLK6ABvYXxiTd +Sm+offTJAgMBAAECggEAN+VysRx3wy1aEvuRo7xpZjxQD/5BKBpFqfxioBogAFfb +xMT6FNnzfmc/o1ohdQvV1vr0jW4Iw8oPGfhD4Eg2KW4WM6jVicf7f6i7FR+/zDZ4 +L3L2WFBOGLFCn0FNvrDfjt9Byx/DxcR69Mc3ANZIaYMQ9Bu7LH73AlfR9oeMLpjL ++6g1qz2yz8Sm2CMCGXTyXtvUCgn2ld6nz8KlZ8FTUG9C9mAabuvV91Ko6rmTxuiv +YKvHSPnIjXRjuC+Ozjf1rYTOJ5LVMNNhlbIKBG/Nx5QzL7bA3XDtMD1BEI9pdHR+ +5HwA0tV2Ex67tBCJwlBAhYLxuPjfOj1R5KV8wriE3QKBgQDNvqOaGYiXwp9Rajoo +ltlOBPfnjshd9tPdc6tTUQR34vSbkHrg0HVJhvIP5LRbyx/M/8ACQxFkDRE4U7fJ +xVGDs8Pi0FqcqFTnm/AYQ5eZbJkPp9qe71aDOPanncrVNEGFeW26LaeLGbTLrOMM +6mTmsfGig0MKgml35IMrP+oPuwKBgQDFf56DdaFe08xSK9pDWuKxUuBIagGExQkQ +r9eYasBc336CXh3FWtpSlxl73dqtISh/HbKbv+OZfkVdbmkcTVGlWm/N/XvLqpPK +86kbKW6PY8FxIY/RxiZANf/JJ5gzPp6VQMJeSy+oepeWj11mTLcT02plvIMM0Jmg +Z5B9Hw37SwKBgDR/59lDmLI47FRnCc4fp/WbmPKSYZhwimFgyZ/p9XzuAcLMXD6P +ks4fTBc4IbmmnEfAHuu013QzTWiVHDm1SvaTYXG3/tcosPmkteBLJxz0NB5lk4io +w+eaGn5s6jv7KJj5gkFWswDwn0y1of5CtVqUn3b7jZjZ7DW2rq3TklNPAoGAIzaW +56+AfyzaQEhrWRkKVD2HmcG01Zxf+mav1RArjiOXJd1sB3UkehdQxuIOjFHeK5P6 +9YQoK4T1DyyRdydeCFJwntS0TuLyCPyaySoA+XX61pX6U5e12DsIiTATFgfzNH9g +aHmVXL/G6WRUbdn9xn4qeUs8Pnuu+IeenoB7+LMCgYBBnig9nTp81U+SGsNl2D3J +WUz4z+XzEfKU1nq2s4KNjIPB2T1ne+1x3Uso2hagtEHeuEbZoRY4dtCahAvYwrPM +8wtDFQXWmvFyN3X0Js65GZ++knuseQ1tdlbc/4C+k4u26tVe2GcwhKTjn08++L2E +UB3pLXbssswH271OjD+QkQ== +-----END PRIVATE KEY----- diff --git a/tests/integration/long/ssl/client_bad.key b/tests/integration/long/ssl/client_bad.key new file mode 100644 index 0000000..5d810f2 --- /dev/null +++ b/tests/integration/long/ssl/client_bad.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDha8+NBvpTmTbw +D2EIodXlaaAEtLmXTGoH8pdBm3JxzMuUEkYbGig3YjQ1BAKQgCB1TJGPINcHz7Jo +5aW5To1jrxhhohZYQLCNKlAONDhgJbHEPf7s8dreQ/q5ISt/2I3z68c9I0j3VoRz +AxxcNktl/x+6YkXe9tXf/LWmJk/gHlu72/HuJ5oNyqOKaCCoMoib3jLTlR+lslTy +Qy/CJZH6WJabLOPmppFLaxJMlSGDSTE/Xktt7+H5ssHnfQtyWyylVjZkzChJfBgh +HrLpm3hO5rmqVwOhoKLKVDFMmX3aMGX2S+3KpXQ8gLnPXwfLI9J9fDg5jp7bya4k +OXlZfB5hAgMBAAECggEBANQVFbmudfgPL4PeREHV2SM1JCspSW9SonOFxs8gDCWL +M4HFS5YWHv40c7/pXOxMz7zsZApQMF8WBtnwLeJRSG8f/oVk9Tbk7fZyd81VTjEP +ZdenKGAPEAeL16kzzvRCbxOtoc8gkna6PHTk2VrcbkWxKU23RduHSiOpY9HFO+Mz +iI69tB7657NOiZCQ6xDIjKv+jR63m7VAWKT5jkN+tYpvx4K20na5t8RO1s0shqNE +e2zMG8WXVl6lW4btfkt/lwWUNXu8olMTk9qN2b5Rq7BEJfKwn3lb9vCpUMyewtRB +/8U+Zu7Tlwni5QagOqAUEkjuOJ8cR/Jgwu1mqV2sXxECgYEA9zXi0PjWAe2ZIALd +1iWPZCvvT7yEjt4ulhAYPqi8T38B4K5f//m5SuYPS2ebmSAd2WBTeIX2A6mHc9lk +53gnwvsgAqaFgjYeDqBThpCE8icFXEZnJbtnJyC8zC7pYjUovAHkFEdLw5kQoI6Y +i9HNOS9ugSut8RnF0oSv/E2mahUCgYEA6W+ZAEneBBCsOQclVfVPLm7D+y+5SZEt +zWr2b7CCnGCev/qRCllIEwQ2+W1ACEHof9xjE+aWwEQjX8YnoVbAJo2ru6FFQfI+ +f/SQx7beX8jUAeJGo+CFr2ijdVmcCCbMGeAm8mpACUIQfWPHVqjtGS/CayxdfwA+ +lbWPbkXCMh0CgYBfUgHRPgGW4LyoYTKUfgsaPu6ZukEKrZUc+7u9fWaO6JQaxGHz +26CcxrSjCKIwmvend8L3t/+yTc4S14JW1jfOsPIY04irOp7AWQWb32HD1VP1zpe7 +LtWJetARkw0edwzr4XbGcu89zmlg31rmntEY+bcMS4FYc+2ZTNxm1rISOQKBgGQZ +lct44Xpux9tghBMbMUwg9WtWKKcyWSi4EFsOnsN97zU1tlJwvKZi7UwCHC4uTQvf +LqFPBSAHV//u0fmuYJFnuNeprTA9N63Y6uipMyxxyu/P3yjQ06LHRSjCN1WLhYQn +Cax0AWe266lJSyaPI7TkNQOOL72RFkVOaOYJhd/FAoGAPtpVPTiVK0RYwLnZqaWB +fxyI6w+UjOEbP88vD7N7FEI2kQSGQ6F3pMzDK37NglJVtwjgzEIF9x9BIE8XSf16 +shc0U73Vg9ZsXDNPUz21hhAwYL1cCgnx0mfL88F1Icb5FfxlT/1BPHNHKowA9vST +ihbxCJg/JJBzwXTxPocQisk= +-----END PRIVATE KEY----- diff --git a/tests/integration/long/ssl/client_encrypted.key b/tests/integration/long/ssl/client_encrypted.key new file mode 100644 index 0000000..49f475d --- /dev/null +++ b/tests/integration/long/ssl/client_encrypted.key @@ -0,0 +1,30 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-256-CBC,7288A409E846EBE2DE421B77598DAF98 + +ahiUSf+k9POIEUJb5BGbQ6knk4+FtTz+e+6fouqVc4Lq+RXR9f0pFBi9eDEkFNiN +AcUjLkxh+3TmihTZJprqXSbQ3jacwbnwDOFgtZE3PxoA1heHxADaKCNr+Ph0lC/T +3cIzsoIZ6slk+3n6ERieZRdmvoMH1SY8nXKT5+bLMR4RIjw1y7h26MRhjQS+lXaX +Asd5EOGROCIgefeEBGHAbrlg0FoHy7slqVBxuZphTHKtyK/VK4fRLt6doUzBu5GJ +T2jdrqJCWr5PRn3bAqMemJWxDhZLX4DyNDQPn8riZ8jMbwPOVUSnF8B8re1tNkQ0 +CsH77sYIIjmPdizCdvj91+jH6o7MRCZPvky+PHG/9G5WsPiw5W1i/nrPemT1XJyy +oPRc/fMFfbHmW3HCGqgv2/6Wg+17un/a6UyzXsbNdhDZLCVqtAQ7PSv83z5oUazT +djzFHgxSqRknUY0lOUvP8Rni67MG+Rcksj9HgszhLoC0be64IX0Ey5oc5+pBYrf9 +FVEPsuyyu4aDSRYYATC2E1V/EQRwcvpKEZNFTbqMpQhjrWtlBM/GgQnQBeQdLAGX +yefDSzkH31y5gcdgHLElriWwbHHbcaAmf3e15W94YHgTytJBsQ9A19SmtmgUmo4h +jaFoUooM5mFA8hc/snSe2PdkEefkzS72g8qxa//61LTJAAkVk43dYjoqQ34wq6WR +OB4nn/W2xlfv/ClZJTWf8YvQTrQptJY5VQq/TTEcrXy67Uc0wRHXZK2rTjKeyRj9 +65SkyyXhMopWEl2vX25ReITVfdJ0FgjqI/ugYSf25iOfJtsk+jgrtrswZ+8F2eMq +iAQ+0JSiYmlot2Pn1QCalLjtTz8zeMfXPyo5fbKNMdp52U1cPYld90kUGHZfjqju +GmY/aHa6N8lZGxj8SC/JM36GawaGKe4S/F5BetYJOpaEzkpowqlTC8Syv529rm46 +vvgf+EJL8gRvdtnIEe/qtzbtel299VhaBpuOcApfTDSxRHZmvkCpdHo9I3KgOZB9 +Cqu9Bz+FiJmTk8rGQwmI8EYj38jneEoqA+fN7tUkzxCGacg+x6ke4nOcJzgBhd94 +8DvGclrcAwBY1mlNYRceFJKFXhwLZTKBojZlS8Q9863EAH3DOBLeP85V3YvBD/MK +O+kzPoxN/jPVNho7y4gL7skcqe/IXePzPxBcZrHJjoU7mGVDcVcouRj16XSezMbB +5Pft0/gGiItRJ2+v9DlPjzDfjTuRdS78muaZ4nNqX6B+JmyPJtkb2CdiHz6B21RO +3hjGrffM1nhmYBegyjTVc88IxzYg0T8CZLq1FYxuTZmwyahA520IpwsbfwXxLVMU +5rmou5dj1pVlvoP3l+ivPqugeY3k7UjZ33m5H9p009JR40dybr1S2RbI8Gqhe953 +0bedA4DWvPakODXgYu43al92uR/tyjazeB5t7Iu8uB5Xcm3/Mqoofe9xtdQSCWa0 +jKKvXzSpL1MM2C0bRyYHIkVR65K7Zmi/BzvTaPECo1+Uv+EwqRZRyBzUZKPP8LMq +jTCOBmYaK8+0dTRk8MEzrPW2ihVVJYVMmFyTZKW0iK7kOMKZRkhDCaNSUlPEty7j +-----END RSA PRIVATE KEY----- diff --git a/tests/integration/long/ssl/driver.crt b/tests/integration/long/ssl/driver.crt deleted file mode 100644 index 76c9999..0000000 Binary files a/tests/integration/long/ssl/driver.crt and /dev/null differ diff --git a/tests/integration/long/ssl/driver.key b/tests/integration/long/ssl/driver.key deleted file mode 100644 index bcb033d..0000000 --- a/tests/integration/long/ssl/driver.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAohKfXUHM5AQvwgTPIretqenYVJzo78z5IE/xjUe0/e24lJCe -qCYaJPHB3kjg05ZQhBWZFsPhxMwh7zvTaLiIfjK9EuDvBP+dhxLbWShXcL8NNu45 -dfM4BebewR82Kk4rAMHgAaWDPjnyo4XJ+DUMlXMzbMrCT35k0R2ddwuEF/OI6dIn -AX/VVDtOaWaiCP6BC4rt9r2y1UjJ5xHAK+bPjev7Y1TrSd8maTQTFzORlVRamwpQ -tMXDJfWyan5+rbAfi74Qk6kBuc25ZWKpYKJlKGgHy9b9875G76K63boXe8hDcDE1 -mJHOEReb/n533OWmtTUH2z9Wz/ZLfE7E784DtQIDAQABAoIBAEjCDXMDMCUI0BvM -puSSCs9loG1Tx6qnnQtpeCoRj+oTBzMCvYcFG+WL9pmApBW4vEqfm4tBwp/jeDR6 -6gxwEy58Pq8z9XmL+z8BMyGSX7bIvfjz9y3BU1wq6cNO7LUPRHThlFuI3yNXRlss -m5/myNBq2CI14Adp2X6bSe6AZ/uL6+Ez8ZLpNiMUtGzTDILyH8bkgRHsyDxoDpF+ -h1r42dZG3ue4JC3oqUE2epvNE5Rzh02OTBSYYbmOmFWkhV2lm6DH46lycFHjkzcm -2meU7q9I7nZrf0+ZkkQXhWGQWcGzHd3si+XMhaHT0BnH8gGFZDzpC/qnvZdIn//y -zDu2B/0CgYEA43kkgZ1YGqi5Vi4ngek/uk4sJ9dOvYIaAag+u5ybRinLhCFDGhr9 -MzksqFY7naq9oeZZrLbftw2FsKsCMYAOrrxZIbhvGm538jwWmBefEmD0Ww+k/WKG -AAv0z4sSnSOq2/sZBQJlOrk8K6wQ+FcyEddiy16zyj9UCzEPSDQoNj8CgYEAtmXY -xYALbGz0peDGfzPq/WjeqCJtjlXIKOB7+vdyi88YE4Tea2vfBmAAWmbTf/el/o8R -txDfP6+RKxXs2jCFCY640W83ar3RjXcwtu+oH4Aqa8S21o6Dx2sx3HOgKoJ3DGGB -HHmYczuDZmN/zHseBrYUf1UNcIDQIWZCLKImkQsCgYEAuY735bfJyC18yr1pwwLX -1o2wXWu4ssSvnEx3qCmvTIQJnaZYi7IafC+Wq1d02EAQ40H6QvcG9ddVCHHnnyOc -VpQUjXpbP49/zx2PPNCAFcj7bFENwRkewGkAclE7hO40kbB6j2iN1WKHoASD72GJ -2Z3+3HFLbp9MWrjRg4/wgZcCgYAk2IgkxYwJOC1nwPN4SM2kqWWpQ2MsSKnpkAeb -mBccpRYxAztHKgBgsk3/9RuukyGGPfKPL6pZnCbQNFqnbPvDBYDSVgw01OmbEUPX -AKzOyD5JjPB+gUWfqEjnRrhJPhe8eYnybaHdTV1q9piffxN+uZOEcXMIkgz5YkXl -7E+sJwKBgFLA2CS19lbcoi5R8AJbUydZJr/LNAbFknWnliiq3GxISfWydA9cG/dI -CxV3297awLhHrCWqziC0zITjEcAhsNkfG/VQlYGJOS3sfvMSrLuW/9bAL8o4VCpC -cOs9e+svbJukJB6UQu4vpROMmv+0quXM325VlCZNel7DPAovYwjW ------END RSA PRIVATE KEY----- diff --git a/tests/integration/long/ssl/driver.pem b/tests/integration/long/ssl/driver.pem deleted file mode 100644 index f5aaa25..0000000 --- a/tests/integration/long/ssl/driver.pem +++ /dev/null @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDnzCCAoegAwIBAgIEJErKsDANBgkqhkiG9w0BAQsFADB/MQswCQYDVQQGEwJVUzETMBEGA1UE -CBMKQ2FsaWZvcm5pYTEUMBIGA1UEBxMLU2FudGEgQ2xhcmExFjAUBgNVBAoTDURhdGFTdGF4IElu -Yy4xGTAXBgNVBAsTEFBIUCBEcml2ZXIgVGVzdHMxEjAQBgNVBAMTCTEyNy4wLjAuMTAgFw0xNjA0 -MTkxNTIzNDVaGA8yMTE2MDMyNjE1MjM0NVowfzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlm -b3JuaWExFDASBgNVBAcTC1NhbnRhIENsYXJhMRYwFAYDVQQKEw1EYXRhU3RheCBJbmMuMRkwFwYD -VQQLExBQSFAgRHJpdmVyIFRlc3RzMRIwEAYDVQQDEwkxMjcuMC4wLjEwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQCiEp9dQczkBC/CBM8it62p6dhUnOjvzPkgT/GNR7T97biUkJ6oJhok -8cHeSODTllCEFZkWw+HEzCHvO9NouIh+Mr0S4O8E/52HEttZKFdwvw027jl18zgF5t7BHzYqTisA -weABpYM+OfKjhcn4NQyVczNsysJPfmTRHZ13C4QX84jp0icBf9VUO05pZqII/oELiu32vbLVSMnn -EcAr5s+N6/tjVOtJ3yZpNBMXM5GVVFqbClC0xcMl9bJqfn6tsB+LvhCTqQG5zbllYqlgomUoaAfL -1v3zvkbvorrduhd7yENwMTWYkc4RF5v+fnfc5aa1NQfbP1bP9kt8TsTvzgO1AgMBAAGjITAfMB0G -A1UdDgQWBBR8aJLDSgkUMcrs08BbxhRA1wJIIzANBgkqhkiG9w0BAQsFAAOCAQEAoHRggyaMKbeB -633sZgzH8DzvngzA/vID+XWAv+lCGdIYNkbu9VJ8IaYsa9JsMvvhp7UFL1mYm32QacjorxqfNTNS -To8z4VOXrGLYkuJL1M2qJjkl3ehkX8tzKXyDIgq4pVCvKkFZR0It+QU87MnHUL1/HIOy+zdNW6ZU -Q7sRCUMtqstiQ4scbispsVevfEBkGNjHIp6M/5Qe6skntRvdNMWZILz82GLym+NppTgcNcwDf7lq -g/syNznM0KAE1VUAJ2y8tArvAZ/XugC2RmZGwY3q/qw1B7kaoTqu7KSdLuWzol5gR0NNVADU5x7U -BrwBmgliT/bGpRz+PAGVYj5OXw== ------END CERTIFICATE----- diff --git a/tests/integration/long/ssl/driver_encrypted.key b/tests/integration/long/ssl/driver_encrypted.key deleted file mode 100644 index 91ae5ef..0000000 --- a/tests/integration/long/ssl/driver_encrypted.key +++ /dev/null @@ -1,30 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-256-CBC,4B3084A6FB74C60EF6AD51C4677FE509 - -PRmOOSwQNcBYCBbGuv/YgKgSep00GGqCeyhej2soLaGKgSjPhe/cE7sFvm6jk72+ -wDJNpuY6gLoKmizvxrgi5iHnoVdaPkRXKkcQHgaLt4TjB2EUfPp/+V5N4FA4DxN2 -/jqfWZ5Fw8ltHbW1hEkxQ58cYWd5OQB8EesQ865Pv364px5GIcDyr9FEgTiE/Ulc -wS5V1DSgytL/iwBP7FE/zejvZLiS0OoqNGq/G0nBSsv68CH7/lCs3i0Gn2E8YNW8 -CYdMnRzsxwPgbvWYYFhNeK1mrXC+RZa7FgLeeXWR6K28aSB8wc35PePBbZT6TViz -jZkmBFvbpLrLP7KNogLdzhFLqBzkP0NgkYtseYFFcuUAmIrWPVrsoA4xHWMkdcB6 -OLMz+zpb5u8rjpa3gWh5xQJbdVDxXGJNxCYzT7sc28wzr8vHFJFg6U2DJL9x+ufW -BXwBafb8biS1TBWGSDsc36NUwkyvv/2zjSytEIkdJ4lp4S69TGcU0Qvr1gA+8zLm -o6/1G5wUTt461mAAlvcy/9pHZlm8K1VShBvBCYouoVfUyIYAKhq0bBm64E/jdE3v -/Rxd/hom0d+m595wbH7f2AZCBVmII+hEyaagtKEO87qztq/WVMjN6h6BtXR5Xjsv -fXg71mMlQvqYuTB7hOhpyPdux0vvGzCdlGmvUsAC+urqCfkUseLAFfTnD7IrfYK8 -lzRyFJPABtrDiVqQpCBsOq/ACERjVpn/XcJgEBui2jhaTodwWIVD9DPlf4o93Fhf -oKE2o2W0TkaU/uaTLNt4TLJ0EXJ8S0XIqXnEvt3eRu0jOcC3ZWlFINdJISjm53LW -o1q/6mlvj2COLxCipUfGLVmIRuuMDybndSiXH+vddLQDZSw9mynYzJUvMcurBYyL -Lb9t+8hSRftRNqnM9ojDB+gmCJ0uQUlSAt47SZHGIi91S5pM7IELgP55SUG02mGn -Pr+BBtQCVNbd1szPXH7dlUfD9eUHZ34uL/2wOMtNT7da4ajviR6HIyLiz3lrI+e+ -2X62fMFD5tnxffMIZLVPhAHHlT8RPzvspA7QHdJzWCsdxZ3VVmWCFL0WHKuP3Hhh -0jIBOh0Y9eFCMcL7yP0rbjv/3MyBqqM4T5RfVkoRE3M/F8+kHObQzdUqy4JxApyb -cb0ipAU3JxgEy2rOkXDoeYeRoCKVNU3MZ3x3/+oTZXBhlP+oIbqMo/bTr8JJFC6y -y38YcWcVdUzYBI3KbH2aRCtUXNK404zm8GNs6hTuB95IrpI6APspNkQS9yhcxBdr -zOjZh8snZ52gVDtgrNCSfSgflPEs1CNeg33PpVfZWCai/zwSVFwJuL4iyQqkTVlL -wmbLUFdZN1AmYC2dJpHm30+cykXWJr/xFpAlZXmtgHlttD02pnTVl98G1rP3Oq8u -NplSV/TOXVc3keBnQ7N5BohnQ1NSLq4wusVd7n9UEoCE6HxCUbWWkAKQIHom+5HI -7PgRw0RJRUFbydBz+bDXz3KEFcTOT5ihtI/qq6tJpXMKz7uKGLAnzTIk2DecQYm4 -c40zTUKGVISky357ZIYB6uG9NRVffqsm9M1oIeprwYNpVzyqxz6Yyen+VCxdPq9w ------END RSA PRIVATE KEY----- diff --git a/tests/integration/long/ssl/rootCa.crt b/tests/integration/long/ssl/rootCa.crt new file mode 100644 index 0000000..a0a0ec7 --- /dev/null +++ b/tests/integration/long/ssl/rootCa.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDCzCCAfMCFCoTNYhIQpOXMBnAq8Bw72qfKwGLMA0GCSqGSIb3DQEBCwUAMEIx +CzAJBgNVBAYTAlVTMREwDwYDVQQKDAhkYXRhc3RheDEPMA0GA1UECwwGZmllbGRz +MQ8wDQYDVQQDDAZyb290Q2EwHhcNMjEwMzE3MTcwNTE2WhcNMzEwMzE1MTcwNTE2 +WjBCMQswCQYDVQQGEwJVUzERMA8GA1UECgwIZGF0YXN0YXgxDzANBgNVBAsMBmZp +ZWxkczEPMA0GA1UEAwwGcm9vdENhMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEApFoQtNu0+XQuMBPle4WAJYIMR74HL15uk9ToKBqMEXL7ah3r23xTTeGr +NyUXicM6Owiup7DK27F4vni+MYKAn7L4uZ99mW0ATYNXBDLFB+wwy1JBk4Dw5+eZ +q9lz1TGK7uBvTOXCllOA2qxRqtMTl2aPy5OuciWQe794abwFqs5+1l9GEuzJGsp1 +P9L4yljbmijC8RmvDFAeUZoKRdKXw2G5kUOHqK9Aej5gLxIK920PezpgLxm0V/PD +ZAlwlsW0vT79RgZCF/vtKcKSLtFTHgPBNPPbkZmOdE7s/6KoAkORBV/9CIsKeTC3 +Y/YeYQ2+G0gxiq1RcMavPw8f58POTQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQA1 +MXBlk6u2oVBM+4SyYc2nsaHyerM+omUEysAUNFJq6S6i0pu32ULcusDfrnrIQoyR +xPJ/GSYqZkIDX0s9LvPVD6A6bnugR+Z6VfEniLkG1+TkFC+JMCblgJyaF/EbuayU +3iJX+uj7ikTySjMSDvXxOHik2i0aOh90B/351+sFnSPQrFDQ0XqxeG8s0d7EiLTV +wWJmsYglSeTo1vF3ilVRwjmHO9sX6cmQhRvRNmiQrdWaM3gLS5F6yoQ2UQQ3YdFp +quhYuNwy0Ip6ZpORHYtzkCKSanz/oUh17QWvi7aaJyqD5G5hWZgn3R4RCutoOHRS +TEJ+xzhY768rpsrrNUou +-----END CERTIFICATE----- diff --git a/tests/integration/long/test_consistency.py b/tests/integration/long/test_consistency.py index bb6828a..bbf4468 100644 --- a/tests/integration/long/test_consistency.py +++ b/tests/integration/long/test_consistency.py @@ -1,367 +1,368 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -import struct, time, traceback, sys, logging +import logging +import struct +import sys +import time +import traceback -from random import randint from cassandra import ConsistencyLevel, OperationTimedOut, ReadTimeout, WriteTimeout, Unavailable -from cassandra.cluster import Cluster +from cassandra.cluster import ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.policies import TokenAwarePolicy, RoundRobinPolicy, DowngradingConsistencyRetryPolicy from cassandra.query import SimpleStatement -from tests.integration import use_singledc, PROTOCOL_VERSION, execute_until_pass +from tests.integration import use_singledc, execute_until_pass, TestCluster -from tests.integration.long.utils import (force_stop, create_schema, wait_for_down, wait_for_up, - start, CoordinatorStats) +from tests.integration.long.utils import ( + force_stop, create_schema, wait_for_down, wait_for_up, start, CoordinatorStats +) try: import unittest2 as unittest except ImportError: import unittest # noqa -ALL_CONSISTENCY_LEVELS = set([ - ConsistencyLevel.ANY, ConsistencyLevel.ONE, ConsistencyLevel.TWO, - ConsistencyLevel.QUORUM, ConsistencyLevel.THREE, - ConsistencyLevel.ALL, ConsistencyLevel.LOCAL_QUORUM, - ConsistencyLevel.EACH_QUORUM]) - -MULTI_DC_CONSISTENCY_LEVELS = set([ - ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.EACH_QUORUM]) - +ALL_CONSISTENCY_LEVELS = { + ConsistencyLevel.ANY, ConsistencyLevel.ONE, ConsistencyLevel.TWO, ConsistencyLevel.QUORUM, + ConsistencyLevel.THREE, ConsistencyLevel.ALL, ConsistencyLevel.LOCAL_QUORUM, + ConsistencyLevel.EACH_QUORUM +} +MULTI_DC_CONSISTENCY_LEVELS = {ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.EACH_QUORUM} SINGLE_DC_CONSISTENCY_LEVELS = ALL_CONSISTENCY_LEVELS - MULTI_DC_CONSISTENCY_LEVELS log = logging.getLogger(__name__) def setup_module(): use_singledc() class ConsistencyTests(unittest.TestCase): def setUp(self): self.coordinator_stats = CoordinatorStats() def _cl_failure(self, consistency_level, e): self.fail('Instead of success, saw %s for CL.%s:\n\n%s' % ( e, ConsistencyLevel.value_to_name[consistency_level], traceback.format_exc())) def _cl_expected_failure(self, cl): self.fail('Test passed at ConsistencyLevel.%s:\n\n%s' % ( ConsistencyLevel.value_to_name[cl], traceback.format_exc())) def _insert(self, session, keyspace, count, consistency_level=ConsistencyLevel.ONE): session.execute('USE %s' % keyspace) for i in range(count): ss = SimpleStatement('INSERT INTO cf(k, i) VALUES (0, 0)', consistency_level=consistency_level) execute_until_pass(session, ss) def _query(self, session, keyspace, count, consistency_level=ConsistencyLevel.ONE): routing_key = struct.pack('>i', 0) for i in range(count): ss = SimpleStatement('SELECT * FROM cf WHERE k = 0', consistency_level=consistency_level, routing_key=routing_key) tries = 0 while True: if tries > 100: raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(ss)) try: self.coordinator_stats.add_coordinator(session.execute_async(ss)) break except (OperationTimedOut, ReadTimeout): ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb tries += 1 time.sleep(1) def _assert_writes_succeed(self, session, keyspace, consistency_levels): for cl in consistency_levels: self.coordinator_stats.reset_counts() try: self._insert(session, keyspace, 1, cl) except Exception as e: self._cl_failure(cl, e) def _assert_reads_succeed(self, session, keyspace, consistency_levels, expected_reader=3): for cl in consistency_levels: self.coordinator_stats.reset_counts() try: self._query(session, keyspace, 1, cl) for i in range(3): if i == expected_reader: self.coordinator_stats.assert_query_count_equals(self, i, 1) else: self.coordinator_stats.assert_query_count_equals(self, i, 0) except Exception as e: self._cl_failure(cl, e) def _assert_writes_fail(self, session, keyspace, consistency_levels): for cl in consistency_levels: self.coordinator_stats.reset_counts() try: self._insert(session, keyspace, 1, cl) self._cl_expected_failure(cl) except (Unavailable, WriteTimeout): pass def _assert_reads_fail(self, session, keyspace, consistency_levels): for cl in consistency_levels: self.coordinator_stats.reset_counts() try: self._query(session, keyspace, 1, cl) self._cl_expected_failure(cl) except (Unavailable, ReadTimeout): pass def _test_tokenaware_one_node_down(self, keyspace, rf, accepted): - cluster = Cluster( - load_balancing_policy=TokenAwarePolicy(RoundRobinPolicy()), - protocol_version=PROTOCOL_VERSION) + cluster = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(TokenAwarePolicy(RoundRobinPolicy()))} + ) session = cluster.connect(wait_for_all_pools=True) wait_for_up(cluster, 1) wait_for_up(cluster, 2) create_schema(cluster, session, keyspace, replication_factor=rf) self._insert(session, keyspace, count=1) self._query(session, keyspace, count=1) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 1) self.coordinator_stats.assert_query_count_equals(self, 3, 0) try: force_stop(2) wait_for_down(cluster, 2) self._assert_writes_succeed(session, keyspace, accepted) self._assert_reads_succeed(session, keyspace, accepted - set([ConsistencyLevel.ANY])) self._assert_writes_fail(session, keyspace, SINGLE_DC_CONSISTENCY_LEVELS - accepted) self._assert_reads_fail(session, keyspace, SINGLE_DC_CONSISTENCY_LEVELS - accepted) finally: start(2) wait_for_up(cluster, 2) cluster.shutdown() def test_rfone_tokenaware_one_node_down(self): self._test_tokenaware_one_node_down( keyspace='test_rfone_tokenaware', rf=1, accepted=set([ConsistencyLevel.ANY])) def test_rftwo_tokenaware_one_node_down(self): self._test_tokenaware_one_node_down( keyspace='test_rftwo_tokenaware', rf=2, accepted=set([ConsistencyLevel.ANY, ConsistencyLevel.ONE])) def test_rfthree_tokenaware_one_node_down(self): self._test_tokenaware_one_node_down( keyspace='test_rfthree_tokenaware', rf=3, accepted=set([ConsistencyLevel.ANY, ConsistencyLevel.ONE, ConsistencyLevel.TWO, ConsistencyLevel.QUORUM])) def test_rfthree_tokenaware_none_down(self): keyspace = 'test_rfthree_tokenaware_none_down' - cluster = Cluster( - load_balancing_policy=TokenAwarePolicy(RoundRobinPolicy()), - protocol_version=PROTOCOL_VERSION) + cluster = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(TokenAwarePolicy(RoundRobinPolicy()))} + ) session = cluster.connect(wait_for_all_pools=True) wait_for_up(cluster, 1) wait_for_up(cluster, 2) create_schema(cluster, session, keyspace, replication_factor=3) self._insert(session, keyspace, count=1) self._query(session, keyspace, count=1) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 1) self.coordinator_stats.assert_query_count_equals(self, 3, 0) self.coordinator_stats.reset_counts() self._assert_writes_succeed(session, keyspace, SINGLE_DC_CONSISTENCY_LEVELS) self._assert_reads_succeed(session, keyspace, SINGLE_DC_CONSISTENCY_LEVELS - set([ConsistencyLevel.ANY]), expected_reader=2) cluster.shutdown() def _test_downgrading_cl(self, keyspace, rf, accepted): - cluster = Cluster( - load_balancing_policy=TokenAwarePolicy(RoundRobinPolicy()), - default_retry_policy=DowngradingConsistencyRetryPolicy(), - protocol_version=PROTOCOL_VERSION) + cluster = TestCluster(execution_profiles={ + EXEC_PROFILE_DEFAULT: ExecutionProfile(TokenAwarePolicy(RoundRobinPolicy()), + DowngradingConsistencyRetryPolicy()) + }) session = cluster.connect(wait_for_all_pools=True) create_schema(cluster, session, keyspace, replication_factor=rf) self._insert(session, keyspace, 1) self._query(session, keyspace, 1) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 1) self.coordinator_stats.assert_query_count_equals(self, 3, 0) try: force_stop(2) wait_for_down(cluster, 2) self._assert_writes_succeed(session, keyspace, accepted) self._assert_reads_succeed(session, keyspace, accepted - set([ConsistencyLevel.ANY])) self._assert_writes_fail(session, keyspace, SINGLE_DC_CONSISTENCY_LEVELS - accepted) self._assert_reads_fail(session, keyspace, SINGLE_DC_CONSISTENCY_LEVELS - accepted) finally: start(2) wait_for_up(cluster, 2) cluster.shutdown() def test_rfone_downgradingcl(self): self._test_downgrading_cl( keyspace='test_rfone_downgradingcl', rf=1, accepted=set([ConsistencyLevel.ANY])) def test_rftwo_downgradingcl(self): self._test_downgrading_cl( keyspace='test_rftwo_downgradingcl', rf=2, accepted=SINGLE_DC_CONSISTENCY_LEVELS) def test_rfthree_roundrobin_downgradingcl(self): keyspace = 'test_rfthree_roundrobin_downgradingcl' - cluster = Cluster( - load_balancing_policy=RoundRobinPolicy(), - default_retry_policy=DowngradingConsistencyRetryPolicy(), - protocol_version=PROTOCOL_VERSION) - self.rfthree_downgradingcl(cluster, keyspace, True) + with TestCluster(execution_profiles={ + EXEC_PROFILE_DEFAULT: ExecutionProfile(RoundRobinPolicy(), + DowngradingConsistencyRetryPolicy()) + }) as cluster: + self.rfthree_downgradingcl(cluster, keyspace, True) def test_rfthree_tokenaware_downgradingcl(self): keyspace = 'test_rfthree_tokenaware_downgradingcl' - cluster = Cluster( - load_balancing_policy=TokenAwarePolicy(RoundRobinPolicy()), - default_retry_policy=DowngradingConsistencyRetryPolicy(), - protocol_version=PROTOCOL_VERSION) - self.rfthree_downgradingcl(cluster, keyspace, False) + with TestCluster(execution_profiles={ + EXEC_PROFILE_DEFAULT: ExecutionProfile(TokenAwarePolicy(RoundRobinPolicy()), + DowngradingConsistencyRetryPolicy()) + }) as cluster: + self.rfthree_downgradingcl(cluster, keyspace, False) def rfthree_downgradingcl(self, cluster, keyspace, roundrobin): session = cluster.connect(wait_for_all_pools=True) create_schema(cluster, session, keyspace, replication_factor=2) self._insert(session, keyspace, count=12) self._query(session, keyspace, count=12) if roundrobin: self.coordinator_stats.assert_query_count_equals(self, 1, 4) self.coordinator_stats.assert_query_count_equals(self, 2, 4) self.coordinator_stats.assert_query_count_equals(self, 3, 4) else: self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 12) self.coordinator_stats.assert_query_count_equals(self, 3, 0) try: self.coordinator_stats.reset_counts() force_stop(2) wait_for_down(cluster, 2) self._assert_writes_succeed(session, keyspace, SINGLE_DC_CONSISTENCY_LEVELS) # Test reads that expected to complete successfully for cl in SINGLE_DC_CONSISTENCY_LEVELS - set([ConsistencyLevel.ANY]): self.coordinator_stats.reset_counts() self._query(session, keyspace, 12, consistency_level=cl) if roundrobin: self.coordinator_stats.assert_query_count_equals(self, 1, 6) self.coordinator_stats.assert_query_count_equals(self, 2, 0) self.coordinator_stats.assert_query_count_equals(self, 3, 6) else: self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 0) self.coordinator_stats.assert_query_count_equals(self, 3, 12) finally: start(2) wait_for_up(cluster, 2) session.cluster.shutdown() # TODO: can't be done in this class since we reuse the ccm cluster # instead we should create these elsewhere # def test_rfthree_downgradingcl_twodcs(self): # def test_rfthree_downgradingcl_twodcs_dcaware(self): class ConnectivityTest(unittest.TestCase): def get_node_not_x(self, node_to_stop): nodes = [1, 2, 3] for num in nodes: if num is not node_to_stop: return num def test_pool_with_host_down(self): """ Test to ensure that cluster.connect() doesn't return prior to pools being initialized. This test will figure out which host our pool logic will connect to first. It then shuts that server down. Previously the cluster.connect() would return prior to the pools being initialized, and the first queries would return a no host exception @since 3.7.0 @jira_ticket PYTHON-617 @expected_result query should complete successfully @test_category connection """ # find the first node, we will try create connections to, shut it down. # We will be shuting down a random house, so we need a complete contact list all_contact_points = ["127.0.0.1", "127.0.0.2", "127.0.0.3"] # Connect up and find out which host will bet queries routed to to first - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() cluster.connect(wait_for_all_pools=True) hosts = cluster.metadata.all_hosts() address = hosts[0].address node_to_stop = int(address.split('.')[-1:][0]) cluster.shutdown() # We now register a cluster that has it's Control Connection NOT on the node that we are shutting down. # We do this so we don't miss the event contact_point = '127.0.0.{0}'.format(self.get_node_not_x(node_to_stop)) - cluster = Cluster(contact_points=[contact_point], protocol_version=PROTOCOL_VERSION) + cluster = TestCluster(contact_points=[contact_point]) cluster.connect(wait_for_all_pools=True) try: force_stop(node_to_stop) wait_for_down(cluster, node_to_stop) # Attempt a query against that node. It should complete - cluster2 = Cluster(contact_points=all_contact_points, protocol_version=PROTOCOL_VERSION) + cluster2 = TestCluster(contact_points=all_contact_points) session2 = cluster2.connect() session2.execute("SELECT * FROM system.local") finally: cluster2.shutdown() start(node_to_stop) wait_for_up(cluster, node_to_stop) cluster.shutdown() diff --git a/tests/integration/long/test_failure_types.py b/tests/integration/long/test_failure_types.py index a67c05a..6bdff8d 100644 --- a/tests/integration/long/test_failure_types.py +++ b/tests/integration/long/test_failure_types.py @@ -1,395 +1,411 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -import sys,logging, traceback, time, re +import logging +import sys +import traceback +import time +from packaging.version import Version + +from mock import Mock -from cassandra import (ConsistencyLevel, OperationTimedOut, ReadTimeout, WriteTimeout, ReadFailure, WriteFailure, - FunctionFailure, ProtocolVersion) -from cassandra.cluster import Cluster, NoHostAvailable, ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.policies import HostFilterPolicy, RoundRobinPolicy +from cassandra import ( + ConsistencyLevel, OperationTimedOut, ReadTimeout, WriteTimeout, ReadFailure, WriteFailure, + FunctionFailure, ProtocolVersion, +) +from cassandra.cluster import ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.concurrent import execute_concurrent_with_args from cassandra.query import SimpleStatement -from tests.integration import use_singledc, PROTOCOL_VERSION, get_cluster, setup_keyspace, remove_cluster, get_node, \ - requiresmallclockgranularity -from mock import Mock +from tests.integration import ( + use_singledc, PROTOCOL_VERSION, get_cluster, setup_keyspace, remove_cluster, + get_node, start_cluster_wait_for_up, requiresmallclockgranularity, + local, CASSANDRA_VERSION, TestCluster) + try: import unittest2 as unittest except ImportError: import unittest log = logging.getLogger(__name__) +@local def setup_module(): """ We need some custom setup for this module. All unit tests in this module require protocol >=4. We won't bother going through the setup required unless that is the protocol version we are using. """ # If we aren't at protocol v 4 or greater don't waste time setting anything up, all tests will be skipped if PROTOCOL_VERSION >= 4: use_singledc(start=False) ccm_cluster = get_cluster() ccm_cluster.stop() - config_options = {'tombstone_failure_threshold': 2000, 'tombstone_warn_threshold': 1000} + config_options = { + 'tombstone_failure_threshold': 2000, + 'tombstone_warn_threshold': 1000, + } ccm_cluster.set_configuration_options(config_options) - ccm_cluster.start(wait_for_binary_proto=True, wait_other_notice=True) + start_cluster_wait_for_up(ccm_cluster) setup_keyspace() def teardown_module(): """ The rest of the tests don't need custom tombstones remove the cluster so as to not interfere with other tests. """ if PROTOCOL_VERSION >= 4: remove_cluster() class ClientExceptionTests(unittest.TestCase): def setUp(self): """ Test is skipped if run with native protocol version <4 """ if PROTOCOL_VERSION < 4: raise unittest.SkipTest( "Native protocol 4,0+ is required for custom payloads, currently using %r" % (PROTOCOL_VERSION,)) - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + self.cluster = TestCluster() self.session = self.cluster.connect() self.nodes_currently_failing = [] self.node1, self.node2, self.node3 = get_cluster().nodes.values() def tearDown(self): self.cluster.shutdown() failing_nodes = [] # Restart the nodes to fully functional again self.setFailingNodes(failing_nodes, "testksfail") def execute_helper(self, session, query): tries = 0 while tries < 100: try: return session.execute(query) except OperationTimedOut: ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb tries += 1 raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(query)) def execute_concurrent_args_helper(self, session, query, params): tries = 0 while tries < 100: try: return execute_concurrent_with_args(session, query, params, concurrency=50) except (ReadTimeout, WriteTimeout, OperationTimedOut, ReadFailure, WriteFailure): ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb tries += 1 raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(query)) def setFailingNodes(self, failing_nodes, keyspace): """ This method will take in a set of failing nodes, and toggle all of the nodes in the provided list to fail writes. @param failing_nodes A definitive list of nodes that should fail writes @param keyspace The keyspace to enable failures on """ # Ensure all of the nodes on the list have failures enabled for node in failing_nodes: if node not in self.nodes_currently_failing: node.stop(wait_other_notice=True, gently=False) node.start(jvm_args=[" -Dcassandra.test.fail_writes_ks=" + keyspace], wait_for_binary_proto=True, wait_other_notice=True) self.nodes_currently_failing.append(node) # Ensure all nodes not on the list, but that are currently set to failing are enabled for node in self.nodes_currently_failing: if node not in failing_nodes: node.stop(wait_other_notice=True, gently=True) node.start(wait_for_binary_proto=True, wait_other_notice=True) self.nodes_currently_failing.remove(node) def _perform_cql_statement(self, text, consistency_level, expected_exception, session=None): """ Simple helper method to preform cql statements and check for expected exception @param text CQl statement to execute @param consistency_level Consistency level at which it is to be executed @param expected_exception Exception expected to be throw or none """ if session is None: session = self.session statement = SimpleStatement(text) statement.consistency_level = consistency_level if expected_exception is None: self.execute_helper(session, statement) else: with self.assertRaises(expected_exception) as cm: self.execute_helper(session, statement) if ProtocolVersion.uses_error_code_map(PROTOCOL_VERSION): if isinstance(cm.exception, ReadFailure): self.assertEqual(list(cm.exception.error_code_map.values())[0], 1) if isinstance(cm.exception, WriteFailure): self.assertEqual(list(cm.exception.error_code_map.values())[0], 0) def test_write_failures_from_coordinator(self): """ Test to validate that write failures from the coordinator are surfaced appropriately. test_write_failures_from_coordinator Enable write failures on the various nodes using a custom jvm flag, cassandra.test.fail_writes_ks. This will cause writes to fail on that specific node. Depending on the replication factor of the keyspace, and the consistency level, we will expect the coordinator to send WriteFailure, or not. @since 2.6.0, 3.7.0 @jira_ticket PYTHON-238, PYTHON-619 @expected_result Appropriate write failures from the coordinator @test_category queries:basic """ # Setup temporary keyspace. self._perform_cql_statement( """ CREATE KEYSPACE testksfail WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '3'} """, consistency_level=ConsistencyLevel.ALL, expected_exception=None) # create table self._perform_cql_statement( """ CREATE TABLE testksfail.test ( k int PRIMARY KEY, v int ) """, consistency_level=ConsistencyLevel.ALL, expected_exception=None) # Disable one node failing_nodes = [self.node1] self.setFailingNodes(failing_nodes, "testksfail") # With one node disabled we would expect a write failure with ConsistencyLevel of all self._perform_cql_statement( """ INSERT INTO testksfail.test (k, v) VALUES (1, 0 ) """, consistency_level=ConsistencyLevel.ALL, expected_exception=WriteFailure) # We have two nodes left so a write with consistency level of QUORUM should complete as expected self._perform_cql_statement( """ INSERT INTO testksfail.test (k, v) VALUES (1, 0 ) """, consistency_level=ConsistencyLevel.QUORUM, expected_exception=None) failing_nodes = [] # Restart the nodes to fully functional again self.setFailingNodes(failing_nodes, "testksfail") # Drop temporary keyspace self._perform_cql_statement( """ DROP KEYSPACE testksfail """, consistency_level=ConsistencyLevel.ANY, expected_exception=None) def test_tombstone_overflow_read_failure(self): """ Test to validate that a ReadFailure is returned from the node when a specified threshold of tombstombs is reached. test_tombstomb_overflow_read_failure First sets the tombstone failure threshold down to a level that allows it to be more easily encountered. We then create some wide rows and ensure they are deleted appropriately. This produces the correct amount of tombstombs. Upon making a simple query we expect to get a read failure back from the coordinator. @since 2.6.0, 3.7.0 @jira_ticket PYTHON-238, PYTHON-619 @expected_result Appropriate write failures from the coordinator @test_category queries:basic """ # Setup table for "wide row" self._perform_cql_statement( """ CREATE TABLE test3rf.test2 ( k int, v0 int, v1 int, PRIMARY KEY (k,v0)) """, consistency_level=ConsistencyLevel.ALL, expected_exception=None) statement = self.session.prepare("INSERT INTO test3rf.test2 (k, v0,v1) VALUES (1,?,1)") parameters = [(x,) for x in range(3000)] self.execute_concurrent_args_helper(self.session, statement, parameters) - statement = self.session.prepare("DELETE v1 FROM test3rf.test2 WHERE k = 1 AND v0 =?") + column = 'v1' if CASSANDRA_VERSION < Version('4.0') else '' + statement = self.session.prepare("DELETE {} FROM test3rf.test2 WHERE k = 1 AND v0 =?".format(column)) parameters = [(x,) for x in range(2001)] self.execute_concurrent_args_helper(self.session, statement, parameters) self._perform_cql_statement( """ SELECT * FROM test3rf.test2 WHERE k = 1 """, consistency_level=ConsistencyLevel.ALL, expected_exception=ReadFailure) self._perform_cql_statement( """ DROP TABLE test3rf.test2; """, consistency_level=ConsistencyLevel.ALL, expected_exception=None) def test_user_function_failure(self): """ Test to validate that exceptions in user defined function are correctly surfaced by the driver to us. test_user_function_failure First creates a table to use for testing. Then creates a function that will throw an exception when invoked. It then invokes the function and expects a FunctionException. Finally it preforms cleanup operations. @since 2.6.0 @jira_ticket PYTHON-238 @expected_result Function failures when UDF throws exception @test_category queries:basic """ # create UDF that throws an exception self._perform_cql_statement( """ CREATE FUNCTION test3rf.test_failure(d double) RETURNS NULL ON NULL INPUT RETURNS double LANGUAGE java AS 'throw new RuntimeException("failure");'; """, consistency_level=ConsistencyLevel.ALL, expected_exception=None) # Create test table self._perform_cql_statement( """ CREATE TABLE test3rf.d (k int PRIMARY KEY , d double); """, consistency_level=ConsistencyLevel.ALL, expected_exception=None) # Insert some values self._perform_cql_statement( """ INSERT INTO test3rf.d (k,d) VALUES (0, 5.12); """, consistency_level=ConsistencyLevel.ALL, expected_exception=None) # Run the function expect a function failure exception self._perform_cql_statement( """ SELECT test_failure(d) FROM test3rf.d WHERE k = 0; """, consistency_level=ConsistencyLevel.ALL, expected_exception=FunctionFailure) self._perform_cql_statement( """ DROP FUNCTION test3rf.test_failure; """, consistency_level=ConsistencyLevel.ALL, expected_exception=None) self._perform_cql_statement( """ DROP TABLE test3rf.d; """, consistency_level=ConsistencyLevel.ALL, expected_exception=None) @requiresmallclockgranularity class TimeoutTimerTest(unittest.TestCase): def setUp(self): """ Setup sessions and pause node1 """ - - # self.node1, self.node2, self.node3 = get_cluster().nodes.values() - - node1 = ExecutionProfile( - load_balancing_policy=HostFilterPolicy( - RoundRobinPolicy(), lambda host: host.address == "127.0.0.1" - ) + self.cluster = TestCluster( + execution_profiles={ + EXEC_PROFILE_DEFAULT: ExecutionProfile( + load_balancing_policy=HostFilterPolicy( + RoundRobinPolicy(), lambda host: host.address == "127.0.0.1" + ) + ) + } ) - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, execution_profiles={EXEC_PROFILE_DEFAULT: node1}) + self.session = self.cluster.connect(wait_for_all_pools=True) self.control_connection_host_number = 1 self.node_to_stop = get_node(self.control_connection_host_number) ddl = ''' CREATE TABLE test3rf.timeout ( k int PRIMARY KEY, v int )''' self.session.execute(ddl) self.node_to_stop.pause() def tearDown(self): """ Shutdown cluster and resume node1 """ self.node_to_stop.resume() self.session.execute("DROP TABLE test3rf.timeout") self.cluster.shutdown() def test_async_timeouts(self): """ Test to validate that timeouts are honored Exercise the underlying timeouts, by attempting a query that will timeout. Ensure the default timeout is still honored. Make sure that user timeouts are also honored. @since 2.7.0 @jira_ticket PYTHON-108 @expected_result timeouts should be honored @test_category """ # Because node1 is stopped these statements will all timeout ss = SimpleStatement('SELECT * FROM test3rf.test', consistency_level=ConsistencyLevel.ALL) # Test with default timeout (should be 10) start_time = time.time() future = self.session.execute_async(ss) with self.assertRaises(OperationTimedOut): future.result() end_time = time.time() total_time = end_time-start_time - expected_time = self.session.default_timeout + expected_time = self.cluster.profile_manager.default.request_timeout # check timeout and ensure it's within a reasonable range self.assertAlmostEqual(expected_time, total_time, delta=.05) # Test with user defined timeout (Should be 1) + expected_time = 1 start_time = time.time() - future = self.session.execute_async(ss, timeout=1) + future = self.session.execute_async(ss, timeout=expected_time) mock_callback = Mock(return_value=None) mock_errorback = Mock(return_value=None) future.add_callback(mock_callback) future.add_errback(mock_errorback) with self.assertRaises(OperationTimedOut): future.result() end_time = time.time() total_time = end_time-start_time - expected_time = 1 # check timeout and ensure it's within a reasonable range self.assertAlmostEqual(expected_time, total_time, delta=.05) self.assertTrue(mock_errorback.called) self.assertFalse(mock_callback.called) diff --git a/tests/integration/long/test_ipv6.py b/tests/integration/long/test_ipv6.py index 5f2bdbd..a49c167 100644 --- a/tests/integration/long/test_ipv6.py +++ b/tests/integration/long/test_ipv6.py @@ -1,124 +1,123 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os, socket, errno from ccmlib import common -from cassandra.cluster import Cluster, NoHostAvailable +from cassandra.cluster import NoHostAvailable from cassandra.io.asyncorereactor import AsyncoreConnection from tests import is_monkey_patched -from tests.integration import use_cluster, remove_cluster, PROTOCOL_VERSION +from tests.integration import use_cluster, remove_cluster, TestCluster if is_monkey_patched(): LibevConnection = -1 AsyncoreConnection = -1 else: try: from cassandra.io.libevreactor import LibevConnection except ImportError: LibevConnection = None try: import unittest2 as unittest except ImportError: import unittest # noqa # If more modules do IPV6 testing, this can be moved down to integration.__init__. # For now, just keeping the clutter here IPV6_CLUSTER_NAME = 'ipv6_test_cluster' def setup_module(module): if os.name != "nt": validate_host_viable() # We use a dedicated cluster (instead of common singledc, as in other tests) because # it's most likely that the test host will only have one local ipv6 address (::1) # singledc has three use_cluster(IPV6_CLUSTER_NAME, [1], ipformat='::%d') def teardown_module(): remove_cluster() def validate_ccm_viable(): try: common.normalize_interface(('::1', 0)) except: raise unittest.SkipTest('this version of ccm does not support ipv6') def validate_host_viable(): # this is something ccm does when starting, but preemptively check to avoid # spinning up the cluster if it's not going to work try: common.assert_socket_available(('::1', 9042)) except: raise unittest.SkipTest('failed binding ipv6 loopback ::1 on 9042') class IPV6ConnectionTest(object): connection_class = None def test_connect(self): - cluster = Cluster(connection_class=self.connection_class, contact_points=['::1'], connect_timeout=10, - protocol_version=PROTOCOL_VERSION) + cluster = TestCluster(connection_class=self.connection_class, contact_points=['::1'], connect_timeout=10) session = cluster.connect() future = session.execute_async("SELECT * FROM system.local") future.result() self.assertEqual(future._current_host.address, '::1') cluster.shutdown() def test_error(self): - cluster = Cluster(connection_class=self.connection_class, contact_points=['::1'], port=9043, - connect_timeout=10, protocol_version=PROTOCOL_VERSION) + cluster = TestCluster(connection_class=self.connection_class, contact_points=['::1'], port=9043, + connect_timeout=10) self.assertRaisesRegexp(NoHostAvailable, '\(\'Unable to connect.*%s.*::1\', 9043.*Connection refused.*' % errno.ECONNREFUSED, cluster.connect) def test_error_multiple(self): if len(socket.getaddrinfo('localhost', 9043, socket.AF_UNSPEC, socket.SOCK_STREAM)) < 2: raise unittest.SkipTest('localhost only resolves one address') - cluster = Cluster(connection_class=self.connection_class, contact_points=['localhost'], port=9043, - connect_timeout=10, protocol_version=PROTOCOL_VERSION) + cluster = TestCluster(connection_class=self.connection_class, contact_points=['localhost'], port=9043, + connect_timeout=10) self.assertRaisesRegexp(NoHostAvailable, '\(\'Unable to connect.*Tried connecting to \[\(.*\(.*\].*Last error', cluster.connect) class LibevConnectionTests(IPV6ConnectionTest, unittest.TestCase): connection_class = LibevConnection def setUp(self): if os.name == "nt": raise unittest.SkipTest("IPv6 is currently not supported under Windows") if LibevConnection == -1: raise unittest.SkipTest("Can't test libev with monkey patching") elif LibevConnection is None: raise unittest.SkipTest("Libev does not appear to be installed properly") class AsyncoreConnectionTests(IPV6ConnectionTest, unittest.TestCase): connection_class = AsyncoreConnection def setUp(self): if os.name == "nt": raise unittest.SkipTest("IPv6 is currently not supported under Windows") if AsyncoreConnection == -1: raise unittest.SkipTest("Can't test asyncore with monkey patching") diff --git a/tests/integration/long/test_large_data.py b/tests/integration/long/test_large_data.py index 76cafa0..ce7e439 100644 --- a/tests/integration/long/test_large_data.py +++ b/tests/integration/long/test_large_data.py @@ -1,275 +1,274 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: from Queue import Queue, Empty except ImportError: from queue import Queue, Empty # noqa from struct import pack import logging, sys, traceback, time from cassandra import ConsistencyLevel, OperationTimedOut, WriteTimeout -from cassandra.cluster import Cluster +from cassandra.cluster import ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.query import dict_factory from cassandra.query import SimpleStatement -from tests.integration import use_singledc, PROTOCOL_VERSION +from tests.integration import use_singledc, PROTOCOL_VERSION, TestCluster from tests.integration.long.utils import create_schema try: import unittest2 as unittest except ImportError: import unittest # noqa log = logging.getLogger(__name__) def setup_module(): use_singledc() # Converts an integer to an string of letters def create_column_name(i): letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] column_name = '' while True: column_name += letters[i % 10] i = i // 10 if not i: break if column_name == 'if': column_name = 'special_case' return column_name class LargeDataTests(unittest.TestCase): def setUp(self): self.keyspace = 'large_data' def make_session_and_keyspace(self): - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster(execution_profiles={ + EXEC_PROFILE_DEFAULT: ExecutionProfile(request_timeout=20, row_factory=dict_factory) + }) session = cluster.connect() - session.default_timeout = 20.0 # increase the default timeout - session.row_factory = dict_factory - create_schema(cluster, session, self.keyspace) return session def batch_futures(self, session, statement_generator): concurrency = 10 futures = Queue(maxsize=concurrency) number_of_timeouts = 0 for i, statement in enumerate(statement_generator): if i > 0 and i % (concurrency - 1) == 0: # clear the existing queue while True: try: futures.get_nowait().result() except (OperationTimedOut, WriteTimeout): ex_type, ex, tb = sys.exc_info() number_of_timeouts += 1 log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb time.sleep(1) except Empty: break future = session.execute_async(statement) futures.put_nowait(future) while True: try: futures.get_nowait().result() except (OperationTimedOut, WriteTimeout): ex_type, ex, tb = sys.exc_info() number_of_timeouts += 1 log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb time.sleep(1) except Empty: break return number_of_timeouts def test_wide_rows(self): table = 'wide_rows' session = self.make_session_and_keyspace() session.execute('CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))' % table) prepared = session.prepare('INSERT INTO %s (k, i) VALUES (0, ?)' % (table, )) # Write via async futures self.batch_futures(session, (prepared.bind((i, )) for i in range(100000))) # Read results = session.execute('SELECT i FROM %s WHERE k=0' % (table, )) # Verify for i, row in enumerate(results): self.assertAlmostEqual(row['i'], i, delta=3) session.cluster.shutdown() def test_wide_batch_rows(self): """ Test for inserting wide rows with batching test_wide_batch_rows tests inserting a wide row of data using batching. It will then attempt to query that data and ensure that all of it has been inserted appropriately. @expected_result all items should be inserted, and verified. @test_category queries:batch """ # Table Creation table = 'wide_batch_rows' session = self.make_session_and_keyspace() session.execute('CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))' % table) # Run batch insert statement = 'BEGIN BATCH ' to_insert = 2000 for i in range(to_insert): statement += 'INSERT INTO %s (k, i) VALUES (%s, %s) ' % (table, 0, i) statement += 'APPLY BATCH' statement = SimpleStatement(statement, consistency_level=ConsistencyLevel.QUORUM) # Execute insert with larger timeout, since it's a wide row try: session.execute(statement,timeout=30.0) except OperationTimedOut: #If we timeout on insertion that's bad but it could be just slow underlying c* #Attempt to validate anyway, we will fail if we don't get the right data back. ex_type, ex, tb = sys.exc_info() log.warning("Batch wide row insertion timed out, this may require additional investigation") log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb # Verify results = session.execute('SELECT i FROM %s WHERE k=%s' % (table, 0)) lastvalue = 0 for j, row in enumerate(results): lastValue=row['i'] self.assertEqual(lastValue, j) #check the last value make sure it's what we expect index_value = to_insert-1 self.assertEqual(lastValue,index_value,"Verification failed only found {0} inserted we were expecting {1}".format(j,index_value)) session.cluster.shutdown() def test_wide_byte_rows(self): """ Test for inserting wide row of bytes test_wide_batch_rows tests inserting a wide row of data bytes. It will then attempt to query that data and ensure that all of it has been inserted appropriately. @expected_result all items should be inserted, and verified. @test_category queries """ # Table creation table = 'wide_byte_rows' session = self.make_session_and_keyspace() session.execute('CREATE TABLE %s (k INT, i INT, v BLOB, PRIMARY KEY(k, i))' % table) # Prepare statement and run insertions to_insert = 100000 prepared = session.prepare('INSERT INTO %s (k, i, v) VALUES (0, ?, 0xCAFE)' % (table, )) timeouts = self.batch_futures(session, (prepared.bind((i, )) for i in range(to_insert))) # Read results = session.execute('SELECT i, v FROM %s WHERE k=0' % (table, )) # number of expected results expected_results = to_insert-timeouts-1 # Verify bb = pack('>H', 0xCAFE) for i, row in enumerate(results): self.assertEqual(row['v'], bb) self.assertGreaterEqual(i, expected_results, "Verification failed only found {0} inserted we were expecting {1}".format(i,expected_results)) session.cluster.shutdown() def test_large_text(self): """ Test for inserting a large text field test_large_text tests inserting a large text field into a row. @expected_result the large text value should be inserted. When the row is queried it should match the original value that was inserted @test_category queries """ table = 'large_text' session = self.make_session_and_keyspace() session.execute('CREATE TABLE %s (k int PRIMARY KEY, txt text)' % table) # Create ultra-long text text = 'a' * 1000000 # Write session.execute(SimpleStatement("INSERT INTO %s (k, txt) VALUES (%s, '%s')" % (table, 0, text), consistency_level=ConsistencyLevel.QUORUM)) # Read result = session.execute('SELECT * FROM %s WHERE k=%s' % (table, 0)) # Verify found_result = False for i, row in enumerate(result): self.assertEqual(row['txt'], text) found_result = True self.assertTrue(found_result, "No results were found") session.cluster.shutdown() def test_wide_table(self): table = 'wide_table' table_width = 330 session = self.make_session_and_keyspace() table_declaration = 'CREATE TABLE %s (key INT PRIMARY KEY, ' table_declaration += ' INT, '.join(create_column_name(i) for i in range(table_width)) table_declaration += ' INT)' session.execute(table_declaration % table) # Write insert_statement = 'INSERT INTO %s (key, ' insert_statement += ', '.join(create_column_name(i) for i in range(table_width)) insert_statement += ') VALUES (%s, ' insert_statement += ', '.join(str(i) for i in range(table_width)) insert_statement += ')' insert_statement = insert_statement % (table, 0) session.execute(SimpleStatement(insert_statement, consistency_level=ConsistencyLevel.QUORUM)) # Read result = session.execute('SELECT * FROM %s WHERE key=%s' % (table, 0)) # Verify for row in result: for i in range(table_width): self.assertEqual(row[create_column_name(i)], i) session.cluster.shutdown() diff --git a/tests/integration/long/test_loadbalancingpolicies.py b/tests/integration/long/test_loadbalancingpolicies.py index 2cc3d8e..f245569 100644 --- a/tests/integration/long/test_loadbalancingpolicies.py +++ b/tests/integration/long/test_loadbalancingpolicies.py @@ -1,737 +1,778 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import struct import sys import traceback +from cassandra import cqltypes from cassandra import ConsistencyLevel, Unavailable, OperationTimedOut, ReadTimeout, ReadFailure, \ WriteTimeout, WriteFailure -from cassandra.cluster import Cluster, NoHostAvailable +from cassandra.cluster import NoHostAvailable, ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.concurrent import execute_concurrent_with_args from cassandra.metadata import murmur3 -from cassandra.policies import (RoundRobinPolicy, DCAwareRoundRobinPolicy, - TokenAwarePolicy, WhiteListRoundRobinPolicy, - HostFilterPolicy) +from cassandra.policies import ( + RoundRobinPolicy, DCAwareRoundRobinPolicy, + TokenAwarePolicy, WhiteListRoundRobinPolicy, + HostFilterPolicy +) from cassandra.query import SimpleStatement -from tests.integration import use_singledc, use_multidc, remove_cluster, PROTOCOL_VERSION +from tests.integration import use_singledc, use_multidc, remove_cluster, TestCluster, greaterthanorequalcass40, notdse from tests.integration.long.utils import (wait_for_up, create_schema, CoordinatorStats, force_stop, wait_for_down, decommission, start, bootstrap, stop, IP_FORMAT) try: import unittest2 as unittest except ImportError: import unittest # noqa log = logging.getLogger(__name__) class LoadBalancingPolicyTests(unittest.TestCase): def setUp(self): remove_cluster() # clear ahead of test so it doesn't use one left in unknown state self.coordinator_stats = CoordinatorStats() self.prepared = None self.probe_cluster = None def tearDown(self): if self.probe_cluster: self.probe_cluster.shutdown() @classmethod def teardown_class(cls): remove_cluster() def _connect_probe_cluster(self): if not self.probe_cluster: # distinct cluster so we can see the status of nodes ignored by the LBP being tested - self.probe_cluster = Cluster(load_balancing_policy=RoundRobinPolicy(), - schema_metadata_enabled=False, token_metadata_enabled=False) + self.probe_cluster = TestCluster( + schema_metadata_enabled=False, + token_metadata_enabled=False, + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(load_balancing_policy=RoundRobinPolicy())} + ) self.probe_session = self.probe_cluster.connect() def _wait_for_nodes_up(self, nodes, cluster=None): log.debug('entered: _wait_for_nodes_up(nodes={ns}, ' 'cluster={cs})'.format(ns=nodes, cs=cluster)) if not cluster: log.debug('connecting to cluster') self._connect_probe_cluster() cluster = self.probe_cluster for n in nodes: wait_for_up(cluster, n) def _wait_for_nodes_down(self, nodes, cluster=None): log.debug('entered: _wait_for_nodes_down(nodes={ns}, ' 'cluster={cs})'.format(ns=nodes, cs=cluster)) if not cluster: self._connect_probe_cluster() cluster = self.probe_cluster for n in nodes: wait_for_down(cluster, n) def _cluster_session_with_lbp(self, lbp): # create a cluster with no delay on events - cluster = Cluster(load_balancing_policy=lbp, protocol_version=PROTOCOL_VERSION, - topology_event_refresh_window=0, status_event_refresh_window=0) + + cluster = TestCluster(topology_event_refresh_window=0, status_event_refresh_window=0, + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(load_balancing_policy=lbp)}) session = cluster.connect() return cluster, session def _insert(self, session, keyspace, count=12, consistency_level=ConsistencyLevel.ONE): log.debug('entered _insert(' 'session={session}, keyspace={keyspace}, ' 'count={count}, consistency_level={consistency_level}' ')'.format(session=session, keyspace=keyspace, count=count, consistency_level=consistency_level)) session.execute('USE %s' % keyspace) ss = SimpleStatement('INSERT INTO cf(k, i) VALUES (0, 0)', consistency_level=consistency_level) tries = 0 while tries < 100: try: execute_concurrent_with_args(session, ss, [None] * count) log.debug('Completed _insert on try #{}'.format(tries + 1)) return except (OperationTimedOut, WriteTimeout, WriteFailure): ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb tries += 1 raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(ss)) def _query(self, session, keyspace, count=12, consistency_level=ConsistencyLevel.ONE, use_prepared=False): log.debug('entered _query(' 'session={session}, keyspace={keyspace}, ' 'count={count}, consistency_level={consistency_level}, ' 'use_prepared={use_prepared}' ')'.format(session=session, keyspace=keyspace, count=count, consistency_level=consistency_level, use_prepared=use_prepared)) if use_prepared: query_string = 'SELECT * FROM %s.cf WHERE k = ?' % keyspace if not self.prepared or self.prepared.query_string != query_string: self.prepared = session.prepare(query_string) self.prepared.consistency_level = consistency_level for i in range(count): tries = 0 while True: if tries > 100: raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(self.prepared)) try: self.coordinator_stats.add_coordinator(session.execute_async(self.prepared.bind((0,)))) break except (OperationTimedOut, ReadTimeout, ReadFailure): ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb tries += 1 else: routing_key = struct.pack('>i', 0) for i in range(count): ss = SimpleStatement('SELECT * FROM %s.cf WHERE k = 0' % keyspace, consistency_level=consistency_level, routing_key=routing_key) tries = 0 while True: if tries > 100: raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(ss)) try: self.coordinator_stats.add_coordinator(session.execute_async(ss)) break except (OperationTimedOut, ReadTimeout, ReadFailure): ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb tries += 1 def test_token_aware_is_used_by_default(self): """ - Test for default loadbalacing policy + Test for default load balancing policy test_token_aware_is_used_by_default tests that the default loadbalancing policy is policies.TokenAwarePolicy. It creates a simple Cluster and verifies that the default loadbalancing policy is TokenAwarePolicy if the murmur3 C extension is found. Otherwise, the default loadbalancing policy is DCAwareRoundRobinPolicy. @since 2.6.0 @jira_ticket PYTHON-160 @expected_result TokenAwarePolicy should be the default loadbalancing policy. @test_category load_balancing:token_aware """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() + self.addCleanup(cluster.shutdown) if murmur3 is not None: - self.assertTrue(isinstance(cluster.load_balancing_policy, TokenAwarePolicy)) + self.assertTrue(isinstance(cluster.profile_manager.default.load_balancing_policy, TokenAwarePolicy)) else: - self.assertTrue(isinstance(cluster.load_balancing_policy, DCAwareRoundRobinPolicy)) - - cluster.shutdown() + self.assertTrue(isinstance(cluster.profile_manager.default.load_balancing_policy, DCAwareRoundRobinPolicy)) def test_roundrobin(self): use_singledc() keyspace = 'test_roundrobin' cluster, session = self._cluster_session_with_lbp(RoundRobinPolicy()) + self.addCleanup(cluster.shutdown) + self._wait_for_nodes_up(range(1, 4), cluster) create_schema(cluster, session, keyspace, replication_factor=3) self._insert(session, keyspace) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 4) self.coordinator_stats.assert_query_count_equals(self, 2, 4) self.coordinator_stats.assert_query_count_equals(self, 3, 4) force_stop(3) self._wait_for_nodes_down([3], cluster) self.coordinator_stats.reset_counts() self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 6) self.coordinator_stats.assert_query_count_equals(self, 2, 6) self.coordinator_stats.assert_query_count_equals(self, 3, 0) decommission(1) start(3) self._wait_for_nodes_down([1], cluster) self._wait_for_nodes_up([3], cluster) self.coordinator_stats.reset_counts() self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 6) self.coordinator_stats.assert_query_count_equals(self, 3, 6) - cluster.shutdown() def test_roundrobin_two_dcs(self): use_multidc([2, 2]) keyspace = 'test_roundrobin_two_dcs' cluster, session = self._cluster_session_with_lbp(RoundRobinPolicy()) + self.addCleanup(cluster.shutdown) self._wait_for_nodes_up(range(1, 5), cluster) create_schema(cluster, session, keyspace, replication_strategy=[2, 2]) self._insert(session, keyspace) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 3) self.coordinator_stats.assert_query_count_equals(self, 2, 3) self.coordinator_stats.assert_query_count_equals(self, 3, 3) self.coordinator_stats.assert_query_count_equals(self, 4, 3) force_stop(1) bootstrap(5, 'dc3') # reset control connection self._insert(session, keyspace, count=1000) self._wait_for_nodes_up([5], cluster) self.coordinator_stats.reset_counts() self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 3) self.coordinator_stats.assert_query_count_equals(self, 3, 3) self.coordinator_stats.assert_query_count_equals(self, 4, 3) self.coordinator_stats.assert_query_count_equals(self, 5, 3) - cluster.shutdown() - def test_roundrobin_two_dcs_2(self): use_multidc([2, 2]) keyspace = 'test_roundrobin_two_dcs_2' cluster, session = self._cluster_session_with_lbp(RoundRobinPolicy()) + self.addCleanup(cluster.shutdown) self._wait_for_nodes_up(range(1, 5), cluster) create_schema(cluster, session, keyspace, replication_strategy=[2, 2]) self._insert(session, keyspace) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 3) self.coordinator_stats.assert_query_count_equals(self, 2, 3) self.coordinator_stats.assert_query_count_equals(self, 3, 3) self.coordinator_stats.assert_query_count_equals(self, 4, 3) force_stop(1) bootstrap(5, 'dc1') # reset control connection self._insert(session, keyspace, count=1000) self._wait_for_nodes_up([5], cluster) self.coordinator_stats.reset_counts() self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 3) self.coordinator_stats.assert_query_count_equals(self, 3, 3) self.coordinator_stats.assert_query_count_equals(self, 4, 3) self.coordinator_stats.assert_query_count_equals(self, 5, 3) - cluster.shutdown() - def test_dc_aware_roundrobin_two_dcs(self): use_multidc([3, 2]) keyspace = 'test_dc_aware_roundrobin_two_dcs' cluster, session = self._cluster_session_with_lbp(DCAwareRoundRobinPolicy('dc1')) + self.addCleanup(cluster.shutdown) self._wait_for_nodes_up(range(1, 6)) create_schema(cluster, session, keyspace, replication_strategy=[2, 2]) self._insert(session, keyspace) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 4) self.coordinator_stats.assert_query_count_equals(self, 2, 4) self.coordinator_stats.assert_query_count_equals(self, 3, 4) self.coordinator_stats.assert_query_count_equals(self, 4, 0) self.coordinator_stats.assert_query_count_equals(self, 5, 0) - cluster.shutdown() - def test_dc_aware_roundrobin_two_dcs_2(self): use_multidc([3, 2]) keyspace = 'test_dc_aware_roundrobin_two_dcs_2' cluster, session = self._cluster_session_with_lbp(DCAwareRoundRobinPolicy('dc2')) + self.addCleanup(cluster.shutdown) self._wait_for_nodes_up(range(1, 6)) create_schema(cluster, session, keyspace, replication_strategy=[2, 2]) self._insert(session, keyspace) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 0) self.coordinator_stats.assert_query_count_equals(self, 3, 0) self.coordinator_stats.assert_query_count_equals(self, 4, 6) self.coordinator_stats.assert_query_count_equals(self, 5, 6) - cluster.shutdown() - def test_dc_aware_roundrobin_one_remote_host(self): use_multidc([2, 2]) keyspace = 'test_dc_aware_roundrobin_one_remote_host' cluster, session = self._cluster_session_with_lbp(DCAwareRoundRobinPolicy('dc2', used_hosts_per_remote_dc=1)) + self.addCleanup(cluster.shutdown) self._wait_for_nodes_up(range(1, 5)) create_schema(cluster, session, keyspace, replication_strategy=[2, 2]) self._insert(session, keyspace) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 0) self.coordinator_stats.assert_query_count_equals(self, 3, 6) self.coordinator_stats.assert_query_count_equals(self, 4, 6) self.coordinator_stats.reset_counts() bootstrap(5, 'dc1') self._wait_for_nodes_up([5]) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 0) self.coordinator_stats.assert_query_count_equals(self, 3, 6) self.coordinator_stats.assert_query_count_equals(self, 4, 6) self.coordinator_stats.assert_query_count_equals(self, 5, 0) self.coordinator_stats.reset_counts() decommission(3) decommission(4) self._wait_for_nodes_down([3, 4]) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 3, 0) self.coordinator_stats.assert_query_count_equals(self, 4, 0) responses = set() for node in [1, 2, 5]: responses.add(self.coordinator_stats.get_query_count(node)) self.assertEqual(set([0, 0, 12]), responses) self.coordinator_stats.reset_counts() decommission(5) self._wait_for_nodes_down([5]) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 3, 0) self.coordinator_stats.assert_query_count_equals(self, 4, 0) self.coordinator_stats.assert_query_count_equals(self, 5, 0) responses = set() for node in [1, 2]: responses.add(self.coordinator_stats.get_query_count(node)) self.assertEqual(set([0, 12]), responses) self.coordinator_stats.reset_counts() decommission(1) self._wait_for_nodes_down([1]) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 12) self.coordinator_stats.assert_query_count_equals(self, 3, 0) self.coordinator_stats.assert_query_count_equals(self, 4, 0) self.coordinator_stats.assert_query_count_equals(self, 5, 0) self.coordinator_stats.reset_counts() force_stop(2) try: self._query(session, keyspace) self.fail() except NoHostAvailable: pass - cluster.shutdown() - def test_token_aware(self): keyspace = 'test_token_aware' self.token_aware(keyspace) def test_token_aware_prepared(self): keyspace = 'test_token_aware_prepared' self.token_aware(keyspace, True) def token_aware(self, keyspace, use_prepared=False): use_singledc() cluster, session = self._cluster_session_with_lbp(TokenAwarePolicy(RoundRobinPolicy())) + self.addCleanup(cluster.shutdown) self._wait_for_nodes_up(range(1, 4), cluster) create_schema(cluster, session, keyspace, replication_factor=1) self._insert(session, keyspace) self._query(session, keyspace, use_prepared=use_prepared) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 12) self.coordinator_stats.assert_query_count_equals(self, 3, 0) self.coordinator_stats.reset_counts() self._query(session, keyspace, use_prepared=use_prepared) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 12) self.coordinator_stats.assert_query_count_equals(self, 3, 0) self.coordinator_stats.reset_counts() force_stop(2) self._wait_for_nodes_down([2], cluster) try: self._query(session, keyspace, use_prepared=use_prepared) self.fail() except Unavailable as e: self.assertEqual(e.consistency, 1) self.assertEqual(e.required_replicas, 1) self.assertEqual(e.alive_replicas, 0) self.coordinator_stats.reset_counts() start(2) self._wait_for_nodes_up([2], cluster) self._query(session, keyspace, use_prepared=use_prepared) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 12) self.coordinator_stats.assert_query_count_equals(self, 3, 0) self.coordinator_stats.reset_counts() stop(2) self._wait_for_nodes_down([2], cluster) try: self._query(session, keyspace, use_prepared=use_prepared) self.fail() except Unavailable: pass self.coordinator_stats.reset_counts() start(2) self._wait_for_nodes_up([2], cluster) decommission(2) self._wait_for_nodes_down([2], cluster) self._query(session, keyspace, use_prepared=use_prepared) results = set([ self.coordinator_stats.get_query_count(1), self.coordinator_stats.get_query_count(3) ]) self.assertEqual(results, set([0, 12])) self.coordinator_stats.assert_query_count_equals(self, 2, 0) - cluster.shutdown() - def test_token_aware_composite_key(self): use_singledc() keyspace = 'test_token_aware_composite_key' table = 'composite' cluster, session = self._cluster_session_with_lbp(TokenAwarePolicy(RoundRobinPolicy())) + self.addCleanup(cluster.shutdown) self._wait_for_nodes_up(range(1, 4), cluster) create_schema(cluster, session, keyspace, replication_factor=2) session.execute('CREATE TABLE %s (' 'k1 int, ' 'k2 int, ' 'i int, ' 'PRIMARY KEY ((k1, k2)))' % table) prepared = session.prepare('INSERT INTO %s ' '(k1, k2, i) ' 'VALUES ' '(?, ?, ?)' % table) bound = prepared.bind((1, 2, 3)) result = session.execute(bound) self.assertIn(result.response_future.attempted_hosts[0], cluster.metadata.get_replicas(keyspace, bound.routing_key)) # There could be race condition with querying a node # which doesn't yet have the data so we query one of # the replicas results = session.execute(SimpleStatement('SELECT * FROM %s WHERE k1 = 1 AND k2 = 2' % table, routing_key=bound.routing_key)) self.assertIn(results.response_future.attempted_hosts[0], cluster.metadata.get_replicas(keyspace, bound.routing_key)) self.assertTrue(results[0].i) - cluster.shutdown() - def test_token_aware_with_rf_2(self, use_prepared=False): use_singledc() keyspace = 'test_token_aware_with_rf_2' cluster, session = self._cluster_session_with_lbp(TokenAwarePolicy(RoundRobinPolicy())) + self.addCleanup(cluster.shutdown) self._wait_for_nodes_up(range(1, 4), cluster) create_schema(cluster, session, keyspace, replication_factor=2) self._insert(session, keyspace) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 12) self.coordinator_stats.assert_query_count_equals(self, 3, 0) self.coordinator_stats.reset_counts() stop(2) self._wait_for_nodes_down([2], cluster) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 0) self.coordinator_stats.assert_query_count_equals(self, 3, 12) - cluster.shutdown() - def test_token_aware_with_local_table(self): use_singledc() cluster, session = self._cluster_session_with_lbp(TokenAwarePolicy(RoundRobinPolicy())) + self.addCleanup(cluster.shutdown) self._wait_for_nodes_up(range(1, 4), cluster) p = session.prepare("SELECT * FROM system.local WHERE key=?") # this would blow up prior to 61b4fad r = session.execute(p, ('local',)) self.assertEqual(r[0].key, 'local') - cluster.shutdown() - def test_token_aware_with_shuffle_rf2(self): """ Test to validate the hosts are shuffled when the `shuffle_replicas` is truthy @since 3.8 @jira_ticket PYTHON-676 @expected_result the request are spread across the replicas, when one of them is down, the requests target the available one @test_category policy """ keyspace = 'test_token_aware_with_rf_2' cluster, session = self._set_up_shuffle_test(keyspace, replication_factor=2) + self.addCleanup(cluster.shutdown) self._check_query_order_changes(session=session, keyspace=keyspace) # check TokenAwarePolicy still return the remaining replicas when one goes down self.coordinator_stats.reset_counts() stop(2) self._wait_for_nodes_down([2], cluster) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 0) self.coordinator_stats.assert_query_count_equals(self, 3, 12) - cluster.shutdown() - def test_token_aware_with_shuffle_rf3(self): """ Test to validate the hosts are shuffled when the `shuffle_replicas` is truthy @since 3.8 @jira_ticket PYTHON-676 @expected_result the request are spread across the replicas, when one of them is down, the requests target the other available ones @test_category policy """ keyspace = 'test_token_aware_with_rf_3' cluster, session = self._set_up_shuffle_test(keyspace, replication_factor=3) + self.addCleanup(cluster.shutdown) self._check_query_order_changes(session=session, keyspace=keyspace) # check TokenAwarePolicy still return the remaining replicas when one goes down self.coordinator_stats.reset_counts() stop(1) self._wait_for_nodes_down([1], cluster) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 0) query_count_two = self.coordinator_stats.get_query_count(2) query_count_three = self.coordinator_stats.get_query_count(3) self.assertEqual(query_count_two + query_count_three, 12) self.coordinator_stats.reset_counts() stop(2) self._wait_for_nodes_down([2], cluster) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 0) self.coordinator_stats.assert_query_count_equals(self, 3, 12) - cluster.shutdown() + @notdse + @greaterthanorequalcass40 + def test_token_aware_with_transient_replication(self): + """ + Test to validate that the token aware policy doesn't route any request to a transient node. + + @since 3.23 + @jira_ticket PYTHON-1207 + @expected_result the requests are spread across the 2 full replicas and + no other nodes are queried by the coordinator. + + @test_category policy + """ + # We can test this with a single dc when CASSANDRA-15670 is fixed + use_multidc([3, 3]) + + cluster, session = self._cluster_session_with_lbp( + TokenAwarePolicy(DCAwareRoundRobinPolicy(), shuffle_replicas=True) + ) + self.addCleanup(cluster.shutdown) + + session.execute("CREATE KEYSPACE test_tr WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': '3/1', 'dc2': '3/1'};") + session.execute("CREATE TABLE test_tr.users (id int PRIMARY KEY, username text) WITH read_repair ='NONE';") + for i in range(100): + session.execute("INSERT INTO test_tr.users (id, username) VALUES (%d, 'user');" % (i,)) + + query = session.prepare("SELECT * FROM test_tr.users WHERE id = ?") + for i in range(100): + f = session.execute_async(query, (i,), trace=True) + full_dc1_replicas = [h for h in cluster.metadata.get_replicas('test_tr', cqltypes.Int32Type.serialize(i, cluster.protocol_version)) + if h.datacenter == 'dc1'] + self.assertEqual(len(full_dc1_replicas), 2) + + f.result() + trace_hosts = [cluster.metadata.get_host(e.source) for e in f.get_query_trace().events] + + for h in f.attempted_hosts: + self.assertIn(h, full_dc1_replicas) + for h in trace_hosts: + self.assertIn(h, full_dc1_replicas) + def _set_up_shuffle_test(self, keyspace, replication_factor): use_singledc() cluster, session = self._cluster_session_with_lbp( TokenAwarePolicy(RoundRobinPolicy(), shuffle_replicas=True) ) self._wait_for_nodes_up(range(1, 4), cluster) create_schema(cluster, session, keyspace, replication_factor=replication_factor) return cluster, session def _check_query_order_changes(self, session, keyspace): LIMIT_TRIES, tried, query_counts = 20, 0, set() while len(query_counts) <= 1: tried += 1 if tried >= LIMIT_TRIES: raise Exception("After {0} tries shuffle returned the same output".format(LIMIT_TRIES)) self._insert(session, keyspace) self._query(session, keyspace) loop_qcs = (self.coordinator_stats.get_query_count(1), self.coordinator_stats.get_query_count(2), self.coordinator_stats.get_query_count(3)) query_counts.add(loop_qcs) self.assertEqual(sum(loop_qcs), 12) # end the loop if we get more than one query ordering self.coordinator_stats.reset_counts() def test_white_list(self): use_singledc() keyspace = 'test_white_list' - cluster = Cluster(('127.0.0.2',), load_balancing_policy=WhiteListRoundRobinPolicy((IP_FORMAT % 2,)), - protocol_version=PROTOCOL_VERSION, topology_event_refresh_window=0, - status_event_refresh_window=0) + cluster = TestCluster( + contact_points=('127.0.0.2',), topology_event_refresh_window=0, status_event_refresh_window=0, + execution_profiles={ + EXEC_PROFILE_DEFAULT: ExecutionProfile( + load_balancing_policy=WhiteListRoundRobinPolicy((IP_FORMAT % 2,)) + ) + } + ) + self.addCleanup(cluster.shutdown) session = cluster.connect() self._wait_for_nodes_up([1, 2, 3]) create_schema(cluster, session, keyspace) self._insert(session, keyspace) self._query(session, keyspace) self.coordinator_stats.assert_query_count_equals(self, 1, 0) self.coordinator_stats.assert_query_count_equals(self, 2, 12) self.coordinator_stats.assert_query_count_equals(self, 3, 0) # white list policy should not allow reconnecting to ignored hosts force_stop(3) self._wait_for_nodes_down([3]) self.assertFalse(cluster.metadata.get_host(IP_FORMAT % 3).is_currently_reconnecting()) self.coordinator_stats.reset_counts() force_stop(2) self._wait_for_nodes_down([2]) try: self._query(session, keyspace) self.fail() except NoHostAvailable: pass - finally: - cluster.shutdown() def test_black_list_with_host_filter_policy(self): """ Test to validate removing certain hosts from the query plan with HostFilterPolicy @since 3.8 @jira_ticket PYTHON-961 @expected_result the excluded hosts are ignored @test_category policy """ use_singledc() keyspace = 'test_black_list_with_hfp' ignored_address = (IP_FORMAT % 2) hfp = HostFilterPolicy( child_policy=RoundRobinPolicy(), predicate=lambda host: host.address != ignored_address ) - cluster = Cluster( - (IP_FORMAT % 1,), - load_balancing_policy=hfp, - protocol_version=PROTOCOL_VERSION, + cluster = TestCluster( + contact_points=(IP_FORMAT % 1,), topology_event_refresh_window=0, - status_event_refresh_window=0 + status_event_refresh_window=0, + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(load_balancing_policy=hfp)} ) self.addCleanup(cluster.shutdown) session = cluster.connect() self._wait_for_nodes_up([1, 2, 3]) self.assertNotIn(ignored_address, [h.address for h in hfp.make_query_plan()]) create_schema(cluster, session, keyspace) self._insert(session, keyspace) self._query(session, keyspace) # RoundRobin doesn't provide a gurantee on the order of the hosts # so we will have that for 127.0.0.1 and 127.0.0.3 the count for one # will be 4 and for the other 8 first_node_count = self.coordinator_stats.get_query_count(1) third_node_count = self.coordinator_stats.get_query_count(3) self.assertEqual(first_node_count + third_node_count, 12) self.assertTrue(first_node_count == 8 or first_node_count == 4) self.coordinator_stats.assert_query_count_equals(self, 2, 0) # policy should not allow reconnecting to ignored host force_stop(2) self._wait_for_nodes_down([2]) self.assertFalse(cluster.metadata.get_host(ignored_address).is_currently_reconnecting()) diff --git a/tests/integration/long/test_policies.py b/tests/integration/long/test_policies.py index f720548..0648e6c 100644 --- a/tests/integration/long/test_policies.py +++ b/tests/integration/long/test_policies.py @@ -1,70 +1,70 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from cassandra import ConsistencyLevel, Unavailable -from cassandra.cluster import Cluster, ExecutionProfile, EXEC_PROFILE_DEFAULT +from cassandra.cluster import ExecutionProfile, EXEC_PROFILE_DEFAULT -from tests.integration import use_cluster, get_cluster, get_node +from tests.integration import use_cluster, get_cluster, get_node, TestCluster def setup_module(): use_cluster('test_cluster', [4]) class RetryPolicyTests(unittest.TestCase): @classmethod def tearDownClass(cls): cluster = get_cluster() - cluster.start() # make sure other nodes are restarted + cluster.start(wait_for_binary_proto=True) # make sure other nodes are restarted def test_should_rethrow_on_unvailable_with_default_policy_if_cas(self): """ Tests for the default retry policy in combination with lightweight transactions. @since 3.17 @jira_ticket PYTHON-1007 @expected_result the query is retried with the default CL, not the serial one. @test_category policy """ ep = ExecutionProfile(consistency_level=ConsistencyLevel.ALL, serial_consistency_level=ConsistencyLevel.SERIAL) - cluster = Cluster(execution_profiles={EXEC_PROFILE_DEFAULT: ep}) + cluster = TestCluster(execution_profiles={EXEC_PROFILE_DEFAULT: ep}) session = cluster.connect() session.execute("CREATE KEYSPACE test_retry_policy_cas WITH replication = {'class':'SimpleStrategy','replication_factor': 3};") session.execute("CREATE TABLE test_retry_policy_cas.t (id int PRIMARY KEY, data text);") session.execute('INSERT INTO test_retry_policy_cas.t ("id", "data") VALUES (%(0)s, %(1)s)', {'0': 42, '1': 'testing'}) get_node(2).stop() get_node(4).stop() # before fix: cassandra.InvalidRequest: Error from server: code=2200 [Invalid query] message="SERIAL is not # supported as conditional update commit consistency. ...."" # after fix: cassandra.Unavailable (expected since replicas are down) with self.assertRaises(Unavailable) as cm: session.execute("update test_retry_policy_cas.t set data = 'staging' where id = 42 if data ='testing'") exception = cm.exception self.assertEqual(exception.consistency, ConsistencyLevel.SERIAL) self.assertEqual(exception.required_replicas, 2) self.assertEqual(exception.alive_replicas, 1) diff --git a/tests/integration/long/test_schema.py b/tests/integration/long/test_schema.py index 5163066..e2945a1 100644 --- a/tests/integration/long/test_schema.py +++ b/tests/integration/long/test_schema.py @@ -1,161 +1,164 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from cassandra import ConsistencyLevel, AlreadyExists -from cassandra.cluster import Cluster from cassandra.query import SimpleStatement -from tests.integration import use_singledc, PROTOCOL_VERSION, execute_until_pass +from tests.integration import use_singledc, execute_until_pass, TestCluster + +import time try: import unittest2 as unittest except ImportError: import unittest # noqa log = logging.getLogger(__name__) def setup_module(): use_singledc() class SchemaTests(unittest.TestCase): @classmethod def setup_class(cls): - cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cls.cluster = TestCluster() cls.session = cls.cluster.connect(wait_for_all_pools=True) @classmethod def teardown_class(cls): cls.cluster.shutdown() def test_recreates(self): """ Basic test for repeated schema creation and use, using many different keyspaces """ session = self.session for i in range(2): for keyspace_number in range(5): keyspace = "ks_{0}".format(keyspace_number) if keyspace in self.cluster.metadata.keyspaces.keys(): drop = "DROP KEYSPACE {0}".format(keyspace) log.debug(drop) execute_until_pass(session, drop) create = "CREATE KEYSPACE {0} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor': 3}}".format(keyspace) log.debug(create) execute_until_pass(session, create) create = "CREATE TABLE {0}.cf (k int PRIMARY KEY, i int)".format(keyspace) log.debug(create) execute_until_pass(session, create) use = "USE {0}".format(keyspace) log.debug(use) execute_until_pass(session, use) insert = "INSERT INTO cf (k, i) VALUES (0, 0)" log.debug(insert) ss = SimpleStatement(insert, consistency_level=ConsistencyLevel.QUORUM) execute_until_pass(session, ss) def test_for_schema_disagreements_different_keyspaces(self): """ Tests for any schema disagreements using many different keyspaces """ session = self.session for i in range(30): execute_until_pass(session, "CREATE KEYSPACE test_{0} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor': 1}}".format(i)) execute_until_pass(session, "CREATE TABLE test_{0}.cf (key int PRIMARY KEY, value int)".format(i)) for j in range(100): execute_until_pass(session, "INSERT INTO test_{0}.cf (key, value) VALUES ({1}, {1})".format(i, j)) execute_until_pass(session, "DROP KEYSPACE test_{0}".format(i)) def test_for_schema_disagreements_same_keyspace(self): """ Tests for any schema disagreements using the same keyspace multiple times """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect(wait_for_all_pools=True) for i in range(30): try: execute_until_pass(session, "CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}") except AlreadyExists: execute_until_pass(session, "DROP KEYSPACE test") execute_until_pass(session, "CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}") execute_until_pass(session, "CREATE TABLE test.cf (key int PRIMARY KEY, value int)") for j in range(100): execute_until_pass(session, "INSERT INTO test.cf (key, value) VALUES ({0}, {0})".format(j)) execute_until_pass(session, "DROP KEYSPACE test") cluster.shutdown() def test_for_schema_disagreement_attribute(self): """ Tests to ensure that schema disagreement is properly surfaced on the response future. Creates and destroys keyspaces/tables with various schema agreement timeouts set. First part runs cql create/drop cmds with schema agreement set in such away were it will be impossible for agreement to occur during timeout. It then validates that the correct value is set on the result. Second part ensures that when schema agreement occurs, that the result set reflects that appropriately @since 3.1.0 @jira_ticket PYTHON-458 @expected_result is_schema_agreed is set appropriately on response thefuture @test_category schema """ # This should yield a schema disagreement - cluster = Cluster(protocol_version=PROTOCOL_VERSION, max_schema_agreement_wait=0.001) + cluster = TestCluster(max_schema_agreement_wait=0.001) session = cluster.connect(wait_for_all_pools=True) rs = session.execute("CREATE KEYSPACE test_schema_disagreement WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}") self.check_and_wait_for_agreement(session, rs, False) rs = session.execute(SimpleStatement("CREATE TABLE test_schema_disagreement.cf (key int PRIMARY KEY, value int)", consistency_level=ConsistencyLevel.ALL)) self.check_and_wait_for_agreement(session, rs, False) rs = session.execute("DROP KEYSPACE test_schema_disagreement") self.check_and_wait_for_agreement(session, rs, False) cluster.shutdown() # These should have schema agreement - cluster = Cluster(protocol_version=PROTOCOL_VERSION, max_schema_agreement_wait=100) + cluster = TestCluster(max_schema_agreement_wait=100) session = cluster.connect() rs = session.execute("CREATE KEYSPACE test_schema_disagreement WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}") self.check_and_wait_for_agreement(session, rs, True) rs = session.execute(SimpleStatement("CREATE TABLE test_schema_disagreement.cf (key int PRIMARY KEY, value int)", consistency_level=ConsistencyLevel.ALL)) self.check_and_wait_for_agreement(session, rs, True) rs = session.execute("DROP KEYSPACE test_schema_disagreement") self.check_and_wait_for_agreement(session, rs, True) cluster.shutdown() def check_and_wait_for_agreement(self, session, rs, exepected): + # Wait for RESULT_KIND_SCHEMA_CHANGE message to arrive + time.sleep(1) self.assertEqual(rs.response_future.is_schema_agreed, exepected) if not rs.response_future.is_schema_agreed: session.cluster.control_connection.wait_for_schema_agreement(wait_time=1000) diff --git a/tests/integration/long/test_ssl.py b/tests/integration/long/test_ssl.py index 7f0a870..4de46f4 100644 --- a/tests/integration/long/test_ssl.py +++ b/tests/integration/long/test_ssl.py @@ -1,413 +1,504 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest import os, sys, traceback, logging, ssl, time, math, uuid -from cassandra.cluster import Cluster, NoHostAvailable +from cassandra.cluster import NoHostAvailable +from cassandra.connection import DefaultEndPoint from cassandra import ConsistencyLevel from cassandra.query import SimpleStatement -from tests.integration import PROTOCOL_VERSION, get_cluster, remove_cluster, use_single_node, EVENT_LOOP_MANAGER + +from OpenSSL import SSL, crypto + +from tests.integration import ( + get_cluster, remove_cluster, use_single_node, start_cluster_wait_for_up, EVENT_LOOP_MANAGER, TestCluster +) + +if not hasattr(ssl, 'match_hostname'): + try: + from backports.ssl_match_hostname import match_hostname + ssl.match_hostname = match_hostname + except ImportError: + pass # tests will fail log = logging.getLogger(__name__) -DEFAULT_PASSWORD = "pythondriver" +DEFAULT_PASSWORD = "cassandra" # Server keystore trust store locations -SERVER_KEYSTORE_PATH = "tests/integration/long/ssl/.keystore" -SERVER_TRUSTSTORE_PATH = "tests/integration/long/ssl/.truststore" +SERVER_KEYSTORE_PATH = os.path.abspath("tests/integration/long/ssl/127.0.0.1.keystore") +SERVER_TRUSTSTORE_PATH = os.path.abspath("tests/integration/long/ssl/cassandra.truststore") # Client specific keys/certs -CLIENT_CA_CERTS = 'tests/integration/long/ssl/cassandra.pem' -DRIVER_KEYFILE = "tests/integration/long/ssl/driver.key" -DRIVER_KEYFILE_ENCRYPTED = "tests/integration/long/ssl/driver_encrypted.key" -DRIVER_CERTFILE = "tests/integration/long/ssl/driver.pem" -DRIVER_CERTFILE_BAD = "tests/integration/long/ssl/python_driver_bad.pem" +CLIENT_CA_CERTS = os.path.abspath("tests/integration/long/ssl/rootCa.crt") +DRIVER_KEYFILE = os.path.abspath("tests/integration/long/ssl/client.key") +DRIVER_KEYFILE_ENCRYPTED = os.path.abspath("tests/integration/long/ssl/client_encrypted.key") +DRIVER_CERTFILE = os.path.abspath("tests/integration/long/ssl/client.crt_signed") +DRIVER_CERTFILE_BAD = os.path.abspath("tests/integration/long/ssl/client_bad.key") +USES_PYOPENSSL = "twisted" in EVENT_LOOP_MANAGER or "eventlet" in EVENT_LOOP_MANAGER if "twisted" in EVENT_LOOP_MANAGER: import OpenSSL - ssl_version = OpenSSL.SSL.TLSv1_METHOD - verify_certs = {'cert_reqs': OpenSSL.SSL.VERIFY_PEER, + ssl_version = OpenSSL.SSL.TLSv1_2_METHOD + verify_certs = {'cert_reqs': SSL.VERIFY_PEER, 'check_hostname': True} - else: - ssl_version = ssl.PROTOCOL_TLSv1 + ssl_version = ssl.PROTOCOL_TLS verify_certs = {'cert_reqs': ssl.CERT_REQUIRED, 'check_hostname': True} +def verify_callback(connection, x509, errnum, errdepth, ok): + return ok + + def setup_cluster_ssl(client_auth=False): """ We need some custom setup for this module. This will start the ccm cluster with basic ssl connectivity, and client authentication if needed. """ use_single_node(start=False) ccm_cluster = get_cluster() ccm_cluster.stop() - # Fetch the absolute path to the keystore for ccm. - abs_path_server_keystore_path = os.path.abspath(SERVER_KEYSTORE_PATH) - # Configure ccm to use ssl. - config_options = {'client_encryption_options': {'enabled': True, - 'keystore': abs_path_server_keystore_path, + 'keystore': SERVER_KEYSTORE_PATH, 'keystore_password': DEFAULT_PASSWORD}} if(client_auth): - abs_path_server_truststore_path = os.path.abspath(SERVER_TRUSTSTORE_PATH) client_encyrption_options = config_options['client_encryption_options'] client_encyrption_options['require_client_auth'] = True - client_encyrption_options['truststore'] = abs_path_server_truststore_path + client_encyrption_options['truststore'] = SERVER_TRUSTSTORE_PATH client_encyrption_options['truststore_password'] = DEFAULT_PASSWORD ccm_cluster.set_configuration_options(config_options) - ccm_cluster.start(wait_for_binary_proto=True, wait_other_notice=True) + start_cluster_wait_for_up(ccm_cluster) def validate_ssl_options(**kwargs): ssl_options = kwargs.get('ssl_options', None) ssl_context = kwargs.get('ssl_context', None) + hostname = kwargs.get('hostname', '127.0.0.1') # find absolute path to client CA_CERTS tries = 0 while True: if tries > 5: raise RuntimeError("Failed to connect to SSL cluster after 5 attempts") try: - cluster = Cluster(protocol_version=PROTOCOL_VERSION, - ssl_options=ssl_options, ssl_context=ssl_context) + cluster = TestCluster( + contact_points=[DefaultEndPoint(hostname)], + ssl_options=ssl_options, + ssl_context=ssl_context + ) session = cluster.connect(wait_for_all_pools=True) break except Exception: ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb tries += 1 # attempt a few simple commands. insert_keyspace = """CREATE KEYSPACE ssltest WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '3'} """ statement = SimpleStatement(insert_keyspace) statement.consistency_level = 3 session.execute(statement) drop_keyspace = "DROP KEYSPACE ssltest" statement = SimpleStatement(drop_keyspace) statement.consistency_level = ConsistencyLevel.ANY session.execute(statement) cluster.shutdown() class SSLConnectionTests(unittest.TestCase): @classmethod def setUpClass(cls): setup_cluster_ssl() @classmethod def tearDownClass(cls): ccm_cluster = get_cluster() ccm_cluster.stop() remove_cluster() def test_can_connect_with_ssl_ca(self): """ Test to validate that we are able to connect to a cluster using ssl. test_can_connect_with_ssl_ca performs a simple sanity check to ensure that we can connect to a cluster with ssl authentication via simple server-side shared certificate authority. The client is able to validate the identity of the server, however by using this method the server can't trust the client unless additional authentication has been provided. @since 2.6.0 @jira_ticket PYTHON-332 @expected_result The client can connect via SSL and preform some basic operations @test_category connection:ssl """ # find absolute path to client CA_CERTS - abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS) - ssl_options = {'ca_certs': abs_path_ca_cert_path,'ssl_version': ssl_version} + ssl_options = {'ca_certs': CLIENT_CA_CERTS,'ssl_version': ssl_version} validate_ssl_options(ssl_options=ssl_options) def test_can_connect_with_ssl_long_running(self): """ Test to validate that long running ssl connections continue to function past thier timeout window @since 3.6.0 @jira_ticket PYTHON-600 @expected_result The client can connect via SSL and preform some basic operations over a period of longer then a minute @test_category connection:ssl """ # find absolute path to client CA_CERTS abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS) ssl_options = {'ca_certs': abs_path_ca_cert_path, 'ssl_version': ssl_version} tries = 0 while True: if tries > 5: raise RuntimeError("Failed to connect to SSL cluster after 5 attempts") try: - cluster = Cluster(protocol_version=PROTOCOL_VERSION, ssl_options=ssl_options) + cluster = TestCluster(ssl_options=ssl_options) session = cluster.connect(wait_for_all_pools=True) break except Exception: ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb tries += 1 # attempt a few simple commands. for i in range(8): rs = session.execute("SELECT * FROM system.local") time.sleep(10) cluster.shutdown() def test_can_connect_with_ssl_ca_host_match(self): """ Test to validate that we are able to connect to a cluster using ssl, and host matching test_can_connect_with_ssl_ca_host_match performs a simple sanity check to ensure that we can connect to a cluster with ssl authentication via simple server-side shared certificate authority. It also validates that the host ip matches what is expected @since 3.3 @jira_ticket PYTHON-296 @expected_result The client can connect via SSL and preform some basic operations, with check_hostname specified @test_category connection:ssl """ - # find absolute path to client CA_CERTS - abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS) - ssl_options = {'ca_certs': abs_path_ca_cert_path, + ssl_options = {'ca_certs': CLIENT_CA_CERTS, 'ssl_version': ssl_version} ssl_options.update(verify_certs) validate_ssl_options(ssl_options=ssl_options) class SSLConnectionAuthTests(unittest.TestCase): @classmethod def setUpClass(cls): setup_cluster_ssl(client_auth=True) @classmethod def tearDownClass(cls): ccm_cluster = get_cluster() ccm_cluster.stop() remove_cluster() def test_can_connect_with_ssl_client_auth(self): """ Test to validate that we can connect to a C* cluster that has client_auth enabled. This test will setup and use a c* cluster that has client authentication enabled. It will then attempt to connect using valid client keys, and certs (that are in the server's truststore), and attempt to preform some basic operations @since 2.7.0 @expected_result The client can connect via SSL and preform some basic operations @test_category connection:ssl """ - # Need to get absolute paths for certs/key - abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS) - abs_driver_keyfile = os.path.abspath(DRIVER_KEYFILE) - abs_driver_certfile = os.path.abspath(DRIVER_CERTFILE) - ssl_options = {'ca_certs': abs_path_ca_cert_path, + ssl_options = {'ca_certs': CLIENT_CA_CERTS, 'ssl_version': ssl_version, - 'keyfile': abs_driver_keyfile, - 'certfile': abs_driver_certfile} + 'keyfile': DRIVER_KEYFILE, + 'certfile': DRIVER_CERTFILE} validate_ssl_options(ssl_options=ssl_options) def test_can_connect_with_ssl_client_auth_host_name(self): """ Test to validate that we can connect to a C* cluster that has client_auth enabled, and hostmatching This test will setup and use a c* cluster that has client authentication enabled. It will then attempt to connect using valid client keys, and certs (that are in the server's truststore), and attempt to preform some basic operations, with check_hostname specified @jira_ticket PYTHON-296 @since 3.3 @expected_result The client can connect via SSL and preform some basic operations @test_category connection:ssl """ - # Need to get absolute paths for certs/key - abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS) - abs_driver_keyfile = os.path.abspath(DRIVER_KEYFILE) - abs_driver_certfile = os.path.abspath(DRIVER_CERTFILE) - - ssl_options = {'ca_certs': abs_path_ca_cert_path, + ssl_options = {'ca_certs': CLIENT_CA_CERTS, 'ssl_version': ssl_version, - 'keyfile': abs_driver_keyfile, - 'certfile': abs_driver_certfile} + 'keyfile': DRIVER_KEYFILE, + 'certfile': DRIVER_CERTFILE} ssl_options.update(verify_certs) validate_ssl_options(ssl_options=ssl_options) def test_cannot_connect_without_client_auth(self): """ Test to validate that we cannot connect without client auth. This test will omit the keys/certs needed to preform client authentication. It will then attempt to connect to a server that has client authentication enabled. @since 2.7.0 @expected_result The client will throw an exception on connect @test_category connection:ssl """ - abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS) - cluster = Cluster(protocol_version=PROTOCOL_VERSION, ssl_options={'ca_certs': abs_path_ca_cert_path, - 'ssl_version': ssl_version}) - # attempt to connect and expect an exception + cluster = TestCluster(ssl_options={'ca_certs': CLIENT_CA_CERTS, + 'ssl_version': ssl_version}) - with self.assertRaises(NoHostAvailable) as context: + with self.assertRaises(NoHostAvailable) as _: cluster.connect() cluster.shutdown() def test_cannot_connect_with_bad_client_auth(self): """ - Test to validate that we cannot connect with invalid client auth. + Test to validate that we cannot connect with invalid client auth. This test will use bad keys/certs to preform client authentication. It will then attempt to connect to a server that has client authentication enabled. @since 2.7.0 @expected_result The client will throw an exception on connect @test_category connection:ssl """ - # Setup absolute paths to key/cert files - abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS) - abs_driver_keyfile = os.path.abspath(DRIVER_KEYFILE) - abs_driver_certfile = os.path.abspath(DRIVER_CERTFILE_BAD) - - cluster = Cluster(protocol_version=PROTOCOL_VERSION, ssl_options={'ca_certs': abs_path_ca_cert_path, - 'ssl_version': ssl_version, - 'keyfile': abs_driver_keyfile, - 'certfile': abs_driver_certfile}) - with self.assertRaises(NoHostAvailable) as context: + ssl_options = {'ca_certs': CLIENT_CA_CERTS, + 'ssl_version': ssl_version, + 'keyfile': DRIVER_KEYFILE} + + if not USES_PYOPENSSL: + # I don't set the bad certfile for pyopenssl because it hangs + ssl_options['certfile'] = DRIVER_CERTFILE_BAD + + cluster = TestCluster( + ssl_options={'ca_certs': CLIENT_CA_CERTS, + 'ssl_version': ssl_version, + 'keyfile': DRIVER_KEYFILE} + ) + + with self.assertRaises(NoHostAvailable) as _: cluster.connect() cluster.shutdown() + def test_cannot_connect_with_invalid_hostname(self): + ssl_options = {'ca_certs': CLIENT_CA_CERTS, + 'ssl_version': ssl_version, + 'keyfile': DRIVER_KEYFILE, + 'certfile': DRIVER_CERTFILE} + ssl_options.update(verify_certs) + + with self.assertRaises(Exception): + validate_ssl_options(ssl_options=ssl_options, hostname='localhost') + class SSLSocketErrorTests(unittest.TestCase): @classmethod def setUpClass(cls): setup_cluster_ssl() @classmethod def tearDownClass(cls): ccm_cluster = get_cluster() ccm_cluster.stop() remove_cluster() def test_ssl_want_write_errors_are_retried(self): """ Test that when a socket receives a WANT_WRITE error, the message chunk sending is retried. @since 3.17.0 @jira_ticket PYTHON-891 @expected_result The query is executed successfully @test_category connection:ssl """ - abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS) - ssl_options = {'ca_certs': abs_path_ca_cert_path, + ssl_options = {'ca_certs': CLIENT_CA_CERTS, 'ssl_version': ssl_version} - cluster = Cluster(protocol_version=PROTOCOL_VERSION, ssl_options=ssl_options) + cluster = TestCluster(ssl_options=ssl_options) session = cluster.connect(wait_for_all_pools=True) try: session.execute('drop keyspace ssl_error_test') except: pass session.execute( "CREATE KEYSPACE ssl_error_test WITH replication = {'class':'SimpleStrategy','replication_factor':1};") session.execute("CREATE TABLE ssl_error_test.big_text (id uuid PRIMARY KEY, data text);") params = { '0': uuid.uuid4(), '1': "0" * int(math.pow(10, 7)) } session.execute('INSERT INTO ssl_error_test.big_text ("id", "data") VALUES (%(0)s, %(1)s)', params) class SSLConnectionWithSSLContextTests(unittest.TestCase): - @classmethod def setUpClass(cls): setup_cluster_ssl() @classmethod def tearDownClass(cls): ccm_cluster = get_cluster() ccm_cluster.stop() remove_cluster() def test_can_connect_with_sslcontext_certificate(self): """ Test to validate that we are able to connect to a cluster using a SSLContext. @since 3.17.0 @jira_ticket PYTHON-995 @expected_result The client can connect via SSL and preform some basic operations @test_category connection:ssl """ - abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS) - ssl_context = ssl.SSLContext(ssl_version) - ssl_context.load_verify_locations(abs_path_ca_cert_path) + if USES_PYOPENSSL: + ssl_context = SSL.Context(SSL.TLSv1_2_METHOD) + ssl_context.load_verify_locations(CLIENT_CA_CERTS) + else: + ssl_context = ssl.SSLContext(ssl_version) + ssl_context.load_verify_locations(CLIENT_CA_CERTS) + ssl_context.verify_mode = ssl.CERT_REQUIRED validate_ssl_options(ssl_context=ssl_context) def test_can_connect_with_ssl_client_auth_password_private_key(self): """ Identical test to SSLConnectionAuthTests.test_can_connect_with_ssl_client_auth, the only difference is that the DRIVER_KEYFILE is encrypted with a password. @since 3.17.0 @jira_ticket PYTHON-995 @expected_result The client can connect via SSL and preform some basic operations @test_category connection:ssl """ abs_driver_keyfile = os.path.abspath(DRIVER_KEYFILE_ENCRYPTED) abs_driver_certfile = os.path.abspath(DRIVER_CERTFILE) - ssl_context = ssl.SSLContext(ssl_version) - ssl_context.load_cert_chain(certfile=abs_driver_certfile, - keyfile=abs_driver_keyfile, - password='cassandra') + ssl_options = {} + + if USES_PYOPENSSL: + ssl_context = SSL.Context(SSL.TLSv1_2_METHOD) + ssl_context.use_certificate_file(abs_driver_certfile) + with open(abs_driver_keyfile) as keyfile: + key = crypto.load_privatekey(crypto.FILETYPE_PEM, keyfile.read(), b'cassandra') + ssl_context.use_privatekey(key) + ssl_context.set_verify(SSL.VERIFY_NONE, verify_callback) + else: + ssl_context = ssl.SSLContext(ssl_version) + ssl_context.load_cert_chain(certfile=abs_driver_certfile, + keyfile=abs_driver_keyfile, + password="cassandra") + ssl_context.verify_mode = ssl.CERT_NONE + validate_ssl_options(ssl_context=ssl_context, ssl_options=ssl_options) + + def test_can_connect_with_ssl_context_ca_host_match(self): + """ + Test to validate that we are able to connect to a cluster using a SSLContext + using client auth, an encrypted keyfile, and host matching + """ + ssl_options = {} + if USES_PYOPENSSL: + ssl_context = SSL.Context(SSL.TLSv1_2_METHOD) + ssl_context.use_certificate_file(DRIVER_CERTFILE) + with open(DRIVER_KEYFILE_ENCRYPTED) as keyfile: + key = crypto.load_privatekey(crypto.FILETYPE_PEM, keyfile.read(), b'cassandra') + ssl_context.use_privatekey(key) + ssl_context.load_verify_locations(CLIENT_CA_CERTS) + ssl_options["check_hostname"] = True + else: + ssl_context = ssl.SSLContext(ssl_version) + ssl_context.verify_mode = ssl.CERT_REQUIRED + ssl_context.load_verify_locations(CLIENT_CA_CERTS) + ssl_context.load_cert_chain( + certfile=DRIVER_CERTFILE, + keyfile=DRIVER_KEYFILE_ENCRYPTED, + password="cassandra", + ) + ssl_context.verify_mode = ssl.CERT_REQUIRED + ssl_options["check_hostname"] = True + validate_ssl_options(ssl_context=ssl_context, ssl_options=ssl_options) + + def test_cannot_connect_ssl_context_with_invalid_hostname(self): + ssl_options = {} + if USES_PYOPENSSL: + ssl_context = SSL.Context(SSL.TLSv1_2_METHOD) + ssl_context.use_certificate_file(DRIVER_CERTFILE) + with open(DRIVER_KEYFILE_ENCRYPTED) as keyfile: + key = crypto.load_privatekey(crypto.FILETYPE_PEM, keyfile.read(), b"cassandra") + ssl_context.use_privatekey(key) + ssl_context.load_verify_locations(CLIENT_CA_CERTS) + ssl_options["check_hostname"] = True + else: + ssl_context = ssl.SSLContext(ssl_version) + ssl_context.verify_mode = ssl.CERT_REQUIRED + ssl_context.load_verify_locations(CLIENT_CA_CERTS) + ssl_context.load_cert_chain( + certfile=DRIVER_CERTFILE, + keyfile=DRIVER_KEYFILE_ENCRYPTED, + password="cassandra", + ) + ssl_context.verify_mode = ssl.CERT_REQUIRED + ssl_options["check_hostname"] = True + with self.assertRaises(Exception): + validate_ssl_options(ssl_context=ssl_context, ssl_options=ssl_options, hostname="localhost") + + @unittest.skipIf(USES_PYOPENSSL, "This test is for the built-in ssl.Context") + def test_can_connect_with_sslcontext_default_context(self): + """ + Test to validate that we are able to connect to a cluster using a SSLContext created from create_default_context(). + @expected_result The client can connect via SSL and preform some basic operations + @test_category connection:ssl + """ + ssl_context = ssl.create_default_context(cafile=CLIENT_CA_CERTS) validate_ssl_options(ssl_context=ssl_context) diff --git a/tests/integration/long/test_topology_change.py b/tests/integration/long/test_topology_change.py new file mode 100644 index 0000000..5b12eef --- /dev/null +++ b/tests/integration/long/test_topology_change.py @@ -0,0 +1,48 @@ +from unittest import TestCase + +from cassandra.policies import HostStateListener +from tests.integration import get_node, use_cluster, local, TestCluster +from tests.integration.long.utils import decommission +from tests.util import wait_until + + +class StateListener(HostStateListener): + def __init__(self): + self.downed_host = None + self.removed_host = None + + def on_remove(self, host): + self.removed_host = host + + def on_up(self, host): + pass + + def on_down(self, host): + self.downed_host = host + + def on_add(self, host): + pass + + +class TopologyChangeTests(TestCase): + @local + def test_removed_node_stops_reconnecting(self): + """ Ensure we stop reconnecting after a node is removed. PYTHON-1181 """ + use_cluster("test_down_then_removed", [3], start=True) + + state_listener = StateListener() + cluster = TestCluster() + self.addCleanup(cluster.shutdown) + cluster.register_listener(state_listener) + session = cluster.connect(wait_for_all_pools=True) + + get_node(3).nodetool("disablebinary") + + wait_until(condition=lambda: state_listener.downed_host is not None, delay=2, max_attempts=50) + self.assertTrue(state_listener.downed_host.is_currently_reconnecting()) + + decommission(3) + + wait_until(condition=lambda: state_listener.removed_host is not None, delay=2, max_attempts=50) + self.assertIs(state_listener.downed_host, state_listener.removed_host) # Just a sanity check + self.assertFalse(state_listener.removed_host.is_currently_reconnecting()) diff --git a/tests/integration/long/utils.py b/tests/integration/long/utils.py index 07652b6..a5b5bdd 100644 --- a/tests/integration/long/utils.py +++ b/tests/integration/long/utils.py @@ -1,183 +1,173 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import logging import time from collections import defaultdict -from ccmlib.node import Node, ToolError +from packaging.version import Version -from nose.tools import assert_in -from cassandra.query import named_tuple_factory -from cassandra.cluster import ConsistencyLevel +from tests.integration import (get_node, get_cluster, wait_for_node_socket, + DSE_VERSION, CASSANDRA_VERSION) -from tests.integration import get_node, get_cluster, wait_for_node_socket IP_FORMAT = '127.0.0.%s' log = logging.getLogger(__name__) class CoordinatorStats(): def __init__(self): self.coordinator_counts = defaultdict(int) def add_coordinator(self, future): log.debug('adding coordinator from {}'.format(future)) future.result() coordinator = future._current_host.address self.coordinator_counts[coordinator] += 1 if future._errors: log.error('future._errors: %s', future._errors) def reset_counts(self): self.coordinator_counts = defaultdict(int) def get_query_count(self, node): ip = '127.0.0.%d' % node return self.coordinator_counts[ip] def assert_query_count_equals(self, testcase, node, expected): ip = '127.0.0.%d' % node if self.get_query_count(node) != expected: testcase.fail('Expected %d queries to %s, but got %d. Query counts: %s' % ( expected, ip, self.coordinator_counts[ip], dict(self.coordinator_counts))) def create_schema(cluster, session, keyspace, simple_strategy=True, replication_factor=1, replication_strategy=None): - row_factory = session.row_factory - session.row_factory = named_tuple_factory - session.default_consistency_level = ConsistencyLevel.QUORUM - if keyspace in cluster.metadata.keyspaces.keys(): session.execute('DROP KEYSPACE %s' % keyspace, timeout=20) if simple_strategy: ddl = "CREATE KEYSPACE %s WITH replication" \ " = {'class': 'SimpleStrategy', 'replication_factor': '%s'}" session.execute(ddl % (keyspace, replication_factor), timeout=10) else: if not replication_strategy: raise Exception('replication_strategy is not set') ddl = "CREATE KEYSPACE %s" \ " WITH replication = { 'class' : 'NetworkTopologyStrategy', %s }" session.execute(ddl % (keyspace, str(replication_strategy)[1:-1]), timeout=10) ddl = 'CREATE TABLE %s.cf (k int PRIMARY KEY, i int)' session.execute(ddl % keyspace, timeout=10) session.execute('USE %s' % keyspace) - session.row_factory = row_factory - session.default_consistency_level = ConsistencyLevel.LOCAL_ONE - def start(node): get_node(node).start() def stop(node): get_node(node).stop() def force_stop(node): log.debug("Forcing stop of node %s", node) get_node(node).stop(wait=False, gently=False) log.debug("Node %s was stopped", node) def decommission(node): - try: - get_node(node).decommission() - except ToolError as e: - expected_errs = (('Not enough live nodes to maintain replication ' - 'factor in keyspace system_distributed'), - 'Perform a forceful decommission to ignore.') - for err in expected_errs: - assert_in(err, e.stdout) - # in this case, we're running against a C* version with CASSANDRA-12510 - # applied and need to decommission with `--force` + if (DSE_VERSION and DSE_VERSION >= Version("5.1")) or CASSANDRA_VERSION >= Version("4.0-a"): + # CASSANDRA-12510 get_node(node).decommission(force=True) + else: + get_node(node).decommission() get_node(node).stop() def bootstrap(node, data_center=None, token=None): log.debug('called bootstrap(' 'node={node}, data_center={data_center}, ' 'token={token})') - node_instance = Node('node%s' % node, - get_cluster(), - auto_bootstrap=False, - thrift_interface=(IP_FORMAT % node, 9160), - storage_interface=(IP_FORMAT % node, 7000), - binary_interface=(IP_FORMAT % node, 9042), - jmx_port=str(7000 + 100 * node), - remote_debug_port=0, - initial_token=token if token else node * 10) - get_cluster().add(node_instance, is_seed=False, data_center=data_center) + cluster = get_cluster() + # for now assumes cluster has at least one node + node_type = type(next(iter(cluster.nodes.values()))) + node_instance = node_type( + 'node%s' % node, + cluster, + auto_bootstrap=False, + thrift_interface=(IP_FORMAT % node, 9160), + storage_interface=(IP_FORMAT % node, 7000), + binary_interface=(IP_FORMAT % node, 9042), + jmx_port=str(7000 + 100 * node), + remote_debug_port=0, + initial_token=token if token else node * 10 + ) + cluster.add(node_instance, is_seed=False, data_center=data_center) try: - start(node) + node_instance.start() except Exception as e0: log.debug('failed 1st bootstrap attempt with: \n{}'.format(e0)) # Try only twice try: - start(node) + node_instance.start() except Exception as e1: log.debug('failed 2nd bootstrap attempt with: \n{}'.format(e1)) log.error('Added node failed to start twice.') raise e1 def ring(node): get_node(node).nodetool('ring') def wait_for_up(cluster, node): tries = 0 addr = IP_FORMAT % node while tries < 100: host = cluster.metadata.get_host(addr) if host and host.is_up: wait_for_node_socket(get_node(node), 60) log.debug("Done waiting for node %s to be up", node) return else: log.debug("Host {} is still marked down, waiting".format(addr)) tries += 1 time.sleep(1) # todo: don't mix string interpolation methods in the same package raise RuntimeError("Host {0} is not up after {1} attempts".format(addr, tries)) def wait_for_down(cluster, node): log.debug("Waiting for node %s to be down", node) tries = 0 addr = IP_FORMAT % node while tries < 100: host = cluster.metadata.get_host(IP_FORMAT % node) if not host or not host.is_up: log.debug("Done waiting for node %s to be down", node) return else: log.debug("Host is still marked up, waiting") tries += 1 time.sleep(1) raise RuntimeError("Host {0} is not down after {1} attempts".format(addr, tries)) diff --git a/tests/integration/simulacron/__init__.py b/tests/integration/simulacron/__init__.py index 665d6b3..6543265 100644 --- a/tests/integration/simulacron/__init__.py +++ b/tests/integration/simulacron/__init__.py @@ -1,58 +1,85 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License try: import unittest2 as unittest except ImportError: import unittest # noqa -from tests.integration.simulacron.utils import stop_simulacron, clear_queries -from tests.integration import PROTOCOL_VERSION, SIMULACRON_JAR, CASSANDRA_VERSION -from tests.integration.simulacron.utils import start_and_prime_singledc +from tests.integration import requiredse, CASSANDRA_VERSION, DSE_VERSION, SIMULACRON_JAR, PROTOCOL_VERSION +from tests.integration.simulacron.utils import ( + clear_queries, + start_and_prime_singledc, + stop_simulacron, + start_and_prime_cluster_defaults, +) from cassandra.cluster import Cluster from packaging.version import Version + +PROTOCOL_VERSION = min(4, PROTOCOL_VERSION if (DSE_VERSION is None or DSE_VERSION >= Version('5.0')) else 3) + + def teardown_package(): stop_simulacron() class SimulacronBase(unittest.TestCase): def tearDown(self): clear_queries() stop_simulacron() class SimulacronCluster(SimulacronBase): cluster, connect = None, True @classmethod def setUpClass(cls): if SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"): return start_and_prime_singledc() if cls.connect: cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) cls.session = cls.cluster.connect(wait_for_all_pools=True) @classmethod def tearDownClass(cls): if SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"): return if cls.cluster: cls.cluster.shutdown() stop_simulacron() + + +@requiredse +class DseSimulacronCluster(SimulacronBase): + + simulacron_cluster = None + cluster, connect = None, True + nodes_per_dc = 1 + + @classmethod + def setUpClass(cls): + if DSE_VERSION is None and SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"): + return + + cls.simulacron_cluster = start_and_prime_cluster_defaults(dse_version=DSE_VERSION, + nodes_per_dc=cls.nodes_per_dc) + if cls.connect: + cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) + cls.session = cls.cluster.connect(wait_for_all_pools=True) diff --git a/tests/integration/advanced/__init__.py b/tests/integration/simulacron/advanced/__init__.py similarity index 67% copy from tests/integration/advanced/__init__.py copy to tests/integration/simulacron/advanced/__init__.py index 662f5b8..2c9ca17 100644 --- a/tests/integration/advanced/__init__.py +++ b/tests/integration/simulacron/advanced/__init__.py @@ -1,23 +1,13 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License - -try: - import unittest2 as unittest -except ImportError: - import unittest # noqa - -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) +# limitations under the License. diff --git a/tests/integration/simulacron/advanced/test_insights.py b/tests/integration/simulacron/advanced/test_insights.py new file mode 100644 index 0000000..3da1465 --- /dev/null +++ b/tests/integration/simulacron/advanced/test_insights.py @@ -0,0 +1,111 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +import time +import json +import re + +from cassandra.cluster import Cluster +from cassandra.datastax.insights.util import version_supports_insights + +from tests.integration import requiressimulacron, requiredse, DSE_VERSION +from tests.integration.simulacron import DseSimulacronCluster, PROTOCOL_VERSION +from tests.integration.simulacron.utils import SimulacronClient, GetLogsQuery, ClearLogsQuery + + +@requiredse +@requiressimulacron +@unittest.skipUnless(DSE_VERSION and version_supports_insights(str(DSE_VERSION)), 'DSE {} does not support insights'.format(DSE_VERSION)) +class InsightsTests(DseSimulacronCluster): + """ + Tests insights integration + + @since 3.18 + @jira_ticket PYTHON-1047 + @expected_result startup and status messages are sent + """ + + connect = False + + def tearDown(self): + if self.cluster: + self.cluster.shutdown() + + @staticmethod + def _get_node_logs(raw_data): + return list(filter(lambda q: q['type'] == 'QUERY' and q['query'].startswith('CALL InsightsRpc.reportInsight'), + json.loads(raw_data)['data_centers'][0]['nodes'][0]['queries'])) + + @staticmethod + def _parse_data(data, index=0): + return json.loads(re.match( + r"CALL InsightsRpc.reportInsight\('(.+)'\)", + data[index]['frame']['message']['query']).group(1)) + + def test_startup_message(self): + self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) + self.session = self.cluster.connect(wait_for_all_pools=True) + + time.sleep(1) # wait the monitor thread is started + response = SimulacronClient().submit_request(GetLogsQuery()) + self.assertTrue('CALL InsightsRpc.reportInsight' in response) + + node_queries = self._get_node_logs(response) + self.assertEqual(1, len(node_queries)) + self.assertTrue(node_queries, "RPC query not found") + + message = self._parse_data(node_queries) + + self.assertEqual(message['metadata']['name'], 'driver.startup') + self.assertEqual(message['data']['initialControlConnection'], + self.cluster.control_connection._connection.host) + self.assertEqual(message['data']['sessionId'], str(self.session.session_id)) + self.assertEqual(message['data']['clientId'], str(self.cluster.client_id)) + self.assertEqual(message['data']['compression'], 'NONE') + + def test_status_message(self): + SimulacronClient().submit_request(ClearLogsQuery()) + + self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False, monitor_reporting_interval=1) + self.session = self.cluster.connect(wait_for_all_pools=True) + + time.sleep(1.1) + response = SimulacronClient().submit_request(GetLogsQuery()) + self.assertTrue('CALL InsightsRpc.reportInsight' in response) + + node_queries = self._get_node_logs(response) + self.assertEqual(2, len(node_queries)) + self.assertTrue(node_queries, "RPC query not found") + + message = self._parse_data(node_queries, 1) + + self.assertEqual(message['metadata']['name'], 'driver.status') + self.assertEqual(message['data']['controlConnection'], + self.cluster.control_connection._connection.host) + self.assertEqual(message['data']['sessionId'], str(self.session.session_id)) + self.assertEqual(message['data']['clientId'], str(self.cluster.client_id)) + self.assertEqual(message['metadata']['insightType'], 'EVENT') + + def test_monitor_disabled(self): + SimulacronClient().submit_request(ClearLogsQuery()) + + self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False, monitor_reporting_enabled=False) + self.session = self.cluster.connect(wait_for_all_pools=True) + + response = SimulacronClient().submit_request(GetLogsQuery()) + self.assertFalse('CALL InsightsRpc.reportInsight' in response) diff --git a/tests/integration/simulacron/test_backpressure.py b/tests/integration/simulacron/test_backpressure.py new file mode 100644 index 0000000..69c38da --- /dev/null +++ b/tests/integration/simulacron/test_backpressure.py @@ -0,0 +1,179 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import time + +from cassandra import OperationTimedOut +from cassandra.cluster import Cluster, ExecutionProfile, EXEC_PROFILE_DEFAULT, NoHostAvailable +from cassandra.policies import RoundRobinPolicy, WhiteListRoundRobinPolicy +from tests.integration import requiressimulacron, libevtest +from tests.integration.simulacron import SimulacronBase, PROTOCOL_VERSION +from tests.integration.simulacron.utils import ResumeReads, PauseReads, prime_request, start_and_prime_singledc + + +@requiressimulacron +@libevtest +class TCPBackpressureTests(SimulacronBase): + def setUp(self): + self.callback_successes = 0 + self.callback_errors = 0 + + def callback_success(self, results): + self.callback_successes += 1 + + def callback_error(self, results): + self.callback_errors += 1 + + def _fill_buffers(self, session, query, expected_blocked=3, **execute_kwargs): + futures = [] + buffer = '1' * 50000 + for _ in range(100000): + future = session.execute_async(query, [buffer], **execute_kwargs) + futures.append(future) + + total_blocked = 0 + for pool in session.get_pools(): + if not pool._connection._socket_writable: + total_blocked += 1 + if total_blocked >= expected_blocked: + break + else: + raise Exception("Unable to fill TCP send buffer on expected number of nodes") + return futures + + def test_paused_connections(self): + """ Verify all requests come back as expected if node resumes within query timeout """ + start_and_prime_singledc() + profile = ExecutionProfile(request_timeout=500, load_balancing_policy=RoundRobinPolicy()) + cluster = Cluster( + protocol_version=PROTOCOL_VERSION, + compression=False, + execution_profiles={EXEC_PROFILE_DEFAULT: profile}, + ) + session = cluster.connect(wait_for_all_pools=True) + self.addCleanup(cluster.shutdown) + + query = session.prepare("INSERT INTO table1 (id) VALUES (?)") + + prime_request(PauseReads()) + futures = self._fill_buffers(session, query) + + # Make sure we actually have some stuck in-flight requests + for in_flight in [pool._connection.in_flight for pool in session.get_pools()]: + self.assertGreater(in_flight, 100) + time.sleep(.5) + for in_flight in [pool._connection.in_flight for pool in session.get_pools()]: + self.assertGreater(in_flight, 100) + + prime_request(ResumeReads()) + + for future in futures: + try: + future.result() + except NoHostAvailable as e: + # We shouldn't have any timeouts here, but all of the queries beyond what can fit + # in the tcp buffer will have returned with a ConnectionBusy exception + self.assertIn("ConnectionBusy", str(e)) + + # Verify that we can continue sending queries without any problems + for host in session.cluster.metadata.all_hosts(): + session.execute(query, ["a"], host=host) + + def test_queued_requests_timeout(self): + """ Verify that queued requests timeout as expected """ + start_and_prime_singledc() + profile = ExecutionProfile(request_timeout=.1, load_balancing_policy=RoundRobinPolicy()) + cluster = Cluster( + protocol_version=PROTOCOL_VERSION, + compression=False, + execution_profiles={EXEC_PROFILE_DEFAULT: profile}, + ) + session = cluster.connect(wait_for_all_pools=True) + self.addCleanup(cluster.shutdown) + + query = session.prepare("INSERT INTO table1 (id) VALUES (?)") + + prime_request(PauseReads()) + + futures = [] + for i in range(1000): + future = session.execute_async(query, [str(i)]) + future.add_callbacks(callback=self.callback_success, errback=self.callback_error) + futures.append(future) + + successes = 0 + for future in futures: + try: + future.result() + successes += 1 + except OperationTimedOut: + pass + + # Simulacron will respond to a couple queries before cutting off reads, so we'll just verify + # that only "a few" successes happened here + self.assertLess(successes, 50) + self.assertLess(self.callback_successes, 50) + self.assertEqual(self.callback_errors, len(futures) - self.callback_successes) + + def test_cluster_busy(self): + """ Verify that once TCP buffer is full we get busy exceptions rather than timeouts """ + start_and_prime_singledc() + profile = ExecutionProfile(load_balancing_policy=RoundRobinPolicy()) + cluster = Cluster( + protocol_version=PROTOCOL_VERSION, + compression=False, + execution_profiles={EXEC_PROFILE_DEFAULT: profile}, + ) + session = cluster.connect(wait_for_all_pools=True) + self.addCleanup(cluster.shutdown) + + query = session.prepare("INSERT INTO table1 (id) VALUES (?)") + + prime_request(PauseReads()) + + # These requests will get stuck in the TCP buffer and we have no choice but to let them time out + self._fill_buffers(session, query, expected_blocked=3) + + # Now that our send buffer is completely full, verify we immediately get busy exceptions rather than timing out + for i in range(1000): + with self.assertRaises(NoHostAvailable) as e: + session.execute(query, [str(i)]) + self.assertIn("ConnectionBusy", str(e.exception)) + + def test_node_busy(self): + """ Verify that once TCP buffer is full, queries continue to get re-routed to other nodes """ + start_and_prime_singledc() + profile = ExecutionProfile(load_balancing_policy=RoundRobinPolicy()) + cluster = Cluster( + protocol_version=PROTOCOL_VERSION, + compression=False, + execution_profiles={EXEC_PROFILE_DEFAULT: profile}, + ) + session = cluster.connect(wait_for_all_pools=True) + self.addCleanup(cluster.shutdown) + + query = session.prepare("INSERT INTO table1 (id) VALUES (?)") + + prime_request(PauseReads(dc_id=0, node_id=0)) + + blocked_profile = ExecutionProfile(load_balancing_policy=WhiteListRoundRobinPolicy(["127.0.0.1"])) + cluster.add_execution_profile('blocked_profile', blocked_profile) + + # Fill our blocked node's tcp buffer until we get a busy exception + self._fill_buffers(session, query, expected_blocked=1, execution_profile='blocked_profile') + + # Now that our send buffer is completely full on one node, + # verify queries get re-routed to other nodes and queries complete successfully + for i in range(1000): + session.execute(query, [str(i)]) + diff --git a/tests/integration/simulacron/test_cluster.py b/tests/integration/simulacron/test_cluster.py index ec20c10..b89f564 100644 --- a/tests/integration/simulacron/test_cluster.py +++ b/tests/integration/simulacron/test_cluster.py @@ -1,80 +1,113 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa -from tests.integration.simulacron import SimulacronCluster -from tests.integration import (requiressimulacron, PROTOCOL_VERSION) -from tests.integration.simulacron.utils import prime_query +import logging +from packaging.version import Version + +import cassandra +from tests.integration.simulacron import SimulacronCluster, SimulacronBase +from tests.integration import (requiressimulacron, PROTOCOL_VERSION, DSE_VERSION, MockLoggingHandler) +from tests.integration.simulacron.utils import prime_query, start_and_prime_singledc from cassandra import (WriteTimeout, WriteType, ConsistencyLevel, UnresolvableContactPoints) -from cassandra.cluster import Cluster +from cassandra.cluster import Cluster, ControlConnection + +PROTOCOL_VERSION = min(4, PROTOCOL_VERSION if (DSE_VERSION is None or DSE_VERSION >= Version('5.0')) else 3) @requiressimulacron class ClusterTests(SimulacronCluster): def test_writetimeout(self): write_type = "UNLOGGED_BATCH" consistency = "LOCAL_QUORUM" received_responses = 1 required_responses = 4 query_to_prime_simple = "SELECT * from simulacron_keyspace.simple" then = { "result": "write_timeout", "delay_in_ms": 0, "consistency_level": consistency, "received": received_responses, "block_for": required_responses, "write_type": write_type, "ignore_on_prepare": True } prime_query(query_to_prime_simple, then=then, rows=None, column_types=None) with self.assertRaises(WriteTimeout) as assert_raised_context: self.session.execute(query_to_prime_simple) wt = assert_raised_context.exception self.assertEqual(wt.write_type, WriteType.name_to_value[write_type]) self.assertEqual(wt.consistency, ConsistencyLevel.name_to_value[consistency]) self.assertEqual(wt.received_responses, received_responses) self.assertEqual(wt.required_responses, required_responses) self.assertIn(write_type, str(wt)) self.assertIn(consistency, str(wt)) self.assertIn(str(received_responses), str(wt)) self.assertIn(str(required_responses), str(wt)) @requiressimulacron class ClusterDNSResolutionTests(SimulacronCluster): connect = False def tearDown(self): if self.cluster: self.cluster.shutdown() def test_connection_with_one_unresolvable_contact_point(self): # shouldn't raise anything due to name resolution failures self.cluster = Cluster(['127.0.0.1', 'dns.invalid'], protocol_version=PROTOCOL_VERSION, compression=False) def test_connection_with_only_unresolvable_contact_points(self): with self.assertRaises(UnresolvableContactPoints): self.cluster = Cluster(['dns.invalid'], protocol_version=PROTOCOL_VERSION, compression=False) + + +@requiressimulacron +class DuplicateRpcTest(SimulacronCluster): + connect = False + + def test_duplicate(self): + mock_handler = MockLoggingHandler() + logger = logging.getLogger(cassandra.cluster.__name__) + logger.addHandler(mock_handler) + address_column = "native_transport_address" if DSE_VERSION and DSE_VERSION > Version("6.0") else "rpc_address" + rows = [ + {"peer": "127.0.0.1", "data_center": "dc", "host_id": "dontcare1", "rack": "rack1", + "release_version": "3.11.4", address_column: "127.0.0.1", "schema_version": "dontcare", "tokens": "1"}, + {"peer": "127.0.0.2", "data_center": "dc", "host_id": "dontcare2", "rack": "rack1", + "release_version": "3.11.4", address_column: "127.0.0.2", "schema_version": "dontcare", "tokens": "2"}, + ] + prime_query(ControlConnection._SELECT_PEERS, rows=rows) + + cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) + session = cluster.connect(wait_for_all_pools=True) + + warnings = mock_handler.messages.get("warning") + self.assertEqual(len(warnings), 1) + self.assertTrue('multiple hosts with the same endpoint' in warnings[0]) + logger.removeHandler(mock_handler) + cluster.shutdown() diff --git a/tests/integration/simulacron/test_connection.py b/tests/integration/simulacron/test_connection.py index c19b616..4ef9724 100644 --- a/tests/integration/simulacron/test_connection.py +++ b/tests/integration/simulacron/test_connection.py @@ -1,468 +1,513 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa import logging import time from mock import Mock, patch from cassandra import OperationTimedOut from cassandra.cluster import (EXEC_PROFILE_DEFAULT, Cluster, ExecutionProfile, _Scheduler, NoHostAvailable) -from cassandra.policies import HostStateListener, RoundRobinPolicy -from cassandra.io.asyncorereactor import AsyncoreConnection -from cassandra.connection import DEFAULT_CQL_VERSION +from cassandra.policies import HostStateListener, RoundRobinPolicy, WhiteListRoundRobinPolicy + from tests import connection_class, thread_pool_executor_class +from tests.util import late +from tests.integration import requiressimulacron, libevtest +from tests.integration.util import assert_quiescent_pool_state +# important to import the patch PROTOCOL_VERSION from the simulacron module +from tests.integration.simulacron import SimulacronBase, PROTOCOL_VERSION +from cassandra.connection import DEFAULT_CQL_VERSION, Connection from tests.unit.cython.utils import cythontest -from tests.integration import (PROTOCOL_VERSION, requiressimulacron) -from tests.integration.util import assert_quiescent_pool_state, late -from tests.integration.simulacron import SimulacronBase from tests.integration.simulacron.utils import (NO_THEN, PrimeOptions, prime_query, prime_request, start_and_prime_cluster_defaults, start_and_prime_singledc, clear_queries, RejectConnections, - RejectType, AcceptConnections) + RejectType, AcceptConnections, PauseReads, ResumeReads) class TrackDownListener(HostStateListener): def __init__(self): self.hosts_marked_down = [] def on_down(self, host): self.hosts_marked_down.append(host) def on_up(self, host): pass def on_add(self, host): pass def on_remove(self, host): pass class ThreadTracker(thread_pool_executor_class): called_functions = [] def submit(self, fn, *args, **kwargs): self.called_functions.append(fn.__name__) return super(ThreadTracker, self).submit(fn, *args, **kwargs) class OrderedRoundRobinPolicy(RoundRobinPolicy): def make_query_plan(self, working_keyspace=None, query=None): self._position += 1 hosts = [] for _ in range(10): hosts.extend(sorted(self._live_hosts, key=lambda x : x.address)) return hosts def _send_options_message(self): """ Mock that doesn't the OptionMessage. It is required for the heart_beat_timeout test to avoid a condition where the CC tries to reconnect in the executor but can't since we prime that message.""" self._compressor = None self.cql_version = DEFAULT_CQL_VERSION self._send_startup_message(no_compact=self.no_compact) @requiressimulacron class ConnectionTests(SimulacronBase): @patch('cassandra.connection.Connection._send_options_message', _send_options_message) def test_heart_beat_timeout(self): """ Test to ensure the hosts are marked as down after a OTO is received. Also to ensure this happens within the expected timeout @since 3.10 @jira_ticket PYTHON-762 @expected_result all the hosts have been marked as down at some point @test_category metadata """ number_of_dcs = 3 nodes_per_dc = 20 query_to_prime = "INSERT INTO test3rf.test (k, v) VALUES (0, 1);" idle_heartbeat_timeout = 5 idle_heartbeat_interval = 1 start_and_prime_cluster_defaults(number_of_dcs, nodes_per_dc) listener = TrackDownListener() executor = ThreadTracker(max_workers=8) # We need to disable compression since it's not supported in simulacron cluster = Cluster(compression=False, idle_heartbeat_interval=idle_heartbeat_interval, idle_heartbeat_timeout=idle_heartbeat_timeout, + protocol_version=PROTOCOL_VERSION, executor_threads=8, execution_profiles={ EXEC_PROFILE_DEFAULT: ExecutionProfile(load_balancing_policy=RoundRobinPolicy())}) self.addCleanup(cluster.shutdown) cluster.scheduler.shutdown() cluster.executor = executor cluster.scheduler = _Scheduler(executor) session = cluster.connect(wait_for_all_pools=True) cluster.register_listener(listener) log = logging.getLogger() log.setLevel('CRITICAL') self.addCleanup(log.setLevel, "DEBUG") prime_query(query_to_prime, then=NO_THEN) futures = [] for _ in range(number_of_dcs * nodes_per_dc): future = session.execute_async(query_to_prime) futures.append(future) for f in futures: f._event.wait() self.assertIsInstance(f._final_exception, OperationTimedOut) prime_request(PrimeOptions(then=NO_THEN)) # We allow from some extra time for all the hosts to be to on_down # The callbacks should start happening after idle_heartbeat_timeout + idle_heartbeat_interval time.sleep((idle_heartbeat_timeout + idle_heartbeat_interval) * 2.5) for host in cluster.metadata.all_hosts(): self.assertIn(host, listener.hosts_marked_down) # In this case HostConnection._replace shouldn't be called self.assertNotIn("_replace", executor.called_functions) def test_callbacks_and_pool_when_oto(self): """ Test to ensure the callbacks are correcltly called and the connection is returned when there is an OTO @since 3.12 @jira_ticket PYTHON-630 @expected_result the connection is correctly returned to the pool after an OTO, also the only the errback is called and not the callback when the message finally arrives. @test_category metadata """ start_and_prime_singledc() cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) session = cluster.connect() self.addCleanup(cluster.shutdown) query_to_prime = "SELECT * from testkesypace.testtable" server_delay = 2 # seconds prime_query(query_to_prime, then={"delay_in_ms": server_delay * 1000}) future = session.execute_async(query_to_prime, timeout=1) callback, errback = Mock(name='callback'), Mock(name='errback') future.add_callbacks(callback, errback) self.assertRaises(OperationTimedOut, future.result) assert_quiescent_pool_state(self, cluster) time.sleep(server_delay + 1) # PYTHON-630 -- only the errback should be called errback.assert_called_once() callback.assert_not_called() @cythontest + @libevtest def test_heartbeat_defunct_deadlock(self): """ Ensure that there is no deadlock when request is in-flight and heartbeat defuncts connection @since 3.16 @jira_ticket PYTHON-1044 @expected_result an OperationTimeout is raised and no deadlock occurs @test_category connection """ start_and_prime_singledc() # This is all about timing. We will need the QUERY response future to time out and the heartbeat to defunct # at the same moment. The latter will schedule a QUERY retry to another node in case the pool is not # already shut down. If and only if the response future timeout falls in between the retry scheduling and # its execution the deadlock occurs. The odds are low, so we need to help fate a bit: # 1) Make one heartbeat messages be sent to every node # 2) Our QUERY goes always to the same host # 3) This host needs to defunct first # 4) Open a small time window for the response future timeout, i.e. block executor threads for retry # execution and last connection to defunct query_to_prime = "SELECT * from testkesypace.testtable" query_host = "127.0.0.2" heartbeat_interval = 1 heartbeat_timeout = 1 lag = 0.05 never = 9999 class PatchedRoundRobinPolicy(RoundRobinPolicy): # Send always to same host def make_query_plan(self, working_keyspace=None, query=None): if query and query.query_string == query_to_prime: return filter(lambda h: h == query_host, self._live_hosts) else: return super(PatchedRoundRobinPolicy, self).make_query_plan() class PatchedCluster(Cluster): # Make sure that QUERY connection will timeout first def get_connection_holders(self): holders = super(PatchedCluster, self).get_connection_holders() return sorted(holders, reverse=True, key=lambda v: int(v._connection.host == query_host)) # Block executor thread like closing a dead socket could do def connection_factory(self, *args, **kwargs): conn = super(PatchedCluster, self).connection_factory(*args, **kwargs) conn.defunct = late(seconds=2*lag)(conn.defunct) return conn cluster = PatchedCluster( protocol_version=PROTOCOL_VERSION, compression=False, idle_heartbeat_interval=heartbeat_interval, idle_heartbeat_timeout=heartbeat_timeout, load_balancing_policy=PatchedRoundRobinPolicy() ) session = cluster.connect() self.addCleanup(cluster.shutdown) prime_query(query_to_prime, then={"delay_in_ms": never}) # Make heartbeat due time.sleep(heartbeat_interval) future = session.execute_async(query_to_prime, timeout=heartbeat_interval+heartbeat_timeout+3*lag) # Delay thread execution like kernel could do future._retry_task = late(seconds=4*lag)(future._retry_task) prime_request(PrimeOptions(then={"result": "no_result", "delay_in_ms": never})) prime_request(RejectConnections("unbind")) self.assertRaisesRegexp(OperationTimedOut, "Connection defunct by heartbeat", future.result) def test_close_when_query(self): """ Test to ensure the driver behaves correctly if the connection is closed just when querying @since 3.12 @expected_result NoHostAvailable is risen @test_category connection """ start_and_prime_singledc() cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) session = cluster.connect() self.addCleanup(cluster.shutdown) query_to_prime = "SELECT * from testkesypace.testtable" for close_type in ("disconnect", "shutdown_read", "shutdown_write"): then = { "result": "close_connection", "delay_in_ms": 0, "close_type": close_type, "scope": "connection" } - prime_query(query_to_prime, then=then, rows=None, column_types=None) + prime_query(query_to_prime, rows=None, column_types=None, then=then) self.assertRaises(NoHostAvailable, session.execute, query_to_prime) def test_retry_after_defunct(self): """ We test cluster._retry is called if an the connection is defunct in the middle of a query Finally we verify the driver recovers correctly in the event of a network partition @since 3.12 @expected_result the driver is able to query even if a host is marked as down in the middle of the query, it will go to the next one if the timeout hasn't expired @test_category connection """ number_of_dcs = 3 nodes_per_dc = 2 query_to_prime = "INSERT INTO test3rf.test (k, v) VALUES (0, 1);" idle_heartbeat_timeout = 1 idle_heartbeat_interval = 5 simulacron_cluster = start_and_prime_cluster_defaults(number_of_dcs, nodes_per_dc) dc_ids = sorted(simulacron_cluster.data_center_ids) last_host = dc_ids.pop() prime_query(query_to_prime, cluster_name="{}/{}".format(simulacron_cluster.cluster_name, last_host)) roundrobin_lbp = OrderedRoundRobinPolicy() - cluster = Cluster(compression=False, + cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False, idle_heartbeat_interval=idle_heartbeat_interval, idle_heartbeat_timeout=idle_heartbeat_timeout, execution_profiles={ EXEC_PROFILE_DEFAULT: ExecutionProfile(load_balancing_policy=roundrobin_lbp)}) session = cluster.connect(wait_for_all_pools=True) self.addCleanup(cluster.shutdown) # This simulates we only have access to one DC for dc_id in dc_ids: datacenter_path = "{}/{}".format(simulacron_cluster.cluster_name, dc_id) prime_query(query_to_prime, then=NO_THEN, cluster_name=datacenter_path) prime_request(PrimeOptions(then=NO_THEN, cluster_name=datacenter_path)) # Only the last datacenter will respond, therefore the first host won't # We want to make sure the returned hosts are 127.0.0.1, 127.0.0.2, ... 127.0.0.8 roundrobin_lbp._position = 0 # After 3 + 1 seconds the connection should be marked and down and another host retried response_future = session.execute_async(query_to_prime, timeout=4 * idle_heartbeat_interval + idle_heartbeat_timeout) response_future.result() self.assertGreater(len(response_future.attempted_hosts), 1) # No error should be raised here since the hosts have been marked # as down and there's still 1 DC available for _ in range(10): session.execute(query_to_prime) # Might take some time to close the previous connections and reconnect time.sleep(10) assert_quiescent_pool_state(self, cluster) clear_queries() time.sleep(10) assert_quiescent_pool_state(self, cluster) def test_idle_connection_is_not_closed(self): """ Test to ensure that the connections aren't closed if they are idle @since 3.12 @jira_ticket PYTHON-573 @expected_result the connections aren't closed nor the hosts are set to down if the connection is idle @test_category connection """ start_and_prime_singledc() idle_heartbeat_timeout = 1 idle_heartbeat_interval = 1 listener = TrackDownListener() - cluster = Cluster(compression=False, + cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False, idle_heartbeat_interval=idle_heartbeat_interval, idle_heartbeat_timeout=idle_heartbeat_timeout) session = cluster.connect(wait_for_all_pools=True) cluster.register_listener(listener) self.addCleanup(cluster.shutdown) time.sleep(20) self.assertEqual(listener.hosts_marked_down, []) def test_host_is_not_set_to_down_after_query_oto(self): """ Test to ensure that the connections aren't closed if there's an OperationTimedOut in a normal query. This should only happen from the heart beat thread (in the case of a OperationTimedOut) with the default configuration @since 3.12 @expected_result the connections aren't closed nor the hosts are set to down @test_category connection """ start_and_prime_singledc() query_to_prime = "SELECT * FROM madeup_keyspace.madeup_table" prime_query(query_to_prime, then=NO_THEN) listener = TrackDownListener() - cluster = Cluster(compression=False) + cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) session = cluster.connect(wait_for_all_pools=True) cluster.register_listener(listener) futures = [] for _ in range(10): future = session.execute_async(query_to_prime) futures.append(future) for f in futures: f._event.wait() self.assertIsInstance(f._final_exception, OperationTimedOut) self.assertEqual(listener.hosts_marked_down, []) assert_quiescent_pool_state(self, cluster) def test_can_shutdown_connection_subclass(self): start_and_prime_singledc() class ExtendedConnection(connection_class): pass - cluster = Cluster(contact_points=["127.0.0.2"], - connection_class=ExtendedConnection) + cluster = Cluster(protocol_version=PROTOCOL_VERSION, + contact_points=["127.0.0.2"], + connection_class=ExtendedConnection, + compression=False) cluster.connect() cluster.shutdown() def test_driver_recovers_nework_isolation(self): start_and_prime_singledc() idle_heartbeat_timeout = 3 idle_heartbeat_interval = 1 listener = TrackDownListener() - cluster = Cluster(['127.0.0.1'], - load_balancing_policy=RoundRobinPolicy(), + cluster = Cluster(protocol_version=PROTOCOL_VERSION, contact_points=['127.0.0.1'], idle_heartbeat_timeout=idle_heartbeat_timeout, idle_heartbeat_interval=idle_heartbeat_interval, - executor_threads=16) + executor_threads=16, + compression=False, + execution_profiles={ + EXEC_PROFILE_DEFAULT: ExecutionProfile(load_balancing_policy=RoundRobinPolicy()) + }) session = cluster.connect(wait_for_all_pools=True) cluster.register_listener(listener) prime_request(PrimeOptions(then=NO_THEN)) prime_request(RejectConnections(RejectType.REJECT_STARTUP)) time.sleep((idle_heartbeat_timeout + idle_heartbeat_interval) * 2) for host in cluster.metadata.all_hosts(): self.assertIn(host, listener.hosts_marked_down) self.assertRaises(NoHostAvailable, session.execute, "SELECT * from system.local") clear_queries() prime_request(AcceptConnections()) time.sleep(idle_heartbeat_timeout + idle_heartbeat_interval + 2) self.assertIsNotNone(session.execute("SELECT * from system.local")) + + def test_max_in_flight(self): + """ Verify we don't exceed max_in_flight when borrowing connections or sending heartbeats """ + Connection.max_in_flight = 50 + start_and_prime_singledc() + profile = ExecutionProfile(request_timeout=1, load_balancing_policy=WhiteListRoundRobinPolicy(['127.0.0.1'])) + cluster = Cluster( + protocol_version=PROTOCOL_VERSION, + compression=False, + execution_profiles={EXEC_PROFILE_DEFAULT: profile}, + idle_heartbeat_interval=.1, + idle_heartbeat_timeout=.1, + ) + session = cluster.connect(wait_for_all_pools=True) + self.addCleanup(cluster.shutdown) + + query = session.prepare("INSERT INTO table1 (id) VALUES (?)") + + prime_request(PauseReads()) + + futures = [] + # + 50 because simulacron doesn't immediately block all queries + for i in range(Connection.max_in_flight + 50): + futures.append(session.execute_async(query, ['a'])) + + prime_request(ResumeReads()) + + for future in futures: + # We're veryfing we don't get an assertion error from Connection.get_request_id, + # so skip any valid errors + try: + future.result() + except OperationTimedOut: + pass + except NoHostAvailable: + pass diff --git a/tests/integration/simulacron/test_empty_column.py b/tests/integration/simulacron/test_empty_column.py index e07534f..91c7698 100644 --- a/tests/integration/simulacron/test_empty_column.py +++ b/tests/integration/simulacron/test_empty_column.py @@ -1,257 +1,258 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from collections import namedtuple, OrderedDict -from cassandra.cluster import Cluster +from cassandra import ProtocolVersion +from cassandra.cluster import Cluster, EXEC_PROFILE_DEFAULT from cassandra.query import (named_tuple_factory, tuple_factory, dict_factory, ordered_dict_factory) from cassandra.cqlengine import columns from cassandra.cqlengine.connection import set_session from cassandra.cqlengine.models import Model -from tests.integration import PROTOCOL_VERSION, requiressimulacron -from tests.integration.simulacron import SimulacronCluster +from tests.integration import requiressimulacron +from tests.integration.simulacron import PROTOCOL_VERSION, SimulacronCluster from tests.integration.simulacron.utils import PrimeQuery, prime_request +PROTOCOL_VERSION = 4 if PROTOCOL_VERSION in \ + (ProtocolVersion.DSE_V1, ProtocolVersion.DSE_V2) else PROTOCOL_VERSION + + @requiressimulacron class EmptyColumnTests(SimulacronCluster): """ Test that legacy empty column names can be read by the driver. @since 3.18 @jira_ticket PYTHON-1082 @expected_result the driver supports those columns """ connect = False def tearDown(self): if self.cluster: self.cluster.shutdown() @staticmethod def _prime_testtable_query(): queries = [ 'SELECT "", " " FROM testks.testtable', 'SELECT "", " " FROM testks.testtable LIMIT 10000' # cqlengine ] then = { 'result': 'success', 'delay_in_ms': 0, 'rows': [ { "": "testval", " ": "testval1" } ], 'column_types': { "": "ascii", " ": "ascii" }, 'ignore_on_prepare': False } for query in queries: prime_request(PrimeQuery(query, then=then)) def test_empty_columns_with_all_row_factories(self): query = 'SELECT "", " " FROM testks.testtable' self._prime_testtable_query() - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) self.session = self.cluster.connect(wait_for_all_pools=True) # Test all row factories - self.session.row_factory = named_tuple_factory + self.cluster.profile_manager.profiles[EXEC_PROFILE_DEFAULT].row_factory = named_tuple_factory self.assertEqual( list(self.session.execute(query)), [namedtuple('Row', ['field_0_', 'field_1_'])('testval', 'testval1')] ) - self.session.row_factory = tuple_factory + self.cluster.profile_manager.profiles[EXEC_PROFILE_DEFAULT].row_factory = tuple_factory self.assertEqual( list(self.session.execute(query)), [('testval', 'testval1')] ) - self.session.row_factory = dict_factory + self.cluster.profile_manager.profiles[EXEC_PROFILE_DEFAULT].row_factory = dict_factory self.assertEqual( list(self.session.execute(query)), [{'': 'testval', ' ': 'testval1'}] ) - self.session.row_factory = ordered_dict_factory + self.cluster.profile_manager.profiles[EXEC_PROFILE_DEFAULT].row_factory = ordered_dict_factory self.assertEqual( list(self.session.execute(query)), [OrderedDict((('', 'testval'), (' ', 'testval1')))] ) def test_empty_columns_in_system_schema(self): queries = [ "SELECT * FROM system_schema.tables", "SELECT * FROM system.schema.tables", "SELECT * FROM system.schema_columnfamilies" ] then = { 'result': 'success', 'delay_in_ms': 0, 'rows': [ { "compression": dict(), "compaction": dict(), "bloom_filter_fp_chance": 0.1, "caching": {"keys": "ALL", "rows_per_partition": "NONE"}, "comment": "comment", "gc_grace_seconds": 60000, - "dclocal_read_repair_chance": 0.1, - "read_repair_chance": 0.1, "keyspace_name": "testks", "table_name": "testtable", "columnfamily_name": "testtable", # C* 2.2 "flags": ["compound"], "comparator": "none" # C* 2.2 } ], 'column_types': { "compression": "map", "compaction": "map", "bloom_filter_fp_chance": "double", "caching": "map", "comment": "ascii", "gc_grace_seconds": "int", - "dclocal_read_repair_chance": "double", - "read_repair_chance": "double", "keyspace_name": "ascii", "table_name": "ascii", "columnfamily_name": "ascii", "flags": "set", "comparator": "ascii" }, 'ignore_on_prepare': False } for query in queries: query = PrimeQuery(query, then=then) prime_request(query) queries = [ "SELECT * FROM system_schema.keyspaces", "SELECT * FROM system.schema_keyspaces" ] then = { 'result': 'success', 'delay_in_ms': 0, 'rows': [ { "strategy_class": "SimpleStrategy", # C* 2.2 "strategy_options": '{}', # C* 2.2 "replication": {'strategy': 'SimpleStrategy', 'replication_factor': 1}, "durable_writes": True, "keyspace_name": "testks" } ], 'column_types': { "strategy_class": "ascii", "strategy_options": "ascii", "replication": "map", "keyspace_name": "ascii", "durable_writes": "boolean" }, 'ignore_on_prepare': False } for query in queries: query = PrimeQuery(query, then=then) prime_request(query) queries = [ "SELECT * FROM system_schema.columns", "SELECT * FROM system.schema.columns", "SELECT * FROM system.schema_columns" ] then = { 'result': 'success', 'delay_in_ms': 0, 'rows': [ { "table_name": 'testtable', "columnfamily_name": 'testtable', # C* 2.2 "column_name": "", "keyspace_name": "testks", "kind": "partition_key", "clustering_order": "none", "position": 0, "type": "text", "column_name_bytes": 0x12, "validator": "none" # C* 2.2 }, { "table_name": 'testtable', "columnfamily_name": 'testtable', # C* 2.2 "column_name": " ", "keyspace_name": "testks", "kind": "regular", "clustering_order": "none", "position": -1, "type": "text", "column_name_bytes": 0x13, "validator": "none" # C* 2.2 } ], 'column_types': { "table_name": "ascii", "columnfamily_name": "ascii", "column_name": "ascii", "keyspace_name": "ascii", "clustering_order": "ascii", "column_name_bytes": "blob", "kind": "ascii", "position": "int", "type": "ascii", "validator": "ascii" # C* 2.2 }, 'ignore_on_prepare': False } for query in queries: query = PrimeQuery(query, then=then) prime_request(query) - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) self.session = self.cluster.connect(wait_for_all_pools=True) table_metadata = self.cluster.metadata.keyspaces['testks'].tables['testtable'] self.assertEqual(len(table_metadata.columns), 2) self.assertIn('', table_metadata.columns) self.assertIn(' ', table_metadata.columns) def test_empty_columns_with_cqlengine(self): self._prime_testtable_query() - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) self.session = self.cluster.connect(wait_for_all_pools=True) set_session(self.session) class TestModel(Model): __keyspace__ = 'testks' __table_name__ = 'testtable' empty = columns.Text(db_field='', primary_key=True) space = columns.Text(db_field=' ') self.assertEqual( [TestModel(empty='testval', space='testval1')], list(TestModel.objects.only(['empty', 'space']).all()) ) diff --git a/tests/integration/simulacron/test_endpoint.py b/tests/integration/simulacron/test_endpoint.py index ba95972..691fcc8 100644 --- a/tests/integration/simulacron/test_endpoint.py +++ b/tests/integration/simulacron/test_endpoint.py @@ -1,121 +1,117 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from functools import total_ordering from cassandra.cluster import Cluster -from cassandra.connection import DefaultEndPoint, EndPoint, EndPointFactory -from tests.integration import (PROTOCOL_VERSION, requiressimulacron) -from tests.integration.simulacron import SimulacronCluster +from cassandra.connection import DefaultEndPoint, EndPoint, DefaultEndPointFactory +from cassandra.metadata import _NodeInfo +from tests.integration import requiressimulacron +from tests.integration.simulacron import SimulacronCluster, PROTOCOL_VERSION @total_ordering class AddressEndPoint(EndPoint): def __init__(self, address, port=9042): self._address = address self._port = port @property def address(self): return self._address @property def port(self): return self._port def resolve(self): return self._address, self._port # connection purpose def __eq__(self, other): return isinstance(other, AddressEndPoint) and \ self.address == other.address def __hash__(self): return hash(self.address) def __lt__(self, other): return self.address < other.address def __str__(self): return str("%s" % self.address) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self.address) -class AddressEndPointFactory(EndPointFactory): +class AddressEndPointFactory(DefaultEndPointFactory): def create(self, row): - addr = None - if "rpc_address" in row: - addr = row.get("rpc_address") - if "native_transport_address" in row: - addr = row.get("native_transport_address") - if not addr or addr in ["0.0.0.0", "::"]: - addr = row.get("peer") - + addr = _NodeInfo.get_broadcast_rpc_address(row) return AddressEndPoint(addr) @requiressimulacron class EndPointTests(SimulacronCluster): """ Basic tests to validate the internal use of the EndPoint class. @since 3.18 @jira_ticket PYTHON-1079 @expected_result all the hosts are using the proper endpoint class """ def test_default_endpoint(self): hosts = self.cluster.metadata.all_hosts() + self.assertEqual(len(hosts), 3) for host in hosts: self.assertIsNotNone(host.endpoint) self.assertIsInstance(host.endpoint, DefaultEndPoint) self.assertEqual(host.address, host.endpoint.address) self.assertEqual(host.broadcast_rpc_address, host.endpoint.address) self.assertIsInstance(self.cluster.control_connection._connection.endpoint, DefaultEndPoint) self.assertIsNotNone(self.cluster.control_connection._connection.endpoint) endpoints = [host.endpoint for host in hosts] self.assertIn(self.cluster.control_connection._connection.endpoint, endpoints) def test_custom_endpoint(self): cluster = Cluster( contact_points=[AddressEndPoint('127.0.0.1')], protocol_version=PROTOCOL_VERSION, endpoint_factory=AddressEndPointFactory(), compression=False, ) cluster.connect(wait_for_all_pools=True) hosts = cluster.metadata.all_hosts() + self.assertEqual(len(hosts), 3) for host in hosts: self.assertIsNotNone(host.endpoint) self.assertIsInstance(host.endpoint, AddressEndPoint) self.assertEqual(str(host.endpoint), host.endpoint.address) self.assertEqual(host.address, host.endpoint.address) self.assertEqual(host.broadcast_rpc_address, host.endpoint.address) self.assertIsInstance(cluster.control_connection._connection.endpoint, AddressEndPoint) self.assertIsNotNone(cluster.control_connection._connection.endpoint) endpoints = [host.endpoint for host in hosts] self.assertIn(cluster.control_connection._connection.endpoint, endpoints) cluster.shutdown() diff --git a/tests/integration/simulacron/test_policies.py b/tests/integration/simulacron/test_policies.py index d7a6775..da093be 100644 --- a/tests/integration/simulacron/test_policies.py +++ b/tests/integration/simulacron/test_policies.py @@ -1,451 +1,464 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from cassandra import OperationTimedOut, WriteTimeout -from cassandra.cluster import Cluster, ExecutionProfile, ResponseFuture +from cassandra.cluster import Cluster, ExecutionProfile, ResponseFuture, EXEC_PROFILE_DEFAULT, NoHostAvailable from cassandra.query import SimpleStatement from cassandra.policies import ConstantSpeculativeExecutionPolicy, RoundRobinPolicy, RetryPolicy, WriteType +from cassandra.protocol import OverloadedErrorMessage, IsBootstrappingErrorMessage, TruncateError, ServerError -from tests.integration import PROTOCOL_VERSION, greaterthancass21, requiressimulacron, SIMULACRON_JAR, \ +from tests.integration import greaterthancass21, requiressimulacron, SIMULACRON_JAR, \ CASSANDRA_VERSION +from tests.integration.simulacron import PROTOCOL_VERSION from tests.integration.simulacron.utils import start_and_prime_singledc, prime_query, \ stop_simulacron, NO_THEN, clear_queries from itertools import count from packaging.version import Version class BadRoundRobinPolicy(RoundRobinPolicy): def make_query_plan(self, working_keyspace=None, query=None): pos = self._position self._position += 1 hosts = [] for _ in range(10): hosts.extend(self._live_hosts) return hosts # This doesn't work well with Windows clock granularity @requiressimulacron class SpecExecTest(unittest.TestCase): @classmethod def setUpClass(cls): if SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"): return start_and_prime_singledc() cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) cls.session = cls.cluster.connect(wait_for_all_pools=True) spec_ep_brr = ExecutionProfile(load_balancing_policy=BadRoundRobinPolicy(), speculative_execution_policy=ConstantSpeculativeExecutionPolicy(1, 6), request_timeout=12) spec_ep_rr = ExecutionProfile(speculative_execution_policy=ConstantSpeculativeExecutionPolicy(.5, 10), request_timeout=12) spec_ep_rr_lim = ExecutionProfile(load_balancing_policy=BadRoundRobinPolicy(), speculative_execution_policy=ConstantSpeculativeExecutionPolicy(0.5, 1), request_timeout=12) spec_ep_brr_lim = ExecutionProfile(load_balancing_policy=BadRoundRobinPolicy(), speculative_execution_policy=ConstantSpeculativeExecutionPolicy(4, 10)) cls.cluster.add_execution_profile("spec_ep_brr", spec_ep_brr) cls.cluster.add_execution_profile("spec_ep_rr", spec_ep_rr) cls.cluster.add_execution_profile("spec_ep_rr_lim", spec_ep_rr_lim) cls.cluster.add_execution_profile("spec_ep_brr_lim", spec_ep_brr_lim) @classmethod def tearDownClass(cls): if SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"): return cls.cluster.shutdown() stop_simulacron() def tearDown(self): clear_queries() @greaterthancass21 def test_speculative_execution(self): """ Test to ensure that speculative execution honors LBP, and that they retry appropriately. This test will use various LBP, and ConstantSpeculativeExecutionPolicy settings and ensure the proper number of hosts are queried @since 3.7.0 @jira_ticket PYTHON-218 @expected_result speculative retries should honor max retries, idempotent state of queries, and underlying lbp. @test_category metadata """ query_to_prime = "INSERT INTO test3rf.test (k, v) VALUES (0, 1);" prime_query(query_to_prime, then={"delay_in_ms": 10000}) statement = SimpleStatement(query_to_prime, is_idempotent=True) statement_non_idem = SimpleStatement(query_to_prime, is_idempotent=False) # This LBP should repeat hosts up to around 30 result = self.session.execute(statement, execution_profile='spec_ep_brr') self.assertEqual(7, len(result.response_future.attempted_hosts)) # This LBP should keep host list to 3 result = self.session.execute(statement, execution_profile='spec_ep_rr') self.assertEqual(3, len(result.response_future.attempted_hosts)) # Spec_execution policy should limit retries to 1 result = self.session.execute(statement, execution_profile='spec_ep_rr_lim') self.assertEqual(2, len(result.response_future.attempted_hosts)) # Spec_execution policy should not be used if the query is not idempotent result = self.session.execute(statement_non_idem, execution_profile='spec_ep_brr') self.assertEqual(1, len(result.response_future.attempted_hosts)) # Default policy with non_idem query result = self.session.execute(statement_non_idem, timeout=12) self.assertEqual(1, len(result.response_future.attempted_hosts)) # Should be able to run an idempotent query against default execution policy with no speculative_execution_policy result = self.session.execute(statement, timeout=12) self.assertEqual(1, len(result.response_future.attempted_hosts)) # Test timeout with spec_ex with self.assertRaises(OperationTimedOut): self.session.execute(statement, execution_profile='spec_ep_rr', timeout=.5) prepared_query_to_prime = "SELECT * FROM test3rf.test where k = ?" when = {"params": {"k": "0"}, "param_types": {"k": "ascii"}} prime_query(prepared_query_to_prime, when=when, then={"delay_in_ms": 4000}) # PYTHON-736 Test speculation policy works with a prepared statement prepared_statement = self.session.prepare(prepared_query_to_prime) # non-idempotent result = self.session.execute(prepared_statement, ("0",), execution_profile='spec_ep_brr') self.assertEqual(1, len(result.response_future.attempted_hosts)) # idempotent prepared_statement.is_idempotent = True result = self.session.execute(prepared_statement, ("0",), execution_profile='spec_ep_brr') self.assertLess(1, len(result.response_future.attempted_hosts)) def test_speculative_and_timeout(self): """ Test to ensure the timeout is honored when using speculative execution @since 3.10 @jira_ticket PYTHON-750 @expected_result speculative retries be schedule every fixed period, during the maximum period of the timeout. @test_category metadata """ query_to_prime = "INSERT INTO testkeyspace.testtable (k, v) VALUES (0, 1);" prime_query(query_to_prime, then=NO_THEN) statement = SimpleStatement(query_to_prime, is_idempotent=True) # An OperationTimedOut is placed here in response_future, # that's why we can't call session.execute,which would raise it, but # we have to directly wait for the event response_future = self.session.execute_async(statement, execution_profile='spec_ep_brr_lim', timeout=14) response_future._event.wait(16) self.assertIsInstance(response_future._final_exception, OperationTimedOut) # This is because 14 / 4 + 1 = 4 self.assertEqual(len(response_future.attempted_hosts), 4) def test_delay_can_be_0(self): """ Test to validate that the delay can be zero for the ConstantSpeculativeExecutionPolicy @since 3.13 @jira_ticket PYTHON-836 @expected_result all the queries are executed immediately @test_category policy """ query_to_prime = "INSERT INTO madeup_keyspace.madeup_table(k, v) VALUES (1, 2)" prime_query(query_to_prime, then={"delay_in_ms": 5000}) number_of_requests = 4 spec = ExecutionProfile(load_balancing_policy=RoundRobinPolicy(), speculative_execution_policy=ConstantSpeculativeExecutionPolicy(0, number_of_requests)) - cluster = Cluster() + cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False) cluster.add_execution_profile("spec", spec) session = cluster.connect(wait_for_all_pools=True) self.addCleanup(cluster.shutdown) counter = count() def patch_and_count(f): def patched(*args, **kwargs): next(counter) - print("patched") f(*args, **kwargs) return patched self.addCleanup(setattr, ResponseFuture, "send_request", ResponseFuture.send_request) ResponseFuture.send_request = patch_and_count(ResponseFuture.send_request) stmt = SimpleStatement(query_to_prime) stmt.is_idempotent = True results = session.execute(stmt, execution_profile="spec") self.assertEqual(len(results.response_future.attempted_hosts), 3) # send_request is called number_of_requests times for the speculative request # plus one for the call from the main thread. self.assertEqual(next(counter), number_of_requests + 1) class CustomRetryPolicy(RetryPolicy): def on_write_timeout(self, query, consistency, write_type, required_responses, received_responses, retry_num): if retry_num != 0: return self.RETHROW, None elif write_type == WriteType.SIMPLE: return self.RETHROW, None elif write_type == WriteType.CDC: return self.IGNORE, None class CounterRetryPolicy(RetryPolicy): def __init__(self): self.write_timeout = count() self.read_timeout = count() self.unavailable = count() self.request_error = count() def on_read_timeout(self, query, consistency, required_responses, received_responses, data_retrieved, retry_num): next(self.read_timeout) return self.IGNORE, None def on_write_timeout(self, query, consistency, write_type, required_responses, received_responses, retry_num): next(self.write_timeout) return self.IGNORE, None def on_unavailable(self, query, consistency, required_replicas, alive_replicas, retry_num): next(self.unavailable) return self.IGNORE, None def on_request_error(self, query, consistency, error, retry_num): next(self.request_error) - return self.IGNORE, None + return self.RETHROW, None def reset_counters(self): self.write_timeout = count() self.read_timeout = count() self.unavailable = count() self.request_error = count() @requiressimulacron class RetryPolicyTests(unittest.TestCase): @classmethod def setUpClass(cls): if SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"): return start_and_prime_singledc() @classmethod def tearDownClass(cls): if SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"): return stop_simulacron() def tearDown(self): clear_queries() def set_cluster(self, retry_policy): - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False, - default_retry_policy=retry_policy) + self.cluster = Cluster( + protocol_version=PROTOCOL_VERSION, + compression=False, + execution_profiles={ + EXEC_PROFILE_DEFAULT: ExecutionProfile(retry_policy=retry_policy) + }, + ) self.session = self.cluster.connect(wait_for_all_pools=True) self.addCleanup(self.cluster.shutdown) def test_retry_policy_ignores_and_rethrows(self): """ Test to verify :class:`~cassandra.protocol.WriteTimeoutErrorMessage` is decoded correctly and that :attr:`.~cassandra.policies.RetryPolicy.RETHROW` and :attr:`.~cassandra.policies.RetryPolicy.IGNORE` are respected to localhost @since 3.12 @jira_ticket PYTHON-812 @expected_result the retry policy functions as expected @test_category connection """ self.set_cluster(CustomRetryPolicy()) query_to_prime_simple = "SELECT * from simulacron_keyspace.simple" query_to_prime_cdc = "SELECT * from simulacron_keyspace.cdc" then = { "result": "write_timeout", "delay_in_ms": 0, "consistency_level": "LOCAL_QUORUM", "received": 1, "block_for": 2, "write_type": "SIMPLE", "ignore_on_prepare": True } - prime_query(query_to_prime_simple, then=then, rows=None, column_types=None) + prime_query(query_to_prime_simple, rows=None, column_types=None, then=then) then["write_type"] = "CDC" - prime_query(query_to_prime_cdc, then=then, rows=None, column_types=None) + prime_query(query_to_prime_cdc, rows=None, column_types=None, then=then) with self.assertRaises(WriteTimeout): self.session.execute(query_to_prime_simple) #CDC should be ignored self.session.execute(query_to_prime_cdc) def test_retry_policy_with_prepared(self): """ Test to verify that the retry policy is called as expected for bound and prepared statements when set at the cluster level @since 3.13 @jira_ticket PYTHON-861 @expected_result the appropriate retry policy is called @test_category connection """ counter_policy = CounterRetryPolicy() self.set_cluster(counter_policy) query_to_prime = "SELECT * from simulacron_keyspace.simulacron_table" then = { "result": "write_timeout", "delay_in_ms": 0, "consistency_level": "LOCAL_QUORUM", "received": 1, "block_for": 2, "write_type": "SIMPLE", "ignore_on_prepare": True } prime_query(query_to_prime, then=then, rows=None, column_types=None) self.session.execute(query_to_prime) self.assertEqual(next(counter_policy.write_timeout), 1) counter_policy.reset_counters() query_to_prime_prepared = "SELECT * from simulacron_keyspace.simulacron_table WHERE key = :key" when = {"params": {"key": "0"}, "param_types": {"key": "ascii"}} prime_query(query_to_prime_prepared, when=when, then=then, rows=None, column_types=None) prepared_stmt = self.session.prepare(query_to_prime_prepared) bound_stm = prepared_stmt.bind({"key": "0"}) self.session.execute(bound_stm) self.assertEqual(next(counter_policy.write_timeout), 1) counter_policy.reset_counters() self.session.execute(prepared_stmt, ("0",)) self.assertEqual(next(counter_policy.write_timeout), 1) def test_setting_retry_policy_to_statement(self): """ Test to verify that the retry policy is called as expected for bound and prepared statements when set to the prepared statement @since 3.13 @jira_ticket PYTHON-861 @expected_result the appropriate retry policy is called @test_category connection """ retry_policy = RetryPolicy() self.set_cluster(retry_policy) then = { "result": "write_timeout", "delay_in_ms": 0, "consistency_level": "LOCAL_QUORUM", "received": 1, "block_for": 2, "write_type": "SIMPLE", "ignore_on_prepare": True } query_to_prime_prepared = "SELECT * from simulacron_keyspace.simulacron_table WHERE key = :key" when = {"params": {"key": "0"}, "param_types": {"key": "ascii"}} prime_query(query_to_prime_prepared, when=when, then=then, rows=None, column_types=None) counter_policy = CounterRetryPolicy() prepared_stmt = self.session.prepare(query_to_prime_prepared) prepared_stmt.retry_policy = counter_policy self.session.execute(prepared_stmt, ("0",)) self.assertEqual(next(counter_policy.write_timeout), 1) counter_policy.reset_counters() bound_stmt = prepared_stmt.bind({"key": "0"}) bound_stmt.retry_policy = counter_policy self.session.execute(bound_stmt) self.assertEqual(next(counter_policy.write_timeout), 1) def test_retry_policy_on_request_error(self): """ Test to verify that on_request_error is called properly. @since 3.18 @jira_ticket PYTHON-1064 @expected_result the appropriate retry policy is called @test_category connection """ overloaded_error = { "result": "overloaded", "message": "overloaded" } bootstrapping_error = { "result": "is_bootstrapping", "message": "isbootstrapping" } truncate_error = { "result": "truncate_error", "message": "truncate_error" } server_error = { "result": "server_error", "message": "server_error" } # Test the on_request_error call retry_policy = CounterRetryPolicy() self.set_cluster(retry_policy) - for e in [overloaded_error, bootstrapping_error, truncate_error, server_error]: + for prime_error, exc in [ + (overloaded_error, OverloadedErrorMessage), + (bootstrapping_error, IsBootstrappingErrorMessage), + (truncate_error, TruncateError), + (server_error, ServerError)]: + + clear_queries() query_to_prime = "SELECT * from simulacron_keyspace.simulacron_table;" - prime_query(query_to_prime, then=e, rows=None, column_types=None) + prime_query(query_to_prime, then=prime_error, rows=None, column_types=None) rf = self.session.execute_async(query_to_prime) - try: + + with self.assertRaises(exc): rf.result() - except: - pass + self.assertEqual(len(rf.attempted_hosts), 1) # no retry self.assertEqual(next(retry_policy.request_error), 4) # Test that by default, retry on next host retry_policy = RetryPolicy() self.set_cluster(retry_policy) for e in [overloaded_error, bootstrapping_error, truncate_error, server_error]: + clear_queries() query_to_prime = "SELECT * from simulacron_keyspace.simulacron_table;" prime_query(query_to_prime, then=e, rows=None, column_types=None) rf = self.session.execute_async(query_to_prime) - try: + + with self.assertRaises(NoHostAvailable): rf.result() - except: - pass + self.assertEqual(len(rf.attempted_hosts), 3) # all 3 nodes failed diff --git a/tests/integration/simulacron/utils.py b/tests/integration/simulacron/utils.py index 5ec5383..ba9573f 100644 --- a/tests/integration/simulacron/utils.py +++ b/tests/integration/simulacron/utils.py @@ -1,380 +1,466 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License -from six.moves.urllib.request import build_opener, Request, HTTPHandler import json -from tests.integration import CASSANDRA_VERSION, SIMULACRON_JAR import subprocess import time -import nose +from six.moves.urllib.request import build_opener, Request, HTTPHandler + +from cassandra.metadata import SchemaParserV4, SchemaParserDSE68 + +from tests.util import wait_until_not_raised +from tests.integration import CASSANDRA_VERSION, SIMULACRON_JAR, DSE_VERSION DEFAULT_CLUSTER = "python_simulacron_cluster" class SimulacronCluster(object): """ Represents a Cluster object as returned by simulacron """ def __init__(self, json_text): self.json = json_text self.o = json.loads(json_text) @property def cluster_id(self): return self.o["id"] @property def cluster_name(self): return self.o["name"] @property def data_center_ids(self): return [dc["id"] for dc in self.o["data_centers"]] @property def data_centers_names(self): return [dc["name"] for dc in self.o["data_centers"]] def get_node_ids(self, datacenter_id): datacenter = list(filter(lambda x: x["id"] == datacenter_id, self.o["data_centers"])).pop() return [node["id"] for node in datacenter["nodes"]] class SimulacronServer(object): """ Class for starting and stopping the server from within the tests """ def __init__(self, jar_path): self.jar_path = jar_path self.running = False self.proc = None def start(self): self.proc = subprocess.Popen(['java', '-jar', self.jar_path, "--loglevel", "ERROR"], shell=False) self.running = True def stop(self): if self.proc: self.proc.terminate() self.running = False def is_running(self): # We could check self.proc.poll here instead return self.running SERVER_SIMULACRON = SimulacronServer(SIMULACRON_JAR) def start_simulacron(): """ Starts and waits for simulacron to run """ if SERVER_SIMULACRON.is_running(): SERVER_SIMULACRON.stop() SERVER_SIMULACRON.start() - #TODO improve this sleep, maybe check the logs like ccm + # TODO improve this sleep, maybe check the logs like ccm time.sleep(5) + def stop_simulacron(): SERVER_SIMULACRON.stop() class SimulacronClient(object): def __init__(self, admin_addr="127.0.0.1:8187"): self.admin_addr = admin_addr def submit_request(self, query): opener = build_opener(HTTPHandler) data = json.dumps(query.fetch_json()).encode('utf8') request = Request("http://{}/{}{}".format( self.admin_addr, query.path, query.fetch_url_params()), data=data) request.get_method = lambda: query.method request.add_header("Content-Type", 'application/json') request.add_header("Content-Length", len(data)) - connection = opener.open(request) + # wait that simulacron is ready and listening + connection = wait_until_not_raised(lambda: opener.open(request), 1, 10) return connection.read().decode('utf-8') def prime_server_versions(self): """ This information has to be primed for the test harness to run """ system_local_row = {} system_local_row["cql_version"] = CASSANDRA_VERSION.base_version system_local_row["release_version"] = CASSANDRA_VERSION.base_version + "-SNAPSHOT" + if DSE_VERSION: + system_local_row["dse_version"] = DSE_VERSION.base_version column_types = {"cql_version": "ascii", "release_version": "ascii"} system_local = PrimeQuery("SELECT cql_version, release_version FROM system.local", rows=[system_local_row], column_types=column_types) self.submit_request(system_local) def clear_all_queries(self, cluster_name=DEFAULT_CLUSTER): """ Clear all the primed queries from a particular cluster :param cluster_name: cluster to clear queries from """ opener = build_opener(HTTPHandler) request = Request("http://{0}/{1}/{2}".format( self.admin_addr, "prime", cluster_name)) request.get_method = lambda: 'DELETE' connection = opener.open(request) return connection.read() NO_THEN = object() class SimulacronRequest(object): def fetch_json(self): return {} def fetch_url_params(self): return "" @property def method(self): raise NotImplementedError() class PrimeOptions(SimulacronRequest): """ Class used for specifying how should simulacron respond to an OptionsMessage """ def __init__(self, then=None, cluster_name=DEFAULT_CLUSTER): self.path = "prime/{}".format(cluster_name) self.then = then def fetch_json(self): json_dict = {} then = {} when = {} when['request'] = "options" if self.then is not None and self.then is not NO_THEN: then.update(self.then) json_dict['when'] = when if self.then is not NO_THEN: json_dict['then'] = then return json_dict def fetch_url_params(self): return "" @property def method(self): return "POST" class RejectType(): UNBIND = "UNBIND" STOP = "STOP" REJECT_STARTUP = "REJECT_STARTUP" class RejectConnections(SimulacronRequest): """ Class used for making simulacron reject new connections """ def __init__(self, reject_type, cluster_name=DEFAULT_CLUSTER): self.path = "listener/{}".format(cluster_name) self.reject_type = reject_type def fetch_url_params(self): return "?type={0}".format(self.reject_type) @property def method(self): return "DELETE" class AcceptConnections(SimulacronRequest): """ Class used for making simulacron reject new connections """ def __init__(self, cluster_name=DEFAULT_CLUSTER): self.path = "listener/{}".format(cluster_name) @property def method(self): return "PUT" class PrimeQuery(SimulacronRequest): """ Class used for specifying how should simulacron respond to particular query """ def __init__(self, expected_query, result="success", rows=None, column_types=None, when=None, then=None, cluster_name=DEFAULT_CLUSTER): self.expected_query = expected_query self.rows = rows self.result = result self.column_types = column_types self.path = "prime/{}".format(cluster_name) self.then = then self.when = when def fetch_json(self): json_dict = {} then = {} when = {} when['query'] = self.expected_query then['result'] = self.result if self.rows is not None: then['rows'] = self.rows if self.column_types is not None: then['column_types'] = self.column_types if self.then is not None and self.then is not NO_THEN: then.update(self.then) if self.then is not NO_THEN: json_dict['then'] = then if self.when is not None: when.update(self.when) json_dict['when'] = when return json_dict def set_node(self, cluster_id, datacenter_id, node_id): self.cluster_id = cluster_id self.datacenter_id = datacenter_id self.node_id = node_id self.path += '/'.join([component for component in (self.cluster_id, self.datacenter_id, self.node_id) if component is not None]) def fetch_url_params(self): return "" @property def method(self): return "POST" + class ClusterQuery(SimulacronRequest): """ Class used for creating a cluster """ - def __init__(self, cluster_name, cassandra_version, data_centers="3", json_dict=None): + def __init__(self, cluster_name, cassandra_version, data_centers="3", json_dict=None, dse_version=None): self.cluster_name = cluster_name self.cassandra_version = cassandra_version + self.dse_version = dse_version self.data_centers = data_centers if json_dict is None: self.json_dict = {} else: self.json_dict = json_dict self.path = "cluster" def fetch_json(self): return self.json_dict def fetch_url_params(self): - return "?cassandra_version={0}&data_centers={1}&name={2}".\ + q = "?cassandra_version={0}&data_centers={1}&name={2}".\ format(self.cassandra_version, self.data_centers, self.cluster_name) + if self.dse_version: + q += "&dse_version={0}".format(self.dse_version) + + return q @property def method(self): return "POST" + +class GetLogsQuery(SimulacronRequest): + """ + Class used to get logs from simulacron + """ + def __init__(self, cluster_name=DEFAULT_CLUSTER, dc_id=0): + self.path = "log/{}/{}".format(cluster_name, dc_id) + + @property + def method(self): + return "GET" + + +class ClearLogsQuery(SimulacronRequest): + """ + Class used to get logs from simulacron + """ + def __init__(self, cluster_name=DEFAULT_CLUSTER, dc_id=0): + self.path = "log/{}/{}".format(cluster_name, dc_id) + + @property + def method(self): + return "DELETE" + + +class _PauseOrResumeReads(SimulacronRequest): + def __init__(self, cluster_name=DEFAULT_CLUSTER, dc_id=None, node_id=None): + self.path = "pause-reads/{}".format(cluster_name) + if dc_id is not None: + self.path += "/{}".format(dc_id) + if node_id is not None: + self.path += "/{}".format(node_id) + elif node_id: + raise Exception("Can't set node_id without dc_id") + + @property + def method(self): + raise NotImplementedError() + + +class PauseReads(_PauseOrResumeReads): + @property + def method(self): + return "PUT" + + +class ResumeReads(_PauseOrResumeReads): + @property + def method(self): + return "DELETE" + + def prime_driver_defaults(): """ Function to prime the necessary queries so the test harness can run """ client_simulacron = SimulacronClient() client_simulacron.prime_server_versions() - -def prime_cluster(data_centers="3", version=CASSANDRA_VERSION, cluster_name=DEFAULT_CLUSTER): + # prepare InvalidResponses for virtual tables + for query in [SchemaParserV4._SELECT_VIRTUAL_KEYSPACES, + SchemaParserV4._SELECT_VIRTUAL_TABLES, + SchemaParserV4._SELECT_VIRTUAL_COLUMNS]: + client_simulacron.submit_request( + PrimeQuery(query, result='invalid', + then={"result": "invalid", + "delay_in_ms": 0, + "ignore_on_prepare": True, + "message": "Invalid Query!"}) + ) + + # prepare empty rows for NGDG + for query in [SchemaParserDSE68._SELECT_VERTICES, + SchemaParserDSE68._SELECT_EDGES]: + client_simulacron.submit_request( + PrimeQuery(query, result='success', + then={'rows': [], 'column_types': {'row1': 'int'}})) + + +def prime_cluster(data_centers="3", version=None, cluster_name=DEFAULT_CLUSTER, dse_version=None): """ Creates a new cluster in the simulacron server :param cluster_name: name of the cluster :param data_centers: string describing the datacenter, e.g. 2/3 would be two datacenters of 2 nodes and three nodes :param version: C* version """ - version = version or CASSANDRA_VERSION.base_version - cluster_query = ClusterQuery(cluster_name, version, data_centers) + version = version or CASSANDRA_VERSION + cluster_query = ClusterQuery(cluster_name, version, data_centers, dse_version=dse_version) client_simulacron = SimulacronClient() response = client_simulacron.submit_request(cluster_query) return SimulacronCluster(response) def start_and_prime_singledc(cluster_name=DEFAULT_CLUSTER): """ Starts simulacron and creates a cluster with a single datacenter :param cluster_name: name of the cluster to start and prime :return: """ return start_and_prime_cluster_defaults(number_of_dc=1, nodes_per_dc=3, cluster_name=cluster_name) -def start_and_prime_cluster_defaults(number_of_dc=1, nodes_per_dc=3, version=CASSANDRA_VERSION, cluster_name=DEFAULT_CLUSTER): +def start_and_prime_cluster_defaults(number_of_dc=1, nodes_per_dc=3, version=CASSANDRA_VERSION, + cluster_name=DEFAULT_CLUSTER, dse_version=None): """ :param number_of_dc: number of datacentes :param nodes_per_dc: number of nodes per datacenter :param version: C* version """ start_simulacron() data_centers = ",".join([str(nodes_per_dc)] * number_of_dc) - simulacron_cluster = prime_cluster(data_centers=data_centers, version=version, cluster_name=cluster_name) + simulacron_cluster = prime_cluster(data_centers=data_centers, version=version, + cluster_name=cluster_name, dse_version=dse_version) prime_driver_defaults() return simulacron_cluster default_column_types = { "key": "bigint", "value": "ascii" } default_row = {"key": 2, "value": "value"} default_rows = [default_row] def prime_request(request): """ :param request: It could be PrimeQuery class or an PrimeOptions class """ return SimulacronClient().submit_request(request) def prime_query(query, rows=default_rows, column_types=default_column_types, when=None, then=None, cluster_name=DEFAULT_CLUSTER): """ Shortcut function for priming a query :return: """ # If then is set, then rows and column_types should not query = PrimeQuery(query, rows=rows, column_types=column_types, when=when, then=then, cluster_name=cluster_name) response = prime_request(query) return response def clear_queries(): """ Clears all the queries that have been primed to simulacron """ SimulacronClient().clear_all_queries() diff --git a/tests/integration/standard/test_authentication.py b/tests/integration/standard/test_authentication.py index f8ce423..9755c50 100644 --- a/tests/integration/standard/test_authentication.py +++ b/tests/integration/standard/test_authentication.py @@ -1,192 +1,185 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import time -from cassandra.cluster import Cluster, NoHostAvailable +from cassandra.cluster import NoHostAvailable from cassandra.auth import PlainTextAuthProvider, SASLClient, SaslAuthProvider from tests.integration import use_singledc, get_cluster, remove_cluster, PROTOCOL_VERSION, CASSANDRA_IP, \ - set_default_cass_ip, USE_CASS_EXTERNAL + USE_CASS_EXTERNAL, start_cluster_wait_for_up, TestCluster from tests.integration.util import assert_quiescent_pool_state try: import unittest2 as unittest except ImportError: import unittest log = logging.getLogger(__name__) #This can be tested for remote hosts, but the cluster has to be configured accordingly #@local def setup_module(): if CASSANDRA_IP.startswith("127.0.0.") and not USE_CASS_EXTERNAL: use_singledc(start=False) ccm_cluster = get_cluster() ccm_cluster.stop() config_options = {'authenticator': 'PasswordAuthenticator', 'authorizer': 'CassandraAuthorizer'} ccm_cluster.set_configuration_options(config_options) log.debug("Starting ccm test cluster with %s", config_options) - ccm_cluster.start(wait_for_binary_proto=True, wait_other_notice=True) - # there seems to be some race, with some versions of C* taking longer to - # get the auth (and default user) setup. Sleep here to give it a chance - time.sleep(10) - else: - set_default_cass_ip() + start_cluster_wait_for_up(ccm_cluster) def teardown_module(): remove_cluster() # this test messes with config class AuthenticationTests(unittest.TestCase): """ Tests to cover basic authentication functionality """ def get_authentication_provider(self, username, password): """ Return correct authentication provider based on protocol version. There is a difference in the semantics of authentication provider argument with protocol versions 1 and 2 For protocol version 2 and higher it should be a PlainTextAuthProvider object. For protocol version 1 it should be a function taking hostname as an argument and returning a dictionary containing username and password. :param username: authentication username :param password: authentication password :return: authentication object suitable for Cluster.connect() """ if PROTOCOL_VERSION < 2: return lambda hostname: dict(username=username, password=password) else: return PlainTextAuthProvider(username=username, password=password) def cluster_as(self, usr, pwd): # test we can connect at least once with creds # to ensure the role manager is setup for _ in range(5): try: - cluster = Cluster( - protocol_version=PROTOCOL_VERSION, + cluster = TestCluster( idle_heartbeat_interval=0, auth_provider=self.get_authentication_provider(username='cassandra', password='cassandra')) cluster.connect(wait_for_all_pools=True) - return Cluster( - protocol_version=PROTOCOL_VERSION, + return TestCluster( idle_heartbeat_interval=0, auth_provider=self.get_authentication_provider(username=usr, password=pwd)) except Exception as e: time.sleep(5) raise Exception('Unable to connect with creds: {}/{}'.format(usr, pwd)) def test_auth_connect(self): user = 'u' passwd = 'password' root_session = self.cluster_as('cassandra', 'cassandra').connect() root_session.execute('CREATE USER %s WITH PASSWORD %s', (user, passwd)) try: cluster = self.cluster_as(user, passwd) - session = cluster.connect() + session = cluster.connect(wait_for_all_pools=True) try: self.assertTrue(session.execute('SELECT release_version FROM system.local')) assert_quiescent_pool_state(self, cluster, wait=1) for pool in session.get_pools(): connection, _ = pool.borrow_connection(timeout=0) self.assertEqual(connection.authenticator.server_authenticator_class, 'org.apache.cassandra.auth.PasswordAuthenticator') pool.return_connection(connection) finally: cluster.shutdown() finally: root_session.execute('DROP USER %s', user) assert_quiescent_pool_state(self, root_session.cluster, wait=1) root_session.cluster.shutdown() def test_connect_wrong_pwd(self): cluster = self.cluster_as('cassandra', 'wrong_pass') try: self.assertRaisesRegexp(NoHostAvailable, '.*AuthenticationFailed.', cluster.connect) assert_quiescent_pool_state(self, cluster) finally: cluster.shutdown() def test_connect_wrong_username(self): cluster = self.cluster_as('wrong_user', 'cassandra') try: self.assertRaisesRegexp(NoHostAvailable, '.*AuthenticationFailed.*', cluster.connect) assert_quiescent_pool_state(self, cluster) finally: cluster.shutdown() def test_connect_empty_pwd(self): cluster = self.cluster_as('Cassandra', '') try: self.assertRaisesRegexp(NoHostAvailable, '.*AuthenticationFailed.*', cluster.connect) assert_quiescent_pool_state(self, cluster) finally: cluster.shutdown() def test_connect_no_auth_provider(self): - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() try: self.assertRaisesRegexp(NoHostAvailable, '.*AuthenticationFailed.*', cluster.connect) assert_quiescent_pool_state(self, cluster) finally: cluster.shutdown() class SaslAuthenticatorTests(AuthenticationTests): """ Test SaslAuthProvider as PlainText """ def setUp(self): if PROTOCOL_VERSION < 2: raise unittest.SkipTest('Sasl authentication not available for protocol v1') if SASLClient is None: raise unittest.SkipTest('pure-sasl is not installed') def get_authentication_provider(self, username, password): sasl_kwargs = {'service': 'cassandra', 'mechanism': 'PLAIN', 'qops': ['auth'], 'username': username, 'password': password} return SaslAuthProvider(**sasl_kwargs) # these could equally be unit tests def test_host_passthrough(self): sasl_kwargs = {'service': 'cassandra', 'mechanism': 'PLAIN'} provider = SaslAuthProvider(**sasl_kwargs) host = 'thehostname' authenticator = provider.new_authenticator(host) self.assertEqual(authenticator.sasl.host, host) def test_host_rejected(self): sasl_kwargs = {'host': 'something'} self.assertRaises(ValueError, SaslAuthProvider, **sasl_kwargs) diff --git a/tests/integration/standard/test_authentication_misconfiguration.py b/tests/integration/standard/test_authentication_misconfiguration.py index 5998693..546141d 100644 --- a/tests/integration/standard/test_authentication_misconfiguration.py +++ b/tests/integration/standard/test_authentication_misconfiguration.py @@ -1,47 +1,46 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest -from cassandra.cluster import Cluster -from tests.integration import CASSANDRA_IP, USE_CASS_EXTERNAL, use_cluster, PROTOCOL_VERSION +from tests.integration import USE_CASS_EXTERNAL, use_cluster, TestCluster class MisconfiguredAuthenticationTests(unittest.TestCase): """ One node (not the contact point) has password auth. The rest of the nodes have no auth """ @classmethod def setUpClass(cls): if not USE_CASS_EXTERNAL: ccm_cluster = use_cluster(cls.__name__, [3], start=False) node3 = ccm_cluster.nodes['node3'] node3.set_configuration_options(values={ 'authenticator': 'PasswordAuthenticator', 'authorizer': 'CassandraAuthorizer', }) - ccm_cluster.start() + ccm_cluster.start(wait_for_binary_proto=True) cls.ccm_cluster = ccm_cluster def test_connect_no_auth_provider(self): - cluster = Cluster(protocol_version=PROTOCOL_VERSION, contact_points=[CASSANDRA_IP]) + cluster = TestCluster() cluster.connect() cluster.refresh_nodes() down_hosts = [host for host in cluster.metadata.all_hosts() if not host.is_up] self.assertEqual(len(down_hosts), 1) cluster.shutdown() @classmethod def tearDownClass(cls): if not USE_CASS_EXTERNAL: cls.ccm_cluster.stop() diff --git a/tests/integration/standard/test_client_warnings.py b/tests/integration/standard/test_client_warnings.py index 1092af7..c5ce5dc 100644 --- a/tests/integration/standard/test_client_warnings.py +++ b/tests/integration/standard/test_client_warnings.py @@ -1,133 +1,132 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest from cassandra.query import BatchStatement -from cassandra.cluster import Cluster -from tests.integration import use_singledc, PROTOCOL_VERSION, local +from tests.integration import use_singledc, PROTOCOL_VERSION, local, TestCluster def setup_module(): use_singledc() class ClientWarningTests(unittest.TestCase): @classmethod def setUpClass(cls): if PROTOCOL_VERSION < 4: return - cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cls.cluster = TestCluster() cls.session = cls.cluster.connect() cls.session.execute("CREATE TABLE IF NOT EXISTS test1rf.client_warning (k int, v0 int, v1 int, PRIMARY KEY (k, v0))") cls.prepared = cls.session.prepare("INSERT INTO test1rf.client_warning (k, v0, v1) VALUES (?, ?, ?)") cls.warn_batch = BatchStatement() # 213 = 5 * 1024 / (4+4 + 4+4 + 4+4) # thresh_kb/ (min param size) for x in range(214): cls.warn_batch.add(cls.prepared, (x, x, 1)) @classmethod def tearDownClass(cls): if PROTOCOL_VERSION < 4: return cls.cluster.shutdown() def setUp(self): if PROTOCOL_VERSION < 4: raise unittest.SkipTest( "Native protocol 4,0+ is required for client warnings, currently using %r" % (PROTOCOL_VERSION,)) def test_warning_basic(self): """ Test to validate that client warnings can be surfaced @since 2.6.0 @jira_ticket PYTHON-315 @expected_result valid warnings returned @test_assumptions - batch_size_warn_threshold_in_kb: 5 @test_category queries:client_warning """ future = self.session.execute_async(self.warn_batch) future.result() self.assertEqual(len(future.warnings), 1) self.assertRegexpMatches(future.warnings[0], 'Batch.*exceeding.*') def test_warning_with_trace(self): """ Test to validate client warning with tracing @since 2.6.0 @jira_ticket PYTHON-315 @expected_result valid warnings returned @test_assumptions - batch_size_warn_threshold_in_kb: 5 @test_category queries:client_warning """ future = self.session.execute_async(self.warn_batch, trace=True) future.result() self.assertEqual(len(future.warnings), 1) self.assertRegexpMatches(future.warnings[0], 'Batch.*exceeding.*') self.assertIsNotNone(future.get_query_trace()) @local def test_warning_with_custom_payload(self): """ Test to validate client warning with custom payload @since 2.6.0 @jira_ticket PYTHON-315 @expected_result valid warnings returned @test_assumptions - batch_size_warn_threshold_in_kb: 5 @test_category queries:client_warning """ payload = {'key': b'value'} future = self.session.execute_async(self.warn_batch, custom_payload=payload) future.result() self.assertEqual(len(future.warnings), 1) self.assertRegexpMatches(future.warnings[0], 'Batch.*exceeding.*') self.assertDictEqual(future.custom_payload, payload) @local def test_warning_with_trace_and_custom_payload(self): """ Test to validate client warning with tracing and client warning @since 2.6.0 @jira_ticket PYTHON-315 @expected_result valid warnings returned @test_assumptions - batch_size_warn_threshold_in_kb: 5 @test_category queries:client_warning """ payload = {'key': b'value'} future = self.session.execute_async(self.warn_batch, trace=True, custom_payload=payload) future.result() self.assertEqual(len(future.warnings), 1) self.assertRegexpMatches(future.warnings[0], 'Batch.*exceeding.*') self.assertIsNotNone(future.get_query_trace()) self.assertDictEqual(future.custom_payload, payload) diff --git a/tests/integration/standard/test_cluster.py b/tests/integration/standard/test_cluster.py index 768fa77..c7d8266 100644 --- a/tests/integration/standard/test_cluster.py +++ b/tests/integration/standard/test_cluster.py @@ -1,1564 +1,1581 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from collections import deque from copy import copy from mock import Mock, call, patch import time from uuid import uuid4 import logging import warnings from packaging.version import Version import cassandra -from cassandra.cluster import Cluster, NoHostAvailable, ExecutionProfile, EXEC_PROFILE_DEFAULT +from cassandra.cluster import NoHostAvailable, ExecutionProfile, EXEC_PROFILE_DEFAULT, ControlConnection, Cluster from cassandra.concurrent import execute_concurrent from cassandra.policies import (RoundRobinPolicy, ExponentialReconnectionPolicy, RetryPolicy, SimpleConvictionPolicy, HostDistance, AddressTranslator, TokenAwarePolicy, HostFilterPolicy) from cassandra import ConsistencyLevel from cassandra.query import SimpleStatement, TraceUnavailable, tuple_factory from cassandra.auth import PlainTextAuthProvider, SaslAuthProvider from cassandra import connection from cassandra.connection import DefaultEndPoint from tests import notwindows -from tests.integration import use_singledc, PROTOCOL_VERSION, get_server_versions, CASSANDRA_VERSION, \ +from tests.integration import use_singledc, get_server_versions, CASSANDRA_VERSION, \ execute_until_pass, execute_with_long_wait_retry, get_node, MockLoggingHandler, get_unsupported_lower_protocol, \ - get_unsupported_upper_protocol, protocolv5, local, CASSANDRA_IP, greaterthanorequalcass30, lessthanorequalcass40 + get_unsupported_upper_protocol, protocolv6, local, CASSANDRA_IP, greaterthanorequalcass30, lessthanorequalcass40, \ + DSE_VERSION, TestCluster, PROTOCOL_VERSION from tests.integration.util import assert_quiescent_pool_state import sys +log = logging.getLogger(__name__) + def setup_module(): use_singledc() warnings.simplefilter("always") class IgnoredHostPolicy(RoundRobinPolicy): def __init__(self, ignored_hosts): self.ignored_hosts = ignored_hosts RoundRobinPolicy.__init__(self) def distance(self, host): if(host.address in self.ignored_hosts): return HostDistance.IGNORED else: return HostDistance.LOCAL class ClusterTests(unittest.TestCase): @local def test_ignored_host_up(self): """ Test to ensure that is_up is not set by default on ignored hosts @since 3.6 @jira_ticket PYTHON-551 @expected_result ignored hosts should have None set for is_up @test_category connection """ - ingored_host_policy = IgnoredHostPolicy(["127.0.0.2", "127.0.0.3"]) - cluster = Cluster(protocol_version=PROTOCOL_VERSION, load_balancing_policy=ingored_host_policy) - session = cluster.connect() + ignored_host_policy = IgnoredHostPolicy(["127.0.0.2", "127.0.0.3"]) + cluster = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(load_balancing_policy=ignored_host_policy)} + ) + cluster.connect() for host in cluster.metadata.all_hosts(): if str(host) == "127.0.0.1:9042": self.assertTrue(host.is_up) else: self.assertIsNone(host.is_up) cluster.shutdown() @local def test_host_resolution(self): """ Test to insure A records are resolved appropriately. @since 3.3 @jira_ticket PYTHON-415 @expected_result hostname will be transformed into IP @test_category connection """ - cluster = Cluster(contact_points=["localhost"], protocol_version=PROTOCOL_VERSION, connect_timeout=1) + cluster = TestCluster(contact_points=["localhost"], connect_timeout=1) self.assertTrue(DefaultEndPoint('127.0.0.1') in cluster.endpoints_resolved) @local def test_host_duplication(self): """ Ensure that duplicate hosts in the contact points are surfaced in the cluster metadata @since 3.3 @jira_ticket PYTHON-103 @expected_result duplicate hosts aren't surfaced in cluster.metadata @test_category connection """ - cluster = Cluster(contact_points=["localhost", "127.0.0.1", "localhost", "localhost", "localhost"], protocol_version=PROTOCOL_VERSION, connect_timeout=1) + cluster = TestCluster( + contact_points=["localhost", "127.0.0.1", "localhost", "localhost", "localhost"], + connect_timeout=1 + ) cluster.connect(wait_for_all_pools=True) self.assertEqual(len(cluster.metadata.all_hosts()), 3) cluster.shutdown() - cluster = Cluster(contact_points=["127.0.0.1", "localhost"], protocol_version=PROTOCOL_VERSION, connect_timeout=1) + cluster = TestCluster(contact_points=["127.0.0.1", "localhost"], connect_timeout=1) cluster.connect(wait_for_all_pools=True) self.assertEqual(len(cluster.metadata.all_hosts()), 3) cluster.shutdown() @local def test_raise_error_on_control_connection_timeout(self): """ Test for initial control connection timeout test_raise_error_on_control_connection_timeout tests that the driver times out after the set initial connection timeout. It first pauses node1, essentially making it unreachable. It then attempts to create a Cluster object via connecting to node1 with a timeout of 1 second, and ensures that a NoHostAvailable is raised, along with an OperationTimedOut for 1 second. @expected_errors NoHostAvailable When node1 is paused, and a connection attempt is made. @since 2.6.0 @jira_ticket PYTHON-206 @expected_result NoHostAvailable exception should be raised after 1 second. @test_category connection """ get_node(1).pause() - cluster = Cluster(contact_points=['127.0.0.1'], protocol_version=PROTOCOL_VERSION, connect_timeout=1) + cluster = TestCluster(contact_points=['127.0.0.1'], connect_timeout=1) with self.assertRaisesRegexp(NoHostAvailable, "OperationTimedOut\('errors=Timed out creating connection \(1 seconds\)"): cluster.connect() cluster.shutdown() get_node(1).resume() def test_basic(self): """ Test basic connection and usage """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect() result = execute_until_pass(session, """ CREATE KEYSPACE clustertests WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} """) self.assertFalse(result) result = execute_with_long_wait_retry(session, """ CREATE TABLE clustertests.cf0 ( a text, b text, c text, PRIMARY KEY (a, b) ) """) self.assertFalse(result) result = session.execute( """ INSERT INTO clustertests.cf0 (a, b, c) VALUES ('a', 'b', 'c') """) self.assertFalse(result) result = session.execute("SELECT * FROM clustertests.cf0") self.assertEqual([('a', 'b', 'c')], result) execute_with_long_wait_retry(session, "DROP KEYSPACE clustertests") cluster.shutdown() def test_session_host_parameter(self): """ Test for protocol negotiation Very that NoHostAvailable is risen in Session.__init__ when there are no valid connections and that no error is arisen otherwise, despite maybe being some invalid hosts @since 3.9 @jira_ticket PYTHON-665 @expected_result NoHostAvailable when the driver is unable to connect to a valid host, no exception otherwise @test_category connection """ def cleanup(): """ When this test fails, the inline .shutdown() calls don't get called, so we register this as a cleanup. """ self.cluster_to_shutdown.shutdown() self.addCleanup(cleanup) # Test with empty list - self.cluster_to_shutdown = Cluster([], protocol_version=PROTOCOL_VERSION) + self.cluster_to_shutdown = TestCluster(contact_points=[]) with self.assertRaises(NoHostAvailable): self.cluster_to_shutdown.connect() self.cluster_to_shutdown.shutdown() # Test with only invalid - self.cluster_to_shutdown = Cluster(('1.2.3.4',), protocol_version=PROTOCOL_VERSION) + self.cluster_to_shutdown = TestCluster(contact_points=('1.2.3.4',)) with self.assertRaises(NoHostAvailable): self.cluster_to_shutdown.connect() self.cluster_to_shutdown.shutdown() # Test with valid and invalid hosts - self.cluster_to_shutdown = Cluster(("127.0.0.1", "127.0.0.2", "1.2.3.4"), - protocol_version=PROTOCOL_VERSION) + self.cluster_to_shutdown = TestCluster(contact_points=("127.0.0.1", "127.0.0.2", "1.2.3.4")) self.cluster_to_shutdown.connect() self.cluster_to_shutdown.shutdown() def test_protocol_negotiation(self): """ Test for protocol negotiation test_protocol_negotiation tests that the driver will select the correct protocol version to match the correct cassandra version. Please note that 2.1.5 has a bug https://issues.apache.org/jira/browse/CASSANDRA-9451 that will cause this test to fail that will cause this to not pass. It was rectified in 2.1.6 @since 2.6.0 @jira_ticket PYTHON-240 @expected_result the correct protocol version should be selected @test_category connection """ cluster = Cluster() self.assertLessEqual(cluster.protocol_version, cassandra.ProtocolVersion.MAX_SUPPORTED) session = cluster.connect() updated_protocol_version = session._protocol_version updated_cluster_version = cluster.protocol_version # Make sure the correct protocol was selected by default - if CASSANDRA_VERSION >= Version('2.2'): + if DSE_VERSION and DSE_VERSION >= Version("6.0"): + self.assertEqual(updated_protocol_version, cassandra.ProtocolVersion.DSE_V2) + self.assertEqual(updated_cluster_version, cassandra.ProtocolVersion.DSE_V2) + elif DSE_VERSION and DSE_VERSION >= Version("5.1"): + self.assertEqual(updated_protocol_version, cassandra.ProtocolVersion.DSE_V1) + self.assertEqual(updated_cluster_version, cassandra.ProtocolVersion.DSE_V1) + elif CASSANDRA_VERSION >= Version('4.0-beta5'): + self.assertEqual(updated_protocol_version, cassandra.ProtocolVersion.V5) + self.assertEqual(updated_cluster_version, cassandra.ProtocolVersion.V5) + elif CASSANDRA_VERSION >= Version('4.0-a'): + self.assertEqual(updated_protocol_version, cassandra.ProtocolVersion.V4) + self.assertEqual(updated_cluster_version, cassandra.ProtocolVersion.V4) + elif CASSANDRA_VERSION >= Version('3.11'): + self.assertEqual(updated_protocol_version, cassandra.ProtocolVersion.V4) + self.assertEqual(updated_cluster_version, cassandra.ProtocolVersion.V4) + elif CASSANDRA_VERSION >= Version('3.0'): + self.assertEqual(updated_protocol_version, cassandra.ProtocolVersion.V4) + self.assertEqual(updated_cluster_version, cassandra.ProtocolVersion.V4) + elif CASSANDRA_VERSION >= Version('2.2'): self.assertEqual(updated_protocol_version, 4) self.assertEqual(updated_cluster_version, 4) elif CASSANDRA_VERSION >= Version('2.1'): self.assertEqual(updated_protocol_version, 3) self.assertEqual(updated_cluster_version, 3) elif CASSANDRA_VERSION >= Version('2.0'): self.assertEqual(updated_protocol_version, 2) self.assertEqual(updated_cluster_version, 2) else: self.assertEqual(updated_protocol_version, 1) self.assertEqual(updated_cluster_version, 1) cluster.shutdown() def test_invalid_protocol_negotation(self): """ Test for protocol negotiation when explicit versions are set If an explicit protocol version that is not compatible with the server version is set an exception should be thrown. It should not attempt to negotiate for reference supported protocol version to server versions is as follows/ 1.2 -> 1 2.0 -> 2, 1 2.1 -> 3, 2, 1 2.2 -> 4, 3, 2, 1 3.X -> 4, 3 @since 3.6.0 @jira_ticket PYTHON-537 @expected_result downgrading should not be allowed when explicit protocol versions are set. @test_category connection """ upper_bound = get_unsupported_upper_protocol() + log.debug('got upper_bound of {}'.format(upper_bound)) if upper_bound is not None: - cluster = Cluster(protocol_version=upper_bound) + cluster = TestCluster(protocol_version=upper_bound) with self.assertRaises(NoHostAvailable): cluster.connect() cluster.shutdown() lower_bound = get_unsupported_lower_protocol() + log.debug('got lower_bound of {}'.format(lower_bound)) if lower_bound is not None: - cluster = Cluster(protocol_version=lower_bound) + cluster = TestCluster(protocol_version=lower_bound) with self.assertRaises(NoHostAvailable): cluster.connect() cluster.shutdown() def test_connect_on_keyspace(self): """ Ensure clusters that connect on a keyspace, do """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect() result = session.execute( """ INSERT INTO test1rf.test (k, v) VALUES (8889, 8889) """) self.assertFalse(result) result = session.execute("SELECT * FROM test1rf.test") self.assertEqual([(8889, 8889)], result, "Rows in ResultSet are {0}".format(result.current_rows)) # test_connect_on_keyspace session2 = cluster.connect('test1rf') result2 = session2.execute("SELECT * FROM test") self.assertEqual(result, result2) cluster.shutdown() def test_set_keyspace_twice(self): - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect() session.execute("USE system") session.execute("USE system") cluster.shutdown() def test_default_connections(self): """ Ensure errors are not thrown when using non-default policies """ - Cluster( - load_balancing_policy=RoundRobinPolicy(), + TestCluster( reconnection_policy=ExponentialReconnectionPolicy(1.0, 600.0), - default_retry_policy=RetryPolicy(), conviction_policy_factory=SimpleConvictionPolicy, protocol_version=PROTOCOL_VERSION ) def test_connect_to_already_shutdown_cluster(self): """ Ensure you cannot connect to a cluster that's been shutdown """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() cluster.shutdown() self.assertRaises(Exception, cluster.connect) def test_auth_provider_is_callable(self): """ Ensure that auth_providers are always callable """ self.assertRaises(TypeError, Cluster, auth_provider=1, protocol_version=1) - c = Cluster(protocol_version=1) + c = TestCluster(protocol_version=1) self.assertRaises(TypeError, setattr, c, 'auth_provider', 1) def test_v2_auth_provider(self): """ Check for v2 auth_provider compliance """ bad_auth_provider = lambda x: {'username': 'foo', 'password': 'bar'} self.assertRaises(TypeError, Cluster, auth_provider=bad_auth_provider, protocol_version=2) - c = Cluster(protocol_version=2) + c = TestCluster(protocol_version=2) self.assertRaises(TypeError, setattr, c, 'auth_provider', bad_auth_provider) def test_conviction_policy_factory_is_callable(self): """ Ensure that conviction_policy_factory are always callable """ self.assertRaises(ValueError, Cluster, conviction_policy_factory=1) def test_connect_to_bad_hosts(self): """ Ensure that a NoHostAvailable Exception is thrown when a cluster cannot connect to given hosts """ - cluster = Cluster(['127.1.2.9', '127.1.2.10'], - protocol_version=PROTOCOL_VERSION) + cluster = TestCluster(contact_points=['127.1.2.9', '127.1.2.10'], + protocol_version=PROTOCOL_VERSION) self.assertRaises(NoHostAvailable, cluster.connect) def test_cluster_settings(self): """ Test connection setting getters and setters """ if PROTOCOL_VERSION >= 3: raise unittest.SkipTest("min/max requests and core/max conns aren't used with v3 protocol") - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() min_requests_per_connection = cluster.get_min_requests_per_connection(HostDistance.LOCAL) self.assertEqual(cassandra.cluster.DEFAULT_MIN_REQUESTS, min_requests_per_connection) cluster.set_min_requests_per_connection(HostDistance.LOCAL, min_requests_per_connection + 1) self.assertEqual(cluster.get_min_requests_per_connection(HostDistance.LOCAL), min_requests_per_connection + 1) max_requests_per_connection = cluster.get_max_requests_per_connection(HostDistance.LOCAL) self.assertEqual(cassandra.cluster.DEFAULT_MAX_REQUESTS, max_requests_per_connection) cluster.set_max_requests_per_connection(HostDistance.LOCAL, max_requests_per_connection + 1) self.assertEqual(cluster.get_max_requests_per_connection(HostDistance.LOCAL), max_requests_per_connection + 1) core_connections_per_host = cluster.get_core_connections_per_host(HostDistance.LOCAL) self.assertEqual(cassandra.cluster.DEFAULT_MIN_CONNECTIONS_PER_LOCAL_HOST, core_connections_per_host) cluster.set_core_connections_per_host(HostDistance.LOCAL, core_connections_per_host + 1) self.assertEqual(cluster.get_core_connections_per_host(HostDistance.LOCAL), core_connections_per_host + 1) max_connections_per_host = cluster.get_max_connections_per_host(HostDistance.LOCAL) self.assertEqual(cassandra.cluster.DEFAULT_MAX_CONNECTIONS_PER_LOCAL_HOST, max_connections_per_host) cluster.set_max_connections_per_host(HostDistance.LOCAL, max_connections_per_host + 1) self.assertEqual(cluster.get_max_connections_per_host(HostDistance.LOCAL), max_connections_per_host + 1) def test_refresh_schema(self): - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect() original_meta = cluster.metadata.keyspaces # full schema refresh, with wait cluster.refresh_schema_metadata() self.assertIsNot(original_meta, cluster.metadata.keyspaces) self.assertEqual(original_meta, cluster.metadata.keyspaces) cluster.shutdown() def test_refresh_schema_keyspace(self): - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect() original_meta = cluster.metadata.keyspaces original_system_meta = original_meta['system'] # only refresh one keyspace cluster.refresh_keyspace_metadata('system') current_meta = cluster.metadata.keyspaces self.assertIs(original_meta, current_meta) current_system_meta = current_meta['system'] self.assertIsNot(original_system_meta, current_system_meta) self.assertEqual(original_system_meta.as_cql_query(), current_system_meta.as_cql_query()) cluster.shutdown() def test_refresh_schema_table(self): - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect() original_meta = cluster.metadata.keyspaces original_system_meta = original_meta['system'] original_system_schema_meta = original_system_meta.tables['local'] # only refresh one table cluster.refresh_table_metadata('system', 'local') current_meta = cluster.metadata.keyspaces current_system_meta = current_meta['system'] current_system_schema_meta = current_system_meta.tables['local'] self.assertIs(original_meta, current_meta) self.assertIs(original_system_meta, current_system_meta) self.assertIsNot(original_system_schema_meta, current_system_schema_meta) self.assertEqual(original_system_schema_meta.as_cql_query(), current_system_schema_meta.as_cql_query()) cluster.shutdown() def test_refresh_schema_type(self): if get_server_versions()[0] < (2, 1, 0): raise unittest.SkipTest('UDTs were introduced in Cassandra 2.1') if PROTOCOL_VERSION < 3: raise unittest.SkipTest('UDTs are not specified in change events for protocol v2') # We may want to refresh types on keyspace change events in that case(?) - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect() keyspace_name = 'test1rf' type_name = self._testMethodName execute_until_pass(session, 'CREATE TYPE IF NOT EXISTS %s.%s (one int, two text)' % (keyspace_name, type_name)) original_meta = cluster.metadata.keyspaces original_test1rf_meta = original_meta[keyspace_name] original_type_meta = original_test1rf_meta.user_types[type_name] # only refresh one type cluster.refresh_user_type_metadata('test1rf', type_name) current_meta = cluster.metadata.keyspaces current_test1rf_meta = current_meta[keyspace_name] current_type_meta = current_test1rf_meta.user_types[type_name] self.assertIs(original_meta, current_meta) self.assertEqual(original_test1rf_meta.export_as_string(), current_test1rf_meta.export_as_string()) self.assertIsNot(original_type_meta, current_type_meta) self.assertEqual(original_type_meta.as_cql_query(), current_type_meta.as_cql_query()) cluster.shutdown() @local @notwindows def test_refresh_schema_no_wait(self): - contact_points = [CASSANDRA_IP] - cluster = Cluster(protocol_version=PROTOCOL_VERSION, max_schema_agreement_wait=10, - contact_points=contact_points, - load_balancing_policy=HostFilterPolicy( - RoundRobinPolicy(), lambda host: host.address == CASSANDRA_IP - )) - session = cluster.connect() + original_wait_for_responses = connection.Connection.wait_for_responses - schema_ver = session.execute("SELECT schema_version FROM system.local WHERE key='local'")[0][0] - new_schema_ver = uuid4() - session.execute("UPDATE system.local SET schema_version=%s WHERE key='local'", (new_schema_ver,)) + def patched_wait_for_responses(*args, **kwargs): + # When selecting schema version, replace the real schema UUID with an unexpected UUID + response = original_wait_for_responses(*args, **kwargs) + if len(args) > 2 and hasattr(args[2], "query") and args[2].query == "SELECT schema_version FROM system.local WHERE key='local'": + new_uuid = uuid4() + response[1].parsed_rows[0] = (new_uuid,) + return response - - try: + with patch.object(connection.Connection, "wait_for_responses", patched_wait_for_responses): agreement_timeout = 1 # cluster agreement wait exceeded - c = Cluster(protocol_version=PROTOCOL_VERSION, max_schema_agreement_wait=agreement_timeout) + c = TestCluster(max_schema_agreement_wait=agreement_timeout) c.connect() self.assertTrue(c.metadata.keyspaces) # cluster agreement wait used for refresh original_meta = c.metadata.keyspaces start_time = time.time() self.assertRaisesRegexp(Exception, r"Schema metadata was not refreshed.*", c.refresh_schema_metadata) end_time = time.time() self.assertGreaterEqual(end_time - start_time, agreement_timeout) self.assertIs(original_meta, c.metadata.keyspaces) # refresh wait overrides cluster value original_meta = c.metadata.keyspaces start_time = time.time() c.refresh_schema_metadata(max_schema_agreement_wait=0) end_time = time.time() self.assertLess(end_time - start_time, agreement_timeout) self.assertIsNot(original_meta, c.metadata.keyspaces) self.assertEqual(original_meta, c.metadata.keyspaces) c.shutdown() refresh_threshold = 0.5 # cluster agreement bypass - c = Cluster(protocol_version=PROTOCOL_VERSION, max_schema_agreement_wait=0) + c = TestCluster(max_schema_agreement_wait=0) start_time = time.time() s = c.connect() end_time = time.time() self.assertLess(end_time - start_time, refresh_threshold) self.assertTrue(c.metadata.keyspaces) # cluster agreement wait used for refresh original_meta = c.metadata.keyspaces start_time = time.time() c.refresh_schema_metadata() end_time = time.time() self.assertLess(end_time - start_time, refresh_threshold) self.assertIsNot(original_meta, c.metadata.keyspaces) self.assertEqual(original_meta, c.metadata.keyspaces) # refresh wait overrides cluster value original_meta = c.metadata.keyspaces start_time = time.time() self.assertRaisesRegexp(Exception, r"Schema metadata was not refreshed.*", c.refresh_schema_metadata, max_schema_agreement_wait=agreement_timeout) end_time = time.time() self.assertGreaterEqual(end_time - start_time, agreement_timeout) self.assertIs(original_meta, c.metadata.keyspaces) c.shutdown() - finally: - # TODO once fixed this connect call - session = cluster.connect() - session.execute("UPDATE system.local SET schema_version=%s WHERE key='local'", (schema_ver,)) - - cluster.shutdown() def test_trace(self): """ Ensure trace can be requested for async and non-async queries """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect() result = session.execute( "SELECT * FROM system.local", trace=True) self._check_trace(result.get_query_trace()) query = "SELECT * FROM system.local" statement = SimpleStatement(query) result = session.execute(statement, trace=True) self._check_trace(result.get_query_trace()) query = "SELECT * FROM system.local" statement = SimpleStatement(query) result = session.execute(statement) self.assertIsNone(result.get_query_trace()) statement2 = SimpleStatement(query) future = session.execute_async(statement2, trace=True) future.result() self._check_trace(future.get_query_trace()) statement2 = SimpleStatement(query) future = session.execute_async(statement2) future.result() self.assertIsNone(future.get_query_trace()) prepared = session.prepare("SELECT * FROM system.local") future = session.execute_async(prepared, parameters=(), trace=True) future.result() self._check_trace(future.get_query_trace()) cluster.shutdown() def test_trace_unavailable(self): """ First checks that TraceUnavailable is arisen if the max_wait parameter is negative Then checks that TraceUnavailable is arisen if the result hasn't been set yet @since 3.10 @jira_ticket PYTHON-196 @expected_result TraceUnavailable is arisen in both cases @test_category query """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() self.addCleanup(cluster.shutdown) session = cluster.connect() query = "SELECT * FROM system.local" statement = SimpleStatement(query) max_retry_count = 10 for i in range(max_retry_count): future = session.execute_async(statement, trace=True) future.result() try: result = future.get_query_trace(-1.0) # In case the result has time to come back before this timeout due to a race condition self._check_trace(result) except TraceUnavailable: break else: raise Exception("get_query_trace didn't raise TraceUnavailable after {} tries".format(max_retry_count)) for i in range(max_retry_count): future = session.execute_async(statement, trace=True) try: result = future.get_query_trace(max_wait=120) # In case the result has been set check the trace self._check_trace(result) except TraceUnavailable: break else: raise Exception("get_query_trace didn't raise TraceUnavailable after {} tries".format(max_retry_count)) def test_one_returns_none(self): """ Test ResulSet.one returns None if no rows where found @since 3.14 @jira_ticket PYTHON-947 @expected_result ResulSet.one is None @test_category query """ - with Cluster() as cluster: + with TestCluster() as cluster: session = cluster.connect() self.assertIsNone(session.execute("SELECT * from system.local WHERE key='madeup_key'").one()) def test_string_coverage(self): """ Ensure str(future) returns without error """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect() query = "SELECT * FROM system.local" statement = SimpleStatement(query) future = session.execute_async(statement) self.assertIn(query, str(future)) future.result() self.assertIn(query, str(future)) self.assertIn('result', str(future)) cluster.shutdown() def test_can_connect_with_plainauth(self): """ Verify that we can connect setting PlainTextAuthProvider against a C* server without authentication set. We also verify a warning is issued per connection. This test is here instead of in test_authentication.py because the C* server running in that module has auth set. @since 3.14 @jira_ticket PYTHON-940 @expected_result we can connect, query C* and warning are issued @test_category auth """ auth_provider = PlainTextAuthProvider( username="made_up_username", password="made_up_password" ) self._warning_are_issued_when_auth(auth_provider) def test_can_connect_with_sslauth(self): """ Verify that we can connect setting SaslAuthProvider against a C* server without authentication set. We also verify a warning is issued per connection. This test is here instead of in test_authentication.py because the C* server running in that module has auth set. @since 3.14 @jira_ticket PYTHON-940 @expected_result we can connect, query C* and warning are issued @test_category auth """ sasl_kwargs = {'service': 'cassandra', 'mechanism': 'PLAIN', 'qops': ['auth'], 'username': "made_up_username", 'password': "made_up_password"} auth_provider = SaslAuthProvider(**sasl_kwargs) self._warning_are_issued_when_auth(auth_provider) def _warning_are_issued_when_auth(self, auth_provider): with MockLoggingHandler().set_module_name(connection.__name__) as mock_handler: - with Cluster(auth_provider=auth_provider) as cluster: + with TestCluster(auth_provider=auth_provider) as cluster: session = cluster.connect() self.assertIsNotNone(session.execute("SELECT * from system.local")) # Three conenctions to nodes plus the control connection - self.assertEqual(4, mock_handler.get_message_count('warning', - "An authentication challenge was not sent")) + auth_warning = mock_handler.get_message_count('warning', "An authentication challenge was not sent") + self.assertGreaterEqual(auth_warning, 4) + self.assertEqual( + auth_warning, + mock_handler.get_message_count("debug", "Got ReadyMessage on new connection") + ) def test_idle_heartbeat(self): interval = 2 - cluster = Cluster(protocol_version=PROTOCOL_VERSION, idle_heartbeat_interval=interval) + cluster = TestCluster(idle_heartbeat_interval=interval, + monitor_reporting_enabled=False) if PROTOCOL_VERSION < 3: cluster.set_core_connections_per_host(HostDistance.LOCAL, 1) session = cluster.connect(wait_for_all_pools=True) # This test relies on impl details of connection req id management to see if heartbeats # are being sent. May need update if impl is changed connection_request_ids = {} for h in cluster.get_connection_holders(): for c in h.get_connections(): # make sure none are idle (should have startup messages self.assertFalse(c.is_idle) with c.lock: connection_request_ids[id(c)] = deque(c.request_ids) # copy of request ids # let two heatbeat intervals pass (first one had startup messages in it) time.sleep(2 * interval + interval/2) connections = [c for holders in cluster.get_connection_holders() for c in holders.get_connections()] # make sure requests were sent on all connections for c in connections: expected_ids = connection_request_ids[id(c)] expected_ids.rotate(-1) with c.lock: self.assertListEqual(list(c.request_ids), list(expected_ids)) # assert idle status self.assertTrue(all(c.is_idle for c in connections)) # send messages on all connections statements_and_params = [("SELECT release_version FROM system.local", ())] * len(cluster.metadata.all_hosts()) results = execute_concurrent(session, statements_and_params) for success, result in results: self.assertTrue(success) # assert not idle status self.assertFalse(any(c.is_idle if not c.is_control_connection else False for c in connections)) # holders include session pools and cc holders = cluster.get_connection_holders() self.assertIn(cluster.control_connection, holders) self.assertEqual(len(holders), len(cluster.metadata.all_hosts()) + 1) # hosts pools, 1 for cc # include additional sessions session2 = cluster.connect(wait_for_all_pools=True) holders = cluster.get_connection_holders() self.assertIn(cluster.control_connection, holders) self.assertEqual(len(holders), 2 * len(cluster.metadata.all_hosts()) + 1) # 2 sessions' hosts pools, 1 for cc cluster._idle_heartbeat.stop() cluster._idle_heartbeat.join() assert_quiescent_pool_state(self, cluster) cluster.shutdown() @patch('cassandra.cluster.Cluster.idle_heartbeat_interval', new=0.1) def test_idle_heartbeat_disabled(self): self.assertTrue(Cluster.idle_heartbeat_interval) # heartbeat disabled with '0' - cluster = Cluster(protocol_version=PROTOCOL_VERSION, idle_heartbeat_interval=0) + cluster = TestCluster(idle_heartbeat_interval=0) self.assertEqual(cluster.idle_heartbeat_interval, 0) session = cluster.connect() # let two heatbeat intervals pass (first one had startup messages in it) time.sleep(2 * Cluster.idle_heartbeat_interval) connections = [c for holders in cluster.get_connection_holders() for c in holders.get_connections()] # assert not idle status (should never get reset because there is not heartbeat) self.assertFalse(any(c.is_idle for c in connections)) cluster.shutdown() def test_pool_management(self): # Ensure that in_flight and request_ids quiesce after cluster operations - cluster = Cluster(protocol_version=PROTOCOL_VERSION, idle_heartbeat_interval=0) # no idle heartbeat here, pool management is tested in test_idle_heartbeat + cluster = TestCluster(idle_heartbeat_interval=0) # no idle heartbeat here, pool management is tested in test_idle_heartbeat session = cluster.connect() session2 = cluster.connect() # prepare p = session.prepare("SELECT * FROM system.local WHERE key=?") self.assertTrue(session.execute(p, ('local',))) # simple self.assertTrue(session.execute("SELECT * FROM system.local WHERE key='local'")) # set keyspace session.set_keyspace('system') session.set_keyspace('system_traces') # use keyspace session.execute('USE system') session.execute('USE system_traces') # refresh schema cluster.refresh_schema_metadata() cluster.refresh_schema_metadata(max_schema_agreement_wait=0) assert_quiescent_pool_state(self, cluster) cluster.shutdown() @local def test_profile_load_balancing(self): """ Tests that profile load balancing policies are honored. @since 3.5 @jira_ticket PYTHON-569 @expected_result Execution Policy should be used when applicable. @test_category config_profiles """ query = "select release_version from system.local" node1 = ExecutionProfile( load_balancing_policy=HostFilterPolicy( RoundRobinPolicy(), lambda host: host.address == CASSANDRA_IP ) ) - with Cluster(execution_profiles={'node1': node1}) as cluster: + with TestCluster(execution_profiles={'node1': node1}, monitor_reporting_enabled=False) as cluster: session = cluster.connect(wait_for_all_pools=True) # default is DCA RR for all hosts expected_hosts = set(cluster.metadata.all_hosts()) queried_hosts = set() for _ in expected_hosts: rs = session.execute(query) queried_hosts.add(rs.response_future._current_host) self.assertEqual(queried_hosts, expected_hosts) # by name we should only hit the one expected_hosts = set(h for h in cluster.metadata.all_hosts() if h.address == CASSANDRA_IP) queried_hosts = set() for _ in cluster.metadata.all_hosts(): rs = session.execute(query, execution_profile='node1') queried_hosts.add(rs.response_future._current_host) self.assertEqual(queried_hosts, expected_hosts) # use a copied instance and override the row factory # assert last returned value can be accessed as a namedtuple so we can prove something different named_tuple_row = rs[0] self.assertIsInstance(named_tuple_row, tuple) self.assertTrue(named_tuple_row.release_version) tmp_profile = copy(node1) tmp_profile.row_factory = tuple_factory queried_hosts = set() for _ in cluster.metadata.all_hosts(): rs = session.execute(query, execution_profile=tmp_profile) queried_hosts.add(rs.response_future._current_host) self.assertEqual(queried_hosts, expected_hosts) tuple_row = rs[0] self.assertIsInstance(tuple_row, tuple) with self.assertRaises(AttributeError): tuple_row.release_version # make sure original profile is not impacted self.assertTrue(session.execute(query, execution_profile='node1')[0].release_version) def test_setting_lbp_legacy(self): - cluster = Cluster() + cluster = TestCluster() self.addCleanup(cluster.shutdown) cluster.load_balancing_policy = RoundRobinPolicy() self.assertEqual( list(cluster.load_balancing_policy.make_query_plan()), [] ) cluster.connect() self.assertNotEqual( list(cluster.load_balancing_policy.make_query_plan()), [] ) def test_profile_lb_swap(self): """ Tests that profile load balancing policies are not shared Creates two LBP, runs a few queries, and validates that each LBP is execised seperately between EP's @since 3.5 @jira_ticket PYTHON-569 @expected_result LBP should not be shared. @test_category config_profiles """ query = "select release_version from system.local" rr1 = ExecutionProfile(load_balancing_policy=RoundRobinPolicy()) rr2 = ExecutionProfile(load_balancing_policy=RoundRobinPolicy()) exec_profiles = {'rr1': rr1, 'rr2': rr2} - with Cluster(execution_profiles=exec_profiles) as cluster: + with TestCluster(execution_profiles=exec_profiles) as cluster: session = cluster.connect(wait_for_all_pools=True) # default is DCA RR for all hosts expected_hosts = set(cluster.metadata.all_hosts()) rr1_queried_hosts = set() rr2_queried_hosts = set() rs = session.execute(query, execution_profile='rr1') rr1_queried_hosts.add(rs.response_future._current_host) rs = session.execute(query, execution_profile='rr2') rr2_queried_hosts.add(rs.response_future._current_host) self.assertEqual(rr2_queried_hosts, rr1_queried_hosts) def test_ta_lbp(self): """ Test that execution profiles containing token aware LBP can be added @since 3.5 @jira_ticket PYTHON-569 @expected_result Queries can run @test_category config_profiles """ query = "select release_version from system.local" ta1 = ExecutionProfile() - with Cluster() as cluster: + with TestCluster() as cluster: session = cluster.connect() cluster.add_execution_profile("ta1", ta1) rs = session.execute(query, execution_profile='ta1') def test_clone_shared_lbp(self): """ Tests that profile load balancing policies are shared on clone Creates one LBP clones it, and ensures that the LBP is shared between the two EP's @since 3.5 @jira_ticket PYTHON-569 @expected_result LBP is shared @test_category config_profiles """ query = "select release_version from system.local" rr1 = ExecutionProfile(load_balancing_policy=RoundRobinPolicy()) exec_profiles = {'rr1': rr1} - with Cluster(execution_profiles=exec_profiles) as cluster: + with TestCluster(execution_profiles=exec_profiles) as cluster: session = cluster.connect(wait_for_all_pools=True) self.assertGreater(len(cluster.metadata.all_hosts()), 1, "We only have one host connected at this point") rr1_clone = session.execution_profile_clone_update('rr1', row_factory=tuple_factory) cluster.add_execution_profile("rr1_clone", rr1_clone) rr1_queried_hosts = set() rr1_clone_queried_hosts = set() rs = session.execute(query, execution_profile='rr1') rr1_queried_hosts.add(rs.response_future._current_host) rs = session.execute(query, execution_profile='rr1_clone') rr1_clone_queried_hosts.add(rs.response_future._current_host) self.assertNotEqual(rr1_clone_queried_hosts, rr1_queried_hosts) def test_missing_exec_prof(self): """ Tests to verify that using an unknown profile raises a ValueError @since 3.5 @jira_ticket PYTHON-569 @expected_result ValueError @test_category config_profiles """ query = "select release_version from system.local" rr1 = ExecutionProfile(load_balancing_policy=RoundRobinPolicy()) rr2 = ExecutionProfile(load_balancing_policy=RoundRobinPolicy()) exec_profiles = {'rr1': rr1, 'rr2': rr2} - with Cluster(execution_profiles=exec_profiles) as cluster: + with TestCluster(execution_profiles=exec_profiles) as cluster: session = cluster.connect() with self.assertRaises(ValueError): session.execute(query, execution_profile='rr3') @local def test_profile_pool_management(self): """ Tests that changes to execution profiles correctly impact our cluster's pooling @since 3.5 @jira_ticket PYTHON-569 @expected_result pools should be correctly updated as EP's are added and removed @test_category config_profiles """ node1 = ExecutionProfile( load_balancing_policy=HostFilterPolicy( RoundRobinPolicy(), lambda host: host.address == "127.0.0.1" ) ) node2 = ExecutionProfile( load_balancing_policy=HostFilterPolicy( RoundRobinPolicy(), lambda host: host.address == "127.0.0.2" ) ) - with Cluster(execution_profiles={EXEC_PROFILE_DEFAULT: node1, 'node2': node2}) as cluster: + with TestCluster(execution_profiles={EXEC_PROFILE_DEFAULT: node1, 'node2': node2}) as cluster: session = cluster.connect(wait_for_all_pools=True) pools = session.get_pool_state() # there are more hosts, but we connected to the ones in the lbp aggregate self.assertGreater(len(cluster.metadata.all_hosts()), 2) self.assertEqual(set(h.address for h in pools), set(('127.0.0.1', '127.0.0.2'))) # dynamically update pools on add node3 = ExecutionProfile( load_balancing_policy=HostFilterPolicy( RoundRobinPolicy(), lambda host: host.address == "127.0.0.3" ) ) cluster.add_execution_profile('node3', node3) pools = session.get_pool_state() self.assertEqual(set(h.address for h in pools), set(('127.0.0.1', '127.0.0.2', '127.0.0.3'))) @local def test_add_profile_timeout(self): """ Tests that EP Timeouts are honored. @since 3.5 @jira_ticket PYTHON-569 @expected_result EP timeouts should override defaults @test_category config_profiles """ max_retry_count = 10 for i in range(max_retry_count): node1 = ExecutionProfile( load_balancing_policy=HostFilterPolicy( RoundRobinPolicy(), lambda host: host.address == "127.0.0.1" ) ) - with Cluster(execution_profiles={EXEC_PROFILE_DEFAULT: node1}) as cluster: + with TestCluster(execution_profiles={EXEC_PROFILE_DEFAULT: node1}) as cluster: session = cluster.connect(wait_for_all_pools=True) pools = session.get_pool_state() self.assertGreater(len(cluster.metadata.all_hosts()), 2) self.assertEqual(set(h.address for h in pools), set(('127.0.0.1',))) node2 = ExecutionProfile( load_balancing_policy=HostFilterPolicy( RoundRobinPolicy(), lambda host: host.address in ["127.0.0.2", "127.0.0.3"] ) ) start = time.time() try: self.assertRaises(cassandra.OperationTimedOut, cluster.add_execution_profile, 'profile_{0}'.format(i), node2, pool_wait_timeout=sys.float_info.min) break except AssertionError: end = time.time() self.assertAlmostEqual(start, end, 1) else: raise Exception("add_execution_profile didn't timeout after {0} retries".format(max_retry_count)) + @notwindows + def test_execute_query_timeout(self): + with TestCluster() as cluster: + session = cluster.connect(wait_for_all_pools=True) + query = "SELECT * FROM system.local" + + # default is passed down + default_profile = cluster.profile_manager.profiles[EXEC_PROFILE_DEFAULT] + rs = session.execute(query) + self.assertEqual(rs.response_future.timeout, default_profile.request_timeout) + + # tiny timeout times out as expected + tmp_profile = copy(default_profile) + tmp_profile.request_timeout = sys.float_info.min + + max_retry_count = 10 + for _ in range(max_retry_count): + start = time.time() + try: + with self.assertRaises(cassandra.OperationTimedOut): + session.execute(query, execution_profile=tmp_profile) + break + except: + import traceback + traceback.print_exc() + end = time.time() + self.assertAlmostEqual(start, end, 1) + else: + raise Exception("session.execute didn't time out in {0} tries".format(max_retry_count)) + def test_replicas_are_queried(self): """ Test that replicas are queried first for TokenAwarePolicy. A table with RF 1 is created. All the queries should go to that replica when TokenAwarePolicy is used. Then using HostFilterPolicy the replica is excluded from the considered hosts. By checking the trace we verify that there are no more replicas. @since 3.5 @jira_ticket PYTHON-653 @expected_result the replicas are queried for HostFilterPolicy @test_category metadata """ queried_hosts = set() - with Cluster(protocol_version=PROTOCOL_VERSION, - load_balancing_policy=TokenAwarePolicy(RoundRobinPolicy())) as cluster: + tap_profile = ExecutionProfile( + load_balancing_policy=TokenAwarePolicy(RoundRobinPolicy()) + ) + with TestCluster(execution_profiles={EXEC_PROFILE_DEFAULT: tap_profile}) as cluster: session = cluster.connect(wait_for_all_pools=True) session.execute(''' CREATE TABLE test1rf.table_with_big_key ( k1 int, k2 int, k3 int, k4 int, PRIMARY KEY((k1, k2, k3), k4))''') prepared = session.prepare("""SELECT * from test1rf.table_with_big_key WHERE k1 = ? AND k2 = ? AND k3 = ? AND k4 = ?""") for i in range(10): result = session.execute(prepared, (i, i, i, i), trace=True) trace = result.response_future.get_query_trace(query_cl=ConsistencyLevel.ALL) queried_hosts = self._assert_replica_queried(trace, only_replicas=True) last_i = i + hfp_profile = ExecutionProfile( + load_balancing_policy=HostFilterPolicy(RoundRobinPolicy(), + predicate=lambda host: host.address != only_replica) + ) only_replica = queried_hosts.pop() log = logging.getLogger(__name__) log.info("The only replica found was: {}".format(only_replica)) available_hosts = [host for host in ["127.0.0.1", "127.0.0.2", "127.0.0.3"] if host != only_replica] - with Cluster(contact_points=available_hosts, - protocol_version=PROTOCOL_VERSION, - load_balancing_policy=HostFilterPolicy(RoundRobinPolicy(), - predicate=lambda host: host.address != only_replica)) as cluster: + with TestCluster(contact_points=available_hosts, + execution_profiles={EXEC_PROFILE_DEFAULT: hfp_profile}) as cluster: session = cluster.connect(wait_for_all_pools=True) prepared = session.prepare("""SELECT * from test1rf.table_with_big_key WHERE k1 = ? AND k2 = ? AND k3 = ? AND k4 = ?""") for _ in range(10): result = session.execute(prepared, (last_i, last_i, last_i, last_i), trace=True) trace = result.response_future.get_query_trace(query_cl=ConsistencyLevel.ALL) self._assert_replica_queried(trace, only_replicas=False) session.execute('''DROP TABLE test1rf.table_with_big_key''') @unittest.skip @greaterthanorequalcass30 @lessthanorequalcass40 def test_compact_option(self): """ Test the driver can connect with the no_compact option and the results are as expected. This test is very similar to the corresponding dtest @since 3.12 @jira_ticket PYTHON-366 @expected_result only one hosts' metadata will be populated @test_category connection """ - nc_cluster = Cluster(protocol_version=PROTOCOL_VERSION, no_compact=True) + nc_cluster = TestCluster(no_compact=True) nc_session = nc_cluster.connect() - cluster = Cluster(protocol_version=PROTOCOL_VERSION, no_compact=False) + cluster = TestCluster(no_compact=False) session = cluster.connect() self.addCleanup(cluster.shutdown) self.addCleanup(nc_cluster.shutdown) nc_session.set_keyspace("test3rf") session.set_keyspace("test3rf") nc_session.execute( "CREATE TABLE IF NOT EXISTS compact_table (k int PRIMARY KEY, v1 int, v2 int) WITH COMPACT STORAGE;") for i in range(1, 5): nc_session.execute( "INSERT INTO compact_table (k, column1, v1, v2, value) VALUES " "({i}, 'a{i}', {i}, {i}, textAsBlob('b{i}'))".format(i=i)) nc_session.execute( "INSERT INTO compact_table (k, column1, v1, v2, value) VALUES " "({i}, 'a{i}{i}', {i}{i}, {i}{i}, textAsBlob('b{i}{i}'))".format(i=i)) nc_results = nc_session.execute("SELECT * FROM compact_table") self.assertEqual( set(nc_results.current_rows), {(1, u'a1', 11, 11, 'b1'), (1, u'a11', 11, 11, 'b11'), (2, u'a2', 22, 22, 'b2'), (2, u'a22', 22, 22, 'b22'), (3, u'a3', 33, 33, 'b3'), (3, u'a33', 33, 33, 'b33'), (4, u'a4', 44, 44, 'b4'), (4, u'a44', 44, 44, 'b44')}) results = session.execute("SELECT * FROM compact_table") self.assertEqual( set(results.current_rows), {(1, 11, 11), (2, 22, 22), (3, 33, 33), (4, 44, 44)}) def _assert_replica_queried(self, trace, only_replicas=True): queried_hosts = set() for row in trace.events: queried_hosts.add(row.source) if only_replicas: self.assertEqual(len(queried_hosts), 1, "The hosts queried where {}".format(queried_hosts)) else: self.assertGreater(len(queried_hosts), 1, "The host queried was {}".format(queried_hosts)) return queried_hosts def _check_trace(self, trace): self.assertIsNotNone(trace.request_type) self.assertIsNotNone(trace.duration) self.assertIsNotNone(trace.started_at) self.assertIsNotNone(trace.coordinator) self.assertIsNotNone(trace.events) class LocalHostAdressTranslator(AddressTranslator): def __init__(self, addr_map=None): self.addr_map = addr_map def translate(self, addr): new_addr = self.addr_map.get(addr) return new_addr @local class TestAddressTranslation(unittest.TestCase): def test_address_translator_basic(self): """ Test host address translation Uses a custom Address Translator to map all ip back to one. Validates AddressTranslator invocation by ensuring that only meta data associated with single host is populated @since 3.3 @jira_ticket PYTHON-69 @expected_result only one hosts' metadata will be populated @test_category metadata """ lh_ad = LocalHostAdressTranslator({'127.0.0.1': '127.0.0.1', '127.0.0.2': '127.0.0.1', '127.0.0.3': '127.0.0.1'}) - c = Cluster(address_translator=lh_ad) + c = TestCluster(address_translator=lh_ad) c.connect() self.assertEqual(len(c.metadata.all_hosts()), 1) c.shutdown() def test_address_translator_with_mixed_nodes(self): """ Test host address translation Uses a custom Address Translator to map ip's of non control_connection nodes to each other Validates AddressTranslator invocation by ensuring that metadata for mapped hosts is also mapped @since 3.3 @jira_ticket PYTHON-69 @expected_result metadata for crossed hosts will also be crossed @test_category metadata """ adder_map = {'127.0.0.1': '127.0.0.1', '127.0.0.2': '127.0.0.3', '127.0.0.3': '127.0.0.2'} lh_ad = LocalHostAdressTranslator(adder_map) - c = Cluster(address_translator=lh_ad) + c = TestCluster(address_translator=lh_ad) c.connect() for host in c.metadata.all_hosts(): self.assertEqual(adder_map.get(host.address), host.broadcast_address) c.shutdown() @local class ContextManagementTest(unittest.TestCase): load_balancing_policy = HostFilterPolicy( RoundRobinPolicy(), lambda host: host.address == CASSANDRA_IP ) cluster_kwargs = {'execution_profiles': {EXEC_PROFILE_DEFAULT: ExecutionProfile(load_balancing_policy= load_balancing_policy)}, 'schema_metadata_enabled': False, 'token_metadata_enabled': False} def test_no_connect(self): """ Test cluster context without connecting. @since 3.4 @jira_ticket PYTHON-521 @expected_result context should still be valid @test_category configuration """ - with Cluster() as cluster: + with TestCluster() as cluster: self.assertFalse(cluster.is_shutdown) self.assertTrue(cluster.is_shutdown) def test_simple_nested(self): """ Test cluster and session contexts nested in one another. @since 3.4 @jira_ticket PYTHON-521 @expected_result cluster/session should be crated and shutdown appropriately. @test_category configuration """ - with Cluster(**self.cluster_kwargs) as cluster: + with TestCluster(**self.cluster_kwargs) as cluster: with cluster.connect() as session: self.assertFalse(cluster.is_shutdown) self.assertFalse(session.is_shutdown) self.assertTrue(session.execute('select release_version from system.local')[0]) self.assertTrue(session.is_shutdown) self.assertTrue(cluster.is_shutdown) def test_cluster_no_session(self): """ Test cluster context without session context. @since 3.4 @jira_ticket PYTHON-521 @expected_result Session should be created correctly. Cluster should shutdown outside of context @test_category configuration """ - with Cluster(**self.cluster_kwargs) as cluster: + with TestCluster(**self.cluster_kwargs) as cluster: session = cluster.connect() self.assertFalse(cluster.is_shutdown) self.assertFalse(session.is_shutdown) self.assertTrue(session.execute('select release_version from system.local')[0]) self.assertTrue(session.is_shutdown) self.assertTrue(cluster.is_shutdown) def test_session_no_cluster(self): """ Test session context without cluster context. @since 3.4 @jira_ticket PYTHON-521 @expected_result session should be created correctly. Session should shutdown correctly outside of context @test_category configuration """ - cluster = Cluster(**self.cluster_kwargs) + cluster = TestCluster(**self.cluster_kwargs) unmanaged_session = cluster.connect() with cluster.connect() as session: self.assertFalse(cluster.is_shutdown) self.assertFalse(session.is_shutdown) self.assertFalse(unmanaged_session.is_shutdown) self.assertTrue(session.execute('select release_version from system.local')[0]) self.assertTrue(session.is_shutdown) self.assertFalse(cluster.is_shutdown) self.assertFalse(unmanaged_session.is_shutdown) unmanaged_session.shutdown() self.assertTrue(unmanaged_session.is_shutdown) self.assertFalse(cluster.is_shutdown) cluster.shutdown() self.assertTrue(cluster.is_shutdown) class HostStateTest(unittest.TestCase): def test_down_event_with_active_connection(self): """ Test to ensure that on down calls to clusters with connections still active don't result in a host being marked down. The second part of the test kills the connection then invokes on_down, and ensures the state changes for host's metadata. @since 3.7 @jira_ticket PYTHON-498 @expected_result host should never be toggled down while a connection is active. @test_category connection """ - with Cluster(protocol_version=PROTOCOL_VERSION) as cluster: + with TestCluster() as cluster: session = cluster.connect(wait_for_all_pools=True) random_host = cluster.metadata.all_hosts()[0] cluster.on_down(random_host, False) for _ in range(10): new_host = cluster.metadata.all_hosts()[0] self.assertTrue(new_host.is_up, "Host was not up on iteration {0}".format(_)) time.sleep(.01) pool = session._pools.get(random_host) pool.shutdown() cluster.on_down(random_host, False) was_marked_down = False for _ in range(20): new_host = cluster.metadata.all_hosts()[0] if not new_host.is_up: was_marked_down = True break time.sleep(.01) self.assertTrue(was_marked_down) @local class DontPrepareOnIgnoredHostsTest(unittest.TestCase): ignored_addresses = ['127.0.0.3'] ignore_node_3_policy = IgnoredHostPolicy(ignored_addresses) def test_prepare_on_ignored_hosts(self): - cluster = Cluster(protocol_version=PROTOCOL_VERSION, - load_balancing_policy=self.ignore_node_3_policy) + cluster = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(load_balancing_policy=self.ignore_node_3_policy)} + ) session = cluster.connect() cluster.reprepare_on_up, cluster.prepare_on_all_hosts = True, False hosts = cluster.metadata.all_hosts() session.execute("CREATE KEYSPACE clustertests " "WITH replication = " "{'class': 'SimpleStrategy', 'replication_factor': '1'}") session.execute("CREATE TABLE clustertests.tab (a text, PRIMARY KEY (a))") # assign to an unused variable so cluster._prepared_statements retains # reference _ = session.prepare("INSERT INTO clustertests.tab (a) VALUES ('a')") # noqa cluster.connection_factory = Mock(wraps=cluster.connection_factory) unignored_address = '127.0.0.1' unignored_host = next(h for h in hosts if h.address == unignored_address) ignored_host = next(h for h in hosts if h.address in self.ignored_addresses) unignored_host.is_up = ignored_host.is_up = False cluster.on_up(unignored_host) cluster.on_up(ignored_host) # the length of mock_calls will vary, but all should use the unignored # address for c in cluster.connection_factory.mock_calls: self.assertEqual(call(DefaultEndPoint(unignored_address)), c) cluster.shutdown() -@local -class DuplicateRpcTest(unittest.TestCase): - - load_balancing_policy = HostFilterPolicy(RoundRobinPolicy(), - lambda host: host.address == "127.0.0.1") - - def setUp(self): - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, load_balancing_policy=self.load_balancing_policy) - self.session = self.cluster.connect() - self.session.execute("UPDATE system.peers SET rpc_address = '127.0.0.1' WHERE peer='127.0.0.2'") - - def tearDown(self): - self.session.execute("UPDATE system.peers SET rpc_address = '127.0.0.2' WHERE peer='127.0.0.2'") - self.cluster.shutdown() - - def test_duplicate(self): - """ - Test duplicate RPC addresses. - - Modifies the system.peers table to make hosts have the same rpc address. Ensures such hosts are filtered out and a message is logged - - @since 3.4 - @jira_ticket PYTHON-366 - @expected_result only one hosts' metadata will be populated - - @test_category metadata - """ - mock_handler = MockLoggingHandler() - logger = logging.getLogger(cassandra.cluster.__name__) - logger.addHandler(mock_handler) - test_cluster = Cluster(protocol_version=PROTOCOL_VERSION, load_balancing_policy=self.load_balancing_policy) - test_cluster.connect() - warnings = mock_handler.messages.get("warning") - self.assertEqual(len(warnings), 1) - self.assertTrue('multiple' in warnings[0]) - logger.removeHandler(mock_handler) - test_cluster.shutdown() - - -@protocolv5 +@protocolv6 class BetaProtocolTest(unittest.TestCase): - @protocolv5 + @protocolv6 def test_invalid_protocol_version_beta_option(self): """ - Test cluster connection with protocol v5 and beta flag not set + Test cluster connection with protocol v6 and beta flag not set @since 3.7.0 - @jira_ticket PYTHON-614 - @expected_result client shouldn't connect with V5 and no beta flag set + @jira_ticket PYTHON-614, PYTHON-1232 + @expected_result client shouldn't connect with V6 and no beta flag set @test_category connection """ - cluster = Cluster(protocol_version=cassandra.ProtocolVersion.MAX_SUPPORTED, allow_beta_protocol_version=False) + cluster = TestCluster(protocol_version=cassandra.ProtocolVersion.V6, allow_beta_protocol_version=False) try: with self.assertRaises(NoHostAvailable): cluster.connect() except Exception as e: self.fail("Unexpected error encountered {0}".format(e.message)) - @protocolv5 + @protocolv6 def test_valid_protocol_version_beta_options_connect(self): """ Test cluster connection with protocol version 5 and beta flag set @since 3.7.0 - @jira_ticket PYTHON-614 - @expected_result client should connect with protocol v5 and beta flag set. + @jira_ticket PYTHON-614, PYTHON-1232 + @expected_result client should connect with protocol v6 and beta flag set. @test_category connection """ - cluster = Cluster(protocol_version=cassandra.ProtocolVersion.MAX_SUPPORTED, allow_beta_protocol_version=True) + cluster = Cluster(protocol_version=cassandra.ProtocolVersion.V6, allow_beta_protocol_version=True) session = cluster.connect() - self.assertEqual(cluster.protocol_version, cassandra.ProtocolVersion.MAX_SUPPORTED) + self.assertEqual(cluster.protocol_version, cassandra.ProtocolVersion.V6) self.assertTrue(session.execute("select release_version from system.local")[0]) cluster.shutdown() class DeprecationWarningTest(unittest.TestCase): def test_deprecation_warnings_legacy_parameters(self): """ Tests the deprecation warning has been added when using legacy parameters @since 3.13 @jira_ticket PYTHON-877 @expected_result the deprecation warning is emitted @test_category logs """ with warnings.catch_warnings(record=True) as w: - Cluster(load_balancing_policy=RoundRobinPolicy()) + TestCluster(load_balancing_policy=RoundRobinPolicy()) self.assertEqual(len(w), 1) self.assertIn("Legacy execution parameters will be removed in 4.0. Consider using execution profiles.", str(w[0].message)) def test_deprecation_warnings_meta_refreshed(self): """ Tests the deprecation warning has been added when enabling metadata refreshment @since 3.13 @jira_ticket PYTHON-890 @expected_result the deprecation warning is emitted @test_category logs """ with warnings.catch_warnings(record=True) as w: - cluster = Cluster() + cluster = TestCluster() cluster.set_meta_refresh_enabled(True) self.assertEqual(len(w), 1) self.assertIn("Cluster.set_meta_refresh_enabled is deprecated and will be removed in 4.0.", str(w[0].message)) def test_deprecation_warning_default_consistency_level(self): """ Tests the deprecation warning has been added when enabling session the default consistency level to session @since 3.14 @jira_ticket PYTHON-935 @expected_result the deprecation warning is emitted @test_category logs """ with warnings.catch_warnings(record=True) as w: - cluster = Cluster() + cluster = TestCluster() session = cluster.connect() session.default_consistency_level = ConsistencyLevel.ONE self.assertEqual(len(w), 1) self.assertIn("Setting the consistency level at the session level will be removed in 4.0", str(w[0].message)) diff --git a/tests/integration/standard/test_concurrent.py b/tests/integration/standard/test_concurrent.py index c85bb64..8bd65c7 100644 --- a/tests/integration/standard/test_concurrent.py +++ b/tests/integration/standard/test_concurrent.py @@ -1,309 +1,311 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from itertools import cycle -from six import next import sys, logging, traceback from cassandra import InvalidRequest, ConsistencyLevel, ReadTimeout, WriteTimeout, OperationTimedOut, \ ReadFailure, WriteFailure -from cassandra.cluster import Cluster +from cassandra.cluster import ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.concurrent import execute_concurrent, execute_concurrent_with_args, ExecutionResult from cassandra.policies import HostDistance from cassandra.query import tuple_factory, SimpleStatement -from tests.integration import use_singledc, PROTOCOL_VERSION +from tests.integration import use_singledc, PROTOCOL_VERSION, TestCluster from six import next try: import unittest2 as unittest except ImportError: import unittest # noqa log = logging.getLogger(__name__) def setup_module(): use_singledc() class ClusterTests(unittest.TestCase): @classmethod def setUpClass(cls): - cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cls.cluster = TestCluster( + execution_profiles = { + EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=tuple_factory) + } + ) if PROTOCOL_VERSION < 3: cls.cluster.set_core_connections_per_host(HostDistance.LOCAL, 1) cls.session = cls.cluster.connect() - cls.session.row_factory = tuple_factory @classmethod def tearDownClass(cls): cls.cluster.shutdown() def execute_concurrent_helper(self, session, query, results_generator=False): count = 0 while count < 100: try: return execute_concurrent(session, query, results_generator=False) except (ReadTimeout, WriteTimeout, OperationTimedOut, ReadFailure, WriteFailure): ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb count += 1 raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(query)) def execute_concurrent_args_helper(self, session, query, params, results_generator=False): count = 0 while count < 100: try: return execute_concurrent_with_args(session, query, params, results_generator=results_generator) except (ReadTimeout, WriteTimeout, OperationTimedOut, ReadFailure, WriteFailure): ex_type, ex, tb = sys.exc_info() log.warning("{0}: {1} Backtrace: {2}".format(ex_type.__name__, ex, traceback.extract_tb(tb))) del tb raise RuntimeError("Failed to execute query after 100 attempts: {0}".format(query)) def test_execute_concurrent(self): for num_statements in (0, 1, 2, 7, 10, 99, 100, 101, 199, 200, 201): # write statement = SimpleStatement( "INSERT INTO test3rf.test (k, v) VALUES (%s, %s)", consistency_level=ConsistencyLevel.QUORUM) statements = cycle((statement, )) parameters = [(i, i) for i in range(num_statements)] results = self.execute_concurrent_helper(self.session, list(zip(statements, parameters))) self.assertEqual(num_statements, len(results)) for success, result in results: self.assertTrue(success) self.assertFalse(result) # read statement = SimpleStatement( "SELECT v FROM test3rf.test WHERE k=%s", consistency_level=ConsistencyLevel.QUORUM) statements = cycle((statement, )) parameters = [(i, ) for i in range(num_statements)] results = self.execute_concurrent_helper(self.session, list(zip(statements, parameters))) self.assertEqual(num_statements, len(results)) self.assertEqual([(True, [(i,)]) for i in range(num_statements)], results) def test_execute_concurrent_with_args(self): for num_statements in (0, 1, 2, 7, 10, 99, 100, 101, 199, 200, 201): statement = SimpleStatement( "INSERT INTO test3rf.test (k, v) VALUES (%s, %s)", consistency_level=ConsistencyLevel.QUORUM) parameters = [(i, i) for i in range(num_statements)] results = self.execute_concurrent_args_helper(self.session, statement, parameters) self.assertEqual(num_statements, len(results)) for success, result in results: self.assertTrue(success) self.assertFalse(result) # read statement = SimpleStatement( "SELECT v FROM test3rf.test WHERE k=%s", consistency_level=ConsistencyLevel.QUORUM) parameters = [(i, ) for i in range(num_statements)] results = self.execute_concurrent_args_helper(self.session, statement, parameters) self.assertEqual(num_statements, len(results)) self.assertEqual([(True, [(i,)]) for i in range(num_statements)], results) def test_execute_concurrent_with_args_generator(self): """ Test to validate that generator based results are surfaced correctly Repeatedly inserts data into a a table and attempts to query it. It then validates that the results are returned in the order expected @since 2.7.0 @jira_ticket PYTHON-123 @expected_result all data should be returned in order. @test_category queries:async """ for num_statements in (0, 1, 2, 7, 10, 99, 100, 101, 199, 200, 201): statement = SimpleStatement( "INSERT INTO test3rf.test (k, v) VALUES (%s, %s)", consistency_level=ConsistencyLevel.QUORUM) parameters = [(i, i) for i in range(num_statements)] results = self.execute_concurrent_args_helper(self.session, statement, parameters, results_generator=True) for success, result in results: self.assertTrue(success) self.assertFalse(result) results = self.execute_concurrent_args_helper(self.session, statement, parameters, results_generator=True) for result in results: self.assertTrue(isinstance(result, ExecutionResult)) self.assertTrue(result.success) self.assertFalse(result.result_or_exc) # read statement = SimpleStatement( "SELECT v FROM test3rf.test WHERE k=%s", consistency_level=ConsistencyLevel.QUORUM) parameters = [(i, ) for i in range(num_statements)] results = self.execute_concurrent_args_helper(self.session, statement, parameters, results_generator=True) for i in range(num_statements): result = next(results) self.assertEqual((True, [(i,)]), result) self.assertRaises(StopIteration, next, results) def test_execute_concurrent_paged_result(self): if PROTOCOL_VERSION < 2: raise unittest.SkipTest( "Protocol 2+ is required for Paging, currently testing against %r" % (PROTOCOL_VERSION,)) num_statements = 201 statement = SimpleStatement( "INSERT INTO test3rf.test (k, v) VALUES (%s, %s)", consistency_level=ConsistencyLevel.QUORUM) parameters = [(i, i) for i in range(num_statements)] results = self.execute_concurrent_args_helper(self.session, statement, parameters) self.assertEqual(num_statements, len(results)) for success, result in results: self.assertTrue(success) self.assertFalse(result) # read statement = SimpleStatement( "SELECT * FROM test3rf.test LIMIT %s", consistency_level=ConsistencyLevel.QUORUM, fetch_size=int(num_statements / 2)) results = self.execute_concurrent_args_helper(self.session, statement, [(num_statements,)]) self.assertEqual(1, len(results)) self.assertTrue(results[0][0]) result = results[0][1] self.assertTrue(result.has_more_pages) self.assertEqual(num_statements, sum(1 for _ in result)) def test_execute_concurrent_paged_result_generator(self): """ Test to validate that generator based results are surfaced correctly when paging is used Inserts data into a a table and attempts to query it. It then validates that the results are returned as expected (no order specified) @since 2.7.0 @jira_ticket PYTHON-123 @expected_result all data should be returned in order. @test_category paging """ if PROTOCOL_VERSION < 2: raise unittest.SkipTest( "Protocol 2+ is required for Paging, currently testing against %r" % (PROTOCOL_VERSION,)) num_statements = 201 statement = SimpleStatement( "INSERT INTO test3rf.test (k, v) VALUES (%s, %s)", consistency_level=ConsistencyLevel.QUORUM) parameters = [(i, i) for i in range(num_statements)] results = self.execute_concurrent_args_helper(self.session, statement, parameters, results_generator=True) self.assertEqual(num_statements, sum(1 for _ in results)) # read statement = SimpleStatement( "SELECT * FROM test3rf.test LIMIT %s", consistency_level=ConsistencyLevel.QUORUM, fetch_size=int(num_statements / 2)) paged_results_gen = self.execute_concurrent_args_helper(self.session, statement, [(num_statements,)], results_generator=True) # iterate over all the result and make sure we find the correct number. found_results = 0 for result_tuple in paged_results_gen: paged_result = result_tuple[1] for _ in paged_result: found_results += 1 self.assertEqual(found_results, num_statements) def test_first_failure(self): statements = cycle(("INSERT INTO test3rf.test (k, v) VALUES (%s, %s)", )) parameters = [(i, i) for i in range(100)] # we'll get an error back from the server parameters[57] = ('efefef', 'awefawefawef') self.assertRaises( InvalidRequest, execute_concurrent, self.session, list(zip(statements, parameters)), raise_on_first_error=True) def test_first_failure_client_side(self): statement = SimpleStatement( "INSERT INTO test3rf.test (k, v) VALUES (%s, %s)", consistency_level=ConsistencyLevel.QUORUM) statements = cycle((statement, )) parameters = [(i, i) for i in range(100)] # the driver will raise an error when binding the params parameters[57] = 1 self.assertRaises( TypeError, execute_concurrent, self.session, list(zip(statements, parameters)), raise_on_first_error=True) def test_no_raise_on_first_failure(self): statement = SimpleStatement( "INSERT INTO test3rf.test (k, v) VALUES (%s, %s)", consistency_level=ConsistencyLevel.QUORUM) statements = cycle((statement, )) parameters = [(i, i) for i in range(100)] # we'll get an error back from the server parameters[57] = ('efefef', 'awefawefawef') results = execute_concurrent(self.session, list(zip(statements, parameters)), raise_on_first_error=False) for i, (success, result) in enumerate(results): if i == 57: self.assertFalse(success) self.assertIsInstance(result, InvalidRequest) else: self.assertTrue(success) self.assertFalse(result) def test_no_raise_on_first_failure_client_side(self): statement = SimpleStatement( "INSERT INTO test3rf.test (k, v) VALUES (%s, %s)", consistency_level=ConsistencyLevel.QUORUM) statements = cycle((statement, )) parameters = [(i, i) for i in range(100)] # the driver will raise an error when binding the params parameters[57] = 1 results = execute_concurrent(self.session, list(zip(statements, parameters)), raise_on_first_error=False) for i, (success, result) in enumerate(results): if i == 57: self.assertFalse(success) self.assertIsInstance(result, TypeError) else: self.assertTrue(success) self.assertFalse(result) diff --git a/tests/integration/standard/test_connection.py b/tests/integration/standard/test_connection.py index 595fc12..aaa5a27 100644 --- a/tests/integration/standard/test_connection.py +++ b/tests/integration/standard/test_connection.py @@ -1,462 +1,469 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from functools import partial +from mock import patch import logging from six.moves import range import sys import threading from threading import Thread, Event import time from unittest import SkipTest from cassandra import ConsistencyLevel, OperationTimedOut -from cassandra.cluster import NoHostAvailable, ConnectionShutdown, Cluster +from cassandra.cluster import NoHostAvailable, ConnectionShutdown, ExecutionProfile, EXEC_PROFILE_DEFAULT import cassandra.io.asyncorereactor from cassandra.io.asyncorereactor import AsyncoreConnection from cassandra.protocol import QueryMessage from cassandra.connection import Connection from cassandra.policies import HostFilterPolicy, RoundRobinPolicy, HostStateListener from cassandra.pool import HostConnectionPool from tests import is_monkey_patched -from tests.integration import use_singledc, PROTOCOL_VERSION, get_node, CASSANDRA_IP, local, \ - requiresmallclockgranularity, greaterthancass20 +from tests.integration import use_singledc, get_node, CASSANDRA_IP, local, \ + requiresmallclockgranularity, greaterthancass20, TestCluster + try: from cassandra.io.libevreactor import LibevConnection import cassandra.io.libevreactor except ImportError: LibevConnection = None log = logging.getLogger(__name__) def setup_module(): use_singledc() class ConnectionTimeoutTest(unittest.TestCase): def setUp(self): - self.defaultInFlight = Connection.max_in_flight - Connection.max_in_flight = 2 - self.cluster = Cluster( - protocol_version=PROTOCOL_VERSION, - load_balancing_policy=HostFilterPolicy( - RoundRobinPolicy(), predicate=lambda host: host.address == CASSANDRA_IP + self.cluster = TestCluster(execution_profiles={ + EXEC_PROFILE_DEFAULT: ExecutionProfile( + load_balancing_policy=HostFilterPolicy( + RoundRobinPolicy(), predicate=lambda host: host.address == CASSANDRA_IP + ) ) - ) + }) + self.session = self.cluster.connect() def tearDown(self): - Connection.max_in_flight = self.defaultInFlight self.cluster.shutdown() + @patch('cassandra.connection.Connection.max_in_flight', 2) def test_in_flight_timeout(self): """ Test to ensure that connection id fetching will block when max_id is reached/ In previous versions of the driver this test will cause a NoHostAvailable exception to be thrown, when the max_id is restricted @since 3.3 @jira_ticket PYTHON-514 @expected_result When many requests are run on a single node connection acquisition should block until connection is available or the request times out. @test_category connection timeout """ futures = [] query = '''SELECT * FROM system.local''' - for i in range(100): + for _ in range(100): futures.append(self.session.execute_async(query)) for future in futures: future.result() class TestHostListener(HostStateListener): host_down = None def on_down(self, host): self.host_down = True def on_up(self, host): self.host_down = False class HeartbeatTest(unittest.TestCase): """ Test to validate failing a heartbeat check doesn't mark a host as down @since 3.3 @jira_ticket PYTHON-286 @expected_result host should be marked down when heartbeat fails. This happens after PYTHON-734 @test_category connection heartbeat """ def setUp(self): - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, idle_heartbeat_interval=1) + self.cluster = TestCluster(idle_heartbeat_interval=1) self.session = self.cluster.connect(wait_for_all_pools=True) def tearDown(self): self.cluster.shutdown() @local @greaterthancass20 def test_heart_beat_timeout(self): # Setup a host listener to ensure the nodes don't go down test_listener = TestHostListener() host = "127.0.0.1:9042" node = get_node(1) initial_connections = self.fetch_connections(host, self.cluster) self.assertNotEqual(len(initial_connections), 0) self.cluster.register_listener(test_listener) # Pause the node try: node.pause() # Wait for connections associated with this host go away self.wait_for_no_connections(host, self.cluster) # Wait to seconds for the driver to be notified time.sleep(2) self.assertTrue(test_listener.host_down) # Resume paused node finally: node.resume() # Run a query to ensure connections are re-established current_host = "" count = 0 while current_host != host and count < 100: rs = self.session.execute_async("SELECT * FROM system.local", trace=False) rs.result() current_host = str(rs._current_host) count += 1 time.sleep(.1) self.assertLess(count, 100, "Never connected to the first node") new_connections = self.wait_for_connections(host, self.cluster) self.assertFalse(test_listener.host_down) # Make sure underlying new connections don't match previous ones for connection in initial_connections: self.assertFalse(connection in new_connections) def fetch_connections(self, host, cluster): # Given a cluster object and host grab all connection associated with that host connections = [] holders = cluster.get_connection_holders() for conn in holders: if host == str(getattr(conn, 'host', '')): if isinstance(conn, HostConnectionPool): if conn._connections is not None and len(conn._connections) > 0: connections.append(conn._connections) else: if conn._connection is not None: connections.append(conn._connection) return connections def wait_for_connections(self, host, cluster): retry = 0 while(retry < 300): retry += 1 connections = self.fetch_connections(host, cluster) if len(connections) is not 0: return connections time.sleep(.1) self.fail("No new connections found") def wait_for_no_connections(self, host, cluster): retry = 0 while(retry < 100): retry += 1 connections = self.fetch_connections(host, cluster) if len(connections) is 0: return time.sleep(.5) self.fail("Connections never cleared") class ConnectionTests(object): klass = None def setUp(self): self.klass.initialize_reactor() def get_connection(self, timeout=5): """ Helper method to solve automated testing issues within Jenkins. Officially patched under the 2.0 branch through 17998ef72a2fe2e67d27dd602b6ced33a58ad8ef, but left as is for the 1.0 branch due to possible regressions for fixing an automated testing edge-case. """ conn = None e = None for i in range(5): try: contact_point = CASSANDRA_IP - conn = self.klass.factory(endpoint=contact_point, timeout=timeout, protocol_version=PROTOCOL_VERSION) + conn = self.klass.factory( + endpoint=contact_point, + timeout=timeout, + protocol_version=TestCluster.DEFAULT_PROTOCOL_VERSION, + allow_beta_protocol_version=TestCluster.DEFAULT_ALLOW_BETA + ) break except (OperationTimedOut, NoHostAvailable, ConnectionShutdown) as e: continue if conn: return conn else: raise e def test_single_connection(self): """ Test a single connection with sequential requests. """ conn = self.get_connection() query = "SELECT keyspace_name FROM system.schema_keyspaces LIMIT 1" event = Event() def cb(count, *args, **kwargs): count += 1 if count >= 10: conn.close() event.set() else: conn.send_msg( QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE), request_id=0, cb=partial(cb, count)) conn.send_msg( QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE), request_id=0, cb=partial(cb, 0)) event.wait() def test_single_connection_pipelined_requests(self): """ Test a single connection with pipelined requests. """ conn = self.get_connection() query = "SELECT keyspace_name FROM system.schema_keyspaces LIMIT 1" responses = [False] * 100 event = Event() def cb(response_list, request_num, *args, **kwargs): response_list[request_num] = True if all(response_list): conn.close() event.set() for i in range(100): conn.send_msg( QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE), request_id=i, cb=partial(cb, responses, i)) event.wait() def test_multiple_connections(self): """ Test multiple connections with pipelined requests. """ conns = [self.get_connection() for i in range(5)] events = [Event() for i in range(5)] query = "SELECT keyspace_name FROM system.schema_keyspaces LIMIT 1" def cb(event, conn, count, *args, **kwargs): count += 1 if count >= 10: conn.close() event.set() else: conn.send_msg( QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE), request_id=count, cb=partial(cb, event, conn, count)) for event, conn in zip(events, conns): conn.send_msg( QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE), request_id=0, cb=partial(cb, event, conn, 0)) for event in events: event.wait() def test_multiple_threads_shared_connection(self): """ Test sharing a single connections across multiple threads, which will result in pipelined requests. """ num_requests_per_conn = 25 num_threads = 5 event = Event() conn = self.get_connection() query = "SELECT keyspace_name FROM system.schema_keyspaces LIMIT 1" def cb(all_responses, thread_responses, request_num, *args, **kwargs): thread_responses[request_num] = True if all(map(all, all_responses)): conn.close() event.set() def send_msgs(all_responses, thread_responses): for i in range(num_requests_per_conn): qmsg = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE) with conn.lock: request_id = conn.get_request_id() conn.send_msg(qmsg, request_id, cb=partial(cb, all_responses, thread_responses, i)) all_responses = [] threads = [] for i in range(num_threads): thread_responses = [False] * num_requests_per_conn all_responses.append(thread_responses) t = Thread(target=send_msgs, args=(all_responses, thread_responses)) threads.append(t) for t in threads: t.start() for t in threads: t.join() event.wait() def test_multiple_threads_multiple_connections(self): """ Test several threads, each with their own Connection and pipelined requests. """ num_requests_per_conn = 25 num_conns = 5 events = [Event() for i in range(5)] query = "SELECT keyspace_name FROM system.schema_keyspaces LIMIT 1" def cb(conn, event, thread_responses, request_num, *args, **kwargs): thread_responses[request_num] = True if all(thread_responses): conn.close() event.set() def send_msgs(conn, event): thread_responses = [False] * num_requests_per_conn for i in range(num_requests_per_conn): qmsg = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE) with conn.lock: request_id = conn.get_request_id() conn.send_msg(qmsg, request_id, cb=partial(cb, conn, event, thread_responses, i)) event.wait() threads = [] for i in range(num_conns): conn = self.get_connection() t = Thread(target=send_msgs, args=(conn, events[i])) threads.append(t) for t in threads: t.start() for t in threads: t.join() @requiresmallclockgranularity def test_connect_timeout(self): # Underlying socket implementations don't always throw a socket timeout even with min float # This can be timing sensitive, added retry to ensure failure occurs if it can max_retry_count = 10 exception_thrown = False for i in range(max_retry_count): start = time.time() try: conn = self.get_connection(timeout=sys.float_info.min) conn.close() except Exception as e: end = time.time() self.assertAlmostEqual(start, end, 1) exception_thrown = True break self.assertTrue(exception_thrown) def test_subclasses_share_loop(self): if self.klass not in (AsyncoreConnection, LibevConnection): raise SkipTest class C1(self.klass): pass class C2(self.klass): pass - clusterC1 = Cluster(connection_class=C1) + clusterC1 = TestCluster(connection_class=C1) clusterC1.connect(wait_for_all_pools=True) - clusterC2 = Cluster(connection_class=C2) + clusterC2 = TestCluster(connection_class=C2) clusterC2.connect(wait_for_all_pools=True) self.addCleanup(clusterC1.shutdown) self.addCleanup(clusterC2.shutdown) self.assertEqual(len(get_eventloop_threads(self.event_loop_name)), 1) def get_eventloop_threads(name): all_threads = list(threading.enumerate()) log.debug('all threads: {}'.format(all_threads)) log.debug('all names: {}'.format([thread.name for thread in all_threads])) event_loops_threads = [thread for thread in all_threads if name == thread.name] return event_loops_threads class AsyncoreConnectionTests(ConnectionTests, unittest.TestCase): klass = AsyncoreConnection event_loop_name = "asyncore_cassandra_driver_event_loop" def setUp(self): if is_monkey_patched(): raise unittest.SkipTest("Can't test asyncore with monkey patching") ConnectionTests.setUp(self) def clean_global_loop(self): cassandra.io.asyncorereactor._global_loop._cleanup() cassandra.io.asyncorereactor._global_loop = None class LibevConnectionTests(ConnectionTests, unittest.TestCase): klass = LibevConnection event_loop_name = "event_loop" def setUp(self): if is_monkey_patched(): raise unittest.SkipTest("Can't test libev with monkey patching") if LibevConnection is None: raise unittest.SkipTest( 'libev does not appear to be installed properly') ConnectionTests.setUp(self) def clean_global_loop(self): cassandra.io.libevreactor._global_loop._cleanup() cassandra.io.libevreactor._global_loop = None diff --git a/tests/integration/standard/test_control_connection.py b/tests/integration/standard/test_control_connection.py index b928cd2..db7cff8 100644 --- a/tests/integration/standard/test_control_connection.py +++ b/tests/integration/standard/test_control_connection.py @@ -1,105 +1,131 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License # # # +from cassandra import InvalidRequest try: import unittest2 as unittest except ImportError: import unittest # noqa -from cassandra.cluster import Cluster from cassandra.protocol import ConfigurationException -from tests.integration import use_singledc, PROTOCOL_VERSION +from tests.integration import use_singledc, PROTOCOL_VERSION, TestCluster, greaterthanorequalcass40, notdse from tests.integration.datatype_utils import update_datatypes def setup_module(): use_singledc() update_datatypes() class ControlConnectionTests(unittest.TestCase): def setUp(self): if PROTOCOL_VERSION < 3: raise unittest.SkipTest( "Native protocol 3,0+ is required for UDTs using %r" % (PROTOCOL_VERSION,)) - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + self.cluster = TestCluster() def tearDown(self): try: self.session.execute("DROP KEYSPACE keyspacetodrop ") - except (ConfigurationException): + except (ConfigurationException, InvalidRequest): # we already removed the keyspace. pass self.cluster.shutdown() def test_drop_keyspace(self): """ Test to validate that dropping a keyspace with user defined types doesn't kill the control connection. Creates a keyspace, and populates with a user defined type. It then records the control_connection's id. It will then drop the keyspace and get the id of the control_connection again. They should be the same. If they are not dropping the keyspace likely caused the control connection to be rebuilt. @since 2.7.0 @jira_ticket PYTHON-358 @expected_result the control connection is not killed @test_category connection """ self.session = self.cluster.connect() self.session.execute(""" CREATE KEYSPACE keyspacetodrop WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1' } """) self.session.set_keyspace("keyspacetodrop") self.session.execute("CREATE TYPE user (age int, name text)") self.session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen)") cc_id_pre_drop = id(self.cluster.control_connection._connection) self.session.execute("DROP KEYSPACE keyspacetodrop") cc_id_post_drop = id(self.cluster.control_connection._connection) self.assertEqual(cc_id_post_drop, cc_id_pre_drop) def test_get_control_connection_host(self): """ Test to validate Cluster.get_control_connection_host() metadata @since 3.5.0 @jira_ticket PYTHON-583 @expected_result the control connection metadata should accurately reflect cluster state. @test_category metadata """ host = self.cluster.get_control_connection_host() self.assertEqual(host, None) self.session = self.cluster.connect() cc_host = self.cluster.control_connection._connection.host host = self.cluster.get_control_connection_host() self.assertEqual(host.address, cc_host) self.assertEqual(host.is_up, True) # reconnect and make sure that the new host is reflected correctly self.cluster.control_connection._reconnect() new_host = self.cluster.get_control_connection_host() self.assertNotEqual(host, new_host) + @notdse + @greaterthanorequalcass40 + def test_control_connection_port_discovery(self): + """ + Test to validate that the correct port is discovered when peersV2 is used (C* 4.0+). + + Unit tests already validate that the port can be picked up (or not) from the query. This validates + it picks up the correct port from a real server and is able to connect. + """ + self.cluster = TestCluster() + + host = self.cluster.get_control_connection_host() + self.assertEqual(host, None) + + self.session = self.cluster.connect() + cc_endpoint = self.cluster.control_connection._connection.endpoint + + host = self.cluster.get_control_connection_host() + self.assertEqual(host.endpoint, cc_endpoint) + self.assertEqual(host.is_up, True) + hosts = self.cluster.metadata.all_hosts() + self.assertEqual(3, len(hosts)) + + for host in hosts: + self.assertEqual(9042, host.broadcast_rpc_port) + self.assertEqual(7000, host.broadcast_port) diff --git a/tests/integration/standard/test_custom_cluster.py b/tests/integration/standard/test_custom_cluster.py index 5ca5c5c..84e0737 100644 --- a/tests/integration/standard/test_custom_cluster.py +++ b/tests/integration/standard/test_custom_cluster.py @@ -1,63 +1,63 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -from cassandra.cluster import Cluster, NoHostAvailable -from tests.integration import use_singledc, get_cluster, remove_cluster, local -from tests.integration.util import wait_until, wait_until_not_raised +from cassandra.cluster import NoHostAvailable +from tests.integration import use_singledc, get_cluster, remove_cluster, local, TestCluster +from tests.util import wait_until, wait_until_not_raised try: import unittest2 as unittest except ImportError: import unittest def setup_module(): use_singledc(start=False) ccm_cluster = get_cluster() ccm_cluster.stop() config_options = {'native_transport_port': 9046} ccm_cluster.set_configuration_options(config_options) # can't use wait_for_binary_proto cause ccm tries on port 9042 ccm_cluster.start(wait_for_binary_proto=False) # wait until all nodes are up - wait_until_not_raised(lambda: Cluster(['127.0.0.1'], port=9046).connect().shutdown(), 1, 10) - wait_until_not_raised(lambda: Cluster(['127.0.0.2'], port=9046).connect().shutdown(), 1, 10) - wait_until_not_raised(lambda: Cluster(['127.0.0.3'], port=9046).connect().shutdown(), 1, 10) + wait_until_not_raised(lambda: TestCluster(contact_points=['127.0.0.1'], port=9046).connect().shutdown(), 1, 20) + wait_until_not_raised(lambda: TestCluster(contact_points=['127.0.0.2'], port=9046).connect().shutdown(), 1, 20) + wait_until_not_raised(lambda: TestCluster(contact_points=['127.0.0.3'], port=9046).connect().shutdown(), 1, 20) def teardown_module(): remove_cluster() class CustomClusterTests(unittest.TestCase): @local def test_connection_honor_cluster_port(self): """ Test that the initial contact point and discovered nodes honor the cluster port on new connection. All hosts should be marked as up and we should be able to execute queries on it. """ - cluster = Cluster() + cluster = TestCluster() with self.assertRaises(NoHostAvailable): cluster.connect() # should fail on port 9042 - cluster = Cluster(port=9046) + cluster = TestCluster(port=9046) session = cluster.connect(wait_for_all_pools=True) wait_until(lambda: len(cluster.metadata.all_hosts()) == 3, 1, 5) for host in cluster.metadata.all_hosts(): self.assertTrue(host.is_up) session.execute("select * from system.local", host=host) diff --git a/tests/integration/standard/test_custom_payload.py b/tests/integration/standard/test_custom_payload.py index c68e9ef..9906a82 100644 --- a/tests/integration/standard/test_custom_payload.py +++ b/tests/integration/standard/test_custom_payload.py @@ -1,170 +1,170 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest import six from cassandra.query import (SimpleStatement, BatchStatement, BatchType) -from cassandra.cluster import Cluster -from tests.integration import use_singledc, PROTOCOL_VERSION, local +from tests.integration import use_singledc, PROTOCOL_VERSION, local, TestCluster + def setup_module(): use_singledc() #These test rely on the custom payload being returned but by default C* #ignores all the payloads. @local class CustomPayloadTests(unittest.TestCase): def setUp(self): if PROTOCOL_VERSION < 4: raise unittest.SkipTest( "Native protocol 4,0+ is required for custom payloads, currently using %r" % (PROTOCOL_VERSION,)) - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + self.cluster = TestCluster() self.session = self.cluster.connect() def tearDown(self): self.cluster.shutdown() def test_custom_query_basic(self): """ Test to validate that custom payloads work with simple queries creates a simple query and ensures that custom payloads are passed to C*. A custom query provider is used with C* so we can validate that same custom payloads are sent back with the results @since 2.6 @jira_ticket PYTHON-280 @expected_result valid custom payloads should be sent and received @test_category queries:custom_payload """ # Create a simple query statement a query = "SELECT * FROM system.local" statement = SimpleStatement(query) # Validate that various types of custom payloads are sent and received okay self.validate_various_custom_payloads(statement=statement) def test_custom_query_batching(self): """ Test to validate that custom payloads work with batch queries creates a batch query and ensures that custom payloads are passed to C*. A custom query provider is used with C* so we can validate that same custom payloads are sent back with the results @since 2.6 @jira_ticket PYTHON-280 @expected_result valid custom payloads should be sent and received @test_category queries:custom_payload """ # Construct Batch Statement batch = BatchStatement(BatchType.LOGGED) for i in range(10): batch.add(SimpleStatement("INSERT INTO test3rf.test (k, v) VALUES (%s, %s)"), (i, i)) # Validate that various types of custom payloads are sent and received okay self.validate_various_custom_payloads(statement=batch) def test_custom_query_prepared(self): """ Test to validate that custom payloads work with prepared queries creates a batch query and ensures that custom payloads are passed to C*. A custom query provider is used with C* so we can validate that same custom payloads are sent back with the results @since 2.6 @jira_ticket PYTHON-280 @expected_result valid custom payloads should be sent and received @test_category queries:custom_payload """ # Construct prepared statement prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) bound = prepared.bind((1, None)) # Validate that various custom payloads are validated correctly self.validate_various_custom_payloads(statement=bound) def validate_various_custom_payloads(self, statement): """ This is a utility method that given a statement will attempt to submit the statement with various custom payloads. It will validate that the custom payloads are sent and received correctly. @param statement The statement to validate the custom queries in conjunction with """ # Simple key value custom_payload = {'test': b'test_return'} self.execute_async_validate_custom_payload(statement=statement, custom_payload=custom_payload) # no key value custom_payload = {'': b''} self.execute_async_validate_custom_payload(statement=statement, custom_payload=custom_payload) # Space value custom_payload = {' ': b' '} self.execute_async_validate_custom_payload(statement=statement, custom_payload=custom_payload) # Long key value pair key_value = "x" * 10 custom_payload = {key_value: six.b(key_value)} self.execute_async_validate_custom_payload(statement=statement, custom_payload=custom_payload) # Max supported value key pairs according C* binary protocol v4 should be 65534 (unsigned short max value) for i in range(65534): custom_payload[str(i)] = six.b('x') self.execute_async_validate_custom_payload(statement=statement, custom_payload=custom_payload) # Add one custom payload to this is too many key value pairs and should fail custom_payload[str(65535)] = six.b('x') with self.assertRaises(ValueError): self.execute_async_validate_custom_payload(statement=statement, custom_payload=custom_payload) def execute_async_validate_custom_payload(self, statement, custom_payload): """ This is just a simple method that submits a statement with a payload, and validates that the custom payload we submitted matches the one that we got back @param statement The statement to execute @param custom_payload The custom payload to submit with """ # Submit the statement with our custom payload. Validate the one # we receive from the server matches response_future = self.session.execute_async(statement, custom_payload=custom_payload) response_future.result() returned_custom_payload = response_future.custom_payload self.assertEqual(custom_payload, returned_custom_payload) diff --git a/tests/integration/standard/test_custom_protocol_handler.py b/tests/integration/standard/test_custom_protocol_handler.py index e76972b..bf54951 100644 --- a/tests/integration/standard/test_custom_protocol_handler.py +++ b/tests/integration/standard/test_custom_protocol_handler.py @@ -1,234 +1,317 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from cassandra.protocol import ProtocolHandler, ResultMessage, QueryMessage, UUIDType, read_int from cassandra.query import tuple_factory, SimpleStatement -from cassandra.cluster import Cluster, ResponseFuture +from cassandra.cluster import (ResponseFuture, ExecutionProfile, EXEC_PROFILE_DEFAULT, + ContinuousPagingOptions, NoHostAvailable) from cassandra import ProtocolVersion, ConsistencyLevel -from tests.integration import use_singledc, PROTOCOL_VERSION, drop_keyspace_shutdown_cluster, \ - greaterthanorequalcass30, execute_with_long_wait_retry +from tests.integration import use_singledc, drop_keyspace_shutdown_cluster, \ + greaterthanorequalcass30, execute_with_long_wait_retry, greaterthanorequaldse51, greaterthanorequalcass3_10, \ + TestCluster, greaterthanorequalcass40, requirecassandra from tests.integration.datatype_utils import update_datatypes, PRIMITIVE_DATATYPES from tests.integration.standard.utils import create_table_with_all_types, get_all_primitive_params from six import binary_type import uuid import mock def setup_module(): use_singledc() update_datatypes() class CustomProtocolHandlerTest(unittest.TestCase): @classmethod def setUpClass(cls): - cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cls.cluster = TestCluster() cls.session = cls.cluster.connect() cls.session.execute("CREATE KEYSPACE custserdes WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}") cls.session.set_keyspace("custserdes") @classmethod def tearDownClass(cls): drop_keyspace_shutdown_cluster("custserdes", cls.session, cls.cluster) def test_custom_raw_uuid_row_results(self): """ Test to validate that custom protocol handlers work with raw row results Connect and validate that the normal protocol handler is used. Re-Connect and validate that the custom protocol handler is used. Re-Connect and validate that the normal protocol handler is used. @since 2.7 @jira_ticket PYTHON-313 @expected_result custom protocol handler is invoked appropriately. @test_category data_types:serialization """ # Ensure that we get normal uuid back first - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=tuple_factory)} + ) session = cluster.connect(keyspace="custserdes") - session.row_factory = tuple_factory result = session.execute("SELECT schema_version FROM system.local") uuid_type = result[0][0] self.assertEqual(type(uuid_type), uuid.UUID) # use our custom protocol handlder - session.client_protocol_handler = CustomTestRawRowType - session.row_factory = tuple_factory result_set = session.execute("SELECT schema_version FROM system.local") raw_value = result_set[0][0] self.assertTrue(isinstance(raw_value, binary_type)) self.assertEqual(len(raw_value), 16) # Ensure that we get normal uuid back when we re-connect session.client_protocol_handler = ProtocolHandler result_set = session.execute("SELECT schema_version FROM system.local") uuid_type = result_set[0][0] self.assertEqual(type(uuid_type), uuid.UUID) cluster.shutdown() def test_custom_raw_row_results_all_types(self): """ Test to validate that custom protocol handlers work with varying types of results Connect, create a table with all sorts of data. Query the data, make the sure the custom results handler is used correctly. @since 2.7 @jira_ticket PYTHON-313 @expected_result custom protocol handler is invoked with various result types @test_category data_types:serialization """ # Connect using a custom protocol handler that tracks the various types the result message is used with. - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=tuple_factory)} + ) session = cluster.connect(keyspace="custserdes") session.client_protocol_handler = CustomProtocolHandlerResultMessageTracked - session.row_factory = tuple_factory colnames = create_table_with_all_types("alltypes", session, 1) columns_string = ", ".join(colnames) # verify data params = get_all_primitive_params(0) results = session.execute("SELECT {0} FROM alltypes WHERE primkey=0".format(columns_string))[0] for expected, actual in zip(params, results): self.assertEqual(actual, expected) # Ensure we have covered the various primitive types self.assertEqual(len(CustomResultMessageTracked.checked_rev_row_set), len(PRIMITIVE_DATATYPES)-1) cluster.shutdown() + @requirecassandra + @greaterthanorequalcass40 + def test_protocol_divergence_v5_fail_by_continuous_paging(self): + """ + Test to validate that V5 and DSE_V1 diverge. ContinuousPagingOptions is not supported by V5 + + @since DSE 2.0b3 GRAPH 1.0b1 + @jira_ticket PYTHON-694 + @expected_result NoHostAvailable will be risen when the continuous_paging_options parameter is set + + @test_category connection + """ + cluster = TestCluster(protocol_version=ProtocolVersion.V5, allow_beta_protocol_version=True) + session = cluster.connect() + + max_pages = 4 + max_pages_per_second = 3 + continuous_paging_options = ContinuousPagingOptions(max_pages=max_pages, + max_pages_per_second=max_pages_per_second) + + future = self._send_query_message(session, timeout=session.default_timeout, + consistency_level=ConsistencyLevel.ONE, + continuous_paging_options=continuous_paging_options) + + # This should raise NoHostAvailable because continuous paging is not supported under ProtocolVersion.DSE_V1 + with self.assertRaises(NoHostAvailable) as context: + future.result() + self.assertIn("Continuous paging may only be used with protocol version ProtocolVersion.DSE_V1 or higher", + str(context.exception)) + + cluster.shutdown() + @greaterthanorequalcass30 def test_protocol_divergence_v4_fail_by_flag_uses_int(self): """ Test to validate that the _PAGE_SIZE_FLAG is not treated correctly in V4 if the flags are written using write_uint instead of write_int @since 3.9 @jira_ticket PYTHON-713 @expected_result the fetch_size=1 parameter will be ignored @test_category connection """ self._protocol_divergence_fail_by_flag_uses_int(ProtocolVersion.V4, uses_int_query_flag=False, int_flag=True) + @requirecassandra + @greaterthanorequalcass40 + def test_protocol_v5_uses_flag_int(self): + """ + Test to validate that the _PAGE_SIZE_FLAG is treated correctly using write_uint for V5 + + @jira_ticket PYTHON-694 + @expected_result the fetch_size=1 parameter will be honored + + @test_category connection + """ + self._protocol_divergence_fail_by_flag_uses_int(ProtocolVersion.V5, uses_int_query_flag=True, beta=True, + int_flag=True) + + @greaterthanorequaldse51 + def test_protocol_dsev1_uses_flag_int(self): + """ + Test to validate that the _PAGE_SIZE_FLAG is treated correctly using write_uint for DSE_V1 + + @jira_ticket PYTHON-694 + @expected_result the fetch_size=1 parameter will be honored + + @test_category connection + """ + self._protocol_divergence_fail_by_flag_uses_int(ProtocolVersion.DSE_V1, uses_int_query_flag=True, + int_flag=True) + + @requirecassandra + @greaterthanorequalcass40 + def test_protocol_divergence_v5_fail_by_flag_uses_int(self): + """ + Test to validate that the _PAGE_SIZE_FLAG is treated correctly using write_uint for V5 + + @jira_ticket PYTHON-694 + @expected_result the fetch_size=1 parameter will be honored + + @test_category connection + """ + self._protocol_divergence_fail_by_flag_uses_int(ProtocolVersion.V5, uses_int_query_flag=False, beta=True, + int_flag=False) + + @greaterthanorequaldse51 + def test_protocol_divergence_dsev1_fail_by_flag_uses_int(self): + """ + Test to validate that the _PAGE_SIZE_FLAG is treated correctly using write_uint for DSE_V1 + + @jira_ticket PYTHON-694 + @expected_result the fetch_size=1 parameter will be honored + + @test_category connection + """ + self._protocol_divergence_fail_by_flag_uses_int(ProtocolVersion.DSE_V1, uses_int_query_flag=False, + int_flag=False) def _send_query_message(self, session, timeout, **kwargs): query = "SELECT * FROM test3rf.test" message = QueryMessage(query=query, **kwargs) future = ResponseFuture(session, message, query=None, timeout=timeout) future.send_request() return future def _protocol_divergence_fail_by_flag_uses_int(self, version, uses_int_query_flag, int_flag = True, beta=False): - cluster = Cluster(protocol_version=version, allow_beta_protocol_version=beta) + cluster = TestCluster(protocol_version=version, allow_beta_protocol_version=beta) session = cluster.connect() query_one = SimpleStatement("INSERT INTO test3rf.test (k, v) VALUES (1, 1)") query_two = SimpleStatement("INSERT INTO test3rf.test (k, v) VALUES (2, 2)") execute_with_long_wait_retry(session, query_one) execute_with_long_wait_retry(session, query_two) with mock.patch('cassandra.protocol.ProtocolVersion.uses_int_query_flags', new=mock.Mock(return_value=int_flag)): future = self._send_query_message(session, 10, consistency_level=ConsistencyLevel.ONE, fetch_size=1) response = future.result() # This means the flag are not handled as they are meant by the server if uses_int=False self.assertEqual(response.has_more_pages, uses_int_query_flag) execute_with_long_wait_retry(session, SimpleStatement("TRUNCATE test3rf.test")) cluster.shutdown() class CustomResultMessageRaw(ResultMessage): """ This is a custom Result Message that is used to return raw results, rather then results which contain objects. """ my_type_codes = ResultMessage.type_codes.copy() my_type_codes[0xc] = UUIDType type_codes = my_type_codes - @classmethod - def recv_results_rows(cls, f, protocol_version, user_type_map, result_metadata): - paging_state, column_metadata, result_metadata_id = cls.recv_results_metadata(f, user_type_map) + def recv_results_rows(self, f, protocol_version, user_type_map, result_metadata): + self.recv_results_metadata(f, user_type_map) + column_metadata = self.column_metadata or result_metadata rowcount = read_int(f) - rows = [cls.recv_row(f, len(column_metadata)) for _ in range(rowcount)] - colnames = [c[2] for c in column_metadata] - coltypes = [c[3] for c in column_metadata] - return paging_state, coltypes, (colnames, rows), result_metadata_id + self.parsed_rows = [self.recv_row(f, len(column_metadata)) for _ in range(rowcount)] + self.column_names = [c[2] for c in column_metadata] + self.column_types = [c[3] for c in column_metadata] class CustomTestRawRowType(ProtocolHandler): """ This is the a custom protocol handler that will substitute the the customResultMesageRowRaw Result message for our own implementation """ my_opcodes = ProtocolHandler.message_types_by_opcode.copy() my_opcodes[CustomResultMessageRaw.opcode] = CustomResultMessageRaw message_types_by_opcode = my_opcodes class CustomResultMessageTracked(ResultMessage): """ This is a custom Result Message that is use to track what primitive types have been processed when it receives results """ my_type_codes = ResultMessage.type_codes.copy() my_type_codes[0xc] = UUIDType type_codes = my_type_codes checked_rev_row_set = set() - @classmethod - def recv_results_rows(cls, f, protocol_version, user_type_map, result_metadata): - paging_state, column_metadata, result_metadata_id = cls.recv_results_metadata(f, user_type_map) + def recv_results_rows(self, f, protocol_version, user_type_map, result_metadata): + self.recv_results_metadata(f, user_type_map) + column_metadata = self.column_metadata or result_metadata rowcount = read_int(f) - rows = [cls.recv_row(f, len(column_metadata)) for _ in range(rowcount)] - colnames = [c[2] for c in column_metadata] - coltypes = [c[3] for c in column_metadata] - cls.checked_rev_row_set.update(coltypes) - parsed_rows = [ + rows = [self.recv_row(f, len(column_metadata)) for _ in range(rowcount)] + self.column_names = [c[2] for c in column_metadata] + self.column_types = [c[3] for c in column_metadata] + self.checked_rev_row_set.update(self.column_types) + self.parsed_rows = [ tuple(ctype.from_binary(val, protocol_version) - for ctype, val in zip(coltypes, row)) + for ctype, val in zip(self.column_types, row)) for row in rows] - return paging_state, coltypes, (colnames, parsed_rows), result_metadata_id class CustomProtocolHandlerResultMessageTracked(ProtocolHandler): """ This is the a custom protocol handler that will substitute the the CustomTestRawRowTypeTracked Result message for our own implementation """ my_opcodes = ProtocolHandler.message_types_by_opcode.copy() my_opcodes[CustomResultMessageTracked.opcode] = CustomResultMessageTracked message_types_by_opcode = my_opcodes - - diff --git a/tests/integration/standard/test_cython_protocol_handlers.py b/tests/integration/standard/test_cython_protocol_handlers.py index 593dcba..4e45553 100644 --- a/tests/integration/standard/test_cython_protocol_handlers.py +++ b/tests/integration/standard/test_cython_protocol_handlers.py @@ -1,258 +1,263 @@ """Test the various Cython-based message deserializers""" # Based on test_custom_protocol_handler.py try: import unittest2 as unittest except ImportError: import unittest from itertools import count -from cassandra.query import tuple_factory -from cassandra.cluster import Cluster, NoHostAvailable +from cassandra.cluster import ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.concurrent import execute_concurrent_with_args -from cassandra.protocol import ProtocolHandler, LazyProtocolHandler, NumpyProtocolHandler from cassandra.cython_deps import HAVE_CYTHON, HAVE_NUMPY +from cassandra.protocol import ProtocolHandler, LazyProtocolHandler, NumpyProtocolHandler +from cassandra.query import tuple_factory from tests import VERIFY_CYTHON -from tests.integration import use_singledc, PROTOCOL_VERSION, notprotocolv1, drop_keyspace_shutdown_cluster, BasicSharedKeyspaceUnitTestCase, execute_with_retry_tolerant, greaterthancass21 +from tests.integration import use_singledc, notprotocolv1, \ + drop_keyspace_shutdown_cluster, BasicSharedKeyspaceUnitTestCase, greaterthancass21, TestCluster from tests.integration.datatype_utils import update_datatypes from tests.integration.standard.utils import ( create_table_with_all_types, get_all_primitive_params, get_primitive_datatypes) - from tests.unit.cython.utils import cythontest, numpytest def setup_module(): use_singledc() update_datatypes() class CythonProtocolHandlerTest(unittest.TestCase): N_ITEMS = 10 @classmethod def setUpClass(cls): - cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cls.cluster = TestCluster() cls.session = cls.cluster.connect() cls.session.execute("CREATE KEYSPACE testspace WITH replication = " "{ 'class' : 'SimpleStrategy', 'replication_factor': '1'}") cls.session.set_keyspace("testspace") cls.colnames = create_table_with_all_types("test_table", cls.session, cls.N_ITEMS) @classmethod def tearDownClass(cls): drop_keyspace_shutdown_cluster("testspace", cls.session, cls.cluster) @cythontest def test_cython_parser(self): """ Test Cython-based parser that returns a list of tuples """ verify_iterator_data(self.assertEqual, get_data(ProtocolHandler)) @cythontest def test_cython_lazy_parser(self): """ Test Cython-based parser that returns an iterator of tuples """ verify_iterator_data(self.assertEqual, get_data(LazyProtocolHandler)) - @notprotocolv1 @numpytest def test_cython_lazy_results_paged(self): """ Test Cython-based parser that returns an iterator, over multiple pages """ # arrays = { 'a': arr1, 'b': arr2, ... } - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=tuple_factory)} + ) session = cluster.connect(keyspace="testspace") - session.row_factory = tuple_factory session.client_protocol_handler = LazyProtocolHandler session.default_fetch_size = 2 self.assertLess(session.default_fetch_size, self.N_ITEMS) results = session.execute("SELECT * FROM test_table") self.assertTrue(results.has_more_pages) self.assertEqual(verify_iterator_data(self.assertEqual, results), self.N_ITEMS) # make sure we see all rows cluster.shutdown() @notprotocolv1 @numpytest def test_numpy_parser(self): """ Test Numpy-based parser that returns a NumPy array """ # arrays = { 'a': arr1, 'b': arr2, ... } result = get_data(NumpyProtocolHandler) self.assertFalse(result.has_more_pages) self._verify_numpy_page(result[0]) @notprotocolv1 @numpytest def test_numpy_results_paged(self): """ Test Numpy-based parser that returns a NumPy array """ # arrays = { 'a': arr1, 'b': arr2, ... } - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=tuple_factory)} + ) session = cluster.connect(keyspace="testspace") - session.row_factory = tuple_factory session.client_protocol_handler = NumpyProtocolHandler session.default_fetch_size = 2 expected_pages = (self.N_ITEMS + session.default_fetch_size - 1) // session.default_fetch_size self.assertLess(session.default_fetch_size, self.N_ITEMS) results = session.execute("SELECT * FROM test_table") self.assertTrue(results.has_more_pages) for count, page in enumerate(results, 1): self.assertIsInstance(page, dict) for colname, arr in page.items(): if count <= expected_pages: self.assertGreater(len(arr), 0, "page count: %d" % (count,)) self.assertLessEqual(len(arr), session.default_fetch_size) else: # we get one extra item out of this iteration because of the way NumpyParser returns results # The last page is returned as a dict with zero-length arrays self.assertEqual(len(arr), 0) self.assertEqual(self._verify_numpy_page(page), len(arr)) self.assertEqual(count, expected_pages + 1) # see note about extra 'page' above cluster.shutdown() @numpytest def test_cython_numpy_are_installed_valid(self): """ Test to validate that cython and numpy are installed correctly @since 3.3.0 @jira_ticket PYTHON-543 @expected_result Cython and Numpy should be present @test_category configuration """ if VERIFY_CYTHON: self.assertTrue(HAVE_CYTHON) self.assertTrue(HAVE_NUMPY) def _verify_numpy_page(self, page): colnames = self.colnames datatypes = get_primitive_datatypes() for colname, datatype in zip(colnames, datatypes): arr = page[colname] self.match_dtype(datatype, arr.dtype) return verify_iterator_data(self.assertEqual, arrays_to_list_of_tuples(page, colnames)) def match_dtype(self, datatype, dtype): """Match a string cqltype (e.g. 'int' or 'blob') with a numpy dtype""" if datatype == 'smallint': self.match_dtype_props(dtype, 'i', 2) elif datatype == 'int': self.match_dtype_props(dtype, 'i', 4) elif datatype in ('bigint', 'counter'): self.match_dtype_props(dtype, 'i', 8) elif datatype == 'float': self.match_dtype_props(dtype, 'f', 4) elif datatype == 'double': self.match_dtype_props(dtype, 'f', 8) else: self.assertEqual(dtype.kind, 'O', msg=(dtype, datatype)) def match_dtype_props(self, dtype, kind, size, signed=None): self.assertEqual(dtype.kind, kind, msg=dtype) self.assertEqual(dtype.itemsize, size, msg=dtype) def arrays_to_list_of_tuples(arrays, colnames): """Convert a dict of arrays (as given by the numpy protocol handler) to a list of tuples""" first_array = arrays[colnames[0]] return [tuple(arrays[colname][i] for colname in colnames) for i in range(len(first_array))] def get_data(protocol_handler): """ Get data from the test table. """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=tuple_factory)} + ) session = cluster.connect(keyspace="testspace") # use our custom protocol handler session.client_protocol_handler = protocol_handler - session.row_factory = tuple_factory results = session.execute("SELECT * FROM test_table") cluster.shutdown() return results def verify_iterator_data(assertEqual, results): """ Check the result of get_data() when this is a list or iterator of tuples """ count = 0 for count, result in enumerate(results, 1): params = get_all_primitive_params(result[0]) assertEqual(len(params), len(result), msg="Not the right number of columns?") for expected, actual in zip(params, result): assertEqual(actual, expected) return count class NumpyNullTest(BasicSharedKeyspaceUnitTestCase): + @classmethod + def setUpClass(cls): + cls.common_setup(1, execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=tuple_factory)}) + @numpytest @greaterthancass21 def test_null_types(self): """ Test to validate that the numpy protocol handler can deal with null values. @since 3.3.0 - updated 3.6.0: now numeric types used masked array @jira_ticket PYTHON-550 @expected_result Numpy can handle non mapped types' null values. @test_category data_types:serialization """ s = self.session - s.row_factory = tuple_factory s.client_protocol_handler = NumpyProtocolHandler table = "%s.%s" % (self.keyspace_name, self.function_table_name) create_table_with_all_types(table, s, 10) begin_unset = max(s.execute('select primkey from %s' % (table,))[0]['primkey']) + 1 keys_null = range(begin_unset, begin_unset + 10) # scatter some emptry rows in here insert = "insert into %s (primkey) values (%%s)" % (table,) execute_concurrent_with_args(s, insert, ((k,) for k in keys_null)) result = s.execute("select * from %s" % (table,))[0] from numpy.ma import masked, MaskedArray result_keys = result.pop('primkey') mapped_index = [v[1] for v in sorted(zip(result_keys, count()))] had_masked = had_none = False for col_array in result.values(): # these have to be different branches (as opposed to comparing against an 'unset value') # because None and `masked` have different identity and equals semantics if isinstance(col_array, MaskedArray): had_masked = True [self.assertIsNot(col_array[i], masked) for i in mapped_index[:begin_unset]] [self.assertIs(col_array[i], masked) for i in mapped_index[begin_unset:]] else: had_none = True [self.assertIsNotNone(col_array[i]) for i in mapped_index[:begin_unset]] [self.assertIsNone(col_array[i]) for i in mapped_index[begin_unset:]] self.assertTrue(had_masked) self.assertTrue(had_none) diff --git a/tests/integration/standard/test_dse.py b/tests/integration/standard/test_dse.py index a8a3d64..1b9b5be 100644 --- a/tests/integration/standard/test_dse.py +++ b/tests/integration/standard/test_dse.py @@ -1,98 +1,95 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from packaging.version import Version -from cassandra.cluster import Cluster from tests import notwindows from tests.unit.cython.utils import notcython from tests.integration import (execute_until_pass, - execute_with_long_wait_retry, use_cluster) + execute_with_long_wait_retry, use_cluster, TestCluster) try: import unittest2 as unittest except ImportError: import unittest # noqa CCM_IS_DSE = (os.environ.get('CCM_IS_DSE', None) == 'true') @unittest.skipIf(os.environ.get('CCM_ARGS', None), 'environment has custom CCM_ARGS; skipping') @notwindows @notcython # no need to double up on this test; also __default__ setting doesn't work class DseCCMClusterTest(unittest.TestCase): """ This class can be executed setting the DSE_VERSION variable, for example: DSE_VERSION=5.1.4 python2.7 -m nose tests/integration/standard/test_dse.py If CASSANDRA_VERSION is set instead, it will be converted to the corresponding DSE_VERSION """ def test_dse_5x(self): self._test_basic(Version('5.1.10')) def test_dse_60(self): self._test_basic(Version('6.0.2')) @unittest.skipUnless(CCM_IS_DSE, 'DSE version unavailable') def test_dse_67(self): self._test_basic(Version('6.7.0')) def _test_basic(self, dse_version): """ Test basic connection and usage """ cluster_name = '{}-{}'.format( self.__class__.__name__, dse_version.base_version.replace('.', '_') ) - use_cluster(cluster_name=cluster_name, nodes=[3], - dse_cluster=True, dse_options={}, dse_version=dse_version) + use_cluster(cluster_name=cluster_name, nodes=[3], dse_options={}) - cluster = Cluster( - allow_beta_protocol_version=(dse_version >= Version('6.7.0'))) + cluster = TestCluster() session = cluster.connect() result = execute_until_pass( session, """ CREATE KEYSPACE clustertests WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} """) self.assertFalse(result) result = execute_with_long_wait_retry( session, """ CREATE TABLE clustertests.cf0 ( a text, b text, c text, PRIMARY KEY (a, b) ) """) self.assertFalse(result) result = session.execute( """ INSERT INTO clustertests.cf0 (a, b, c) VALUES ('a', 'b', 'c') """) self.assertFalse(result) result = session.execute("SELECT * FROM clustertests.cf0") self.assertEqual([('a', 'b', 'c')], result) execute_with_long_wait_retry(session, "DROP KEYSPACE clustertests") cluster.shutdown() diff --git a/tests/integration/standard/test_metadata.py b/tests/integration/standard/test_metadata.py index 4fb7ebf..bd556f3 100644 --- a/tests/integration/standard/test_metadata.py +++ b/tests/integration/standard/test_metadata.py @@ -1,2481 +1,2529 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from collections import defaultdict import difflib import logging import six import sys import time import os from packaging.version import Version from mock import Mock, patch from cassandra import AlreadyExists, SignatureDescriptor, UserFunctionDescriptor, UserAggregateDescriptor -from cassandra.cluster import Cluster from cassandra.encoder import Encoder from cassandra.metadata import (IndexMetadata, Token, murmur3, Function, Aggregate, protect_name, protect_names, RegisteredTableExtension, _RegisteredExtensionType, get_schema_parser, group_keys_by_replica, NO_VALID_REPLICA) +from cassandra.util import SortedSet from tests.integration import (get_cluster, use_singledc, PROTOCOL_VERSION, execute_until_pass, BasicSegregatedKeyspaceUnitTestCase, BasicSharedKeyspaceUnitTestCase, BasicExistingKeyspaceUnitTestCase, drop_keyspace_shutdown_cluster, CASSANDRA_VERSION, - get_supported_protocol_versions, greaterthanorequalcass30, lessthancass30, local, - greaterthancass20, greaterthanorequalcass40) - -from tests.integration import greaterthancass21 + greaterthanorequaldse51, greaterthanorequalcass30, lessthancass30, local, + get_supported_protocol_versions, greaterthancass20, + greaterthancass21, assert_startswith, greaterthanorequalcass40, + greaterthanorequaldse67, lessthancass40, + TestCluster, DSE_VERSION) log = logging.getLogger(__name__) def setup_module(): use_singledc() -class HostMetatDataTests(BasicExistingKeyspaceUnitTestCase): +class HostMetaDataTests(BasicExistingKeyspaceUnitTestCase): @local - def test_broadcast_listen_address(self): + def test_host_addresses(self): """ - Check to ensure that the broadcast, rpc_address, listen adresss and host are is populated correctly + Check to ensure that the broadcast_address, broadcast_rpc_address, + listen adresss, ports and host are is populated correctly. @since 3.3 @jira_ticket PYTHON-332 @expected_result They are populated for C*> 2.1.6, 2.2.0 @test_category metadata """ # All nodes should have the broadcast_address, rpc_address and host_id set for host in self.cluster.metadata.all_hosts(): self.assertIsNotNone(host.broadcast_address) self.assertIsNotNone(host.broadcast_rpc_address) self.assertIsNotNone(host.host_id) + + if not DSE_VERSION and CASSANDRA_VERSION >= Version('4-a'): + self.assertIsNotNone(host.broadcast_port) + self.assertIsNotNone(host.broadcast_rpc_port) + con = self.cluster.control_connection.get_connections()[0] local_host = con.host # The control connection node should have the listen address set. listen_addrs = [host.listen_address for host in self.cluster.metadata.all_hosts()] self.assertTrue(local_host in listen_addrs) # The control connection node should have the broadcast_rpc_address set. rpc_addrs = [host.broadcast_rpc_address for host in self.cluster.metadata.all_hosts()] self.assertTrue(local_host in rpc_addrs) @unittest.skipUnless( - os.getenv('MAPPED_CASSANDRA_VERSION', None) is None, + os.getenv('MAPPED_CASSANDRA_VERSION', None) is not None, "Don't check the host version for test-dse") def test_host_release_version(self): """ Checks the hosts release version and validates that it is equal to the Cassandra version we are using in our test harness. @since 3.3 @jira_ticket PYTHON-301 @expected_result host.release version should match our specified Cassandra version. @test_category metadata """ for host in self.cluster.metadata.all_hosts(): - self.assertTrue(host.release_version.startswith(CASSANDRA_VERSION.base_version)) + assert_startswith(host.release_version, CASSANDRA_VERSION.base_version) + @local class MetaDataRemovalTest(unittest.TestCase): def setUp(self): - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, contact_points=['127.0.0.1', '127.0.0.2', '127.0.0.3', '126.0.0.186']) + self.cluster = TestCluster(contact_points=['127.0.0.1', '127.0.0.2', '127.0.0.3', '126.0.0.186']) self.cluster.connect() def tearDown(self): self.cluster.shutdown() def test_bad_contact_point(self): """ Checks to ensure that hosts that are not resolvable are excluded from the contact point list. @since 3.6 @jira_ticket PYTHON-549 @expected_result Invalid hosts on the contact list should be excluded @test_category metadata """ self.assertEqual(len(self.cluster.metadata.all_hosts()), 3) class SchemaMetadataTests(BasicSegregatedKeyspaceUnitTestCase): def test_schema_metadata_disable(self): """ Checks to ensure that schema metadata_enabled, and token_metadata_enabled flags work correctly. @since 3.3 @jira_ticket PYTHON-327 @expected_result schema metadata will not be populated when schema_metadata_enabled is fause token_metadata will be missing when token_metadata is set to false @test_category metadata """ # Validate metadata is missing where appropriate - no_schema = Cluster(schema_metadata_enabled=False) + no_schema = TestCluster(schema_metadata_enabled=False) no_schema_session = no_schema.connect() self.assertEqual(len(no_schema.metadata.keyspaces), 0) self.assertEqual(no_schema.metadata.export_schema_as_string(), '') - no_token = Cluster(token_metadata_enabled=False) + no_token = TestCluster(token_metadata_enabled=False) no_token_session = no_token.connect() self.assertEqual(len(no_token.metadata.token_map.token_to_host_owner), 0) # Do a simple query to ensure queries are working query = "SELECT * FROM system.local" no_schema_rs = no_schema_session.execute(query) no_token_rs = no_token_session.execute(query) self.assertIsNotNone(no_schema_rs[0]) self.assertIsNotNone(no_token_rs[0]) no_schema.shutdown() no_token.shutdown() def make_create_statement(self, partition_cols, clustering_cols=None, other_cols=None): clustering_cols = clustering_cols or [] other_cols = other_cols or [] statement = "CREATE TABLE %s.%s (" % (self.keyspace_name, self.function_table_name) if len(partition_cols) == 1 and not clustering_cols: statement += "%s text PRIMARY KEY, " % protect_name(partition_cols[0]) else: statement += ", ".join("%s text" % protect_name(col) for col in partition_cols) statement += ", " statement += ", ".join("%s text" % protect_name(col) for col in clustering_cols + other_cols) if len(partition_cols) != 1 or clustering_cols: statement += ", PRIMARY KEY (" if len(partition_cols) > 1: statement += "(" + ", ".join(protect_names(partition_cols)) + ")" else: statement += protect_name(partition_cols[0]) if clustering_cols: statement += ", " statement += ", ".join(protect_names(clustering_cols)) statement += ")" statement += ")" return statement def check_create_statement(self, tablemeta, original): recreate = tablemeta.as_cql_query(formatted=False) self.assertEqual(original, recreate[:len(original)]) execute_until_pass(self.session, "DROP TABLE {0}.{1}".format(self.keyspace_name, self.function_table_name)) execute_until_pass(self.session, recreate) # create the table again, but with formatting enabled execute_until_pass(self.session, "DROP TABLE {0}.{1}".format(self.keyspace_name, self.function_table_name)) recreate = tablemeta.as_cql_query(formatted=True) execute_until_pass(self.session, recreate) def get_table_metadata(self): self.cluster.refresh_table_metadata(self.keyspace_name, self.function_table_name) return self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name] def test_basic_table_meta_properties(self): create_statement = self.make_create_statement(["a"], [], ["b", "c"]) self.session.execute(create_statement) self.cluster.refresh_schema_metadata() meta = self.cluster.metadata self.assertNotEqual(meta.cluster_name, None) self.assertTrue(self.keyspace_name in meta.keyspaces) ksmeta = meta.keyspaces[self.keyspace_name] self.assertEqual(ksmeta.name, self.keyspace_name) self.assertTrue(ksmeta.durable_writes) self.assertEqual(ksmeta.replication_strategy.name, 'SimpleStrategy') self.assertEqual(ksmeta.replication_strategy.replication_factor, 1) self.assertTrue(self.function_table_name in ksmeta.tables) tablemeta = ksmeta.tables[self.function_table_name] self.assertEqual(tablemeta.keyspace_name, ksmeta.name) self.assertEqual(tablemeta.name, self.function_table_name) self.assertEqual(tablemeta.name, self.function_table_name) self.assertEqual([u'a'], [c.name for c in tablemeta.partition_key]) self.assertEqual([], tablemeta.clustering_key) self.assertEqual([u'a', u'b', u'c'], sorted(tablemeta.columns.keys())) cc = self.cluster.control_connection._connection - parser = get_schema_parser(cc, CASSANDRA_VERSION.base_version, 1) + parser = get_schema_parser( + cc, + self.cluster.metadata.get_host(cc.host).release_version, + self.cluster.metadata.get_host(cc.host).dse_version, + 1 + ) for option in tablemeta.options: self.assertIn(option, parser.recognized_table_options) self.check_create_statement(tablemeta, create_statement) def test_compound_primary_keys(self): create_statement = self.make_create_statement(["a"], ["b"], ["c"]) create_statement += " WITH CLUSTERING ORDER BY (b ASC)" self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.assertEqual([u'a'], [c.name for c in tablemeta.partition_key]) self.assertEqual([u'b'], [c.name for c in tablemeta.clustering_key]) self.assertEqual([u'a', u'b', u'c'], sorted(tablemeta.columns.keys())) self.check_create_statement(tablemeta, create_statement) def test_compound_primary_keys_protected(self): create_statement = self.make_create_statement(["Aa"], ["Bb"], ["Cc"]) create_statement += ' WITH CLUSTERING ORDER BY ("Bb" ASC)' self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.assertEqual([u'Aa'], [c.name for c in tablemeta.partition_key]) self.assertEqual([u'Bb'], [c.name for c in tablemeta.clustering_key]) self.assertEqual([u'Aa', u'Bb', u'Cc'], sorted(tablemeta.columns.keys())) self.check_create_statement(tablemeta, create_statement) def test_compound_primary_keys_more_columns(self): create_statement = self.make_create_statement(["a"], ["b", "c"], ["d", "e", "f"]) create_statement += " WITH CLUSTERING ORDER BY (b ASC, c ASC)" self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.assertEqual([u'a'], [c.name for c in tablemeta.partition_key]) self.assertEqual([u'b', u'c'], [c.name for c in tablemeta.clustering_key]) self.assertEqual( [u'a', u'b', u'c', u'd', u'e', u'f'], sorted(tablemeta.columns.keys())) self.check_create_statement(tablemeta, create_statement) def test_composite_primary_key(self): create_statement = self.make_create_statement(["a", "b"], [], ["c"]) self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.assertEqual([u'a', u'b'], [c.name for c in tablemeta.partition_key]) self.assertEqual([], tablemeta.clustering_key) self.assertEqual([u'a', u'b', u'c'], sorted(tablemeta.columns.keys())) self.check_create_statement(tablemeta, create_statement) def test_composite_in_compound_primary_key(self): create_statement = self.make_create_statement(["a", "b"], ["c"], ["d", "e"]) create_statement += " WITH CLUSTERING ORDER BY (c ASC)" self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.assertEqual([u'a', u'b'], [c.name for c in tablemeta.partition_key]) self.assertEqual([u'c'], [c.name for c in tablemeta.clustering_key]) self.assertEqual([u'a', u'b', u'c', u'd', u'e'], sorted(tablemeta.columns.keys())) self.check_create_statement(tablemeta, create_statement) def test_compound_primary_keys_compact(self): create_statement = self.make_create_statement(["a"], ["b"], ["c"]) create_statement += " WITH CLUSTERING ORDER BY (b ASC)" self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.assertEqual([u'a'], [c.name for c in tablemeta.partition_key]) self.assertEqual([u'b'], [c.name for c in tablemeta.clustering_key]) self.assertEqual([u'a', u'b', u'c'], sorted(tablemeta.columns.keys())) self.check_create_statement(tablemeta, create_statement) def test_cluster_column_ordering_reversed_metadata(self): """ Simple test to ensure that the metatdata associated with cluster ordering is surfaced is surfaced correctly. Creates a table with a few clustering keys. Then checks the clustering order associated with clustering columns and ensure it's set correctly. @since 3.0.0 @jira_ticket PYTHON-402 @expected_result is_reversed is set on DESC order, and is False on ASC @test_category metadata """ create_statement = self.make_create_statement(["a"], ["b", "c"], ["d"]) create_statement += " WITH CLUSTERING ORDER BY (b ASC, c DESC)" self.session.execute(create_statement) tablemeta = self.get_table_metadata() b_column = tablemeta.columns['b'] self.assertFalse(b_column.is_reversed) c_column = tablemeta.columns['c'] self.assertTrue(c_column.is_reversed) def test_compound_primary_keys_more_columns_compact(self): create_statement = self.make_create_statement(["a"], ["b", "c"], ["d"]) create_statement += " WITH CLUSTERING ORDER BY (b ASC, c ASC)" self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.assertEqual([u'a'], [c.name for c in tablemeta.partition_key]) self.assertEqual([u'b', u'c'], [c.name for c in tablemeta.clustering_key]) self.assertEqual([u'a', u'b', u'c', u'd'], sorted(tablemeta.columns.keys())) self.check_create_statement(tablemeta, create_statement) def test_composite_primary_key_compact(self): create_statement = self.make_create_statement(["a", "b"], [], ["c"]) self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.assertEqual([u'a', u'b'], [c.name for c in tablemeta.partition_key]) self.assertEqual([], tablemeta.clustering_key) self.assertEqual([u'a', u'b', u'c'], sorted(tablemeta.columns.keys())) self.check_create_statement(tablemeta, create_statement) def test_composite_in_compound_primary_key_compact(self): create_statement = self.make_create_statement(["a", "b"], ["c"], ["d"]) create_statement += " WITH CLUSTERING ORDER BY (c ASC)" self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.assertEqual([u'a', u'b'], [c.name for c in tablemeta.partition_key]) self.assertEqual([u'c'], [c.name for c in tablemeta.clustering_key]) self.assertEqual([u'a', u'b', u'c', u'd'], sorted(tablemeta.columns.keys())) self.check_create_statement(tablemeta, create_statement) @lessthancass30 def test_cql_compatibility(self): # having more than one non-PK column is okay if there aren't any # clustering columns create_statement = self.make_create_statement(["a"], [], ["b", "c", "d"]) self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.assertEqual([u'a'], [c.name for c in tablemeta.partition_key]) self.assertEqual([], tablemeta.clustering_key) self.assertEqual([u'a', u'b', u'c', u'd'], sorted(tablemeta.columns.keys())) self.assertTrue(tablemeta.is_cql_compatible) # It will be cql compatible after CASSANDRA-10857 # since compact storage is being dropped tablemeta.clustering_key = ["foo", "bar"] tablemeta.columns["foo"] = None tablemeta.columns["bar"] = None self.assertTrue(tablemeta.is_cql_compatible) def test_compound_primary_keys_ordering(self): create_statement = self.make_create_statement(["a"], ["b"], ["c"]) create_statement += " WITH CLUSTERING ORDER BY (b DESC)" self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.check_create_statement(tablemeta, create_statement) def test_compound_primary_keys_more_columns_ordering(self): create_statement = self.make_create_statement(["a"], ["b", "c"], ["d", "e", "f"]) create_statement += " WITH CLUSTERING ORDER BY (b DESC, c ASC)" self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.check_create_statement(tablemeta, create_statement) def test_composite_in_compound_primary_key_ordering(self): create_statement = self.make_create_statement(["a", "b"], ["c"], ["d", "e"]) create_statement += " WITH CLUSTERING ORDER BY (c DESC)" self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.check_create_statement(tablemeta, create_statement) + @lessthancass40 def test_compact_storage(self): create_statement = self.make_create_statement(["a"], [], ["b"]) create_statement += " WITH COMPACT STORAGE" self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.check_create_statement(tablemeta, create_statement) + @lessthancass40 def test_dense_compact_storage(self): create_statement = self.make_create_statement(["a"], ["b"], ["c"]) create_statement += " WITH COMPACT STORAGE" self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.check_create_statement(tablemeta, create_statement) def test_counter(self): create_statement = ( "CREATE TABLE {keyspace}.{table} (" "key text PRIMARY KEY, a1 counter)" ).format(keyspace=self.keyspace_name, table=self.function_table_name) self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.check_create_statement(tablemeta, create_statement) + @lessthancass40 def test_counter_with_compact_storage(self): """ PYTHON-1100 """ create_statement = ( "CREATE TABLE {keyspace}.{table} (" "key text PRIMARY KEY, a1 counter) WITH COMPACT STORAGE" ).format(keyspace=self.keyspace_name, table=self.function_table_name) self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.check_create_statement(tablemeta, create_statement) + @lessthancass40 def test_counter_with_dense_compact_storage(self): create_statement = ( "CREATE TABLE {keyspace}.{table} (" "key text, c1 text, a1 counter, PRIMARY KEY (key, c1)) WITH COMPACT STORAGE" ).format(keyspace=self.keyspace_name, table=self.function_table_name) self.session.execute(create_statement) tablemeta = self.get_table_metadata() self.check_create_statement(tablemeta, create_statement) def test_indexes(self): create_statement = self.make_create_statement(["a"], ["b", "c"], ["d", "e", "f"]) create_statement += " WITH CLUSTERING ORDER BY (b ASC, c ASC)" execute_until_pass(self.session, create_statement) d_index = "CREATE INDEX d_index ON %s.%s (d)" % (self.keyspace_name, self.function_table_name) e_index = "CREATE INDEX e_index ON %s.%s (e)" % (self.keyspace_name, self.function_table_name) execute_until_pass(self.session, d_index) execute_until_pass(self.session, e_index) tablemeta = self.get_table_metadata() statements = tablemeta.export_as_string().strip() statements = [s.strip() for s in statements.split(';')] statements = list(filter(bool, statements)) self.assertEqual(3, len(statements)) self.assertIn(d_index, statements) self.assertIn(e_index, statements) # make sure indexes are included in KeyspaceMetadata.export_as_string() ksmeta = self.cluster.metadata.keyspaces[self.keyspace_name] statement = ksmeta.export_as_string() self.assertIn('CREATE INDEX d_index', statement) self.assertIn('CREATE INDEX e_index', statement) @greaterthancass21 def test_collection_indexes(self): self.session.execute("CREATE TABLE %s.%s (a int PRIMARY KEY, b map)" % (self.keyspace_name, self.function_table_name)) self.session.execute("CREATE INDEX index1 ON %s.%s (keys(b))" % (self.keyspace_name, self.function_table_name)) tablemeta = self.get_table_metadata() self.assertIn('(keys(b))', tablemeta.export_as_string()) self.session.execute("DROP INDEX %s.index1" % (self.keyspace_name,)) self.session.execute("CREATE INDEX index2 ON %s.%s (b)" % (self.keyspace_name, self.function_table_name)) tablemeta = self.get_table_metadata() target = ' (b)' if CASSANDRA_VERSION < Version("3.0") else 'values(b))' # explicit values in C* 3+ self.assertIn(target, tablemeta.export_as_string()) # test full indexes on frozen collections, if available if CASSANDRA_VERSION >= Version("2.1.3"): self.session.execute("DROP TABLE %s.%s" % (self.keyspace_name, self.function_table_name)) self.session.execute("CREATE TABLE %s.%s (a int PRIMARY KEY, b frozen>)" % (self.keyspace_name, self.function_table_name)) self.session.execute("CREATE INDEX index3 ON %s.%s (full(b))" % (self.keyspace_name, self.function_table_name)) tablemeta = self.get_table_metadata() self.assertIn('(full(b))', tablemeta.export_as_string()) def test_compression_disabled(self): create_statement = self.make_create_statement(["a"], ["b"], ["c"]) create_statement += " WITH compression = {}" self.session.execute(create_statement) tablemeta = self.get_table_metadata() expected = "compression = {}" if CASSANDRA_VERSION < Version("3.0") else "compression = {'enabled': 'false'}" self.assertIn(expected, tablemeta.export_as_string()) def test_non_size_tiered_compaction(self): """ test options for non-size-tiered compaction strategy Creates a table with LeveledCompactionStrategy, specifying one non-default option. Verifies that the option is present in generated CQL, and that other legacy table parameters (min_threshold, max_threshold) are not included. @since 2.6.0 @jira_ticket PYTHON-352 @expected_result the options map for LeveledCompactionStrategy does not contain min_threshold, max_threshold @test_category metadata """ create_statement = self.make_create_statement(["a"], [], ["b", "c"]) create_statement += "WITH COMPACTION = {'class': 'LeveledCompactionStrategy', 'tombstone_threshold': '0.3'}" self.session.execute(create_statement) table_meta = self.get_table_metadata() cql = table_meta.export_as_string() self.assertIn("'tombstone_threshold': '0.3'", cql) self.assertIn("LeveledCompactionStrategy", cql) # formerly legacy options; reintroduced in 4.0 - if CASSANDRA_VERSION < Version('4.0'): + if CASSANDRA_VERSION < Version('4.0-a'): self.assertNotIn("min_threshold", cql) self.assertNotIn("max_threshold", cql) def test_refresh_schema_metadata(self): """ test for synchronously refreshing all cluster metadata test_refresh_schema_metadata tests all cluster metadata is refreshed when calling refresh_schema_metadata(). It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema change push events. It then alters the cluster, creating a new keyspace, using the first cluster object, and verifies that the cluster metadata has not changed in the second cluster object. It then calls refresh_schema_metadata() and verifies that the cluster metadata is updated in the second cluster object. Similarly, it then proceeds to altering keyspace, table, UDT, UDF, and UDA metadata and subsequently verfies that these metadata is updated when refresh_schema_metadata() is called. @since 2.6.0 @jira_ticket PYTHON-291 @expected_result Cluster, keyspace, table, UDT, UDF, and UDA metadata should be refreshed when refresh_schema_metadata() is called. @test_category metadata """ - - cluster2 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=-1) + cluster2 = TestCluster(schema_event_refresh_window=-1) cluster2.connect() self.assertNotIn("new_keyspace", cluster2.metadata.keyspaces) # Cluster metadata modification self.session.execute("CREATE KEYSPACE new_keyspace WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}") self.assertNotIn("new_keyspace", cluster2.metadata.keyspaces) cluster2.refresh_schema_metadata() self.assertIn("new_keyspace", cluster2.metadata.keyspaces) # Keyspace metadata modification self.session.execute("ALTER KEYSPACE {0} WITH durable_writes = false".format(self.keyspace_name)) self.assertTrue(cluster2.metadata.keyspaces[self.keyspace_name].durable_writes) cluster2.refresh_schema_metadata() self.assertFalse(cluster2.metadata.keyspaces[self.keyspace_name].durable_writes) # Table metadata modification table_name = "test" self.session.execute("CREATE TABLE {0}.{1} (a int PRIMARY KEY, b text)".format(self.keyspace_name, table_name)) cluster2.refresh_schema_metadata() self.session.execute("ALTER TABLE {0}.{1} ADD c double".format(self.keyspace_name, table_name)) self.assertNotIn("c", cluster2.metadata.keyspaces[self.keyspace_name].tables[table_name].columns) cluster2.refresh_schema_metadata() self.assertIn("c", cluster2.metadata.keyspaces[self.keyspace_name].tables[table_name].columns) if PROTOCOL_VERSION >= 3: # UDT metadata modification self.session.execute("CREATE TYPE {0}.user (age int, name text)".format(self.keyspace_name)) self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].user_types, {}) cluster2.refresh_schema_metadata() self.assertIn("user", cluster2.metadata.keyspaces[self.keyspace_name].user_types) if PROTOCOL_VERSION >= 4: # UDF metadata modification self.session.execute("""CREATE FUNCTION {0}.sum_int(key int, val int) RETURNS NULL ON NULL INPUT RETURNS int - LANGUAGE javascript AS 'key + val';""".format(self.keyspace_name)) + LANGUAGE java AS 'return key+val;';""".format(self.keyspace_name)) self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].functions, {}) cluster2.refresh_schema_metadata() self.assertIn("sum_int(int,int)", cluster2.metadata.keyspaces[self.keyspace_name].functions) # UDA metadata modification self.session.execute("""CREATE AGGREGATE {0}.sum_agg(int) SFUNC sum_int STYPE int INITCOND 0""" .format(self.keyspace_name)) self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].aggregates, {}) cluster2.refresh_schema_metadata() self.assertIn("sum_agg(int)", cluster2.metadata.keyspaces[self.keyspace_name].aggregates) # Cluster metadata modification self.session.execute("DROP KEYSPACE new_keyspace") self.assertIn("new_keyspace", cluster2.metadata.keyspaces) cluster2.refresh_schema_metadata() self.assertNotIn("new_keyspace", cluster2.metadata.keyspaces) cluster2.shutdown() def test_refresh_keyspace_metadata(self): """ test for synchronously refreshing keyspace metadata test_refresh_keyspace_metadata tests that keyspace metadata is refreshed when calling refresh_keyspace_metadata(). It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema change push events. It then alters the keyspace, disabling durable_writes, using the first cluster object, and verifies that the keyspace metadata has not changed in the second cluster object. Finally, it calls refresh_keyspace_metadata() and verifies that the keyspace metadata is updated in the second cluster object. @since 2.6.0 @jira_ticket PYTHON-291 @expected_result Keyspace metadata should be refreshed when refresh_keyspace_metadata() is called. @test_category metadata """ - cluster2 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=-1) + cluster2 = TestCluster(schema_event_refresh_window=-1) cluster2.connect() self.assertTrue(cluster2.metadata.keyspaces[self.keyspace_name].durable_writes) self.session.execute("ALTER KEYSPACE {0} WITH durable_writes = false".format(self.keyspace_name)) self.assertTrue(cluster2.metadata.keyspaces[self.keyspace_name].durable_writes) cluster2.refresh_keyspace_metadata(self.keyspace_name) self.assertFalse(cluster2.metadata.keyspaces[self.keyspace_name].durable_writes) cluster2.shutdown() def test_refresh_table_metadata(self): """ test for synchronously refreshing table metadata test_refresh_table_metatadata tests that table metadata is refreshed when calling test_refresh_table_metatadata(). It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema change push events. It then alters the table, adding a new column, using the first cluster object, and verifies that the table metadata has not changed in the second cluster object. Finally, it calls test_refresh_table_metatadata() and verifies that the table metadata is updated in the second cluster object. @since 2.6.0 @jira_ticket PYTHON-291 @expected_result Table metadata should be refreshed when refresh_table_metadata() is called. @test_category metadata """ table_name = "test" self.session.execute("CREATE TABLE {0}.{1} (a int PRIMARY KEY, b text)".format(self.keyspace_name, table_name)) - cluster2 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=-1) + cluster2 = TestCluster(schema_event_refresh_window=-1) cluster2.connect() self.assertNotIn("c", cluster2.metadata.keyspaces[self.keyspace_name].tables[table_name].columns) self.session.execute("ALTER TABLE {0}.{1} ADD c double".format(self.keyspace_name, table_name)) self.assertNotIn("c", cluster2.metadata.keyspaces[self.keyspace_name].tables[table_name].columns) cluster2.refresh_table_metadata(self.keyspace_name, table_name) self.assertIn("c", cluster2.metadata.keyspaces[self.keyspace_name].tables[table_name].columns) cluster2.shutdown() @greaterthanorequalcass30 def test_refresh_metadata_for_mv(self): """ test for synchronously refreshing materialized view metadata test_refresh_table_metadata_for_materialized_views tests that materialized view metadata is refreshed when calling test_refresh_table_metatadata() with the materialized view name as the table. It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema change push events. It then creates a new materialized view , using the first cluster object, and verifies that the materialized view metadata has not changed in the second cluster object. Finally, it calls test_refresh_table_metatadata() with the materialized view name as the table name, and verifies that the materialized view metadata is updated in the second cluster object. @since 3.0.0 @jira_ticket PYTHON-371 @expected_result Materialized view metadata should be refreshed when refresh_table_metadata() is called. @test_category metadata """ self.session.execute("CREATE TABLE {0}.{1} (a int PRIMARY KEY, b text)".format(self.keyspace_name, self.function_table_name)) - cluster2 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=-1) + cluster2 = TestCluster(schema_event_refresh_window=-1) cluster2.connect() try: self.assertNotIn("mv1", cluster2.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views) - self.session.execute("CREATE MATERIALIZED VIEW {0}.mv1 AS SELECT b FROM {0}.{1} WHERE b IS NOT NULL PRIMARY KEY (a, b)" + self.session.execute("CREATE MATERIALIZED VIEW {0}.mv1 AS SELECT a, b FROM {0}.{1} " + "WHERE a IS NOT NULL AND b IS NOT NULL PRIMARY KEY (a, b)" .format(self.keyspace_name, self.function_table_name)) self.assertNotIn("mv1", cluster2.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views) cluster2.refresh_table_metadata(self.keyspace_name, "mv1") self.assertIn("mv1", cluster2.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views) finally: cluster2.shutdown() original_meta = self.cluster.metadata.keyspaces[self.keyspace_name].views['mv1'] self.assertIs(original_meta, self.session.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views['mv1']) self.cluster.refresh_materialized_view_metadata(self.keyspace_name, 'mv1') current_meta = self.cluster.metadata.keyspaces[self.keyspace_name].views['mv1'] self.assertIsNot(current_meta, original_meta) self.assertIsNot(original_meta, self.session.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views['mv1']) self.assertEqual(original_meta.as_cql_query(), current_meta.as_cql_query()) - cluster3 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=-1) + cluster3 = TestCluster(schema_event_refresh_window=-1) cluster3.connect() try: self.assertNotIn("mv2", cluster3.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views) - self.session.execute("CREATE MATERIALIZED VIEW {0}.mv2 AS SELECT b FROM {0}.{1} WHERE b IS NOT NULL PRIMARY KEY (a, b)" - .format(self.keyspace_name, self.function_table_name)) + self.session.execute( + "CREATE MATERIALIZED VIEW {0}.mv2 AS SELECT a, b FROM {0}.{1} " + "WHERE a IS NOT NULL AND b IS NOT NULL PRIMARY KEY (a, b)".format( + self.keyspace_name, self.function_table_name) + ) self.assertNotIn("mv2", cluster3.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views) cluster3.refresh_materialized_view_metadata(self.keyspace_name, 'mv2') self.assertIn("mv2", cluster3.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views) finally: cluster3.shutdown() def test_refresh_user_type_metadata(self): """ test for synchronously refreshing UDT metadata in keyspace test_refresh_user_type_metadata tests that UDT metadata in a keyspace is refreshed when calling refresh_user_type_metadata(). It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema change push events. It then alters the keyspace, creating a new UDT, using the first cluster object, and verifies that the UDT metadata has not changed in the second cluster object. Finally, it calls refresh_user_type_metadata() and verifies that the UDT metadata in the keyspace is updated in the second cluster object. @since 2.6.0 @jira_ticket PYTHON-291 @expected_result UDT metadata in the keyspace should be refreshed when refresh_user_type_metadata() is called. @test_category metadata """ if PROTOCOL_VERSION < 3: raise unittest.SkipTest("Protocol 3+ is required for UDTs, currently testing against {0}".format(PROTOCOL_VERSION)) - cluster2 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=-1) + cluster2 = TestCluster(schema_event_refresh_window=-1) cluster2.connect() self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].user_types, {}) self.session.execute("CREATE TYPE {0}.user (age int, name text)".format(self.keyspace_name)) self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].user_types, {}) cluster2.refresh_user_type_metadata(self.keyspace_name, "user") self.assertIn("user", cluster2.metadata.keyspaces[self.keyspace_name].user_types) cluster2.shutdown() @greaterthancass20 def test_refresh_user_type_metadata_proto_2(self): """ Test to insure that protocol v1/v2 surface UDT metadata changes @since 3.7.0 @jira_ticket PYTHON-106 @expected_result UDT metadata in the keyspace should be updated regardless of protocol version @test_category metadata """ supported_versions = get_supported_protocol_versions() if 2 not in supported_versions: # 1 and 2 were dropped in the same version raise unittest.SkipTest("Protocol versions 1 and 2 are not supported in Cassandra version ".format(CASSANDRA_VERSION)) for protocol_version in (1, 2): - cluster = Cluster(protocol_version=protocol_version) + cluster = TestCluster() session = cluster.connect() self.assertEqual(cluster.metadata.keyspaces[self.keyspace_name].user_types, {}) session.execute("CREATE TYPE {0}.user (age int, name text)".format(self.keyspace_name)) self.assertIn("user", cluster.metadata.keyspaces[self.keyspace_name].user_types) self.assertIn("age", cluster.metadata.keyspaces[self.keyspace_name].user_types["user"].field_names) self.assertIn("name", cluster.metadata.keyspaces[self.keyspace_name].user_types["user"].field_names) session.execute("ALTER TYPE {0}.user ADD flag boolean".format(self.keyspace_name)) self.assertIn("flag", cluster.metadata.keyspaces[self.keyspace_name].user_types["user"].field_names) session.execute("ALTER TYPE {0}.user RENAME flag TO something".format(self.keyspace_name)) self.assertIn("something", cluster.metadata.keyspaces[self.keyspace_name].user_types["user"].field_names) session.execute("DROP TYPE {0}.user".format(self.keyspace_name)) self.assertEqual(cluster.metadata.keyspaces[self.keyspace_name].user_types, {}) cluster.shutdown() def test_refresh_user_function_metadata(self): """ test for synchronously refreshing UDF metadata in keyspace test_refresh_user_function_metadata tests that UDF metadata in a keyspace is refreshed when calling refresh_user_function_metadata(). It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema change push events. It then alters the keyspace, creating a new UDF, using the first cluster object, and verifies that the UDF metadata has not changed in the second cluster object. Finally, it calls refresh_user_function_metadata() and verifies that the UDF metadata in the keyspace is updated in the second cluster object. @since 2.6.0 @jira_ticket PYTHON-291 @expected_result UDF metadata in the keyspace should be refreshed when refresh_user_function_metadata() is called. @test_category metadata """ if PROTOCOL_VERSION < 4: raise unittest.SkipTest("Protocol 4+ is required for UDFs, currently testing against {0}".format(PROTOCOL_VERSION)) - cluster2 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=-1) + cluster2 = TestCluster(schema_event_refresh_window=-1) cluster2.connect() self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].functions, {}) self.session.execute("""CREATE FUNCTION {0}.sum_int(key int, val int) RETURNS NULL ON NULL INPUT RETURNS int - LANGUAGE javascript AS 'key + val';""".format(self.keyspace_name)) + LANGUAGE java AS ' return key + val;';""".format(self.keyspace_name)) self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].functions, {}) cluster2.refresh_user_function_metadata(self.keyspace_name, UserFunctionDescriptor("sum_int", ["int", "int"])) self.assertIn("sum_int(int,int)", cluster2.metadata.keyspaces[self.keyspace_name].functions) cluster2.shutdown() def test_refresh_user_aggregate_metadata(self): """ test for synchronously refreshing UDA metadata in keyspace test_refresh_user_aggregate_metadata tests that UDA metadata in a keyspace is refreshed when calling refresh_user_aggregate_metadata(). It creates a second cluster object with schema_event_refresh_window=-1 such that schema refreshes are disabled for schema change push events. It then alters the keyspace, creating a new UDA, using the first cluster object, and verifies that the UDA metadata has not changed in the second cluster object. Finally, it calls refresh_user_aggregate_metadata() and verifies that the UDF metadata in the keyspace is updated in the second cluster object. @since 2.6.0 @jira_ticket PYTHON-291 @expected_result UDA metadata in the keyspace should be refreshed when refresh_user_aggregate_metadata() is called. @test_category metadata """ if PROTOCOL_VERSION < 4: raise unittest.SkipTest("Protocol 4+ is required for UDAs, currently testing against {0}".format(PROTOCOL_VERSION)) - cluster2 = Cluster(protocol_version=PROTOCOL_VERSION, schema_event_refresh_window=-1) + cluster2 = TestCluster(schema_event_refresh_window=-1) cluster2.connect() self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].aggregates, {}) self.session.execute("""CREATE FUNCTION {0}.sum_int(key int, val int) RETURNS NULL ON NULL INPUT RETURNS int - LANGUAGE javascript AS 'key + val';""".format(self.keyspace_name)) + LANGUAGE java AS 'return key + val;';""".format(self.keyspace_name)) self.session.execute("""CREATE AGGREGATE {0}.sum_agg(int) SFUNC sum_int STYPE int INITCOND 0""" .format(self.keyspace_name)) self.assertEqual(cluster2.metadata.keyspaces[self.keyspace_name].aggregates, {}) cluster2.refresh_user_aggregate_metadata(self.keyspace_name, UserAggregateDescriptor("sum_agg", ["int"])) self.assertIn("sum_agg(int)", cluster2.metadata.keyspaces[self.keyspace_name].aggregates) cluster2.shutdown() @greaterthanorequalcass30 def test_multiple_indices(self): """ test multiple indices on the same column. Creates a table and two indices. Ensures that both indices metatdata is surface appropriately. @since 3.0.0 @jira_ticket PYTHON-276 @expected_result IndexMetadata is appropriately surfaced @test_category metadata """ self.session.execute("CREATE TABLE {0}.{1} (a int PRIMARY KEY, b map)".format(self.keyspace_name, self.function_table_name)) self.session.execute("CREATE INDEX index_1 ON {0}.{1}(b)".format(self.keyspace_name, self.function_table_name)) self.session.execute("CREATE INDEX index_2 ON {0}.{1}(keys(b))".format(self.keyspace_name, self.function_table_name)) indices = self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].indexes self.assertEqual(len(indices), 2) index_1 = indices["index_1"] index_2 = indices['index_2'] self.assertEqual(index_1.table_name, "test_multiple_indices") self.assertEqual(index_1.name, "index_1") self.assertEqual(index_1.kind, "COMPOSITES") self.assertEqual(index_1.index_options["target"], "values(b)") self.assertEqual(index_1.keyspace_name, "schemametadatatests") self.assertEqual(index_2.table_name, "test_multiple_indices") self.assertEqual(index_2.name, "index_2") self.assertEqual(index_2.kind, "COMPOSITES") self.assertEqual(index_2.index_options["target"], "keys(b)") self.assertEqual(index_2.keyspace_name, "schemametadatatests") @greaterthanorequalcass30 def test_table_extensions(self): s = self.session ks = self.keyspace_name ks_meta = s.cluster.metadata.keyspaces[ks] t = self.function_table_name v = t + 'view' s.execute("CREATE TABLE %s.%s (k text PRIMARY KEY, v int)" % (ks, t)) - s.execute("CREATE MATERIALIZED VIEW %s.%s AS SELECT * FROM %s.%s WHERE v IS NOT NULL PRIMARY KEY (v, k)" % (ks, v, ks, t)) + s.execute( + "CREATE MATERIALIZED VIEW %s.%s AS SELECT * FROM %s.%s " + "WHERE v IS NOT NULL AND k IS NOT NULL PRIMARY KEY (v, k)" % (ks, v, ks, t) + ) table_meta = ks_meta.tables[t] view_meta = table_meta.views[v] self.assertFalse(table_meta.extensions) self.assertFalse(view_meta.extensions) original_table_cql = table_meta.export_as_string() original_view_cql = view_meta.export_as_string() # extensions registered, not present # -------------------------------------- class Ext0(RegisteredTableExtension): name = t @classmethod def after_table_cql(cls, table_meta, ext_key, ext_blob): return "%s %s %s %s" % (cls.name, table_meta.name, ext_key, ext_blob) class Ext1(Ext0): name = t + '##' self.assertFalse(table_meta.extensions) self.assertFalse(view_meta.extensions) self.assertIn(Ext0.name, _RegisteredExtensionType._extension_registry) self.assertIn(Ext1.name, _RegisteredExtensionType._extension_registry) - self.assertEqual(len(_RegisteredExtensionType._extension_registry), 2) + # There will bee the RLAC extension here. + self.assertEqual(len(_RegisteredExtensionType._extension_registry), 3) self.cluster.refresh_table_metadata(ks, t) table_meta = ks_meta.tables[t] view_meta = table_meta.views[v] self.assertEqual(table_meta.export_as_string(), original_table_cql) self.assertEqual(view_meta.export_as_string(), original_view_cql) update_t = s.prepare('UPDATE system_schema.tables SET extensions=? WHERE keyspace_name=? AND table_name=?') # for blob type coercing update_v = s.prepare('UPDATE system_schema.views SET extensions=? WHERE keyspace_name=? AND view_name=?') # extensions registered, one present # -------------------------------------- ext_map = {Ext0.name: six.b("THA VALUE")} [(s.execute(update_t, (ext_map, ks, t)), s.execute(update_v, (ext_map, ks, v))) for _ in self.cluster.metadata.all_hosts()] # we're manipulating metadata - do it on all hosts self.cluster.refresh_table_metadata(ks, t) self.cluster.refresh_materialized_view_metadata(ks, v) table_meta = ks_meta.tables[t] view_meta = table_meta.views[v] self.assertIn(Ext0.name, table_meta.extensions) new_cql = table_meta.export_as_string() self.assertNotEqual(new_cql, original_table_cql) self.assertIn(Ext0.after_table_cql(table_meta, Ext0.name, ext_map[Ext0.name]), new_cql) self.assertNotIn(Ext1.name, new_cql) self.assertIn(Ext0.name, view_meta.extensions) new_cql = view_meta.export_as_string() self.assertNotEqual(new_cql, original_view_cql) self.assertIn(Ext0.after_table_cql(view_meta, Ext0.name, ext_map[Ext0.name]), new_cql) self.assertNotIn(Ext1.name, new_cql) # extensions registered, one present # -------------------------------------- ext_map = {Ext0.name: six.b("THA VALUE"), Ext1.name: six.b("OTHA VALUE")} [(s.execute(update_t, (ext_map, ks, t)), s.execute(update_v, (ext_map, ks, v))) for _ in self.cluster.metadata.all_hosts()] # we're manipulating metadata - do it on all hosts self.cluster.refresh_table_metadata(ks, t) self.cluster.refresh_materialized_view_metadata(ks, v) table_meta = ks_meta.tables[t] view_meta = table_meta.views[v] self.assertIn(Ext0.name, table_meta.extensions) self.assertIn(Ext1.name, table_meta.extensions) new_cql = table_meta.export_as_string() self.assertNotEqual(new_cql, original_table_cql) self.assertIn(Ext0.after_table_cql(table_meta, Ext0.name, ext_map[Ext0.name]), new_cql) self.assertIn(Ext1.after_table_cql(table_meta, Ext1.name, ext_map[Ext1.name]), new_cql) self.assertIn(Ext0.name, view_meta.extensions) self.assertIn(Ext1.name, view_meta.extensions) new_cql = view_meta.export_as_string() self.assertNotEqual(new_cql, original_view_cql) self.assertIn(Ext0.after_table_cql(view_meta, Ext0.name, ext_map[Ext0.name]), new_cql) self.assertIn(Ext1.after_table_cql(view_meta, Ext1.name, ext_map[Ext1.name]), new_cql) class TestCodeCoverage(unittest.TestCase): def test_export_schema(self): """ Test export schema functionality """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() cluster.connect() self.assertIsInstance(cluster.metadata.export_schema_as_string(), six.string_types) cluster.shutdown() def test_export_keyspace_schema(self): """ Test export keyspace schema functionality """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() cluster.connect() for keyspace in cluster.metadata.keyspaces: keyspace_metadata = cluster.metadata.keyspaces[keyspace] self.assertIsInstance(keyspace_metadata.export_as_string(), six.string_types) self.assertIsInstance(keyspace_metadata.as_cql_query(), six.string_types) cluster.shutdown() def assert_equal_diff(self, received, expected): if received != expected: diff_string = '\n'.join(difflib.unified_diff(expected.split('\n'), received.split('\n'), 'EXPECTED', 'RECEIVED', lineterm='')) self.fail(diff_string) def assert_startswith_diff(self, received, prefix): if not received.startswith(prefix): prefix_lines = prefix.split('\n') diff_string = '\n'.join(difflib.unified_diff(prefix_lines, received.split('\n')[:len(prefix_lines)], 'EXPECTED', 'RECEIVED', lineterm='')) self.fail(diff_string) @greaterthancass20 def test_export_keyspace_schema_udts(self): """ Test udt exports """ if PROTOCOL_VERSION < 3: raise unittest.SkipTest( "Protocol 3.0+ is required for UDT change events, currently testing against %r" % (PROTOCOL_VERSION,)) if sys.version_info[0:2] != (2, 7): raise unittest.SkipTest('This test compares static strings generated from dict items, which may change orders. Test with 2.7.') - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect() session.execute(""" CREATE KEYSPACE export_udts WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} AND durable_writes = true; """) session.execute(""" CREATE TYPE export_udts.street ( street_number int, street_name text) """) session.execute(""" CREATE TYPE export_udts.zip ( zipcode int, zip_plus_4 int) """) session.execute(""" CREATE TYPE export_udts.address ( street_address frozen, zip_code frozen) """) session.execute(""" CREATE TABLE export_udts.users ( user text PRIMARY KEY, addresses map>) """) expected_prefix = """CREATE KEYSPACE export_udts WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} AND durable_writes = true; CREATE TYPE export_udts.street ( street_number int, street_name text ); CREATE TYPE export_udts.zip ( zipcode int, zip_plus_4 int ); CREATE TYPE export_udts.address ( street_address frozen, zip_code frozen ); CREATE TABLE export_udts.users ( user text PRIMARY KEY, addresses map>""" self.assert_startswith_diff(cluster.metadata.keyspaces['export_udts'].export_as_string(), expected_prefix) table_meta = cluster.metadata.keyspaces['export_udts'].tables['users'] expected_prefix = """CREATE TABLE export_udts.users ( user text PRIMARY KEY, addresses map>""" self.assert_startswith_diff(table_meta.export_as_string(), expected_prefix) cluster.shutdown() @greaterthancass21 def test_case_sensitivity(self): """ Test that names that need to be escaped in CREATE statements are """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect() ksname = 'AnInterestingKeyspace' cfname = 'AnInterestingTable' session.execute("DROP KEYSPACE IF EXISTS {0}".format(ksname)) session.execute(""" CREATE KEYSPACE "%s" WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} """ % (ksname,)) session.execute(""" CREATE TABLE "%s"."%s" ( k int, "A" int, "B" int, "MyColumn" int, PRIMARY KEY (k, "A")) WITH CLUSTERING ORDER BY ("A" DESC) """ % (ksname, cfname)) session.execute(""" CREATE INDEX myindex ON "%s"."%s" ("MyColumn") """ % (ksname, cfname)) session.execute(""" CREATE INDEX "AnotherIndex" ON "%s"."%s" ("B") """ % (ksname, cfname)) ksmeta = cluster.metadata.keyspaces[ksname] schema = ksmeta.export_as_string() self.assertIn('CREATE KEYSPACE "AnInterestingKeyspace"', schema) self.assertIn('CREATE TABLE "AnInterestingKeyspace"."AnInterestingTable"', schema) self.assertIn('"A" int', schema) self.assertIn('"B" int', schema) self.assertIn('"MyColumn" int', schema) self.assertIn('PRIMARY KEY (k, "A")', schema) self.assertIn('WITH CLUSTERING ORDER BY ("A" DESC)', schema) self.assertIn('CREATE INDEX myindex ON "AnInterestingKeyspace"."AnInterestingTable" ("MyColumn")', schema) self.assertIn('CREATE INDEX "AnotherIndex" ON "AnInterestingKeyspace"."AnInterestingTable" ("B")', schema) cluster.shutdown() def test_already_exists_exceptions(self): """ Ensure AlreadyExists exception is thrown when hit """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect() ksname = 'test3rf' cfname = 'test' ddl = ''' CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '3'}''' self.assertRaises(AlreadyExists, session.execute, ddl % ksname) ddl = ''' CREATE TABLE %s.%s ( k int PRIMARY KEY, v int )''' self.assertRaises(AlreadyExists, session.execute, ddl % (ksname, cfname)) cluster.shutdown() @local def test_replicas(self): """ Ensure cluster.metadata.get_replicas return correctly when not attached to keyspace """ if murmur3 is None: raise unittest.SkipTest('the murmur3 extension is not available') - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() self.assertEqual(cluster.metadata.get_replicas('test3rf', 'key'), []) cluster.connect('test3rf') self.assertNotEqual(list(cluster.metadata.get_replicas('test3rf', six.b('key'))), []) host = list(cluster.metadata.get_replicas('test3rf', six.b('key')))[0] self.assertEqual(host.datacenter, 'dc1') self.assertEqual(host.rack, 'r1') cluster.shutdown() def test_token_map(self): """ Test token mappings """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() cluster.connect('test3rf') ring = cluster.metadata.token_map.ring owners = list(cluster.metadata.token_map.token_to_host_owner[token] for token in ring) get_replicas = cluster.metadata.token_map.get_replicas for ksname in ('test1rf', 'test2rf', 'test3rf'): self.assertNotEqual(list(get_replicas(ksname, ring[0])), []) for i, token in enumerate(ring): self.assertEqual(set(get_replicas('test3rf', token)), set(owners)) self.assertEqual(set(get_replicas('test2rf', token)), set([owners[i], owners[(i + 1) % 3]])) self.assertEqual(set(get_replicas('test1rf', token)), set([owners[i]])) cluster.shutdown() class TokenMetadataTest(unittest.TestCase): """ Test of TokenMap creation and other behavior. """ @local def test_token(self): expected_node_count = len(get_cluster().nodes) - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() cluster.connect() tmap = cluster.metadata.token_map self.assertTrue(issubclass(tmap.token_class, Token)) self.assertEqual(expected_node_count, len(tmap.ring)) cluster.shutdown() class KeyspaceAlterMetadata(unittest.TestCase): """ Test verifies that table metadata is preserved on keyspace alter """ def setUp(self): - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + self.cluster = TestCluster() self.session = self.cluster.connect() name = self._testMethodName.lower() crt_ks = ''' CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1} AND durable_writes = true''' % name self.session.execute(crt_ks) def tearDown(self): name = self._testMethodName.lower() self.session.execute('DROP KEYSPACE %s' % name) self.cluster.shutdown() def test_keyspace_alter(self): """ Table info is preserved upon keyspace alter: Create table Verify schema Alter ks Verify that table metadata is still present PYTHON-173 """ name = self._testMethodName.lower() self.session.execute('CREATE TABLE %s.d (d INT PRIMARY KEY)' % name) original_keyspace_meta = self.cluster.metadata.keyspaces[name] self.assertEqual(original_keyspace_meta.durable_writes, True) self.assertEqual(len(original_keyspace_meta.tables), 1) self.session.execute('ALTER KEYSPACE %s WITH durable_writes = false' % name) new_keyspace_meta = self.cluster.metadata.keyspaces[name] self.assertNotEqual(original_keyspace_meta, new_keyspace_meta) self.assertEqual(new_keyspace_meta.durable_writes, False) class IndexMapTests(unittest.TestCase): keyspace_name = 'index_map_tests' @property def table_name(self): return self._testMethodName.lower() @classmethod def setup_class(cls): - cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cls.cluster = TestCluster() cls.session = cls.cluster.connect() try: if cls.keyspace_name in cls.cluster.metadata.keyspaces: cls.session.execute("DROP KEYSPACE %s" % cls.keyspace_name) cls.session.execute( """ CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}; """ % cls.keyspace_name) cls.session.set_keyspace(cls.keyspace_name) except Exception: cls.cluster.shutdown() raise @classmethod def teardown_class(cls): try: cls.session.execute("DROP KEYSPACE %s" % cls.keyspace_name) finally: cls.cluster.shutdown() def create_basic_table(self): self.session.execute("CREATE TABLE %s (k int PRIMARY KEY, a int)" % self.table_name) def drop_basic_table(self): self.session.execute("DROP TABLE %s" % self.table_name) def test_index_updates(self): self.create_basic_table() ks_meta = self.cluster.metadata.keyspaces[self.keyspace_name] table_meta = ks_meta.tables[self.table_name] self.assertNotIn('a_idx', ks_meta.indexes) self.assertNotIn('b_idx', ks_meta.indexes) self.assertNotIn('a_idx', table_meta.indexes) self.assertNotIn('b_idx', table_meta.indexes) self.session.execute("CREATE INDEX a_idx ON %s (a)" % self.table_name) self.session.execute("ALTER TABLE %s ADD b int" % self.table_name) self.session.execute("CREATE INDEX b_idx ON %s (b)" % self.table_name) ks_meta = self.cluster.metadata.keyspaces[self.keyspace_name] table_meta = ks_meta.tables[self.table_name] self.assertIsInstance(ks_meta.indexes['a_idx'], IndexMetadata) self.assertIsInstance(ks_meta.indexes['b_idx'], IndexMetadata) self.assertIsInstance(table_meta.indexes['a_idx'], IndexMetadata) self.assertIsInstance(table_meta.indexes['b_idx'], IndexMetadata) # both indexes updated when index dropped self.session.execute("DROP INDEX a_idx") # temporarily synchronously refresh the schema metadata, until CASSANDRA-9391 is merged in self.cluster.refresh_table_metadata(self.keyspace_name, self.table_name) ks_meta = self.cluster.metadata.keyspaces[self.keyspace_name] table_meta = ks_meta.tables[self.table_name] self.assertNotIn('a_idx', ks_meta.indexes) self.assertIsInstance(ks_meta.indexes['b_idx'], IndexMetadata) self.assertNotIn('a_idx', table_meta.indexes) self.assertIsInstance(table_meta.indexes['b_idx'], IndexMetadata) # keyspace index updated when table dropped self.drop_basic_table() ks_meta = self.cluster.metadata.keyspaces[self.keyspace_name] self.assertNotIn(self.table_name, ks_meta.tables) self.assertNotIn('a_idx', ks_meta.indexes) self.assertNotIn('b_idx', ks_meta.indexes) def test_index_follows_alter(self): self.create_basic_table() idx = self.table_name + '_idx' self.session.execute("CREATE INDEX %s ON %s (a)" % (idx, self.table_name)) ks_meta = self.cluster.metadata.keyspaces[self.keyspace_name] table_meta = ks_meta.tables[self.table_name] self.assertIsInstance(ks_meta.indexes[idx], IndexMetadata) self.assertIsInstance(table_meta.indexes[idx], IndexMetadata) self.session.execute('ALTER KEYSPACE %s WITH durable_writes = false' % self.keyspace_name) old_meta = ks_meta ks_meta = self.cluster.metadata.keyspaces[self.keyspace_name] self.assertIsNot(ks_meta, old_meta) table_meta = ks_meta.tables[self.table_name] self.assertIsInstance(ks_meta.indexes[idx], IndexMetadata) self.assertIsInstance(table_meta.indexes[idx], IndexMetadata) self.drop_basic_table() class FunctionTest(unittest.TestCase): """ Base functionality for Function and Aggregate metadata test classes """ def setUp(self): """ Tests are skipped if run with native protocol version < 4 """ if PROTOCOL_VERSION < 4: raise unittest.SkipTest("Function metadata requires native protocol version 4+") @property def function_name(self): return self._testMethodName.lower() @classmethod def setup_class(cls): if PROTOCOL_VERSION >= 4: - cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cls.cluster = TestCluster() cls.keyspace_name = cls.__name__.lower() cls.session = cls.cluster.connect() cls.session.execute("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}" % cls.keyspace_name) cls.session.set_keyspace(cls.keyspace_name) cls.keyspace_function_meta = cls.cluster.metadata.keyspaces[cls.keyspace_name].functions cls.keyspace_aggregate_meta = cls.cluster.metadata.keyspaces[cls.keyspace_name].aggregates @classmethod def teardown_class(cls): if PROTOCOL_VERSION >= 4: cls.session.execute("DROP KEYSPACE IF EXISTS %s" % cls.keyspace_name) cls.cluster.shutdown() class Verified(object): def __init__(self, test_case, meta_class, element_meta, **function_kwargs): self.test_case = test_case self.function_kwargs = dict(function_kwargs) self.meta_class = meta_class self.element_meta = element_meta def __enter__(self): tc = self.test_case expected_meta = self.meta_class(**self.function_kwargs) tc.assertNotIn(expected_meta.signature, self.element_meta) tc.session.execute(expected_meta.as_cql_query()) tc.assertIn(expected_meta.signature, self.element_meta) generated_meta = self.element_meta[expected_meta.signature] self.test_case.assertEqual(generated_meta.as_cql_query(), expected_meta.as_cql_query()) return self def __exit__(self, exc_type, exc_val, exc_tb): tc = self.test_case tc.session.execute("DROP %s %s.%s" % (self.meta_class.__name__, tc.keyspace_name, self.signature)) tc.assertNotIn(self.signature, self.element_meta) @property def signature(self): return SignatureDescriptor.format_signature(self.function_kwargs['name'], self.function_kwargs['argument_types']) class VerifiedFunction(Verified): def __init__(self, test_case, **kwargs): super(FunctionTest.VerifiedFunction, self).__init__(test_case, Function, test_case.keyspace_function_meta, **kwargs) class VerifiedAggregate(Verified): def __init__(self, test_case, **kwargs): super(FunctionTest.VerifiedAggregate, self).__init__(test_case, Aggregate, test_case.keyspace_aggregate_meta, **kwargs) class FunctionMetadata(FunctionTest): def make_function_kwargs(self, called_on_null=True): return {'keyspace': self.keyspace_name, 'name': self.function_name, 'argument_types': ['double', 'int'], 'argument_names': ['d', 'i'], 'return_type': 'double', 'language': 'java', 'body': 'return new Double(0.0);', - 'called_on_null_input': called_on_null} + 'called_on_null_input': called_on_null, + 'deterministic': False, + 'monotonic': False, + 'monotonic_on': []} def test_functions_after_udt(self): """ Test to to ensure functions come after UDTs in in keyspace dump test_functions_after_udt creates a basic function. Then queries that function and make sure that in the results that UDT's are listed before any corresponding functions, when we dump the keyspace Ideally we would make a function that takes a udt type, but this presently fails because C* c059a56 requires udt to be frozen to create, but does not store meta indicating frozen SEE https://issues.apache.org/jira/browse/CASSANDRA-9186 Maybe update this after release kwargs = self.make_function_kwargs() kwargs['argument_types'][0] = "frozen<%s>" % udt_name expected_meta = Function(**kwargs) with self.VerifiedFunction(self, **kwargs): @since 2.6.0 @jira_ticket PYTHON-211 @expected_result UDT's should come before any functions @test_category function """ self.assertNotIn(self.function_name, self.keyspace_function_meta) udt_name = 'udtx' self.session.execute("CREATE TYPE %s (x int)" % udt_name) with self.VerifiedFunction(self, **self.make_function_kwargs()): # udts must come before functions in keyspace dump keyspace_cql = self.cluster.metadata.keyspaces[self.keyspace_name].export_as_string() type_idx = keyspace_cql.rfind("CREATE TYPE") func_idx = keyspace_cql.find("CREATE FUNCTION") self.assertNotIn(-1, (type_idx, func_idx), "TYPE or FUNCTION not found in keyspace_cql: " + keyspace_cql) self.assertGreater(func_idx, type_idx) def test_function_same_name_diff_types(self): """ Test to verify to that functions with different signatures are differentiated in metadata test_function_same_name_diff_types Creates two functions. One with the same name but a slightly different signature. Then ensures that both are surfaced separately in our metadata. @since 2.6.0 @jira_ticket PYTHON-211 @expected_result function with the same name but different signatures should be surfaced separately @test_category function """ # Create a function kwargs = self.make_function_kwargs() with self.VerifiedFunction(self, **kwargs): # another function: same name, different type sig. self.assertGreater(len(kwargs['argument_types']), 1) self.assertGreater(len(kwargs['argument_names']), 1) kwargs['argument_types'] = kwargs['argument_types'][:1] kwargs['argument_names'] = kwargs['argument_names'][:1] # Ensure they are surfaced separately with self.VerifiedFunction(self, **kwargs): functions = [f for f in self.keyspace_function_meta.values() if f.name == self.function_name] self.assertEqual(len(functions), 2) self.assertNotEqual(functions[0].argument_types, functions[1].argument_types) def test_function_no_parameters(self): """ Test to verify CQL output for functions with zero parameters Creates a function with no input parameters, verify that CQL output is correct. @since 2.7.1 @jira_ticket PYTHON-392 @expected_result function with no parameters should generate proper CQL @test_category function """ kwargs = self.make_function_kwargs() kwargs['argument_types'] = [] kwargs['argument_names'] = [] kwargs['return_type'] = 'bigint' kwargs['body'] = 'return System.currentTimeMillis() / 1000L;' with self.VerifiedFunction(self, **kwargs) as vf: fn_meta = self.keyspace_function_meta[vf.signature] self.assertRegexpMatches(fn_meta.as_cql_query(), "CREATE FUNCTION.*%s\(\) .*" % kwargs['name']) def test_functions_follow_keyspace_alter(self): """ Test to verify to that functions maintain equality after a keyspace is altered test_functions_follow_keyspace_alter creates a function then alters a the keyspace associated with that function. After the alter we validate that the function maintains the same metadata @since 2.6.0 @jira_ticket PYTHON-211 @expected_result functions are the same after parent keyspace is altered @test_category function """ # Create function with self.VerifiedFunction(self, **self.make_function_kwargs()): original_keyspace_meta = self.cluster.metadata.keyspaces[self.keyspace_name] self.session.execute('ALTER KEYSPACE %s WITH durable_writes = false' % self.keyspace_name) # After keyspace alter ensure that we maintain function equality. try: new_keyspace_meta = self.cluster.metadata.keyspaces[self.keyspace_name] self.assertNotEqual(original_keyspace_meta, new_keyspace_meta) self.assertIs(original_keyspace_meta.functions, new_keyspace_meta.functions) finally: self.session.execute('ALTER KEYSPACE %s WITH durable_writes = true' % self.keyspace_name) def test_function_cql_called_on_null(self): """ Test to verify to that that called on null argument is honored on function creation. test_functions_follow_keyspace_alter create two functions. One with the called_on_null_input set to true, the other with it set to false. We then verify that the metadata constructed from those function is correctly reflected @since 2.6.0 @jira_ticket PYTHON-211 @expected_result functions metadata correctly reflects called_on_null_input flag. @test_category function """ kwargs = self.make_function_kwargs() kwargs['called_on_null_input'] = True with self.VerifiedFunction(self, **kwargs) as vf: fn_meta = self.keyspace_function_meta[vf.signature] self.assertRegexpMatches(fn_meta.as_cql_query(), "CREATE FUNCTION.*\) CALLED ON NULL INPUT RETURNS .*") kwargs['called_on_null_input'] = False with self.VerifiedFunction(self, **kwargs) as vf: fn_meta = self.keyspace_function_meta[vf.signature] self.assertRegexpMatches(fn_meta.as_cql_query(), "CREATE FUNCTION.*\) RETURNS NULL ON NULL INPUT RETURNS .*") class AggregateMetadata(FunctionTest): @classmethod def setup_class(cls): if PROTOCOL_VERSION >= 4: super(AggregateMetadata, cls).setup_class() cls.session.execute("""CREATE OR REPLACE FUNCTION sum_int(s int, i int) RETURNS NULL ON NULL INPUT RETURNS int - LANGUAGE javascript AS 's + i';""") + LANGUAGE java AS 'return s + i;';""") cls.session.execute("""CREATE OR REPLACE FUNCTION sum_int_two(s int, i int, j int) RETURNS NULL ON NULL INPUT RETURNS int - LANGUAGE javascript AS 's + i + j';""") + LANGUAGE java AS 'return s + i + j;';""") cls.session.execute("""CREATE OR REPLACE FUNCTION "List_As_String"(l list) RETURNS NULL ON NULL INPUT RETURNS int - LANGUAGE javascript AS ''''' + l';""") + LANGUAGE java AS 'return l.size();';""") cls.session.execute("""CREATE OR REPLACE FUNCTION extend_list(s list, i int) CALLED ON NULL INPUT RETURNS list LANGUAGE java AS 'if (i != null) s.add(i.toString()); return s;';""") cls.session.execute("""CREATE OR REPLACE FUNCTION update_map(s map, i int) RETURNS NULL ON NULL INPUT RETURNS map LANGUAGE java AS 's.put(new Integer(i), new Integer(i)); return s;';""") cls.session.execute("""CREATE TABLE IF NOT EXISTS t (k int PRIMARY KEY, v int)""") for x in range(4): cls.session.execute("INSERT INTO t (k,v) VALUES (%s, %s)", (x, x)) cls.session.execute("INSERT INTO t (k) VALUES (%s)", (4,)) def make_aggregate_kwargs(self, state_func, state_type, final_func=None, init_cond=None): return {'keyspace': self.keyspace_name, 'name': self.function_name + '_aggregate', 'argument_types': ['int'], 'state_func': state_func, 'state_type': state_type, 'final_func': final_func, 'initial_condition': init_cond, - 'return_type': "does not matter for creation"} + 'return_type': "does not matter for creation", + 'deterministic': False} def test_return_type_meta(self): """ Test to verify to that the return type of a an aggregate is honored in the metadata test_return_type_meta creates an aggregate then ensures the return type of the created aggregate is correctly surfaced in the metadata @since 2.6.0 @jira_ticket PYTHON-211 @expected_result aggregate has the correct return typ in the metadata @test_category aggregate """ with self.VerifiedAggregate(self, **self.make_aggregate_kwargs('sum_int', 'int', init_cond='1')) as va: self.assertEqual(self.keyspace_aggregate_meta[va.signature].return_type, 'int') def test_init_cond(self): """ Test to verify that various initial conditions are correctly surfaced in various aggregate functions test_init_cond creates several different types of aggregates, and given various initial conditions it verifies that they correctly impact the aggregate's execution @since 2.6.0 @jira_ticket PYTHON-211 @expected_result initial conditions are correctly evaluated as part of the aggregates @test_category aggregate """ # This is required until the java driver bundled with C* is updated to support v4 - c = Cluster(protocol_version=3) + c = TestCluster(protocol_version=3) s = c.connect(self.keyspace_name) encoder = Encoder() expected_values = range(4) # int32 for init_cond in (-1, 0, 1): cql_init = encoder.cql_encode_all_types(init_cond) with self.VerifiedAggregate(self, **self.make_aggregate_kwargs('sum_int', 'int', init_cond=cql_init)) as va: sum_res = s.execute("SELECT %s(v) AS sum FROM t" % va.function_kwargs['name'])[0].sum self.assertEqual(sum_res, int(init_cond) + sum(expected_values)) # list for init_cond in ([], ['1', '2']): cql_init = encoder.cql_encode_all_types(init_cond) with self.VerifiedAggregate(self, **self.make_aggregate_kwargs('extend_list', 'list', init_cond=cql_init)) as va: list_res = s.execute("SELECT %s(v) AS list_res FROM t" % va.function_kwargs['name'])[0].list_res self.assertListEqual(list_res[:len(init_cond)], init_cond) self.assertEqual(set(i for i in list_res[len(init_cond):]), set(str(i) for i in expected_values)) # map expected_map_values = dict((i, i) for i in expected_values) expected_key_set = set(expected_values) for init_cond in ({}, {1: 2, 3: 4}, {5: 5}): cql_init = encoder.cql_encode_all_types(init_cond) with self.VerifiedAggregate(self, **self.make_aggregate_kwargs('update_map', 'map', init_cond=cql_init)) as va: map_res = s.execute("SELECT %s(v) AS map_res FROM t" % va.function_kwargs['name'])[0].map_res self.assertDictContainsSubset(expected_map_values, map_res) init_not_updated = dict((k, init_cond[k]) for k in set(init_cond) - expected_key_set) self.assertDictContainsSubset(init_not_updated, map_res) c.shutdown() def test_aggregates_after_functions(self): """ Test to verify that aggregates are listed after function in metadata test_aggregates_after_functions creates an aggregate, and then verifies that they are listed after any function creations when the keypspace dump is preformed @since 2.6.0 @jira_ticket PYTHON-211 @expected_result aggregates are declared after any functions @test_category aggregate """ # functions must come before functions in keyspace dump with self.VerifiedAggregate(self, **self.make_aggregate_kwargs('extend_list', 'list')): keyspace_cql = self.cluster.metadata.keyspaces[self.keyspace_name].export_as_string() func_idx = keyspace_cql.find("CREATE FUNCTION") aggregate_idx = keyspace_cql.rfind("CREATE AGGREGATE") self.assertNotIn(-1, (aggregate_idx, func_idx), "AGGREGATE or FUNCTION not found in keyspace_cql: " + keyspace_cql) self.assertGreater(aggregate_idx, func_idx) def test_same_name_diff_types(self): """ Test to verify to that aggregates with different signatures are differentiated in metadata test_same_name_diff_types Creates two Aggregates. One with the same name but a slightly different signature. Then ensures that both are surfaced separately in our metadata. @since 2.6.0 @jira_ticket PYTHON-211 @expected_result aggregates with the same name but different signatures should be surfaced separately @test_category function """ kwargs = self.make_aggregate_kwargs('sum_int', 'int', init_cond='0') with self.VerifiedAggregate(self, **kwargs): kwargs['state_func'] = 'sum_int_two' kwargs['argument_types'] = ['int', 'int'] with self.VerifiedAggregate(self, **kwargs): aggregates = [a for a in self.keyspace_aggregate_meta.values() if a.name == kwargs['name']] self.assertEqual(len(aggregates), 2) self.assertNotEqual(aggregates[0].argument_types, aggregates[1].argument_types) def test_aggregates_follow_keyspace_alter(self): """ Test to verify to that aggregates maintain equality after a keyspace is altered test_aggregates_follow_keyspace_alter creates a function then alters a the keyspace associated with that function. After the alter we validate that the function maintains the same metadata @since 2.6.0 @jira_ticket PYTHON-211 @expected_result aggregates are the same after parent keyspace is altered @test_category function """ with self.VerifiedAggregate(self, **self.make_aggregate_kwargs('sum_int', 'int', init_cond='0')): original_keyspace_meta = self.cluster.metadata.keyspaces[self.keyspace_name] self.session.execute('ALTER KEYSPACE %s WITH durable_writes = false' % self.keyspace_name) try: new_keyspace_meta = self.cluster.metadata.keyspaces[self.keyspace_name] self.assertNotEqual(original_keyspace_meta, new_keyspace_meta) self.assertIs(original_keyspace_meta.aggregates, new_keyspace_meta.aggregates) finally: self.session.execute('ALTER KEYSPACE %s WITH durable_writes = true' % self.keyspace_name) def test_cql_optional_params(self): """ Test to verify that the initial_cond and final_func parameters are correctly honored test_cql_optional_params creates various aggregates with different combinations of initial_condition, and final_func parameters set. It then ensures they are correctly honored. @since 2.6.0 @jira_ticket PYTHON-211 @expected_result initial_condition and final_func parameters are honored correctly @test_category function """ kwargs = self.make_aggregate_kwargs('extend_list', 'list') encoder = Encoder() # no initial condition, final func self.assertIsNone(kwargs['initial_condition']) self.assertIsNone(kwargs['final_func']) with self.VerifiedAggregate(self, **kwargs) as va: meta = self.keyspace_aggregate_meta[va.signature] self.assertIsNone(meta.initial_condition) self.assertIsNone(meta.final_func) cql = meta.as_cql_query() self.assertEqual(cql.find('INITCOND'), -1) self.assertEqual(cql.find('FINALFUNC'), -1) # initial condition, no final func kwargs['initial_condition'] = encoder.cql_encode_all_types(['init', 'cond']) with self.VerifiedAggregate(self, **kwargs) as va: meta = self.keyspace_aggregate_meta[va.signature] self.assertEqual(meta.initial_condition, kwargs['initial_condition']) self.assertIsNone(meta.final_func) cql = meta.as_cql_query() search_string = "INITCOND %s" % kwargs['initial_condition'] self.assertGreater(cql.find(search_string), 0, '"%s" search string not found in cql:\n%s' % (search_string, cql)) self.assertEqual(cql.find('FINALFUNC'), -1) # no initial condition, final func kwargs['initial_condition'] = None kwargs['final_func'] = 'List_As_String' with self.VerifiedAggregate(self, **kwargs) as va: meta = self.keyspace_aggregate_meta[va.signature] self.assertIsNone(meta.initial_condition) self.assertEqual(meta.final_func, kwargs['final_func']) cql = meta.as_cql_query() self.assertEqual(cql.find('INITCOND'), -1) search_string = 'FINALFUNC "%s"' % kwargs['final_func'] self.assertGreater(cql.find(search_string), 0, '"%s" search string not found in cql:\n%s' % (search_string, cql)) # both kwargs['initial_condition'] = encoder.cql_encode_all_types(['init', 'cond']) kwargs['final_func'] = 'List_As_String' with self.VerifiedAggregate(self, **kwargs) as va: meta = self.keyspace_aggregate_meta[va.signature] self.assertEqual(meta.initial_condition, kwargs['initial_condition']) self.assertEqual(meta.final_func, kwargs['final_func']) cql = meta.as_cql_query() init_cond_idx = cql.find("INITCOND %s" % kwargs['initial_condition']) final_func_idx = cql.find('FINALFUNC "%s"' % kwargs['final_func']) self.assertNotIn(-1, (init_cond_idx, final_func_idx)) self.assertGreater(init_cond_idx, final_func_idx) class BadMetaTest(unittest.TestCase): """ Test behavior when metadata has unexpected form Verify that new cluster/session can still connect, and the CQL output indicates the exception with a warning. PYTHON-370 """ class BadMetaException(Exception): pass @property def function_name(self): return self._testMethodName.lower() @classmethod def setup_class(cls): - cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cls.cluster = TestCluster() cls.keyspace_name = cls.__name__.lower() cls.session = cls.cluster.connect() cls.session.execute("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}" % cls.keyspace_name) cls.session.set_keyspace(cls.keyspace_name) connection = cls.cluster.control_connection._connection - cls.parser_class = get_schema_parser(connection, CASSANDRA_VERSION.base_version, timeout=20).__class__ + + cls.parser_class = get_schema_parser( + connection, + cls.cluster.metadata.get_host(connection.host).release_version, + cls.cluster.metadata.get_host(connection.host).dse_version, + timeout=20 + ).__class__ cls.cluster.control_connection.reconnect = Mock() @classmethod def teardown_class(cls): drop_keyspace_shutdown_cluster(cls.keyspace_name, cls.session, cls.cluster) def test_bad_keyspace(self): with patch.object(self.parser_class, '_build_keyspace_metadata_internal', side_effect=self.BadMetaException): self.cluster.refresh_keyspace_metadata(self.keyspace_name) m = self.cluster.metadata.keyspaces[self.keyspace_name] self.assertIs(m._exc_info[0], self.BadMetaException) self.assertIn("/*\nWarning:", m.export_as_string()) def test_bad_table(self): self.session.execute('CREATE TABLE %s (k int PRIMARY KEY, v int)' % self.function_name) with patch.object(self.parser_class, '_build_column_metadata', side_effect=self.BadMetaException): self.cluster.refresh_table_metadata(self.keyspace_name, self.function_name) m = self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_name] self.assertIs(m._exc_info[0], self.BadMetaException) self.assertIn("/*\nWarning:", m.export_as_string()) def test_bad_index(self): self.session.execute('CREATE TABLE %s (k int PRIMARY KEY, v int)' % self.function_name) self.session.execute('CREATE INDEX ON %s(v)' % self.function_name) with patch.object(self.parser_class, '_build_index_metadata', side_effect=self.BadMetaException): self.cluster.refresh_table_metadata(self.keyspace_name, self.function_name) m = self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_name] self.assertIs(m._exc_info[0], self.BadMetaException) self.assertIn("/*\nWarning:", m.export_as_string()) @greaterthancass20 def test_bad_user_type(self): self.session.execute('CREATE TYPE %s (i int, d double)' % self.function_name) with patch.object(self.parser_class, '_build_user_type', side_effect=self.BadMetaException): self.cluster.refresh_schema_metadata() # presently do not capture these errors on udt direct refresh -- make sure it's contained during full refresh m = self.cluster.metadata.keyspaces[self.keyspace_name] self.assertIs(m._exc_info[0], self.BadMetaException) self.assertIn("/*\nWarning:", m.export_as_string()) @greaterthancass21 def test_bad_user_function(self): self.session.execute("""CREATE FUNCTION IF NOT EXISTS %s (key int, val int) RETURNS NULL ON NULL INPUT RETURNS int - LANGUAGE javascript AS 'key + val';""" % self.function_name) - with patch.object(self.parser_class, '_build_function', side_effect=self.BadMetaException): - self.cluster.refresh_schema_metadata() # presently do not capture these errors on udt direct refresh -- make sure it's contained during full refresh - m = self.cluster.metadata.keyspaces[self.keyspace_name] - self.assertIs(m._exc_info[0], self.BadMetaException) - self.assertIn("/*\nWarning:", m.export_as_string()) + LANGUAGE java AS 'return key + val;';""" % self.function_name) + + #We need to patch as well the reconnect function because after patching the _build_function + #there will an Error refreshing schema which will trigger a reconnection. If this happened + #in a timely manner in the call self.cluster.refresh_schema_metadata() it would return an exception + #due to that a connection would be closed + with patch.object(self.cluster.control_connection, 'reconnect'): + with patch.object(self.parser_class, '_build_function', side_effect=self.BadMetaException): + self.cluster.refresh_schema_metadata() # presently do not capture these errors on udt direct refresh -- make sure it's contained during full refresh + m = self.cluster.metadata.keyspaces[self.keyspace_name] + self.assertIs(m._exc_info[0], self.BadMetaException) + self.assertIn("/*\nWarning:", m.export_as_string()) @greaterthancass21 def test_bad_user_aggregate(self): self.session.execute("""CREATE FUNCTION IF NOT EXISTS sum_int (key int, val int) RETURNS NULL ON NULL INPUT RETURNS int - LANGUAGE javascript AS 'key + val';""") + LANGUAGE java AS 'return key + val;';""") self.session.execute("""CREATE AGGREGATE %s(int) SFUNC sum_int STYPE int INITCOND 0""" % self.function_name) - with patch.object(self.parser_class, '_build_aggregate', side_effect=self.BadMetaException): - self.cluster.refresh_schema_metadata() # presently do not capture these errors on udt direct refresh -- make sure it's contained during full refresh - m = self.cluster.metadata.keyspaces[self.keyspace_name] - self.assertIs(m._exc_info[0], self.BadMetaException) - self.assertIn("/*\nWarning:", m.export_as_string()) + #We have the same issue here as in test_bad_user_function + with patch.object(self.cluster.control_connection, 'reconnect'): + with patch.object(self.parser_class, '_build_aggregate', side_effect=self.BadMetaException): + self.cluster.refresh_schema_metadata() # presently do not capture these errors on udt direct refresh -- make sure it's contained during full refresh + m = self.cluster.metadata.keyspaces[self.keyspace_name] + self.assertIs(m._exc_info[0], self.BadMetaException) + self.assertIn("/*\nWarning:", m.export_as_string()) class DynamicCompositeTypeTest(BasicSharedKeyspaceUnitTestCase): def test_dct_alias(self): """ Tests to make sure DCT's have correct string formatting Constructs a DCT and check the format as generated. To insure it matches what is expected @since 3.6.0 @jira_ticket PYTHON-579 @expected_result DCT subtypes should always have fully qualified names @test_category metadata """ self.session.execute("CREATE TABLE {0}.{1} (" "k int PRIMARY KEY," "c1 'DynamicCompositeType(s => UTF8Type, i => Int32Type)'," "c2 Text)".format(self.ks_name, self.function_table_name)) dct_table = self.cluster.metadata.keyspaces.get(self.ks_name).tables.get(self.function_table_name) # Format can very slightly between versions, strip out whitespace for consistency sake - self.assertTrue("c1'org.apache.cassandra.db.marshal.DynamicCompositeType(" - "s=>org.apache.cassandra.db.marshal.UTF8Type," - "i=>org.apache.cassandra.db.marshal.Int32Type)'" - in dct_table.as_cql_query().replace(" ", "")) + table_text = dct_table.as_cql_query().replace(" ", "") + dynamic_type_text = "c1'org.apache.cassandra.db.marshal.DynamicCompositeType(" + self.assertIn("c1'org.apache.cassandra.db.marshal.DynamicCompositeType(", table_text) + # Types within in the composite can come out in random order, so grab the type definition and find each one + type_definition_start = table_text.index("(", table_text.find(dynamic_type_text)) + type_definition_end = table_text.index(")") + type_definition_text = table_text[type_definition_start:type_definition_end] + self.assertIn("s=>org.apache.cassandra.db.marshal.UTF8Type", type_definition_text) + self.assertIn("i=>org.apache.cassandra.db.marshal.Int32Type", type_definition_text) @greaterthanorequalcass30 -class Materia3lizedViewMetadataTestSimple(BasicSharedKeyspaceUnitTestCase): +class MaterializedViewMetadataTestSimple(BasicSharedKeyspaceUnitTestCase): def setUp(self): self.session.execute("CREATE TABLE {0}.{1} (pk int PRIMARY KEY, c int)".format(self.keyspace_name, self.function_table_name)) - self.session.execute("CREATE MATERIALIZED VIEW {0}.mv1 AS SELECT c FROM {0}.{1} WHERE c IS NOT NULL PRIMARY KEY (pk, c)".format(self.keyspace_name, self.function_table_name)) + self.session.execute( + "CREATE MATERIALIZED VIEW {0}.mv1 AS SELECT pk, c FROM {0}.{1} " + "WHERE pk IS NOT NULL AND c IS NOT NULL PRIMARY KEY (pk, c)".format( + self.keyspace_name, self.function_table_name) + ) def tearDown(self): self.session.execute("DROP MATERIALIZED VIEW {0}.mv1".format(self.keyspace_name)) self.session.execute("DROP TABLE {0}.{1}".format(self.keyspace_name, self.function_table_name)) def test_materialized_view_metadata_creation(self): """ test for materialized view metadata creation test_materialized_view_metadata_creation tests that materialized view metadata properly created implicitly in both keyspace and table metadata under "views". It creates a simple base table and then creates a view based on that table. It then checks that the materialized view metadata is contained in the keyspace and table metadata. Finally, it checks that the keyspace_name and the base_table_name in the view metadata is properly set. @since 3.0.0 @jira_ticket PYTHON-371 @expected_result Materialized view metadata in both the ks and table should be created with a new view is created. @test_category metadata """ self.assertIn("mv1", self.cluster.metadata.keyspaces[self.keyspace_name].views) self.assertIn("mv1", self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views) self.assertEqual(self.keyspace_name, self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views["mv1"].keyspace_name) self.assertEqual(self.function_table_name, self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views["mv1"].base_table_name) def test_materialized_view_metadata_alter(self): """ test for materialized view metadata alteration test_materialized_view_metadata_alter tests that materialized view metadata is properly updated implicitly in the table metadata once that view is updated. It creates a simple base table and then creates a view based on that table. It then alters that materalized view and checks that the materialized view metadata is altered in the table metadata. @since 3.0.0 @jira_ticket PYTHON-371 @expected_result Materialized view metadata should be updated with the view is altered. @test_category metadata """ self.assertIn("SizeTieredCompactionStrategy", self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views["mv1"].options["compaction"]["class"]) self.session.execute("ALTER MATERIALIZED VIEW {0}.mv1 WITH compaction = {{ 'class' : 'LeveledCompactionStrategy' }}".format(self.keyspace_name)) self.assertIn("LeveledCompactionStrategy", self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views["mv1"].options["compaction"]["class"]) def test_materialized_view_metadata_drop(self): """ test for materialized view metadata dropping test_materialized_view_metadata_drop tests that materialized view metadata is properly removed implicitly in both keyspace and table metadata once that view is dropped. It creates a simple base table and then creates a view based on that table. It then drops that materalized view and checks that the materialized view metadata is removed from the keyspace and table metadata. @since 3.0.0 @jira_ticket PYTHON-371 @expected_result Materialized view metadata in both the ks and table should be removed with the view is dropped. @test_category metadata """ self.session.execute("DROP MATERIALIZED VIEW {0}.mv1".format(self.keyspace_name)) self.assertNotIn("mv1", self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views) self.assertNotIn("mv1", self.cluster.metadata.keyspaces[self.keyspace_name].views) self.assertDictEqual({}, self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].views) self.assertDictEqual({}, self.cluster.metadata.keyspaces[self.keyspace_name].views) - self.session.execute("CREATE MATERIALIZED VIEW {0}.mv1 AS SELECT c FROM {0}.{1} WHERE c IS NOT NULL PRIMARY KEY (pk, c)".format(self.keyspace_name, self.function_table_name)) + self.session.execute( + "CREATE MATERIALIZED VIEW {0}.mv1 AS SELECT pk, c FROM {0}.{1} " + "WHERE pk IS NOT NULL AND c IS NOT NULL PRIMARY KEY (pk, c)".format( + self.keyspace_name, self.function_table_name) + ) @greaterthanorequalcass30 class MaterializedViewMetadataTestComplex(BasicSegregatedKeyspaceUnitTestCase): def test_create_view_metadata(self): """ test to ensure that materialized view metadata is properly constructed test_create_view_metadata tests that materialized views metadata is properly constructed. It runs a simple query to construct a materialized view, then proceeds to inspect the metadata associated with that MV. Columns are inspected to insure that all are of the proper type, and in the proper type. @since 3.0.0 @jira_ticket PYTHON-371 @expected_result Materialized view metadata should be constructed appropriately. @test_category metadata """ create_table = """CREATE TABLE {0}.scores( user TEXT, game TEXT, year INT, month INT, day INT, score INT, PRIMARY KEY (user, game, year, month, day) )""".format(self.keyspace_name) self.session.execute(create_table) create_mv = """CREATE MATERIALIZED VIEW {0}.monthlyhigh AS SELECT game, year, month, score, user, day FROM {0}.scores WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL PRIMARY KEY ((game, year, month), score, user, day) WITH CLUSTERING ORDER BY (score DESC, user ASC, day ASC)""".format(self.keyspace_name) self.session.execute(create_mv) score_table = self.cluster.metadata.keyspaces[self.keyspace_name].tables['scores'] mv = self.cluster.metadata.keyspaces[self.keyspace_name].views['monthlyhigh'] self.assertIsNotNone(score_table.views["monthlyhigh"]) self.assertIsNotNone(len(score_table.views), 1) # Make sure user is a partition key, and not null self.assertEqual(len(score_table.partition_key), 1) self.assertIsNotNone(score_table.columns['user']) self.assertTrue(score_table.columns['user'], score_table.partition_key[0]) # Validate clustering keys self.assertEqual(len(score_table.clustering_key), 4) self.assertIsNotNone(score_table.columns['game']) self.assertTrue(score_table.columns['game'], score_table.clustering_key[0]) self.assertIsNotNone(score_table.columns['year']) self.assertTrue(score_table.columns['year'], score_table.clustering_key[1]) self.assertIsNotNone(score_table.columns['month']) self.assertTrue(score_table.columns['month'], score_table.clustering_key[2]) self.assertIsNotNone(score_table.columns['day']) self.assertTrue(score_table.columns['day'], score_table.clustering_key[3]) self.assertIsNotNone(score_table.columns['score']) # Validate basic mv information self.assertEqual(mv.keyspace_name, self.keyspace_name) self.assertEqual(mv.name, "monthlyhigh") self.assertEqual(mv.base_table_name, "scores") self.assertFalse(mv.include_all_columns) # Validate that all columns are preset and correct mv_columns = list(mv.columns.values()) self.assertEqual(len(mv_columns), 6) game_column = mv_columns[0] self.assertIsNotNone(game_column) self.assertEqual(game_column.name, 'game') self.assertEqual(game_column, mv.partition_key[0]) year_column = mv_columns[1] self.assertIsNotNone(year_column) self.assertEqual(year_column.name, 'year') self.assertEqual(year_column, mv.partition_key[1]) month_column = mv_columns[2] self.assertIsNotNone(month_column) self.assertEqual(month_column.name, 'month') self.assertEqual(month_column, mv.partition_key[2]) def compare_columns(a, b, name): self.assertEqual(a.name, name) self.assertEqual(a.name, b.name) self.assertEqual(a.table, b.table) self.assertEqual(a.cql_type, b.cql_type) self.assertEqual(a.is_static, b.is_static) self.assertEqual(a.is_reversed, b.is_reversed) score_column = mv_columns[3] compare_columns(score_column, mv.clustering_key[0], 'score') user_column = mv_columns[4] compare_columns(user_column, mv.clustering_key[1], 'user') day_column = mv_columns[5] compare_columns(day_column, mv.clustering_key[2], 'day') def test_base_table_column_addition_mv(self): """ test to ensure that materialized view metadata is properly updated with base columns are added test_create_view_metadata tests that materialized views metadata is properly updated when columns are added to the base table. @since 3.0.0 @jira_ticket PYTHON-419 @expected_result Materialized view metadata should be updated correctly @test_category metadata """ create_table = """CREATE TABLE {0}.scores( user TEXT, game TEXT, year INT, month INT, day INT, score TEXT, PRIMARY KEY (user, game, year, month, day) )""".format(self.keyspace_name) self.session.execute(create_table) create_mv = """CREATE MATERIALIZED VIEW {0}.monthlyhigh AS SELECT game, year, month, score, user, day FROM {0}.scores WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL PRIMARY KEY ((game, year, month), score, user, day) WITH CLUSTERING ORDER BY (score DESC, user ASC, day ASC)""".format(self.keyspace_name) create_mv_alltime = """CREATE MATERIALIZED VIEW {0}.alltimehigh AS SELECT * FROM {0}.scores WHERE game IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND day IS NOT NULL PRIMARY KEY (game, score, user, year, month, day) - WITH CLUSTERING ORDER BY (score DESC)""".format(self.keyspace_name) + WITH CLUSTERING ORDER BY (score DESC, user ASC, year ASC, month ASC, day ASC)""".format(self.keyspace_name) self.session.execute(create_mv) self.session.execute(create_mv_alltime) score_table = self.cluster.metadata.keyspaces[self.keyspace_name].tables['scores'] self.assertIsNotNone(score_table.views["monthlyhigh"]) self.assertIsNotNone(score_table.views["alltimehigh"]) self.assertEqual(len(self.cluster.metadata.keyspaces[self.keyspace_name].views), 2) insert_fouls = """ALTER TABLE {0}.scores ADD fouls INT""".format((self.keyspace_name)) self.session.execute(insert_fouls) self.assertEqual(len(self.cluster.metadata.keyspaces[self.keyspace_name].views), 2) score_table = self.cluster.metadata.keyspaces[self.keyspace_name].tables['scores'] self.assertIn("fouls", score_table.columns) # This is a workaround for mv notifications being separate from base table schema responses. # This maybe fixed with future protocol changes for i in range(10): mv_alltime = self.cluster.metadata.keyspaces[self.keyspace_name].views["alltimehigh"] if("fouls" in mv_alltime.columns): break time.sleep(.2) self.assertIn("fouls", mv_alltime.columns) mv_alltime_fouls_comumn = self.cluster.metadata.keyspaces[self.keyspace_name].views["alltimehigh"].columns['fouls'] self.assertEqual(mv_alltime_fouls_comumn.cql_type, 'int') @lessthancass30 def test_base_table_type_alter_mv(self): """ test to ensure that materialized view metadata is properly updated when a type in the base table is updated. test_create_view_metadata tests that materialized views metadata is properly updated when the type of base table column is changed. + Support for alter type was removed in CASSANDRA-12443 + @since 3.0.0 @jira_ticket CASSANDRA-10424 @expected_result Materialized view metadata should be updated correctly @test_category metadata """ create_table = """CREATE TABLE {0}.scores( user TEXT, game TEXT, year INT, month INT, day INT, score TEXT, PRIMARY KEY (user, game, year, month, day) )""".format(self.keyspace_name) self.session.execute(create_table) create_mv = """CREATE MATERIALIZED VIEW {0}.monthlyhigh AS SELECT game, year, month, score, user, day FROM {0}.scores WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL PRIMARY KEY ((game, year, month), score, user, day) WITH CLUSTERING ORDER BY (score DESC, user ASC, day ASC)""".format(self.keyspace_name) self.session.execute(create_mv) self.assertEqual(len(self.cluster.metadata.keyspaces[self.keyspace_name].views), 1) alter_scores = """ALTER TABLE {0}.scores ALTER score TYPE blob""".format((self.keyspace_name)) self.session.execute(alter_scores) self.assertEqual(len(self.cluster.metadata.keyspaces[self.keyspace_name].views), 1) score_column = self.cluster.metadata.keyspaces[self.keyspace_name].tables['scores'].columns['score'] self.assertEqual(score_column.cql_type, 'blob') # until CASSANDRA-9920+CASSANDRA-10500 MV updates are only available later with an async event for i in range(10): score_mv_column = self.cluster.metadata.keyspaces[self.keyspace_name].views["monthlyhigh"].columns['score'] if "blob" == score_mv_column.cql_type: break time.sleep(.2) self.assertEqual(score_mv_column.cql_type, 'blob') def test_metadata_with_quoted_identifiers(self): """ test to ensure that materialized view metadata is properly constructed when quoted identifiers are used test_metadata_with_quoted_identifiers tests that materialized views metadata is properly constructed. It runs a simple query to construct a materialized view, then proceeds to inspect the metadata associated with that MV. The caveat here is that the tables and the materialized view both have quoted identifiers Columns are inspected to insure that all are of the proper type, and in the proper type. @since 3.0.0 @jira_ticket PYTHON-371 @expected_result Materialized view metadata should be constructed appropriately even with quoted identifiers. @test_category metadata """ create_table = """CREATE TABLE {0}.t1 ( "theKey" int, "the;Clustering" int, "the Value" int, PRIMARY KEY ("theKey", "the;Clustering"))""".format(self.keyspace_name) self.session.execute(create_table) create_mv = """CREATE MATERIALIZED VIEW {0}.mv1 AS SELECT "theKey", "the;Clustering", "the Value" FROM {0}.t1 WHERE "theKey" IS NOT NULL AND "the;Clustering" IS NOT NULL AND "the Value" IS NOT NULL PRIMARY KEY ("theKey", "the;Clustering")""".format(self.keyspace_name) self.session.execute(create_mv) t1_table = self.cluster.metadata.keyspaces[self.keyspace_name].tables['t1'] mv = self.cluster.metadata.keyspaces[self.keyspace_name].views['mv1'] self.assertIsNotNone(t1_table.views["mv1"]) self.assertIsNotNone(len(t1_table.views), 1) # Validate partition key, and not null self.assertEqual(len(t1_table.partition_key), 1) self.assertIsNotNone(t1_table.columns['theKey']) self.assertTrue(t1_table.columns['theKey'], t1_table.partition_key[0]) # Validate clustering key column self.assertEqual(len(t1_table.clustering_key), 1) self.assertIsNotNone(t1_table.columns['the;Clustering']) self.assertTrue(t1_table.columns['the;Clustering'], t1_table.clustering_key[0]) # Validate regular column self.assertIsNotNone(t1_table.columns['the Value']) # Validate basic mv information self.assertEqual(mv.keyspace_name, self.keyspace_name) self.assertEqual(mv.name, "mv1") self.assertEqual(mv.base_table_name, "t1") self.assertFalse(mv.include_all_columns) # Validate that all columns are preset and correct mv_columns = list(mv.columns.values()) self.assertEqual(len(mv_columns), 3) theKey_column = mv_columns[0] self.assertIsNotNone(theKey_column) self.assertEqual(theKey_column.name, 'theKey') self.assertEqual(theKey_column, mv.partition_key[0]) cluster_column = mv_columns[1] self.assertIsNotNone(cluster_column) self.assertEqual(cluster_column.name, 'the;Clustering') self.assertEqual(cluster_column.name, mv.clustering_key[0].name) self.assertEqual(cluster_column.table, mv.clustering_key[0].table) self.assertEqual(cluster_column.is_static, mv.clustering_key[0].is_static) self.assertEqual(cluster_column.is_reversed, mv.clustering_key[0].is_reversed) value_column = mv_columns[2] self.assertIsNotNone(value_column) self.assertEqual(value_column.name, 'the Value') + @greaterthanorequaldse51 + def test_dse_workloads(self): + """ + Test to ensure dse_workloads is populated appropriately. + Field added in DSE 5.1 + + @jira_ticket PYTHON-667 + @expected_result dse_workloads set is set on host model + + @test_category metadata + """ + for host in self.cluster.metadata.all_hosts(): + self.assertIsInstance(host.dse_workloads, SortedSet) + self.assertIn("Cassandra", host.dse_workloads) + class GroupPerHost(BasicSharedKeyspaceUnitTestCase): @classmethod def setUpClass(cls): cls.common_setup(rf=1, create_class_table=True) cls.table_two_pk = "table_with_two_pk" cls.session.execute( ''' CREATE TABLE {0}.{1} ( k_one int, k_two int, v int, PRIMARY KEY ((k_one, k_two)) )'''.format(cls.ks_name, cls.table_two_pk) ) def test_group_keys_by_host(self): """ Test to ensure group_keys_by_host functions as expected. It is tried with a table with a single field for the partition key and a table with two fields for the partition key @since 3.13 @jira_ticket PYTHON-647 @expected_result group_keys_by_host return the expected value @test_category metadata """ stmt = """SELECT * FROM {}.{} WHERE k_one = ? AND k_two = ? """.format(self.ks_name, self.table_two_pk) keys = ((1, 2), (2, 2), (2, 3), (3, 4)) self._assert_group_keys_by_host(keys, self.table_two_pk, stmt) stmt = """SELECT * FROM {}.{} WHERE k = ? """.format(self.ks_name, self.ks_name) keys = ((1,), (2,), (2,), (3,)) self._assert_group_keys_by_host(keys, self.ks_name, stmt) def _assert_group_keys_by_host(self, keys, table_name, stmt): keys_per_host = group_keys_by_replica(self.session, self.ks_name, table_name, keys) self.assertNotIn(NO_VALID_REPLICA, keys_per_host) prepared_stmt = self.session.prepare(stmt) for key in keys: routing_key = prepared_stmt.bind(key).routing_key hosts = self.cluster.metadata.get_replicas(self.ks_name, routing_key) self.assertEqual(1, len(hosts)) # RF is 1 for this keyspace self.assertIn(key, keys_per_host[hosts[0]]) class VirtualKeypaceTest(BasicSharedKeyspaceUnitTestCase): virtual_ks_names = ('system_virtual_schema', 'system_views') - virtual_ks_structure = { - 'system_views': { - # map from table names to sets of column names for unordered - # comparison - 'caches': {'capacity_bytes', 'entry_count', 'hit_count', - 'hit_ratio', 'name', 'recent_hit_rate_per_second', - 'recent_request_rate_per_second', 'request_count', - 'size_bytes'}, - 'clients': {'address', 'connection_stage', 'driver_name', - 'driver_version', 'hostname', 'port', - 'protocol_version', 'request_count', - 'ssl_cipher_suite', 'ssl_enabled', 'ssl_protocol', - 'username'}, - 'sstable_tasks': {'keyspace_name', 'kind', 'progress', - 'table_name', 'task_id', 'total', 'unit'}, - 'thread_pools': {'active_tasks', 'active_tasks_limit', - 'blocked_tasks', 'blocked_tasks_all_time', - 'completed_tasks', 'name', 'pending_tasks'} - }, - 'system_virtual_schema': { - 'columns': {'clustering_order', 'column_name', - 'column_name_bytes', 'keyspace_name', 'kind', - 'position', 'table_name', 'type'}, - 'keyspaces': {'keyspace_name'}, - 'tables': {'comment', 'keyspace_name', 'table_name'} - } - } - def test_existing_keyspaces_have_correct_virtual_tags(self): for name, ks in self.cluster.metadata.keyspaces.items(): if name in self.virtual_ks_names: self.assertTrue( ks.virtual, 'incorrect .virtual value for {}'.format(name) ) else: self.assertFalse( ks.virtual, 'incorrect .virtual value for {}'.format(name) ) @greaterthanorequalcass40 + @greaterthanorequaldse67 def test_expected_keyspaces_exist_and_are_virtual(self): for name in self.virtual_ks_names: self.assertTrue( self.cluster.metadata.keyspaces[name].virtual, 'incorrect .virtual value for {}'.format(name) ) @greaterthanorequalcass40 + @greaterthanorequaldse67 def test_virtual_keyspaces_have_expected_schema_structure(self): self.maxDiff = None ingested_virtual_ks_structure = defaultdict(dict) for ks_name, ks in self.cluster.metadata.keyspaces.items(): if not ks.virtual: continue for tab_name, tab in ks.tables.items(): ingested_virtual_ks_structure[ks_name][tab_name] = set( tab.columns.keys() ) - self.assertDictEqual(ingested_virtual_ks_structure, - self.virtual_ks_structure) + # Identify a couple known values to verify we parsed the structure correctly + self.assertIn('table_name', ingested_virtual_ks_structure['system_virtual_schema']['tables']) + self.assertIn('type', ingested_virtual_ks_structure['system_virtual_schema']['columns']) + self.assertIn('total', ingested_virtual_ks_structure['system_views']['sstable_tasks']) diff --git a/tests/integration/standard/test_metrics.py b/tests/integration/standard/test_metrics.py index d40a66f..676a534 100644 --- a/tests/integration/standard/test_metrics.py +++ b/tests/integration/standard/test_metrics.py @@ -1,386 +1,406 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from cassandra.connection import ConnectionShutdown from cassandra.policies import HostFilterPolicy, RoundRobinPolicy, FallthroughRetryPolicy try: import unittest2 as unittest except ImportError: import unittest # noqa from cassandra.query import SimpleStatement from cassandra import ConsistencyLevel, WriteTimeout, Unavailable, ReadTimeout from cassandra.protocol import SyntaxException -from cassandra.cluster import Cluster, NoHostAvailable -from tests.integration import get_cluster, get_node, use_singledc, PROTOCOL_VERSION, execute_until_pass +from cassandra.cluster import NoHostAvailable, ExecutionProfile, EXEC_PROFILE_DEFAULT +from tests.integration import get_cluster, get_node, use_singledc, execute_until_pass, TestCluster from greplin import scales from tests.integration import BasicSharedKeyspaceUnitTestCaseRF3WM, BasicExistingKeyspaceUnitTestCase, local +import pprint as pp + + def setup_module(): use_singledc() @local class MetricsTests(unittest.TestCase): def setUp(self): contact_point = ['127.0.0.2'] - self.cluster = Cluster(contact_points=contact_point, metrics_enabled=True, protocol_version=PROTOCOL_VERSION, - load_balancing_policy=HostFilterPolicy( - RoundRobinPolicy(), lambda host: host.address in contact_point - ), - default_retry_policy=FallthroughRetryPolicy()) + self.cluster = TestCluster(contact_points=contact_point, metrics_enabled=True, + execution_profiles= + {EXEC_PROFILE_DEFAULT: + ExecutionProfile( + load_balancing_policy=HostFilterPolicy( + RoundRobinPolicy(), lambda host: host.address in contact_point), + retry_policy=FallthroughRetryPolicy() + ) + } + ) self.session = self.cluster.connect("test3rf", wait_for_all_pools=True) def tearDown(self): self.cluster.shutdown() def test_connection_error(self): """ Trigger and ensure connection_errors are counted Stop all node with the driver knowing about the "DOWN" states. """ # Test writes for i in range(0, 100): self.session.execute_async("INSERT INTO test (k, v) VALUES ({0}, {1})".format(i, i)) # Stop the cluster get_cluster().stop(wait=True, gently=False) try: # Ensure the nodes are actually down query = SimpleStatement("SELECT * FROM test", consistency_level=ConsistencyLevel.ALL) # both exceptions can happen depending on when the connection has been detected as defunct with self.assertRaises((NoHostAvailable, ConnectionShutdown)): self.session.execute(query) finally: get_cluster().start(wait_for_binary_proto=True, wait_other_notice=True) # Give some time for the cluster to come back up, for the next test time.sleep(5) self.assertGreater(self.cluster.metrics.stats.connection_errors, 0) def test_write_timeout(self): """ Trigger and ensure write_timeouts are counted Write a key, value pair. Pause a node without the coordinator node knowing about the "DOWN" state. Attempt a write at cl.ALL and receive a WriteTimeout. """ # Test write self.session.execute("INSERT INTO test (k, v) VALUES (1, 1)") # Assert read query = SimpleStatement("SELECT * FROM test WHERE k=1", consistency_level=ConsistencyLevel.ALL) results = execute_until_pass(self.session, query) self.assertTrue(results) # Pause node so it shows as unreachable to coordinator get_node(1).pause() try: # Test write query = SimpleStatement("INSERT INTO test (k, v) VALUES (2, 2)", consistency_level=ConsistencyLevel.ALL) with self.assertRaises(WriteTimeout): self.session.execute(query, timeout=None) self.assertEqual(1, self.cluster.metrics.stats.write_timeouts) finally: get_node(1).resume() def test_read_timeout(self): """ Trigger and ensure read_timeouts are counted Write a key, value pair. Pause a node without the coordinator node knowing about the "DOWN" state. Attempt a read at cl.ALL and receive a ReadTimeout. """ # Test write self.session.execute("INSERT INTO test (k, v) VALUES (1, 1)") # Assert read query = SimpleStatement("SELECT * FROM test WHERE k=1", consistency_level=ConsistencyLevel.ALL) results = execute_until_pass(self.session, query) self.assertTrue(results) # Pause node so it shows as unreachable to coordinator get_node(1).pause() try: # Test read query = SimpleStatement("SELECT * FROM test", consistency_level=ConsistencyLevel.ALL) with self.assertRaises(ReadTimeout): self.session.execute(query, timeout=None) self.assertEqual(1, self.cluster.metrics.stats.read_timeouts) finally: get_node(1).resume() def test_unavailable(self): """ Trigger and ensure unavailables are counted Write a key, value pair. Stop a node with the coordinator node knowing about the "DOWN" state. Attempt an insert/read at cl.ALL and receive a Unavailable Exception. """ # Test write self.session.execute("INSERT INTO test (k, v) VALUES (1, 1)") # Assert read query = SimpleStatement("SELECT * FROM test WHERE k=1", consistency_level=ConsistencyLevel.ALL) results = execute_until_pass(self.session, query) self.assertTrue(results) # Stop node gracefully # Sometimes this commands continues with the other nodes having not noticed # 1 is down, and a Timeout error is returned instead of an Unavailable get_node(1).stop(wait=True, wait_other_notice=True) time.sleep(5) try: # Test write query = SimpleStatement("INSERT INTO test (k, v) VALUES (2, 2)", consistency_level=ConsistencyLevel.ALL) with self.assertRaises(Unavailable): self.session.execute(query) self.assertEqual(self.cluster.metrics.stats.unavailables, 1) # Test write query = SimpleStatement("SELECT * FROM test", consistency_level=ConsistencyLevel.ALL) with self.assertRaises(Unavailable): self.session.execute(query, timeout=None) self.assertEqual(self.cluster.metrics.stats.unavailables, 2) finally: get_node(1).start(wait_other_notice=True, wait_for_binary_proto=True) # Give some time for the cluster to come back up, for the next test time.sleep(5) self.cluster.shutdown() # def test_other_error(self): # # TODO: Bootstrapping or Overloaded cases # pass # # def test_ignore(self): # # TODO: Look for ways to generate ignores # pass # # def test_retry(self): # # TODO: Look for ways to generate retries # pass class MetricsNamespaceTest(BasicSharedKeyspaceUnitTestCaseRF3WM): @local def test_metrics_per_cluster(self): """ Test to validate that metrics can be scopped to invdividual clusters @since 3.6.0 @jira_ticket PYTHON-561 @expected_result metrics should be scopped to a cluster level @test_category metrics """ - cluster2 = Cluster(metrics_enabled=True, protocol_version=PROTOCOL_VERSION, - default_retry_policy=FallthroughRetryPolicy()) + cluster2 = TestCluster( + metrics_enabled=True, + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(retry_policy=FallthroughRetryPolicy())} + ) cluster2.connect(self.ks_name, wait_for_all_pools=True) self.assertEqual(len(cluster2.metadata.all_hosts()), 3) query = SimpleStatement("SELECT * FROM {0}.{0}".format(self.ks_name), consistency_level=ConsistencyLevel.ALL) self.session.execute(query) # Pause node so it shows as unreachable to coordinator get_node(1).pause() try: # Test write query = SimpleStatement("INSERT INTO {0}.{0} (k, v) VALUES (2, 2)".format(self.ks_name), consistency_level=ConsistencyLevel.ALL) with self.assertRaises(WriteTimeout): self.session.execute(query, timeout=None) finally: get_node(1).resume() # Change the scales stats_name of the cluster2 cluster2.metrics.set_stats_name('cluster2-metrics') stats_cluster1 = self.cluster.metrics.get_stats() stats_cluster2 = cluster2.metrics.get_stats() # Test direct access to stats self.assertEqual(1, self.cluster.metrics.stats.write_timeouts) self.assertEqual(0, cluster2.metrics.stats.write_timeouts) # Test direct access to a child stats self.assertNotEqual(0.0, self.cluster.metrics.request_timer['mean']) self.assertEqual(0.0, cluster2.metrics.request_timer['mean']) # Test access via metrics.get_stats() self.assertNotEqual(0.0, stats_cluster1['request_timer']['mean']) self.assertEqual(0.0, stats_cluster2['request_timer']['mean']) # Test access by stats_name self.assertEqual(0.0, scales.getStats()['cluster2-metrics']['request_timer']['mean']) cluster2.shutdown() def test_duplicate_metrics_per_cluster(self): """ Test to validate that cluster metrics names can't overlap. @since 3.6.0 @jira_ticket PYTHON-561 @expected_result metric names should not be allowed to be same. @test_category metrics """ - cluster2 = Cluster(metrics_enabled=True, protocol_version=PROTOCOL_VERSION, - default_retry_policy=FallthroughRetryPolicy()) - - cluster3 = Cluster(metrics_enabled=True, protocol_version=PROTOCOL_VERSION, - default_retry_policy=FallthroughRetryPolicy()) + cluster2 = TestCluster( + metrics_enabled=True, + monitor_reporting_enabled=False, + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(retry_policy=FallthroughRetryPolicy())} + ) + + cluster3 = TestCluster( + metrics_enabled=True, + monitor_reporting_enabled=False, + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(retry_policy=FallthroughRetryPolicy())} + ) # Ensure duplicate metric names are not allowed cluster2.metrics.set_stats_name("appcluster") cluster2.metrics.set_stats_name("appcluster") with self.assertRaises(ValueError): cluster3.metrics.set_stats_name("appcluster") cluster3.metrics.set_stats_name("devops") session2 = cluster2.connect(self.ks_name, wait_for_all_pools=True) session3 = cluster3.connect(self.ks_name, wait_for_all_pools=True) # Basic validation that naming metrics doesn't impact their segration or accuracy for i in range(10): query = SimpleStatement("SELECT * FROM {0}.{0}".format(self.ks_name), consistency_level=ConsistencyLevel.ALL) session2.execute(query) for i in range(5): query = SimpleStatement("SELECT * FROM {0}.{0}".format(self.ks_name), consistency_level=ConsistencyLevel.ALL) session3.execute(query) self.assertEqual(cluster2.metrics.get_stats()['request_timer']['count'], 10) self.assertEqual(cluster3.metrics.get_stats()['request_timer']['count'], 5) # Check scales to ensure they are appropriately named self.assertTrue("appcluster" in scales._Stats.stats.keys()) self.assertTrue("devops" in scales._Stats.stats.keys()) cluster2.shutdown() cluster3.shutdown() class RequestAnalyzer(object): """ Class used to track request and error counts for a Session. Also computes statistics on encoded request size. """ requests = scales.PmfStat('request size') errors = scales.IntStat('errors') successful = scales.IntStat("success") # Throw exceptions when invoked. throw_on_success = False throw_on_fail = False def __init__(self, session, throw_on_success=False, throw_on_fail=False): scales.init(self, '/request') # each instance will be registered with a session, and receive a callback for each request generated session.add_request_init_listener(self.on_request) self.throw_on_fail = throw_on_fail self.throw_on_success = throw_on_success def on_request(self, rf): # This callback is invoked each time a request is created, on the thread creating the request. # We can use this to count events, or add callbacks rf.add_callbacks(self.on_success, self.on_error, callback_args=(rf,), errback_args=(rf,)) def on_success(self, _, response_future): # future callback on a successful request; just record the size self.requests.addValue(response_future.request_encoded_size) self.successful += 1 if self.throw_on_success: raise AttributeError def on_error(self, _, response_future): # future callback for failed; record size and increment errors self.requests.addValue(response_future.request_encoded_size) self.errors += 1 if self.throw_on_fail: raise AttributeError def remove_ra(self, session): session.remove_request_init_listener(self.on_request) def __str__(self): # just extracting request count from the size stats (which are recorded on all requests) request_sizes = dict(self.requests) count = request_sizes.pop('count') return "%d requests (%d errors)\nRequest size statistics:\n%s" % (count, self.errors, pp.pformat(request_sizes)) class MetricsRequestSize(BasicExistingKeyspaceUnitTestCase): + @classmethod + def setUpClass(cls): + cls.common_setup(1, keyspace_creation=False, monitor_reporting_enabled=False) + def wait_for_count(self, ra, expected_count, error=False): for _ in range(10): if not error: if ra.successful is expected_count: return True else: if ra.errors is expected_count: return True time.sleep(.01) return False def test_metrics_per_cluster(self): """ Test to validate that requests listeners. This test creates a simple metrics based request listener to track request size, it then check to ensure that on_success and on_error methods are invoked appropriately. @since 3.7.0 @jira_ticket PYTHON-284 @expected_result in_error, and on_success should be invoked apropriately @test_category metrics """ ra = RequestAnalyzer(self.session) for _ in range(10): self.session.execute("SELECT release_version FROM system.local") for _ in range(3): try: self.session.execute("nonesense") except SyntaxException: continue self.assertTrue(self.wait_for_count(ra, 10)) self.assertTrue(self.wait_for_count(ra, 3, error=True)) ra.remove_ra(self.session) # Make sure a poorly coded RA doesn't cause issues ra = RequestAnalyzer(self.session, throw_on_success=False, throw_on_fail=True) self.session.execute("SELECT release_version FROM system.local") ra.remove_ra(self.session) RequestAnalyzer(self.session, throw_on_success=True) try: self.session.execute("nonesense") except SyntaxException: pass diff --git a/tests/integration/standard/test_policies.py b/tests/integration/standard/test_policies.py index 5a985e5..24facf4 100644 --- a/tests/integration/standard/test_policies.py +++ b/tests/integration/standard/test_policies.py @@ -1,92 +1,95 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa -from cassandra.cluster import Cluster, ExecutionProfile, ResponseFuture +from cassandra.cluster import ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.policies import HostFilterPolicy, RoundRobinPolicy, SimpleConvictionPolicy, \ WhiteListRoundRobinPolicy from cassandra.pool import Host from cassandra.connection import DefaultEndPoint -from tests.integration import PROTOCOL_VERSION, local, use_singledc +from tests.integration import local, use_singledc, TestCluster from concurrent.futures import wait as wait_futures + def setup_module(): use_singledc() class HostFilterPolicyTests(unittest.TestCase): def test_predicate_changes(self): """ Test to validate host filter reacts correctly when the predicate return a different subset of the hosts HostFilterPolicy @since 3.8 @jira_ticket PYTHON-961 @expected_result the excluded hosts are ignored @test_category policy """ external_event = True contact_point = DefaultEndPoint("127.0.0.1") single_host = {Host(contact_point, SimpleConvictionPolicy)} all_hosts = {Host(DefaultEndPoint("127.0.0.{}".format(i)), SimpleConvictionPolicy) for i in (1, 2, 3)} predicate = lambda host: host.endpoint == contact_point if external_event else True - cluster = Cluster((contact_point,), load_balancing_policy=HostFilterPolicy(RoundRobinPolicy(), - predicate=predicate), - protocol_version=PROTOCOL_VERSION, topology_event_refresh_window=0, - status_event_refresh_window=0) + hfp = ExecutionProfile( + load_balancing_policy=HostFilterPolicy(RoundRobinPolicy(), predicate=predicate) + ) + cluster = TestCluster(contact_points=(contact_point,), execution_profiles={EXEC_PROFILE_DEFAULT: hfp}, + topology_event_refresh_window=0, + status_event_refresh_window=0) session = cluster.connect(wait_for_all_pools=True) queried_hosts = set() for _ in range(10): response = session.execute("SELECT * from system.local") queried_hosts.update(response.response_future.attempted_hosts) self.assertEqual(queried_hosts, single_host) external_event = False futures = session.update_created_pools() wait_futures(futures, timeout=cluster.connect_timeout) queried_hosts = set() for _ in range(10): response = session.execute("SELECT * from system.local") queried_hosts.update(response.response_future.attempted_hosts) self.assertEqual(queried_hosts, all_hosts) class WhiteListRoundRobinPolicyTests(unittest.TestCase): @local def test_only_connects_to_subset(self): only_connect_hosts = {"127.0.0.1", "127.0.0.2"} white_list = ExecutionProfile(load_balancing_policy=WhiteListRoundRobinPolicy(only_connect_hosts)) - cluster = Cluster(execution_profiles={"white_list": white_list}) + cluster = TestCluster(execution_profiles={"white_list": white_list}) #cluster = Cluster(load_balancing_policy=WhiteListRoundRobinPolicy(only_connect_hosts)) session = cluster.connect(wait_for_all_pools=True) queried_hosts = set() for _ in range(10): response = session.execute('SELECT * from system.local', execution_profile="white_list") queried_hosts.update(response.response_future.attempted_hosts) queried_hosts = set(host.address for host in queried_hosts) self.assertEqual(queried_hosts, only_connect_hosts) diff --git a/tests/integration/standard/test_prepared_statements.py b/tests/integration/standard/test_prepared_statements.py index 76073d7..5c79f27 100644 --- a/tests/integration/standard/test_prepared_statements.py +++ b/tests/integration/standard/test_prepared_statements.py @@ -1,587 +1,631 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -from tests.integration import use_singledc, PROTOCOL_VERSION +from tests.integration import use_singledc, PROTOCOL_VERSION, TestCluster try: import unittest2 as unittest except ImportError: import unittest # noqa -from cassandra import InvalidRequest +from cassandra import InvalidRequest, DriverException from cassandra import ConsistencyLevel, ProtocolVersion -from cassandra.cluster import Cluster -from cassandra.query import PreparedStatement, UNSET_VALUE, tuple_factory -from tests.integration import (get_server_versions, greaterthanorequalcass40, - set_default_beta_flag_true, - BasicSharedKeyspaceUnitTestCase) +from cassandra.query import PreparedStatement, UNSET_VALUE +from tests.integration import (get_server_versions, greaterthanorequalcass40, greaterthanorequaldse50, + requirecassandra, BasicSharedKeyspaceUnitTestCase) import logging LOG = logging.getLogger(__name__) + def setup_module(): use_singledc() class PreparedStatementTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.cass_version = get_server_versions() def setUp(self): - self.cluster = Cluster(metrics_enabled=True, protocol_version=PROTOCOL_VERSION, - allow_beta_protocol_version=True) + self.cluster = TestCluster(metrics_enabled=True, allow_beta_protocol_version=True) self.session = self.cluster.connect() def tearDown(self): self.cluster.shutdown() def test_basic(self): """ Test basic PreparedStatement usage """ self.session.execute( """ DROP KEYSPACE IF EXISTS preparedtests """ ) self.session.execute( """ CREATE KEYSPACE preparedtests WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} """) self.session.set_keyspace("preparedtests") self.session.execute( """ CREATE TABLE cf0 ( a text, b text, c text, PRIMARY KEY (a, b) ) """) prepared = self.session.prepare( """ INSERT INTO cf0 (a, b, c) VALUES (?, ?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind(('a', 'b', 'c')) self.session.execute(bound) prepared = self.session.prepare( """ SELECT * FROM cf0 WHERE a=? """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind(('a')) results = self.session.execute(bound) self.assertEqual(results, [('a', 'b', 'c')]) # test with new dict binding prepared = self.session.prepare( """ INSERT INTO cf0 (a, b, c) VALUES (?, ?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({ 'a': 'x', 'b': 'y', 'c': 'z' }) self.session.execute(bound) prepared = self.session.prepare( """ SELECT * FROM cf0 WHERE a=? """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({'a': 'x'}) results = self.session.execute(bound) self.assertEqual(results, [('x', 'y', 'z')]) def test_missing_primary_key(self): """ Ensure an InvalidRequest is thrown when prepared statements are missing the primary key """ self._run_missing_primary_key(self.session) def _run_missing_primary_key(self, session): statement_to_prepare = """INSERT INTO test3rf.test (v) VALUES (?)""" # logic needed work with changes in CASSANDRA-6237 if self.cass_version[0] >= (3, 0, 0): self.assertRaises(InvalidRequest, session.prepare, statement_to_prepare) else: prepared = session.prepare(statement_to_prepare) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1,)) self.assertRaises(InvalidRequest, session.execute, bound) def test_missing_primary_key_dicts(self): """ Ensure an InvalidRequest is thrown when prepared statements are missing the primary key with dict bindings """ self._run_missing_primary_key_dicts(self.session) def _run_missing_primary_key_dicts(self, session): statement_to_prepare = """ INSERT INTO test3rf.test (v) VALUES (?)""" # logic needed work with changes in CASSANDRA-6237 if self.cass_version[0] >= (3, 0, 0): self.assertRaises(InvalidRequest, session.prepare, statement_to_prepare) else: prepared = session.prepare(statement_to_prepare) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({'v': 1}) self.assertRaises(InvalidRequest, session.execute, bound) def test_too_many_bind_values(self): """ Ensure a ValueError is thrown when attempting to bind too many variables """ self._run_too_many_bind_values(self.session) def _run_too_many_bind_values(self, session): statement_to_prepare = """ INSERT INTO test3rf.test (v) VALUES (?)""" # logic needed work with changes in CASSANDRA-6237 if self.cass_version[0] >= (3, 0, 0): self.assertRaises(InvalidRequest, session.prepare, statement_to_prepare) else: prepared = session.prepare(statement_to_prepare) self.assertIsInstance(prepared, PreparedStatement) self.assertRaises(ValueError, prepared.bind, (1, 2)) def test_imprecise_bind_values_dicts(self): """ Ensure an error is thrown when attempting to bind the wrong values with dict bindings """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) # too many values is ok - others are ignored prepared.bind({'k': 1, 'v': 2, 'v2': 3}) # right number, but one does not belong if PROTOCOL_VERSION < 4: # pre v4, the driver bails with key error when 'v' is found missing self.assertRaises(KeyError, prepared.bind, {'k': 1, 'v2': 3}) else: # post v4, the driver uses UNSET_VALUE for 'v' and 'v2' is ignored prepared.bind({'k': 1, 'v2': 3}) # also catch too few variables with dicts self.assertIsInstance(prepared, PreparedStatement) if PROTOCOL_VERSION < 4: self.assertRaises(KeyError, prepared.bind, {}) else: # post v4, the driver attempts to use UNSET_VALUE for unspecified keys self.assertRaises(ValueError, prepared.bind, {}) def test_none_values(self): """ Ensure binding None is handled correctly """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, None)) self.session.execute(bound) prepared = self.session.prepare( """ SELECT * FROM test3rf.test WHERE k=? """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1,)) results = self.session.execute(bound) self.assertEqual(results[0].v, None) def test_unset_values(self): """ Test to validate that UNSET_VALUEs are bound, and have the expected effect Prepare a statement and insert all values. Then follow with execute excluding parameters. Verify that the original values are unaffected. @since 2.6.0 @jira_ticket PYTHON-317 @expected_result UNSET_VALUE is implicitly added to bind parameters, and properly encoded, leving unset values unaffected. @test_category prepared_statements:binding """ if PROTOCOL_VERSION < 4: raise unittest.SkipTest("Binding UNSET values is not supported in protocol version < 4") # table with at least two values so one can be used as a marker self.session.execute("CREATE TABLE IF NOT EXISTS test1rf.test_unset_values (k int PRIMARY KEY, v0 int, v1 int)") insert = self.session.prepare("INSERT INTO test1rf.test_unset_values (k, v0, v1) VALUES (?, ?, ?)") select = self.session.prepare("SELECT * FROM test1rf.test_unset_values WHERE k=?") bind_expected = [ # initial condition ((0, 0, 0), (0, 0, 0)), # unset implicit ((0, 1,), (0, 1, 0)), ({'k': 0, 'v0': 2}, (0, 2, 0)), ({'k': 0, 'v1': 1}, (0, 2, 1)), # unset explicit ((0, 3, UNSET_VALUE), (0, 3, 1)), ((0, UNSET_VALUE, 2), (0, 3, 2)), ({'k': 0, 'v0': 4, 'v1': UNSET_VALUE}, (0, 4, 2)), ({'k': 0, 'v0': UNSET_VALUE, 'v1': 3}, (0, 4, 3)), # nulls still work ((0, None, None), (0, None, None)), ] for params, expected in bind_expected: self.session.execute(insert, params) results = self.session.execute(select, (0,)) self.assertEqual(results[0], expected) self.assertRaises(ValueError, self.session.execute, select, (UNSET_VALUE, 0, 0)) def test_no_meta(self): prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (0, 0) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind(None) bound.consistency_level = ConsistencyLevel.ALL self.session.execute(bound) prepared = self.session.prepare( """ SELECT * FROM test3rf.test WHERE k=0 """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind(None) bound.consistency_level = ConsistencyLevel.ALL results = self.session.execute(bound) self.assertEqual(results[0].v, 0) def test_none_values_dicts(self): """ Ensure binding None is handled correctly with dict bindings """ # test with new dict binding prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({'k': 1, 'v': None}) self.session.execute(bound) prepared = self.session.prepare( """ SELECT * FROM test3rf.test WHERE k=? """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({'k': 1}) results = self.session.execute(bound) self.assertEqual(results[0].v, None) def test_async_binding(self): """ Ensure None binding over async queries """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) future = self.session.execute_async(prepared, (873, None)) future.result() prepared = self.session.prepare( """ SELECT * FROM test3rf.test WHERE k=? """) self.assertIsInstance(prepared, PreparedStatement) future = self.session.execute_async(prepared, (873,)) results = future.result() self.assertEqual(results[0].v, None) def test_async_binding_dicts(self): """ Ensure None binding over async queries with dict bindings """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) future = self.session.execute_async(prepared, {'k': 873, 'v': None}) future.result() prepared = self.session.prepare( """ SELECT * FROM test3rf.test WHERE k=? """) self.assertIsInstance(prepared, PreparedStatement) future = self.session.execute_async(prepared, {'k': 873}) results = future.result() self.assertEqual(results[0].v, None) def test_raise_error_on_prepared_statement_execution_dropped_table(self): """ test for error in executing prepared statement on a dropped table test_raise_error_on_execute_prepared_statement_dropped_table tests that an InvalidRequest is raised when a prepared statement is executed after its corresponding table is dropped. This happens because if a prepared statement is invalid, the driver attempts to automatically re-prepare it on a non-existing table. @expected_errors InvalidRequest If a prepared statement is executed on a dropped table @since 2.6.0 @jira_ticket PYTHON-207 @expected_result InvalidRequest error should be raised upon prepared statement execution. @test_category prepared_statements """ self.session.execute("CREATE TABLE test3rf.error_test (k int PRIMARY KEY, v int)") prepared = self.session.prepare("SELECT * FROM test3rf.error_test WHERE k=?") self.session.execute("DROP TABLE test3rf.error_test") with self.assertRaises(InvalidRequest): self.session.execute(prepared, [0]) + def test_fail_if_different_query_id_on_reprepare(self): + """ PYTHON-1124 and CASSANDRA-15252 """ + keyspace = "test_fail_if_different_query_id_on_reprepare" + self.session.execute( + "CREATE KEYSPACE IF NOT EXISTS {} WITH replication = " + "{{'class': 'SimpleStrategy', 'replication_factor': 1}}".format(keyspace) + ) + self.session.execute("CREATE TABLE IF NOT EXISTS {}.foo(k int PRIMARY KEY)".format(keyspace)) + prepared = self.session.prepare("SELECT * FROM {}.foo WHERE k=?".format(keyspace)) + self.session.execute("DROP TABLE {}.foo".format(keyspace)) + self.session.execute("CREATE TABLE {}.foo(k int PRIMARY KEY)".format(keyspace)) + self.session.execute("USE {}".format(keyspace)) + with self.assertRaises(DriverException) as e: + self.session.execute(prepared, [0]) + self.assertIn("ID mismatch", str(e.exception)) + @greaterthanorequalcass40 class PreparedStatementInvalidationTest(BasicSharedKeyspaceUnitTestCase): def setUp(self): self.table_name = "{}.prepared_statement_invalidation_test".format(self.keyspace_name) self.session.execute("CREATE TABLE {} (a int PRIMARY KEY, b int, d int);".format(self.table_name)) self.session.execute("INSERT INTO {} (a, b, d) VALUES (1, 1, 1);".format(self.table_name)) self.session.execute("INSERT INTO {} (a, b, d) VALUES (2, 2, 2);".format(self.table_name)) self.session.execute("INSERT INTO {} (a, b, d) VALUES (3, 3, 3);".format(self.table_name)) self.session.execute("INSERT INTO {} (a, b, d) VALUES (4, 4, 4);".format(self.table_name)) def tearDown(self): self.session.execute("DROP TABLE {}".format(self.table_name)) def test_invalidated_result_metadata(self): """ Tests to make sure cached metadata is updated when an invalidated prepared statement is reprepared. @since 2.7.0 @jira_ticket PYTHON-621 Prior to this fix, the request would blow up with a protocol error when the result was decoded expecting a different number of columns. """ wildcard_prepared = self.session.prepare("SELECT * FROM {}".format(self.table_name)) original_result_metadata = wildcard_prepared.result_metadata self.assertEqual(len(original_result_metadata), 3) r = self.session.execute(wildcard_prepared) self.assertEqual(r[0], (1, 1, 1)) self.session.execute("ALTER TABLE {} DROP d".format(self.table_name)) # Get a bunch of requests in the pipeline with varying states of result_meta, reprepare, resolved futures = set(self.session.execute_async(wildcard_prepared.bind(None)) for _ in range(200)) for f in futures: self.assertEqual(f.result()[0], (1, 1)) self.assertIsNot(wildcard_prepared.result_metadata, original_result_metadata) def test_prepared_id_is_update(self): """ Tests that checks the query id from the prepared statement is updated properly if the table that the prepared statement is querying is altered. @since 3.12 @jira_ticket PYTHON-808 The query id from the prepared statment must have changed """ prepared_statement = self.session.prepare("SELECT * from {} WHERE a = ?".format(self.table_name)) id_before = prepared_statement.result_metadata_id self.assertEqual(len(prepared_statement.result_metadata), 3) self.session.execute("ALTER TABLE {} ADD c int".format(self.table_name)) bound_statement = prepared_statement.bind((1, )) self.session.execute(bound_statement, timeout=1) id_after = prepared_statement.result_metadata_id self.assertNotEqual(id_before, id_after) self.assertEqual(len(prepared_statement.result_metadata), 4) def test_prepared_id_is_updated_across_pages(self): """ Test that checks that the query id from the prepared statement is updated if the table hat the prepared statement is querying is altered while fetching pages in a single query. Then it checks that the updated rows have the expected result. @since 3.12 @jira_ticket PYTHON-808 """ prepared_statement = self.session.prepare("SELECT * from {}".format(self.table_name)) id_before = prepared_statement.result_metadata_id self.assertEqual(len(prepared_statement.result_metadata), 3) prepared_statement.fetch_size = 2 result = self.session.execute(prepared_statement.bind((None))) self.assertTrue(result.has_more_pages) self.session.execute("ALTER TABLE {} ADD c int".format(self.table_name)) result_set = set(x for x in ((1, 1, 1), (2, 2, 2), (3, 3, None, 3), (4, 4, None, 4))) expected_result_set = set(row for row in result) id_after = prepared_statement.result_metadata_id self.assertEqual(result_set, expected_result_set) self.assertNotEqual(id_before, id_after) self.assertEqual(len(prepared_statement.result_metadata), 4) def test_prepare_id_is_updated_across_session(self): """ Test that checks that the query id from the prepared statement is updated if the table hat the prepared statement is querying is altered by a different session @since 3.12 @jira_ticket PYTHON-808 """ - one_cluster = Cluster(metrics_enabled=True, protocol_version=PROTOCOL_VERSION) + one_cluster = TestCluster(metrics_enabled=True) one_session = one_cluster.connect() self.addCleanup(one_cluster.shutdown) stm = "SELECT * from {} WHERE a = ?".format(self.table_name) one_prepared_stm = one_session.prepare(stm) self.assertEqual(len(one_prepared_stm.result_metadata), 3) one_id_before = one_prepared_stm.result_metadata_id self.session.execute("ALTER TABLE {} ADD c int".format(self.table_name)) one_session.execute(one_prepared_stm, (1, )) one_id_after = one_prepared_stm.result_metadata_id self.assertNotEqual(one_id_before, one_id_after) self.assertEqual(len(one_prepared_stm.result_metadata), 4) def test_not_reprepare_invalid_statements(self): """ Test that checks that an InvalidRequest is arisen if a column expected by the prepared statement is dropped. @since 3.12 @jira_ticket PYTHON-808 """ prepared_statement = self.session.prepare( "SELECT a, b, d FROM {} WHERE a = ?".format(self.table_name)) self.session.execute("ALTER TABLE {} DROP d".format(self.table_name)) with self.assertRaises(InvalidRequest): self.session.execute(prepared_statement.bind((1, ))) def test_id_is_not_updated_conditional_v4(self): """ Test that verifies that the result_metadata and the result_metadata_id are udpated correctly in conditional statements in protocol V4 @since 3.13 @jira_ticket PYTHON-847 """ - cluster = Cluster(protocol_version=ProtocolVersion.V4) + cluster = TestCluster(protocol_version=ProtocolVersion.V4) session = cluster.connect() self.addCleanup(cluster.shutdown) self._test_updated_conditional(session, 9) + @requirecassandra def test_id_is_not_updated_conditional_v5(self): """ Test that verifies that the result_metadata and the result_metadata_id are udpated correctly in conditional statements in protocol V5 + @since 3.13 + @jira_ticket PYTHON-847 + """ + cluster = TestCluster(protocol_version=ProtocolVersion.V5) + session = cluster.connect() + self.addCleanup(cluster.shutdown) + self._test_updated_conditional(session, 10) + + @greaterthanorequaldse50 + def test_id_is_not_updated_conditional_dsev1(self): + """ + Test that verifies that the result_metadata and the + result_metadata_id are udpated correctly in conditional statements + in protocol DSE V1 + + @since 3.13 + @jira_ticket PYTHON-847 + """ + cluster = TestCluster(protocol_version=ProtocolVersion.DSE_V1) + session = cluster.connect() + self.addCleanup(cluster.shutdown) + self._test_updated_conditional(session, 10) + + @greaterthanorequaldse50 + def test_id_is_not_updated_conditional_dsev2(self): + """ + Test that verifies that the result_metadata and the + result_metadata_id are udpated correctly in conditional statements + in protocol DSE V2 @since 3.13 @jira_ticket PYTHON-847 """ - cluster = Cluster(protocol_version=ProtocolVersion.V5) + cluster = TestCluster(protocol_version=ProtocolVersion.DSE_V2) session = cluster.connect() self.addCleanup(cluster.shutdown) self._test_updated_conditional(session, 10) def _test_updated_conditional(self, session, value): prepared_statement = session.prepare( "INSERT INTO {}(a, b, d) VALUES " "(?, ? , ?) IF NOT EXISTS".format(self.table_name)) first_id = prepared_statement.result_metadata_id LOG.debug('initial result_metadata_id: {}'.format(first_id)) def check_result_and_metadata(expected): self.assertEqual( session.execute(prepared_statement, (value, value, value))[0], expected ) self.assertEqual(prepared_statement.result_metadata_id, first_id) - self.assertEqual(prepared_statement.result_metadata, []) + self.assertIsNone(prepared_statement.result_metadata) # Successful conditional update check_result_and_metadata((True,)) # Failed conditional update check_result_and_metadata((False, value, value, value)) session.execute("ALTER TABLE {} ADD c int".format(self.table_name)) # Failed conditional update check_result_and_metadata((False, value, value, None, value)) diff --git a/tests/integration/standard/test_query.py b/tests/integration/standard/test_query.py index 97a1e68..ea0e326 100644 --- a/tests/integration/standard/test_query.py +++ b/tests/integration/standard/test_query.py @@ -1,1653 +1,1656 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from cassandra.concurrent import execute_concurrent from cassandra import DriverException try: import unittest2 as unittest except ImportError: import unittest # noqa import logging from cassandra import ProtocolVersion from cassandra import ConsistencyLevel, Unavailable, InvalidRequest, cluster from cassandra.query import (PreparedStatement, BoundStatement, SimpleStatement, BatchStatement, BatchType, dict_factory, TraceUnavailable) -from cassandra.cluster import Cluster, NoHostAvailable, ExecutionProfile, EXEC_PROFILE_DEFAULT +from cassandra.cluster import NoHostAvailable, ExecutionProfile, EXEC_PROFILE_DEFAULT, Cluster from cassandra.policies import HostDistance, RoundRobinPolicy, WhiteListRoundRobinPolicy from tests.integration import use_singledc, PROTOCOL_VERSION, BasicSharedKeyspaceUnitTestCase, \ greaterthanprotocolv3, MockLoggingHandler, get_supported_protocol_versions, local, get_cluster, setup_keyspace, \ - USE_CASS_EXTERNAL, greaterthanorequalcass40 + USE_CASS_EXTERNAL, greaterthanorequalcass40, DSE_VERSION, TestCluster, requirecassandra from tests import notwindows from tests.integration import greaterthanorequalcass30, get_node import time import random import re import mock import six log = logging.getLogger(__name__) def setup_module(): if not USE_CASS_EXTERNAL: use_singledc(start=False) ccm_cluster = get_cluster() ccm_cluster.stop() # This is necessary because test_too_many_statements may # timeout otherwise config_options = {'write_request_timeout_in_ms': '20000'} ccm_cluster.set_configuration_options(config_options) ccm_cluster.start(wait_for_binary_proto=True, wait_other_notice=True) setup_keyspace() class QueryTests(BasicSharedKeyspaceUnitTestCase): def test_query(self): prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """.format(self.keyspace_name)) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, None)) self.assertIsInstance(bound, BoundStatement) self.assertEqual(2, len(bound.values)) self.session.execute(bound) self.assertEqual(bound.routing_key, b'\x00\x00\x00\x01') def test_trace_prints_okay(self): """ Code coverage to ensure trace prints to string without error """ query = "SELECT * FROM system.local" statement = SimpleStatement(query) rs = self.session.execute(statement, trace=True) # Ensure this does not throw an exception trace = rs.get_query_trace() self.assertTrue(trace.events) str(trace) for event in trace.events: str(event) def test_row_error_message(self): """ Test to validate, new column deserialization message @since 3.7.0 @jira_ticket PYTHON-361 @expected_result Special failed decoding message should be present @test_category tracing """ self.session.execute("CREATE TABLE {0}.{1} (k int PRIMARY KEY, v timestamp)".format(self.keyspace_name,self.function_table_name)) ss = SimpleStatement("INSERT INTO {0}.{1} (k, v) VALUES (1, 1000000000000000)".format(self.keyspace_name, self.function_table_name)) self.session.execute(ss) with self.assertRaises(DriverException) as context: self.session.execute("SELECT * FROM {0}.{1}".format(self.keyspace_name, self.function_table_name)) self.assertIn("Failed decoding result column", str(context.exception)) def test_trace_id_to_resultset(self): future = self.session.execute_async("SELECT * FROM system.local", trace=True) # future should have the current trace rs = future.result() future_trace = future.get_query_trace() self.assertIsNotNone(future_trace) rs_trace = rs.get_query_trace() self.assertEqual(rs_trace, future_trace) self.assertTrue(rs_trace.events) self.assertEqual(len(rs_trace.events), len(future_trace.events)) self.assertListEqual([rs_trace], rs.get_all_query_traces()) def test_trace_ignores_row_factory(self): - self.session.row_factory = dict_factory - - query = "SELECT * FROM system.local" - statement = SimpleStatement(query) - rs = self.session.execute(statement, trace=True) - - # Ensure this does not throw an exception - trace = rs.get_query_trace() - self.assertTrue(trace.events) - str(trace) - for event in trace.events: - str(event) + with TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=dict_factory)} + ) as cluster: + s = cluster.connect() + query = "SELECT * FROM system.local" + statement = SimpleStatement(query) + rs = s.execute(statement, trace=True) + + # Ensure this does not throw an exception + trace = rs.get_query_trace() + self.assertTrue(trace.events) + str(trace) + for event in trace.events: + str(event) @local @greaterthanprotocolv3 def test_client_ip_in_trace(self): """ Test to validate that client trace contains client ip information. creates a simple query and ensures that the client trace information is present. This will only be the case if the c* version is 2.2 or greater @since 2.6.0 @jira_ticket PYTHON-435 @expected_result client address should be present in C* >= 2.2, otherwise should be none. @test_category tracing #The current version on the trunk doesn't have the version set to 2.2 yet. #For now we will use the protocol version. Once they update the version on C* trunk #we can use the C*. See below #self._cass_version, self._cql_version = get_server_versions() #if self._cass_version < (2, 2): # raise unittest.SkipTest("Client IP was not present in trace until C* 2.2") """ # Make simple query with trace enabled query = "SELECT * FROM system.local" statement = SimpleStatement(query) response_future = self.session.execute_async(statement, trace=True) response_future.result() # Fetch the client_ip from the trace. trace = response_future.get_query_trace(max_wait=10.0) client_ip = trace.client # Ip address should be in the local_host range pat = re.compile("127.0.0.\d{1,3}") # Ensure that ip is set self.assertIsNotNone(client_ip, "Client IP was not set in trace with C* >= 2.2") self.assertTrue(pat.match(client_ip), "Client IP from trace did not match the expected value") def test_trace_cl(self): """ Test to ensure that CL is set correctly honored when executing trace queries. @since 3.3 @jira_ticket PYTHON-435 @expected_result Consistency Levels set on get_query_trace should be honored """ # Execute a query query = "SELECT * FROM system.local" statement = SimpleStatement(query) response_future = self.session.execute_async(statement, trace=True) response_future.result() with self.assertRaises(Unavailable): response_future.get_query_trace(query_cl=ConsistencyLevel.THREE) # Try again with a smattering of other CL's self.assertIsNotNone(response_future.get_query_trace(max_wait=2.0, query_cl=ConsistencyLevel.TWO).trace_id) response_future = self.session.execute_async(statement, trace=True) response_future.result() self.assertIsNotNone(response_future.get_query_trace(max_wait=2.0, query_cl=ConsistencyLevel.ONE).trace_id) response_future = self.session.execute_async(statement, trace=True) response_future.result() with self.assertRaises(InvalidRequest): self.assertIsNotNone(response_future.get_query_trace(max_wait=2.0, query_cl=ConsistencyLevel.ANY).trace_id) self.assertIsNotNone(response_future.get_query_trace(max_wait=2.0, query_cl=ConsistencyLevel.QUORUM).trace_id) @notwindows def test_incomplete_query_trace(self): """ Tests to ensure that partial tracing works. Creates a table and runs an insert. Then attempt a query with tracing enabled. After the query is run we delete the duration information associated with the trace, and attempt to populate the tracing information. Should fail with wait_for_complete=True, succeed for False. @since 3.0.0 @jira_ticket PYTHON-438 @expected_result tracing comes back sans duration @test_category tracing """ # Create table and run insert, then select self.session.execute("CREATE TABLE {0} (k INT, i INT, PRIMARY KEY(k, i))".format(self.keyspace_table_name)) self.session.execute("INSERT INTO {0} (k, i) VALUES (0, 1)".format(self.keyspace_table_name)) response_future = self.session.execute_async("SELECT i FROM {0} WHERE k=0".format(self.keyspace_table_name), trace=True) response_future.result() self.assertEqual(len(response_future._query_traces), 1) trace = response_future._query_traces[0] self.assertTrue(self._wait_for_trace_to_populate(trace.trace_id)) # Delete trace duration from the session (this is what the driver polls for "complete") delete_statement = SimpleStatement("DELETE duration FROM system_traces.sessions WHERE session_id = {0}".format(trace.trace_id), consistency_level=ConsistencyLevel.ALL) self.session.execute(delete_statement) self.assertTrue(self._wait_for_trace_to_delete(trace.trace_id)) # should raise because duration is not set self.assertRaises(TraceUnavailable, trace.populate, max_wait=0.2, wait_for_complete=True) self.assertFalse(trace.events) # should get the events with wait False trace.populate(wait_for_complete=False) self.assertIsNone(trace.duration) self.assertIsNotNone(trace.trace_id) self.assertIsNotNone(trace.request_type) self.assertIsNotNone(trace.parameters) self.assertTrue(trace.events) # non-zero list len self.assertIsNotNone(trace.started_at) def _wait_for_trace_to_populate(self, trace_id): count = 0 retry_max = 10 while(not self._is_trace_present(trace_id) and count < retry_max): time.sleep(.2) count += 1 return count != retry_max def _wait_for_trace_to_delete(self, trace_id): count = 0 retry_max = 10 while(self._is_trace_present(trace_id) and count < retry_max): time.sleep(.2) count += 1 return count != retry_max def _is_trace_present(self, trace_id): select_statement = SimpleStatement("SElECT duration FROM system_traces.sessions WHERE session_id = {0}".format(trace_id), consistency_level=ConsistencyLevel.ALL) ssrs = self.session.execute(select_statement) if not len(ssrs.current_rows) or ssrs[0].duration is None: return False return True def test_query_by_id(self): """ Test to ensure column_types are set as part of the result set @since 3.8 @jira_ticket PYTHON-648 @expected_result column_names should be preset. @test_category queries basic """ create_table = "CREATE TABLE {0}.{1} (id int primary key, m map)".format(self.keyspace_name, self.function_table_name) self.session.execute(create_table) self.session.execute("insert into "+self.keyspace_name+"."+self.function_table_name+" (id, m) VALUES ( 1, {1: 'one', 2: 'two', 3:'three'})") results1 = self.session.execute("select id, m from {0}.{1}".format(self.keyspace_name, self.function_table_name)) self.assertIsNotNone(results1.column_types) self.assertEqual(results1.column_types[0].typename, 'int') self.assertEqual(results1.column_types[1].typename, 'map') self.assertEqual(results1.column_types[0].cassname, 'Int32Type') self.assertEqual(results1.column_types[1].cassname, 'MapType') self.assertEqual(len(results1.column_types[0].subtypes), 0) self.assertEqual(len(results1.column_types[1].subtypes), 2) self.assertEqual(results1.column_types[1].subtypes[0].typename, "int") self.assertEqual(results1.column_types[1].subtypes[1].typename, "varchar") self.assertEqual(results1.column_types[1].subtypes[0].cassname, "Int32Type") self.assertEqual(results1.column_types[1].subtypes[1].cassname, "VarcharType") def test_column_names(self): """ Test to validate the columns are present on the result set. Preforms a simple query against a table then checks to ensure column names are correct and present and correct. @since 3.0.0 @jira_ticket PYTHON-439 @expected_result column_names should be preset. @test_category queries basic """ create_table = """CREATE TABLE {0}.{1}( user TEXT, game TEXT, year INT, month INT, day INT, score INT, PRIMARY KEY (user, game, year, month, day) )""".format(self.keyspace_name, self.function_table_name) self.session.execute(create_table) result_set = self.session.execute("SELECT * FROM {0}.{1}".format(self.keyspace_name, self.function_table_name)) self.assertIsNotNone(result_set.column_types) self.assertEqual(result_set.column_names, [u'user', u'game', u'year', u'month', u'day', u'score']) @greaterthanorequalcass30 def test_basic_json_query(self): insert_query = SimpleStatement("INSERT INTO test3rf.test(k, v) values (1, 1)", consistency_level = ConsistencyLevel.QUORUM) json_query = SimpleStatement("SELECT JSON * FROM test3rf.test where k=1", consistency_level = ConsistencyLevel.QUORUM) self.session.execute(insert_query) results = self.session.execute(json_query) self.assertEqual(results.column_names, ["[json]"]) self.assertEqual(results[0][0], '{"k": 1, "v": 1}') def test_host_targeting_query(self): """ Test to validate the the single host targeting works. @since 3.17.0 @jira_ticket PYTHON-933 @expected_result the coordinator host is always the one set """ default_ep = self.cluster.profile_manager.default # copy of default EP with checkable LBP checkable_ep = self.session.execution_profile_clone_update( ep=default_ep, load_balancing_policy=mock.Mock(wraps=default_ep.load_balancing_policy) ) query = SimpleStatement("INSERT INTO test3rf.test(k, v) values (1, 1)") for i in range(10): host = random.choice(self.cluster.metadata.all_hosts()) log.debug('targeting {}'.format(host)) future = self.session.execute_async(query, host=host, execution_profile=checkable_ep) future.result() # check we're using the selected host self.assertEqual(host, future.coordinator_host) # check that this bypasses the LBP self.assertFalse(checkable_ep.load_balancing_policy.make_query_plan.called) class PreparedStatementTests(unittest.TestCase): def setUp(self): - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + self.cluster = TestCluster() self.session = self.cluster.connect() def tearDown(self): self.cluster.shutdown() def test_routing_key(self): """ Simple code coverage to ensure routing_keys can be accessed """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, None)) self.assertEqual(bound.routing_key, b'\x00\x00\x00\x01') def test_empty_routing_key_indexes(self): """ Ensure when routing_key_indexes are blank, the routing key should be None """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) prepared.routing_key_indexes = None self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, None)) self.assertEqual(bound.routing_key, None) def test_predefined_routing_key(self): """ Basic test that ensures _set_routing_key() overrides the current routing key """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, None)) bound._set_routing_key('fake_key') self.assertEqual(bound.routing_key, 'fake_key') def test_multiple_routing_key_indexes(self): """ Basic test that uses a fake routing_key_index """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) prepared.routing_key_indexes = [0, 1] bound = prepared.bind((1, 2)) self.assertEqual(bound.routing_key, b'\x00\x04\x00\x00\x00\x01\x00\x00\x04\x00\x00\x00\x02\x00') prepared.routing_key_indexes = [1, 0] bound = prepared.bind((1, 2)) self.assertEqual(bound.routing_key, b'\x00\x04\x00\x00\x00\x02\x00\x00\x04\x00\x00\x00\x01\x00') def test_bound_keyspace(self): """ Ensure that bound.keyspace works as expected """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, 2)) self.assertEqual(bound.keyspace, 'test3rf') class ForcedHostIndexPolicy(RoundRobinPolicy): def __init__(self, host_index_to_use=0): super(ForcedHostIndexPolicy, self).__init__() self.host_index_to_use = host_index_to_use def set_host(self, host_index): """ 0-based index of which host to use """ self.host_index_to_use = host_index def make_query_plan(self, working_keyspace=None, query=None): live_hosts = sorted(list(self._live_hosts)) host = [] try: host = [live_hosts[self.host_index_to_use]] except IndexError as e: six.raise_from(IndexError( 'You specified an index larger than the number of hosts. Total hosts: {}. Index specified: {}'.format( len(live_hosts), self.host_index_to_use )), e) return host class PreparedStatementMetdataTest(unittest.TestCase): def test_prepared_metadata_generation(self): """ Test to validate that result metadata is appropriately populated across protocol version In protocol version 1 result metadata is retrieved everytime the statement is issued. In all other protocol versions it's set once upon the prepare, then re-used. This test ensures that it manifests it's self the same across multiple protocol versions. @since 3.6.0 @jira_ticket PYTHON-71 @expected_result result metadata is consistent. """ base_line = None for proto_version in get_supported_protocol_versions(): beta_flag = True if proto_version in ProtocolVersion.BETA_VERSIONS else False cluster = Cluster(protocol_version=proto_version, allow_beta_protocol_version=beta_flag) session = cluster.connect() select_statement = session.prepare("SELECT * FROM system.local") if proto_version == 1: self.assertEqual(select_statement.result_metadata, None) else: self.assertNotEqual(select_statement.result_metadata, None) future = session.execute_async(select_statement) results = future.result() if base_line is None: base_line = results[0]._asdict().keys() else: self.assertEqual(base_line, results[0]._asdict().keys()) cluster.shutdown() class PreparedStatementArgTest(unittest.TestCase): def setUp(self): self.mock_handler = MockLoggingHandler() logger = logging.getLogger(cluster.__name__) logger.addHandler(self.mock_handler) def test_prepare_on_all_hosts(self): """ Test to validate prepare_on_all_hosts flag is honored. Force the host of each query to ensure prepared queries are cycled over nodes that should not have them prepared. Check the logs to insure they are being re-prepared on those nodes @since 3.4.0 @jira_ticket PYTHON-556 @expected_result queries will have to re-prepared on hosts that aren't the control connection """ - clus = Cluster(protocol_version=PROTOCOL_VERSION, prepare_on_all_hosts=False, reprepare_on_up=False) + clus = TestCluster(prepare_on_all_hosts=False, reprepare_on_up=False) self.addCleanup(clus.shutdown) session = clus.connect(wait_for_all_pools=True) select_statement = session.prepare("SELECT k FROM test3rf.test WHERE k = ?") for host in clus.metadata.all_hosts(): session.execute(select_statement, (1, ), host=host) self.assertEqual(2, self.mock_handler.get_message_count('debug', "Re-preparing")) def test_prepare_batch_statement(self): """ Test to validate a prepared statement used inside a batch statement is correctly handled by the driver @since 3.10 @jira_ticket PYTHON-706 @expected_result queries will have to re-prepared on hosts that aren't the control connection and the batch statement will be sent. """ policy = ForcedHostIndexPolicy() - clus = Cluster( + clus = TestCluster( execution_profiles={ EXEC_PROFILE_DEFAULT: ExecutionProfile(load_balancing_policy=policy), }, - protocol_version=PROTOCOL_VERSION, prepare_on_all_hosts=False, reprepare_on_up=False, ) self.addCleanup(clus.shutdown) table = "test3rf.%s" % self._testMethodName.lower() session = clus.connect(wait_for_all_pools=True) session.execute("DROP TABLE IF EXISTS %s" % table) session.execute("CREATE TABLE %s (k int PRIMARY KEY, v int )" % table) insert_statement = session.prepare("INSERT INTO %s (k, v) VALUES (?, ?)" % table) # This is going to query a host where the query # is not prepared policy.set_host(1) batch_statement = BatchStatement(consistency_level=ConsistencyLevel.ONE) batch_statement.add(insert_statement, (1, 2)) session.execute(batch_statement) # To verify our test assumption that queries are getting re-prepared properly self.assertEqual(1, self.mock_handler.get_message_count('debug', "Re-preparing")) select_results = session.execute(SimpleStatement("SELECT * FROM %s WHERE k = 1" % table, consistency_level=ConsistencyLevel.ALL)) first_row = select_results[0][:2] self.assertEqual((1, 2), first_row) def test_prepare_batch_statement_after_alter(self): """ Test to validate a prepared statement used inside a batch statement is correctly handled by the driver. The metadata might be updated when a table is altered. This tests combines queries not being prepared and an update of the prepared statement metadata @since 3.10 @jira_ticket PYTHON-706 @expected_result queries will have to re-prepared on hosts that aren't the control connection and the batch statement will be sent. """ - clus = Cluster(protocol_version=PROTOCOL_VERSION, prepare_on_all_hosts=False, reprepare_on_up=False) + clus = TestCluster(prepare_on_all_hosts=False, reprepare_on_up=False) self.addCleanup(clus.shutdown) table = "test3rf.%s" % self._testMethodName.lower() session = clus.connect(wait_for_all_pools=True) session.execute("DROP TABLE IF EXISTS %s" % table) session.execute("CREATE TABLE %s (k int PRIMARY KEY, a int, b int, d int)" % table) insert_statement = session.prepare("INSERT INTO %s (k, b, d) VALUES (?, ?, ?)" % table) # Altering the table might trigger an update in the insert metadata session.execute("ALTER TABLE %s ADD c int" % table) values_to_insert = [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)] # We query the three hosts in order (due to the ForcedHostIndexPolicy) # the first three queries will have to be repreapred and the rest should # work as normal batch prepared statements hosts = clus.metadata.all_hosts() for i in range(10): value_to_insert = values_to_insert[i % len(values_to_insert)] batch_statement = BatchStatement(consistency_level=ConsistencyLevel.ONE) batch_statement.add(insert_statement, value_to_insert) session.execute(batch_statement, host=hosts[i % len(hosts)]) select_results = session.execute("SELECT * FROM %s" % table) expected_results = [ (1, None, 2, None, 3), (2, None, 3, None, 4), (3, None, 4, None, 5), (4, None, 5, None, 6) ] self.assertEqual(set(expected_results), set(select_results._current_rows)) # To verify our test assumption that queries are getting re-prepared properly self.assertEqual(3, self.mock_handler.get_message_count('debug', "Re-preparing")) class PrintStatementTests(unittest.TestCase): """ Test that shows the format used when printing Statements """ def test_simple_statement(self): """ Highlight the format of printing SimpleStatements """ ss = SimpleStatement('SELECT * FROM test3rf.test', consistency_level=ConsistencyLevel.ONE) self.assertEqual(str(ss), '') def test_prepared_statement(self): """ Highlight the difference between Prepared and Bound statements """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cluster = TestCluster() session = cluster.connect() prepared = session.prepare('INSERT INTO test3rf.test (k, v) VALUES (?, ?)') prepared.consistency_level = ConsistencyLevel.ONE self.assertEqual(str(prepared), '') bound = prepared.bind((1, 2)) self.assertEqual(str(bound), '') cluster.shutdown() class BatchStatementTests(BasicSharedKeyspaceUnitTestCase): def setUp(self): if PROTOCOL_VERSION < 2: raise unittest.SkipTest( "Protocol 2.0+ is required for BATCH operations, currently testing against %r" % (PROTOCOL_VERSION,)) - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + self.cluster = TestCluster() if PROTOCOL_VERSION < 3: self.cluster.set_core_connections_per_host(HostDistance.LOCAL, 1) self.session = self.cluster.connect(wait_for_all_pools=True) def tearDown(self): self.cluster.shutdown() def confirm_results(self): keys = set() values = set() # Assuming the test data is inserted at default CL.ONE, we need ALL here to guarantee we see # everything inserted results = self.session.execute(SimpleStatement("SELECT * FROM test3rf.test", consistency_level=ConsistencyLevel.ALL)) for result in results: keys.add(result.k) values.add(result.v) self.assertEqual(set(range(10)), keys, msg=results) self.assertEqual(set(range(10)), values, msg=results) def test_string_statements(self): batch = BatchStatement(BatchType.LOGGED) for i in range(10): batch.add("INSERT INTO test3rf.test (k, v) VALUES (%s, %s)", (i, i)) self.session.execute(batch) self.session.execute_async(batch).result() self.confirm_results() def test_simple_statements(self): batch = BatchStatement(BatchType.LOGGED) for i in range(10): batch.add(SimpleStatement("INSERT INTO test3rf.test (k, v) VALUES (%s, %s)"), (i, i)) self.session.execute(batch) self.session.execute_async(batch).result() self.confirm_results() def test_prepared_statements(self): prepared = self.session.prepare("INSERT INTO test3rf.test (k, v) VALUES (?, ?)") batch = BatchStatement(BatchType.LOGGED) for i in range(10): batch.add(prepared, (i, i)) self.session.execute(batch) self.session.execute_async(batch).result() self.confirm_results() def test_bound_statements(self): prepared = self.session.prepare("INSERT INTO test3rf.test (k, v) VALUES (?, ?)") batch = BatchStatement(BatchType.LOGGED) for i in range(10): batch.add(prepared.bind((i, i))) self.session.execute(batch) self.session.execute_async(batch).result() self.confirm_results() def test_no_parameters(self): batch = BatchStatement(BatchType.LOGGED) batch.add("INSERT INTO test3rf.test (k, v) VALUES (0, 0)") batch.add("INSERT INTO test3rf.test (k, v) VALUES (1, 1)", ()) batch.add(SimpleStatement("INSERT INTO test3rf.test (k, v) VALUES (2, 2)")) batch.add(SimpleStatement("INSERT INTO test3rf.test (k, v) VALUES (3, 3)"), ()) prepared = self.session.prepare("INSERT INTO test3rf.test (k, v) VALUES (4, 4)") batch.add(prepared) batch.add(prepared, ()) batch.add(prepared.bind([])) batch.add(prepared.bind([]), ()) batch.add("INSERT INTO test3rf.test (k, v) VALUES (5, 5)", ()) batch.add("INSERT INTO test3rf.test (k, v) VALUES (6, 6)", ()) batch.add("INSERT INTO test3rf.test (k, v) VALUES (7, 7)", ()) batch.add("INSERT INTO test3rf.test (k, v) VALUES (8, 8)", ()) batch.add("INSERT INTO test3rf.test (k, v) VALUES (9, 9)", ()) self.assertRaises(ValueError, batch.add, prepared.bind([]), (1)) self.assertRaises(ValueError, batch.add, prepared.bind([]), (1, 2)) self.assertRaises(ValueError, batch.add, prepared.bind([]), (1, 2, 3)) self.session.execute(batch) self.confirm_results() def test_unicode(self): ddl = ''' CREATE TABLE test3rf.testtext ( k int PRIMARY KEY, v text )''' self.session.execute(ddl) unicode_text = u'Fran\u00E7ois' query = u'INSERT INTO test3rf.testtext (k, v) VALUES (%s, %s)' try: batch = BatchStatement(BatchType.LOGGED) batch.add(u"INSERT INTO test3rf.testtext (k, v) VALUES (%s, %s)", (0, unicode_text)) self.session.execute(batch) finally: self.session.execute("DROP TABLE test3rf.testtext") def test_too_many_statements(self): + # The actual max # of statements is 0xFFFF, but this can occasionally cause a server write timeout. + large_batch = 0xFFF max_statements = 0xFFFF ss = SimpleStatement("INSERT INTO test3rf.test (k, v) VALUES (0, 0)") b = BatchStatement(batch_type=BatchType.UNLOGGED, consistency_level=ConsistencyLevel.ONE) - # max works - b.add_all([ss] * max_statements, [None] * max_statements) - self.session.execute(b) + # large number works works + b.add_all([ss] * large_batch, [None] * large_batch) + self.session.execute(b, timeout=30.0) + b = BatchStatement(batch_type=BatchType.UNLOGGED, consistency_level=ConsistencyLevel.ONE) # max + 1 raises + b.add_all([ss] * max_statements, [None] * max_statements) self.assertRaises(ValueError, b.add, ss) # also would have bombed trying to encode b._statements_and_parameters.append((False, ss.query_string, ())) self.assertRaises(NoHostAvailable, self.session.execute, b) class SerialConsistencyTests(unittest.TestCase): def setUp(self): if PROTOCOL_VERSION < 2: raise unittest.SkipTest( "Protocol 2.0+ is required for Serial Consistency, currently testing against %r" % (PROTOCOL_VERSION,)) - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + self.cluster = TestCluster() if PROTOCOL_VERSION < 3: self.cluster.set_core_connections_per_host(HostDistance.LOCAL, 1) self.session = self.cluster.connect() def tearDown(self): self.cluster.shutdown() def test_conditional_update(self): self.session.execute("INSERT INTO test3rf.test (k, v) VALUES (0, 0)") statement = SimpleStatement( "UPDATE test3rf.test SET v=1 WHERE k=0 IF v=1", serial_consistency_level=ConsistencyLevel.SERIAL) # crazy test, but PYTHON-299 # TODO: expand to check more parameters get passed to statement, and on to messages self.assertEqual(statement.serial_consistency_level, ConsistencyLevel.SERIAL) future = self.session.execute_async(statement) result = future.result() self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.SERIAL) self.assertTrue(result) self.assertFalse(result[0].applied) statement = SimpleStatement( "UPDATE test3rf.test SET v=1 WHERE k=0 IF v=0", serial_consistency_level=ConsistencyLevel.LOCAL_SERIAL) self.assertEqual(statement.serial_consistency_level, ConsistencyLevel.LOCAL_SERIAL) future = self.session.execute_async(statement) result = future.result() self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.LOCAL_SERIAL) self.assertTrue(result) self.assertTrue(result[0].applied) def test_conditional_update_with_prepared_statements(self): self.session.execute("INSERT INTO test3rf.test (k, v) VALUES (0, 0)") statement = self.session.prepare( "UPDATE test3rf.test SET v=1 WHERE k=0 IF v=2") statement.serial_consistency_level = ConsistencyLevel.SERIAL future = self.session.execute_async(statement) result = future.result() self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.SERIAL) self.assertTrue(result) self.assertFalse(result[0].applied) statement = self.session.prepare( "UPDATE test3rf.test SET v=1 WHERE k=0 IF v=0") bound = statement.bind(()) bound.serial_consistency_level = ConsistencyLevel.LOCAL_SERIAL future = self.session.execute_async(bound) result = future.result() self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.LOCAL_SERIAL) self.assertTrue(result) self.assertTrue(result[0].applied) def test_conditional_update_with_batch_statements(self): self.session.execute("INSERT INTO test3rf.test (k, v) VALUES (0, 0)") statement = BatchStatement(serial_consistency_level=ConsistencyLevel.SERIAL) statement.add("UPDATE test3rf.test SET v=1 WHERE k=0 IF v=1") self.assertEqual(statement.serial_consistency_level, ConsistencyLevel.SERIAL) future = self.session.execute_async(statement) result = future.result() self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.SERIAL) self.assertTrue(result) self.assertFalse(result[0].applied) statement = BatchStatement(serial_consistency_level=ConsistencyLevel.LOCAL_SERIAL) statement.add("UPDATE test3rf.test SET v=1 WHERE k=0 IF v=0") self.assertEqual(statement.serial_consistency_level, ConsistencyLevel.LOCAL_SERIAL) future = self.session.execute_async(statement) result = future.result() self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.LOCAL_SERIAL) self.assertTrue(result) self.assertTrue(result[0].applied) def test_bad_consistency_level(self): statement = SimpleStatement("foo") self.assertRaises(ValueError, setattr, statement, 'serial_consistency_level', ConsistencyLevel.ONE) self.assertRaises(ValueError, SimpleStatement, 'foo', serial_consistency_level=ConsistencyLevel.ONE) class LightweightTransactionTests(unittest.TestCase): def setUp(self): """ Test is skipped if run with cql version < 2 """ if PROTOCOL_VERSION < 2: raise unittest.SkipTest( "Protocol 2.0+ is required for Lightweight transactions, currently testing against %r" % (PROTOCOL_VERSION,)) serial_profile = ExecutionProfile(consistency_level=ConsistencyLevel.SERIAL) - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, execution_profiles={'serial': serial_profile}) + self.cluster = TestCluster(execution_profiles={'serial': serial_profile}) self.session = self.cluster.connect() ddl = ''' CREATE TABLE test3rf.lwt ( k int PRIMARY KEY, v int )''' self.session.execute(ddl) ddl = ''' CREATE TABLE test3rf.lwt_clustering ( k int, c int, v int, PRIMARY KEY (k, c))''' self.session.execute(ddl) def tearDown(self): """ Shutdown cluster """ self.session.execute("DROP TABLE test3rf.lwt") self.session.execute("DROP TABLE test3rf.lwt_clustering") self.cluster.shutdown() def test_no_connection_refused_on_timeout(self): """ Test for PYTHON-91 "Connection closed after LWT timeout" Verifies that connection to the cluster is not shut down when timeout occurs. Number of iterations can be specified with LWT_ITERATIONS environment variable. Default value is 1000 """ insert_statement = self.session.prepare("INSERT INTO test3rf.lwt (k, v) VALUES (0, 0) IF NOT EXISTS") delete_statement = self.session.prepare("DELETE FROM test3rf.lwt WHERE k = 0 IF EXISTS") iterations = int(os.getenv("LWT_ITERATIONS", 1000)) # Prepare series of parallel statements statements_and_params = [] for i in range(iterations): statements_and_params.append((insert_statement, ())) statements_and_params.append((delete_statement, ())) received_timeout = False results = execute_concurrent(self.session, statements_and_params, raise_on_first_error=False) for (success, result) in results: if success: continue else: # In this case result is an exception - if type(result).__name__ == "NoHostAvailable": + exception_type = type(result).__name__ + if exception_type == "NoHostAvailable": self.fail("PYTHON-91: Disconnected from Cassandra: %s" % result.message) - if type(result).__name__ == "WriteTimeout": - received_timeout = True - continue - if type(result).__name__ == "WriteFailure": - received_timeout = True - continue - if type(result).__name__ == "ReadTimeout": - continue - if type(result).__name__ == "ReadFailure": + if exception_type in ["WriteTimeout", "WriteFailure", "ReadTimeout", "ReadFailure", "ErrorMessageSub"]: + if type(result).__name__ in ["WriteTimeout", "WriteFailure"]: + received_timeout = True continue - self.fail("Unexpected exception %s: %s" % (type(result).__name__, result.message)) + self.fail("Unexpected exception %s: %s" % (exception_type, result.message)) # Make sure test passed self.assertTrue(received_timeout) def test_was_applied_batch_stmt(self): """ Test to ensure `:attr:cassandra.cluster.ResultSet.was_applied` works as expected with Batchstatements. For both type of batches verify was_applied has the correct result under different scenarios: - If on LWT fails the rest of the statements fail including normal UPSERTS - If on LWT fails the rest of the statements fail - All the queries succeed @since 3.14 @jira_ticket PYTHON-848 @expected_result `:attr:cassandra.cluster.ResultSet.was_applied` is updated as expected @test_category query """ for batch_type in (BatchType.UNLOGGED, BatchType.LOGGED): batch_statement = BatchStatement(batch_type) batch_statement.add_all(["INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 0, 10) IF NOT EXISTS;", "INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 1, 10);", "INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 2, 10);"], [None] * 3) result = self.session.execute(batch_statement) #self.assertTrue(result.was_applied) # Should fail since (0, 0, 10) have already been written # The non conditional insert shouldn't be written as well batch_statement = BatchStatement(batch_type) batch_statement.add_all(["INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 0, 10) IF NOT EXISTS;", "INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 3, 10) IF NOT EXISTS;", "INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 4, 10);", "INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 5, 10) IF NOT EXISTS;"], [None] * 4) result = self.session.execute(batch_statement) self.assertFalse(result.was_applied) all_rows = self.session.execute("SELECT * from test3rf.lwt_clustering", execution_profile='serial') # Verify the non conditional insert hasn't been inserted self.assertEqual(len(all_rows.current_rows), 3) # Should fail since (0, 0, 10) have already been written batch_statement = BatchStatement(batch_type) batch_statement.add_all(["INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 0, 10) IF NOT EXISTS;", "INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 3, 10) IF NOT EXISTS;", "INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 5, 10) IF NOT EXISTS;"], [None] * 3) result = self.session.execute(batch_statement) self.assertFalse(result.was_applied) # Should fail since (0, 0, 10) have already been written batch_statement.add("INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 0, 10) IF NOT EXISTS;") result = self.session.execute(batch_statement) self.assertFalse(result.was_applied) # Should succeed batch_statement = BatchStatement(batch_type) batch_statement.add_all(["INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 3, 10) IF NOT EXISTS;", "INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 4, 10) IF NOT EXISTS;", "INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 5, 10) IF NOT EXISTS;"], [None] * 3) result = self.session.execute(batch_statement) self.assertTrue(result.was_applied) all_rows = self.session.execute("SELECT * from test3rf.lwt_clustering", execution_profile='serial') for i, row in enumerate(all_rows): self.assertEqual((0, i, 10), (row[0], row[1], row[2])) self.session.execute("TRUNCATE TABLE test3rf.lwt_clustering") def test_empty_batch_statement(self): """ Test to ensure `:attr:cassandra.cluster.ResultSet.was_applied` works as expected with empty Batchstatements. @since 3.14 @jira_ticket PYTHON-848 @expected_result an Exception is raised expected @test_category query """ batch_statement = BatchStatement() results = self.session.execute(batch_statement) with self.assertRaises(RuntimeError): results.was_applied @unittest.skip("Skipping until PYTHON-943 is resolved") def test_was_applied_batch_string(self): batch_statement = BatchStatement(BatchType.LOGGED) batch_statement.add_all(["INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 0, 10);", "INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 1, 10);", "INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 2, 10);"], [None] * 3) self.session.execute(batch_statement) batch_str = """ BEGIN unlogged batch INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 0, 10) IF NOT EXISTS; INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 1, 10) IF NOT EXISTS; INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 2, 10) IF NOT EXISTS; APPLY batch; """ result = self.session.execute(batch_str) self.assertFalse(result.was_applied) batch_str = """ BEGIN unlogged batch INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 3, 10) IF NOT EXISTS; INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 4, 10) IF NOT EXISTS; INSERT INTO test3rf.lwt_clustering (k, c, v) VALUES (0, 5, 10) IF NOT EXISTS; APPLY batch; """ result = self.session.execute(batch_str) self.assertTrue(result.was_applied) class BatchStatementDefaultRoutingKeyTests(unittest.TestCase): # Test for PYTHON-126: BatchStatement.add() should set the routing key of the first added prepared statement def setUp(self): if PROTOCOL_VERSION < 2: raise unittest.SkipTest( "Protocol 2.0+ is required for BATCH operations, currently testing against %r" % (PROTOCOL_VERSION,)) - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + self.cluster = TestCluster() self.session = self.cluster.connect() query = """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """ self.simple_statement = SimpleStatement(query, routing_key='ss_rk', keyspace='keyspace_name') self.prepared = self.session.prepare(query) def tearDown(self): self.cluster.shutdown() def test_rk_from_bound(self): """ batch routing key is inherited from BoundStatement """ bound = self.prepared.bind((1, None)) batch = BatchStatement() batch.add(bound) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, bound.routing_key) def test_rk_from_simple(self): """ batch routing key is inherited from SimpleStatement """ batch = BatchStatement() batch.add(self.simple_statement) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, self.simple_statement.routing_key) def test_inherit_first_rk_bound(self): """ compound batch inherits the first routing key of the first added statement (bound statement is first) """ bound = self.prepared.bind((100000000, None)) batch = BatchStatement() batch.add("ss with no rk") batch.add(bound) batch.add(self.simple_statement) for i in range(3): batch.add(self.prepared, (i, i)) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, bound.routing_key) def test_inherit_first_rk_simple_statement(self): """ compound batch inherits the first routing key of the first added statement (Simplestatement is first) """ bound = self.prepared.bind((1, None)) batch = BatchStatement() batch.add("ss with no rk") batch.add(self.simple_statement) batch.add(bound) for i in range(10): batch.add(self.prepared, (i, i)) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, self.simple_statement.routing_key) def test_inherit_first_rk_prepared_param(self): """ compound batch inherits the first routing key of the first added statement (prepared statement is first) """ bound = self.prepared.bind((2, None)) batch = BatchStatement() batch.add("ss with no rk") batch.add(self.prepared, (1, 0)) batch.add(bound) batch.add(self.simple_statement) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, self.prepared.bind((1, 0)).routing_key) @greaterthanorequalcass30 class MaterializedViewQueryTest(BasicSharedKeyspaceUnitTestCase): def test_mv_filtering(self): """ Test to ensure that cql filtering where clauses are properly supported in the python driver. test_mv_filtering Tests that various complex MV where clauses produce the correct results. It also validates that these results and the grammar is supported appropriately. @since 3.0.0 @jira_ticket PYTHON-399 @expected_result Materialized view where clauses should produce the appropriate results. @test_category materialized_view """ create_table = """CREATE TABLE {0}.scores( user TEXT, game TEXT, year INT, month INT, day INT, score INT, PRIMARY KEY (user, game, year, month, day) )""".format(self.keyspace_name) self.session.execute(create_table) create_mv_alltime = """CREATE MATERIALIZED VIEW {0}.alltimehigh AS SELECT * FROM {0}.scores WHERE game IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND day IS NOT NULL PRIMARY KEY (game, score, user, year, month, day) - WITH CLUSTERING ORDER BY (score DESC)""".format(self.keyspace_name) + WITH CLUSTERING ORDER BY (score DESC, user ASC, year ASC, month ASC, day ASC)""".format(self.keyspace_name) create_mv_dailyhigh = """CREATE MATERIALIZED VIEW {0}.dailyhigh AS SELECT * FROM {0}.scores WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND day IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL PRIMARY KEY ((game, year, month, day), score, user) - WITH CLUSTERING ORDER BY (score DESC)""".format(self.keyspace_name) + WITH CLUSTERING ORDER BY (score DESC, user ASC)""".format(self.keyspace_name) create_mv_monthlyhigh = """CREATE MATERIALIZED VIEW {0}.monthlyhigh AS SELECT * FROM {0}.scores WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL PRIMARY KEY ((game, year, month), score, user, day) - WITH CLUSTERING ORDER BY (score DESC)""".format(self.keyspace_name) + WITH CLUSTERING ORDER BY (score DESC, user ASC, day ASC)""".format(self.keyspace_name) create_mv_filtereduserhigh = """CREATE MATERIALIZED VIEW {0}.filtereduserhigh AS SELECT * FROM {0}.scores WHERE user in ('jbellis', 'pcmanus') AND game IS NOT NULL AND score IS NOT NULL AND year is NOT NULL AND day is not NULL and month IS NOT NULL PRIMARY KEY (game, score, user, year, month, day) - WITH CLUSTERING ORDER BY (score DESC)""".format(self.keyspace_name) + WITH CLUSTERING ORDER BY (score DESC, user ASC, year ASC, month ASC, day ASC)""".format(self.keyspace_name) self.session.execute(create_mv_alltime) self.session.execute(create_mv_dailyhigh) self.session.execute(create_mv_monthlyhigh) self.session.execute(create_mv_filtereduserhigh) self.addCleanup(self.session.execute, "DROP MATERIALIZED VIEW {0}.alltimehigh".format(self.keyspace_name)) self.addCleanup(self.session.execute, "DROP MATERIALIZED VIEW {0}.dailyhigh".format(self.keyspace_name)) self.addCleanup(self.session.execute, "DROP MATERIALIZED VIEW {0}.monthlyhigh".format(self.keyspace_name)) self.addCleanup(self.session.execute, "DROP MATERIALIZED VIEW {0}.filtereduserhigh".format(self.keyspace_name)) prepared_insert = self.session.prepare("""INSERT INTO {0}.scores (user, game, year, month, day, score) VALUES (?, ?, ? ,? ,?, ?)""".format(self.keyspace_name)) bound = prepared_insert.bind(('pcmanus', 'Coup', 2015, 5, 1, 4000)) self.session.execute(bound) bound = prepared_insert.bind(('jbellis', 'Coup', 2015, 5, 3, 1750)) self.session.execute(bound) bound = prepared_insert.bind(('yukim', 'Coup', 2015, 5, 3, 2250)) self.session.execute(bound) bound = prepared_insert.bind(('tjake', 'Coup', 2015, 5, 3, 500)) self.session.execute(bound) bound = prepared_insert.bind(('iamaleksey', 'Coup', 2015, 6, 1, 2500)) self.session.execute(bound) bound = prepared_insert.bind(('tjake', 'Coup', 2015, 6, 2, 1000)) self.session.execute(bound) bound = prepared_insert.bind(('pcmanus', 'Coup', 2015, 6, 2, 2000)) self.session.execute(bound) bound = prepared_insert.bind(('jmckenzie', 'Coup', 2015, 6, 9, 2700)) self.session.execute(bound) bound = prepared_insert.bind(('jbellis', 'Coup', 2015, 6, 20, 3500)) self.session.execute(bound) bound = prepared_insert.bind(('jbellis', 'Checkers', 2015, 6, 20, 1200)) self.session.execute(bound) bound = prepared_insert.bind(('jbellis', 'Chess', 2015, 6, 21, 3500)) self.session.execute(bound) bound = prepared_insert.bind(('pcmanus', 'Chess', 2015, 1, 25, 3200)) self.session.execute(bound) # Test simple statement and alltime high filtering query_statement = SimpleStatement("SELECT * FROM {0}.alltimehigh WHERE game='Coup'".format(self.keyspace_name), consistency_level=ConsistencyLevel.QUORUM) results = self.session.execute(query_statement) self.assertEqual(results[0].game, 'Coup') self.assertEqual(results[0].year, 2015) self.assertEqual(results[0].month, 5) self.assertEqual(results[0].day, 1) self.assertEqual(results[0].score, 4000) self.assertEqual(results[0].user, "pcmanus") # Test prepared statement and daily high filtering prepared_query = self.session.prepare("SELECT * FROM {0}.dailyhigh WHERE game=? AND year=? AND month=? and day=?".format(self.keyspace_name)) bound_query = prepared_query.bind(("Coup", 2015, 6, 2)) results = self.session.execute(bound_query) self.assertEqual(results[0].game, 'Coup') self.assertEqual(results[0].year, 2015) self.assertEqual(results[0].month, 6) self.assertEqual(results[0].day, 2) self.assertEqual(results[0].score, 2000) self.assertEqual(results[0].user, "pcmanus") self.assertEqual(results[1].game, 'Coup') self.assertEqual(results[1].year, 2015) self.assertEqual(results[1].month, 6) self.assertEqual(results[1].day, 2) self.assertEqual(results[1].score, 1000) self.assertEqual(results[1].user, "tjake") # Test montly high range queries prepared_query = self.session.prepare("SELECT * FROM {0}.monthlyhigh WHERE game=? AND year=? AND month=? and score >= ? and score <= ?".format(self.keyspace_name)) bound_query = prepared_query.bind(("Coup", 2015, 6, 2500, 3500)) results = self.session.execute(bound_query) self.assertEqual(results[0].game, 'Coup') self.assertEqual(results[0].year, 2015) self.assertEqual(results[0].month, 6) self.assertEqual(results[0].day, 20) self.assertEqual(results[0].score, 3500) self.assertEqual(results[0].user, "jbellis") self.assertEqual(results[1].game, 'Coup') self.assertEqual(results[1].year, 2015) self.assertEqual(results[1].month, 6) self.assertEqual(results[1].day, 9) self.assertEqual(results[1].score, 2700) self.assertEqual(results[1].user, "jmckenzie") self.assertEqual(results[2].game, 'Coup') self.assertEqual(results[2].year, 2015) self.assertEqual(results[2].month, 6) self.assertEqual(results[2].day, 1) self.assertEqual(results[2].score, 2500) self.assertEqual(results[2].user, "iamaleksey") # Test filtered user high scores query_statement = SimpleStatement("SELECT * FROM {0}.filtereduserhigh WHERE game='Chess'".format(self.keyspace_name), consistency_level=ConsistencyLevel.QUORUM) results = self.session.execute(query_statement) self.assertEqual(results[0].game, 'Chess') self.assertEqual(results[0].year, 2015) self.assertEqual(results[0].month, 6) self.assertEqual(results[0].day, 21) self.assertEqual(results[0].score, 3500) self.assertEqual(results[0].user, "jbellis") self.assertEqual(results[1].game, 'Chess') self.assertEqual(results[1].year, 2015) self.assertEqual(results[1].month, 1) self.assertEqual(results[1].day, 25) self.assertEqual(results[1].score, 3200) self.assertEqual(results[1].user, "pcmanus") class UnicodeQueryTest(BasicSharedKeyspaceUnitTestCase): def setUp(self): ddl = ''' CREATE TABLE {0}.{1} ( k int PRIMARY KEY, v text )'''.format(self.keyspace_name, self.function_table_name) self.session.execute(ddl) def tearDown(self): self.session.execute("DROP TABLE {0}.{1}".format(self.keyspace_name,self.function_table_name)) def test_unicode(self): """ Test to validate that unicode query strings are handled appropriately by various query types @since 3.0.0 @jira_ticket PYTHON-334 @expected_result no unicode exceptions are thrown @test_category query """ unicode_text = u'Fran\u00E7ois' batch = BatchStatement(BatchType.LOGGED) batch.add(u"INSERT INTO {0}.{1} (k, v) VALUES (%s, %s)".format(self.keyspace_name, self.function_table_name), (0, unicode_text)) self.session.execute(batch) self.session.execute(u"INSERT INTO {0}.{1} (k, v) VALUES (%s, %s)".format(self.keyspace_name, self.function_table_name), (0, unicode_text)) prepared = self.session.prepare(u"INSERT INTO {0}.{1} (k, v) VALUES (?, ?)".format(self.keyspace_name, self.function_table_name)) bound = prepared.bind((1, unicode_text)) self.session.execute(bound) class BaseKeyspaceTests(): @classmethod def setUpClass(cls): - cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cls.cluster = TestCluster() cls.session = cls.cluster.connect(wait_for_all_pools=True) cls.ks_name = cls.__name__.lower() cls.alternative_ks = "alternative_keyspace" cls.table_name = "table_query_keyspace_tests" ddl = """CREATE KEYSPACE {0} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor': '{1}'}}""".format(cls.ks_name, 1) cls.session.execute(ddl) ddl = """CREATE KEYSPACE {0} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor': '{1}'}}""".format(cls.alternative_ks, 1) cls.session.execute(ddl) ddl = ''' CREATE TABLE {0}.{1} ( k int PRIMARY KEY, v int )'''.format(cls.ks_name, cls.table_name) cls.session.execute(ddl) ddl = ''' CREATE TABLE {0}.{1} ( k int PRIMARY KEY, v int )'''.format(cls.alternative_ks, cls.table_name) cls.session.execute(ddl) cls.session.execute("INSERT INTO {}.{} (k, v) VALUES (1, 1)".format(cls.ks_name, cls.table_name)) cls.session.execute("INSERT INTO {}.{} (k, v) VALUES (2, 2)".format(cls.alternative_ks, cls.table_name)) @classmethod def tearDownClass(cls): ddl = "DROP KEYSPACE {}".format(cls.alternative_ks) cls.session.execute(ddl) ddl = "DROP KEYSPACE {}".format(cls.ks_name) cls.session.execute(ddl) cls.cluster.shutdown() + class QueryKeyspaceTests(BaseKeyspaceTests): def test_setting_keyspace(self): """ Test the basic functionality of PYTHON-678, the keyspace can be set independently of the query and read the results @since 3.12 @jira_ticket PYTHON-678 @expected_result the query is executed and the results retrieved @test_category query """ self._check_set_keyspace_in_statement(self.session) + @requirecassandra + @greaterthanorequalcass40 def test_setting_keyspace_and_session(self): """ Test we can still send the keyspace independently even the session connects to a keyspace when it's created @since 3.12 @jira_ticket PYTHON-678 @expected_result the query is executed and the results retrieved @test_category query """ - cluster = Cluster(protocol_version=ProtocolVersion.V5, allow_beta_protocol_version=True) + cluster = TestCluster(protocol_version=ProtocolVersion.V5, allow_beta_protocol_version=True) session = cluster.connect(self.alternative_ks) self.addCleanup(cluster.shutdown) self._check_set_keyspace_in_statement(session) def test_setting_keyspace_and_session_after_created(self): """ Test we can still send the keyspace independently even the session connects to a different keyspace after being created @since 3.12 @jira_ticket PYTHON-678 @expected_result the query is executed and the results retrieved @test_category query """ - cluster = Cluster(protocol_version=ProtocolVersion.V5, allow_beta_protocol_version=True) + cluster = TestCluster() session = cluster.connect() self.addCleanup(cluster.shutdown) session.set_keyspace(self.alternative_ks) self._check_set_keyspace_in_statement(session) def test_setting_keyspace_and_same_session(self): """ Test we can still send the keyspace independently even if the session is connected to the sent keyspace @since 3.12 @jira_ticket PYTHON-678 @expected_result the query is executed and the results retrieved @test_category query """ - cluster = Cluster(protocol_version=ProtocolVersion.V5, allow_beta_protocol_version=True) + cluster = TestCluster() session = cluster.connect(self.ks_name) self.addCleanup(cluster.shutdown) self._check_set_keyspace_in_statement(session) @greaterthanorequalcass40 class SimpleWithKeyspaceTests(QueryKeyspaceTests, unittest.TestCase): @unittest.skip def test_lower_protocol(self): - cluster = Cluster(protocol_version=ProtocolVersion.V4) + cluster = TestCluster(protocol_version=ProtocolVersion.V4) session = cluster.connect(self.ks_name) self.addCleanup(cluster.shutdown) simple_stmt = SimpleStatement("SELECT * from {}".format(self.table_name), keyspace=self.ks_name) # This raises cassandra.cluster.NoHostAvailable: ('Unable to complete the operation against # any hosts', {: UnsupportedOperation('Keyspaces may only be # set on queries with protocol version 5 or higher. Consider setting Cluster.protocol_version to 5.',), # : ConnectionException('Host has been marked down or removed',), # : ConnectionException('Host has been marked down or removed',)}) with self.assertRaises(NoHostAvailable): session.execute(simple_stmt) def _check_set_keyspace_in_statement(self, session): simple_stmt = SimpleStatement("SELECT * from {}".format(self.table_name), keyspace=self.ks_name) results = session.execute(simple_stmt) self.assertEqual(results[0], (1, 1)) simple_stmt = SimpleStatement("SELECT * from {}".format(self.table_name)) simple_stmt.keyspace = self.ks_name results = session.execute(simple_stmt) self.assertEqual(results[0], (1, 1)) @greaterthanorequalcass40 class BatchWithKeyspaceTests(QueryKeyspaceTests, unittest.TestCase): def _check_set_keyspace_in_statement(self, session): batch_stmt = BatchStatement() for i in range(10): batch_stmt.add("INSERT INTO {} (k, v) VALUES (%s, %s)".format(self.table_name), (i, i)) batch_stmt.keyspace = self.ks_name session.execute(batch_stmt) self.confirm_results() def confirm_results(self): keys = set() values = set() # Assuming the test data is inserted at default CL.ONE, we need ALL here to guarantee we see # everything inserted results = self.session.execute(SimpleStatement("SELECT * FROM {}.{}".format(self.ks_name, self.table_name), consistency_level=ConsistencyLevel.ALL)) for result in results: keys.add(result.k) values.add(result.v) self.assertEqual(set(range(10)), keys, msg=results) self.assertEqual(set(range(10)), values, msg=results) @greaterthanorequalcass40 class PreparedWithKeyspaceTests(BaseKeyspaceTests, unittest.TestCase): def setUp(self): - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION, allow_beta_protocol_version=True) + self.cluster = TestCluster() self.session = self.cluster.connect() def tearDown(self): self.cluster.shutdown() def test_prepared_with_keyspace_explicit(self): """ Test the basic functionality of PYTHON-678, the keyspace can be set independently of the query and read the results @since 3.12 @jira_ticket PYTHON-678 @expected_result the query is executed and the results retrieved @test_category query """ query = "SELECT * from {} WHERE k = ?".format(self.table_name) prepared_statement = self.session.prepare(query, keyspace=self.ks_name) results = self.session.execute(prepared_statement, (1, )) self.assertEqual(results[0], (1, 1)) prepared_statement_alternative = self.session.prepare(query, keyspace=self.alternative_ks) self.assertNotEqual(prepared_statement.query_id, prepared_statement_alternative.query_id) results = self.session.execute(prepared_statement_alternative, (2,)) self.assertEqual(results[0], (2, 2)) def test_reprepare_after_host_is_down(self): """ Test that Cluster._prepare_all_queries is called and the when a node comes up and the queries succeed later @since 3.12 @jira_ticket PYTHON-678 @expected_result the query is executed and the results retrieved @test_category query """ mock_handler = MockLoggingHandler() logger = logging.getLogger(cluster.__name__) logger.addHandler(mock_handler) get_node(1).stop(wait=True, gently=True, wait_other_notice=True) only_first = ExecutionProfile(load_balancing_policy=WhiteListRoundRobinPolicy(["127.0.0.1"])) self.cluster.add_execution_profile("only_first", only_first) query = "SELECT v from {} WHERE k = ?".format(self.table_name) prepared_statement = self.session.prepare(query, keyspace=self.ks_name) prepared_statement_alternative = self.session.prepare(query, keyspace=self.alternative_ks) get_node(1).start(wait_for_binary_proto=True, wait_other_notice=True) # We wait for cluster._prepare_all_queries to be called time.sleep(5) self.assertEqual(1, mock_handler.get_message_count('debug', 'Preparing all known prepared statements')) results = self.session.execute(prepared_statement, (1,), execution_profile="only_first") self.assertEqual(results[0], (1, )) results = self.session.execute(prepared_statement_alternative, (2,), execution_profile="only_first") self.assertEqual(results[0], (2, )) def test_prepared_not_found(self): """ Test to if a query fails on a node that didn't have the query prepared, it is re-prepared as expected and then the query is executed @since 3.12 @jira_ticket PYTHON-678 @expected_result the query is executed and the results retrieved @test_category query """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION, allow_beta_protocol_version=True) + cluster = TestCluster() session = self.cluster.connect("system") self.addCleanup(cluster.shutdown) cluster.prepare_on_all_hosts = False query = "SELECT k from {} WHERE k = ?".format(self.table_name) prepared_statement = session.prepare(query, keyspace=self.ks_name) for _ in range(10): results = session.execute(prepared_statement, (1, )) self.assertEqual(results[0], (1,)) def test_prepared_in_query_keyspace(self): """ Test to the the keyspace can be set in the query @since 3.12 @jira_ticket PYTHON-678 @expected_result the results are retrieved correctly @test_category query """ - cluster = Cluster(protocol_version=PROTOCOL_VERSION, allow_beta_protocol_version=True) + cluster = TestCluster() session = self.cluster.connect() self.addCleanup(cluster.shutdown) query = "SELECT k from {}.{} WHERE k = ?".format(self.ks_name, self.table_name) prepared_statement = session.prepare(query) results = session.execute(prepared_statement, (1,)) self.assertEqual(results[0], (1,)) query = "SELECT k from {}.{} WHERE k = ?".format(self.alternative_ks, self.table_name) prepared_statement = session.prepare(query) results = session.execute(prepared_statement, (2,)) self.assertEqual(results[0], (2,)) def test_prepared_in_query_keyspace_and_explicit(self): """ Test to the the keyspace set explicitly is ignored if it is specified as well in the query @since 3.12 @jira_ticket PYTHON-678 @expected_result the keyspace set explicitly is ignored and the results are retrieved correctly @test_category query """ query = "SELECT k from {}.{} WHERE k = ?".format(self.ks_name, self.table_name) prepared_statement = self.session.prepare(query, keyspace="system") results = self.session.execute(prepared_statement, (1,)) self.assertEqual(results[0], (1,)) query = "SELECT k from {}.{} WHERE k = ?".format(self.ks_name, self.table_name) prepared_statement = self.session.prepare(query, keyspace=self.alternative_ks) results = self.session.execute(prepared_statement, (1,)) self.assertEqual(results[0], (1,)) diff --git a/tests/integration/standard/test_query_paging.py b/tests/integration/standard/test_query_paging.py index dfe9f70..dac4ec5 100644 --- a/tests/integration/standard/test_query_paging.py +++ b/tests/integration/standard/test_query_paging.py @@ -1,413 +1,415 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -from tests.integration import use_singledc, PROTOCOL_VERSION +from tests.integration import use_singledc, PROTOCOL_VERSION, TestCluster import logging log = logging.getLogger(__name__) try: import unittest2 as unittest except ImportError: import unittest # noqa from itertools import cycle, count from six.moves import range from threading import Event -from cassandra.cluster import Cluster +from cassandra import ConsistencyLevel +from cassandra.cluster import EXEC_PROFILE_DEFAULT, ExecutionProfile from cassandra.concurrent import execute_concurrent, execute_concurrent_with_args from cassandra.policies import HostDistance from cassandra.query import SimpleStatement def setup_module(): use_singledc() class QueryPagingTests(unittest.TestCase): def setUp(self): if PROTOCOL_VERSION < 2: raise unittest.SkipTest( "Protocol 2.0+ is required for Paging state, currently testing against %r" % (PROTOCOL_VERSION,)) - self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + self.cluster = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(consistency_level=ConsistencyLevel.LOCAL_QUORUM)} + ) if PROTOCOL_VERSION < 3: self.cluster.set_core_connections_per_host(HostDistance.LOCAL, 1) self.session = self.cluster.connect(wait_for_all_pools=True) self.session.execute("TRUNCATE test3rf.test") def tearDown(self): self.cluster.shutdown() def test_paging(self): statements_and_params = zip(cycle(["INSERT INTO test3rf.test (k, v) VALUES (%s, 0)"]), [(i, ) for i in range(100)]) execute_concurrent(self.session, list(statements_and_params)) prepared = self.session.prepare("SELECT * FROM test3rf.test") for fetch_size in (2, 3, 7, 10, 99, 100, 101, 10000): self.session.default_fetch_size = fetch_size self.assertEqual(100, len(list(self.session.execute("SELECT * FROM test3rf.test")))) statement = SimpleStatement("SELECT * FROM test3rf.test") self.assertEqual(100, len(list(self.session.execute(statement)))) self.assertEqual(100, len(list(self.session.execute(prepared)))) def test_paging_state(self): """ Test to validate paging state api @since 3.7.0 @jira_ticket PYTHON-200 @expected_result paging state should returned should be accurate, and allow for queries to be resumed. @test_category queries """ statements_and_params = zip(cycle(["INSERT INTO test3rf.test (k, v) VALUES (%s, 0)"]), [(i, ) for i in range(100)]) execute_concurrent(self.session, list(statements_and_params)) list_all_results = [] self.session.default_fetch_size = 3 result_set = self.session.execute("SELECT * FROM test3rf.test") while(result_set.has_more_pages): for row in result_set.current_rows: self.assertNotIn(row, list_all_results) list_all_results.extend(result_set.current_rows) page_state = result_set.paging_state result_set = self.session.execute("SELECT * FROM test3rf.test", paging_state=page_state) if(len(result_set.current_rows) > 0): list_all_results.append(result_set.current_rows) self.assertEqual(len(list_all_results), 100) def test_paging_verify_writes(self): statements_and_params = zip(cycle(["INSERT INTO test3rf.test (k, v) VALUES (%s, 0)"]), [(i, ) for i in range(100)]) execute_concurrent(self.session, statements_and_params) prepared = self.session.prepare("SELECT * FROM test3rf.test") for fetch_size in (2, 3, 7, 10, 99, 100, 101, 10000): self.session.default_fetch_size = fetch_size results = self.session.execute("SELECT * FROM test3rf.test") result_array = set() result_set = set() for result in results: result_array.add(result.k) result_set.add(result.v) self.assertEqual(set(range(100)), result_array) self.assertEqual(set([0]), result_set) statement = SimpleStatement("SELECT * FROM test3rf.test") results = self.session.execute(statement) result_array = set() result_set = set() for result in results: result_array.add(result.k) result_set.add(result.v) self.assertEqual(set(range(100)), result_array) self.assertEqual(set([0]), result_set) results = self.session.execute(prepared) result_array = set() result_set = set() for result in results: result_array.add(result.k) result_set.add(result.v) self.assertEqual(set(range(100)), result_array) self.assertEqual(set([0]), result_set) def test_paging_verify_with_composite_keys(self): ddl = ''' CREATE TABLE test3rf.test_paging_verify_2 ( k1 int, k2 int, v int, PRIMARY KEY(k1, k2) )''' self.session.execute(ddl) statements_and_params = zip(cycle(["INSERT INTO test3rf.test_paging_verify_2 " "(k1, k2, v) VALUES (0, %s, %s)"]), [(i, i + 1) for i in range(100)]) execute_concurrent(self.session, statements_and_params) prepared = self.session.prepare("SELECT * FROM test3rf.test_paging_verify_2") for fetch_size in (2, 3, 7, 10, 99, 100, 101, 10000): self.session.default_fetch_size = fetch_size results = self.session.execute("SELECT * FROM test3rf.test_paging_verify_2") result_array = [] value_array = [] for result in results: result_array.append(result.k2) value_array.append(result.v) self.assertSequenceEqual(range(100), result_array) self.assertSequenceEqual(range(1, 101), value_array) statement = SimpleStatement("SELECT * FROM test3rf.test_paging_verify_2") results = self.session.execute(statement) result_array = [] value_array = [] for result in results: result_array.append(result.k2) value_array.append(result.v) self.assertSequenceEqual(range(100), result_array) self.assertSequenceEqual(range(1, 101), value_array) results = self.session.execute(prepared) result_array = [] value_array = [] for result in results: result_array.append(result.k2) value_array.append(result.v) self.assertSequenceEqual(range(100), result_array) self.assertSequenceEqual(range(1, 101), value_array) def test_async_paging(self): statements_and_params = zip(cycle(["INSERT INTO test3rf.test (k, v) VALUES (%s, 0)"]), [(i, ) for i in range(100)]) execute_concurrent(self.session, list(statements_and_params)) prepared = self.session.prepare("SELECT * FROM test3rf.test") for fetch_size in (2, 3, 7, 10, 99, 100, 101, 10000): self.session.default_fetch_size = fetch_size self.assertEqual(100, len(list(self.session.execute_async("SELECT * FROM test3rf.test").result()))) statement = SimpleStatement("SELECT * FROM test3rf.test") self.assertEqual(100, len(list(self.session.execute_async(statement).result()))) self.assertEqual(100, len(list(self.session.execute_async(prepared).result()))) def test_async_paging_verify_writes(self): ddl = ''' CREATE TABLE test3rf.test_async_paging_verify ( k1 int, k2 int, v int, PRIMARY KEY(k1, k2) )''' self.session.execute(ddl) statements_and_params = zip(cycle(["INSERT INTO test3rf.test_async_paging_verify " "(k1, k2, v) VALUES (0, %s, %s)"]), [(i, i + 1) for i in range(100)]) execute_concurrent(self.session, statements_and_params) prepared = self.session.prepare("SELECT * FROM test3rf.test_async_paging_verify") for fetch_size in (2, 3, 7, 10, 99, 100, 101, 10000): self.session.default_fetch_size = fetch_size results = self.session.execute_async("SELECT * FROM test3rf.test_async_paging_verify").result() result_array = [] value_array = [] for result in results: result_array.append(result.k2) value_array.append(result.v) self.assertSequenceEqual(range(100), result_array) self.assertSequenceEqual(range(1, 101), value_array) statement = SimpleStatement("SELECT * FROM test3rf.test_async_paging_verify") results = self.session.execute_async(statement).result() result_array = [] value_array = [] for result in results: result_array.append(result.k2) value_array.append(result.v) self.assertSequenceEqual(range(100), result_array) self.assertSequenceEqual(range(1, 101), value_array) results = self.session.execute_async(prepared).result() result_array = [] value_array = [] for result in results: result_array.append(result.k2) value_array.append(result.v) self.assertSequenceEqual(range(100), result_array) self.assertSequenceEqual(range(1, 101), value_array) def test_paging_callbacks(self): """ Test to validate callback api @since 3.9.0 @jira_ticket PYTHON-733 @expected_result callbacks shouldn't be called twice per message and the fetch_size should be handled in a transparent way to the user @test_category queries """ statements_and_params = zip(cycle(["INSERT INTO test3rf.test (k, v) VALUES (%s, 0)"]), [(i, ) for i in range(100)]) execute_concurrent(self.session, list(statements_and_params)) prepared = self.session.prepare("SELECT * FROM test3rf.test") for fetch_size in (2, 3, 7, 10, 99, 100, 101, 10000): self.session.default_fetch_size = fetch_size future = self.session.execute_async("SELECT * FROM test3rf.test", timeout=20) event = Event() counter = count() number_of_calls = count() def handle_page(rows, future, counter, number_of_calls): next(number_of_calls) for row in rows: next(counter) if future.has_more_pages: future.start_fetching_next_page() else: event.set() def handle_error(err): event.set() self.fail(err) future.add_callbacks(callback=handle_page, callback_args=(future, counter, number_of_calls), errback=handle_error) event.wait() self.assertEqual(next(number_of_calls), 100 // fetch_size + 1) self.assertEqual(next(counter), 100) # simple statement future = self.session.execute_async(SimpleStatement("SELECT * FROM test3rf.test"), timeout=20) event.clear() counter = count() number_of_calls = count() future.add_callbacks(callback=handle_page, callback_args=(future, counter, number_of_calls), errback=handle_error) event.wait() self.assertEqual(next(number_of_calls), 100 // fetch_size + 1) self.assertEqual(next(counter), 100) # prepared statement future = self.session.execute_async(prepared, timeout=20) event.clear() counter = count() number_of_calls = count() future.add_callbacks(callback=handle_page, callback_args=(future, counter, number_of_calls), errback=handle_error) event.wait() self.assertEqual(next(number_of_calls), 100 // fetch_size + 1) self.assertEqual(next(counter), 100) def test_concurrent_with_paging(self): statements_and_params = zip(cycle(["INSERT INTO test3rf.test (k, v) VALUES (%s, 0)"]), [(i, ) for i in range(100)]) execute_concurrent(self.session, list(statements_and_params)) prepared = self.session.prepare("SELECT * FROM test3rf.test") for fetch_size in (2, 3, 7, 10, 99, 100, 101, 10000): self.session.default_fetch_size = fetch_size results = execute_concurrent_with_args(self.session, prepared, [None] * 10) self.assertEqual(10, len(results)) for (success, result) in results: self.assertTrue(success) self.assertEqual(100, len(list(result))) def test_fetch_size(self): """ Ensure per-statement fetch_sizes override the default fetch size. """ statements_and_params = zip(cycle(["INSERT INTO test3rf.test (k, v) VALUES (%s, 0)"]), [(i, ) for i in range(100)]) execute_concurrent(self.session, list(statements_and_params)) prepared = self.session.prepare("SELECT * FROM test3rf.test") self.session.default_fetch_size = 10 result = self.session.execute(prepared, []) self.assertTrue(result.has_more_pages) self.session.default_fetch_size = 2000 result = self.session.execute(prepared, []) self.assertFalse(result.has_more_pages) self.session.default_fetch_size = None result = self.session.execute(prepared, []) self.assertFalse(result.has_more_pages) self.session.default_fetch_size = 10 prepared.fetch_size = 2000 result = self.session.execute(prepared, []) self.assertFalse(result.has_more_pages) prepared.fetch_size = None result = self.session.execute(prepared, []) self.assertFalse(result.has_more_pages) prepared.fetch_size = 10 result = self.session.execute(prepared, []) self.assertTrue(result.has_more_pages) prepared.fetch_size = 2000 bound = prepared.bind([]) result = self.session.execute(bound, []) self.assertFalse(result.has_more_pages) prepared.fetch_size = None bound = prepared.bind([]) result = self.session.execute(bound, []) self.assertFalse(result.has_more_pages) prepared.fetch_size = 10 bound = prepared.bind([]) result = self.session.execute(bound, []) self.assertTrue(result.has_more_pages) bound.fetch_size = 2000 result = self.session.execute(bound, []) self.assertFalse(result.has_more_pages) bound.fetch_size = None result = self.session.execute(bound, []) self.assertFalse(result.has_more_pages) bound.fetch_size = 10 result = self.session.execute(bound, []) self.assertTrue(result.has_more_pages) s = SimpleStatement("SELECT * FROM test3rf.test", fetch_size=None) result = self.session.execute(s, []) self.assertFalse(result.has_more_pages) s = SimpleStatement("SELECT * FROM test3rf.test") result = self.session.execute(s, []) self.assertTrue(result.has_more_pages) s = SimpleStatement("SELECT * FROM test3rf.test") s.fetch_size = None result = self.session.execute(s, []) self.assertFalse(result.has_more_pages) diff --git a/tests/integration/standard/test_routing.py b/tests/integration/standard/test_routing.py index bf4c787..e1dabba 100644 --- a/tests/integration/standard/test_routing.py +++ b/tests/integration/standard/test_routing.py @@ -1,97 +1,95 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from uuid import uuid1 import logging log = logging.getLogger(__name__) -from cassandra.cluster import Cluster - -from tests.integration import use_singledc, PROTOCOL_VERSION +from tests.integration import use_singledc, TestCluster def setup_module(): use_singledc() class RoutingTests(unittest.TestCase): @property def cfname(self): return self._testMethodName.lower() @classmethod def setup_class(cls): - cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cls.cluster = TestCluster() cls.session = cls.cluster.connect('test1rf') @classmethod def teardown_class(cls): cls.cluster.shutdown() def insert_select_token(self, insert, select, key_values): s = self.session bound = insert.bind(key_values) s.execute(bound) my_token = s.cluster.metadata.token_map.token_class.from_key(bound.routing_key) cass_token = s.execute(select, key_values)[0][0] token = s.cluster.metadata.token_map.token_class(cass_token) self.assertEqual(my_token, token) def create_prepare(self, key_types): s = self.session table_name = "%s_%s" % (self.cfname, '_'.join(key_types)) key_count = len(key_types) key_decl = ', '.join(['k%d %s' % (i, t) for i, t in enumerate(key_types)]) primary_key = ', '.join(['k%d' % i for i in range(key_count)]) s.execute("CREATE TABLE %s (%s, v int, PRIMARY KEY ((%s)))" % (table_name, key_decl, primary_key)) parameter_places = ', '.join(['?'] * key_count) insert = s.prepare("INSERT INTO %s (%s, v) VALUES (%s, 1)" % (table_name, primary_key, parameter_places)) where_clause = ' AND '.join(['k%d = ?' % i for i in range(key_count)]) select = s.prepare("SELECT token(%s) FROM %s WHERE %s" % (primary_key, table_name, where_clause)) return insert, select def test_singular_key(self): # string insert, select = self.create_prepare(('text',)) self.insert_select_token(insert, select, ('some text value',)) # non-string insert, select = self.create_prepare(('bigint',)) self.insert_select_token(insert, select, (12390890177098123,)) def test_composite(self): # double bool insert, select = self.create_prepare(('double', 'boolean')) self.insert_select_token(insert, select, (3.1459, True)) self.insert_select_token(insert, select, (1.21e9, False)) # uuid string int insert, select = self.create_prepare(('timeuuid', 'varchar', 'int')) self.insert_select_token(insert, select, (uuid1(), 'asdf', 400)) self.insert_select_token(insert, select, (uuid1(), 'fdsa', -1)) diff --git a/tests/integration/standard/test_row_factories.py b/tests/integration/standard/test_row_factories.py index df709c3..93f25d9 100644 --- a/tests/integration/standard/test_row_factories.py +++ b/tests/integration/standard/test_row_factories.py @@ -1,259 +1,222 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -from tests.integration import get_server_versions, use_singledc, PROTOCOL_VERSION, BasicSharedKeyspaceUnitTestCaseWFunctionTable, BasicSharedKeyspaceUnitTestCase, execute_until_pass +from tests.integration import get_server_versions, use_singledc, \ + BasicSharedKeyspaceUnitTestCaseWFunctionTable, BasicSharedKeyspaceUnitTestCase, execute_until_pass, TestCluster try: import unittest2 as unittest except ImportError: import unittest # noqa -from cassandra.cluster import Cluster, ResultSet +from cassandra.cluster import ResultSet, ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.query import tuple_factory, named_tuple_factory, dict_factory, ordered_dict_factory from cassandra.util import OrderedDict def setup_module(): use_singledc() class NameTupleFactory(BasicSharedKeyspaceUnitTestCase): def setUp(self): - super(NameTupleFactory, self).setUp() - self.session.row_factory = named_tuple_factory + self.common_setup(1, execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=named_tuple_factory)}) ddl = ''' CREATE TABLE {0}.{1} ( k int PRIMARY KEY, v1 text, v2 text, v3 text)'''.format(self.ks_name, self.function_table_name) self.session.execute(ddl) execute_until_pass(self.session, ddl) def test_sanitizing(self): """ Test to ensure that same named results are surfaced in the NamedTupleFactory Creates a table with a few different text fields. Inserts a few values in that table. It then fetches the values and confirms that despite all be being selected as the same name they are propagated in the result set differently. @since 3.3 @jira_ticket PYTHON-467 @expected_result duplicate named results have unique row names. @test_category queries """ for x in range(5): insert1 = ''' INSERT INTO {0}.{1} ( k , v1, v2, v3 ) VALUES ( 1 , 'v1{2}', 'v2{2}','v3{2}' ) '''.format(self.keyspace_name, self.function_table_name, str(x)) self.session.execute(insert1) query = "SELECT v1 AS duplicate, v2 AS duplicate, v3 AS duplicate from {0}.{1}".format(self.ks_name, self.function_table_name) rs = self.session.execute(query) row = rs[0] self.assertTrue(hasattr(row, 'duplicate')) self.assertTrue(hasattr(row, 'duplicate_')) self.assertTrue(hasattr(row, 'duplicate__')) class RowFactoryTests(BasicSharedKeyspaceUnitTestCaseWFunctionTable): """ Test different row_factories and access code """ - def setUp(self): - super(RowFactoryTests, self).setUp() - self.insert1 = ''' - INSERT INTO {0}.{1} - ( k , v ) - VALUES - ( 1 , 1 ) - '''.format(self.keyspace_name, self.function_table_name) - - self.insert2 = ''' - INSERT INTO {0}.{1} - ( k , v ) - VALUES - ( 2 , 2 ) - '''.format(self.keyspace_name, self.function_table_name) - - self.select = ''' - SELECT * FROM {0}.{1} - '''.format(self.keyspace_name, self.function_table_name) - - def tearDown(self): - self.drop_function_table() + @classmethod + def setUpClass(cls): + cls.common_setup(rf=1, create_class_table=True) + q = "INSERT INTO {0}.{1} (k, v) VALUES (%s, %s)".format(cls.ks_name, cls.ks_name) + cls.session.execute(q, (1, 1)) + cls.session.execute(q, (2, 2)) + cls.select = "SELECT * FROM {0}.{1}".format(cls.ks_name, cls.ks_name) + + def _results_from_row_factory(self, row_factory): + cluster = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=row_factory)} + ) + with cluster: + return cluster.connect().execute(self.select) def test_tuple_factory(self): - session = self.session - session.row_factory = tuple_factory - - session.execute(self.insert1) - session.execute(self.insert2) - - result = session.execute(self.select) - + result = self._results_from_row_factory(tuple_factory) self.assertIsInstance(result, ResultSet) self.assertIsInstance(result[0], tuple) for row in result: self.assertEqual(row[0], row[1]) self.assertEqual(result[0][0], result[0][1]) self.assertEqual(result[0][0], 1) self.assertEqual(result[1][0], result[1][1]) self.assertEqual(result[1][0], 2) def test_named_tuple_factory(self): - session = self.session - session.row_factory = named_tuple_factory - - session.execute(self.insert1) - session.execute(self.insert2) - - result = session.execute(self.select) - + result = self._results_from_row_factory(named_tuple_factory) self.assertIsInstance(result, ResultSet) result = list(result) for row in result: self.assertEqual(row.k, row.v) self.assertEqual(result[0].k, result[0].v) self.assertEqual(result[0].k, 1) self.assertEqual(result[1].k, result[1].v) self.assertEqual(result[1].k, 2) - def test_dict_factory(self): - session = self.session - session.row_factory = dict_factory - - session.execute(self.insert1) - session.execute(self.insert2) - - result = session.execute(self.select) - + def _test_dict_factory(self, row_factory, row_type): + result = self._results_from_row_factory(row_factory) self.assertIsInstance(result, ResultSet) - self.assertIsInstance(result[0], dict) + self.assertIsInstance(result[0], row_type) for row in result: self.assertEqual(row['k'], row['v']) self.assertEqual(result[0]['k'], result[0]['v']) self.assertEqual(result[0]['k'], 1) self.assertEqual(result[1]['k'], result[1]['v']) self.assertEqual(result[1]['k'], 2) - def test_ordered_dict_factory(self): - session = self.session - session.row_factory = ordered_dict_factory - - session.execute(self.insert1) - session.execute(self.insert2) - - result = session.execute(self.select) - - self.assertIsInstance(result, ResultSet) - self.assertIsInstance(result[0], OrderedDict) - - for row in result: - self.assertEqual(row['k'], row['v']) + def test_dict_factory(self): + self._test_dict_factory(dict_factory, dict) - self.assertEqual(result[0]['k'], result[0]['v']) - self.assertEqual(result[0]['k'], 1) - self.assertEqual(result[1]['k'], result[1]['v']) - self.assertEqual(result[1]['k'], 2) + def test_ordered_dict_factory(self): + self._test_dict_factory(ordered_dict_factory, OrderedDict) def test_generator_row_factory(self): """ Test that ResultSet.one() works with a row_factory that contains a generator. @since 3.16 @jira_ticket PYTHON-1026 @expected_result one() returns the first row @test_category queries """ def generator_row_factory(column_names, rows): return _gen_row_factory(rows) def _gen_row_factory(rows): for r in rows: yield r session = self.session session.row_factory = generator_row_factory - session.execute(self.insert1) + session.execute(''' + INSERT INTO {0}.{1} + ( k , v ) + VALUES + ( 1 , 1 ) + '''.format(self.keyspace_name, self.function_table_name)) result = session.execute(self.select) self.assertIsInstance(result, ResultSet) first_row = result.one() self.assertEqual(first_row[0], first_row[1]) class NamedTupleFactoryAndNumericColNamesTests(unittest.TestCase): """ Test for PYTHON-122: Improve Error Handling/Reporting for named_tuple_factory and Numeric Column Names """ @classmethod def setup_class(cls): - cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION) + cls.cluster = TestCluster() cls.session = cls.cluster.connect() cls._cass_version, cls._cql_version = get_server_versions() ddl = ''' - CREATE TABLE test1rf.table_num_col ( key blob PRIMARY KEY, "626972746864617465" blob ) - WITH COMPACT STORAGE''' + CREATE TABLE test1rf.table_num_col ( key blob PRIMARY KEY, "626972746864617465" blob )''' cls.session.execute(ddl) @classmethod def teardown_class(cls): cls.session.execute("DROP TABLE test1rf.table_num_col") cls.cluster.shutdown() def test_no_exception_on_select(self): """ no exception on SELECT for numeric column name """ try: self.session.execute('SELECT * FROM test1rf.table_num_col') except ValueError as e: self.fail("Unexpected ValueError exception: %s" % e.message) def test_can_select_using_alias(self): """ can SELECT "" AS aliases """ if self._cass_version < (2, 0, 0): raise unittest.SkipTest("Alias in SELECT not supported before 2.0") try: self.session.execute('SELECT key, "626972746864617465" AS my_col from test1rf.table_num_col') except ValueError as e: self.fail("Unexpected ValueError exception: %s" % e.message) def test_can_select_with_dict_factory(self): """ can SELECT numeric column using dict_factory """ - self.session.row_factory = dict_factory - try: - self.session.execute('SELECT * FROM test1rf.table_num_col') - except ValueError as e: - self.fail("Unexpected ValueError exception: %s" % e.message) + with TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=dict_factory)} + ) as cluster: + try: + cluster.connect().execute('SELECT * FROM test1rf.table_num_col') + except ValueError as e: + self.fail("Unexpected ValueError exception: %s" % e.message) diff --git a/tests/integration/standard/test_single_interface.py b/tests/integration/standard/test_single_interface.py new file mode 100644 index 0000000..91451a5 --- /dev/null +++ b/tests/integration/standard/test_single_interface.py @@ -0,0 +1,77 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +import six + +from cassandra import ConsistencyLevel +from cassandra.query import SimpleStatement + +from packaging.version import Version +from tests.integration import use_singledc, PROTOCOL_VERSION, \ + remove_cluster, greaterthanorequalcass40, notdse, \ + CASSANDRA_VERSION, DSE_VERSION, TestCluster + + +def setup_module(): + if not DSE_VERSION and CASSANDRA_VERSION >= Version('4-a'): + remove_cluster() + use_singledc(use_single_interface=True) + +def teardown_module(): + remove_cluster() + + +@notdse +@greaterthanorequalcass40 +class SingleInterfaceTest(unittest.TestCase): + + def setUp(self): + self.cluster = TestCluster() + self.session = self.cluster.connect() + + def tearDown(self): + if self.cluster is not None: + self.cluster.shutdown() + + def test_single_interface(self): + """ + Test that we can connect to a multiple hosts bound to a single interface. + """ + hosts = self.cluster.metadata._hosts + broadcast_rpc_ports = [] + broadcast_ports = [] + self.assertEqual(len(hosts), 3) + for endpoint, host in six.iteritems(hosts): + + self.assertEqual(endpoint.address, host.broadcast_rpc_address) + self.assertEqual(endpoint.port, host.broadcast_rpc_port) + + if host.broadcast_rpc_port in broadcast_rpc_ports: + self.fail("Duplicate broadcast_rpc_port") + broadcast_rpc_ports.append(host.broadcast_rpc_port) + if host.broadcast_port in broadcast_ports: + self.fail("Duplicate broadcast_port") + broadcast_ports.append(host.broadcast_port) + + for _ in range(1, 100): + self.session.execute(SimpleStatement("select * from system_distributed.view_build_status", + consistency_level=ConsistencyLevel.ALL)) + + for pool in self.session.get_pools(): + self.assertEquals(1, pool.get_state()['open_count']) diff --git a/tests/integration/standard/test_types.py b/tests/integration/standard/test_types.py index b49ee06..0592b7d 100644 --- a/tests/integration/standard/test_types.py +++ b/tests/integration/standard/test_types.py @@ -1,948 +1,1315 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from datetime import datetime import math +from packaging.version import Version import six import cassandra from cassandra import InvalidRequest -from cassandra.cluster import Cluster +from cassandra import util +from cassandra.cluster import ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.concurrent import execute_concurrent_with_args from cassandra.cqltypes import Int32Type, EMPTY from cassandra.query import dict_factory, ordered_dict_factory from cassandra.util import sortedset, Duration from tests.unit.cython.utils import cythontest -from tests.integration import use_singledc, PROTOCOL_VERSION, execute_until_pass, notprotocolv1, \ - BasicSharedKeyspaceUnitTestCase, greaterthancass21, lessthancass30, greaterthanorequalcass3_10 +from tests.integration import use_singledc, execute_until_pass, notprotocolv1, \ + BasicSharedKeyspaceUnitTestCase, greaterthancass21, lessthancass30, greaterthanorequaldse51, \ + DSE_VERSION, greaterthanorequalcass3_10, requiredse, TestCluster from tests.integration.datatype_utils import update_datatypes, PRIMITIVE_DATATYPES, COLLECTION_TYPES, PRIMITIVE_DATATYPES_KEYS, \ get_sample, get_all_samples, get_collection_sample def setup_module(): use_singledc() update_datatypes() class TypeTests(BasicSharedKeyspaceUnitTestCase): @classmethod def setUpClass(cls): # cls._cass_version, cls. = get_server_versions() super(TypeTests, cls).setUpClass() cls.session.set_keyspace(cls.ks_name) def test_can_insert_blob_type_as_string(self): """ Tests that byte strings in Python maps to blob type in Cassandra """ s = self.session s.execute("CREATE TABLE blobstring (a ascii PRIMARY KEY, b blob)") params = ['key1', b'blobbyblob'] query = "INSERT INTO blobstring (a, b) VALUES (%s, %s)" # In python2, with Cassandra > 2.0, we don't treat the 'byte str' type as a blob, so we'll encode it # as a string literal and have the following failure. if six.PY2 and self.cql_version >= (3, 1, 0): # Blob values can't be specified using string notation in CQL 3.1.0 and # above which is used by default in Cassandra 2.0. if self.cass_version >= (2, 1, 0): msg = r'.*Invalid STRING constant \(.*?\) for "b" of type blob.*' else: msg = r'.*Invalid STRING constant \(.*?\) for b of type blob.*' self.assertRaisesRegexp(InvalidRequest, msg, s.execute, query, params) return # In python2, with Cassandra < 2.0, we can manually encode the 'byte str' type as hex for insertion in a blob. if six.PY2: cass_params = [params[0], params[1].encode('hex')] s.execute(query, cass_params) # In python 3, the 'bytes' type is treated as a blob, so we can correctly encode it with hex notation. else: s.execute(query, params) results = s.execute("SELECT * FROM blobstring")[0] for expected, actual in zip(params, results): self.assertEqual(expected, actual) def test_can_insert_blob_type_as_bytearray(self): """ Tests that blob type in Cassandra maps to bytearray in Python """ s = self.session s.execute("CREATE TABLE blobbytes (a ascii PRIMARY KEY, b blob)") params = ['key1', bytearray(b'blob1')] s.execute("INSERT INTO blobbytes (a, b) VALUES (%s, %s)", params) results = s.execute("SELECT * FROM blobbytes")[0] for expected, actual in zip(params, results): self.assertEqual(expected, actual) @unittest.skipIf(not hasattr(cassandra, 'deserializers'), "Cython required for to test DesBytesTypeArray deserializer") def test_des_bytes_type_array(self): """ Simple test to ensure the DesBytesTypeByteArray deserializer functionally works @since 3.1 @jira_ticket PYTHON-503 @expected_result byte array should be deserialized appropriately. @test_category queries:custom_payload """ original = None try: original = cassandra.deserializers.DesBytesType cassandra.deserializers.DesBytesType = cassandra.deserializers.DesBytesTypeByteArray s = self.session s.execute("CREATE TABLE blobbytes2 (a ascii PRIMARY KEY, b blob)") params = ['key1', bytearray(b'blob1')] s.execute("INSERT INTO blobbytes2 (a, b) VALUES (%s, %s)", params) results = s.execute("SELECT * FROM blobbytes2")[0] for expected, actual in zip(params, results): self.assertEqual(expected, actual) finally: if original is not None: cassandra.deserializers.DesBytesType=original def test_can_insert_primitive_datatypes(self): """ Test insertion of all datatype primitives """ - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(self.keyspace_name) # create table alpha_type_list = ["zz int PRIMARY KEY"] col_names = ["zz"] start_index = ord('a') for i, datatype in enumerate(PRIMITIVE_DATATYPES): alpha_type_list.append("{0} {1}".format(chr(start_index + i), datatype)) col_names.append(chr(start_index + i)) s.execute("CREATE TABLE alltypes ({0})".format(', '.join(alpha_type_list))) # create the input params = [0] for datatype in PRIMITIVE_DATATYPES: params.append((get_sample(datatype))) # insert into table as a simple statement columns_string = ', '.join(col_names) placeholders = ', '.join(["%s"] * len(col_names)) s.execute("INSERT INTO alltypes ({0}) VALUES ({1})".format(columns_string, placeholders), params) # verify data results = s.execute("SELECT {0} FROM alltypes WHERE zz=0".format(columns_string))[0] for expected, actual in zip(params, results): self.assertEqual(actual, expected) # try the same thing sending one insert at the time s.execute("TRUNCATE alltypes;") for i, datatype in enumerate(PRIMITIVE_DATATYPES): single_col_name = chr(start_index + i) single_col_names = ["zz", single_col_name] placeholders = ','.join(["%s"] * len(single_col_names)) single_columns_string = ', '.join(single_col_names) for j, data_sample in enumerate(get_all_samples(datatype)): key = i + 1000 * j single_params = (key, data_sample) s.execute("INSERT INTO alltypes ({0}) VALUES ({1})".format(single_columns_string, placeholders), single_params) # verify data result = s.execute("SELECT {0} FROM alltypes WHERE zz=%s".format(single_columns_string), (key,))[0][1] compare_value = data_sample if six.PY3: import ipaddress if isinstance(data_sample, ipaddress.IPv4Address) or isinstance(data_sample, ipaddress.IPv6Address): compare_value = str(data_sample) self.assertEqual(result, compare_value) # try the same thing with a prepared statement placeholders = ','.join(["?"] * len(col_names)) s.execute("TRUNCATE alltypes;") insert = s.prepare("INSERT INTO alltypes ({0}) VALUES ({1})".format(columns_string, placeholders)) s.execute(insert.bind(params)) # verify data results = s.execute("SELECT {0} FROM alltypes WHERE zz=0".format(columns_string))[0] for expected, actual in zip(params, results): self.assertEqual(actual, expected) # verify data with prepared statement query select = s.prepare("SELECT {0} FROM alltypes WHERE zz=?".format(columns_string)) results = s.execute(select.bind([0]))[0] for expected, actual in zip(params, results): self.assertEqual(actual, expected) # verify data with with prepared statement, use dictionary with no explicit columns - s.row_factory = ordered_dict_factory select = s.prepare("SELECT * FROM alltypes") - results = s.execute(select)[0] + results = s.execute(select, + execution_profile=s.execution_profile_clone_update(EXEC_PROFILE_DEFAULT, row_factory=ordered_dict_factory))[0] for expected, actual in zip(params, results.values()): self.assertEqual(actual, expected) c.shutdown() def test_can_insert_collection_datatypes(self): """ Test insertion of all collection types """ - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(self.keyspace_name) # use tuple encoding, to convert native python tuple into raw CQL s.encoder.mapping[tuple] = s.encoder.cql_encode_tuple # create table alpha_type_list = ["zz int PRIMARY KEY"] col_names = ["zz"] start_index = ord('a') for i, collection_type in enumerate(COLLECTION_TYPES): for j, datatype in enumerate(PRIMITIVE_DATATYPES_KEYS): if collection_type == "map": type_string = "{0}_{1} {2}<{3}, {3}>".format(chr(start_index + i), chr(start_index + j), collection_type, datatype) elif collection_type == "tuple": type_string = "{0}_{1} frozen<{2}<{3}>>".format(chr(start_index + i), chr(start_index + j), collection_type, datatype) else: type_string = "{0}_{1} {2}<{3}>".format(chr(start_index + i), chr(start_index + j), collection_type, datatype) alpha_type_list.append(type_string) col_names.append("{0}_{1}".format(chr(start_index + i), chr(start_index + j))) s.execute("CREATE TABLE allcoltypes ({0})".format(', '.join(alpha_type_list))) columns_string = ', '.join(col_names) # create the input for simple statement params = [0] for collection_type in COLLECTION_TYPES: for datatype in PRIMITIVE_DATATYPES_KEYS: params.append((get_collection_sample(collection_type, datatype))) # insert into table as a simple statement placeholders = ', '.join(["%s"] * len(col_names)) s.execute("INSERT INTO allcoltypes ({0}) VALUES ({1})".format(columns_string, placeholders), params) # verify data results = s.execute("SELECT {0} FROM allcoltypes WHERE zz=0".format(columns_string))[0] for expected, actual in zip(params, results): self.assertEqual(actual, expected) # create the input for prepared statement params = [0] for collection_type in COLLECTION_TYPES: for datatype in PRIMITIVE_DATATYPES_KEYS: params.append((get_collection_sample(collection_type, datatype))) # try the same thing with a prepared statement placeholders = ','.join(["?"] * len(col_names)) insert = s.prepare("INSERT INTO allcoltypes ({0}) VALUES ({1})".format(columns_string, placeholders)) s.execute(insert.bind(params)) # verify data results = s.execute("SELECT {0} FROM allcoltypes WHERE zz=0".format(columns_string))[0] for expected, actual in zip(params, results): self.assertEqual(actual, expected) # verify data with prepared statement query select = s.prepare("SELECT {0} FROM allcoltypes WHERE zz=?".format(columns_string)) results = s.execute(select.bind([0]))[0] for expected, actual in zip(params, results): self.assertEqual(actual, expected) # verify data with with prepared statement, use dictionary with no explicit columns - s.row_factory = ordered_dict_factory select = s.prepare("SELECT * FROM allcoltypes") - results = s.execute(select)[0] + results = s.execute(select, + execution_profile=s.execution_profile_clone_update(EXEC_PROFILE_DEFAULT, + row_factory=ordered_dict_factory))[0] for expected, actual in zip(params, results.values()): self.assertEqual(actual, expected) c.shutdown() def test_can_insert_empty_strings_and_nulls(self): """ Test insertion of empty strings and null values """ s = self.session # create table alpha_type_list = ["zz int PRIMARY KEY"] col_names = [] string_types = set(('ascii', 'text', 'varchar')) string_columns = set(('')) # this is just a list of types to try with empty strings non_string_types = PRIMITIVE_DATATYPES - string_types - set(('blob', 'date', 'inet', 'time', 'timestamp')) non_string_columns = set() start_index = ord('a') for i, datatype in enumerate(PRIMITIVE_DATATYPES): col_name = chr(start_index + i) alpha_type_list.append("{0} {1}".format(col_name, datatype)) col_names.append(col_name) if datatype in non_string_types: non_string_columns.add(col_name) if datatype in string_types: string_columns.add(col_name) execute_until_pass(s, "CREATE TABLE all_empty ({0})".format(', '.join(alpha_type_list))) # verify all types initially null with simple statement columns_string = ','.join(col_names) s.execute("INSERT INTO all_empty (zz) VALUES (2)") results = s.execute("SELECT {0} FROM all_empty WHERE zz=2".format(columns_string))[0] self.assertTrue(all(x is None for x in results)) # verify all types initially null with prepared statement select = s.prepare("SELECT {0} FROM all_empty WHERE zz=?".format(columns_string)) results = s.execute(select.bind([2]))[0] self.assertTrue(all(x is None for x in results)) # insert empty strings for string-like fields expected_values = dict((col, '') for col in string_columns) columns_string = ','.join(string_columns) placeholders = ','.join(["%s"] * len(string_columns)) s.execute("INSERT INTO all_empty (zz, {0}) VALUES (3, {1})".format(columns_string, placeholders), expected_values.values()) # verify string types empty with simple statement results = s.execute("SELECT {0} FROM all_empty WHERE zz=3".format(columns_string))[0] for expected, actual in zip(expected_values.values(), results): self.assertEqual(actual, expected) # verify string types empty with prepared statement results = s.execute(s.prepare("SELECT {0} FROM all_empty WHERE zz=?".format(columns_string)), [3])[0] for expected, actual in zip(expected_values.values(), results): self.assertEqual(actual, expected) # non-string types shouldn't accept empty strings for col in non_string_columns: query = "INSERT INTO all_empty (zz, {0}) VALUES (4, %s)".format(col) with self.assertRaises(InvalidRequest): s.execute(query, ['']) insert = s.prepare("INSERT INTO all_empty (zz, {0}) VALUES (4, ?)".format(col)) with self.assertRaises(TypeError): s.execute(insert, ['']) # verify that Nones can be inserted and overwrites existing data # create the input params = [] for datatype in PRIMITIVE_DATATYPES: params.append((get_sample(datatype))) # insert the data columns_string = ','.join(col_names) placeholders = ','.join(["%s"] * len(col_names)) simple_insert = "INSERT INTO all_empty (zz, {0}) VALUES (5, {1})".format(columns_string, placeholders) s.execute(simple_insert, params) # then insert None, which should null them out null_values = [None] * len(col_names) s.execute(simple_insert, null_values) # check via simple statement query = "SELECT {0} FROM all_empty WHERE zz=5".format(columns_string) results = s.execute(query)[0] for col in results: self.assertEqual(None, col) # check via prepared statement select = s.prepare("SELECT {0} FROM all_empty WHERE zz=?".format(columns_string)) results = s.execute(select.bind([5]))[0] for col in results: self.assertEqual(None, col) # do the same thing again, but use a prepared statement to insert the nulls s.execute(simple_insert, params) placeholders = ','.join(["?"] * len(col_names)) insert = s.prepare("INSERT INTO all_empty (zz, {0}) VALUES (5, {1})".format(columns_string, placeholders)) s.execute(insert, null_values) results = s.execute(query)[0] for col in results: self.assertEqual(None, col) results = s.execute(select.bind([5]))[0] for col in results: self.assertEqual(None, col) def test_can_insert_empty_values_for_int32(self): """ Ensure Int32Type supports empty values """ s = self.session execute_until_pass(s, "CREATE TABLE empty_values (a text PRIMARY KEY, b int)") execute_until_pass(s, "INSERT INTO empty_values (a, b) VALUES ('a', blobAsInt(0x))") try: Int32Type.support_empty_values = True results = execute_until_pass(s, "SELECT b FROM empty_values WHERE a='a'")[0] self.assertIs(EMPTY, results.b) finally: Int32Type.support_empty_values = False def test_timezone_aware_datetimes_are_timestamps(self): """ Ensure timezone-aware datetimes are converted to timestamps correctly """ try: import pytz except ImportError as exc: raise unittest.SkipTest('pytz is not available: %r' % (exc,)) dt = datetime(1997, 8, 29, 11, 14) eastern_tz = pytz.timezone('US/Eastern') eastern_tz.localize(dt) s = self.session s.execute("CREATE TABLE tz_aware (a ascii PRIMARY KEY, b timestamp)") # test non-prepared statement s.execute("INSERT INTO tz_aware (a, b) VALUES ('key1', %s)", [dt]) result = s.execute("SELECT b FROM tz_aware WHERE a='key1'")[0].b self.assertEqual(dt.utctimetuple(), result.utctimetuple()) # test prepared statement insert = s.prepare("INSERT INTO tz_aware (a, b) VALUES ('key2', ?)") s.execute(insert.bind([dt])) result = s.execute("SELECT b FROM tz_aware WHERE a='key2'")[0].b self.assertEqual(dt.utctimetuple(), result.utctimetuple()) def test_can_insert_tuples(self): """ Basic test of tuple functionality """ if self.cass_version < (2, 1, 0): raise unittest.SkipTest("The tuple type was introduced in Cassandra 2.1") - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(self.keyspace_name) # use this encoder in order to insert tuples s.encoder.mapping[tuple] = s.encoder.cql_encode_tuple s.execute("CREATE TABLE tuple_type (a int PRIMARY KEY, b frozen>)") # test non-prepared statement complete = ('foo', 123, True) s.execute("INSERT INTO tuple_type (a, b) VALUES (0, %s)", parameters=(complete,)) result = s.execute("SELECT b FROM tuple_type WHERE a=0")[0] self.assertEqual(complete, result.b) partial = ('bar', 456) partial_result = partial + (None,) s.execute("INSERT INTO tuple_type (a, b) VALUES (1, %s)", parameters=(partial,)) result = s.execute("SELECT b FROM tuple_type WHERE a=1")[0] self.assertEqual(partial_result, result.b) # test single value tuples subpartial = ('zoo',) subpartial_result = subpartial + (None, None) s.execute("INSERT INTO tuple_type (a, b) VALUES (2, %s)", parameters=(subpartial,)) result = s.execute("SELECT b FROM tuple_type WHERE a=2")[0] self.assertEqual(subpartial_result, result.b) # test prepared statement prepared = s.prepare("INSERT INTO tuple_type (a, b) VALUES (?, ?)") s.execute(prepared, parameters=(3, complete)) s.execute(prepared, parameters=(4, partial)) s.execute(prepared, parameters=(5, subpartial)) # extra items in the tuple should result in an error self.assertRaises(ValueError, s.execute, prepared, parameters=(0, (1, 2, 3, 4, 5, 6))) prepared = s.prepare("SELECT b FROM tuple_type WHERE a=?") self.assertEqual(complete, s.execute(prepared, (3,))[0].b) self.assertEqual(partial_result, s.execute(prepared, (4,))[0].b) self.assertEqual(subpartial_result, s.execute(prepared, (5,))[0].b) c.shutdown() def test_can_insert_tuples_with_varying_lengths(self): """ Test tuple types of lengths of 1, 2, 3, and 384 to ensure edge cases work as expected. """ if self.cass_version < (2, 1, 0): raise unittest.SkipTest("The tuple type was introduced in Cassandra 2.1") - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=dict_factory)} + ) s = c.connect(self.keyspace_name) - # set the row_factory to dict_factory for programmatic access # set the encoder for tuples for the ability to write tuples - s.row_factory = dict_factory s.encoder.mapping[tuple] = s.encoder.cql_encode_tuple # programmatically create the table with tuples of said sizes lengths = (1, 2, 3, 384) value_schema = [] for i in lengths: value_schema += [' v_%s frozen>' % (i, ', '.join(['int'] * i))] s.execute("CREATE TABLE tuple_lengths (k int PRIMARY KEY, %s)" % (', '.join(value_schema),)) # insert tuples into same key using different columns # and verify the results for i in lengths: # ensure tuples of larger sizes throw an error created_tuple = tuple(range(0, i + 1)) self.assertRaises(InvalidRequest, s.execute, "INSERT INTO tuple_lengths (k, v_%s) VALUES (0, %s)", (i, created_tuple)) # ensure tuples of proper sizes are written and read correctly created_tuple = tuple(range(0, i)) s.execute("INSERT INTO tuple_lengths (k, v_%s) VALUES (0, %s)", (i, created_tuple)) result = s.execute("SELECT v_%s FROM tuple_lengths WHERE k=0", (i,))[0] self.assertEqual(tuple(created_tuple), result['v_%s' % i]) c.shutdown() def test_can_insert_tuples_all_primitive_datatypes(self): """ Ensure tuple subtypes are appropriately handled. """ if self.cass_version < (2, 1, 0): raise unittest.SkipTest("The tuple type was introduced in Cassandra 2.1") - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(self.keyspace_name) s.encoder.mapping[tuple] = s.encoder.cql_encode_tuple s.execute("CREATE TABLE tuple_primitive (" "k int PRIMARY KEY, " "v frozen>)" % ','.join(PRIMITIVE_DATATYPES)) values = [] type_count = len(PRIMITIVE_DATATYPES) for i, data_type in enumerate(PRIMITIVE_DATATYPES): # create tuples to be written and ensure they match with the expected response # responses have trailing None values for every element that has not been written values.append(get_sample(data_type)) expected = tuple(values + [None] * (type_count - len(values))) s.execute("INSERT INTO tuple_primitive (k, v) VALUES (%s, %s)", (i, tuple(values))) result = s.execute("SELECT v FROM tuple_primitive WHERE k=%s", (i,))[0] self.assertEqual(result.v, expected) c.shutdown() def test_can_insert_tuples_all_collection_datatypes(self): """ Ensure tuple subtypes are appropriately handled for maps, sets, and lists. """ if self.cass_version < (2, 1, 0): raise unittest.SkipTest("The tuple type was introduced in Cassandra 2.1") - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=dict_factory)} + ) s = c.connect(self.keyspace_name) - # set the row_factory to dict_factory for programmatic access # set the encoder for tuples for the ability to write tuples - s.row_factory = dict_factory s.encoder.mapping[tuple] = s.encoder.cql_encode_tuple values = [] # create list values for datatype in PRIMITIVE_DATATYPES_KEYS: values.append('v_{0} frozen>>'.format(len(values), datatype)) # create set values for datatype in PRIMITIVE_DATATYPES_KEYS: values.append('v_{0} frozen>>'.format(len(values), datatype)) # create map values for datatype in PRIMITIVE_DATATYPES_KEYS: datatype_1 = datatype_2 = datatype if datatype == 'blob': # unhashable type: 'bytearray' datatype_1 = 'ascii' values.append('v_{0} frozen>>'.format(len(values), datatype_1, datatype_2)) # make sure we're testing all non primitive data types in the future if set(COLLECTION_TYPES) != set(['tuple', 'list', 'map', 'set']): raise NotImplemented('Missing datatype not implemented: {}'.format( set(COLLECTION_TYPES) - set(['tuple', 'list', 'map', 'set']) )) # create table s.execute("CREATE TABLE tuple_non_primative (" "k int PRIMARY KEY, " "%s)" % ', '.join(values)) i = 0 # test tuple> for datatype in PRIMITIVE_DATATYPES_KEYS: created_tuple = tuple([[get_sample(datatype)]]) s.execute("INSERT INTO tuple_non_primative (k, v_%s) VALUES (0, %s)", (i, created_tuple)) result = s.execute("SELECT v_%s FROM tuple_non_primative WHERE k=0", (i,))[0] self.assertEqual(created_tuple, result['v_%s' % i]) i += 1 # test tuple> for datatype in PRIMITIVE_DATATYPES_KEYS: created_tuple = tuple([sortedset([get_sample(datatype)])]) s.execute("INSERT INTO tuple_non_primative (k, v_%s) VALUES (0, %s)", (i, created_tuple)) result = s.execute("SELECT v_%s FROM tuple_non_primative WHERE k=0", (i,))[0] self.assertEqual(created_tuple, result['v_%s' % i]) i += 1 # test tuple> for datatype in PRIMITIVE_DATATYPES_KEYS: if datatype == 'blob': # unhashable type: 'bytearray' created_tuple = tuple([{get_sample('ascii'): get_sample(datatype)}]) else: created_tuple = tuple([{get_sample(datatype): get_sample(datatype)}]) s.execute("INSERT INTO tuple_non_primative (k, v_%s) VALUES (0, %s)", (i, created_tuple)) result = s.execute("SELECT v_%s FROM tuple_non_primative WHERE k=0", (i,))[0] self.assertEqual(created_tuple, result['v_%s' % i]) i += 1 c.shutdown() def nested_tuples_schema_helper(self, depth): """ Helper method for creating nested tuple schema """ if depth == 0: return 'int' else: return 'tuple<%s>' % self.nested_tuples_schema_helper(depth - 1) def nested_tuples_creator_helper(self, depth): """ Helper method for creating nested tuples """ if depth == 0: return 303 else: return (self.nested_tuples_creator_helper(depth - 1), ) def test_can_insert_nested_tuples(self): """ Ensure nested are appropriately handled. """ if self.cass_version < (2, 1, 0): raise unittest.SkipTest("The tuple type was introduced in Cassandra 2.1") - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=dict_factory)} + ) s = c.connect(self.keyspace_name) - # set the row_factory to dict_factory for programmatic access # set the encoder for tuples for the ability to write tuples - s.row_factory = dict_factory s.encoder.mapping[tuple] = s.encoder.cql_encode_tuple # create a table with multiple sizes of nested tuples s.execute("CREATE TABLE nested_tuples (" "k int PRIMARY KEY, " "v_1 frozen<%s>," "v_2 frozen<%s>," "v_3 frozen<%s>," "v_32 frozen<%s>" ")" % (self.nested_tuples_schema_helper(1), self.nested_tuples_schema_helper(2), self.nested_tuples_schema_helper(3), self.nested_tuples_schema_helper(32))) for i in (1, 2, 3, 32): # create tuple created_tuple = self.nested_tuples_creator_helper(i) # write tuple s.execute("INSERT INTO nested_tuples (k, v_%s) VALUES (%s, %s)", (i, i, created_tuple)) # verify tuple was written and read correctly result = s.execute("SELECT v_%s FROM nested_tuples WHERE k=%s", (i, i))[0] self.assertEqual(created_tuple, result['v_%s' % i]) c.shutdown() def test_can_insert_tuples_with_nulls(self): """ Test tuples with null and empty string fields. """ if self.cass_version < (2, 1, 0): raise unittest.SkipTest("The tuple type was introduced in Cassandra 2.1") s = self.session s.execute("CREATE TABLE tuples_nulls (k int PRIMARY KEY, t frozen>)") insert = s.prepare("INSERT INTO tuples_nulls (k, t) VALUES (0, ?)") s.execute(insert, [(None, None, None, None)]) result = s.execute("SELECT * FROM tuples_nulls WHERE k=0") self.assertEqual((None, None, None, None), result[0].t) read = s.prepare("SELECT * FROM tuples_nulls WHERE k=0") self.assertEqual((None, None, None, None), s.execute(read)[0].t) # also test empty strings where compatible s.execute(insert, [('', None, None, b'')]) result = s.execute("SELECT * FROM tuples_nulls WHERE k=0") self.assertEqual(('', None, None, b''), result[0].t) self.assertEqual(('', None, None, b''), s.execute(read)[0].t) def test_can_insert_unicode_query_string(self): """ Test to ensure unicode strings can be used in a query """ s = self.session s.execute(u"SELECT * FROM system.local WHERE key = 'ef\u2052ef'") s.execute(u"SELECT * FROM system.local WHERE key = %s", (u"fe\u2051fe",)) def test_can_read_composite_type(self): """ Test to ensure that CompositeTypes can be used in a query """ s = self.session s.execute(""" CREATE TABLE composites ( a int PRIMARY KEY, b 'org.apache.cassandra.db.marshal.CompositeType(AsciiType, Int32Type)' )""") # CompositeType string literals are split on ':' chars s.execute("INSERT INTO composites (a, b) VALUES (0, 'abc:123')") result = s.execute("SELECT * FROM composites WHERE a = 0")[0] self.assertEqual(0, result.a) self.assertEqual(('abc', 123), result.b) # CompositeType values can omit elements at the end s.execute("INSERT INTO composites (a, b) VALUES (0, 'abc')") result = s.execute("SELECT * FROM composites WHERE a = 0")[0] self.assertEqual(0, result.a) self.assertEqual(('abc',), result.b) @notprotocolv1 def test_special_float_cql_encoding(self): """ Test to insure that Infinity -Infinity and NaN are supported by the python driver. @since 3.0.0 @jira_ticket PYTHON-282 @expected_result nan, inf and -inf can be inserted and selected correctly. @test_category data_types """ s = self.session s.execute(""" CREATE TABLE float_cql_encoding ( f float PRIMARY KEY, d double )""") items = (float('nan'), float('inf'), float('-inf')) def verify_insert_select(ins_statement, sel_statement): execute_concurrent_with_args(s, ins_statement, ((f, f) for f in items)) for f in items: row = s.execute(sel_statement, (f,))[0] if math.isnan(f): self.assertTrue(math.isnan(row.f)) self.assertTrue(math.isnan(row.d)) else: self.assertEqual(row.f, f) self.assertEqual(row.d, f) # cql encoding verify_insert_select('INSERT INTO float_cql_encoding (f, d) VALUES (%s, %s)', 'SELECT * FROM float_cql_encoding WHERE f=%s') s.execute("TRUNCATE float_cql_encoding") # prepared binding verify_insert_select(s.prepare('INSERT INTO float_cql_encoding (f, d) VALUES (?, ?)'), s.prepare('SELECT * FROM float_cql_encoding WHERE f=?')) @cythontest def test_cython_decimal(self): """ Test to validate that decimal deserialization works correctly in with our cython extensions @since 3.0.0 @jira_ticket PYTHON-212 @expected_result no exceptions are thrown, decimal is decoded correctly @test_category data_types serialization """ self.session.execute("CREATE TABLE {0} (dc decimal PRIMARY KEY)".format(self.function_table_name)) try: self.session.execute("INSERT INTO {0} (dc) VALUES (-1.08430792318105707)".format(self.function_table_name)) results = self.session.execute("SELECT * FROM {0}".format(self.function_table_name)) self.assertTrue(str(results[0].dc) == '-1.08430792318105707') finally: self.session.execute("DROP TABLE {0}".format(self.function_table_name)) @greaterthanorequalcass3_10 def test_smoke_duration_values(self): """ Test to write several Duration values to the database and verify they can be read correctly. The verify than an exception is arisen if the value is too big @since 3.10 @jira_ticket PYTHON-747 @expected_result the read value in C* matches the written one @test_category data_types serialization """ self.session.execute(""" CREATE TABLE duration_smoke (k int primary key, v duration) """) self.addCleanup(self.session.execute, "DROP TABLE duration_smoke") prepared = self.session.prepare(""" INSERT INTO duration_smoke (k, v) VALUES (?, ?) """) nanosecond_smoke_values = [0, -1, 1, 100, 1000, 1000000, 1000000000, 10000000000000,-9223372036854775807, 9223372036854775807, int("7FFFFFFFFFFFFFFF", 16), int("-7FFFFFFFFFFFFFFF", 16)] month_day_smoke_values = [0, -1, 1, 100, 1000, 1000000, 1000000000, int("7FFFFFFF", 16), int("-7FFFFFFF", 16)] for nanosecond_value in nanosecond_smoke_values: for month_day_value in month_day_smoke_values: # Must have the same sign if (month_day_value <= 0) != (nanosecond_value <= 0): continue self.session.execute(prepared, (1, Duration(month_day_value, month_day_value, nanosecond_value))) results = self.session.execute("SELECT * FROM duration_smoke") v = results[0][1] self.assertEqual(Duration(month_day_value, month_day_value, nanosecond_value), v, "Error encoding value {0},{0},{1}".format(month_day_value, nanosecond_value)) self.assertRaises(ValueError, self.session.execute, prepared, (1, Duration(0, 0, int("8FFFFFFFFFFFFFF0", 16)))) self.assertRaises(ValueError, self.session.execute, prepared, (1, Duration(0, int("8FFFFFFFFFFFFFF0", 16), 0))) self.assertRaises(ValueError, self.session.execute, prepared, (1, Duration(int("8FFFFFFFFFFFFFF0", 16), 0, 0))) + +@requiredse +class AbstractDateRangeTest(): + + def test_single_value_daterange_round_trip(self): + self._daterange_round_trip( + util.DateRange( + value=util.DateRangeBound( + datetime(2014, 10, 1, 0), + util.DateRangePrecision.YEAR + ) + ), + util.DateRange( + value=util.DateRangeBound( + datetime(2014, 1, 1, 0), + util.DateRangePrecision.YEAR + ) + ) + ) + + def test_open_high_daterange_round_trip(self): + self._daterange_round_trip( + util.DateRange( + lower_bound=util.DateRangeBound( + datetime(2013, 10, 1, 6, 20, 39), + util.DateRangePrecision.SECOND + ) + ) + ) + + def test_open_low_daterange_round_trip(self): + self._daterange_round_trip( + util.DateRange( + upper_bound=util.DateRangeBound( + datetime(2013, 10, 28), + util.DateRangePrecision.DAY + ) + ) + ) + + def test_open_both_daterange_round_trip(self): + self._daterange_round_trip( + util.DateRange( + lower_bound=util.OPEN_BOUND, + upper_bound=util.OPEN_BOUND, + ) + ) + + def test_closed_daterange_round_trip(self): + insert = util.DateRange( + lower_bound=util.DateRangeBound( + datetime(2015, 3, 1, 10, 15, 30, 1000), + util.DateRangePrecision.MILLISECOND + ), + upper_bound=util.DateRangeBound( + datetime(2016, 1, 1, 10, 15, 30, 999000), + util.DateRangePrecision.MILLISECOND + ) + ) + self._daterange_round_trip(insert) + + def test_epoch_value_round_trip(self): + insert = util.DateRange( + value=util.DateRangeBound( + datetime(1970, 1, 1), + util.DateRangePrecision.YEAR + ) + ) + self._daterange_round_trip(insert) + + def test_double_bounded_daterange_round_trip_from_string(self): + self._daterange_round_trip( + '[2015-03-01T10:15:30.010Z TO 2016-01-01T10:15:30.999Z]', + util.DateRange( + lower_bound=util.DateRangeBound( + datetime(2015, 3, 1, 10, 15, 30, 10000), + util.DateRangePrecision.MILLISECOND + ), + upper_bound=util.DateRangeBound( + datetime(2016, 1, 1, 10, 15, 30, 999000), + util.DateRangePrecision.MILLISECOND + ), + ) + ) + + def test_open_high_daterange_round_trip_from_string(self): + self._daterange_round_trip( + '[2015-03 TO *]', + util.DateRange( + lower_bound=util.DateRangeBound( + datetime(2015, 3, 1, 0, 0), + util.DateRangePrecision.MONTH + ), + upper_bound=util.DateRangeBound(None, None) + ) + ) + + def test_open_low_daterange_round_trip_from_string(self): + self._daterange_round_trip( + '[* TO 2015-03]', + util.DateRange( + lower_bound=util.DateRangeBound(None, None), + upper_bound=util.DateRangeBound( + datetime(2015, 3, 1, 0, 0), + 'MONTH' + ) + ) + ) + + def test_no_bounds_daterange_round_trip_from_string(self): + self._daterange_round_trip( + '[* TO *]', + util.DateRange( + lower_bound=(None, None), + upper_bound=(None, None) + ) + ) + + def test_single_no_bounds_daterange_round_trip_from_string(self): + self._daterange_round_trip( + '*', + util.DateRange( + value=(None, None) + ) + ) + + def test_single_value_daterange_round_trip_from_string(self): + self._daterange_round_trip( + '2001-01-01T12:30:30.000Z', + util.DateRange( + value=util.DateRangeBound( + datetime(2001, 1, 1, 12, 30, 30), + 'MILLISECOND' + ) + ) + ) + + def test_daterange_with_negative_bound_round_trip_from_string(self): + self._daterange_round_trip( + '[-1991-01-01T00:00:00.001 TO 1990-02-03]', + util.DateRange( + lower_bound=(-124997039999999, 'MILLISECOND'), + upper_bound=util.DateRangeBound( + datetime(1990, 2, 3, 12, 30, 30), + 'DAY' + ) + ) + ) + + def test_epoch_value_round_trip_from_string(self): + self._daterange_round_trip( + '1970', + util.DateRange( + value=util.DateRangeBound( + datetime(1970, 1, 1), + util.DateRangePrecision.YEAR + ) + ) + ) + + +@greaterthanorequaldse51 +class TestDateRangePrepared(AbstractDateRangeTest, BasicSharedKeyspaceUnitTestCase): + """ + Tests various inserts and queries using Date-ranges and prepared queries + + @since 2.0.0 + @jira_ticket PYTHON-668 + @expected_result Date ranges will be inserted and retrieved succesfully + + @test_category data_types + """ + + @classmethod + def setUpClass(cls): + super(TestDateRangePrepared, cls).setUpClass() + cls.session.set_keyspace(cls.ks_name) + if DSE_VERSION and DSE_VERSION >= Version('5.1'): + cls.session.execute("CREATE TABLE tab (dr 'DateRangeType' PRIMARY KEY)") + + + def _daterange_round_trip(self, to_insert, expected=None): + if isinstance(to_insert, util.DateRange): + prep = self.session.prepare("INSERT INTO tab (dr) VALUES (?);") + self.session.execute(prep, (to_insert,)) + prep_sel = self.session.prepare("SELECT * FROM tab WHERE dr = ? ") + results = self.session.execute(prep_sel, (to_insert,)) + else: + prep = self.session.prepare("INSERT INTO tab (dr) VALUES ('%s');" % (to_insert,)) + self.session.execute(prep) + prep_sel = self.session.prepare("SELECT * FROM tab WHERE dr = '%s' " % (to_insert,)) + results = self.session.execute(prep_sel) + + dr = results[0].dr + # sometimes this is truncated in the assertEquals output on failure; + if isinstance(expected, six.string_types): + self.assertEqual(str(dr), expected) + else: + self.assertEqual(dr, expected or to_insert) + + # This can only be run as a prepared statement + def test_daterange_wide(self): + self._daterange_round_trip( + util.DateRange( + lower_bound=(-9223372036854775808, 'MILLISECOND'), + upper_bound=(9223372036854775807, 'MILLISECOND') + ), + '[-9223372036854775808ms TO 9223372036854775807ms]' + ) + # This can only be run as a prepared statement + def test_daterange_with_negative_bound_round_trip_to_string(self): + self._daterange_round_trip( + util.DateRange( + lower_bound=(-124997039999999, 'MILLISECOND'), + upper_bound=util.DateRangeBound( + datetime(1990, 2, 3, 12, 30, 30), + 'DAY' + ) + ), + '[-124997039999999ms TO 1990-02-03]' + ) + +@greaterthanorequaldse51 +class TestDateRangeSimple(AbstractDateRangeTest, BasicSharedKeyspaceUnitTestCase): + """ + Tests various inserts and queries using Date-ranges and simple queries + + @since 2.0.0 + @jira_ticket PYTHON-668 + @expected_result DateRanges will be inserted and retrieved successfully + @test_category data_types + """ + @classmethod + def setUpClass(cls): + super(TestDateRangeSimple, cls).setUpClass() + cls.session.set_keyspace(cls.ks_name) + if DSE_VERSION and DSE_VERSION >= Version('5.1'): + cls.session.execute("CREATE TABLE tab (dr 'DateRangeType' PRIMARY KEY)") + + + def _daterange_round_trip(self, to_insert, expected=None): + + query = "INSERT INTO tab (dr) VALUES ('{0}');".format(to_insert) + self.session.execute("INSERT INTO tab (dr) VALUES ('{0}');".format(to_insert)) + query = "SELECT * FROM tab WHERE dr = '{0}' ".format(to_insert) + results= self.session.execute("SELECT * FROM tab WHERE dr = '{0}' ".format(to_insert)) + + dr = results[0].dr + # sometimes this is truncated in the assertEquals output on failure; + if isinstance(expected, six.string_types): + self.assertEqual(str(dr), expected) + else: + self.assertEqual(dr, expected or to_insert) + + +@greaterthanorequaldse51 +class TestDateRangeCollection(BasicSharedKeyspaceUnitTestCase): + + + @classmethod + def setUpClass(cls): + super(TestDateRangeCollection, cls).setUpClass() + cls.session.set_keyspace(cls.ks_name) + + def test_date_range_collection(self): + """ + Tests DateRange type in collections + + @since 2.0.0 + @jira_ticket PYTHON-668 + @expected_result DateRanges will be inserted and retrieved successfully when part of a list or map + @test_category data_types + """ + self.session.execute("CREATE TABLE dateRangeIntegrationTest5 (k int PRIMARY KEY, l list<'DateRangeType'>, s set<'DateRangeType'>, dr2i map<'DateRangeType', int>, i2dr map)") + self.session.execute("INSERT INTO dateRangeIntegrationTest5 (k, l, s, i2dr, dr2i) VALUES (" + + "1, " + + "['[2000-01-01T10:15:30.001Z TO 2020]', '[2010-01-01T10:15:30.001Z TO 2020]', '2001-01-02'], " + + "{'[2000-01-01T10:15:30.001Z TO 2020]', '[2000-01-01T10:15:30.001Z TO 2020]', '[2010-01-01T10:15:30.001Z TO 2020]'}, " + + "{1: '[2000-01-01T10:15:30.001Z TO 2020]', 2: '[2010-01-01T10:15:30.001Z TO 2020]'}, " + + "{'[2000-01-01T10:15:30.001Z TO 2020]': 1, '[2010-01-01T10:15:30.001Z TO 2020]': 2})") + results = list(self.session.execute("SELECT * FROM dateRangeIntegrationTest5")) + self.assertEqual(len(results),1) + + lower_bound_1 = util.DateRangeBound(datetime(2000, 1, 1, 10, 15, 30, 1000), 'MILLISECOND') + + lower_bound_2 = util.DateRangeBound(datetime(2010, 1, 1, 10, 15, 30, 1000), 'MILLISECOND') + + upper_bound_1 = util.DateRangeBound(datetime(2020, 1, 1), 'YEAR') + + value_1 = util.DateRangeBound(datetime(2001, 1, 2), 'DAY') + + dt = util.DateRange(lower_bound=lower_bound_1, upper_bound=upper_bound_1) + dt2 = util.DateRange(lower_bound=lower_bound_2, upper_bound=upper_bound_1) + dt3 = util.DateRange(value=value_1) + + + + list_result = results[0].l + self.assertEqual(3, len(list_result)) + self.assertEqual(list_result[0],dt) + self.assertEqual(list_result[1],dt2) + self.assertEqual(list_result[2],dt3) + + set_result = results[0].s + self.assertEqual(len(set_result), 2) + self.assertIn(dt, set_result) + self.assertIn(dt2, set_result) + + d2i = results[0].dr2i + self.assertEqual(len(d2i), 2) + self.assertEqual(d2i[dt],1) + self.assertEqual(d2i[dt2],2) + + i2r = results[0].i2dr + self.assertEqual(len(i2r), 2) + self.assertEqual(i2r[1],dt) + self.assertEqual(i2r[2],dt2) + + def test_allow_date_range_in_udt_tuple(self): + """ + Tests DateRanges in tuples and udts + + @since 2.0.0 + @jira_ticket PYTHON-668 + @expected_result DateRanges will be inserted and retrieved successfully in udt's and tuples + @test_category data_types + """ + self.session.execute("CREATE TYPE IF NOT EXISTS test_udt (i int, range 'DateRangeType')") + self.session.execute("CREATE TABLE dateRangeIntegrationTest4 (k int PRIMARY KEY, u test_udt, uf frozen, t tuple<'DateRangeType', int>, tf frozen>)") + self.session.execute("INSERT INTO dateRangeIntegrationTest4 (k, u, uf, t, tf) VALUES (" + + "1, " + + "{i: 10, range: '[2000-01-01T10:15:30.003Z TO 2020-01-01T10:15:30.001Z]'}, " + + "{i: 20, range: '[2000-01-01T10:15:30.003Z TO 2020-01-01T10:15:30.001Z]'}, " + + "('[2000-01-01T10:15:30.003Z TO 2020-01-01T10:15:30.001Z]', 30), " + + "('[2000-01-01T10:15:30.003Z TO 2020-01-01T10:15:30.001Z]', 40))") + + lower_bound = util.DateRangeBound( + datetime(2000, 1, 1, 10, 15, 30, 3000), + 'MILLISECOND') + + upper_bound = util.DateRangeBound( + datetime(2020, 1, 1, 10, 15, 30, 1000), + 'MILLISECOND') + + expected_dt = util.DateRange(lower_bound=lower_bound ,upper_bound=upper_bound) + + results_list = list(self.session.execute("SELECT * FROM dateRangeIntegrationTest4")) + self.assertEqual(len(results_list), 1) + udt = results_list[0].u + self.assertEqual(udt.range, expected_dt) + self.assertEqual(udt.i, 10) + + + uf = results_list[0].uf + self.assertEqual(uf.range, expected_dt) + self.assertEqual(uf.i, 20) + + t = results_list[0].t + self.assertEqual(t[0], expected_dt) + self.assertEqual(t[1], 30) + + tf = results_list[0].tf + self.assertEqual(tf[0], expected_dt) + self.assertEqual(tf[1], 40) + + class TypeTestsProtocol(BasicSharedKeyspaceUnitTestCase): @greaterthancass21 @lessthancass30 def test_nested_types_with_protocol_version(self): """ Test to validate that nested type serialization works on various protocol versions. Provided the version of cassandra is greater the 2.1.3 we would expect to nested to types to work at all protocol versions. @since 3.0.0 @jira_ticket PYTHON-215 @expected_result no exceptions are thrown @test_category data_types serialization """ ddl = '''CREATE TABLE {0}.t ( k int PRIMARY KEY, v list>>)'''.format(self.keyspace_name) self.session.execute(ddl) ddl = '''CREATE TABLE {0}.u ( k int PRIMARY KEY, v set>>)'''.format(self.keyspace_name) self.session.execute(ddl) ddl = '''CREATE TABLE {0}.v ( k int PRIMARY KEY, v map>, frozen>>, v1 frozen>)'''.format(self.keyspace_name) self.session.execute(ddl) self.session.execute("CREATE TYPE {0}.typ (v0 frozen>>>, v1 frozen>)".format(self.keyspace_name)) ddl = '''CREATE TABLE {0}.w ( k int PRIMARY KEY, v frozen)'''.format(self.keyspace_name) self.session.execute(ddl) - for pvi in range(1, 5): + for pvi in range(3, 5): self.run_inserts_at_version(pvi) - for pvr in range(1, 5): + for pvr in range(3, 5): self.read_inserts_at_level(pvr) def read_inserts_at_level(self, proto_ver): - session = Cluster(protocol_version=proto_ver).connect(self.keyspace_name) + session = TestCluster(protocol_version=proto_ver).connect(self.keyspace_name) try: results = session.execute('select * from t')[0] self.assertEqual("[SortedSet([1, 2]), SortedSet([3, 5])]", str(results.v)) results = session.execute('select * from u')[0] self.assertEqual("SortedSet([[1, 2], [3, 5]])", str(results.v)) results = session.execute('select * from v')[0] self.assertEqual("{SortedSet([1, 2]): [1, 2, 3], SortedSet([3, 5]): [4, 5, 6]}", str(results.v)) results = session.execute('select * from w')[0] self.assertEqual("typ(v0=OrderedMapSerializedKey([(1, [1, 2, 3]), (2, [4, 5, 6])]), v1=[7, 8, 9])", str(results.v)) finally: session.cluster.shutdown() def run_inserts_at_version(self, proto_ver): - session = Cluster(protocol_version=proto_ver).connect(self.keyspace_name) + session = TestCluster(protocol_version=proto_ver).connect(self.keyspace_name) try: p = session.prepare('insert into t (k, v) values (?, ?)') session.execute(p, (0, [{1, 2}, {3, 5}])) p = session.prepare('insert into u (k, v) values (?, ?)') session.execute(p, (0, {(1, 2), (3, 5)})) p = session.prepare('insert into v (k, v, v1) values (?, ?, ?)') session.execute(p, (0, {(1, 2): [1, 2, 3], (3, 5): [4, 5, 6]}, (123, 'four'))) p = session.prepare('insert into w (k, v) values (?, ?)') session.execute(p, (0, ({1: [1, 2, 3], 2: [4, 5, 6]}, [7, 8, 9]))) finally: session.cluster.shutdown() - - - diff --git a/tests/integration/standard/test_udts.py b/tests/integration/standard/test_udts.py index 514c562..6d9676f 100644 --- a/tests/integration/standard/test_udts.py +++ b/tests/integration/standard/test_udts.py @@ -1,760 +1,757 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from collections import namedtuple from functools import partial import six from cassandra import InvalidRequest -from cassandra.cluster import Cluster, UserTypeDoesNotExist +from cassandra.cluster import UserTypeDoesNotExist, ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.query import dict_factory from cassandra.util import OrderedMap -from tests.integration import use_singledc, PROTOCOL_VERSION, execute_until_pass, BasicSegregatedKeyspaceUnitTestCase, \ - greaterthancass20, greaterthanorequalcass36, lessthancass30 +from tests.integration import use_singledc, execute_until_pass, \ + BasicSegregatedKeyspaceUnitTestCase, greaterthancass20, lessthancass30, greaterthanorequalcass36, TestCluster from tests.integration.datatype_utils import update_datatypes, PRIMITIVE_DATATYPES, PRIMITIVE_DATATYPES_KEYS, \ COLLECTION_TYPES, get_sample, get_collection_sample nested_collection_udt = namedtuple('nested_collection_udt', ['m', 't', 'l', 's']) nested_collection_udt_nested = namedtuple('nested_collection_udt_nested', ['m', 't', 'l', 's', 'u']) def setup_module(): use_singledc() update_datatypes() @greaterthancass20 class UDTTests(BasicSegregatedKeyspaceUnitTestCase): @property def table_name(self): return self._testMethodName.lower() def setUp(self): super(UDTTests, self).setUp() self.session.set_keyspace(self.keyspace_name) @greaterthanorequalcass36 def test_non_frozen_udts(self): """ Test to ensure that non frozen udt's work with C* >3.6. @since 3.7.0 @jira_ticket PYTHON-498 @expected_result Non frozen UDT's are supported @test_category data_types, udt """ self.session.execute("USE {0}".format(self.keyspace_name)) self.session.execute("CREATE TYPE user (state text, has_corn boolean)") self.session.execute("CREATE TABLE {0} (a int PRIMARY KEY, b user)".format(self.function_table_name)) User = namedtuple('user', ('state', 'has_corn')) self.cluster.register_user_type(self.keyspace_name, "user", User) self.session.execute("INSERT INTO {0} (a, b) VALUES (%s, %s)".format(self.function_table_name), (0, User("Nebraska", True))) self.session.execute("UPDATE {0} SET b.has_corn = False where a = 0".format(self.function_table_name)) result = self.session.execute("SELECT * FROM {0}".format(self.function_table_name)) self.assertFalse(result[0].b.has_corn) table_sql = self.cluster.metadata.keyspaces[self.keyspace_name].tables[self.function_table_name].as_cql_query() self.assertNotIn("", table_sql) def test_can_insert_unprepared_registered_udts(self): """ Test the insertion of unprepared, registered UDTs """ - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.execute("CREATE TYPE user (age int, name text)") s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen)") User = namedtuple('user', ('age', 'name')) c.register_user_type(self.keyspace_name, "user", User) s.execute("INSERT INTO mytable (a, b) VALUES (%s, %s)", (0, User(42, 'bob'))) result = s.execute("SELECT b FROM mytable WHERE a=0") row = result[0] self.assertEqual(42, row.b.age) self.assertEqual('bob', row.b.name) self.assertTrue(type(row.b) is User) # use the same UDT name in a different keyspace s.execute(""" CREATE KEYSPACE udt_test_unprepared_registered2 WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1' } """) s.set_keyspace("udt_test_unprepared_registered2") s.execute("CREATE TYPE user (state text, is_cool boolean)") s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen)") User = namedtuple('user', ('state', 'is_cool')) c.register_user_type("udt_test_unprepared_registered2", "user", User) s.execute("INSERT INTO mytable (a, b) VALUES (%s, %s)", (0, User('Texas', True))) result = s.execute("SELECT b FROM mytable WHERE a=0") row = result[0] self.assertEqual('Texas', row.b.state) self.assertEqual(True, row.b.is_cool) self.assertTrue(type(row.b) is User) s.execute("DROP KEYSPACE udt_test_unprepared_registered2") c.shutdown() def test_can_register_udt_before_connecting(self): """ Test the registration of UDTs before session creation """ - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(wait_for_all_pools=True) s.execute(""" CREATE KEYSPACE udt_test_register_before_connecting WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1' } """) s.set_keyspace("udt_test_register_before_connecting") s.execute("CREATE TYPE user (age int, name text)") s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen)") s.execute(""" CREATE KEYSPACE udt_test_register_before_connecting2 WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1' } """) s.set_keyspace("udt_test_register_before_connecting2") s.execute("CREATE TYPE user (state text, is_cool boolean)") s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen)") # now that types are defined, shutdown and re-create Cluster c.shutdown() - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() User1 = namedtuple('user', ('age', 'name')) User2 = namedtuple('user', ('state', 'is_cool')) c.register_user_type("udt_test_register_before_connecting", "user", User1) c.register_user_type("udt_test_register_before_connecting2", "user", User2) s = c.connect(wait_for_all_pools=True) s.set_keyspace("udt_test_register_before_connecting") s.execute("INSERT INTO mytable (a, b) VALUES (%s, %s)", (0, User1(42, 'bob'))) result = s.execute("SELECT b FROM mytable WHERE a=0") row = result[0] self.assertEqual(42, row.b.age) self.assertEqual('bob', row.b.name) self.assertTrue(type(row.b) is User1) # use the same UDT name in a different keyspace s.set_keyspace("udt_test_register_before_connecting2") s.execute("INSERT INTO mytable (a, b) VALUES (%s, %s)", (0, User2('Texas', True))) result = s.execute("SELECT b FROM mytable WHERE a=0") row = result[0] self.assertEqual('Texas', row.b.state) self.assertEqual(True, row.b.is_cool) self.assertTrue(type(row.b) is User2) s.execute("DROP KEYSPACE udt_test_register_before_connecting") s.execute("DROP KEYSPACE udt_test_register_before_connecting2") c.shutdown() def test_can_insert_prepared_unregistered_udts(self): """ Test the insertion of prepared, unregistered UDTs """ - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.execute("CREATE TYPE user (age int, name text)") s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen)") User = namedtuple('user', ('age', 'name')) insert = s.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)") s.execute(insert, (0, User(42, 'bob'))) select = s.prepare("SELECT b FROM mytable WHERE a=?") result = s.execute(select, (0,)) row = result[0] self.assertEqual(42, row.b.age) self.assertEqual('bob', row.b.name) # use the same UDT name in a different keyspace s.execute(""" CREATE KEYSPACE udt_test_prepared_unregistered2 WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1' } """) s.set_keyspace("udt_test_prepared_unregistered2") s.execute("CREATE TYPE user (state text, is_cool boolean)") s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen)") User = namedtuple('user', ('state', 'is_cool')) insert = s.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)") s.execute(insert, (0, User('Texas', True))) select = s.prepare("SELECT b FROM mytable WHERE a=?") result = s.execute(select, (0,)) row = result[0] self.assertEqual('Texas', row.b.state) self.assertEqual(True, row.b.is_cool) s.execute("DROP KEYSPACE udt_test_prepared_unregistered2") c.shutdown() def test_can_insert_prepared_registered_udts(self): """ Test the insertion of prepared, registered UDTs """ - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.execute("CREATE TYPE user (age int, name text)") User = namedtuple('user', ('age', 'name')) c.register_user_type(self.keyspace_name, "user", User) s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen)") insert = s.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)") s.execute(insert, (0, User(42, 'bob'))) select = s.prepare("SELECT b FROM mytable WHERE a=?") result = s.execute(select, (0,)) row = result[0] self.assertEqual(42, row.b.age) self.assertEqual('bob', row.b.name) self.assertTrue(type(row.b) is User) # use the same UDT name in a different keyspace s.execute(""" CREATE KEYSPACE udt_test_prepared_registered2 WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1' } """) s.set_keyspace("udt_test_prepared_registered2") s.execute("CREATE TYPE user (state text, is_cool boolean)") User = namedtuple('user', ('state', 'is_cool')) c.register_user_type("udt_test_prepared_registered2", "user", User) s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen)") insert = s.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)") s.execute(insert, (0, User('Texas', True))) select = s.prepare("SELECT b FROM mytable WHERE a=?") result = s.execute(select, (0,)) row = result[0] self.assertEqual('Texas', row.b.state) self.assertEqual(True, row.b.is_cool) self.assertTrue(type(row.b) is User) s.execute("DROP KEYSPACE udt_test_prepared_registered2") c.shutdown() def test_can_insert_udts_with_nulls(self): """ Test the insertion of UDTs with null and empty string fields """ - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.execute("CREATE TYPE user (a text, b int, c uuid, d blob)") User = namedtuple('user', ('a', 'b', 'c', 'd')) c.register_user_type(self.keyspace_name, "user", User) s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen)") insert = s.prepare("INSERT INTO mytable (a, b) VALUES (0, ?)") s.execute(insert, [User(None, None, None, None)]) results = s.execute("SELECT b FROM mytable WHERE a=0") self.assertEqual((None, None, None, None), results[0].b) select = s.prepare("SELECT b FROM mytable WHERE a=0") self.assertEqual((None, None, None, None), s.execute(select)[0].b) # also test empty strings s.execute(insert, [User('', None, None, six.binary_type())]) results = s.execute("SELECT b FROM mytable WHERE a=0") self.assertEqual(('', None, None, six.binary_type()), results[0].b) c.shutdown() def test_can_insert_udts_with_varying_lengths(self): """ Test for ensuring extra-lengthy udts are properly inserted """ - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(self.keyspace_name, wait_for_all_pools=True) - MAX_TEST_LENGTH = 254 + max_test_length = 254 # create the seed udt, increase timeout to avoid the query failure on slow systems s.execute("CREATE TYPE lengthy_udt ({0})" .format(', '.join(['v_{0} int'.format(i) - for i in range(MAX_TEST_LENGTH)]))) + for i in range(max_test_length)]))) # create a table with multiple sizes of nested udts # no need for all nested types, only a spot checked few and the largest one s.execute("CREATE TABLE mytable (" "k int PRIMARY KEY, " "v frozen)") # create and register the seed udt type - udt = namedtuple('lengthy_udt', tuple(['v_{0}'.format(i) for i in range(MAX_TEST_LENGTH)])) + udt = namedtuple('lengthy_udt', tuple(['v_{0}'.format(i) for i in range(max_test_length)])) c.register_user_type(self.keyspace_name, "lengthy_udt", udt) # verify inserts and reads - for i in (0, 1, 2, 3, MAX_TEST_LENGTH): + for i in (0, 1, 2, 3, max_test_length): # create udt - params = [j for j in range(i)] + [None for j in range(MAX_TEST_LENGTH - i)] + params = [j for j in range(i)] + [None for j in range(max_test_length - i)] created_udt = udt(*params) # write udt s.execute("INSERT INTO mytable (k, v) VALUES (0, %s)", (created_udt,)) # verify udt was written and read correctly, increase timeout to avoid the query failure on slow systems result = s.execute("SELECT v FROM mytable WHERE k=0")[0] self.assertEqual(created_udt, result.v) c.shutdown() - def nested_udt_schema_helper(self, session, MAX_NESTING_DEPTH): + def nested_udt_schema_helper(self, session, max_nesting_depth): # create the seed udt execute_until_pass(session, "CREATE TYPE depth_0 (age int, name text)") # create the nested udts - for i in range(MAX_NESTING_DEPTH): + for i in range(max_nesting_depth): execute_until_pass(session, "CREATE TYPE depth_{0} (value frozen)".format(i + 1, i)) # create a table with multiple sizes of nested udts # no need for all nested types, only a spot checked few and the largest one execute_until_pass(session, "CREATE TABLE mytable (" "k int PRIMARY KEY, " "v_0 frozen, " "v_1 frozen, " "v_2 frozen, " "v_3 frozen, " - "v_{0} frozen)".format(MAX_NESTING_DEPTH)) + "v_{0} frozen)".format(max_nesting_depth)) def nested_udt_creation_helper(self, udts, i): if i == 0: return udts[0](42, 'Bob') else: return udts[i](self.nested_udt_creation_helper(udts, i - 1)) - def nested_udt_verification_helper(self, session, MAX_NESTING_DEPTH, udts): - for i in (0, 1, 2, 3, MAX_NESTING_DEPTH): + def nested_udt_verification_helper(self, session, max_nesting_depth, udts): + for i in (0, 1, 2, 3, max_nesting_depth): # create udt udt = self.nested_udt_creation_helper(udts, i) # write udt via simple statement session.execute("INSERT INTO mytable (k, v_%s) VALUES (0, %s)", [i, udt]) # verify udt was written and read correctly result = session.execute("SELECT v_{0} FROM mytable WHERE k=0".format(i))[0] self.assertEqual(udt, result["v_{0}".format(i)]) # write udt via prepared statement insert = session.prepare("INSERT INTO mytable (k, v_{0}) VALUES (1, ?)".format(i)) session.execute(insert, [udt]) # verify udt was written and read correctly result = session.execute("SELECT v_{0} FROM mytable WHERE k=1".format(i))[0] self.assertEqual(udt, result["v_{0}".format(i)]) + def _cluster_default_dict_factory(self): + return TestCluster( + execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=dict_factory)} + ) + def test_can_insert_nested_registered_udts(self): """ Test for ensuring nested registered udts are properly inserted """ + with self._cluster_default_dict_factory() as c: + s = c.connect(self.keyspace_name, wait_for_all_pools=True) - c = Cluster(protocol_version=PROTOCOL_VERSION) - s = c.connect(self.keyspace_name, wait_for_all_pools=True) - s.row_factory = dict_factory + max_nesting_depth = 16 - MAX_NESTING_DEPTH = 16 + # create the schema + self.nested_udt_schema_helper(s, max_nesting_depth) - # create the schema - self.nested_udt_schema_helper(s, MAX_NESTING_DEPTH) - - # create and register the seed udt type - udts = [] - udt = namedtuple('depth_0', ('age', 'name')) - udts.append(udt) - c.register_user_type(self.keyspace_name, "depth_0", udts[0]) - - # create and register the nested udt types - for i in range(MAX_NESTING_DEPTH): - udt = namedtuple('depth_{0}'.format(i + 1), ('value')) + # create and register the seed udt type + udts = [] + udt = namedtuple('depth_0', ('age', 'name')) udts.append(udt) - c.register_user_type(self.keyspace_name, "depth_{0}".format(i + 1), udts[i + 1]) + c.register_user_type(self.keyspace_name, "depth_0", udts[0]) - # insert udts and verify inserts with reads - self.nested_udt_verification_helper(s, MAX_NESTING_DEPTH, udts) + # create and register the nested udt types + for i in range(max_nesting_depth): + udt = namedtuple('depth_{0}'.format(i + 1), ('value')) + udts.append(udt) + c.register_user_type(self.keyspace_name, "depth_{0}".format(i + 1), udts[i + 1]) - c.shutdown() + # insert udts and verify inserts with reads + self.nested_udt_verification_helper(s, max_nesting_depth, udts) def test_can_insert_nested_unregistered_udts(self): """ Test for ensuring nested unregistered udts are properly inserted """ - c = Cluster(protocol_version=PROTOCOL_VERSION) - s = c.connect(self.keyspace_name, wait_for_all_pools=True) - s.row_factory = dict_factory - - MAX_NESTING_DEPTH = 16 + with self._cluster_default_dict_factory() as c: + s = c.connect(self.keyspace_name, wait_for_all_pools=True) - # create the schema - self.nested_udt_schema_helper(s, MAX_NESTING_DEPTH) + max_nesting_depth = 16 - # create the seed udt type - udts = [] - udt = namedtuple('depth_0', ('age', 'name')) - udts.append(udt) + # create the schema + self.nested_udt_schema_helper(s, max_nesting_depth) - # create the nested udt types - for i in range(MAX_NESTING_DEPTH): - udt = namedtuple('depth_{0}'.format(i + 1), ('value')) + # create the seed udt type + udts = [] + udt = namedtuple('depth_0', ('age', 'name')) udts.append(udt) - # insert udts via prepared statements and verify inserts with reads - for i in (0, 1, 2, 3, MAX_NESTING_DEPTH): - # create udt - udt = self.nested_udt_creation_helper(udts, i) + # create the nested udt types + for i in range(max_nesting_depth): + udt = namedtuple('depth_{0}'.format(i + 1), ('value')) + udts.append(udt) - # write udt - insert = s.prepare("INSERT INTO mytable (k, v_{0}) VALUES (0, ?)".format(i)) - s.execute(insert, [udt]) + # insert udts via prepared statements and verify inserts with reads + for i in (0, 1, 2, 3, max_nesting_depth): + # create udt + udt = self.nested_udt_creation_helper(udts, i) - # verify udt was written and read correctly - result = s.execute("SELECT v_{0} FROM mytable WHERE k=0".format(i))[0] - self.assertEqual(udt, result["v_{0}".format(i)]) + # write udt + insert = s.prepare("INSERT INTO mytable (k, v_{0}) VALUES (0, ?)".format(i)) + s.execute(insert, [udt]) - c.shutdown() + # verify udt was written and read correctly + result = s.execute("SELECT v_{0} FROM mytable WHERE k=0".format(i))[0] + self.assertEqual(udt, result["v_{0}".format(i)]) def test_can_insert_nested_registered_udts_with_different_namedtuples(self): """ Test for ensuring nested udts are inserted correctly when the created namedtuples are use names that are different the cql type. """ - c = Cluster(protocol_version=PROTOCOL_VERSION) - s = c.connect(self.keyspace_name, wait_for_all_pools=True) - s.row_factory = dict_factory + with self._cluster_default_dict_factory() as c: + s = c.connect(self.keyspace_name, wait_for_all_pools=True) - MAX_NESTING_DEPTH = 16 + max_nesting_depth = 16 - # create the schema - self.nested_udt_schema_helper(s, MAX_NESTING_DEPTH) + # create the schema + self.nested_udt_schema_helper(s, max_nesting_depth) - # create and register the seed udt type - udts = [] - udt = namedtuple('level_0', ('age', 'name')) - udts.append(udt) - c.register_user_type(self.keyspace_name, "depth_0", udts[0]) - - # create and register the nested udt types - for i in range(MAX_NESTING_DEPTH): - udt = namedtuple('level_{0}'.format(i + 1), ('value')) + # create and register the seed udt type + udts = [] + udt = namedtuple('level_0', ('age', 'name')) udts.append(udt) - c.register_user_type(self.keyspace_name, "depth_{0}".format(i + 1), udts[i + 1]) + c.register_user_type(self.keyspace_name, "depth_0", udts[0]) - # insert udts and verify inserts with reads - self.nested_udt_verification_helper(s, MAX_NESTING_DEPTH, udts) + # create and register the nested udt types + for i in range(max_nesting_depth): + udt = namedtuple('level_{0}'.format(i + 1), ('value')) + udts.append(udt) + c.register_user_type(self.keyspace_name, "depth_{0}".format(i + 1), udts[i + 1]) - c.shutdown() + # insert udts and verify inserts with reads + self.nested_udt_verification_helper(s, max_nesting_depth, udts) def test_raise_error_on_nonexisting_udts(self): """ Test for ensuring that an error is raised for operating on a nonexisting udt or an invalid keyspace """ - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(self.keyspace_name, wait_for_all_pools=True) User = namedtuple('user', ('age', 'name')) with self.assertRaises(UserTypeDoesNotExist): c.register_user_type("some_bad_keyspace", "user", User) with self.assertRaises(UserTypeDoesNotExist): c.register_user_type("system", "user", User) with self.assertRaises(InvalidRequest): s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen)") c.shutdown() def test_can_insert_udt_all_datatypes(self): """ Test for inserting various types of PRIMITIVE_DATATYPES into UDT's """ - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(self.keyspace_name, wait_for_all_pools=True) # create UDT alpha_type_list = [] start_index = ord('a') for i, datatype in enumerate(PRIMITIVE_DATATYPES): alpha_type_list.append("{0} {1}".format(chr(start_index + i), datatype)) s.execute(""" CREATE TYPE alldatatypes ({0}) """.format(', '.join(alpha_type_list)) ) s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen)") # register UDT alphabet_list = [] for i in range(ord('a'), ord('a') + len(PRIMITIVE_DATATYPES)): alphabet_list.append('{0}'.format(chr(i))) Alldatatypes = namedtuple("alldatatypes", alphabet_list) c.register_user_type(self.keyspace_name, "alldatatypes", Alldatatypes) # insert UDT data params = [] for datatype in PRIMITIVE_DATATYPES: params.append((get_sample(datatype))) insert = s.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)") s.execute(insert, (0, Alldatatypes(*params))) # retrieve and verify data results = s.execute("SELECT * FROM mytable") row = results[0].b for expected, actual in zip(params, row): self.assertEqual(expected, actual) c.shutdown() def test_can_insert_udt_all_collection_datatypes(self): """ Test for inserting various types of COLLECTION_TYPES into UDT's """ - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(self.keyspace_name, wait_for_all_pools=True) # create UDT alpha_type_list = [] start_index = ord('a') for i, collection_type in enumerate(COLLECTION_TYPES): for j, datatype in enumerate(PRIMITIVE_DATATYPES_KEYS): if collection_type == "map": type_string = "{0}_{1} {2}<{3}, {3}>".format(chr(start_index + i), chr(start_index + j), collection_type, datatype) elif collection_type == "tuple": type_string = "{0}_{1} frozen<{2}<{3}>>".format(chr(start_index + i), chr(start_index + j), collection_type, datatype) else: type_string = "{0}_{1} {2}<{3}>".format(chr(start_index + i), chr(start_index + j), collection_type, datatype) alpha_type_list.append(type_string) s.execute(""" CREATE TYPE alldatatypes ({0}) """.format(', '.join(alpha_type_list)) ) s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen)") # register UDT alphabet_list = [] for i in range(ord('a'), ord('a') + len(COLLECTION_TYPES)): for j in range(ord('a'), ord('a') + len(PRIMITIVE_DATATYPES_KEYS)): alphabet_list.append('{0}_{1}'.format(chr(i), chr(j))) Alldatatypes = namedtuple("alldatatypes", alphabet_list) c.register_user_type(self.keyspace_name, "alldatatypes", Alldatatypes) # insert UDT data params = [] for collection_type in COLLECTION_TYPES: for datatype in PRIMITIVE_DATATYPES_KEYS: params.append((get_collection_sample(collection_type, datatype))) insert = s.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)") s.execute(insert, (0, Alldatatypes(*params))) # retrieve and verify data results = s.execute("SELECT * FROM mytable") row = results[0].b for expected, actual in zip(params, row): self.assertEqual(expected, actual) c.shutdown() def insert_select_column(self, session, table_name, column_name, value): insert = session.prepare("INSERT INTO %s (k, %s) VALUES (?, ?)" % (table_name, column_name)) session.execute(insert, (0, value)) result = session.execute("SELECT %s FROM %s WHERE k=%%s" % (column_name, table_name), (0,))[0][0] self.assertEqual(result, value) def test_can_insert_nested_collections(self): """ Test for inserting various types of nested COLLECTION_TYPES into tables and UDTs """ if self.cass_version < (2, 1, 3): raise unittest.SkipTest("Support for nested collections was introduced in Cassandra 2.1.3") - c = Cluster(protocol_version=PROTOCOL_VERSION) + c = TestCluster() s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.encoder.mapping[tuple] = s.encoder.cql_encode_tuple name = self._testMethodName s.execute(""" CREATE TYPE %s ( m frozen>, t tuple, l frozen>, s frozen> )""" % name) s.execute(""" CREATE TYPE %s_nested ( m frozen>, t tuple, l frozen>, s frozen>, u frozen<%s> )""" % (name, name)) s.execute(""" CREATE TABLE %s ( k int PRIMARY KEY, map_map map>, frozen>>, map_set map>, frozen>>, map_list map>, frozen>>, map_tuple map>, frozen>>, map_udt map, frozen<%s>>, )""" % (name, name, name)) validate = partial(self.insert_select_column, s, name) validate('map_map', OrderedMap([({1: 1, 2: 2}, {3: 3, 4: 4}), ({5: 5, 6: 6}, {7: 7, 8: 8})])) validate('map_set', OrderedMap([(set((1, 2)), set((3, 4))), (set((5, 6)), set((7, 8)))])) validate('map_list', OrderedMap([([1, 2], [3, 4]), ([5, 6], [7, 8])])) validate('map_tuple', OrderedMap([((1, 2), (3,)), ((4, 5), (6,))])) value = nested_collection_udt({1: 'v1', 2: 'v2'}, (3, 'v3'), [4, 5, 6, 7], set((8, 9, 10))) key = nested_collection_udt_nested(value.m, value.t, value.l, value.s, value) key2 = nested_collection_udt_nested({3: 'v3'}, value.t, value.l, value.s, value) validate('map_udt', OrderedMap([(key, value), (key2, value)])) c.shutdown() def test_non_alphanum_identifiers(self): """ PYTHON-413 """ s = self.session non_alphanum_name = 'test.field@#$%@%#!' type_name = 'type2' s.execute('CREATE TYPE "%s" ("%s" text)' % (non_alphanum_name, non_alphanum_name)) s.execute('CREATE TYPE %s ("%s" text)' % (type_name, non_alphanum_name)) # table with types as map keys to make sure the tuple lookup works s.execute('CREATE TABLE %s (k int PRIMARY KEY, non_alphanum_type_map map, int>, alphanum_type_map map, int>)' % (self.table_name, non_alphanum_name, type_name)) s.execute('INSERT INTO %s (k, non_alphanum_type_map, alphanum_type_map) VALUES (%s, {{"%s": \'nonalphanum\'}: 0}, {{"%s": \'alphanum\'}: 1})' % (self.table_name, 0, non_alphanum_name, non_alphanum_name)) row = s.execute('SELECT * FROM %s' % (self.table_name,))[0] k, v = row.non_alphanum_type_map.popitem() self.assertEqual(v, 0) self.assertEqual(k.__class__, tuple) self.assertEqual(k[0], 'nonalphanum') k, v = row.alphanum_type_map.popitem() self.assertEqual(v, 1) self.assertNotEqual(k.__class__, tuple) # should be the namedtuple type self.assertEqual(k[0], 'alphanum') self.assertEqual(k.field_0_, 'alphanum') # named tuple with positional field name @lessthancass30 def test_type_alteration(self): + """ + Support for ALTER TYPE was removed in CASSANDRA-12443 + """ s = self.session type_name = "type_name" self.assertNotIn(type_name, s.cluster.metadata.keyspaces['udttests'].user_types) s.execute('CREATE TYPE %s (v0 int)' % (type_name,)) self.assertIn(type_name, s.cluster.metadata.keyspaces['udttests'].user_types) s.execute('CREATE TABLE %s (k int PRIMARY KEY, v frozen<%s>)' % (self.table_name, type_name)) s.execute('INSERT INTO %s (k, v) VALUES (0, {v0 : 1})' % (self.table_name,)) s.cluster.register_user_type('udttests', type_name, dict) val = s.execute('SELECT v FROM %s' % self.table_name)[0][0] self.assertEqual(val['v0'], 1) # add field s.execute('ALTER TYPE %s ADD v1 text' % (type_name,)) val = s.execute('SELECT v FROM %s' % self.table_name)[0][0] self.assertEqual(val['v0'], 1) self.assertIsNone(val['v1']) s.execute("INSERT INTO %s (k, v) VALUES (0, {v0 : 2, v1 : 'sometext'})" % (self.table_name,)) val = s.execute('SELECT v FROM %s' % self.table_name)[0][0] self.assertEqual(val['v0'], 2) self.assertEqual(val['v1'], 'sometext') # alter field type s.execute('ALTER TYPE %s ALTER v1 TYPE blob' % (type_name,)) s.execute("INSERT INTO %s (k, v) VALUES (0, {v0 : 3, v1 : 0xdeadbeef})" % (self.table_name,)) val = s.execute('SELECT v FROM %s' % self.table_name)[0][0] self.assertEqual(val['v0'], 3) self.assertEqual(val['v1'], six.b('\xde\xad\xbe\xef')) @lessthancass30 def test_alter_udt(self): """ Test to ensure that altered UDT's are properly surfaced without needing to restart the underlying session. @since 3.0.0 @jira_ticket PYTHON-226 @expected_result UDT's will reflect added columns without a session restart. @test_category data_types, udt """ # Create udt ensure it has the proper column names. self.session.set_keyspace(self.keyspace_name) self.session.execute("CREATE TYPE typetoalter (a int)") typetoalter = namedtuple('typetoalter', ('a')) self.session.execute("CREATE TABLE {0} (pk int primary key, typetoalter frozen)".format(self.function_table_name)) insert_statement = self.session.prepare("INSERT INTO {0} (pk, typetoalter) VALUES (?, ?)".format(self.function_table_name)) self.session.execute(insert_statement, [1, typetoalter(1)]) results = self.session.execute("SELECT * from {0}".format(self.function_table_name)) for result in results: self.assertTrue(hasattr(result.typetoalter, 'a')) self.assertFalse(hasattr(result.typetoalter, 'b')) # Alter UDT and ensure the alter is honored in results self.session.execute("ALTER TYPE typetoalter add b int") typetoalter = namedtuple('typetoalter', ('a', 'b')) self.session.execute(insert_statement, [2, typetoalter(2, 2)]) results = self.session.execute("SELECT * from {0}".format(self.function_table_name)) for result in results: self.assertTrue(hasattr(result.typetoalter, 'a')) self.assertTrue(hasattr(result.typetoalter, 'b')) - diff --git a/tests/integration/upgrade/test_upgrade.py b/tests/integration/upgrade/test_upgrade.py index 7fa88a9..31df55c 100644 --- a/tests/integration/upgrade/test_upgrade.py +++ b/tests/integration/upgrade/test_upgrade.py @@ -1,279 +1,288 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from itertools import count from cassandra.auth import PlainTextAuthProvider, SaslAuthProvider from cassandra.cluster import ConsistencyLevel, Cluster, DriverException, ExecutionProfile from cassandra.policies import ConstantSpeculativeExecutionPolicy from tests.integration.upgrade import UpgradeBase, UpgradeBaseAuth, UpgradePath, upgrade_paths try: import unittest2 as unittest except ImportError: import unittest # noqa +# Previous Cassandra upgrade two_to_three_path = upgrade_paths([ UpgradePath("2.2.9-3.11", {"version": "2.2.9"}, {"version": "3.11.4"}, {}), ]) + +# Previous DSE upgrade +five_upgrade_path = upgrade_paths([ + UpgradePath("5.0.11-5.1.4", {"version": "5.0.11"}, {"version": "5.1.4"}, {}), +]) + + class UpgradeTests(UpgradeBase): @two_to_three_path def test_can_write(self): """ Verify that the driver will keep querying C* even if there is a host down while being upgraded and that all the writes will eventually succeed @since 3.12 @jira_ticket PYTHON-546 @expected_result all the writes succeed @test_category upgrade """ self.start_upgrade(0) + self.cluster_driver.add_execution_profile("all", ExecutionProfile(consistency_level=ConsistencyLevel.ALL)) + self.cluster_driver.add_execution_profile("one", ExecutionProfile(consistency_level=ConsistencyLevel.LOCAL_ONE)) + c = count() while not self.is_upgraded(): - self.session.execute("INSERT INTO test3rf.test(k, v) VALUES (%s, 0)", (next(c), )) + self.session.execute("INSERT INTO test3rf.test(k, v) VALUES (%s, 0)", (next(c), ), execution_profile="one") time.sleep(0.0001) - self.session.default_consistency_level = ConsistencyLevel.ALL - total_number_of_inserted = self.session.execute("SELECT COUNT(*) from test3rf.test")[0][0] + total_number_of_inserted = self.session.execute("SELECT COUNT(*) from test3rf.test", execution_profile="all")[0][0] self.assertEqual(total_number_of_inserted, next(c)) - self.session.default_consistency_level = ConsistencyLevel.LOCAL_ONE self.assertEqual(self.logger_handler.get_message_count("error", ""), 0) @two_to_three_path def test_can_connect(self): """ Verify that the driver can connect to all the nodes despite some nodes being in different versions @since 3.12 @jira_ticket PYTHON-546 @expected_result the driver connects successfully and can execute queries against all the hosts @test_category upgrade """ def connect_and_shutdown(): cluster = Cluster() session = cluster.connect(wait_for_all_pools=True) queried_hosts = set() for _ in range(10): results = session.execute("SELECT * from system.local") self.assertGreater(len(results.current_rows), 0) self.assertEqual(len(results.response_future.attempted_hosts), 1) queried_hosts.add(results.response_future.attempted_hosts[0]) self.assertEqual(len(queried_hosts), 3) cluster.shutdown() connect_and_shutdown() for node in self.nodes: self.upgrade_node(node) connect_and_shutdown() connect_and_shutdown() class UpgradeTestsMetadata(UpgradeBase): @two_to_three_path def test_can_write(self): """ Verify that the driver will keep querying C* even if there is a host down while being upgraded and that all the writes will eventually succeed @since 3.12 @jira_ticket PYTHON-546 @expected_result all the writes succeed @test_category upgrade """ self.start_upgrade(0) + self.cluster_driver.add_execution_profile("all", ExecutionProfile(consistency_level=ConsistencyLevel.ALL)) + self.cluster_driver.add_execution_profile("one", ExecutionProfile(consistency_level=ConsistencyLevel.LOCAL_ONE)) + c = count() while not self.is_upgraded(): - self.session.execute("INSERT INTO test3rf.test(k, v) VALUES (%s, 0)", (next(c),)) + self.session.execute("INSERT INTO test3rf.test(k, v) VALUES (%s, 0)", (next(c),), execution_profile="one") time.sleep(0.0001) - self.session.default_consistency_level = ConsistencyLevel.ALL - total_number_of_inserted = self.session.execute("SELECT COUNT(*) from test3rf.test")[0][0] + total_number_of_inserted = self.session.execute("SELECT COUNT(*) from test3rf.test", execution_profile="all")[0][0] self.assertEqual(total_number_of_inserted, next(c)) - self.session.default_consistency_level = ConsistencyLevel.LOCAL_ONE self.assertEqual(self.logger_handler.get_message_count("error", ""), 0) @two_to_three_path def test_schema_metadata_gets_refreshed(self): """ Verify that the driver fails to update the metadata while connected against different versions of nodes. This won't succeed because each node will report a different schema version @since 3.12 @jira_ticket PYTHON-546 @expected_result the driver raises DriverException when updating the schema metadata while upgrading all the hosts @test_category metadata """ original_meta = self.cluster_driver.metadata.keyspaces number_of_nodes = len(self.cluster.nodelist()) nodes = self.nodes for node in nodes[1:]: self.upgrade_node(node) # Wait for the control connection to reconnect time.sleep(20) with self.assertRaises(DriverException): self.cluster_driver.refresh_schema_metadata(max_schema_agreement_wait=10) self.upgrade_node(nodes[0]) # Wait for the control connection to reconnect time.sleep(20) self.cluster_driver.refresh_schema_metadata(max_schema_agreement_wait=40) self.assertNotEqual(original_meta, self.cluster_driver.metadata.keyspaces) @two_to_three_path def test_schema_nodes_gets_refreshed(self): """ Verify that the driver token map and node list gets rebuild correctly while upgrading. The token map and the node list should be the same after each node upgrade @since 3.12 @jira_ticket PYTHON-546 @expected_result the token map and the node list stays consistent with each node upgrade metadata while upgrading all the hosts @test_category metadata """ for node in self.nodes: token_map = self.cluster_driver.metadata.token_map self.upgrade_node(node) # Wait for the control connection to reconnect time.sleep(20) self.cluster_driver.refresh_nodes(force_token_rebuild=True) self._assert_same_token_map(token_map, self.cluster_driver.metadata.token_map) def _assert_same_token_map(self, original, new): self.assertIsNot(original, new) self.assertEqual(original.tokens_to_hosts_by_ks, new.tokens_to_hosts_by_ks) self.assertEqual(original.token_to_host_owner, new.token_to_host_owner) self.assertEqual(original.ring, new.ring) two_to_three_with_auth_path = upgrade_paths([ UpgradePath("2.2.9-3.11-auth", {"version": "2.2.9"}, {"version": "3.11.4"}, {'authenticator': 'PasswordAuthenticator', 'authorizer': 'CassandraAuthorizer'}), ]) class UpgradeTestsAuthentication(UpgradeBaseAuth): @two_to_three_with_auth_path def test_can_connect_auth_plain(self): """ Verify that the driver can connect despite some nodes being in different versions with plain authentication @since 3.12 @jira_ticket PYTHON-546 @expected_result the driver connects successfully and can execute queries against all the hosts @test_category upgrade """ auth_provider = PlainTextAuthProvider( username="cassandra", password="cassandra" ) self.connect_and_shutdown(auth_provider) for node in self.nodes: self.upgrade_node(node) self.connect_and_shutdown(auth_provider) self.connect_and_shutdown(auth_provider) @two_to_three_with_auth_path def test_can_connect_auth_sasl(self): """ Verify that the driver can connect despite some nodes being in different versions with ssl authentication @since 3.12 @jira_ticket PYTHON-546 @expected_result the driver connects successfully and can execute queries against all the hosts @test_category upgrade """ sasl_kwargs = {'service': 'cassandra', 'mechanism': 'PLAIN', 'qops': ['auth'], 'username': 'cassandra', 'password': 'cassandra'} auth_provider = SaslAuthProvider(**sasl_kwargs) self.connect_and_shutdown(auth_provider) for node in self.nodes: self.upgrade_node(node) self.connect_and_shutdown(auth_provider) self.connect_and_shutdown(auth_provider) def connect_and_shutdown(self, auth_provider): cluster = Cluster(idle_heartbeat_interval=0, auth_provider=auth_provider) session = cluster.connect(wait_for_all_pools=True) queried_hosts = set() for _ in range(10): results = session.execute("SELECT * from system.local") self.assertGreater(len(results.current_rows), 0) self.assertEqual(len(results.response_future.attempted_hosts), 1) queried_hosts.add(results.response_future.attempted_hosts[0]) self.assertEqual(len(queried_hosts), 3) cluster.shutdown() class UpgradeTestsPolicies(UpgradeBase): @two_to_three_path def test_can_write_speculative(self): """ Verify that the driver will keep querying C* even if there is a host down while being upgraded and that all the writes will eventually succeed using the ConstantSpeculativeExecutionPolicy policy @since 3.12 @jira_ticket PYTHON-546 @expected_result all the writes succeed @test_category upgrade """ spec_ep_rr = ExecutionProfile(speculative_execution_policy=ConstantSpeculativeExecutionPolicy(.5, 10), request_timeout=12) cluster = Cluster() self.addCleanup(cluster.shutdown) cluster.add_execution_profile("spec_ep_rr", spec_ep_rr) - + cluster.add_execution_profile("all", ExecutionProfile(consistency_level=ConsistencyLevel.ALL)) session = cluster.connect() self.start_upgrade(0) c = count() while not self.is_upgraded(): session.execute("INSERT INTO test3rf.test(k, v) VALUES (%s, 0)", (next(c),), execution_profile='spec_ep_rr') time.sleep(0.0001) - session.default_consistency_level = ConsistencyLevel.ALL - total_number_of_inserted = session.execute("SELECT COUNT(*) from test3rf.test")[0][0] + total_number_of_inserted = session.execute("SELECT COUNT(*) from test3rf.test", execution_profile="all")[0][0] self.assertEqual(total_number_of_inserted, next(c)) self.assertEqual(self.logger_handler.get_message_count("error", ""), 0) diff --git a/tests/integration/util.py b/tests/integration/util.py index a2ce9d5..6215449 100644 --- a/tests/integration/util.py +++ b/tests/integration/util.py @@ -1,109 +1,51 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tests.integration import PROTOCOL_VERSION -from functools import wraps import time def assert_quiescent_pool_state(test_case, cluster, wait=None): """ Checking the quiescent pool state checks that none of the requests ids have been lost. However, the callback corresponding to a request_id is called before the request_id is returned back to the pool, therefore session.execute("SELECT * from system.local") assert_quiescent_pool_state(self, session.cluster) (with no wait) might fail because when execute comes back the request_id hasn't yet been returned to the pool, therefore the wait. """ if wait is not None: time.sleep(wait) for session in cluster.sessions: pool_states = session.get_pool_state().values() test_case.assertTrue(pool_states) for state in pool_states: test_case.assertFalse(state['shutdown']) test_case.assertGreater(state['open_count'], 0) test_case.assertTrue(all((i == 0 for i in state['in_flights']))) for holder in cluster.get_connection_holders(): for connection in holder.get_connections(): # all ids are unique req_ids = connection.request_ids test_case.assertEqual(len(req_ids), len(set(req_ids))) test_case.assertEqual(connection.highest_request_id, len(req_ids) - 1) test_case.assertEqual(connection.highest_request_id, max(req_ids)) if PROTOCOL_VERSION < 3: test_case.assertEqual(connection.highest_request_id, connection.max_request_id) - - -def wait_until(condition, delay, max_attempts): - """ - Executes a function at regular intervals while the condition - is false and the amount of attempts < maxAttempts. - :param condition: a function - :param delay: the delay in second - :param max_attempts: the maximum number of attempts. So the timeout - of this function is delay*max_attempts - """ - attempt = 0 - while not condition() and attempt < max_attempts: - attempt += 1 - time.sleep(delay) - - if attempt >= max_attempts: - raise Exception("Condition is still False after {} attempts.".format(max_attempts)) - - -def wait_until_not_raised(condition, delay, max_attempts): - """ - Executes a function at regular intervals while the condition - doesn't raise an exception and the amount of attempts < maxAttempts. - :param condition: a function - :param delay: the delay in second - :param max_attempts: the maximum number of attemps. So the timeout - of this function will be delay*max_attempts - """ - def wrapped_condition(): - try: - condition() - except: - return False - - return True - - attempt = 0 - while attempt < (max_attempts-1): - attempt += 1 - if wrapped_condition(): - return - - time.sleep(delay) - - # last attempt, let the exception raise - condition() - - -def late(seconds=1): - def decorator(func): - @wraps(func) - def wrapper(*args, **kwargs): - time.sleep(seconds) - func(*args, **kwargs) - return wrapper - return decorator diff --git a/tests/integration/advanced/__init__.py b/tests/unit/advanced/__init__.py similarity index 67% copy from tests/integration/advanced/__init__.py copy to tests/unit/advanced/__init__.py index 662f5b8..2c9ca17 100644 --- a/tests/integration/advanced/__init__.py +++ b/tests/unit/advanced/__init__.py @@ -1,23 +1,13 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License - -try: - import unittest2 as unittest -except ImportError: - import unittest # noqa - -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) +# limitations under the License. diff --git a/tests/unit/advanced/cloud/test_cloud.py b/tests/unit/advanced/cloud/test_cloud.py index e6001fb..ab18f0a 100644 --- a/tests/unit/advanced/cloud/test_cloud.py +++ b/tests/unit/advanced/cloud/test_cloud.py @@ -1,77 +1,113 @@ # Copyright DataStax, Inc. # # Licensed under the DataStax DSE Driver License; # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # http://www.datastax.com/terms/datastax-dse-driver-license-terms +import tempfile +import os +import shutil +import six + try: import unittest2 as unittest except ImportError: import unittest # noqa -import os - +from cassandra import DriverException from cassandra.datastax import cloud from mock import patch +from tests import notwindows class CloudTests(unittest.TestCase): current_path = os.path.dirname(os.path.abspath(__file__)) + creds_path = os.path.join(current_path, './creds.zip') config_zip = { - 'secure_connect_bundle': os.path.join(current_path, './creds.zip') + 'secure_connect_bundle': creds_path } metadata_json = """ {"region":"local", "contact_info": { "type":"sni_proxy", "local_dc":"dc1", "contact_points":[ "b13ae7b4-e711-4660-8dd1-bec57d37aa64", "d4330144-5fb3-425a-86a1-431b3e4d0671", "86537b87-91a9-4c59-b715-716486e72c42" ], "sni_proxy_address":"localhost:30002" } }""" @staticmethod def _read_metadata_info_side_effect(config, _): return config def _check_config(self, config): self.assertEqual(config.username, 'cassandra') self.assertEqual(config.password, 'cassandra') self.assertEqual(config.host, 'localhost') self.assertEqual(config.port, 30443) self.assertEqual(config.keyspace, 'system') self.assertEqual(config.local_dc, None) self.assertIsNotNone(config.ssl_context) self.assertIsNone(config.sni_host) self.assertIsNone(config.sni_port) self.assertIsNone(config.host_ids) def test_read_cloud_config_from_zip(self): with patch('cassandra.datastax.cloud.read_metadata_info', side_effect=self._read_metadata_info_side_effect): config = cloud.get_cloud_config(self.config_zip) self._check_config(config) def test_parse_metadata_info(self): config = cloud.CloudConfig() cloud.parse_metadata_info(config, self.metadata_json) self.assertEqual(config.sni_host, 'localhost') self.assertEqual(config.sni_port, 30002) self.assertEqual(config.local_dc, 'dc1') host_ids = [ "b13ae7b4-e711-4660-8dd1-bec57d37aa64", "d4330144-5fb3-425a-86a1-431b3e4d0671", "86537b87-91a9-4c59-b715-716486e72c42" ] for host_id in host_ids: self.assertIn(host_id, config.host_ids) + + @notwindows + def test_use_default_tempdir(self): + tmpdir = tempfile.mkdtemp() + + def clean_tmp_dir(): + os.chmod(tmpdir, 0o777) + shutil.rmtree(tmpdir) + self.addCleanup(clean_tmp_dir) + + tmp_creds_path = os.path.join(tmpdir, 'creds.zip') + shutil.copyfile(self.creds_path, tmp_creds_path) + os.chmod(tmpdir, 0o544) + config = { + 'secure_connect_bundle': tmp_creds_path + } + + # The directory is not writtable.. we expect a permission error + exc = PermissionError if six.PY3 else OSError + with self.assertRaises(exc): + cloud.get_cloud_config(config) + + # With use_default_tempdir, we expect an connection refused + # since the cluster doesn't exist + with self.assertRaises(DriverException): + config = { + 'secure_connect_bundle': tmp_creds_path, + 'use_default_tempdir': True + } + cloud.get_cloud_config(config) diff --git a/tests/unit/advanced/test_auth.py b/tests/unit/advanced/test_auth.py new file mode 100644 index 0000000..bb411af --- /dev/null +++ b/tests/unit/advanced/test_auth.py @@ -0,0 +1,45 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from puresasl import QOP + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +from cassandra.auth import DSEGSSAPIAuthProvider + +# Cannot import requiredse from tests.integration +# This auth provider requires kerberos and puresals +DSE_VERSION = os.getenv('DSE_VERSION', None) +@unittest.skipUnless(DSE_VERSION, "DSE required") +class TestGSSAPI(unittest.TestCase): + + def test_host_resolution(self): + # resolves by default + provider = DSEGSSAPIAuthProvider(service='test', qops=QOP.all) + authenticator = provider.new_authenticator('127.0.0.1') + self.assertEqual(authenticator.sasl.host, 'localhost') + + # numeric fallback okay + authenticator = provider.new_authenticator('192.0.2.1') + self.assertEqual(authenticator.sasl.host, '192.0.2.1') + + # disable explicitly + provider = DSEGSSAPIAuthProvider(service='test', qops=QOP.all, resolve_host_name=False) + authenticator = provider.new_authenticator('127.0.0.1') + self.assertEqual(authenticator.sasl.host, '127.0.0.1') + diff --git a/tests/unit/advanced/test_execution_profile.py b/tests/unit/advanced/test_execution_profile.py new file mode 100644 index 0000000..8592f56 --- /dev/null +++ b/tests/unit/advanced/test_execution_profile.py @@ -0,0 +1,34 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +from cassandra.cluster import GraphExecutionProfile, GraphAnalyticsExecutionProfile +from cassandra.graph import GraphOptions + + +class GraphExecutionProfileTest(unittest.TestCase): + + def test_graph_source_can_be_set_with_graph_execution_profile(self): + options = GraphOptions(graph_source='a') + ep = GraphExecutionProfile(graph_options=options) + self.assertEqual(ep.graph_options.graph_source, b'a') + + def test_graph_source_is_preserve_with_graph_analytics_execution_profile(self): + options = GraphOptions(graph_source='doesnt_matter') + ep = GraphAnalyticsExecutionProfile(graph_options=options) + self.assertEqual(ep.graph_options.graph_source, b'a') # graph source is set automatically diff --git a/tests/unit/advanced/test_geometry.py b/tests/unit/advanced/test_geometry.py new file mode 100644 index 0000000..4fa2644 --- /dev/null +++ b/tests/unit/advanced/test_geometry.py @@ -0,0 +1,281 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +import struct +import math +from cassandra.cqltypes import lookup_casstype +from cassandra.protocol import ProtocolVersion +from cassandra.cqltypes import PointType, LineStringType, PolygonType, WKBGeometryType +from cassandra.util import Point, LineString, Polygon, _LinearRing, Distance, _HAS_GEOMET + +wkb_be = 0 +wkb_le = 1 + +protocol_versions = ProtocolVersion.SUPPORTED_VERSIONS + + +class GeoTypes(unittest.TestCase): + + samples = (Point(1, 2), LineString(((1, 2), (3, 4), (5, 6))), Polygon([(10.1, 10.0), (110.0, 10.0), (110., 110.0), (10., 110.0), (10., 10.0)], [[(20., 20.0), (20., 30.0), (30., 30.0), (30., 20.0), (20., 20.0)], [(40., 20.0), (40., 30.0), (50., 30.0), (50., 20.0), (40., 20.0)]])) + + def test_marshal_platform(self): + for proto_ver in protocol_versions: + for geo in self.samples: + cql_type = lookup_casstype(geo.__class__.__name__ + 'Type') + self.assertEqual(cql_type.from_binary(cql_type.to_binary(geo, proto_ver), proto_ver), geo) + + def _verify_both_endian(self, typ, body_fmt, params, expected): + for proto_ver in protocol_versions: + self.assertEqual(typ.from_binary(struct.pack(">BI" + body_fmt, wkb_be, *params), proto_ver), expected) + self.assertEqual(typ.from_binary(struct.pack(" base map + base = GraphOptions(**self.api_params) + self.assertEqual(GraphOptions().get_options_map(base), base._graph_options) + + # something set overrides + kwargs = self.api_params.copy() # this test concept got strange after we added default values for a couple GraphOption attrs + kwargs['graph_name'] = 'unit_test' + other = GraphOptions(**kwargs) + options = base.get_options_map(other) + updated = self.opt_mapping['graph_name'] + self.assertEqual(options[updated], six.b('unit_test')) + for name in (n for n in self.opt_mapping.values() if n != updated): + self.assertEqual(options[name], base._graph_options[name]) + + # base unchanged + self._verify_api_params(base, self.api_params) + + def test_set_attr(self): + expected = 'test@@@@' + opts = GraphOptions(graph_name=expected) + self.assertEqual(opts.graph_name, six.b(expected)) + expected = 'somethingelse####' + opts.graph_name = expected + self.assertEqual(opts.graph_name, six.b(expected)) + + # will update options with set value + another = GraphOptions() + self.assertIsNone(another.graph_name) + another.update(opts) + self.assertEqual(another.graph_name, six.b(expected)) + + opts.graph_name = None + self.assertIsNone(opts.graph_name) + # will not update another with its set-->unset value + another.update(opts) + self.assertEqual(another.graph_name, six.b(expected)) # remains unset + opt_map = another.get_options_map(opts) + self.assertEqual(opt_map, another._graph_options) + + def test_del_attr(self): + opts = GraphOptions(**self.api_params) + test_params = self.api_params.copy() + del test_params['graph_source'] + del opts.graph_source + self._verify_api_params(opts, test_params) + + def _verify_api_params(self, opts, api_params): + self.assertEqual(len(opts._graph_options), len(api_params)) + for name, value in api_params.items(): + try: + value = six.b(value) + except: + pass # already bytes + self.assertEqual(getattr(opts, name), value) + self.assertEqual(opts._graph_options[self.opt_mapping[name]], value) + + def test_consistency_levels(self): + read_cl = ConsistencyLevel.ONE + write_cl = ConsistencyLevel.LOCAL_QUORUM + + # set directly + opts = GraphOptions(graph_read_consistency_level=read_cl, graph_write_consistency_level=write_cl) + self.assertEqual(opts.graph_read_consistency_level, read_cl) + self.assertEqual(opts.graph_write_consistency_level, write_cl) + + # mapping from base + opt_map = opts.get_options_map() + self.assertEqual(opt_map['graph-read-consistency'], six.b(ConsistencyLevel.value_to_name[read_cl])) + self.assertEqual(opt_map['graph-write-consistency'], six.b(ConsistencyLevel.value_to_name[write_cl])) + + # empty by default + new_opts = GraphOptions() + opt_map = new_opts.get_options_map() + self.assertNotIn('graph-read-consistency', opt_map) + self.assertNotIn('graph-write-consistency', opt_map) + + # set from other + opt_map = new_opts.get_options_map(opts) + self.assertEqual(opt_map['graph-read-consistency'], six.b(ConsistencyLevel.value_to_name[read_cl])) + self.assertEqual(opt_map['graph-write-consistency'], six.b(ConsistencyLevel.value_to_name[write_cl])) + + def test_graph_source_convenience_attributes(self): + opts = GraphOptions() + self.assertEqual(opts.graph_source, b'g') + self.assertFalse(opts.is_analytics_source) + self.assertTrue(opts.is_graph_source) + self.assertFalse(opts.is_default_source) + + opts.set_source_default() + self.assertIsNotNone(opts.graph_source) + self.assertFalse(opts.is_analytics_source) + self.assertFalse(opts.is_graph_source) + self.assertTrue(opts.is_default_source) + + opts.set_source_analytics() + self.assertIsNotNone(opts.graph_source) + self.assertTrue(opts.is_analytics_source) + self.assertFalse(opts.is_graph_source) + self.assertFalse(opts.is_default_source) + + opts.set_source_graph() + self.assertIsNotNone(opts.graph_source) + self.assertFalse(opts.is_analytics_source) + self.assertTrue(opts.is_graph_source) + self.assertFalse(opts.is_default_source) + +class GraphStatementTests(unittest.TestCase): + + def test_init(self): + # just make sure Statement attributes are accepted + kwargs = {'query_string': object(), + 'retry_policy': RetryPolicy(), + 'consistency_level': object(), + 'fetch_size': object(), + 'keyspace': object(), + 'custom_payload': object()} + statement = SimpleGraphStatement(**kwargs) + for k, v in kwargs.items(): + self.assertIs(getattr(statement, k), v) + + # but not a bogus parameter + kwargs['bogus'] = object() + self.assertRaises(TypeError, SimpleGraphStatement, **kwargs) + + +class GraphRowFactoryTests(unittest.TestCase): + + def test_object_row_factory(self): + col_names = [] # unused + rows = [object() for _ in range(10)] + self.assertEqual(single_object_row_factory(col_names, ((o,) for o in rows)), rows) + + def test_graph_result_row_factory(self): + col_names = [] # unused + rows = [json.dumps({'result': i}) for i in range(10)] + results = graph_result_row_factory(col_names, ((o,) for o in rows)) + for i, res in enumerate(results): + self.assertIsInstance(res, Result) + self.assertEqual(res.value, i) diff --git a/tests/unit/advanced/test_insights.py b/tests/unit/advanced/test_insights.py new file mode 100644 index 0000000..2cc170e --- /dev/null +++ b/tests/unit/advanced/test_insights.py @@ -0,0 +1,308 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +import logging +from mock import sentinel +import sys + +from cassandra import ConsistencyLevel +from cassandra.cluster import ( + ExecutionProfile, GraphExecutionProfile, ProfileManager, + GraphAnalyticsExecutionProfile, + EXEC_PROFILE_DEFAULT, EXEC_PROFILE_GRAPH_DEFAULT, + EXEC_PROFILE_GRAPH_ANALYTICS_DEFAULT, + EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT +) +from cassandra.datastax.graph.query import GraphOptions +from cassandra.datastax.insights.registry import insights_registry +from cassandra.datastax.insights.serializers import initialize_registry +from cassandra.datastax.insights.util import namespace +from cassandra.policies import ( + RoundRobinPolicy, + LoadBalancingPolicy, + DCAwareRoundRobinPolicy, + TokenAwarePolicy, + WhiteListRoundRobinPolicy, + HostFilterPolicy, + ConstantReconnectionPolicy, + ExponentialReconnectionPolicy, + RetryPolicy, + SpeculativeExecutionPolicy, + ConstantSpeculativeExecutionPolicy, + WrapperPolicy +) + + +log = logging.getLogger(__name__) + +initialize_registry(insights_registry) + + +class TestGetConfig(unittest.TestCase): + + def test_invalid_object(self): + class NoConfAsDict(object): + pass + + obj = NoConfAsDict() + + ns = 'tests.unit.advanced.test_insights' + if sys.version_info > (3,): + ns += '.TestGetConfig.test_invalid_object.' + + # no default + # ... as a policy + self.assertEqual(insights_registry.serialize(obj, policy=True), + {'type': 'NoConfAsDict', + 'namespace': ns, + 'options': {}}) + # ... not as a policy (default) + self.assertEqual(insights_registry.serialize(obj), + {'type': 'NoConfAsDict', + 'namespace': ns, + }) + # with default + self.assertIs(insights_registry.serialize(obj, default=sentinel.attr_err_default), + sentinel.attr_err_default) + + def test_successful_return(self): + + class SuperclassSentinel(object): + pass + + class SubclassSentinel(SuperclassSentinel): + pass + + @insights_registry.register_serializer_for(SuperclassSentinel) + def superclass_sentinel_serializer(obj): + return sentinel.serialized_superclass + + self.assertIs(insights_registry.serialize(SuperclassSentinel()), + sentinel.serialized_superclass) + self.assertIs(insights_registry.serialize(SubclassSentinel()), + sentinel.serialized_superclass) + + # with default -- same behavior + self.assertIs(insights_registry.serialize(SubclassSentinel(), default=object()), + sentinel.serialized_superclass) + +class TestConfigAsDict(unittest.TestCase): + + # graph/query.py + def test_graph_options(self): + self.maxDiff = None + + go = GraphOptions(graph_name='name_for_test', + graph_source='source_for_test', + graph_language='lang_for_test', + graph_protocol='protocol_for_test', + graph_read_consistency_level=ConsistencyLevel.ANY, + graph_write_consistency_level=ConsistencyLevel.ONE, + graph_invalid_option='invalid') + + log.debug(go._graph_options) + + self.assertEqual( + insights_registry.serialize(go), + {'source': 'source_for_test', + 'language': 'lang_for_test', + 'graphProtocol': 'protocol_for_test', + # no graph_invalid_option + } + ) + + # cluster.py + def test_execution_profile(self): + self.maxDiff = None + self.assertEqual( + insights_registry.serialize(ExecutionProfile()), + {'consistency': 'LOCAL_ONE', + 'continuousPagingOptions': None, + 'loadBalancing': {'namespace': 'cassandra.policies', + 'options': {'child_policy': {'namespace': 'cassandra.policies', + 'options': {'local_dc': '', + 'used_hosts_per_remote_dc': 0}, + 'type': 'DCAwareRoundRobinPolicy'}, + 'shuffle_replicas': False}, + 'type': 'TokenAwarePolicy'}, + 'readTimeout': 10.0, + 'retry': {'namespace': 'cassandra.policies', 'options': {}, 'type': 'RetryPolicy'}, + 'serialConsistency': None, + 'speculativeExecution': {'namespace': 'cassandra.policies', + 'options': {}, 'type': 'NoSpeculativeExecutionPolicy'}, + 'graphOptions': None + } + ) + + def test_graph_execution_profile(self): + self.maxDiff = None + self.assertEqual( + insights_registry.serialize(GraphExecutionProfile()), + {'consistency': 'LOCAL_ONE', + 'continuousPagingOptions': None, + 'loadBalancing': {'namespace': 'cassandra.policies', + 'options': {'child_policy': {'namespace': 'cassandra.policies', + 'options': {'local_dc': '', + 'used_hosts_per_remote_dc': 0}, + 'type': 'DCAwareRoundRobinPolicy'}, + 'shuffle_replicas': False}, + 'type': 'TokenAwarePolicy'}, + 'readTimeout': 30.0, + 'retry': {'namespace': 'cassandra.policies', 'options': {}, 'type': 'NeverRetryPolicy'}, + 'serialConsistency': None, + 'speculativeExecution': {'namespace': 'cassandra.policies', + 'options': {}, 'type': 'NoSpeculativeExecutionPolicy'}, + 'graphOptions': {'graphProtocol': None, + 'language': 'gremlin-groovy', + 'source': 'g'}, + } + ) + + def test_graph_analytics_execution_profile(self): + self.maxDiff = None + self.assertEqual( + insights_registry.serialize(GraphAnalyticsExecutionProfile()), + {'consistency': 'LOCAL_ONE', + 'continuousPagingOptions': None, + 'loadBalancing': {'namespace': 'cassandra.policies', + 'options': {'child_policy': {'namespace': 'cassandra.policies', + 'options': {'child_policy': {'namespace': 'cassandra.policies', + 'options': {'local_dc': '', + 'used_hosts_per_remote_dc': 0}, + 'type': 'DCAwareRoundRobinPolicy'}, + 'shuffle_replicas': False}, + 'type': 'TokenAwarePolicy'}}, + 'type': 'DefaultLoadBalancingPolicy'}, + 'readTimeout': 604800.0, + 'retry': {'namespace': 'cassandra.policies', 'options': {}, 'type': 'NeverRetryPolicy'}, + 'serialConsistency': None, + 'speculativeExecution': {'namespace': 'cassandra.policies', + 'options': {}, 'type': 'NoSpeculativeExecutionPolicy'}, + 'graphOptions': {'graphProtocol': None, + 'language': 'gremlin-groovy', + 'source': 'a'}, + } + ) + + # policies.py + def test_DC_aware_round_robin_policy(self): + self.assertEqual( + insights_registry.serialize(DCAwareRoundRobinPolicy()), + {'namespace': 'cassandra.policies', + 'options': {'local_dc': '', 'used_hosts_per_remote_dc': 0}, + 'type': 'DCAwareRoundRobinPolicy'} + ) + self.assertEqual( + insights_registry.serialize(DCAwareRoundRobinPolicy(local_dc='fake_local_dc', + used_hosts_per_remote_dc=15)), + {'namespace': 'cassandra.policies', + 'options': {'local_dc': 'fake_local_dc', 'used_hosts_per_remote_dc': 15}, + 'type': 'DCAwareRoundRobinPolicy'} + ) + + def test_token_aware_policy(self): + self.assertEqual( + insights_registry.serialize(TokenAwarePolicy(child_policy=LoadBalancingPolicy())), + {'namespace': 'cassandra.policies', + 'options': {'child_policy': {'namespace': 'cassandra.policies', + 'options': {}, + 'type': 'LoadBalancingPolicy'}, + 'shuffle_replicas': False}, + 'type': 'TokenAwarePolicy'} + ) + + def test_whitelist_round_robin_policy(self): + self.assertEqual( + insights_registry.serialize(WhiteListRoundRobinPolicy(['127.0.0.3'])), + {'namespace': 'cassandra.policies', + 'options': {'allowed_hosts': ('127.0.0.3',)}, + 'type': 'WhiteListRoundRobinPolicy'} + ) + + def test_host_filter_policy(self): + def my_predicate(s): + return False + + self.assertEqual( + insights_registry.serialize(HostFilterPolicy(LoadBalancingPolicy(), my_predicate)), + {'namespace': 'cassandra.policies', + 'options': {'child_policy': {'namespace': 'cassandra.policies', + 'options': {}, + 'type': 'LoadBalancingPolicy'}, + 'predicate': 'my_predicate'}, + 'type': 'HostFilterPolicy'} + ) + + def test_constant_reconnection_policy(self): + self.assertEqual( + insights_registry.serialize(ConstantReconnectionPolicy(3, 200)), + {'type': 'ConstantReconnectionPolicy', + 'namespace': 'cassandra.policies', + 'options': {'delay': 3, 'max_attempts': 200} + } + ) + + def test_exponential_reconnection_policy(self): + self.assertEqual( + insights_registry.serialize(ExponentialReconnectionPolicy(4, 100, 10)), + {'type': 'ExponentialReconnectionPolicy', + 'namespace': 'cassandra.policies', + 'options': {'base_delay': 4, 'max_delay': 100, 'max_attempts': 10} + } + ) + + def test_retry_policy(self): + self.assertEqual( + insights_registry.serialize(RetryPolicy()), + {'type': 'RetryPolicy', + 'namespace': 'cassandra.policies', + 'options': {} + } + ) + + def test_spec_exec_policy(self): + self.assertEqual( + insights_registry.serialize(SpeculativeExecutionPolicy()), + {'type': 'SpeculativeExecutionPolicy', + 'namespace': 'cassandra.policies', + 'options': {} + } + ) + + def test_constant_spec_exec_policy(self): + self.assertEqual( + insights_registry.serialize(ConstantSpeculativeExecutionPolicy(100, 101)), + {'type': 'ConstantSpeculativeExecutionPolicy', + 'namespace': 'cassandra.policies', + 'options': {'delay': 100, + 'max_attempts': 101} + } + ) + + def test_wrapper_policy(self): + self.assertEqual( + insights_registry.serialize(WrapperPolicy(LoadBalancingPolicy())), + {'namespace': 'cassandra.policies', + 'options': {'child_policy': {'namespace': 'cassandra.policies', + 'options': {}, + 'type': 'LoadBalancingPolicy'} + }, + 'type': 'WrapperPolicy'} + ) diff --git a/tests/unit/advanced/test_metadata.py b/tests/unit/advanced/test_metadata.py new file mode 100644 index 0000000..addd514 --- /dev/null +++ b/tests/unit/advanced/test_metadata.py @@ -0,0 +1,141 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +from cassandra.metadata import ( + KeyspaceMetadata, TableMetadataDSE68, + VertexMetadata, EdgeMetadata +) + + +class GraphMetadataToCQLTests(unittest.TestCase): + + def _create_edge_metadata(self, partition_keys=['pk1'], clustering_keys=['c1']): + return EdgeMetadata( + 'keyspace', 'table', 'label', 'from_table', 'from_label', + partition_keys, clustering_keys, 'to_table', 'to_label', + partition_keys, clustering_keys) + + def _create_vertex_metadata(self, label_name='label'): + return VertexMetadata('keyspace', 'table', label_name) + + def _create_keyspace_metadata(self, graph_engine): + return KeyspaceMetadata( + 'keyspace', True, 'org.apache.cassandra.locator.SimpleStrategy', + {'replication_factor': 1}, graph_engine=graph_engine) + + def _create_table_metadata(self, with_vertex=False, with_edge=False): + tm = TableMetadataDSE68('keyspace', 'table') + if with_vertex: + tm.vertex = self._create_vertex_metadata() if with_vertex is True else with_vertex + elif with_edge: + tm.edge = self._create_edge_metadata() if with_edge is True else with_edge + + return tm + + def test_keyspace_no_graph_engine(self): + km = self._create_keyspace_metadata(None) + self.assertEqual(km.graph_engine, None) + self.assertNotIn( + "graph_engine", + km.as_cql_query() + ) + + def test_keyspace_with_graph_engine(self): + graph_engine = 'Core' + km = self._create_keyspace_metadata(graph_engine) + self.assertEqual(km.graph_engine, graph_engine) + cql = km.as_cql_query() + self.assertIn( + "graph_engine", + cql + ) + self.assertIn( + "Core", + cql + ) + + def test_table_no_vertex_or_edge(self): + tm = self._create_table_metadata() + self.assertIsNone(tm.vertex) + self.assertIsNone(tm.edge) + cql = tm.as_cql_query() + self.assertNotIn("VERTEX LABEL", cql) + self.assertNotIn("EDGE LABEL", cql) + + def test_table_with_vertex(self): + tm = self._create_table_metadata(with_vertex=True) + self.assertIsInstance(tm.vertex, VertexMetadata) + self.assertIsNone(tm.edge) + cql = tm.as_cql_query() + self.assertIn("VERTEX LABEL", cql) + self.assertNotIn("EDGE LABEL", cql) + + def test_table_with_edge(self): + tm = self._create_table_metadata(with_edge=True) + self.assertIsNone(tm.vertex) + self.assertIsInstance(tm.edge, EdgeMetadata) + cql = tm.as_cql_query() + self.assertNotIn("VERTEX LABEL", cql) + self.assertIn("EDGE LABEL", cql) + self.assertIn("FROM from_label", cql) + self.assertIn("TO to_label", cql) + + def test_vertex_with_label(self): + tm = self. _create_table_metadata(with_vertex=True) + self.assertTrue(tm.as_cql_query().endswith('VERTEX LABEL label')) + + def test_edge_single_partition_key_and_clustering_key(self): + tm = self._create_table_metadata(with_edge=True) + self.assertIn( + 'FROM from_label(pk1, c1)', + tm.as_cql_query() + ) + + def test_edge_multiple_partition_keys(self): + edge = self._create_edge_metadata(partition_keys=['pk1', 'pk2']) + tm = self. _create_table_metadata(with_edge=edge) + self.assertIn( + 'FROM from_label((pk1, pk2), ', + tm.as_cql_query() + ) + + def test_edge_no_clustering_keys(self): + edge = self._create_edge_metadata(clustering_keys=[]) + tm = self. _create_table_metadata(with_edge=edge) + self.assertIn( + 'FROM from_label(pk1) ', + tm.as_cql_query() + ) + + def test_edge_multiple_clustering_keys(self): + edge = self._create_edge_metadata(clustering_keys=['c1', 'c2']) + tm = self. _create_table_metadata(with_edge=edge) + self.assertIn( + 'FROM from_label(pk1, c1, c2) ', + tm.as_cql_query() + ) + + def test_edge_multiple_partition_and_clustering_keys(self): + edge = self._create_edge_metadata(partition_keys=['pk1', 'pk2'], + clustering_keys=['c1', 'c2']) + tm = self. _create_table_metadata(with_edge=edge) + self.assertIn( + 'FROM from_label((pk1, pk2), c1, c2) ', + tm.as_cql_query() + ) diff --git a/tests/unit/advanced/test_policies.py b/tests/unit/advanced/test_policies.py new file mode 100644 index 0000000..79e7410 --- /dev/null +++ b/tests/unit/advanced/test_policies.py @@ -0,0 +1,103 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +from mock import Mock + +from cassandra.pool import Host +from cassandra.policies import RoundRobinPolicy + +from cassandra.policies import DSELoadBalancingPolicy + + +class ClusterMetaMock(object): + def __init__(self, hosts=None): + self.hosts = hosts or {} + + def get_host(self, addr): + return self.hosts.get(addr) + + +class DSELoadBalancingPolicyTest(unittest.TestCase): + + def test_no_target(self): + node_count = 4 + hosts = list(range(node_count)) + policy = DSELoadBalancingPolicy(RoundRobinPolicy()) + policy.populate(Mock(metadata=ClusterMetaMock()), hosts) + for _ in range(node_count): + query_plan = list(policy.make_query_plan(None, Mock(target_host=None))) + self.assertEqual(sorted(query_plan), hosts) + + def test_status_updates(self): + node_count = 4 + hosts = list(range(node_count)) + policy = DSELoadBalancingPolicy(RoundRobinPolicy()) + policy.populate(Mock(metadata=ClusterMetaMock()), hosts) + policy.on_down(0) + policy.on_remove(1) + policy.on_up(4) + policy.on_add(5) + query_plan = list(policy.make_query_plan()) + self.assertEqual(sorted(query_plan), [2, 3, 4, 5]) + + def test_no_live_nodes(self): + hosts = [0, 1, 2, 3] + policy = RoundRobinPolicy() + policy.populate(None, hosts) + + for i in range(4): + policy.on_down(i) + + query_plan = list(policy.make_query_plan()) + self.assertEqual(query_plan, []) + + def test_target_no_host(self): + node_count = 4 + hosts = list(range(node_count)) + policy = DSELoadBalancingPolicy(RoundRobinPolicy()) + policy.populate(Mock(metadata=ClusterMetaMock()), hosts) + query_plan = list(policy.make_query_plan(None, Mock(target_host='127.0.0.1'))) + self.assertEqual(sorted(query_plan), hosts) + + def test_target_host_down(self): + node_count = 4 + hosts = [Host(i, Mock()) for i in range(node_count)] + target_host = hosts[1] + + policy = DSELoadBalancingPolicy(RoundRobinPolicy()) + policy.populate(Mock(metadata=ClusterMetaMock({'127.0.0.1': target_host})), hosts) + query_plan = list(policy.make_query_plan(None, Mock(target_host='127.0.0.1'))) + self.assertEqual(sorted(query_plan), hosts) + + target_host.is_up = False + policy.on_down(target_host) + query_plan = list(policy.make_query_plan(None, Mock(target_host='127.0.0.1'))) + self.assertNotIn(target_host, query_plan) + + def test_target_host_nominal(self): + node_count = 4 + hosts = [Host(i, Mock()) for i in range(node_count)] + target_host = hosts[1] + target_host.is_up = True + + policy = DSELoadBalancingPolicy(RoundRobinPolicy()) + policy.populate(Mock(metadata=ClusterMetaMock({'127.0.0.1': target_host})), hosts) + for _ in range(10): + query_plan = list(policy.make_query_plan(None, Mock(target_host='127.0.0.1'))) + self.assertEqual(sorted(query_plan), hosts) + self.assertEqual(query_plan[0], target_host) diff --git a/tests/unit/io/test_asyncioreactor.py b/tests/unit/io/test_asyncioreactor.py index be3c2bc..aa00a32 100644 --- a/tests/unit/io/test_asyncioreactor.py +++ b/tests/unit/io/test_asyncioreactor.py @@ -1,76 +1,77 @@ +AsyncioConnection, ASYNCIO_AVAILABLE = None, False try: from cassandra.io.asyncioreactor import AsyncioConnection import asynctest ASYNCIO_AVAILABLE = True except (ImportError, SyntaxError): AsyncioConnection = None ASYNCIO_AVAILABLE = False from tests import is_monkey_patched, connection_class from tests.unit.io.utils import TimerCallback, TimerTestMixin from mock import patch import unittest import time skip_me = (is_monkey_patched() or (not ASYNCIO_AVAILABLE) or (connection_class is not AsyncioConnection)) @unittest.skipIf(is_monkey_patched(), 'runtime is monkey patched for another reactor') @unittest.skipIf(connection_class is not AsyncioConnection, 'not running asyncio tests; current connection_class is {}'.format(connection_class)) @unittest.skipUnless(ASYNCIO_AVAILABLE, "asyncio is not available for this runtime") class AsyncioTimerTests(TimerTestMixin, unittest.TestCase): @classmethod def setUpClass(cls): if skip_me: return cls.connection_class = AsyncioConnection AsyncioConnection.initialize_reactor() @classmethod def tearDownClass(cls): if skip_me: return if ASYNCIO_AVAILABLE and AsyncioConnection._loop: AsyncioConnection._loop.stop() @property def create_timer(self): return self.connection.create_timer @property def _timers(self): raise RuntimeError('no TimerManager for AsyncioConnection') def setUp(self): if skip_me: return socket_patcher = patch('socket.socket') self.addCleanup(socket_patcher.stop) socket_patcher.start() old_selector = AsyncioConnection._loop._selector AsyncioConnection._loop._selector = asynctest.TestSelector() def reset_selector(): AsyncioConnection._loop._selector = old_selector self.addCleanup(reset_selector) super(AsyncioTimerTests, self).setUp() def test_timer_cancellation(self): # Various lists for tracking callback stage timeout = .1 callback = TimerCallback(timeout) timer = self.create_timer(timeout, callback.invoke) timer.cancel() # Release context allow for timer thread to run. time.sleep(.2) # Assert that the cancellation was honored self.assertFalse(callback.was_invoked()) diff --git a/tests/unit/io/test_asyncorereactor.py b/tests/unit/io/test_asyncorereactor.py index 7e55059..4e0e540 100644 --- a/tests/unit/io/test_asyncorereactor.py +++ b/tests/unit/io/test_asyncorereactor.py @@ -1,85 +1,85 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from mock import patch import socket -import cassandra.io.asyncorereactor +import cassandra.io.asyncorereactor as asyncorereactor from cassandra.io.asyncorereactor import AsyncoreConnection from tests import is_monkey_patched from tests.unit.io.utils import ReactorTestMixin, TimerTestMixin, noop_if_monkey_patched class AsyncorePatcher(unittest.TestCase): @classmethod @noop_if_monkey_patched def setUpClass(cls): if is_monkey_patched(): return AsyncoreConnection.initialize_reactor() socket_patcher = patch('socket.socket', spec=socket.socket) channel_patcher = patch( 'cassandra.io.asyncorereactor.AsyncoreConnection.add_channel', new=(lambda *args, **kwargs: None) ) cls.mock_socket = socket_patcher.start() cls.mock_socket.connect_ex.return_value = 0 cls.mock_socket.getsockopt.return_value = 0 cls.mock_socket.fileno.return_value = 100 channel_patcher.start() cls.patchers = (socket_patcher, channel_patcher) @classmethod @noop_if_monkey_patched def tearDownClass(cls): for p in cls.patchers: try: p.stop() except: pass class AsyncoreConnectionTest(ReactorTestMixin, AsyncorePatcher): connection_class = AsyncoreConnection socket_attr_name = 'socket' def setUp(self): if is_monkey_patched(): raise unittest.SkipTest("Can't test asyncore with monkey patching") class TestAsyncoreTimer(TimerTestMixin, AsyncorePatcher): connection_class = AsyncoreConnection @property def create_timer(self): return self.connection.create_timer @property def _timers(self): - return cassandra.io.asyncorereactor._global_loop._timers + return asyncorereactor._global_loop._timers def setUp(self): if is_monkey_patched(): raise unittest.SkipTest("Can't test asyncore with monkey patching") super(TestAsyncoreTimer, self).setUp() diff --git a/tests/unit/io/test_twistedreactor.py b/tests/unit/io/test_twistedreactor.py index f0a1d73..e7c34cb 100644 --- a/tests/unit/io/test_twistedreactor.py +++ b/tests/unit/io/test_twistedreactor.py @@ -1,226 +1,191 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest from mock import Mock, patch from cassandra.connection import DefaultEndPoint try: from twisted.test import proto_helpers from twisted.python.failure import Failure from cassandra.io import twistedreactor from cassandra.io.twistedreactor import TwistedConnection except ImportError: twistedreactor = TwistedConnection = None # NOQA from cassandra.connection import _Frame from tests.unit.io.utils import TimerTestMixin class TestTwistedTimer(TimerTestMixin, unittest.TestCase): """ Simple test class that is used to validate that the TimerManager, and timer classes function appropriately with the twisted infrastructure """ connection_class = TwistedConnection @property def create_timer(self): return self.connection.create_timer @property def _timers(self): return self.connection._loop._timers def setUp(self): if twistedreactor is None: raise unittest.SkipTest("Twisted libraries not available") twistedreactor.TwistedConnection.initialize_reactor() super(TestTwistedTimer, self).setUp() class TestTwistedProtocol(unittest.TestCase): def setUp(self): if twistedreactor is None: raise unittest.SkipTest("Twisted libraries not available") twistedreactor.TwistedConnection.initialize_reactor() self.tr = proto_helpers.StringTransportWithDisconnection() self.tr.connector = Mock() self.mock_connection = Mock() - self.tr.connector.factory = twistedreactor.TwistedConnectionClientFactory( - self.mock_connection) - self.obj_ut = twistedreactor.TwistedConnectionProtocol() + self.obj_ut = twistedreactor.TwistedConnectionProtocol(self.mock_connection) self.tr.protocol = self.obj_ut def tearDown(self): pass def test_makeConnection(self): """ Verify that the protocol class notifies the connection object that a successful connection was made. """ self.obj_ut.makeConnection(self.tr) self.assertTrue(self.mock_connection.client_connection_made.called) def test_receiving_data(self): """ Verify that the dataReceived() callback writes the data to the connection object's buffer and calls handle_read(). """ self.obj_ut.makeConnection(self.tr) self.obj_ut.dataReceived('foobar') self.assertTrue(self.mock_connection.handle_read.called) self.mock_connection._iobuf.write.assert_called_with("foobar") -class TestTwistedClientFactory(unittest.TestCase): - def setUp(self): - if twistedreactor is None: - raise unittest.SkipTest("Twisted libraries not available") - twistedreactor.TwistedConnection.initialize_reactor() - self.mock_connection = Mock() - self.obj_ut = twistedreactor.TwistedConnectionClientFactory( - self.mock_connection) - - def test_client_connection_failed(self): - """ - Verify that connection failed causes the connection object to close. - """ - exc = Exception('a test') - self.obj_ut.clientConnectionFailed(None, Failure(exc)) - self.mock_connection.defunct.assert_called_with(exc) - - def test_client_connection_lost(self): - """ - Verify that connection lost causes the connection object to close. - """ - exc = Exception('a test') - self.obj_ut.clientConnectionLost(None, Failure(exc)) - self.mock_connection.defunct.assert_called_with(exc) - - class TestTwistedConnection(unittest.TestCase): def setUp(self): if twistedreactor is None: raise unittest.SkipTest("Twisted libraries not available") twistedreactor.TwistedConnection.initialize_reactor() self.reactor_cft_patcher = patch( 'twisted.internet.reactor.callFromThread') self.reactor_run_patcher = patch('twisted.internet.reactor.run') self.mock_reactor_cft = self.reactor_cft_patcher.start() self.mock_reactor_run = self.reactor_run_patcher.start() self.obj_ut = twistedreactor.TwistedConnection(DefaultEndPoint('1.2.3.4'), cql_version='3.0.1') def tearDown(self): self.reactor_cft_patcher.stop() self.reactor_run_patcher.stop() def test_connection_initialization(self): """ Verify that __init__() works correctly. """ self.mock_reactor_cft.assert_called_with(self.obj_ut.add_connection) self.obj_ut._loop._cleanup() self.mock_reactor_run.assert_called_with(installSignalHandlers=False) - @patch('twisted.internet.reactor.connectTCP') - def test_add_connection(self, mock_connectTCP): - """ - Verify that add_connection() gives us a valid twisted connector. - """ - self.obj_ut.add_connection() - self.assertTrue(self.obj_ut.connector is not None) - self.assertTrue(mock_connectTCP.called) - def test_client_connection_made(self): """ Verifiy that _send_options_message() is called in client_connection_made() """ self.obj_ut._send_options_message = Mock() self.obj_ut.client_connection_made(Mock()) self.obj_ut._send_options_message.assert_called_with() @patch('twisted.internet.reactor.connectTCP') def test_close(self, mock_connectTCP): """ Verify that close() disconnects the connector and errors callbacks. """ + transport = Mock() self.obj_ut.error_all_requests = Mock() self.obj_ut.add_connection() + self.obj_ut.client_connection_made(transport) self.obj_ut.is_closed = False self.obj_ut.close() self.assertTrue(self.obj_ut.connected_event.is_set()) self.assertTrue(self.obj_ut.error_all_requests.called) def test_handle_read__incomplete(self): """ Verify that handle_read() processes incomplete messages properly. """ self.obj_ut.process_msg = Mock() self.assertEqual(self.obj_ut._iobuf.getvalue(), b'') # buf starts empty # incomplete header self.obj_ut._iobuf.write(b'\x84\x00\x00\x00\x00') self.obj_ut.handle_read() - self.assertEqual(self.obj_ut._iobuf.getvalue(), b'\x84\x00\x00\x00\x00') + self.assertEqual(self.obj_ut._io_buffer.cql_frame_buffer.getvalue(), b'\x84\x00\x00\x00\x00') # full header, but incomplete body self.obj_ut._iobuf.write(b'\x00\x00\x00\x15') self.obj_ut.handle_read() - self.assertEqual(self.obj_ut._iobuf.getvalue(), + self.assertEqual(self.obj_ut._io_buffer.cql_frame_buffer.getvalue(), b'\x84\x00\x00\x00\x00\x00\x00\x00\x15') self.assertEqual(self.obj_ut._current_frame.end_pos, 30) # verify we never attempted to process the incomplete message self.assertFalse(self.obj_ut.process_msg.called) def test_handle_read__fullmessage(self): """ Verify that handle_read() processes complete messages properly. """ self.obj_ut.process_msg = Mock() self.assertEqual(self.obj_ut._iobuf.getvalue(), b'') # buf starts empty # write a complete message, plus 'NEXT' (to simulate next message) # assumes protocol v3+ as default Connection.protocol_version body = b'this is the drum roll' extra = b'NEXT' self.obj_ut._iobuf.write( b'\x84\x01\x00\x02\x03\x00\x00\x00\x15' + body + extra) self.obj_ut.handle_read() - self.assertEqual(self.obj_ut._iobuf.getvalue(), extra) + self.assertEqual(self.obj_ut._io_buffer.cql_frame_buffer.getvalue(), extra) self.obj_ut.process_msg.assert_called_with( _Frame(version=4, flags=1, stream=2, opcode=3, body_offset=9, end_pos=9 + len(body)), body) @patch('twisted.internet.reactor.connectTCP') def test_push(self, mock_connectTCP): """ Verifiy that push() calls transport.write(data). """ self.obj_ut.add_connection() transport_mock = Mock() self.obj_ut.transport = transport_mock self.obj_ut.push('123 pickup') self.mock_reactor_cft.assert_called_with( transport_mock.write, '123 pickup') diff --git a/tests/unit/io/utils.py b/tests/unit/io/utils.py index 2856b9d..848513f 100644 --- a/tests/unit/io/utils.py +++ b/tests/unit/io/utils.py @@ -1,516 +1,517 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -from cassandra.connection import (ConnectionException, ProtocolError, - HEADER_DIRECTION_TO_CLIENT) -from cassandra.marshal import int32_pack, uint8_pack, uint32_pack -from cassandra.protocol import (write_stringmultimap, write_int, write_string, - SupportedMessage, ReadyMessage, ServerError) +from cassandra.connection import ( + ConnectionException, ProtocolError, HEADER_DIRECTION_TO_CLIENT +) +from cassandra.marshal import uint8_pack, uint32_pack +from cassandra.protocol import ( + write_stringmultimap, write_int, write_string, SupportedMessage, ReadyMessage, ServerError +) from cassandra.connection import DefaultEndPoint - from tests import is_monkey_patched import io import random from functools import wraps from itertools import cycle import six from six import binary_type, BytesIO from mock import Mock import errno import logging import math import os from socket import error as socket_error import ssl try: import unittest2 as unittest except ImportError: import unittest # noqa import time log = logging.getLogger(__name__) class TimerCallback(object): invoked = False created_time = 0 invoked_time = 0 expected_wait = 0 def __init__(self, expected_wait): self.invoked = False self.created_time = time.time() self.expected_wait = expected_wait def invoke(self): self.invoked_time = time.time() self.invoked = True def was_invoked(self): return self.invoked def get_wait_time(self): elapsed_time = self.invoked_time - self.created_time return elapsed_time def wait_match_excepted(self): if self.expected_wait - .01 <= self.get_wait_time() <= self.expected_wait + .01: return True return False def get_timeout(gross_time, start, end, precision, split_range): """ A way to generate varying timeouts based on ranges :param gross_time: Some integer between start and end :param start: the start value of the range :param end: the end value of the range :param precision: the precision to use to generate the timeout. :param split_range: generate values from both ends :return: a timeout value to use """ if split_range: top_num = float(end) / precision bottom_num = float(start) / precision if gross_time % 2 == 0: timeout = top_num - float(gross_time) / precision else: timeout = bottom_num + float(gross_time) / precision else: timeout = float(gross_time) / precision return timeout def submit_and_wait_for_completion(unit_test, create_timer, start, end, increment, precision, split_range=False): """ This will submit a number of timers to the provided connection. It will then ensure that the corresponding callback is invoked in the appropriate amount of time. :param unit_test: Invoking unit tests :param connection: Connection to create the timer on. :param start: Lower bound of range. :param end: Upper bound of the time range :param increment: +1, or -1 :param precision: 100 for centisecond, 1000 for milliseconds :param split_range: True to split the range between incrementing and decrementing. """ # Various lists for tracking callback as completed or pending pending_callbacks = [] completed_callbacks = [] # submit timers with various timeouts for gross_time in range(start, end, increment): timeout = get_timeout(gross_time, start, end, precision, split_range) callback = TimerCallback(timeout) create_timer(timeout, callback.invoke) pending_callbacks.append(callback) # wait for all the callbacks associated with the timers to be invoked while len(pending_callbacks) is not 0: for callback in pending_callbacks: if callback.was_invoked(): pending_callbacks.remove(callback) completed_callbacks.append(callback) time.sleep(.1) # ensure they are all called back in a timely fashion for callback in completed_callbacks: unit_test.assertAlmostEqual(callback.expected_wait, callback.get_wait_time(), delta=.15) def noop_if_monkey_patched(f): if is_monkey_patched(): @wraps(f) def noop(*args, **kwargs): return return noop return f class TimerTestMixin(object): connection_class = connection = None # replace with property returning the connection's create_timer and _timers create_timer = _timers = None def setUp(self): self.connection = self.connection_class( DefaultEndPoint("127.0.0.1"), connect_timeout=5 ) def tearDown(self): self.connection.close() def test_multi_timer_validation(self): """ Verify that timer timeouts are honored appropriately """ # Tests timers submitted in order at various timeouts submit_and_wait_for_completion(self, self.create_timer, 0, 100, 1, 100) # Tests timers submitted in reverse order at various timeouts submit_and_wait_for_completion(self, self.create_timer, 100, 0, -1, 100) # Tests timers submitted in varying order at various timeouts submit_and_wait_for_completion(self, self.create_timer, 0, 100, 1, 100, True), def test_timer_cancellation(self): """ Verify that timer cancellation is honored """ # Various lists for tracking callback stage timeout = .1 callback = TimerCallback(timeout) timer = self.create_timer(timeout, callback.invoke) timer.cancel() # Release context allow for timer thread to run. time.sleep(.2) timer_manager = self._timers # Assert that the cancellation was honored self.assertFalse(timer_manager._queue) self.assertFalse(timer_manager._new_timers) self.assertFalse(callback.was_invoked()) class ReactorTestMixin(object): connection_class = socket_attr_name = None null_handle_function_args = () def get_socket(self, connection): return getattr(connection, self.socket_attr_name) def set_socket(self, connection, obj): return setattr(connection, self.socket_attr_name, obj) def make_header_prefix(self, message_class, version=2, stream_id=0): return binary_type().join(map(uint8_pack, [ 0xff & (HEADER_DIRECTION_TO_CLIENT | version), 0, # flags (compression) stream_id, message_class.opcode # opcode ])) def make_connection(self): c = self.connection_class(DefaultEndPoint('1.2.3.4'), cql_version='3.0.1', connect_timeout=5) mocket = Mock() mocket.send.side_effect = lambda x: len(x) self.set_socket(c, mocket) return c def make_options_body(self): options_buf = BytesIO() write_stringmultimap(options_buf, { 'CQL_VERSION': ['3.0.1'], 'COMPRESSION': [] }) return options_buf.getvalue() def make_error_body(self, code, msg): buf = BytesIO() write_int(buf, code) write_string(buf, msg) return buf.getvalue() def make_msg(self, header, body=binary_type()): return header + uint32_pack(len(body)) + body def test_successful_connection(self): c = self.make_connection() # let it write the OptionsMessage c.handle_write(*self.null_handle_function_args) # read in a SupportedMessage response header = self.make_header_prefix(SupportedMessage) options = self.make_options_body() self.get_socket(c).recv.return_value = self.make_msg(header, options) c.handle_read(*self.null_handle_function_args) # let it write out a StartupMessage c.handle_write(*self.null_handle_function_args) header = self.make_header_prefix(ReadyMessage, stream_id=1) self.get_socket(c).recv.return_value = self.make_msg(header) c.handle_read(*self.null_handle_function_args) self.assertTrue(c.connected_event.is_set()) return c def test_eagain_on_buffer_size(self): self._check_error_recovery_on_buffer_size(errno.EAGAIN) def test_ewouldblock_on_buffer_size(self): self._check_error_recovery_on_buffer_size(errno.EWOULDBLOCK) def test_sslwantread_on_buffer_size(self): self._check_error_recovery_on_buffer_size( ssl.SSL_ERROR_WANT_READ, error_class=ssl.SSLError) def test_sslwantwrite_on_buffer_size(self): self._check_error_recovery_on_buffer_size( ssl.SSL_ERROR_WANT_WRITE, error_class=ssl.SSLError) def _check_error_recovery_on_buffer_size(self, error_code, error_class=socket_error): c = self.test_successful_connection() # current data, used by the recv side_effect message_chunks = None def recv_side_effect(*args): response = message_chunks.pop(0) if isinstance(response, error_class): raise response else: return response # setup self.get_socket(c).recv.side_effect = recv_side_effect c.process_io_buffer = Mock() def chunk(size): return six.b('a') * size buf_size = c.in_buffer_size # List of messages to test. A message = (chunks, expected_read_size) messages = [ ([chunk(200)], 200), ([chunk(200), chunk(200)], 200), # first chunk < in_buffer_size, process the message ([chunk(buf_size), error_class(error_code)], buf_size), ([chunk(buf_size), chunk(buf_size), error_class(error_code)], buf_size*2), ([chunk(buf_size), chunk(buf_size), chunk(10)], (buf_size*2) + 10), ([chunk(buf_size), chunk(buf_size), error_class(error_code), chunk(10)], buf_size*2), ([error_class(error_code), chunk(buf_size)], 0) ] for message, expected_size in messages: message_chunks = message - c._iobuf = io.BytesIO() + c._io_buffer._io_buffer = io.BytesIO() c.process_io_buffer.reset_mock() c.handle_read(*self.null_handle_function_args) - c._iobuf.seek(0, os.SEEK_END) + c._io_buffer.io_buffer.seek(0, os.SEEK_END) # Ensure the message size is the good one and that the # message has been processed if it is non-empty - self.assertEqual(c._iobuf.tell(), expected_size) + self.assertEqual(c._io_buffer.io_buffer.tell(), expected_size) if expected_size == 0: c.process_io_buffer.assert_not_called() else: c.process_io_buffer.assert_called_once_with() def test_protocol_error(self): c = self.make_connection() # let it write the OptionsMessage c.handle_write(*self.null_handle_function_args) # read in a SupportedMessage response header = self.make_header_prefix(SupportedMessage, version=0xa4) options = self.make_options_body() self.get_socket(c).recv.return_value = self.make_msg(header, options) c.handle_read(*self.null_handle_function_args) # make sure it errored correctly self.assertTrue(c.is_defunct) self.assertTrue(c.connected_event.is_set()) self.assertIsInstance(c.last_error, ProtocolError) def test_error_message_on_startup(self): c = self.make_connection() # let it write the OptionsMessage c.handle_write(*self.null_handle_function_args) # read in a SupportedMessage response header = self.make_header_prefix(SupportedMessage) options = self.make_options_body() self.get_socket(c).recv.return_value = self.make_msg(header, options) c.handle_read(*self.null_handle_function_args) # let it write out a StartupMessage c.handle_write(*self.null_handle_function_args) header = self.make_header_prefix(ServerError, stream_id=1) body = self.make_error_body(ServerError.error_code, ServerError.summary) self.get_socket(c).recv.return_value = self.make_msg(header, body) c.handle_read(*self.null_handle_function_args) # make sure it errored correctly self.assertTrue(c.is_defunct) self.assertIsInstance(c.last_error, ConnectionException) self.assertTrue(c.connected_event.is_set()) def test_socket_error_on_write(self): c = self.make_connection() # make the OptionsMessage write fail self.get_socket(c).send.side_effect = socket_error(errno.EIO, "bad stuff!") c.handle_write(*self.null_handle_function_args) # make sure it errored correctly self.assertTrue(c.is_defunct) self.assertIsInstance(c.last_error, socket_error) self.assertTrue(c.connected_event.is_set()) def test_blocking_on_write(self): c = self.make_connection() # make the OptionsMessage write block self.get_socket(c).send.side_effect = socket_error(errno.EAGAIN, "socket busy") c.handle_write(*self.null_handle_function_args) self.assertFalse(c.is_defunct) # try again with normal behavior self.get_socket(c).send.side_effect = lambda x: len(x) c.handle_write(*self.null_handle_function_args) self.assertFalse(c.is_defunct) self.assertTrue(self.get_socket(c).send.call_args is not None) def test_partial_send(self): c = self.make_connection() # only write the first four bytes of the OptionsMessage write_size = 4 self.get_socket(c).send.side_effect = None self.get_socket(c).send.return_value = write_size c.handle_write(*self.null_handle_function_args) msg_size = 9 # v3+ frame header expected_writes = int(math.ceil(float(msg_size) / write_size)) size_mod = msg_size % write_size last_write_size = size_mod if size_mod else write_size self.assertFalse(c.is_defunct) self.assertEqual(expected_writes, self.get_socket(c).send.call_count) self.assertEqual(last_write_size, len(self.get_socket(c).send.call_args[0][0])) def test_socket_error_on_read(self): c = self.make_connection() # let it write the OptionsMessage c.handle_write(*self.null_handle_function_args) # read in a SupportedMessage response self.get_socket(c).recv.side_effect = socket_error(errno.EIO, "busy socket") c.handle_read(*self.null_handle_function_args) # make sure it errored correctly self.assertTrue(c.is_defunct) self.assertIsInstance(c.last_error, socket_error) self.assertTrue(c.connected_event.is_set()) def test_partial_header_read(self): c = self.make_connection() header = self.make_header_prefix(SupportedMessage) options = self.make_options_body() message = self.make_msg(header, options) self.get_socket(c).recv.return_value = message[0:1] c.handle_read(*self.null_handle_function_args) - self.assertEqual(c._iobuf.getvalue(), message[0:1]) + self.assertEqual(c._io_buffer.cql_frame_buffer.getvalue(), message[0:1]) self.get_socket(c).recv.return_value = message[1:] c.handle_read(*self.null_handle_function_args) - self.assertEqual(six.binary_type(), c._iobuf.getvalue()) + self.assertEqual(six.binary_type(), c._io_buffer.io_buffer.getvalue()) # let it write out a StartupMessage c.handle_write(*self.null_handle_function_args) header = self.make_header_prefix(ReadyMessage, stream_id=1) self.get_socket(c).recv.return_value = self.make_msg(header) c.handle_read(*self.null_handle_function_args) self.assertTrue(c.connected_event.is_set()) self.assertFalse(c.is_defunct) def test_partial_message_read(self): c = self.make_connection() header = self.make_header_prefix(SupportedMessage) options = self.make_options_body() message = self.make_msg(header, options) # read in the first nine bytes self.get_socket(c).recv.return_value = message[:9] c.handle_read(*self.null_handle_function_args) - self.assertEqual(c._iobuf.getvalue(), message[:9]) + self.assertEqual(c._io_buffer.cql_frame_buffer.getvalue(), message[:9]) # ... then read in the rest self.get_socket(c).recv.return_value = message[9:] c.handle_read(*self.null_handle_function_args) - self.assertEqual(six.binary_type(), c._iobuf.getvalue()) + self.assertEqual(six.binary_type(), c._io_buffer.io_buffer.getvalue()) # let it write out a StartupMessage c.handle_write(*self.null_handle_function_args) header = self.make_header_prefix(ReadyMessage, stream_id=1) self.get_socket(c).recv.return_value = self.make_msg(header) c.handle_read(*self.null_handle_function_args) self.assertTrue(c.connected_event.is_set()) self.assertFalse(c.is_defunct) def test_mixed_message_and_buffer_sizes(self): """ Validate that all messages are processed with different scenarios: - various message sizes - various socket buffer sizes - random non-fatal errors raised """ c = self.make_connection() c.process_io_buffer = Mock() errors = cycle([ ssl.SSLError(ssl.SSL_ERROR_WANT_READ), ssl.SSLError(ssl.SSL_ERROR_WANT_WRITE), socket_error(errno.EWOULDBLOCK), socket_error(errno.EAGAIN) ]) for buffer_size in [512, 1024, 2048, 4096, 8192]: c.in_buffer_size = buffer_size for i in range(1, 15): c.process_io_buffer.reset_mock() - c._iobuf = io.BytesIO() + c._io_buffer._io_buffer = io.BytesIO() message = io.BytesIO(six.b('a') * (2**i)) def recv_side_effect(*args): if random.randint(1,10) % 3 == 0: raise next(errors) return message.read(args[0]) self.get_socket(c).recv.side_effect = recv_side_effect c.handle_read(*self.null_handle_function_args) - if c._iobuf.tell(): + if c._io_buffer.io_buffer.tell(): c.process_io_buffer.assert_called_once() else: c.process_io_buffer.assert_not_called() diff --git a/tests/integration/advanced/__init__.py b/tests/unit/test_auth.py similarity index 54% copy from tests/integration/advanced/__init__.py copy to tests/unit/test_auth.py index 662f5b8..7b4196f 100644 --- a/tests/integration/advanced/__init__.py +++ b/tests/unit/test_auth.py @@ -1,23 +1,32 @@ -# Copyright DataStax, Inc. +# -*- coding: utf-8 -*- +# # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and -# limitations under the License +# limitations under the License. + +import six +from cassandra.auth import PlainTextAuthenticator try: import unittest2 as unittest except ImportError: import unittest # noqa -try: - from ccmlib import common -except ImportError as e: - raise unittest.SkipTest('ccm is a dependency for integration tests:', e) + +class TestPlainTextAuthenticator(unittest.TestCase): + + def test_evaluate_challenge_with_unicode_data(self): + authenticator = PlainTextAuthenticator("johnӁ", "doeӁ") + self.assertEqual( + authenticator.evaluate_challenge(six.ensure_binary('PLAIN-START')), + six.ensure_binary("\x00johnӁ\x00doeӁ") + ) diff --git a/tests/unit/test_cluster.py b/tests/unit/test_cluster.py index fd46731..620f642 100644 --- a/tests/unit/test_cluster.py +++ b/tests/unit/test_cluster.py @@ -1,518 +1,584 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa import logging import six from mock import patch, Mock from cassandra import ConsistencyLevel, DriverException, Timeout, Unavailable, RequestExecutionException, ReadTimeout, WriteTimeout, CoordinationFailure, ReadFailure, WriteFailure, FunctionFailure, AlreadyExists,\ - InvalidRequest, Unauthorized, AuthenticationFailed, OperationTimedOut, UnsupportedOperation, RequestValidationException, ConfigurationException -from cassandra.cluster import _Scheduler, Session, Cluster, _NOT_SET, default_lbp_factory, \ - ExecutionProfile, _ConfigMode, EXEC_PROFILE_DEFAULT, NoHostAvailable -from cassandra.policies import HostDistance, RetryPolicy, RoundRobinPolicy, \ - DowngradingConsistencyRetryPolicy, SimpleConvictionPolicy -from cassandra.query import SimpleStatement, named_tuple_factory, tuple_factory + InvalidRequest, Unauthorized, AuthenticationFailed, OperationTimedOut, UnsupportedOperation, RequestValidationException, ConfigurationException, ProtocolVersion +from cassandra.cluster import _Scheduler, Session, Cluster, default_lbp_factory, \ + ExecutionProfile, _ConfigMode, EXEC_PROFILE_DEFAULT from cassandra.pool import Host +from cassandra.policies import HostDistance, RetryPolicy, RoundRobinPolicy, DowngradingConsistencyRetryPolicy, SimpleConvictionPolicy +from cassandra.query import SimpleStatement, named_tuple_factory, tuple_factory from tests.unit.utils import mock_session_pools from tests import connection_class log = logging.getLogger(__name__) class ExceptionTypeTest(unittest.TestCase): def test_exception_types(self): """ PYTHON-443 Sanity check to ensure we don't unintentionally change class hierarchy of exception types """ self.assertTrue(issubclass(Unavailable, DriverException)) self.assertTrue(issubclass(Unavailable, RequestExecutionException)) self.assertTrue(issubclass(ReadTimeout, DriverException)) self.assertTrue(issubclass(ReadTimeout, RequestExecutionException)) self.assertTrue(issubclass(ReadTimeout, Timeout)) self.assertTrue(issubclass(WriteTimeout, DriverException)) self.assertTrue(issubclass(WriteTimeout, RequestExecutionException)) self.assertTrue(issubclass(WriteTimeout, Timeout)) self.assertTrue(issubclass(CoordinationFailure, DriverException)) self.assertTrue(issubclass(CoordinationFailure, RequestExecutionException)) self.assertTrue(issubclass(ReadFailure, DriverException)) self.assertTrue(issubclass(ReadFailure, RequestExecutionException)) self.assertTrue(issubclass(ReadFailure, CoordinationFailure)) self.assertTrue(issubclass(WriteFailure, DriverException)) self.assertTrue(issubclass(WriteFailure, RequestExecutionException)) self.assertTrue(issubclass(WriteFailure, CoordinationFailure)) self.assertTrue(issubclass(FunctionFailure, DriverException)) self.assertTrue(issubclass(FunctionFailure, RequestExecutionException)) self.assertTrue(issubclass(RequestValidationException, DriverException)) self.assertTrue(issubclass(ConfigurationException, DriverException)) self.assertTrue(issubclass(ConfigurationException, RequestValidationException)) self.assertTrue(issubclass(AlreadyExists, DriverException)) self.assertTrue(issubclass(AlreadyExists, RequestValidationException)) self.assertTrue(issubclass(AlreadyExists, ConfigurationException)) self.assertTrue(issubclass(InvalidRequest, DriverException)) self.assertTrue(issubclass(InvalidRequest, RequestValidationException)) self.assertTrue(issubclass(Unauthorized, DriverException)) self.assertTrue(issubclass(Unauthorized, RequestValidationException)) self.assertTrue(issubclass(AuthenticationFailed, DriverException)) self.assertTrue(issubclass(OperationTimedOut, DriverException)) self.assertTrue(issubclass(UnsupportedOperation, DriverException)) class ClusterTest(unittest.TestCase): + def test_tuple_for_contact_points(self): + cluster = Cluster(contact_points=[('localhost', 9045), ('127.0.0.2', 9046), '127.0.0.3'], port=9999) + for cp in cluster.endpoints_resolved: + if cp.address in ('::1', '127.0.0.1'): + self.assertEqual(cp.port, 9045) + elif cp.address == '127.0.0.2': + self.assertEqual(cp.port, 9046) + else: + self.assertEqual(cp.address, '127.0.0.3') + self.assertEqual(cp.port, 9999) + def test_invalid_contact_point_types(self): with self.assertRaises(ValueError): Cluster(contact_points=[None], protocol_version=4, connect_timeout=1) with self.assertRaises(TypeError): Cluster(contact_points="not a sequence", protocol_version=4, connect_timeout=1) def test_requests_in_flight_threshold(self): d = HostDistance.LOCAL mn = 3 mx = 5 c = Cluster(protocol_version=2) c.set_min_requests_per_connection(d, mn) c.set_max_requests_per_connection(d, mx) # min underflow, max, overflow for n in (-1, mx, 127): self.assertRaises(ValueError, c.set_min_requests_per_connection, d, n) # max underflow, under min, overflow for n in (0, mn, 128): self.assertRaises(ValueError, c.set_max_requests_per_connection, d, n) class SchedulerTest(unittest.TestCase): # TODO: this suite could be expanded; for now just adding a test covering a ticket @patch('time.time', return_value=3) # always queue at same time @patch('cassandra.cluster._Scheduler.run') # don't actually run the thread def test_event_delay_timing(self, *_): """ Schedule something with a time collision to make sure the heap comparison works PYTHON-473 """ sched = _Scheduler(None) sched.schedule(0, lambda: None) sched.schedule(0, lambda: None) # pre-473: "TypeError: unorderable types: function() < function()"t class SessionTest(unittest.TestCase): def setUp(self): if connection_class is None: raise unittest.SkipTest('libev does not appear to be installed correctly') connection_class.initialize_reactor() # TODO: this suite could be expanded; for now just adding a test covering a PR @mock_session_pools - def test_default_serial_consistency_level(self, *_): + def test_default_serial_consistency_level_ep(self, *_): + """ + Make sure default_serial_consistency_level passes through to a query message using execution profiles. + Also make sure Statement.serial_consistency_level overrides the default. + + PR #510 + """ + c = Cluster(protocol_version=4) + s = Session(c, [Host("127.0.0.1", SimpleConvictionPolicy)]) + + # default is None + default_profile = c.profile_manager.default + self.assertIsNone(default_profile.serial_consistency_level) + + for cl in (None, ConsistencyLevel.LOCAL_SERIAL, ConsistencyLevel.SERIAL): + s.get_execution_profile(EXEC_PROFILE_DEFAULT).serial_consistency_level = cl + + # default is passed through + f = s.execute_async(query='') + self.assertEqual(f.message.serial_consistency_level, cl) + + # any non-None statement setting takes precedence + for cl_override in (ConsistencyLevel.LOCAL_SERIAL, ConsistencyLevel.SERIAL): + f = s.execute_async(SimpleStatement(query_string='', serial_consistency_level=cl_override)) + self.assertEqual(default_profile.serial_consistency_level, cl) + self.assertEqual(f.message.serial_consistency_level, cl_override) + + @mock_session_pools + def test_default_serial_consistency_level_legacy(self, *_): """ - Make sure default_serial_consistency_level passes through to a query message. + Make sure default_serial_consistency_level passes through to a query message using legacy settings. Also make sure Statement.serial_consistency_level overrides the default. PR #510 """ - s = Session(Cluster(protocol_version=4), [Host("127.0.0.1", SimpleConvictionPolicy)]) + c = Cluster(protocol_version=4) + s = Session(c, [Host("127.0.0.1", SimpleConvictionPolicy)]) # default is None self.assertIsNone(s.default_serial_consistency_level) # Should fail with self.assertRaises(ValueError): s.default_serial_consistency_level = ConsistencyLevel.ANY with self.assertRaises(ValueError): s.default_serial_consistency_level = 1001 for cl in (None, ConsistencyLevel.LOCAL_SERIAL, ConsistencyLevel.SERIAL): s.default_serial_consistency_level = cl - # default is passed through - f = s.execute_async(query='') - self.assertEqual(f.message.serial_consistency_level, cl) - # any non-None statement setting takes precedence for cl_override in (ConsistencyLevel.LOCAL_SERIAL, ConsistencyLevel.SERIAL): f = s.execute_async(SimpleStatement(query_string='', serial_consistency_level=cl_override)) self.assertEqual(s.default_serial_consistency_level, cl) self.assertEqual(f.message.serial_consistency_level, cl_override) +class ProtocolVersionTests(unittest.TestCase): + + def test_protocol_downgrade_test(self): + lower = ProtocolVersion.get_lower_supported(ProtocolVersion.DSE_V2) + self.assertEqual(ProtocolVersion.DSE_V1, lower) + lower = ProtocolVersion.get_lower_supported(ProtocolVersion.DSE_V1) + self.assertEqual(ProtocolVersion.V5,lower) + lower = ProtocolVersion.get_lower_supported(ProtocolVersion.V5) + self.assertEqual(ProtocolVersion.V4,lower) + lower = ProtocolVersion.get_lower_supported(ProtocolVersion.V4) + self.assertEqual(ProtocolVersion.V3,lower) + lower = ProtocolVersion.get_lower_supported(ProtocolVersion.V3) + self.assertEqual(ProtocolVersion.V2,lower) + lower = ProtocolVersion.get_lower_supported(ProtocolVersion.V2) + self.assertEqual(ProtocolVersion.V1, lower) + lower = ProtocolVersion.get_lower_supported(ProtocolVersion.V1) + self.assertEqual(0, lower) + + self.assertTrue(ProtocolVersion.uses_error_code_map(ProtocolVersion.DSE_V1)) + self.assertTrue(ProtocolVersion.uses_int_query_flags(ProtocolVersion.DSE_V1)) + + self.assertFalse(ProtocolVersion.uses_error_code_map(ProtocolVersion.V4)) + self.assertFalse(ProtocolVersion.uses_int_query_flags(ProtocolVersion.V4)) + + class ExecutionProfileTest(unittest.TestCase): def setUp(self): if connection_class is None: raise unittest.SkipTest('libev does not appear to be installed correctly') connection_class.initialize_reactor() def _verify_response_future_profile(self, rf, prof): self.assertEqual(rf._load_balancer, prof.load_balancing_policy) self.assertEqual(rf._retry_policy, prof.retry_policy) self.assertEqual(rf.message.consistency_level, prof.consistency_level) self.assertEqual(rf.message.serial_consistency_level, prof.serial_consistency_level) self.assertEqual(rf.timeout, prof.request_timeout) self.assertEqual(rf.row_factory, prof.row_factory) @mock_session_pools def test_default_exec_parameters(self): cluster = Cluster() self.assertEqual(cluster._config_mode, _ConfigMode.UNCOMMITTED) self.assertEqual(cluster.load_balancing_policy.__class__, default_lbp_factory().__class__) + self.assertEqual(cluster.profile_manager.default.load_balancing_policy.__class__, default_lbp_factory().__class__) self.assertEqual(cluster.default_retry_policy.__class__, RetryPolicy) + self.assertEqual(cluster.profile_manager.default.retry_policy.__class__, RetryPolicy) session = Session(cluster, hosts=[Host("127.0.0.1", SimpleConvictionPolicy)]) self.assertEqual(session.default_timeout, 10.0) + self.assertEqual(cluster.profile_manager.default.request_timeout, 10.0) self.assertEqual(session.default_consistency_level, ConsistencyLevel.LOCAL_ONE) + self.assertEqual(cluster.profile_manager.default.consistency_level, ConsistencyLevel.LOCAL_ONE) self.assertEqual(session.default_serial_consistency_level, None) + self.assertEqual(cluster.profile_manager.default.serial_consistency_level, None) self.assertEqual(session.row_factory, named_tuple_factory) + self.assertEqual(cluster.profile_manager.default.row_factory, named_tuple_factory) @mock_session_pools def test_default_legacy(self): cluster = Cluster(load_balancing_policy=RoundRobinPolicy(), default_retry_policy=DowngradingConsistencyRetryPolicy()) self.assertEqual(cluster._config_mode, _ConfigMode.LEGACY) session = Session(cluster, hosts=[Host("127.0.0.1", SimpleConvictionPolicy)]) session.default_timeout = 3.7 session.default_consistency_level = ConsistencyLevel.ALL session.default_serial_consistency_level = ConsistencyLevel.SERIAL rf = session.execute_async("query") expected_profile = ExecutionProfile(cluster.load_balancing_policy, cluster.default_retry_policy, session.default_consistency_level, session.default_serial_consistency_level, session.default_timeout, session.row_factory) self._verify_response_future_profile(rf, expected_profile) @mock_session_pools def test_default_profile(self): non_default_profile = ExecutionProfile(RoundRobinPolicy(), *[object() for _ in range(2)]) cluster = Cluster(execution_profiles={'non-default': non_default_profile}) session = Session(cluster, hosts=[Host("127.0.0.1", SimpleConvictionPolicy)]) self.assertEqual(cluster._config_mode, _ConfigMode.PROFILES) - default_profile = session.get_execution_profile(EXEC_PROFILE_DEFAULT) + default_profile = cluster.profile_manager.profiles[EXEC_PROFILE_DEFAULT] rf = session.execute_async("query") self._verify_response_future_profile(rf, default_profile) rf = session.execute_async("query", execution_profile='non-default') self._verify_response_future_profile(rf, non_default_profile) for name, ep in six.iteritems(cluster.profile_manager.profiles): self.assertEqual(ep, session.get_execution_profile(name)) # invalid ep with self.assertRaises(ValueError): session.get_execution_profile('non-existent') def test_serial_consistency_level_validation(self): # should pass ep = ExecutionProfile(RoundRobinPolicy(), serial_consistency_level=ConsistencyLevel.SERIAL) ep = ExecutionProfile(RoundRobinPolicy(), serial_consistency_level=ConsistencyLevel.LOCAL_SERIAL) # should not pass with self.assertRaises(ValueError): ep = ExecutionProfile(RoundRobinPolicy(), serial_consistency_level=ConsistencyLevel.ANY) with self.assertRaises(ValueError): ep = ExecutionProfile(RoundRobinPolicy(), serial_consistency_level=42) @mock_session_pools def test_statement_params_override_legacy(self): cluster = Cluster(load_balancing_policy=RoundRobinPolicy(), default_retry_policy=DowngradingConsistencyRetryPolicy()) self.assertEqual(cluster._config_mode, _ConfigMode.LEGACY) session = Session(cluster, hosts=[Host("127.0.0.1", SimpleConvictionPolicy)]) ss = SimpleStatement("query", retry_policy=DowngradingConsistencyRetryPolicy(), consistency_level=ConsistencyLevel.ALL, serial_consistency_level=ConsistencyLevel.SERIAL) my_timeout = 1.1234 self.assertNotEqual(ss.retry_policy.__class__, cluster.default_retry_policy) self.assertNotEqual(ss.consistency_level, session.default_consistency_level) self.assertNotEqual(ss._serial_consistency_level, session.default_serial_consistency_level) self.assertNotEqual(my_timeout, session.default_timeout) rf = session.execute_async(ss, timeout=my_timeout) expected_profile = ExecutionProfile(load_balancing_policy=cluster.load_balancing_policy, retry_policy=ss.retry_policy, request_timeout=my_timeout, consistency_level=ss.consistency_level, serial_consistency_level=ss._serial_consistency_level) self._verify_response_future_profile(rf, expected_profile) @mock_session_pools def test_statement_params_override_profile(self): non_default_profile = ExecutionProfile(RoundRobinPolicy(), *[object() for _ in range(2)]) cluster = Cluster(execution_profiles={'non-default': non_default_profile}) session = Session(cluster, hosts=[Host("127.0.0.1", SimpleConvictionPolicy)]) self.assertEqual(cluster._config_mode, _ConfigMode.PROFILES) rf = session.execute_async("query", execution_profile='non-default') ss = SimpleStatement("query", retry_policy=DowngradingConsistencyRetryPolicy(), consistency_level=ConsistencyLevel.ALL, serial_consistency_level=ConsistencyLevel.SERIAL) my_timeout = 1.1234 self.assertNotEqual(ss.retry_policy.__class__, rf._load_balancer.__class__) self.assertNotEqual(ss.consistency_level, rf.message.consistency_level) self.assertNotEqual(ss._serial_consistency_level, rf.message.serial_consistency_level) self.assertNotEqual(my_timeout, rf.timeout) rf = session.execute_async(ss, timeout=my_timeout, execution_profile='non-default') expected_profile = ExecutionProfile(non_default_profile.load_balancing_policy, ss.retry_policy, ss.consistency_level, ss._serial_consistency_level, my_timeout, non_default_profile.row_factory) self._verify_response_future_profile(rf, expected_profile) @mock_session_pools def test_no_profile_with_legacy(self): # don't construct with both self.assertRaises(ValueError, Cluster, load_balancing_policy=RoundRobinPolicy(), execution_profiles={'a': ExecutionProfile()}) self.assertRaises(ValueError, Cluster, default_retry_policy=DowngradingConsistencyRetryPolicy(), execution_profiles={'a': ExecutionProfile()}) self.assertRaises(ValueError, Cluster, load_balancing_policy=RoundRobinPolicy(), default_retry_policy=DowngradingConsistencyRetryPolicy(), execution_profiles={'a': ExecutionProfile()}) # can't add after cluster = Cluster(load_balancing_policy=RoundRobinPolicy()) self.assertRaises(ValueError, cluster.add_execution_profile, 'name', ExecutionProfile()) # session settings lock out profiles cluster = Cluster() session = Session(cluster, hosts=[Host("127.0.0.1", SimpleConvictionPolicy)]) for attr, value in (('default_timeout', 1), ('default_consistency_level', ConsistencyLevel.ANY), ('default_serial_consistency_level', ConsistencyLevel.SERIAL), ('row_factory', tuple_factory)): cluster._config_mode = _ConfigMode.UNCOMMITTED setattr(session, attr, value) self.assertRaises(ValueError, cluster.add_execution_profile, 'name' + attr, ExecutionProfile()) # don't accept profile self.assertRaises(ValueError, session.execute_async, "query", execution_profile='some name here') @mock_session_pools def test_no_legacy_with_profile(self): cluster_init = Cluster(execution_profiles={'name': ExecutionProfile()}) cluster_add = Cluster() cluster_add.add_execution_profile('name', ExecutionProfile()) # for clusters with profiles added either way... for cluster in (cluster_init, cluster_init): # don't allow legacy parameters set for attr, value in (('default_retry_policy', RetryPolicy()), ('load_balancing_policy', default_lbp_factory())): self.assertRaises(ValueError, setattr, cluster, attr, value) session = Session(cluster, hosts=[Host("127.0.0.1", SimpleConvictionPolicy)]) for attr, value in (('default_timeout', 1), ('default_consistency_level', ConsistencyLevel.ANY), ('default_serial_consistency_level', ConsistencyLevel.SERIAL), ('row_factory', tuple_factory)): self.assertRaises(ValueError, setattr, session, attr, value) @mock_session_pools def test_profile_name_value(self): internalized_profile = ExecutionProfile(RoundRobinPolicy(), *[object() for _ in range(2)]) cluster = Cluster(execution_profiles={'by-name': internalized_profile}) session = Session(cluster, hosts=[Host("127.0.0.1", SimpleConvictionPolicy)]) self.assertEqual(cluster._config_mode, _ConfigMode.PROFILES) rf = session.execute_async("query", execution_profile='by-name') self._verify_response_future_profile(rf, internalized_profile) by_value = ExecutionProfile(RoundRobinPolicy(), *[object() for _ in range(2)]) rf = session.execute_async("query", execution_profile=by_value) self._verify_response_future_profile(rf, by_value) @mock_session_pools def test_exec_profile_clone(self): cluster = Cluster(execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(), 'one': ExecutionProfile()}) session = Session(cluster, hosts=[Host("127.0.0.1", SimpleConvictionPolicy)]) profile_attrs = {'request_timeout': 1, 'consistency_level': ConsistencyLevel.ANY, 'serial_consistency_level': ConsistencyLevel.SERIAL, 'row_factory': tuple_factory, 'retry_policy': RetryPolicy(), 'load_balancing_policy': default_lbp_factory()} reference_attributes = ('retry_policy', 'load_balancing_policy') # default and one named for profile in (EXEC_PROFILE_DEFAULT, 'one'): active = session.get_execution_profile(profile) clone = session.execution_profile_clone_update(profile) self.assertIsNot(clone, active) all_updated = session.execution_profile_clone_update(clone, **profile_attrs) self.assertIsNot(all_updated, clone) for attr, value in profile_attrs.items(): self.assertEqual(getattr(clone, attr), getattr(active, attr)) if attr in reference_attributes: self.assertIs(getattr(clone, attr), getattr(active, attr)) self.assertNotEqual(getattr(all_updated, attr), getattr(active, attr)) # cannot clone nonexistent profile self.assertRaises(ValueError, session.execution_profile_clone_update, 'DOES NOT EXIST', **profile_attrs) def test_no_profiles_same_name(self): # can override default in init cluster = Cluster(execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(), 'one': ExecutionProfile()}) # cannot update default self.assertRaises(ValueError, cluster.add_execution_profile, EXEC_PROFILE_DEFAULT, ExecutionProfile()) # cannot update named init self.assertRaises(ValueError, cluster.add_execution_profile, 'one', ExecutionProfile()) # can add new name cluster.add_execution_profile('two', ExecutionProfile()) # cannot add a profile added dynamically self.assertRaises(ValueError, cluster.add_execution_profile, 'two', ExecutionProfile()) def test_warning_on_no_lbp_with_contact_points_legacy_mode(self): """ Test that users are warned when they instantiate a Cluster object in legacy mode with contact points but no load-balancing policy. @since 3.12.0 @jira_ticket PYTHON-812 @expected_result logs @test_category configuration """ self._check_warning_on_no_lbp_with_contact_points( cluster_kwargs={'contact_points': ['127.0.0.1']} ) def test_warning_on_no_lbp_with_contact_points_profile_mode(self): """ Test that users are warned when they instantiate a Cluster object in execution profile mode with contact points but no load-balancing policy. @since 3.12.0 @jira_ticket PYTHON-812 @expected_result logs @test_category configuration """ self._check_warning_on_no_lbp_with_contact_points(cluster_kwargs={ 'contact_points': ['127.0.0.1'], 'execution_profiles': {EXEC_PROFILE_DEFAULT: ExecutionProfile()} }) @mock_session_pools def _check_warning_on_no_lbp_with_contact_points(self, cluster_kwargs): with patch('cassandra.cluster.log') as patched_logger: Cluster(**cluster_kwargs) patched_logger.warning.assert_called_once() warning_message = patched_logger.warning.call_args[0][0] self.assertIn('please specify a load-balancing policy', warning_message) self.assertIn("contact_points = ['127.0.0.1']", warning_message) def test_no_warning_on_contact_points_with_lbp_legacy_mode(self): """ Test that users aren't warned when they instantiate a Cluster object with contact points and a load-balancing policy in legacy mode. @since 3.12.0 @jira_ticket PYTHON-812 @expected_result no logs @test_category configuration """ self._check_no_warning_on_contact_points_with_lbp({ 'contact_points': ['127.0.0.1'], 'load_balancing_policy': object() }) def test_no_warning_on_contact_points_with_lbp_profiles_mode(self): """ Test that users aren't warned when they instantiate a Cluster object with contact points and a load-balancing policy in execution profile mode. @since 3.12.0 @jira_ticket PYTHON-812 @expected_result no logs @test_category configuration """ ep_with_lbp = ExecutionProfile(load_balancing_policy=object()) self._check_no_warning_on_contact_points_with_lbp(cluster_kwargs={ 'contact_points': ['127.0.0.1'], 'execution_profiles': { EXEC_PROFILE_DEFAULT: ep_with_lbp } }) @mock_session_pools def _check_no_warning_on_contact_points_with_lbp(self, cluster_kwargs): """ Test that users aren't warned when they instantiate a Cluster object with contact points and a load-balancing policy. @since 3.12.0 @jira_ticket PYTHON-812 @expected_result no logs @test_category configuration """ with patch('cassandra.cluster.log') as patched_logger: Cluster(**cluster_kwargs) patched_logger.warning.assert_not_called() @mock_session_pools def test_warning_adding_no_lbp_ep_to_cluster_with_contact_points(self): ep_with_lbp = ExecutionProfile(load_balancing_policy=object()) cluster = Cluster( contact_points=['127.0.0.1'], execution_profiles={EXEC_PROFILE_DEFAULT: ep_with_lbp}) with patch('cassandra.cluster.log') as patched_logger: cluster.add_execution_profile( name='no_lbp', profile=ExecutionProfile() ) patched_logger.warning.assert_called_once() warning_message = patched_logger.warning.call_args[0][0] self.assertIn('no_lbp', warning_message) self.assertIn('trying to add', warning_message) self.assertIn('please specify a load-balancing policy', warning_message) @mock_session_pools def test_no_warning_adding_lbp_ep_to_cluster_with_contact_points(self): ep_with_lbp = ExecutionProfile(load_balancing_policy=object()) cluster = Cluster( contact_points=['127.0.0.1'], execution_profiles={EXEC_PROFILE_DEFAULT: ep_with_lbp}) with patch('cassandra.cluster.log') as patched_logger: cluster.add_execution_profile( name='with_lbp', profile=ExecutionProfile(load_balancing_policy=Mock(name='lbp')) ) patched_logger.warning.assert_not_called() diff --git a/tests/unit/test_connection.py b/tests/unit/test_connection.py index fccf854..21b8862 100644 --- a/tests/unit/test_connection.py +++ b/tests/unit/test_connection.py @@ -1,489 +1,493 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from mock import Mock, ANY, call, patch import six from six import BytesIO import time from threading import Lock from cassandra import OperationTimedOut from cassandra.cluster import Cluster from cassandra.connection import (Connection, HEADER_DIRECTION_TO_CLIENT, ProtocolError, locally_supported_compressions, ConnectionHeartbeat, _Frame, Timer, TimerManager, ConnectionException, DefaultEndPoint) from cassandra.marshal import uint8_pack, uint32_pack, int32_pack from cassandra.protocol import (write_stringmultimap, write_int, write_string, SupportedMessage, ProtocolHandler) +from tests.util import wait_until + class ConnectionTest(unittest.TestCase): def make_connection(self): c = Connection(DefaultEndPoint('1.2.3.4')) c._socket = Mock() c._socket.send.side_effect = lambda x: len(x) return c def make_header_prefix(self, message_class, version=Connection.protocol_version, stream_id=0): if Connection.protocol_version < 3: return six.binary_type().join(map(uint8_pack, [ 0xff & (HEADER_DIRECTION_TO_CLIENT | version), 0, # flags (compression) stream_id, message_class.opcode # opcode ])) else: return six.binary_type().join(map(uint8_pack, [ 0xff & (HEADER_DIRECTION_TO_CLIENT | version), 0, # flags (compression) 0, # MSB for v3+ stream stream_id, message_class.opcode # opcode ])) def make_options_body(self): options_buf = BytesIO() write_stringmultimap(options_buf, { 'CQL_VERSION': ['3.0.1'], 'COMPRESSION': [] }) return options_buf.getvalue() def make_error_body(self, code, msg): buf = BytesIO() write_int(buf, code) write_string(buf, msg) return buf.getvalue() def make_msg(self, header, body=""): return header + uint32_pack(len(body)) + body def test_connection_endpoint(self): endpoint = DefaultEndPoint('1.2.3.4') c = Connection(endpoint) self.assertEqual(c.endpoint, endpoint) self.assertEqual(c.endpoint.address, endpoint.address) c = Connection(host=endpoint) # kwarg self.assertEqual(c.endpoint, endpoint) self.assertEqual(c.endpoint.address, endpoint.address) c = Connection('10.0.0.1') endpoint = DefaultEndPoint('10.0.0.1') self.assertEqual(c.endpoint, endpoint) self.assertEqual(c.endpoint.address, endpoint.address) def test_bad_protocol_version(self, *args): c = self.make_connection() c._requests = Mock() c.defunct = Mock() # read in a SupportedMessage response header = self.make_header_prefix(SupportedMessage, version=0x7f) options = self.make_options_body() message = self.make_msg(header, options) - c._iobuf = BytesIO() + c._iobuf._io_buffer = BytesIO() c._iobuf.write(message) c.process_io_buffer() # make sure it errored correctly c.defunct.assert_called_once_with(ANY) args, kwargs = c.defunct.call_args self.assertIsInstance(args[0], ProtocolError) def test_negative_body_length(self, *args): c = self.make_connection() c._requests = Mock() c.defunct = Mock() # read in a SupportedMessage response header = self.make_header_prefix(SupportedMessage) message = header + int32_pack(-13) - c._iobuf = BytesIO() + c._iobuf._io_buffer = BytesIO() c._iobuf.write(message) c.process_io_buffer() # make sure it errored correctly c.defunct.assert_called_once_with(ANY) args, kwargs = c.defunct.call_args self.assertIsInstance(args[0], ProtocolError) def test_unsupported_cql_version(self, *args): c = self.make_connection() c._requests = {0: (c._handle_options_response, ProtocolHandler.decode_message, [])} c.defunct = Mock() c.cql_version = "3.0.3" options_buf = BytesIO() write_stringmultimap(options_buf, { 'CQL_VERSION': ['7.8.9'], 'COMPRESSION': [] }) options = options_buf.getvalue() c.process_msg(_Frame(version=4, flags=0, stream=0, opcode=SupportedMessage.opcode, body_offset=9, end_pos=9 + len(options)), options) # make sure it errored correctly c.defunct.assert_called_once_with(ANY) args, kwargs = c.defunct.call_args self.assertIsInstance(args[0], ProtocolError) def test_prefer_lz4_compression(self, *args): c = self.make_connection() c._requests = {0: (c._handle_options_response, ProtocolHandler.decode_message, [])} c.defunct = Mock() c.cql_version = "3.0.3" locally_supported_compressions.pop('lz4', None) locally_supported_compressions.pop('snappy', None) locally_supported_compressions['lz4'] = ('lz4compress', 'lz4decompress') locally_supported_compressions['snappy'] = ('snappycompress', 'snappydecompress') # read in a SupportedMessage response options_buf = BytesIO() write_stringmultimap(options_buf, { 'CQL_VERSION': ['3.0.3'], 'COMPRESSION': ['snappy', 'lz4'] }) options = options_buf.getvalue() c.process_msg(_Frame(version=4, flags=0, stream=0, opcode=SupportedMessage.opcode, body_offset=9, end_pos=9 + len(options)), options) self.assertEqual(c.decompressor, locally_supported_compressions['lz4'][1]) def test_requested_compression_not_available(self, *args): c = self.make_connection() c._requests = {0: (c._handle_options_response, ProtocolHandler.decode_message, [])} c.defunct = Mock() # request lz4 compression c.compression = "lz4" locally_supported_compressions.pop('lz4', None) locally_supported_compressions.pop('snappy', None) locally_supported_compressions['lz4'] = ('lz4compress', 'lz4decompress') locally_supported_compressions['snappy'] = ('snappycompress', 'snappydecompress') # the server only supports snappy options_buf = BytesIO() write_stringmultimap(options_buf, { 'CQL_VERSION': ['3.0.3'], 'COMPRESSION': ['snappy'] }) options = options_buf.getvalue() c.process_msg(_Frame(version=4, flags=0, stream=0, opcode=SupportedMessage.opcode, body_offset=9, end_pos=9 + len(options)), options) # make sure it errored correctly c.defunct.assert_called_once_with(ANY) args, kwargs = c.defunct.call_args self.assertIsInstance(args[0], ProtocolError) def test_use_requested_compression(self, *args): c = self.make_connection() c._requests = {0: (c._handle_options_response, ProtocolHandler.decode_message, [])} c.defunct = Mock() # request snappy compression c.compression = "snappy" locally_supported_compressions.pop('lz4', None) locally_supported_compressions.pop('snappy', None) locally_supported_compressions['lz4'] = ('lz4compress', 'lz4decompress') locally_supported_compressions['snappy'] = ('snappycompress', 'snappydecompress') # the server only supports snappy options_buf = BytesIO() write_stringmultimap(options_buf, { 'CQL_VERSION': ['3.0.3'], 'COMPRESSION': ['snappy', 'lz4'] }) options = options_buf.getvalue() c.process_msg(_Frame(version=4, flags=0, stream=0, opcode=SupportedMessage.opcode, body_offset=9, end_pos=9 + len(options)), options) self.assertEqual(c.decompressor, locally_supported_compressions['snappy'][1]) def test_disable_compression(self, *args): c = self.make_connection() c._requests = {0: (c._handle_options_response, ProtocolHandler.decode_message)} c.defunct = Mock() # disable compression c.compression = False locally_supported_compressions.pop('lz4', None) locally_supported_compressions.pop('snappy', None) locally_supported_compressions['lz4'] = ('lz4compress', 'lz4decompress') locally_supported_compressions['snappy'] = ('snappycompress', 'snappydecompress') # read in a SupportedMessage response header = self.make_header_prefix(SupportedMessage) # the server only supports snappy options_buf = BytesIO() write_stringmultimap(options_buf, { 'CQL_VERSION': ['3.0.3'], 'COMPRESSION': ['snappy', 'lz4'] }) options = options_buf.getvalue() message = self.make_msg(header, options) c.process_msg(message, len(message) - 8) self.assertEqual(c.decompressor, None) def test_not_implemented(self): """ Ensure the following methods throw NIE's. If not, come back and test them. """ c = self.make_connection() self.assertRaises(NotImplementedError, c.close) def test_set_keyspace_blocking(self): c = self.make_connection() self.assertEqual(c.keyspace, None) c.set_keyspace_blocking(None) self.assertEqual(c.keyspace, None) c.keyspace = 'ks' c.set_keyspace_blocking('ks') self.assertEqual(c.keyspace, 'ks') def test_set_connection_class(self): cluster = Cluster(connection_class='test') self.assertEqual('test', cluster.connection_class) @patch('cassandra.connection.ConnectionHeartbeat._raise_if_stopped') class ConnectionHeartbeatTest(unittest.TestCase): @staticmethod def make_get_holders(len): holders = [] for _ in range(len): holder = Mock() holder.get_connections = Mock(return_value=[]) holders.append(holder) get_holders = Mock(return_value=holders) return get_holders def run_heartbeat(self, get_holders_fun, count=2, interval=0.05, timeout=0.05): ch = ConnectionHeartbeat(interval, get_holders_fun, timeout=timeout) - time.sleep(interval * count) + # wait until the thread is started + wait_until(lambda: get_holders_fun.call_count > 0, 0.01, 100) + time.sleep(interval * (count-1)) ch.stop() self.assertTrue(get_holders_fun.call_count) def test_empty_connections(self, *args): count = 3 get_holders = self.make_get_holders(1) self.run_heartbeat(get_holders, count) - self.assertGreaterEqual(get_holders.call_count, count - 1) # lower bound to account for thread spinup time + self.assertGreaterEqual(get_holders.call_count, count-1) self.assertLessEqual(get_holders.call_count, count) holder = get_holders.return_value[0] holder.get_connections.assert_has_calls([call()] * get_holders.call_count) def test_idle_non_idle(self, *args): request_id = 999 # connection.send_msg(OptionsMessage(), connection.get_request_id(), self._options_callback) def send_msg(msg, req_id, msg_callback): msg_callback(SupportedMessage([], {})) idle_connection = Mock(spec=Connection, host='localhost', max_request_id=127, lock=Lock(), in_flight=0, is_idle=True, is_defunct=False, is_closed=False, get_request_id=lambda: request_id, send_msg=Mock(side_effect=send_msg)) non_idle_connection = Mock(spec=Connection, in_flight=0, is_idle=False, is_defunct=False, is_closed=False) get_holders = self.make_get_holders(1) holder = get_holders.return_value[0] holder.get_connections.return_value.append(idle_connection) holder.get_connections.return_value.append(non_idle_connection) self.run_heartbeat(get_holders) holder.get_connections.assert_has_calls([call()] * get_holders.call_count) self.assertEqual(idle_connection.in_flight, 0) self.assertEqual(non_idle_connection.in_flight, 0) idle_connection.send_msg.assert_has_calls([call(ANY, request_id, ANY)] * get_holders.call_count) self.assertEqual(non_idle_connection.send_msg.call_count, 0) def test_closed_defunct(self, *args): get_holders = self.make_get_holders(1) closed_connection = Mock(spec=Connection, in_flight=0, is_idle=False, is_defunct=False, is_closed=True) defunct_connection = Mock(spec=Connection, in_flight=0, is_idle=False, is_defunct=True, is_closed=False) holder = get_holders.return_value[0] holder.get_connections.return_value.append(closed_connection) holder.get_connections.return_value.append(defunct_connection) self.run_heartbeat(get_holders) holder.get_connections.assert_has_calls([call()] * get_holders.call_count) self.assertEqual(closed_connection.in_flight, 0) self.assertEqual(defunct_connection.in_flight, 0) self.assertEqual(closed_connection.send_msg.call_count, 0) self.assertEqual(defunct_connection.send_msg.call_count, 0) def test_no_req_ids(self, *args): in_flight = 3 get_holders = self.make_get_holders(1) max_connection = Mock(spec=Connection, host='localhost', lock=Lock(), max_request_id=in_flight - 1, in_flight=in_flight, is_idle=True, is_defunct=False, is_closed=False) holder = get_holders.return_value[0] holder.get_connections.return_value.append(max_connection) self.run_heartbeat(get_holders) holder.get_connections.assert_has_calls([call()] * get_holders.call_count) self.assertEqual(max_connection.in_flight, in_flight) self.assertEqual(max_connection.send_msg.call_count, 0) self.assertEqual(max_connection.send_msg.call_count, 0) max_connection.defunct.assert_has_calls([call(ANY)] * get_holders.call_count) holder.return_connection.assert_has_calls( [call(max_connection)] * get_holders.call_count) def test_unexpected_response(self, *args): request_id = 999 get_holders = self.make_get_holders(1) def send_msg(msg, req_id, msg_callback): msg_callback(object()) connection = Mock(spec=Connection, host='localhost', max_request_id=127, lock=Lock(), in_flight=0, is_idle=True, is_defunct=False, is_closed=False, get_request_id=lambda: request_id, send_msg=Mock(side_effect=send_msg)) holder = get_holders.return_value[0] holder.get_connections.return_value.append(connection) self.run_heartbeat(get_holders) self.assertEqual(connection.in_flight, get_holders.call_count) connection.send_msg.assert_has_calls([call(ANY, request_id, ANY)] * get_holders.call_count) connection.defunct.assert_has_calls([call(ANY)] * get_holders.call_count) exc = connection.defunct.call_args_list[0][0][0] self.assertIsInstance(exc, ConnectionException) self.assertRegexpMatches(exc.args[0], r'^Received unexpected response to OptionsMessage.*') holder.return_connection.assert_has_calls( [call(connection)] * get_holders.call_count) def test_timeout(self, *args): request_id = 999 get_holders = self.make_get_holders(1) def send_msg(msg, req_id, msg_callback): pass # we used endpoint=X here because it's a mock and we need connection.endpoint to be set connection = Mock(spec=Connection, endpoint=DefaultEndPoint('localhost'), max_request_id=127, lock=Lock(), in_flight=0, is_idle=True, is_defunct=False, is_closed=False, get_request_id=lambda: request_id, send_msg=Mock(side_effect=send_msg)) holder = get_holders.return_value[0] holder.get_connections.return_value.append(connection) self.run_heartbeat(get_holders) self.assertEqual(connection.in_flight, get_holders.call_count) connection.send_msg.assert_has_calls([call(ANY, request_id, ANY)] * get_holders.call_count) connection.defunct.assert_has_calls([call(ANY)] * get_holders.call_count) exc = connection.defunct.call_args_list[0][0][0] self.assertIsInstance(exc, OperationTimedOut) self.assertEqual(exc.errors, 'Connection heartbeat timeout after 0.05 seconds') self.assertEqual(exc.last_host, DefaultEndPoint('localhost')) holder.return_connection.assert_has_calls( [call(connection)] * get_holders.call_count) class TimerTest(unittest.TestCase): def test_timer_collision(self): # simple test demonstrating #466 # same timeout, comparison will defer to the Timer object itself t1 = Timer(0, lambda: None) t2 = Timer(0, lambda: None) t2.end = t1.end tm = TimerManager() tm.add_timer(t1) tm.add_timer(t2) # Prior to #466: "TypeError: unorderable types: Timer() < Timer()" tm.service_timeouts() class DefaultEndPointTest(unittest.TestCase): def test_default_endpoint_properties(self): endpoint = DefaultEndPoint('10.0.0.1') self.assertEqual(endpoint.address, '10.0.0.1') self.assertEqual(endpoint.port, 9042) self.assertEqual(str(endpoint), '10.0.0.1:9042') endpoint = DefaultEndPoint('10.0.0.1', 8888) self.assertEqual(endpoint.address, '10.0.0.1') self.assertEqual(endpoint.port, 8888) self.assertEqual(str(endpoint), '10.0.0.1:8888') def test_endpoint_equality(self): self.assertEqual( DefaultEndPoint('10.0.0.1'), DefaultEndPoint('10.0.0.1') ) self.assertEqual( DefaultEndPoint('10.0.0.1'), DefaultEndPoint('10.0.0.1', 9042) ) self.assertNotEqual( DefaultEndPoint('10.0.0.1'), DefaultEndPoint('10.0.0.2') ) self.assertNotEqual( DefaultEndPoint('10.0.0.1'), DefaultEndPoint('10.0.0.1', 0000) ) def test_endpoint_resolve(self): self.assertEqual( DefaultEndPoint('10.0.0.1').resolve(), ('10.0.0.1', 9042) ) self.assertEqual( DefaultEndPoint('10.0.0.1', 3232).resolve(), ('10.0.0.1', 3232) ) diff --git a/tests/unit/test_control_connection.py b/tests/unit/test_control_connection.py index e76fbd2..efad1ca 100644 --- a/tests/unit/test_control_connection.py +++ b/tests/unit/test_control_connection.py @@ -1,519 +1,592 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa import six from concurrent.futures import ThreadPoolExecutor from mock import Mock, ANY, call from cassandra import OperationTimedOut, SchemaTargetType, SchemaChangeType from cassandra.protocol import ResultMessage, RESULT_KIND_ROWS from cassandra.cluster import ControlConnection, _Scheduler, ProfileManager, EXEC_PROFILE_DEFAULT, ExecutionProfile from cassandra.pool import Host from cassandra.connection import EndPoint, DefaultEndPoint, DefaultEndPointFactory from cassandra.policies import (SimpleConvictionPolicy, RoundRobinPolicy, ConstantReconnectionPolicy, IdentityTranslator) PEER_IP = "foobar" class MockMetadata(object): def __init__(self): self.hosts = { DefaultEndPoint("192.168.1.0"): Host(DefaultEndPoint("192.168.1.0"), SimpleConvictionPolicy), DefaultEndPoint("192.168.1.1"): Host(DefaultEndPoint("192.168.1.1"), SimpleConvictionPolicy), DefaultEndPoint("192.168.1.2"): Host(DefaultEndPoint("192.168.1.2"), SimpleConvictionPolicy) } for host in self.hosts.values(): host.set_up() + host.release_version = "3.11" self.cluster_name = None self.partitioner = None self.token_map = {} - def get_host(self, endpoint_or_address): + def get_host(self, endpoint_or_address, port=None): if not isinstance(endpoint_or_address, EndPoint): for host in six.itervalues(self.hosts): - if host.address == endpoint_or_address: + if (host.address == endpoint_or_address and + (port is None or host.broadcast_rpc_port is None or host.broadcast_rpc_port == port)): return host else: return self.hosts.get(endpoint_or_address) def all_hosts(self): return self.hosts.values() def rebuild_token_map(self, partitioner, token_map): self.partitioner = partitioner self.token_map = token_map class MockCluster(object): max_schema_agreement_wait = 5 profile_manager = ProfileManager() reconnection_policy = ConstantReconnectionPolicy(2) address_translator = IdentityTranslator() down_host = None contact_points = [] is_shutdown = False def __init__(self): self.metadata = MockMetadata() self.added_hosts = [] self.removed_hosts = [] self.scheduler = Mock(spec=_Scheduler) self.executor = Mock(spec=ThreadPoolExecutor) self.profile_manager.profiles[EXEC_PROFILE_DEFAULT] = ExecutionProfile(RoundRobinPolicy()) self.endpoint_factory = DefaultEndPointFactory().configure(self) def add_host(self, endpoint, datacenter, rack, signal=False, refresh_nodes=True): host = Host(endpoint, SimpleConvictionPolicy, datacenter, rack) self.added_hosts.append(host) - return host + return host, True def remove_host(self, host): self.removed_hosts.append(host) def on_up(self, host): pass def on_down(self, host, is_host_addition): self.down_host = host +def _node_meta_results(local_results, peer_results): + """ + creates a pair of ResultMessages from (col_names, parsed_rows) + """ + local_response = ResultMessage(kind=RESULT_KIND_ROWS) + local_response.column_names = local_results[0] + local_response.parsed_rows = local_results[1] + + peer_response = ResultMessage(kind=RESULT_KIND_ROWS) + peer_response.column_names = peer_results[0] + peer_response.parsed_rows = peer_results[1] + + return peer_response, local_response + + class MockConnection(object): is_defunct = False def __init__(self): self.endpoint = DefaultEndPoint("192.168.1.0") self.local_results = [ ["schema_version", "cluster_name", "data_center", "rack", "partitioner", "release_version", "tokens"], [["a", "foocluster", "dc1", "rack1", "Murmur3Partitioner", "2.2.0", ["0", "100", "200"]]] ] self.peer_results = [ - ["rpc_address", "peer", "schema_version", "data_center", "rack", "tokens"], - [["192.168.1.1", "10.0.0.1", "a", "dc1", "rack1", ["1", "101", "201"]], - ["192.168.1.2", "10.0.0.2", "a", "dc1", "rack1", ["2", "102", "202"]]] + ["rpc_address", "peer", "schema_version", "data_center", "rack", "tokens", "host_id"], + [["192.168.1.1", "10.0.0.1", "a", "dc1", "rack1", ["1", "101", "201"], "uuid1"], + ["192.168.1.2", "10.0.0.2", "a", "dc1", "rack1", ["2", "102", "202"], "uuid2"]] ] - local_response = ResultMessage( - kind=RESULT_KIND_ROWS, results=self.local_results) - peer_response = ResultMessage( - kind=RESULT_KIND_ROWS, results=self.peer_results) - self.wait_for_responses = Mock(return_value=(peer_response, local_response)) + self.peer_results_v2 = [ + ["native_address", "native_port", "peer", "peer_port", "schema_version", "data_center", "rack", "tokens", "host_id"], + [["192.168.1.1", 9042, "10.0.0.1", 7042, "a", "dc1", "rack1", ["1", "101", "201"], "uuid1"], + ["192.168.1.2", 9042, "10.0.0.2", 7040, "a", "dc1", "rack1", ["2", "102", "202"], "uuid2"]] + ] + self.wait_for_responses = Mock(return_value=_node_meta_results(self.local_results, self.peer_results)) class FakeTime(object): def __init__(self): self.clock = 0 def time(self): return self.clock def sleep(self, amount): self.clock += amount class ControlConnectionTest(unittest.TestCase): + _matching_schema_preloaded_results = _node_meta_results( + local_results=(["schema_version", "cluster_name", "data_center", "rack", "partitioner", "release_version", "tokens", "host_id"], + [["a", "foocluster", "dc1", "rack1", "Murmur3Partitioner", "2.2.0", ["0", "100", "200"], "uuid1"]]), + peer_results=(["rpc_address", "peer", "schema_version", "data_center", "rack", "tokens", "host_id"], + [["192.168.1.1", "10.0.0.1", "a", "dc1", "rack1", ["1", "101", "201"], "uuid2"], + ["192.168.1.2", "10.0.0.2", "a", "dc1", "rack1", ["2", "102", "202"], "uuid3"]])) + + _nonmatching_schema_preloaded_results = _node_meta_results( + local_results=(["schema_version", "cluster_name", "data_center", "rack", "partitioner", "release_version", "tokens", "host_id"], + [["a", "foocluster", "dc1", "rack1", "Murmur3Partitioner", "2.2.0", ["0", "100", "200"], "uuid1"]]), + peer_results=(["rpc_address", "peer", "schema_version", "data_center", "rack", "tokens", "host_id"], + [["192.168.1.1", "10.0.0.1", "a", "dc1", "rack1", ["1", "101", "201"], "uuid2"], + ["192.168.1.2", "10.0.0.2", "b", "dc1", "rack1", ["2", "102", "202"], "uuid3"]])) + def setUp(self): self.cluster = MockCluster() self.connection = MockConnection() self.time = FakeTime() self.control_connection = ControlConnection(self.cluster, 1, 0, 0, 0) self.control_connection._connection = self.connection self.control_connection._time = self.time - def _get_matching_schema_preloaded_results(self): - local_results = [ - ["schema_version", "cluster_name", "data_center", "rack", "partitioner", "release_version", "tokens"], - [["a", "foocluster", "dc1", "rack1", "Murmur3Partitioner", "2.2.0", ["0", "100", "200"]]] - ] - local_response = ResultMessage(kind=RESULT_KIND_ROWS, results=local_results) - - peer_results = [ - ["rpc_address", "peer", "schema_version", "data_center", "rack", "tokens"], - [["192.168.1.1", "10.0.0.1", "a", "dc1", "rack1", ["1", "101", "201"]], - ["192.168.1.2", "10.0.0.2", "a", "dc1", "rack1", ["2", "102", "202"]]] - ] - peer_response = ResultMessage(kind=RESULT_KIND_ROWS, results=peer_results) - - return (peer_response, local_response) - - def _get_nonmatching_schema_preloaded_results(self): - local_results = [ - ["schema_version", "cluster_name", "data_center", "rack", "partitioner", "release_version", "tokens"], - [["a", "foocluster", "dc1", "rack1", "Murmur3Partitioner", "2.2.0", ["0", "100", "200"]]] - ] - local_response = ResultMessage(kind=RESULT_KIND_ROWS, results=local_results) - - peer_results = [ - ["rpc_address", "peer", "schema_version", "data_center", "rack", "tokens"], - [["192.168.1.1", "10.0.0.1", "a", "dc1", "rack1", ["1", "101", "201"]], - ["192.168.1.2", "10.0.0.2", "b", "dc1", "rack1", ["2", "102", "202"]]] - ] - peer_response = ResultMessage(kind=RESULT_KIND_ROWS, results=peer_results) - - return (peer_response, local_response) - def test_wait_for_schema_agreement(self): """ Basic test with all schema versions agreeing """ self.assertTrue(self.control_connection.wait_for_schema_agreement()) # the control connection should not have slept at all self.assertEqual(self.time.clock, 0) def test_wait_for_schema_agreement_uses_preloaded_results_if_given(self): """ wait_for_schema_agreement uses preloaded results if given for shared table queries """ - preloaded_results = self._get_matching_schema_preloaded_results() - + preloaded_results = self._matching_schema_preloaded_results self.assertTrue(self.control_connection.wait_for_schema_agreement(preloaded_results=preloaded_results)) # the control connection should not have slept at all self.assertEqual(self.time.clock, 0) # the connection should not have made any queries if given preloaded results self.assertEqual(self.connection.wait_for_responses.call_count, 0) def test_wait_for_schema_agreement_falls_back_to_querying_if_schemas_dont_match_preloaded_result(self): """ wait_for_schema_agreement requery if schema does not match using preloaded results """ - preloaded_results = self._get_nonmatching_schema_preloaded_results() - + preloaded_results = self._nonmatching_schema_preloaded_results self.assertTrue(self.control_connection.wait_for_schema_agreement(preloaded_results=preloaded_results)) # the control connection should not have slept at all self.assertEqual(self.time.clock, 0) self.assertEqual(self.connection.wait_for_responses.call_count, 1) def test_wait_for_schema_agreement_fails(self): """ Make sure the control connection sleeps and retries """ # change the schema version on one node self.connection.peer_results[1][1][2] = 'b' self.assertFalse(self.control_connection.wait_for_schema_agreement()) # the control connection should have slept until it hit the limit self.assertGreaterEqual(self.time.clock, self.cluster.max_schema_agreement_wait) def test_wait_for_schema_agreement_skipping(self): """ If rpc_address or schema_version isn't set, the host should be skipped """ # an entry with no schema_version self.connection.peer_results[1].append( ["192.168.1.3", "10.0.0.3", None, "dc1", "rack1", ["3", "103", "203"]] ) # an entry with a different schema_version and no rpc_address self.connection.peer_results[1].append( [None, None, "b", "dc1", "rack1", ["4", "104", "204"]] ) # change the schema version on one of the existing entries self.connection.peer_results[1][1][3] = 'c' self.cluster.metadata.get_host(DefaultEndPoint('192.168.1.1')).is_up = False self.assertTrue(self.control_connection.wait_for_schema_agreement()) self.assertEqual(self.time.clock, 0) def test_wait_for_schema_agreement_rpc_lookup(self): """ If the rpc_address is 0.0.0.0, the "peer" column should be used instead. """ self.connection.peer_results[1].append( ["0.0.0.0", PEER_IP, "b", "dc1", "rack1", ["3", "103", "203"]] ) host = Host(DefaultEndPoint("0.0.0.0"), SimpleConvictionPolicy) self.cluster.metadata.hosts[DefaultEndPoint("foobar")] = host host.is_up = False # even though the new host has a different schema version, it's # marked as down, so the control connection shouldn't care self.assertTrue(self.control_connection.wait_for_schema_agreement()) self.assertEqual(self.time.clock, 0) # but once we mark it up, the control connection will care host.is_up = True self.assertFalse(self.control_connection.wait_for_schema_agreement()) self.assertGreaterEqual(self.time.clock, self.cluster.max_schema_agreement_wait) def test_refresh_nodes_and_tokens(self): self.control_connection.refresh_node_list_and_token_map() meta = self.cluster.metadata self.assertEqual(meta.partitioner, 'Murmur3Partitioner') self.assertEqual(meta.cluster_name, 'foocluster') # check token map self.assertEqual(sorted(meta.all_hosts()), sorted(meta.token_map.keys())) for token_list in meta.token_map.values(): self.assertEqual(3, len(token_list)) # check datacenter/rack for host in meta.all_hosts(): self.assertEqual(host.datacenter, "dc1") self.assertEqual(host.rack, "rack1") self.assertEqual(self.connection.wait_for_responses.call_count, 1) + def test_refresh_nodes_and_tokens_with_invalid_peers(self): + def refresh_and_validate_added_hosts(): + self.connection.wait_for_responses = Mock(return_value=_node_meta_results( + self.connection.local_results, self.connection.peer_results)) + self.control_connection.refresh_node_list_and_token_map() + self.assertEqual(1, len(self.cluster.added_hosts)) # only one valid peer found + + # peersV1 + del self.connection.peer_results[:] + self.connection.peer_results.extend([ + ["rpc_address", "peer", "schema_version", "data_center", "rack", "tokens", "host_id"], + [["192.168.1.3", "10.0.0.1", "a", "dc1", "rack1", ["1", "101", "201"], 'uuid5'], + # all others are invalid + [None, None, "a", "dc1", "rack1", ["1", "101", "201"], 'uuid1'], + ["192.168.1.7", "10.0.0.1", "a", None, "rack1", ["1", "101", "201"], 'uuid2'], + ["192.168.1.6", "10.0.0.1", "a", "dc1", None, ["1", "101", "201"], 'uuid3'], + ["192.168.1.5", "10.0.0.1", "a", "dc1", "rack1", None, 'uuid4'], + ["192.168.1.4", "10.0.0.1", "a", "dc1", "rack1", ["1", "101", "201"], None]]]) + refresh_and_validate_added_hosts() + + # peersV2 + del self.cluster.added_hosts[:] + del self.connection.peer_results[:] + self.connection.peer_results.extend([ + ["native_address", "native_port", "peer", "peer_port", "schema_version", "data_center", "rack", "tokens", "host_id"], + [["192.168.1.4", 9042, "10.0.0.1", 7042, "a", "dc1", "rack1", ["1", "101", "201"], "uuid1"], + # all others are invalid + [None, 9042, None, 7040, "a", "dc1", "rack1", ["2", "102", "202"], "uuid2"], + ["192.168.1.5", 9042, "10.0.0.2", 7040, "a", None, "rack1", ["2", "102", "202"], "uuid2"], + ["192.168.1.5", 9042, "10.0.0.2", 7040, "a", "dc1", None, ["2", "102", "202"], "uuid2"], + ["192.168.1.5", 9042, "10.0.0.2", 7040, "a", "dc1", "rack1", None, "uuid2"], + ["192.168.1.5", 9042, "10.0.0.2", 7040, "a", "dc1", "rack1", ["2", "102", "202"], None]]]) + refresh_and_validate_added_hosts() + def test_refresh_nodes_and_tokens_uses_preloaded_results_if_given(self): """ refresh_nodes_and_tokens uses preloaded results if given for shared table queries """ - preloaded_results = self._get_matching_schema_preloaded_results() - + preloaded_results = self._matching_schema_preloaded_results self.control_connection._refresh_node_list_and_token_map(self.connection, preloaded_results=preloaded_results) meta = self.cluster.metadata self.assertEqual(meta.partitioner, 'Murmur3Partitioner') self.assertEqual(meta.cluster_name, 'foocluster') # check token map self.assertEqual(sorted(meta.all_hosts()), sorted(meta.token_map.keys())) for token_list in meta.token_map.values(): self.assertEqual(3, len(token_list)) # check datacenter/rack for host in meta.all_hosts(): self.assertEqual(host.datacenter, "dc1") self.assertEqual(host.rack, "rack1") # the connection should not have made any queries if given preloaded results self.assertEqual(self.connection.wait_for_responses.call_count, 0) def test_refresh_nodes_and_tokens_no_partitioner(self): """ Test handling of an unknown partitioner. """ # set the partitioner column to None self.connection.local_results[1][0][4] = None self.control_connection.refresh_node_list_and_token_map() meta = self.cluster.metadata self.assertEqual(meta.partitioner, None) self.assertEqual(meta.token_map, {}) def test_refresh_nodes_and_tokens_add_host(self): self.connection.peer_results[1].append( - ["192.168.1.3", "10.0.0.3", "a", "dc1", "rack1", ["3", "103", "203"]] + ["192.168.1.3", "10.0.0.3", "a", "dc1", "rack1", ["3", "103", "203"], "uuid3"] ) self.cluster.scheduler.schedule = lambda delay, f, *args, **kwargs: f(*args, **kwargs) self.control_connection.refresh_node_list_and_token_map() self.assertEqual(1, len(self.cluster.added_hosts)) self.assertEqual(self.cluster.added_hosts[0].address, "192.168.1.3") self.assertEqual(self.cluster.added_hosts[0].datacenter, "dc1") self.assertEqual(self.cluster.added_hosts[0].rack, "rack1") + self.assertEqual(self.cluster.added_hosts[0].host_id, "uuid3") def test_refresh_nodes_and_tokens_remove_host(self): del self.connection.peer_results[1][1] self.control_connection.refresh_node_list_and_token_map() self.assertEqual(1, len(self.cluster.removed_hosts)) self.assertEqual(self.cluster.removed_hosts[0].address, "192.168.1.2") def test_refresh_nodes_and_tokens_timeout(self): def bad_wait_for_responses(*args, **kwargs): self.assertEqual(kwargs['timeout'], self.control_connection._timeout) raise OperationTimedOut() self.connection.wait_for_responses = bad_wait_for_responses self.control_connection.refresh_node_list_and_token_map() self.cluster.executor.submit.assert_called_with(self.control_connection._reconnect) def test_refresh_schema_timeout(self): def bad_wait_for_responses(*args, **kwargs): self.time.sleep(kwargs['timeout']) raise OperationTimedOut() self.connection.wait_for_responses = Mock(side_effect=bad_wait_for_responses) self.control_connection.refresh_schema() self.assertEqual(self.connection.wait_for_responses.call_count, self.cluster.max_schema_agreement_wait / self.control_connection._timeout) self.assertEqual(self.connection.wait_for_responses.call_args[1]['timeout'], self.control_connection._timeout) def test_handle_topology_change(self): event = { 'change_type': 'NEW_NODE', 'address': ('1.2.3.4', 9000) } self.cluster.scheduler.reset_mock() self.control_connection._handle_topology_change(event) + self.cluster.scheduler.schedule_unique.assert_called_once_with(ANY, self.control_connection._refresh_nodes_if_not_up, None) event = { 'change_type': 'REMOVED_NODE', 'address': ('1.2.3.4', 9000) } self.cluster.scheduler.reset_mock() self.control_connection._handle_topology_change(event) self.cluster.scheduler.schedule_unique.assert_called_once_with(ANY, self.cluster.remove_host, None) event = { 'change_type': 'MOVED_NODE', 'address': ('1.2.3.4', 9000) } self.cluster.scheduler.reset_mock() self.control_connection._handle_topology_change(event) self.cluster.scheduler.schedule_unique.assert_called_once_with(ANY, self.control_connection._refresh_nodes_if_not_up, None) def test_handle_status_change(self): event = { 'change_type': 'UP', 'address': ('1.2.3.4', 9000) } self.cluster.scheduler.reset_mock() self.control_connection._handle_status_change(event) self.cluster.scheduler.schedule_unique.assert_called_once_with(ANY, self.control_connection.refresh_node_list_and_token_map) # do the same with a known Host event = { 'change_type': 'UP', - 'address': ('192.168.1.0', 9000) + 'address': ('192.168.1.0', 9042) } self.cluster.scheduler.reset_mock() self.control_connection._handle_status_change(event) host = self.cluster.metadata.hosts[DefaultEndPoint('192.168.1.0')] self.cluster.scheduler.schedule_unique.assert_called_once_with(ANY, self.cluster.on_up, host) self.cluster.scheduler.schedule.reset_mock() event = { 'change_type': 'DOWN', 'address': ('1.2.3.4', 9000) } self.control_connection._handle_status_change(event) self.assertFalse(self.cluster.scheduler.schedule.called) # do the same with a known Host event = { 'change_type': 'DOWN', 'address': ('192.168.1.0', 9000) } self.control_connection._handle_status_change(event) host = self.cluster.metadata.hosts[DefaultEndPoint('192.168.1.0')] self.assertIs(host, self.cluster.down_host) def test_handle_schema_change(self): change_types = [getattr(SchemaChangeType, attr) for attr in vars(SchemaChangeType) if attr[0] != '_'] for change_type in change_types: event = { 'target_type': SchemaTargetType.TABLE, 'change_type': change_type, 'keyspace': 'ks1', 'table': 'table1' } self.cluster.scheduler.reset_mock() self.control_connection._handle_schema_change(event) self.cluster.scheduler.schedule_unique.assert_called_once_with(ANY, self.control_connection.refresh_schema, **event) self.cluster.scheduler.reset_mock() event['target_type'] = SchemaTargetType.KEYSPACE del event['table'] self.control_connection._handle_schema_change(event) self.cluster.scheduler.schedule_unique.assert_called_once_with(ANY, self.control_connection.refresh_schema, **event) def test_refresh_disabled(self): cluster = MockCluster() schema_event = { 'target_type': SchemaTargetType.TABLE, 'change_type': SchemaChangeType.CREATED, 'keyspace': 'ks1', 'table': 'table1' } status_event = { 'change_type': 'UP', 'address': ('1.2.3.4', 9000) } topo_event = { 'change_type': 'MOVED_NODE', 'address': ('1.2.3.4', 9000) } cc_no_schema_refresh = ControlConnection(cluster, 1, -1, 0, 0) cluster.scheduler.reset_mock() # no call on schema refresh cc_no_schema_refresh._handle_schema_change(schema_event) self.assertFalse(cluster.scheduler.schedule.called) self.assertFalse(cluster.scheduler.schedule_unique.called) # topo and status changes as normal cc_no_schema_refresh._handle_status_change(status_event) cc_no_schema_refresh._handle_topology_change(topo_event) cluster.scheduler.schedule_unique.assert_has_calls([call(ANY, cc_no_schema_refresh.refresh_node_list_and_token_map), call(ANY, cc_no_schema_refresh._refresh_nodes_if_not_up, None)]) cc_no_topo_refresh = ControlConnection(cluster, 1, 0, -1, 0) cluster.scheduler.reset_mock() # no call on topo refresh cc_no_topo_refresh._handle_topology_change(topo_event) self.assertFalse(cluster.scheduler.schedule.called) self.assertFalse(cluster.scheduler.schedule_unique.called) # schema and status change refresh as normal cc_no_topo_refresh._handle_status_change(status_event) cc_no_topo_refresh._handle_schema_change(schema_event) cluster.scheduler.schedule_unique.assert_has_calls([call(ANY, cc_no_topo_refresh.refresh_node_list_and_token_map), call(0.0, cc_no_topo_refresh.refresh_schema, **schema_event)]) + def test_refresh_nodes_and_tokens_add_host_detects_port(self): + del self.connection.peer_results[:] + self.connection.peer_results.extend(self.connection.peer_results_v2) + self.connection.peer_results[1].append( + ["192.168.1.3", 555, "10.0.0.3", 666, "a", "dc1", "rack1", ["3", "103", "203"], "uuid3"] + ) + self.connection.wait_for_responses = Mock(return_value=_node_meta_results( + self.connection.local_results, self.connection.peer_results)) + self.cluster.scheduler.schedule = lambda delay, f, *args, **kwargs: f(*args, **kwargs) + self.control_connection.refresh_node_list_and_token_map() + self.assertEqual(1, len(self.cluster.added_hosts)) + self.assertEqual(self.cluster.added_hosts[0].endpoint.address, "192.168.1.3") + self.assertEqual(self.cluster.added_hosts[0].endpoint.port, 555) + self.assertEqual(self.cluster.added_hosts[0].broadcast_rpc_address, "192.168.1.3") + self.assertEqual(self.cluster.added_hosts[0].broadcast_rpc_port, 555) + self.assertEqual(self.cluster.added_hosts[0].broadcast_address, "10.0.0.3") + self.assertEquals(self.cluster.added_hosts[0].broadcast_port, 666) + self.assertEqual(self.cluster.added_hosts[0].datacenter, "dc1") + self.assertEqual(self.cluster.added_hosts[0].rack, "rack1") + + def test_refresh_nodes_and_tokens_add_host_detects_invalid_port(self): + del self.connection.peer_results[:] + self.connection.peer_results.extend(self.connection.peer_results_v2) + self.connection.peer_results[1].append( + ["192.168.1.3", -1, "10.0.0.3", 0, "a", "dc1", "rack1", ["3", "103", "203"], "uuid3"] + ) + self.connection.wait_for_responses = Mock(return_value=_node_meta_results( + self.connection.local_results, self.connection.peer_results)) + self.cluster.scheduler.schedule = lambda delay, f, *args, **kwargs: f(*args, **kwargs) + self.control_connection.refresh_node_list_and_token_map() + self.assertEqual(1, len(self.cluster.added_hosts)) + self.assertEqual(self.cluster.added_hosts[0].endpoint.address, "192.168.1.3") + self.assertEqual(self.cluster.added_hosts[0].endpoint.port, 9042) # fallback default + self.assertEqual(self.cluster.added_hosts[0].broadcast_rpc_address, "192.168.1.3") + self.assertEqual(self.cluster.added_hosts[0].broadcast_rpc_port, None) + self.assertEqual(self.cluster.added_hosts[0].broadcast_address, "10.0.0.3") + self.assertEquals(self.cluster.added_hosts[0].broadcast_port, None) + self.assertEqual(self.cluster.added_hosts[0].datacenter, "dc1") + self.assertEqual(self.cluster.added_hosts[0].rack, "rack1") + class EventTimingTest(unittest.TestCase): """ A simple test to validate that event scheduling happens in order Added for PYTHON-358 """ def setUp(self): self.cluster = MockCluster() self.connection = MockConnection() self.time = FakeTime() # Use 2 for the schema_event_refresh_window which is what we would normally default to. self.control_connection = ControlConnection(self.cluster, 1, 2, 0, 0) self.control_connection._connection = self.connection self.control_connection._time = self.time def test_event_delay_timing(self): """ Submits a wide array of events make sure that each is scheduled to occur in the order they were received """ prior_delay = 0 for _ in range(100): for change_type in ('CREATED', 'DROPPED', 'UPDATED'): event = { 'change_type': change_type, 'keyspace': '1', 'table': 'table1' } # This is to increment the fake time, we don't actually sleep here. self.time.sleep(.001) self.cluster.scheduler.reset_mock() self.control_connection._handle_schema_change(event) self.cluster.scheduler.mock_calls # Grabs the delay parameter from the scheduler invocation current_delay = self.cluster.scheduler.mock_calls[0][1][0] self.assertLess(prior_delay, current_delay) prior_delay = current_delay diff --git a/tests/unit/test_host_connection_pool.py b/tests/unit/test_host_connection_pool.py index 78af476..e62488b 100644 --- a/tests/unit/test_host_connection_pool.py +++ b/tests/unit/test_host_connection_pool.py @@ -1,243 +1,261 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from mock import Mock, NonCallableMagicMock from threading import Thread, Event, Lock from cassandra.cluster import Session from cassandra.connection import Connection -from cassandra.pool import Host, HostConnectionPool, NoConnectionsAvailable +from cassandra.pool import HostConnection, HostConnectionPool +from cassandra.pool import Host, NoConnectionsAvailable from cassandra.policies import HostDistance, SimpleConvictionPolicy -class HostConnectionPoolTests(unittest.TestCase): +class _PoolTests(unittest.TestCase): + PoolImpl = None + uses_single_connection = None def make_session(self): session = NonCallableMagicMock(spec=Session, keyspace='foobarkeyspace') session.cluster.get_core_connections_per_host.return_value = 1 session.cluster.get_max_requests_per_connection.return_value = 1 session.cluster.get_max_connections_per_host.return_value = 1 return session def test_borrow_and_return(self): host = Mock(spec=Host, address='ip1') session = self.make_session() conn = NonCallableMagicMock(spec=Connection, in_flight=0, is_defunct=False, is_closed=False, max_request_id=100) session.cluster.connection_factory.return_value = conn - pool = HostConnectionPool(host, HostDistance.LOCAL, session) + pool = self.PoolImpl(host, HostDistance.LOCAL, session) session.cluster.connection_factory.assert_called_once_with(host.endpoint) c, request_id = pool.borrow_connection(timeout=0.01) self.assertIs(c, conn) self.assertEqual(1, conn.in_flight) conn.set_keyspace_blocking.assert_called_once_with('foobarkeyspace') pool.return_connection(conn) self.assertEqual(0, conn.in_flight) - self.assertNotIn(conn, pool._trash) + if not self.uses_single_connection: + self.assertNotIn(conn, pool._trash) def test_failed_wait_for_connection(self): host = Mock(spec=Host, address='ip1') session = self.make_session() conn = NonCallableMagicMock(spec=Connection, in_flight=0, is_defunct=False, is_closed=False, max_request_id=100) session.cluster.connection_factory.return_value = conn - pool = HostConnectionPool(host, HostDistance.LOCAL, session) + pool = self.PoolImpl(host, HostDistance.LOCAL, session) session.cluster.connection_factory.assert_called_once_with(host.endpoint) pool.borrow_connection(timeout=0.01) self.assertEqual(1, conn.in_flight) conn.in_flight = conn.max_request_id # we're already at the max number of requests for this connection, # so we this should fail self.assertRaises(NoConnectionsAvailable, pool.borrow_connection, 0) def test_successful_wait_for_connection(self): host = Mock(spec=Host, address='ip1') session = self.make_session() conn = NonCallableMagicMock(spec=Connection, in_flight=0, is_defunct=False, is_closed=False, max_request_id=100, lock=Lock()) session.cluster.connection_factory.return_value = conn - pool = HostConnectionPool(host, HostDistance.LOCAL, session) + pool = self.PoolImpl(host, HostDistance.LOCAL, session) session.cluster.connection_factory.assert_called_once_with(host.endpoint) pool.borrow_connection(timeout=0.01) self.assertEqual(1, conn.in_flight) def get_second_conn(): c, request_id = pool.borrow_connection(1.0) self.assertIs(conn, c) pool.return_connection(c) t = Thread(target=get_second_conn) t.start() pool.return_connection(conn) t.join() self.assertEqual(0, conn.in_flight) - def test_all_connections_trashed(self): - host = Mock(spec=Host, address='ip1') - session = self.make_session() - conn = NonCallableMagicMock(spec=Connection, in_flight=0, is_defunct=False, is_closed=False, max_request_id=100, lock=Lock()) - session.cluster.connection_factory.return_value = conn - session.cluster.get_core_connections_per_host.return_value = 1 - - # manipulate the core connection setting so that we can - # trash the only connection - pool = HostConnectionPool(host, HostDistance.LOCAL, session) - session.cluster.get_core_connections_per_host.return_value = 0 - pool._maybe_trash_connection(conn) - session.cluster.get_core_connections_per_host.return_value = 1 - - submit_called = Event() - - def fire_event(*args, **kwargs): - submit_called.set() - - session.submit.side_effect = fire_event - - def get_conn(): - conn.reset_mock() - c, request_id = pool.borrow_connection(1.0) - self.assertIs(conn, c) - self.assertEqual(1, conn.in_flight) - conn.set_keyspace_blocking.assert_called_once_with('foobarkeyspace') - pool.return_connection(c) - - t = Thread(target=get_conn) - t.start() - - submit_called.wait() - self.assertEqual(1, pool._scheduled_for_creation) - session.submit.assert_called_once_with(pool._create_new_connection) - - # now run the create_new_connection call - pool._create_new_connection() - - t.join() - self.assertEqual(0, conn.in_flight) - def test_spawn_when_at_max(self): host = Mock(spec=Host, address='ip1') session = self.make_session() conn = NonCallableMagicMock(spec=Connection, in_flight=0, is_defunct=False, is_closed=False, max_request_id=100) conn.max_request_id = 100 session.cluster.connection_factory.return_value = conn # core conns = 1, max conns = 2 session.cluster.get_max_connections_per_host.return_value = 2 - pool = HostConnectionPool(host, HostDistance.LOCAL, session) + pool = self.PoolImpl(host, HostDistance.LOCAL, session) session.cluster.connection_factory.assert_called_once_with(host.endpoint) pool.borrow_connection(timeout=0.01) self.assertEqual(1, conn.in_flight) # make this conn full conn.in_flight = conn.max_request_id # we don't care about making this borrow_connection call succeed for the # purposes of this test, as long as it results in a new connection # creation being scheduled self.assertRaises(NoConnectionsAvailable, pool.borrow_connection, 0) - session.submit.assert_called_once_with(pool._create_new_connection) + if not self.uses_single_connection: + session.submit.assert_called_once_with(pool._create_new_connection) def test_return_defunct_connection(self): host = Mock(spec=Host, address='ip1') session = self.make_session() conn = NonCallableMagicMock(spec=Connection, in_flight=0, is_defunct=False, is_closed=False, max_request_id=100, signaled_error=False) session.cluster.connection_factory.return_value = conn - pool = HostConnectionPool(host, HostDistance.LOCAL, session) + pool = self.PoolImpl(host, HostDistance.LOCAL, session) session.cluster.connection_factory.assert_called_once_with(host.endpoint) pool.borrow_connection(timeout=0.01) conn.is_defunct = True session.cluster.signal_connection_failure.return_value = False pool.return_connection(conn) # the connection should be closed a new creation scheduled self.assertTrue(session.submit.call_args) self.assertFalse(pool.is_shutdown) def test_return_defunct_connection_on_down_host(self): host = Mock(spec=Host, address='ip1') session = self.make_session() conn = NonCallableMagicMock(spec=Connection, in_flight=0, is_defunct=False, is_closed=False, max_request_id=100, signaled_error=False) session.cluster.connection_factory.return_value = conn - pool = HostConnectionPool(host, HostDistance.LOCAL, session) + pool = self.PoolImpl(host, HostDistance.LOCAL, session) session.cluster.connection_factory.assert_called_once_with(host.endpoint) pool.borrow_connection(timeout=0.01) conn.is_defunct = True session.cluster.signal_connection_failure.return_value = True pool.return_connection(conn) # the connection should be closed a new creation scheduled self.assertTrue(session.cluster.signal_connection_failure.call_args) self.assertTrue(conn.close.call_args) self.assertFalse(session.submit.called) self.assertTrue(pool.is_shutdown) def test_return_closed_connection(self): host = Mock(spec=Host, address='ip1') session = self.make_session() - conn = NonCallableMagicMock(spec=Connection, in_flight=0, is_defunct=False, is_closed=True, max_request_id=100, signaled_error=False) + conn = NonCallableMagicMock(spec=Connection, in_flight=0, is_defunct=False, is_closed=True, max_request_id=100, + signaled_error=False) session.cluster.connection_factory.return_value = conn - pool = HostConnectionPool(host, HostDistance.LOCAL, session) + pool = self.PoolImpl(host, HostDistance.LOCAL, session) session.cluster.connection_factory.assert_called_once_with(host.endpoint) pool.borrow_connection(timeout=0.01) conn.is_closed = True session.cluster.signal_connection_failure.return_value = False pool.return_connection(conn) # a new creation should be scheduled self.assertTrue(session.submit.call_args) self.assertFalse(pool.is_shutdown) def test_host_instantiations(self): """ Ensure Host fails if not initialized properly """ self.assertRaises(ValueError, Host, None, None) self.assertRaises(ValueError, Host, '127.0.0.1', None) self.assertRaises(ValueError, Host, None, SimpleConvictionPolicy) def test_host_equality(self): """ Test host equality has correct logic """ a = Host('127.0.0.1', SimpleConvictionPolicy) b = Host('127.0.0.1', SimpleConvictionPolicy) c = Host('127.0.0.2', SimpleConvictionPolicy) self.assertEqual(a, b, 'Two Host instances should be equal when sharing.') self.assertNotEqual(a, c, 'Two Host instances should NOT be equal when using two different addresses.') self.assertNotEqual(b, c, 'Two Host instances should NOT be equal when using two different addresses.') + + +class HostConnectionPoolTests(_PoolTests): + PoolImpl = HostConnectionPool + uses_single_connection = False + + def test_all_connections_trashed(self): + host = Mock(spec=Host, address='ip1') + session = self.make_session() + conn = NonCallableMagicMock(spec=Connection, in_flight=0, is_defunct=False, is_closed=False, max_request_id=100, + lock=Lock()) + session.cluster.connection_factory.return_value = conn + session.cluster.get_core_connections_per_host.return_value = 1 + + # manipulate the core connection setting so that we can + # trash the only connection + pool = self.PoolImpl(host, HostDistance.LOCAL, session) + session.cluster.get_core_connections_per_host.return_value = 0 + pool._maybe_trash_connection(conn) + session.cluster.get_core_connections_per_host.return_value = 1 + + submit_called = Event() + + def fire_event(*args, **kwargs): + submit_called.set() + + session.submit.side_effect = fire_event + + def get_conn(): + conn.reset_mock() + c, request_id = pool.borrow_connection(1.0) + self.assertIs(conn, c) + self.assertEqual(1, conn.in_flight) + conn.set_keyspace_blocking.assert_called_once_with('foobarkeyspace') + pool.return_connection(c) + + t = Thread(target=get_conn) + t.start() + + submit_called.wait() + self.assertEqual(1, pool._scheduled_for_creation) + session.submit.assert_called_once_with(pool._create_new_connection) + + # now run the create_new_connection call + pool._create_new_connection() + + t.join() + self.assertEqual(0, conn.in_flight) + + +class HostConnectionTests(_PoolTests): + PoolImpl = HostConnection + uses_single_connection = True + diff --git a/tests/unit/test_metadata.py b/tests/unit/test_metadata.py index 49b2627..b2143f8 100644 --- a/tests/unit/test_metadata.py +++ b/tests/unit/test_metadata.py @@ -1,622 +1,863 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from binascii import unhexlify import logging from mock import Mock import os import six import timeit import cassandra from cassandra.cqltypes import strip_frozen from cassandra.marshal import uint16_unpack, uint16_pack from cassandra.metadata import (Murmur3Token, MD5Token, BytesToken, ReplicationStrategy, NetworkTopologyStrategy, SimpleStrategy, LocalStrategy, protect_name, protect_names, protect_value, is_valid_name, UserType, KeyspaceMetadata, get_schema_parser, _UnknownStrategy, ColumnMetadata, TableMetadata, IndexMetadata, Function, Aggregate, - Metadata, TokenMap) + Metadata, TokenMap, ReplicationFactor) from cassandra.policies import SimpleConvictionPolicy from cassandra.pool import Host log = logging.getLogger(__name__) +class ReplicationFactorTest(unittest.TestCase): + + def test_replication_factor_parsing(self): + rf = ReplicationFactor.create('3') + self.assertEqual(rf.all_replicas, 3) + self.assertEqual(rf.full_replicas, 3) + self.assertEqual(rf.transient_replicas, None) + self.assertEqual(str(rf), '3') + + rf = ReplicationFactor.create('3/1') + self.assertEqual(rf.all_replicas, 3) + self.assertEqual(rf.full_replicas, 2) + self.assertEqual(rf.transient_replicas, 1) + self.assertEqual(str(rf), '3/1') + + self.assertRaises(ValueError, ReplicationFactor.create, '3/') + self.assertRaises(ValueError, ReplicationFactor.create, 'a/1') + self.assertRaises(ValueError, ReplicationFactor.create, 'a') + self.assertRaises(ValueError, ReplicationFactor.create, '3/a') + + def test_replication_factor_equality(self): + self.assertEqual(ReplicationFactor.create('3/1'), ReplicationFactor.create('3/1')) + self.assertEqual(ReplicationFactor.create('3'), ReplicationFactor.create('3')) + self.assertNotEqual(ReplicationFactor.create('3'), ReplicationFactor.create('3/1')) + self.assertNotEqual(ReplicationFactor.create('3'), ReplicationFactor.create('3/1')) + + + class StrategiesTest(unittest.TestCase): @classmethod def setUpClass(cls): "Hook method for setting up class fixture before running tests in the class." if not hasattr(cls, 'assertItemsEqual'): cls.assertItemsEqual = cls.assertCountEqual def test_replication_strategy(self): """ Basic code coverage testing that ensures different ReplicationStrategies can be initiated using parameters correctly. """ rs = ReplicationStrategy() self.assertEqual(rs.create('OldNetworkTopologyStrategy', None), _UnknownStrategy('OldNetworkTopologyStrategy', None)) fake_options_map = {'options': 'map'} uks = rs.create('OldNetworkTopologyStrategy', fake_options_map) self.assertEqual(uks, _UnknownStrategy('OldNetworkTopologyStrategy', fake_options_map)) self.assertEqual(uks.make_token_replica_map({}, []), {}) fake_options_map = {'dc1': '3'} self.assertIsInstance(rs.create('NetworkTopologyStrategy', fake_options_map), NetworkTopologyStrategy) self.assertEqual(rs.create('NetworkTopologyStrategy', fake_options_map).dc_replication_factors, NetworkTopologyStrategy(fake_options_map).dc_replication_factors) fake_options_map = {'options': 'map'} self.assertIsNone(rs.create('SimpleStrategy', fake_options_map)) fake_options_map = {'options': 'map'} self.assertIsInstance(rs.create('LocalStrategy', fake_options_map), LocalStrategy) fake_options_map = {'options': 'map', 'replication_factor': 3} self.assertIsInstance(rs.create('SimpleStrategy', fake_options_map), SimpleStrategy) self.assertEqual(rs.create('SimpleStrategy', fake_options_map).replication_factor, SimpleStrategy(fake_options_map).replication_factor) self.assertEqual(rs.create('xxxxxxxx', fake_options_map), _UnknownStrategy('xxxxxxxx', fake_options_map)) self.assertRaises(NotImplementedError, rs.make_token_replica_map, None, None) self.assertRaises(NotImplementedError, rs.export_for_schema) + def test_simple_replication_type_parsing(self): + """ Test equality between passing numeric and string replication factor for simple strategy """ + rs = ReplicationStrategy() + + simple_int = rs.create('SimpleStrategy', {'replication_factor': 3}) + simple_str = rs.create('SimpleStrategy', {'replication_factor': '3'}) + + self.assertEqual(simple_int.export_for_schema(), simple_str.export_for_schema()) + self.assertEqual(simple_int, simple_str) + + # make token replica map + ring = [MD5Token(0), MD5Token(1), MD5Token(2)] + hosts = [Host('dc1.{}'.format(host), SimpleConvictionPolicy) for host in range(3)] + token_to_host = dict(zip(ring, hosts)) + self.assertEqual( + simple_int.make_token_replica_map(token_to_host, ring), + simple_str.make_token_replica_map(token_to_host, ring) + ) + + def test_transient_replication_parsing(self): + """ Test that we can PARSE a transient replication factor for SimpleStrategy """ + rs = ReplicationStrategy() + + simple_transient = rs.create('SimpleStrategy', {'replication_factor': '3/1'}) + self.assertEqual(simple_transient.replication_factor_info, ReplicationFactor(3, 1)) + self.assertEqual(simple_transient.replication_factor, 2) + self.assertIn("'replication_factor': '3/1'", simple_transient.export_for_schema()) + + simple_str = rs.create('SimpleStrategy', {'replication_factor': '2'}) + self.assertNotEqual(simple_transient, simple_str) + + # make token replica map + ring = [MD5Token(0), MD5Token(1), MD5Token(2)] + hosts = [Host('dc1.{}'.format(host), SimpleConvictionPolicy) for host in range(3)] + token_to_host = dict(zip(ring, hosts)) + self.assertEqual( + simple_transient.make_token_replica_map(token_to_host, ring), + simple_str.make_token_replica_map(token_to_host, ring) + ) + + def test_nts_replication_parsing(self): + """ Test equality between passing numeric and string replication factor for NTS """ + rs = ReplicationStrategy() + + nts_int = rs.create('NetworkTopologyStrategy', {'dc1': 3, 'dc2': 5}) + nts_str = rs.create('NetworkTopologyStrategy', {'dc1': '3', 'dc2': '5'}) + + self.assertEqual(nts_int.dc_replication_factors['dc1'], 3) + self.assertEqual(nts_str.dc_replication_factors['dc1'], 3) + self.assertEqual(nts_int.dc_replication_factors_info['dc1'], ReplicationFactor(3)) + self.assertEqual(nts_str.dc_replication_factors_info['dc1'], ReplicationFactor(3)) + + self.assertEqual(nts_int.export_for_schema(), nts_str.export_for_schema()) + self.assertEqual(nts_int, nts_str) + + # make token replica map + ring = [MD5Token(0), MD5Token(1), MD5Token(2)] + hosts = [Host('dc1.{}'.format(host), SimpleConvictionPolicy) for host in range(3)] + token_to_host = dict(zip(ring, hosts)) + self.assertEqual( + nts_int.make_token_replica_map(token_to_host, ring), + nts_str.make_token_replica_map(token_to_host, ring) + ) + + def test_nts_transient_parsing(self): + """ Test that we can PARSE a transient replication factor for NTS """ + rs = ReplicationStrategy() + + nts_transient = rs.create('NetworkTopologyStrategy', {'dc1': '3/1', 'dc2': '5/1'}) + self.assertEqual(nts_transient.dc_replication_factors_info['dc1'], ReplicationFactor(3, 1)) + self.assertEqual(nts_transient.dc_replication_factors_info['dc2'], ReplicationFactor(5, 1)) + self.assertEqual(nts_transient.dc_replication_factors['dc1'], 2) + self.assertEqual(nts_transient.dc_replication_factors['dc2'], 4) + self.assertIn("'dc1': '3/1', 'dc2': '5/1'", nts_transient.export_for_schema()) + + nts_str = rs.create('NetworkTopologyStrategy', {'dc1': '3', 'dc2': '5'}) + self.assertNotEqual(nts_transient, nts_str) + + # make token replica map + ring = [MD5Token(0), MD5Token(1), MD5Token(2)] + hosts = [Host('dc1.{}'.format(host), SimpleConvictionPolicy) for host in range(3)] + token_to_host = dict(zip(ring, hosts)) + self.assertEqual( + nts_transient.make_token_replica_map(token_to_host, ring), + nts_str.make_token_replica_map(token_to_host, ring) + ) + def test_nts_make_token_replica_map(self): token_to_host_owner = {} dc1_1 = Host('dc1.1', SimpleConvictionPolicy) dc1_2 = Host('dc1.2', SimpleConvictionPolicy) dc1_3 = Host('dc1.3', SimpleConvictionPolicy) for host in (dc1_1, dc1_2, dc1_3): host.set_location_info('dc1', 'rack1') token_to_host_owner[MD5Token(0)] = dc1_1 token_to_host_owner[MD5Token(100)] = dc1_2 token_to_host_owner[MD5Token(200)] = dc1_3 dc2_1 = Host('dc2.1', SimpleConvictionPolicy) dc2_2 = Host('dc2.2', SimpleConvictionPolicy) dc2_1.set_location_info('dc2', 'rack1') dc2_2.set_location_info('dc2', 'rack1') token_to_host_owner[MD5Token(1)] = dc2_1 token_to_host_owner[MD5Token(101)] = dc2_2 dc3_1 = Host('dc3.1', SimpleConvictionPolicy) dc3_1.set_location_info('dc3', 'rack3') token_to_host_owner[MD5Token(2)] = dc3_1 ring = [MD5Token(0), MD5Token(1), MD5Token(2), MD5Token(100), MD5Token(101), MD5Token(200)] nts = NetworkTopologyStrategy({'dc1': 2, 'dc2': 2, 'dc3': 1}) replica_map = nts.make_token_replica_map(token_to_host_owner, ring) self.assertItemsEqual(replica_map[MD5Token(0)], (dc1_1, dc1_2, dc2_1, dc2_2, dc3_1)) def test_nts_token_performance(self): """ Tests to ensure that when rf exceeds the number of nodes available, that we dont' needlessly iterate trying to construct tokens for nodes that don't exist. @since 3.7 @jira_ticket PYTHON-379 @expected_result timing with 1500 rf should be same/similar to 3rf if we have 3 nodes @test_category metadata """ token_to_host_owner = {} ring = [] dc1hostnum = 3 current_token = 0 vnodes_per_host = 500 for i in range(dc1hostnum): host = Host('dc1.{0}'.format(i), SimpleConvictionPolicy) host.set_location_info('dc1', "rack1") for vnode_num in range(vnodes_per_host): md5_token = MD5Token(current_token+vnode_num) token_to_host_owner[md5_token] = host ring.append(md5_token) current_token += 1000 nts = NetworkTopologyStrategy({'dc1': 3}) start_time = timeit.default_timer() nts.make_token_replica_map(token_to_host_owner, ring) elapsed_base = timeit.default_timer() - start_time nts = NetworkTopologyStrategy({'dc1': 1500}) start_time = timeit.default_timer() nts.make_token_replica_map(token_to_host_owner, ring) elapsed_bad = timeit.default_timer() - start_time difference = elapsed_bad - elapsed_base self.assertTrue(difference < 1 and difference > -1) def test_nts_make_token_replica_map_multi_rack(self): token_to_host_owner = {} # (A) not enough distinct racks, first skipped is used dc1_1 = Host('dc1.1', SimpleConvictionPolicy) dc1_2 = Host('dc1.2', SimpleConvictionPolicy) dc1_3 = Host('dc1.3', SimpleConvictionPolicy) dc1_4 = Host('dc1.4', SimpleConvictionPolicy) dc1_1.set_location_info('dc1', 'rack1') dc1_2.set_location_info('dc1', 'rack1') dc1_3.set_location_info('dc1', 'rack2') dc1_4.set_location_info('dc1', 'rack2') token_to_host_owner[MD5Token(0)] = dc1_1 token_to_host_owner[MD5Token(100)] = dc1_2 token_to_host_owner[MD5Token(200)] = dc1_3 token_to_host_owner[MD5Token(300)] = dc1_4 # (B) distinct racks, but not contiguous dc2_1 = Host('dc2.1', SimpleConvictionPolicy) dc2_2 = Host('dc2.2', SimpleConvictionPolicy) dc2_3 = Host('dc2.3', SimpleConvictionPolicy) dc2_1.set_location_info('dc2', 'rack1') dc2_2.set_location_info('dc2', 'rack1') dc2_3.set_location_info('dc2', 'rack2') token_to_host_owner[MD5Token(1)] = dc2_1 token_to_host_owner[MD5Token(101)] = dc2_2 token_to_host_owner[MD5Token(201)] = dc2_3 ring = [MD5Token(0), MD5Token(1), MD5Token(100), MD5Token(101), MD5Token(200), MD5Token(201), MD5Token(300)] nts = NetworkTopologyStrategy({'dc1': 3, 'dc2': 2}) replica_map = nts.make_token_replica_map(token_to_host_owner, ring) token_replicas = replica_map[MD5Token(0)] self.assertItemsEqual(token_replicas, (dc1_1, dc1_2, dc1_3, dc2_1, dc2_3)) def test_nts_make_token_replica_map_empty_dc(self): host = Host('1', SimpleConvictionPolicy) host.set_location_info('dc1', 'rack1') token_to_host_owner = {MD5Token(0): host} ring = [MD5Token(0)] nts = NetworkTopologyStrategy({'dc1': 1, 'dc2': 0}) replica_map = nts.make_token_replica_map(token_to_host_owner, ring) self.assertEqual(set(replica_map[MD5Token(0)]), set([host])) def test_nts_export_for_schema(self): strategy = NetworkTopologyStrategy({'dc1': '1', 'dc2': '2'}) self.assertEqual("{'class': 'NetworkTopologyStrategy', 'dc1': '1', 'dc2': '2'}", strategy.export_for_schema()) def test_simple_strategy_make_token_replica_map(self): host1 = Host('1', SimpleConvictionPolicy) host2 = Host('2', SimpleConvictionPolicy) host3 = Host('3', SimpleConvictionPolicy) token_to_host_owner = { MD5Token(0): host1, MD5Token(100): host2, MD5Token(200): host3 } ring = [MD5Token(0), MD5Token(100), MD5Token(200)] rf1_replicas = SimpleStrategy({'replication_factor': '1'}).make_token_replica_map(token_to_host_owner, ring) self.assertItemsEqual(rf1_replicas[MD5Token(0)], [host1]) self.assertItemsEqual(rf1_replicas[MD5Token(100)], [host2]) self.assertItemsEqual(rf1_replicas[MD5Token(200)], [host3]) rf2_replicas = SimpleStrategy({'replication_factor': '2'}).make_token_replica_map(token_to_host_owner, ring) self.assertItemsEqual(rf2_replicas[MD5Token(0)], [host1, host2]) self.assertItemsEqual(rf2_replicas[MD5Token(100)], [host2, host3]) self.assertItemsEqual(rf2_replicas[MD5Token(200)], [host3, host1]) rf3_replicas = SimpleStrategy({'replication_factor': '3'}).make_token_replica_map(token_to_host_owner, ring) self.assertItemsEqual(rf3_replicas[MD5Token(0)], [host1, host2, host3]) self.assertItemsEqual(rf3_replicas[MD5Token(100)], [host2, host3, host1]) self.assertItemsEqual(rf3_replicas[MD5Token(200)], [host3, host1, host2]) def test_ss_equals(self): self.assertNotEqual(SimpleStrategy({'replication_factor': '1'}), NetworkTopologyStrategy({'dc1': 2})) class NameEscapingTest(unittest.TestCase): def test_protect_name(self): """ Test cassandra.metadata.protect_name output """ self.assertEqual(protect_name('tests'), 'tests') self.assertEqual(protect_name('test\'s'), '"test\'s"') self.assertEqual(protect_name('test\'s'), "\"test's\"") self.assertEqual(protect_name('tests ?!@#$%^&*()'), '"tests ?!@#$%^&*()"') self.assertEqual(protect_name('1'), '"1"') self.assertEqual(protect_name('1test'), '"1test"') def test_protect_names(self): """ Test cassandra.metadata.protect_names output """ self.assertEqual(protect_names(['tests']), ['tests']) self.assertEqual(protect_names( [ 'tests', 'test\'s', 'tests ?!@#$%^&*()', '1' ]), [ 'tests', "\"test's\"", '"tests ?!@#$%^&*()"', '"1"' ]) def test_protect_value(self): """ Test cassandra.metadata.protect_value output """ self.assertEqual(protect_value(True), "true") self.assertEqual(protect_value(False), "false") self.assertEqual(protect_value(3.14), '3.14') self.assertEqual(protect_value(3), '3') self.assertEqual(protect_value('test'), "'test'") self.assertEqual(protect_value('test\'s'), "'test''s'") self.assertEqual(protect_value(None), 'NULL') def test_is_valid_name(self): """ Test cassandra.metadata.is_valid_name output """ self.assertEqual(is_valid_name(None), False) self.assertEqual(is_valid_name('test'), True) self.assertEqual(is_valid_name('Test'), False) self.assertEqual(is_valid_name('t_____1'), True) self.assertEqual(is_valid_name('test1'), True) self.assertEqual(is_valid_name('1test1'), False) invalid_keywords = cassandra.metadata.cql_keywords - cassandra.metadata.cql_keywords_unreserved for keyword in invalid_keywords: self.assertEqual(is_valid_name(keyword), False) class GetReplicasTest(unittest.TestCase): def _get_replicas(self, token_klass): tokens = [token_klass(i) for i in range(0, (2 ** 127 - 1), 2 ** 125)] hosts = [Host("ip%d" % i, SimpleConvictionPolicy) for i in range(len(tokens))] token_to_primary_replica = dict(zip(tokens, hosts)) keyspace = KeyspaceMetadata("ks", True, "SimpleStrategy", {"replication_factor": "1"}) metadata = Mock(spec=Metadata, keyspaces={'ks': keyspace}) token_map = TokenMap(token_klass, token_to_primary_replica, tokens, metadata) # tokens match node tokens exactly for token, expected_host in zip(tokens, hosts): replicas = token_map.get_replicas("ks", token) self.assertEqual(set(replicas), {expected_host}) # shift the tokens back by one for token, expected_host in zip(tokens, hosts): replicas = token_map.get_replicas("ks", token_klass(token.value - 1)) self.assertEqual(set(replicas), {expected_host}) # shift the tokens forward by one for i, token in enumerate(tokens): replicas = token_map.get_replicas("ks", token_klass(token.value + 1)) expected_host = hosts[(i + 1) % len(hosts)] self.assertEqual(set(replicas), {expected_host}) def test_murmur3_tokens(self): self._get_replicas(Murmur3Token) def test_md5_tokens(self): self._get_replicas(MD5Token) def test_bytes_tokens(self): self._get_replicas(BytesToken) class Murmur3TokensTest(unittest.TestCase): def test_murmur3_init(self): murmur3_token = Murmur3Token(cassandra.metadata.MIN_LONG - 1) self.assertEqual(str(murmur3_token), '') def test_python_vs_c(self): from cassandra.murmur3 import _murmur3 as mm3_python try: from cassandra.cmurmur3 import murmur3 as mm3_c iterations = 100 for _ in range(iterations): for len in range(0, 32): # zero to one block plus full range of tail lengths key = os.urandom(len) self.assertEqual(mm3_python(key), mm3_c(key)) except ImportError: raise unittest.SkipTest('The cmurmur3 extension is not available') def test_murmur3_python(self): from cassandra.murmur3 import _murmur3 self._verify_hash(_murmur3) def test_murmur3_c(self): try: from cassandra.cmurmur3 import murmur3 self._verify_hash(murmur3) except ImportError: raise unittest.SkipTest('The cmurmur3 extension is not available') def _verify_hash(self, fn): self.assertEqual(fn(six.b('123')), -7468325962851647638) self.assertEqual(fn(b'\x00\xff\x10\xfa\x99' * 10), 5837342703291459765) self.assertEqual(fn(b'\xfe' * 8), -8927430733708461935) self.assertEqual(fn(b'\x10' * 8), 1446172840243228796) self.assertEqual(fn(six.b(str(cassandra.metadata.MAX_LONG))), 7162290910810015547) class MD5TokensTest(unittest.TestCase): def test_md5_tokens(self): md5_token = MD5Token(cassandra.metadata.MIN_LONG - 1) self.assertEqual(md5_token.hash_fn('123'), 42767516990368493138776584305024125808) self.assertEqual(md5_token.hash_fn(str(cassandra.metadata.MAX_LONG)), 28528976619278518853815276204542453639) self.assertEqual(str(md5_token), '' % -9223372036854775809) class BytesTokensTest(unittest.TestCase): def test_bytes_tokens(self): bytes_token = BytesToken(unhexlify(six.b('01'))) self.assertEqual(bytes_token.value, six.b('\x01')) self.assertEqual(str(bytes_token), "" % bytes_token.value) self.assertEqual(bytes_token.hash_fn('123'), '123') self.assertEqual(bytes_token.hash_fn(123), 123) self.assertEqual(bytes_token.hash_fn(str(cassandra.metadata.MAX_LONG)), str(cassandra.metadata.MAX_LONG)) def test_from_string(self): from_unicode = BytesToken.from_string(six.text_type('0123456789abcdef')) from_bin = BytesToken.from_string(six.b('0123456789abcdef')) self.assertEqual(from_unicode, from_bin) self.assertIsInstance(from_unicode.value, six.binary_type) self.assertIsInstance(from_bin.value, six.binary_type) def test_comparison(self): tok = BytesToken.from_string(six.text_type('0123456789abcdef')) token_high_order = uint16_unpack(tok.value[0:2]) self.assertLess(BytesToken(uint16_pack(token_high_order - 1)), tok) self.assertGreater(BytesToken(uint16_pack(token_high_order + 1)), tok) def test_comparison_unicode(self): value = six.b('\'_-()"\xc2\xac') t0 = BytesToken(value) t1 = BytesToken.from_string('00') self.assertGreater(t0, t1) self.assertFalse(t0 < t1) class KeyspaceMetadataTest(unittest.TestCase): def test_export_as_string_user_types(self): keyspace_name = 'test' keyspace = KeyspaceMetadata(keyspace_name, True, 'SimpleStrategy', dict(replication_factor=3)) keyspace.user_types['a'] = UserType(keyspace_name, 'a', ['one', 'two'], ['c', 'int']) keyspace.user_types['b'] = UserType(keyspace_name, 'b', ['one', 'two', 'three'], ['d', 'int', 'a']) keyspace.user_types['c'] = UserType(keyspace_name, 'c', ['one'], ['int']) keyspace.user_types['d'] = UserType(keyspace_name, 'd', ['one'], ['c']) self.assertEqual("""CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '3'} AND durable_writes = true; CREATE TYPE test.c ( one int ); CREATE TYPE test.a ( one c, two int ); CREATE TYPE test.d ( one c ); CREATE TYPE test.b ( one d, two int, three a );""", keyspace.export_as_string()) class UserTypesTest(unittest.TestCase): def test_as_cql_query(self): field_types = ['varint', 'ascii', 'frozen>'] udt = UserType("ks1", "mytype", ["a", "b", "c"], field_types) self.assertEqual("CREATE TYPE ks1.mytype (a varint, b ascii, c frozen>)", udt.as_cql_query(formatted=False)) self.assertEqual("""CREATE TYPE ks1.mytype ( a varint, b ascii, c frozen> );""", udt.export_as_string()) def test_as_cql_query_name_escaping(self): udt = UserType("MyKeyspace", "MyType", ["AbA", "keyspace"], ['ascii', 'ascii']) self.assertEqual('CREATE TYPE "MyKeyspace"."MyType" ("AbA" ascii, "keyspace" ascii)', udt.as_cql_query(formatted=False)) class UserDefinedFunctionTest(unittest.TestCase): def test_as_cql_query_removes_frozen(self): - func = Function("ks1", "myfunction", ["frozen>"], ["a"], "int", "java", "return 0;", True) + func = Function( + "ks1", "myfunction", ["frozen>"], ["a"], + "int", "java", "return 0;", True, False, False, False + ) expected_result = ( "CREATE FUNCTION ks1.myfunction(a tuple) " "CALLED ON NULL INPUT " "RETURNS int " "LANGUAGE java " "AS $$return 0;$$" ) self.assertEqual(expected_result, func.as_cql_query(formatted=False)) class UserDefinedAggregateTest(unittest.TestCase): def test_as_cql_query_removes_frozen(self): - aggregate = Aggregate("ks1", "myaggregate", ["frozen>"], "statefunc", "frozen>", "finalfunc", "(0)", "tuple") + aggregate = Aggregate("ks1", "myaggregate", ["frozen>"], "statefunc", "frozen>", "finalfunc", "(0)", "tuple", False) expected_result = ( "CREATE AGGREGATE ks1.myaggregate(tuple) " "SFUNC statefunc " "STYPE tuple " "FINALFUNC finalfunc " "INITCOND (0)" ) self.assertEqual(expected_result, aggregate.as_cql_query(formatted=False)) class IndexTest(unittest.TestCase): def test_build_index_as_cql(self): column_meta = Mock() column_meta.name = 'column_name_here' column_meta.table.name = 'table_name_here' column_meta.table.keyspace_name = 'keyspace_name_here' column_meta.table.columns = {column_meta.name: column_meta} - parser = get_schema_parser(Mock(), '2.1.0', 0.1) + parser = get_schema_parser(Mock(), '2.1.0', None, 0.1) row = {'index_name': 'index_name_here', 'index_type': 'index_type_here'} index_meta = parser._build_index_metadata(column_meta, row) self.assertEqual(index_meta.as_cql_query(), 'CREATE INDEX index_name_here ON keyspace_name_here.table_name_here (column_name_here)') row['index_options'] = '{ "class_name": "class_name_here" }' row['index_type'] = 'CUSTOM' index_meta = parser._build_index_metadata(column_meta, row) self.assertEqual(index_meta.as_cql_query(), "CREATE CUSTOM INDEX index_name_here ON keyspace_name_here.table_name_here (column_name_here) USING 'class_name_here'") class UnicodeIdentifiersTests(unittest.TestCase): """ Exercise cql generation with unicode characters. Keyspace, Table, and Index names cannot have special chars because C* names files by those identifiers, but they are tested anyway. Looking for encoding errors like PYTHON-447 """ name = six.text_type(b'\'_-()"\xc2\xac'.decode('utf-8')) def test_keyspace_name(self): km = KeyspaceMetadata(self.name, False, 'SimpleStrategy', {'replication_factor': 1}) km.export_as_string() def test_table_name(self): tm = TableMetadata(self.name, self.name) tm.export_as_string() def test_column_name_single_partition(self): tm = TableMetadata('ks', 'table') cm = ColumnMetadata(tm, self.name, u'int') tm.columns[cm.name] = cm tm.partition_key.append(cm) tm.export_as_string() def test_column_name_single_partition_single_clustering(self): tm = TableMetadata('ks', 'table') cm = ColumnMetadata(tm, self.name, u'int') tm.columns[cm.name] = cm tm.partition_key.append(cm) cm = ColumnMetadata(tm, self.name + 'x', u'int') tm.columns[cm.name] = cm tm.clustering_key.append(cm) tm.export_as_string() def test_column_name_multiple_partition(self): tm = TableMetadata('ks', 'table') cm = ColumnMetadata(tm, self.name, u'int') tm.columns[cm.name] = cm tm.partition_key.append(cm) cm = ColumnMetadata(tm, self.name + 'x', u'int') tm.columns[cm.name] = cm tm.partition_key.append(cm) tm.export_as_string() def test_index(self): im = IndexMetadata(self.name, self.name, self.name, kind='', index_options={'target': self.name}) log.debug(im.export_as_string()) im = IndexMetadata(self.name, self.name, self.name, kind='CUSTOM', index_options={'target': self.name, 'class_name': 'Class'}) log.debug(im.export_as_string()) # PYTHON-1008 im = IndexMetadata(self.name, self.name, self.name, kind='CUSTOM', index_options={'target': self.name, 'class_name': 'Class', 'delimiter': self.name}) log.debug(im.export_as_string()) def test_function(self): - fm = Function(self.name, self.name, (u'int', u'int'), (u'x', u'y'), u'int', u'language', self.name, False) + fm = Function(keyspace=self.name, name=self.name, + argument_types=(u'int', u'int'), + argument_names=(u'x', u'y'), + return_type=u'int', language=u'language', + body=self.name, called_on_null_input=False, + deterministic=True, + monotonic=False, monotonic_on=(u'x',)) fm.export_as_string() def test_aggregate(self): - am = Aggregate(self.name, self.name, (u'text',), self.name, u'text', self.name, self.name, u'text') + am = Aggregate(self.name, self.name, (u'text',), self.name, u'text', self.name, self.name, u'text', True) am.export_as_string() def test_user_type(self): um = UserType(self.name, self.name, [self.name, self.name], [u'int', u'text']) um.export_as_string() +class FunctionToCQLTests(unittest.TestCase): + + base_vars = { + 'keyspace': 'ks_name', + 'name': 'function_name', + 'argument_types': (u'int', u'int'), + 'argument_names': (u'x', u'y'), + 'return_type': u'int', + 'language': u'language', + 'body': 'body', + 'called_on_null_input': False, + 'deterministic': True, + 'monotonic': False, + 'monotonic_on': () + } + + def _function_with_kwargs(self, **kwargs): + return Function(**dict(self.base_vars, + **kwargs) + ) + + def test_non_monotonic(self): + self.assertNotIn( + 'MONOTONIC', + self._function_with_kwargs( + monotonic=False, + monotonic_on=() + ).export_as_string() + ) + + def test_monotonic_all(self): + mono_function = self._function_with_kwargs( + monotonic=True, + monotonic_on=() + ) + self.assertIn( + 'MONOTONIC LANG', + mono_function.as_cql_query(formatted=False) + ) + self.assertIn( + 'MONOTONIC\n LANG', + mono_function.as_cql_query(formatted=True) + ) + + def test_monotonic_one(self): + mono_on_function = self._function_with_kwargs( + monotonic=False, + monotonic_on=('x',) + ) + self.assertIn( + 'MONOTONIC ON x LANG', + mono_on_function.as_cql_query(formatted=False) + ) + self.assertIn( + 'MONOTONIC ON x\n LANG', + mono_on_function.as_cql_query(formatted=True) + ) + + def test_nondeterministic(self): + self.assertNotIn( + 'DETERMINISTIC', + self._function_with_kwargs( + deterministic=False + ).as_cql_query(formatted=False) + ) + + def test_deterministic(self): + self.assertIn( + 'DETERMINISTIC', + self._function_with_kwargs( + deterministic=True + ).as_cql_query(formatted=False) + ) + self.assertIn( + 'DETERMINISTIC\n', + self._function_with_kwargs( + deterministic=True + ).as_cql_query(formatted=True) + ) + + +class AggregateToCQLTests(unittest.TestCase): + base_vars = { + 'keyspace': 'ks_name', + 'name': 'function_name', + 'argument_types': (u'int', u'int'), + 'state_func': 'funcname', + 'state_type': u'int', + 'return_type': u'int', + 'final_func': None, + 'initial_condition': '0', + 'deterministic': True + } + + def _aggregate_with_kwargs(self, **kwargs): + return Aggregate(**dict(self.base_vars, + **kwargs) + ) + + def test_nondeterministic(self): + self.assertNotIn( + 'DETERMINISTIC', + self._aggregate_with_kwargs( + deterministic=False + ).as_cql_query(formatted=True) + ) + + def test_deterministic(self): + for formatted in (True, False): + query = self._aggregate_with_kwargs( + deterministic=True + ).as_cql_query(formatted=formatted) + self.assertTrue(query.endswith('DETERMINISTIC'), + msg="'DETERMINISTIC' not found in {}".format(query) + ) + + class HostsTests(unittest.TestCase): def test_iterate_all_hosts_and_modify(self): """ PYTHON-572 """ metadata = Metadata() metadata.add_or_return_host(Host('dc1.1', SimpleConvictionPolicy)) metadata.add_or_return_host(Host('dc1.2', SimpleConvictionPolicy)) self.assertEqual(len(metadata.all_hosts()), 2) for host in metadata.all_hosts(): # this would previously raise in Py3 metadata.remove_host(host) self.assertEqual(len(metadata.all_hosts()), 0) class MetadataHelpersTest(unittest.TestCase): """ For any helper functions that need unit tests """ def test_strip_frozen(self): self.longMessage = True argument_to_expected_results = [ ('int', 'int'), ('tuple', 'tuple'), (r'map<"!@#$%^&*()[]\ frozen >>>", int>', r'map<"!@#$%^&*()[]\ frozen >>>", int>'), # A valid UDT name ('frozen>', 'tuple'), (r'frozen>>", int>>', r'map<"!@#$%^&*()[]\ frozen >>>", int>'), ('frozen>, int>>, frozen>>>>>', 'map, int>, map>>'), ] for argument, expected_result in argument_to_expected_results: result = strip_frozen(argument) self.assertEqual(result, expected_result, "strip_frozen() arg: {}".format(argument)) diff --git a/tests/unit/test_parameter_binding.py b/tests/unit/test_parameter_binding.py index 9c91679..228f3f4 100644 --- a/tests/unit/test_parameter_binding.py +++ b/tests/unit/test_parameter_binding.py @@ -1,223 +1,224 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from cassandra.encoder import Encoder from cassandra.protocol import ColumnMetadata from cassandra.query import (bind_params, ValueSequence, PreparedStatement, BoundStatement, UNSET_VALUE) from cassandra.cqltypes import Int32Type from cassandra.util import OrderedDict from six.moves import xrange import six class ParamBindingTest(unittest.TestCase): def test_bind_sequence(self): result = bind_params("%s %s %s", (1, "a", 2.0), Encoder()) self.assertEqual(result, "1 'a' 2.0") def test_bind_map(self): result = bind_params("%(a)s %(b)s %(c)s", dict(a=1, b="a", c=2.0), Encoder()) self.assertEqual(result, "1 'a' 2.0") def test_sequence_param(self): result = bind_params("%s", (ValueSequence((1, "a", 2.0)),), Encoder()) self.assertEqual(result, "(1, 'a', 2.0)") def test_generator_param(self): result = bind_params("%s", ((i for i in xrange(3)),), Encoder()) self.assertEqual(result, "[0, 1, 2]") def test_none_param(self): result = bind_params("%s", (None,), Encoder()) self.assertEqual(result, "NULL") def test_list_collection(self): result = bind_params("%s", (['a', 'b', 'c'],), Encoder()) self.assertEqual(result, "['a', 'b', 'c']") def test_set_collection(self): result = bind_params("%s", (set(['a', 'b']),), Encoder()) self.assertIn(result, ("{'a', 'b'}", "{'b', 'a'}")) def test_map_collection(self): vals = OrderedDict() vals['a'] = 'a' vals['b'] = 'b' vals['c'] = 'c' result = bind_params("%s", (vals,), Encoder()) self.assertEqual(result, "{'a': 'a', 'b': 'b', 'c': 'c'}") def test_quote_escaping(self): result = bind_params("%s", ("""'ef''ef"ef""ef'""",), Encoder()) self.assertEqual(result, """'''ef''''ef"ef""ef'''""") def test_float_precision(self): f = 3.4028234663852886e+38 self.assertEqual(float(bind_params("%s", (f,), Encoder())), f) class BoundStatementTestV1(unittest.TestCase): protocol_version = 1 @classmethod def setUpClass(cls): column_metadata = [ColumnMetadata('keyspace', 'cf', 'rk0', Int32Type), ColumnMetadata('keyspace', 'cf', 'rk1', Int32Type), ColumnMetadata('keyspace', 'cf', 'ck0', Int32Type), ColumnMetadata('keyspace', 'cf', 'v0', Int32Type)] cls.prepared = PreparedStatement(column_metadata=column_metadata, query_id=None, routing_key_indexes=[1, 0], query=None, keyspace='keyspace', protocol_version=cls.protocol_version, result_metadata=None, result_metadata_id=None) cls.bound = BoundStatement(prepared_statement=cls.prepared) def test_invalid_argument_type(self): values = (0, 0, 0, 'string not int') try: self.bound.bind(values) except TypeError as e: self.assertIn('v0', str(e)) self.assertIn('Int32Type', str(e)) self.assertIn('str', str(e)) else: self.fail('Passed invalid type but exception was not thrown') values = (['1', '2'], 0, 0, 0) try: self.bound.bind(values) except TypeError as e: self.assertIn('rk0', str(e)) self.assertIn('Int32Type', str(e)) self.assertIn('list', str(e)) else: self.fail('Passed invalid type but exception was not thrown') def test_inherit_fetch_size(self): keyspace = 'keyspace1' column_family = 'cf1' column_metadata = [ ColumnMetadata(keyspace, column_family, 'foo1', Int32Type), ColumnMetadata(keyspace, column_family, 'foo2', Int32Type) ] prepared_statement = PreparedStatement(column_metadata=column_metadata, query_id=None, routing_key_indexes=[], query=None, keyspace=keyspace, protocol_version=self.protocol_version, result_metadata=None, result_metadata_id=None) prepared_statement.fetch_size = 1234 bound_statement = BoundStatement(prepared_statement=prepared_statement) self.assertEqual(1234, bound_statement.fetch_size) def test_too_few_parameters_for_routing_key(self): self.assertRaises(ValueError, self.prepared.bind, (1,)) bound = self.prepared.bind((1, 2)) self.assertEqual(bound.keyspace, 'keyspace') def test_dict_missing_routing_key(self): self.assertRaises(KeyError, self.bound.bind, {'rk0': 0, 'ck0': 0, 'v0': 0}) self.assertRaises(KeyError, self.bound.bind, {'rk1': 0, 'ck0': 0, 'v0': 0}) def test_missing_value(self): self.assertRaises(KeyError, self.bound.bind, {'rk0': 0, 'rk1': 0, 'ck0': 0}) def test_extra_value(self): self.bound.bind({'rk0': 0, 'rk1': 0, 'ck0': 0, 'v0': 0, 'should_not_be_here': 123}) # okay to have extra keys in dict self.assertEqual(self.bound.values, [six.b('\x00') * 4] * 4) # four encoded zeros self.assertRaises(ValueError, self.bound.bind, (0, 0, 0, 0, 123)) def test_values_none(self): # should have values self.assertRaises(ValueError, self.bound.bind, None) # prepared statement with no values prepared_statement = PreparedStatement(column_metadata=[], query_id=None, routing_key_indexes=[], query=None, keyspace='whatever', protocol_version=self.protocol_version, result_metadata=None, result_metadata_id=None) bound = prepared_statement.bind(None) self.assertListEqual(bound.values, []) def test_bind_none(self): self.bound.bind({'rk0': 0, 'rk1': 0, 'ck0': 0, 'v0': None}) self.assertEqual(self.bound.values[-1], None) old_values = self.bound.values self.bound.bind((0, 0, 0, None)) self.assertIsNot(self.bound.values, old_values) self.assertEqual(self.bound.values[-1], None) def test_unset_value(self): self.assertRaises(ValueError, self.bound.bind, {'rk0': 0, 'rk1': 0, 'ck0': 0, 'v0': UNSET_VALUE}) self.assertRaises(ValueError, self.bound.bind, (0, 0, 0, UNSET_VALUE)) class BoundStatementTestV2(BoundStatementTestV1): protocol_version = 2 class BoundStatementTestV3(BoundStatementTestV1): protocol_version = 3 class BoundStatementTestV4(BoundStatementTestV1): protocol_version = 4 def test_dict_missing_routing_key(self): # in v4 it implicitly binds UNSET_VALUE for missing items, # UNSET_VALUE is ValueError for routing keys self.assertRaises(ValueError, self.bound.bind, {'rk0': 0, 'ck0': 0, 'v0': 0}) self.assertRaises(ValueError, self.bound.bind, {'rk1': 0, 'ck0': 0, 'v0': 0}) def test_missing_value(self): # in v4 missing values are UNSET_VALUE self.bound.bind({'rk0': 0, 'rk1': 0, 'ck0': 0}) self.assertEqual(self.bound.values[-1], UNSET_VALUE) old_values = self.bound.values self.bound.bind((0, 0, 0)) self.assertIsNot(self.bound.values, old_values) self.assertEqual(self.bound.values[-1], UNSET_VALUE) def test_unset_value(self): self.bound.bind({'rk0': 0, 'rk1': 0, 'ck0': 0, 'v0': UNSET_VALUE}) self.assertEqual(self.bound.values[-1], UNSET_VALUE) self.bound.bind((0, 0, 0, UNSET_VALUE)) self.assertEqual(self.bound.values[-1], UNSET_VALUE) + class BoundStatementTestV5(BoundStatementTestV4): protocol_version = 5 diff --git a/tests/unit/test_policies.py b/tests/unit/test_policies.py index 15fa316..5c0c112 100644 --- a/tests/unit/test_policies.py +++ b/tests/unit/test_policies.py @@ -1,1500 +1,1502 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from itertools import islice, cycle from mock import Mock, patch, call from random import randint import six from six.moves._thread import LockType import sys import struct from threading import Thread from cassandra import ConsistencyLevel from cassandra.cluster import Cluster from cassandra.metadata import Metadata from cassandra.policies import (RoundRobinPolicy, WhiteListRoundRobinPolicy, DCAwareRoundRobinPolicy, TokenAwarePolicy, SimpleConvictionPolicy, HostDistance, ExponentialReconnectionPolicy, RetryPolicy, WriteType, DowngradingConsistencyRetryPolicy, ConstantReconnectionPolicy, LoadBalancingPolicy, ConvictionPolicy, ReconnectionPolicy, FallthroughRetryPolicy, IdentityTranslator, EC2MultiRegionTranslator, HostFilterPolicy) from cassandra.pool import Host from cassandra.connection import DefaultEndPoint from cassandra.query import Statement from six.moves import xrange class LoadBalancingPolicyTest(unittest.TestCase): def test_non_implemented(self): """ Code coverage for interface-style base class """ policy = LoadBalancingPolicy() host = Host(DefaultEndPoint("ip1"), SimpleConvictionPolicy) host.set_location_info("dc1", "rack1") self.assertRaises(NotImplementedError, policy.distance, host) self.assertRaises(NotImplementedError, policy.populate, None, host) self.assertRaises(NotImplementedError, policy.make_query_plan) self.assertRaises(NotImplementedError, policy.on_up, host) self.assertRaises(NotImplementedError, policy.on_down, host) self.assertRaises(NotImplementedError, policy.on_add, host) self.assertRaises(NotImplementedError, policy.on_remove, host) def test_instance_check(self): self.assertRaises(TypeError, Cluster, load_balancing_policy=RoundRobinPolicy) class RoundRobinPolicyTest(unittest.TestCase): def test_basic(self): hosts = [0, 1, 2, 3] policy = RoundRobinPolicy() policy.populate(None, hosts) qplan = list(policy.make_query_plan()) self.assertEqual(sorted(qplan), hosts) def test_multiple_query_plans(self): hosts = [0, 1, 2, 3] policy = RoundRobinPolicy() policy.populate(None, hosts) for i in xrange(20): qplan = list(policy.make_query_plan()) self.assertEqual(sorted(qplan), hosts) def test_single_host(self): policy = RoundRobinPolicy() policy.populate(None, [0]) qplan = list(policy.make_query_plan()) self.assertEqual(qplan, [0]) def test_status_updates(self): hosts = [0, 1, 2, 3] policy = RoundRobinPolicy() policy.populate(None, hosts) policy.on_down(0) policy.on_remove(1) policy.on_up(4) policy.on_add(5) qplan = list(policy.make_query_plan()) self.assertEqual(sorted(qplan), [2, 3, 4, 5]) def test_thread_safety(self): hosts = range(100) policy = RoundRobinPolicy() policy.populate(None, hosts) def check_query_plan(): for i in range(100): qplan = list(policy.make_query_plan()) self.assertEqual(sorted(qplan), list(hosts)) threads = [Thread(target=check_query_plan) for i in range(4)] for t in threads: t.start() for t in threads: t.join() def test_thread_safety_during_modification(self): hosts = range(100) policy = RoundRobinPolicy() policy.populate(None, hosts) errors = [] def check_query_plan(): try: for i in xrange(100): list(policy.make_query_plan()) except Exception as exc: errors.append(exc) def host_up(): for i in xrange(1000): policy.on_up(randint(0, 99)) def host_down(): for i in xrange(1000): policy.on_down(randint(0, 99)) threads = [] for i in range(5): threads.append(Thread(target=check_query_plan)) threads.append(Thread(target=host_up)) threads.append(Thread(target=host_down)) # make the GIL switch after every instruction, maximizing # the chance of race conditions check = six.PY2 or '__pypy__' in sys.builtin_module_names if check: original_interval = sys.getcheckinterval() else: original_interval = sys.getswitchinterval() try: if check: sys.setcheckinterval(0) else: sys.setswitchinterval(0.0001) - map(lambda t: t.start(), threads) - map(lambda t: t.join(), threads) + for t in threads: + t.start() + for t in threads: + t.join() finally: if check: sys.setcheckinterval(original_interval) else: sys.setswitchinterval(original_interval) if errors: self.fail("Saw errors: %s" % (errors,)) def test_no_live_nodes(self): """ Ensure query plan for a downed cluster will execute without errors """ hosts = [0, 1, 2, 3] policy = RoundRobinPolicy() policy.populate(None, hosts) for i in range(4): policy.on_down(i) qplan = list(policy.make_query_plan()) self.assertEqual(qplan, []) class DCAwareRoundRobinPolicyTest(unittest.TestCase): def test_no_remote(self): hosts = [] for i in range(4): h = Host(DefaultEndPoint(i), SimpleConvictionPolicy) h.set_location_info("dc1", "rack1") hosts.append(h) policy = DCAwareRoundRobinPolicy("dc1") policy.populate(None, hosts) qplan = list(policy.make_query_plan()) self.assertEqual(sorted(qplan), sorted(hosts)) def test_with_remotes(self): hosts = [Host(DefaultEndPoint(i), SimpleConvictionPolicy) for i in range(4)] for h in hosts[:2]: h.set_location_info("dc1", "rack1") for h in hosts[2:]: h.set_location_info("dc2", "rack1") local_hosts = set(h for h in hosts if h.datacenter == "dc1") remote_hosts = set(h for h in hosts if h.datacenter != "dc1") # allow all of the remote hosts to be used policy = DCAwareRoundRobinPolicy("dc1", used_hosts_per_remote_dc=2) policy.populate(Mock(), hosts) qplan = list(policy.make_query_plan()) self.assertEqual(set(qplan[:2]), local_hosts) self.assertEqual(set(qplan[2:]), remote_hosts) # allow only one of the remote hosts to be used policy = DCAwareRoundRobinPolicy("dc1", used_hosts_per_remote_dc=1) policy.populate(Mock(), hosts) qplan = list(policy.make_query_plan()) self.assertEqual(set(qplan[:2]), local_hosts) used_remotes = set(qplan[2:]) self.assertEqual(1, len(used_remotes)) self.assertIn(qplan[2], remote_hosts) # allow no remote hosts to be used policy = DCAwareRoundRobinPolicy("dc1", used_hosts_per_remote_dc=0) policy.populate(Mock(), hosts) qplan = list(policy.make_query_plan()) self.assertEqual(2, len(qplan)) self.assertEqual(local_hosts, set(qplan)) def test_get_distance(self): policy = DCAwareRoundRobinPolicy("dc1", used_hosts_per_remote_dc=0) host = Host(DefaultEndPoint("ip1"), SimpleConvictionPolicy) host.set_location_info("dc1", "rack1") policy.populate(Mock(), [host]) self.assertEqual(policy.distance(host), HostDistance.LOCAL) # used_hosts_per_remote_dc is set to 0, so ignore it remote_host = Host(DefaultEndPoint("ip2"), SimpleConvictionPolicy) remote_host.set_location_info("dc2", "rack1") self.assertEqual(policy.distance(remote_host), HostDistance.IGNORED) # dc2 isn't registered in the policy's live_hosts dict policy.used_hosts_per_remote_dc = 1 self.assertEqual(policy.distance(remote_host), HostDistance.IGNORED) # make sure the policy has both dcs registered policy.populate(Mock(), [host, remote_host]) self.assertEqual(policy.distance(remote_host), HostDistance.REMOTE) # since used_hosts_per_remote_dc is set to 1, only the first # remote host in dc2 will be REMOTE, the rest are IGNORED second_remote_host = Host(DefaultEndPoint("ip3"), SimpleConvictionPolicy) second_remote_host.set_location_info("dc2", "rack1") policy.populate(Mock(), [host, remote_host, second_remote_host]) distances = set([policy.distance(remote_host), policy.distance(second_remote_host)]) self.assertEqual(distances, set([HostDistance.REMOTE, HostDistance.IGNORED])) def test_status_updates(self): hosts = [Host(DefaultEndPoint(i), SimpleConvictionPolicy) for i in range(4)] for h in hosts[:2]: h.set_location_info("dc1", "rack1") for h in hosts[2:]: h.set_location_info("dc2", "rack1") policy = DCAwareRoundRobinPolicy("dc1", used_hosts_per_remote_dc=1) policy.populate(Mock(), hosts) policy.on_down(hosts[0]) policy.on_remove(hosts[2]) new_local_host = Host(DefaultEndPoint(4), SimpleConvictionPolicy) new_local_host.set_location_info("dc1", "rack1") policy.on_up(new_local_host) new_remote_host = Host(DefaultEndPoint(5), SimpleConvictionPolicy) new_remote_host.set_location_info("dc9000", "rack1") policy.on_add(new_remote_host) # we now have two local hosts and two remote hosts in separate dcs qplan = list(policy.make_query_plan()) self.assertEqual(set(qplan[:2]), set([hosts[1], new_local_host])) self.assertEqual(set(qplan[2:]), set([hosts[3], new_remote_host])) # since we have hosts in dc9000, the distance shouldn't be IGNORED self.assertEqual(policy.distance(new_remote_host), HostDistance.REMOTE) policy.on_down(new_local_host) policy.on_down(hosts[1]) qplan = list(policy.make_query_plan()) self.assertEqual(set(qplan), set([hosts[3], new_remote_host])) policy.on_down(new_remote_host) policy.on_down(hosts[3]) qplan = list(policy.make_query_plan()) self.assertEqual(qplan, []) def test_modification_during_generation(self): hosts = [Host(DefaultEndPoint(i), SimpleConvictionPolicy) for i in range(4)] for h in hosts[:2]: h.set_location_info("dc1", "rack1") for h in hosts[2:]: h.set_location_info("dc2", "rack1") policy = DCAwareRoundRobinPolicy("dc1", used_hosts_per_remote_dc=3) policy.populate(Mock(), hosts) # The general concept here is to change thee internal state of the # policy during plan generation. In this case we use a grey-box # approach that changes specific things during known phases of the # generator. new_host = Host(DefaultEndPoint(4), SimpleConvictionPolicy) new_host.set_location_info("dc1", "rack1") # new local before iteration plan = policy.make_query_plan() policy.on_up(new_host) # local list is not bound yet, so we get to see that one self.assertEqual(len(list(plan)), 3 + 2) # remove local before iteration plan = policy.make_query_plan() policy.on_down(new_host) # local list is not bound yet, so we don't see it self.assertEqual(len(list(plan)), 2 + 2) # new local after starting iteration plan = policy.make_query_plan() next(plan) policy.on_up(new_host) # local list was is bound, and one consumed, so we only see the other original self.assertEqual(len(list(plan)), 1 + 2) # remove local after traversing available plan = policy.make_query_plan() for _ in range(3): next(plan) policy.on_down(new_host) # we should be past the local list self.assertEqual(len(list(plan)), 0 + 2) # REMOTES CHANGE new_host.set_location_info("dc2", "rack1") # new remote after traversing local, but not starting remote plan = policy.make_query_plan() for _ in range(2): next(plan) policy.on_up(new_host) # list is updated before we get to it self.assertEqual(len(list(plan)), 0 + 3) # remove remote after traversing local, but not starting remote plan = policy.make_query_plan() for _ in range(2): next(plan) policy.on_down(new_host) # list is updated before we get to it self.assertEqual(len(list(plan)), 0 + 2) # new remote after traversing local, and starting remote plan = policy.make_query_plan() for _ in range(3): next(plan) policy.on_up(new_host) # slice is already made, and we've consumed one self.assertEqual(len(list(plan)), 0 + 1) # remove remote after traversing local, and starting remote plan = policy.make_query_plan() for _ in range(3): next(plan) policy.on_down(new_host) # slice is created with all present, and we've consumed one self.assertEqual(len(list(plan)), 0 + 2) # local DC disappears after finishing it, but not starting remote plan = policy.make_query_plan() for _ in range(2): next(plan) policy.on_down(hosts[0]) policy.on_down(hosts[1]) # dict traversal starts as normal self.assertEqual(len(list(plan)), 0 + 2) policy.on_up(hosts[0]) policy.on_up(hosts[1]) # PYTHON-297 addresses the following cases, where DCs come and go # during generation # local DC disappears after finishing it, and starting remote plan = policy.make_query_plan() for _ in range(3): next(plan) policy.on_down(hosts[0]) policy.on_down(hosts[1]) # dict traversal has begun and consumed one self.assertEqual(len(list(plan)), 0 + 1) policy.on_up(hosts[0]) policy.on_up(hosts[1]) # remote DC disappears after finishing local, but not starting remote plan = policy.make_query_plan() for _ in range(2): next(plan) policy.on_down(hosts[2]) policy.on_down(hosts[3]) # nothing left self.assertEqual(len(list(plan)), 0 + 0) policy.on_up(hosts[2]) policy.on_up(hosts[3]) # remote DC disappears while traversing it plan = policy.make_query_plan() for _ in range(3): next(plan) policy.on_down(hosts[2]) policy.on_down(hosts[3]) # we continue with remainder of original list self.assertEqual(len(list(plan)), 0 + 1) policy.on_up(hosts[2]) policy.on_up(hosts[3]) another_host = Host(DefaultEndPoint(5), SimpleConvictionPolicy) another_host.set_location_info("dc3", "rack1") new_host.set_location_info("dc3", "rack1") # new DC while traversing remote plan = policy.make_query_plan() for _ in range(3): next(plan) policy.on_up(new_host) policy.on_up(another_host) # we continue with remainder of original list self.assertEqual(len(list(plan)), 0 + 1) # remote DC disappears after finishing it plan = policy.make_query_plan() for _ in range(3): next(plan) last_host_in_this_dc = next(plan) if last_host_in_this_dc in (new_host, another_host): down_hosts = [new_host, another_host] else: down_hosts = hosts[2:] for h in down_hosts: policy.on_down(h) # the last DC has two self.assertEqual(len(list(plan)), 0 + 2) def test_no_live_nodes(self): """ Ensure query plan for a downed cluster will execute without errors """ hosts = [] for i in range(4): h = Host(DefaultEndPoint(i), SimpleConvictionPolicy) h.set_location_info("dc1", "rack1") hosts.append(h) policy = DCAwareRoundRobinPolicy("dc1", used_hosts_per_remote_dc=1) policy.populate(Mock(), hosts) for host in hosts: policy.on_down(host) qplan = list(policy.make_query_plan()) self.assertEqual(qplan, []) def test_no_nodes(self): """ Ensure query plan for an empty cluster will execute without errors """ policy = DCAwareRoundRobinPolicy("dc1", used_hosts_per_remote_dc=1) policy.populate(None, []) qplan = list(policy.make_query_plan()) self.assertEqual(qplan, []) def test_default_dc(self): host_local = Host(DefaultEndPoint(1), SimpleConvictionPolicy, 'local') host_remote = Host(DefaultEndPoint(2), SimpleConvictionPolicy, 'remote') host_none = Host(DefaultEndPoint(1), SimpleConvictionPolicy) # contact point is '1' cluster = Mock(endpoints_resolved=[DefaultEndPoint(1)]) # contact DC first policy = DCAwareRoundRobinPolicy() policy.populate(cluster, [host_none]) self.assertFalse(policy.local_dc) policy.on_add(host_local) policy.on_add(host_remote) self.assertNotEqual(policy.local_dc, host_remote.datacenter) self.assertEqual(policy.local_dc, host_local.datacenter) # contact DC second policy = DCAwareRoundRobinPolicy() policy.populate(cluster, [host_none]) self.assertFalse(policy.local_dc) policy.on_add(host_remote) policy.on_add(host_local) self.assertNotEqual(policy.local_dc, host_remote.datacenter) self.assertEqual(policy.local_dc, host_local.datacenter) # no DC policy = DCAwareRoundRobinPolicy() policy.populate(cluster, [host_none]) self.assertFalse(policy.local_dc) policy.on_add(host_none) self.assertFalse(policy.local_dc) # only other DC policy = DCAwareRoundRobinPolicy() policy.populate(cluster, [host_none]) self.assertFalse(policy.local_dc) policy.on_add(host_remote) self.assertFalse(policy.local_dc) class TokenAwarePolicyTest(unittest.TestCase): def test_wrap_round_robin(self): cluster = Mock(spec=Cluster) cluster.metadata = Mock(spec=Metadata) hosts = [Host(DefaultEndPoint(str(i)), SimpleConvictionPolicy) for i in range(4)] for host in hosts: host.set_up() def get_replicas(keyspace, packed_key): index = struct.unpack('>i', packed_key)[0] return list(islice(cycle(hosts), index, index + 2)) cluster.metadata.get_replicas.side_effect = get_replicas policy = TokenAwarePolicy(RoundRobinPolicy()) policy.populate(cluster, hosts) for i in range(4): query = Statement(routing_key=struct.pack('>i', i), keyspace='keyspace_name') qplan = list(policy.make_query_plan(None, query)) replicas = get_replicas(None, struct.pack('>i', i)) other = set(h for h in hosts if h not in replicas) self.assertEqual(replicas, qplan[:2]) self.assertEqual(other, set(qplan[2:])) # Should use the secondary policy for i in range(4): qplan = list(policy.make_query_plan()) self.assertEqual(set(qplan), set(hosts)) def test_wrap_dc_aware(self): cluster = Mock(spec=Cluster) cluster.metadata = Mock(spec=Metadata) hosts = [Host(DefaultEndPoint(str(i)), SimpleConvictionPolicy) for i in range(4)] for host in hosts: host.set_up() for h in hosts[:2]: h.set_location_info("dc1", "rack1") for h in hosts[2:]: h.set_location_info("dc2", "rack1") def get_replicas(keyspace, packed_key): index = struct.unpack('>i', packed_key)[0] # return one node from each DC if index % 2 == 0: return [hosts[0], hosts[2]] else: return [hosts[1], hosts[3]] cluster.metadata.get_replicas.side_effect = get_replicas policy = TokenAwarePolicy(DCAwareRoundRobinPolicy("dc1", used_hosts_per_remote_dc=1)) policy.populate(cluster, hosts) for i in range(4): query = Statement(routing_key=struct.pack('>i', i), keyspace='keyspace_name') qplan = list(policy.make_query_plan(None, query)) replicas = get_replicas(None, struct.pack('>i', i)) # first should be the only local replica self.assertIn(qplan[0], replicas) self.assertEqual(qplan[0].datacenter, "dc1") # then the local non-replica self.assertNotIn(qplan[1], replicas) self.assertEqual(qplan[1].datacenter, "dc1") # then one of the remotes (used_hosts_per_remote_dc is 1, so we # shouldn't see two remotes) self.assertEqual(qplan[2].datacenter, "dc2") self.assertEqual(3, len(qplan)) class FakeCluster: def __init__(self): self.metadata = Mock(spec=Metadata) def test_get_distance(self): """ Same test as DCAwareRoundRobinPolicyTest.test_get_distance() Except a FakeCluster is needed for the metadata variable and policy.child_policy is needed to change child policy settings """ policy = TokenAwarePolicy(DCAwareRoundRobinPolicy("dc1", used_hosts_per_remote_dc=0)) host = Host(DefaultEndPoint("ip1"), SimpleConvictionPolicy) host.set_location_info("dc1", "rack1") policy.populate(self.FakeCluster(), [host]) self.assertEqual(policy.distance(host), HostDistance.LOCAL) # used_hosts_per_remote_dc is set to 0, so ignore it remote_host = Host(DefaultEndPoint("ip2"), SimpleConvictionPolicy) remote_host.set_location_info("dc2", "rack1") self.assertEqual(policy.distance(remote_host), HostDistance.IGNORED) # dc2 isn't registered in the policy's live_hosts dict policy._child_policy.used_hosts_per_remote_dc = 1 self.assertEqual(policy.distance(remote_host), HostDistance.IGNORED) # make sure the policy has both dcs registered policy.populate(self.FakeCluster(), [host, remote_host]) self.assertEqual(policy.distance(remote_host), HostDistance.REMOTE) # since used_hosts_per_remote_dc is set to 1, only the first # remote host in dc2 will be REMOTE, the rest are IGNORED second_remote_host = Host(DefaultEndPoint("ip3"), SimpleConvictionPolicy) second_remote_host.set_location_info("dc2", "rack1") policy.populate(self.FakeCluster(), [host, remote_host, second_remote_host]) distances = set([policy.distance(remote_host), policy.distance(second_remote_host)]) self.assertEqual(distances, set([HostDistance.REMOTE, HostDistance.IGNORED])) def test_status_updates(self): """ Same test as DCAwareRoundRobinPolicyTest.test_status_updates() """ hosts = [Host(DefaultEndPoint(i), SimpleConvictionPolicy) for i in range(4)] for h in hosts[:2]: h.set_location_info("dc1", "rack1") for h in hosts[2:]: h.set_location_info("dc2", "rack1") policy = TokenAwarePolicy(DCAwareRoundRobinPolicy("dc1", used_hosts_per_remote_dc=1)) policy.populate(self.FakeCluster(), hosts) policy.on_down(hosts[0]) policy.on_remove(hosts[2]) new_local_host = Host(DefaultEndPoint(4), SimpleConvictionPolicy) new_local_host.set_location_info("dc1", "rack1") policy.on_up(new_local_host) new_remote_host = Host(DefaultEndPoint(5), SimpleConvictionPolicy) new_remote_host.set_location_info("dc9000", "rack1") policy.on_add(new_remote_host) # we now have two local hosts and two remote hosts in separate dcs qplan = list(policy.make_query_plan()) self.assertEqual(set(qplan[:2]), set([hosts[1], new_local_host])) self.assertEqual(set(qplan[2:]), set([hosts[3], new_remote_host])) # since we have hosts in dc9000, the distance shouldn't be IGNORED self.assertEqual(policy.distance(new_remote_host), HostDistance.REMOTE) policy.on_down(new_local_host) policy.on_down(hosts[1]) qplan = list(policy.make_query_plan()) self.assertEqual(set(qplan), set([hosts[3], new_remote_host])) policy.on_down(new_remote_host) policy.on_down(hosts[3]) qplan = list(policy.make_query_plan()) self.assertEqual(qplan, []) def test_statement_keyspace(self): hosts = [Host(DefaultEndPoint(str(i)), SimpleConvictionPolicy) for i in range(4)] for host in hosts: host.set_up() cluster = Mock(spec=Cluster) cluster.metadata = Mock(spec=Metadata) replicas = hosts[2:] cluster.metadata.get_replicas.return_value = replicas child_policy = Mock() child_policy.make_query_plan.return_value = hosts child_policy.distance.return_value = HostDistance.LOCAL policy = TokenAwarePolicy(child_policy) policy.populate(cluster, hosts) # no keyspace, child policy is called keyspace = None routing_key = 'routing_key' query = Statement(routing_key=routing_key) qplan = list(policy.make_query_plan(keyspace, query)) self.assertEqual(hosts, qplan) self.assertEqual(cluster.metadata.get_replicas.call_count, 0) child_policy.make_query_plan.assert_called_once_with(keyspace, query) # working keyspace, no statement cluster.metadata.get_replicas.reset_mock() keyspace = 'working_keyspace' routing_key = 'routing_key' query = Statement(routing_key=routing_key) qplan = list(policy.make_query_plan(keyspace, query)) self.assertEqual(replicas + hosts[:2], qplan) cluster.metadata.get_replicas.assert_called_with(keyspace, routing_key) # statement keyspace, no working cluster.metadata.get_replicas.reset_mock() working_keyspace = None statement_keyspace = 'statement_keyspace' routing_key = 'routing_key' query = Statement(routing_key=routing_key, keyspace=statement_keyspace) qplan = list(policy.make_query_plan(working_keyspace, query)) self.assertEqual(replicas + hosts[:2], qplan) cluster.metadata.get_replicas.assert_called_with(statement_keyspace, routing_key) # both keyspaces set, statement keyspace used for routing cluster.metadata.get_replicas.reset_mock() working_keyspace = 'working_keyspace' statement_keyspace = 'statement_keyspace' routing_key = 'routing_key' query = Statement(routing_key=routing_key, keyspace=statement_keyspace) qplan = list(policy.make_query_plan(working_keyspace, query)) self.assertEqual(replicas + hosts[:2], qplan) cluster.metadata.get_replicas.assert_called_with(statement_keyspace, routing_key) def test_shuffles_if_given_keyspace_and_routing_key(self): """ Test to validate the hosts are shuffled when `shuffle_replicas` is truthy @since 3.8 @jira_ticket PYTHON-676 @expected_result shuffle should be called, because the keyspace and the routing key are set @test_category policy """ self._assert_shuffle(keyspace='keyspace', routing_key='routing_key') def test_no_shuffle_if_given_no_keyspace(self): """ Test to validate the hosts are not shuffled when no keyspace is provided @since 3.8 @jira_ticket PYTHON-676 @expected_result shuffle should be called, because keyspace is None @test_category policy """ self._assert_shuffle(keyspace=None, routing_key='routing_key') def test_no_shuffle_if_given_no_routing_key(self): """ Test to validate the hosts are not shuffled when no routing_key is provided @since 3.8 @jira_ticket PYTHON-676 @expected_result shuffle should be called, because routing_key is None @test_category policy """ self._assert_shuffle(keyspace='keyspace', routing_key=None) @patch('cassandra.policies.shuffle') def _assert_shuffle(self, patched_shuffle, keyspace, routing_key): hosts = [Host(DefaultEndPoint(str(i)), SimpleConvictionPolicy) for i in range(4)] for host in hosts: host.set_up() cluster = Mock(spec=Cluster) cluster.metadata = Mock(spec=Metadata) replicas = hosts[2:] cluster.metadata.get_replicas.return_value = replicas child_policy = Mock() child_policy.make_query_plan.return_value = hosts child_policy.distance.return_value = HostDistance.LOCAL policy = TokenAwarePolicy(child_policy, shuffle_replicas=True) policy.populate(cluster, hosts) cluster.metadata.get_replicas.reset_mock() child_policy.make_query_plan.reset_mock() query = Statement(routing_key=routing_key) qplan = list(policy.make_query_plan(keyspace, query)) if keyspace is None or routing_key is None: self.assertEqual(hosts, qplan) self.assertEqual(cluster.metadata.get_replicas.call_count, 0) child_policy.make_query_plan.assert_called_once_with(keyspace, query) self.assertEqual(patched_shuffle.call_count, 0) else: self.assertEqual(set(replicas), set(qplan[:2])) self.assertEqual(hosts[:2], qplan[2:]) child_policy.make_query_plan.assert_called_once_with(keyspace, query) self.assertEqual(patched_shuffle.call_count, 1) class ConvictionPolicyTest(unittest.TestCase): def test_not_implemented(self): """ Code coverage for interface-style base class """ conviction_policy = ConvictionPolicy(1) self.assertRaises(NotImplementedError, conviction_policy.add_failure, 1) self.assertRaises(NotImplementedError, conviction_policy.reset) class SimpleConvictionPolicyTest(unittest.TestCase): def test_basic_responses(self): """ Code coverage for SimpleConvictionPolicy """ conviction_policy = SimpleConvictionPolicy(1) self.assertEqual(conviction_policy.add_failure(1), True) self.assertEqual(conviction_policy.reset(), None) class ReconnectionPolicyTest(unittest.TestCase): def test_basic_responses(self): """ Code coverage for interface-style base class """ policy = ReconnectionPolicy() self.assertRaises(NotImplementedError, policy.new_schedule) class ConstantReconnectionPolicyTest(unittest.TestCase): def test_bad_vals(self): """ Test initialization values """ self.assertRaises(ValueError, ConstantReconnectionPolicy, -1, 0) def test_schedule(self): """ Test ConstantReconnectionPolicy schedule """ delay = 2 max_attempts = 100 policy = ConstantReconnectionPolicy(delay=delay, max_attempts=max_attempts) schedule = list(policy.new_schedule()) self.assertEqual(len(schedule), max_attempts) for i, delay in enumerate(schedule): self.assertEqual(delay, delay) def test_schedule_negative_max_attempts(self): """ Test how negative max_attempts are handled """ delay = 2 max_attempts = -100 try: ConstantReconnectionPolicy(delay=delay, max_attempts=max_attempts) self.fail('max_attempts should throw ValueError when negative') except ValueError: pass def test_schedule_infinite_attempts(self): delay = 2 max_attempts = None crp = ConstantReconnectionPolicy(delay=delay, max_attempts=max_attempts) # this is infinite. we'll just verify one more than default for _, d in zip(range(65), crp.new_schedule()): self.assertEqual(d, delay) class ExponentialReconnectionPolicyTest(unittest.TestCase): def _assert_between(self, value, min, max): self.assertTrue(min <= value <= max) def test_bad_vals(self): self.assertRaises(ValueError, ExponentialReconnectionPolicy, -1, 0) self.assertRaises(ValueError, ExponentialReconnectionPolicy, 0, -1) self.assertRaises(ValueError, ExponentialReconnectionPolicy, 9000, 1) self.assertRaises(ValueError, ExponentialReconnectionPolicy, 1, 2, -1) def test_schedule_no_max(self): base_delay = 2.0 max_delay = 100.0 test_iter = 10000 policy = ExponentialReconnectionPolicy(base_delay=base_delay, max_delay=max_delay, max_attempts=None) sched_slice = list(islice(policy.new_schedule(), 0, test_iter)) self._assert_between(sched_slice[0], base_delay*0.85, base_delay*1.15) self._assert_between(sched_slice[-1], max_delay*0.85, max_delay*1.15) self.assertEqual(len(sched_slice), test_iter) def test_schedule_with_max(self): base_delay = 2.0 max_delay = 100.0 max_attempts = 64 policy = ExponentialReconnectionPolicy(base_delay=base_delay, max_delay=max_delay, max_attempts=max_attempts) schedule = list(policy.new_schedule()) self.assertEqual(len(schedule), max_attempts) for i, delay in enumerate(schedule): if i == 0: self._assert_between(delay, base_delay*0.85, base_delay*1.15) elif i < 6: value = base_delay * (2 ** i) self._assert_between(delay, value*85/100, value*1.15) else: self._assert_between(delay, max_delay*85/100, max_delay*1.15) def test_schedule_exactly_one_attempt(self): base_delay = 2.0 max_delay = 100.0 max_attempts = 1 policy = ExponentialReconnectionPolicy( base_delay=base_delay, max_delay=max_delay, max_attempts=max_attempts ) self.assertEqual(len(list(policy.new_schedule())), 1) def test_schedule_overflow(self): """ Test to verify an OverflowError is handled correctly in the ExponentialReconnectionPolicy @since 3.10 @jira_ticket PYTHON-707 @expected_result all numbers should be less than sys.float_info.max since that's the biggest max we can possibly have as that argument must be a float. Note that is possible for a float to be inf. @test_category policy """ # This should lead to overflow # Note that this may not happen in the fist iterations # as sys.float_info.max * 2 = inf base_delay = sys.float_info.max - 1 max_delay = sys.float_info.max max_attempts = 2**12 policy = ExponentialReconnectionPolicy(base_delay=base_delay, max_delay=max_delay, max_attempts=max_attempts) schedule = list(policy.new_schedule()) for number in schedule: self.assertLessEqual(number, sys.float_info.max) def test_schedule_with_jitter(self): """ Test to verify jitter is added properly and is always between -/+ 15%. @since 3.18 @jira_ticket PYTHON-1065 """ for i in range(100): base_delay = float(randint(2, 5)) max_delay = (base_delay - 1) * 100.0 ep = ExponentialReconnectionPolicy(base_delay, max_delay, max_attempts=64) schedule = ep.new_schedule() for i in range(64): exp_delay = min(base_delay * (2 ** i), max_delay) min_jitter_delay = max(base_delay, exp_delay*85/100) max_jitter_delay = min(max_delay, exp_delay*115/100) delay = next(schedule) self._assert_between(delay, min_jitter_delay, max_jitter_delay) ONE = ConsistencyLevel.ONE class RetryPolicyTest(unittest.TestCase): def test_read_timeout(self): policy = RetryPolicy() # if this is the second or greater attempt, rethrow retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=1, received_responses=2, data_retrieved=True, retry_num=1) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) # if we didn't get enough responses, rethrow retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=2, received_responses=1, data_retrieved=True, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) # if we got enough responses, but also got a data response, rethrow retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=2, received_responses=2, data_retrieved=True, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) # we got enough responses but no data response, so retry retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=2, received_responses=2, data_retrieved=False, retry_num=0) self.assertEqual(retry, RetryPolicy.RETRY) self.assertEqual(consistency, ONE) def test_write_timeout(self): policy = RetryPolicy() # if this is the second or greater attempt, rethrow retry, consistency = policy.on_write_timeout( query=None, consistency=ONE, write_type=WriteType.SIMPLE, required_responses=1, received_responses=2, retry_num=1) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) # if it's not a BATCH_LOG write, don't retry it retry, consistency = policy.on_write_timeout( query=None, consistency=ONE, write_type=WriteType.SIMPLE, required_responses=1, received_responses=2, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) # retry BATCH_LOG writes regardless of received responses retry, consistency = policy.on_write_timeout( query=None, consistency=ONE, write_type=WriteType.BATCH_LOG, required_responses=10000, received_responses=1, retry_num=0) self.assertEqual(retry, RetryPolicy.RETRY) self.assertEqual(consistency, ONE) def test_unavailable(self): """ Use the same tests for test_write_timeout, but ensure they only RETHROW """ policy = RetryPolicy() retry, consistency = policy.on_unavailable( query=None, consistency=ONE, required_replicas=1, alive_replicas=2, retry_num=1) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) retry, consistency = policy.on_unavailable( query=None, consistency=ONE, required_replicas=1, alive_replicas=2, retry_num=0) self.assertEqual(retry, RetryPolicy.RETRY_NEXT_HOST) self.assertEqual(consistency, None) retry, consistency = policy.on_unavailable( query=None, consistency=ONE, required_replicas=10000, alive_replicas=1, retry_num=0) self.assertEqual(retry, RetryPolicy.RETRY_NEXT_HOST) self.assertEqual(consistency, None) class FallthroughRetryPolicyTest(unittest.TestCase): """ Use the same tests for test_write_timeout, but ensure they only RETHROW """ def test_read_timeout(self): policy = FallthroughRetryPolicy() retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=1, received_responses=2, data_retrieved=True, retry_num=1) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=2, received_responses=1, data_retrieved=True, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=2, received_responses=2, data_retrieved=True, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=2, received_responses=2, data_retrieved=False, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) def test_write_timeout(self): policy = FallthroughRetryPolicy() retry, consistency = policy.on_write_timeout( query=None, consistency=ONE, write_type=WriteType.SIMPLE, required_responses=1, received_responses=2, retry_num=1) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) retry, consistency = policy.on_write_timeout( query=None, consistency=ONE, write_type=WriteType.SIMPLE, required_responses=1, received_responses=2, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) retry, consistency = policy.on_write_timeout( query=None, consistency=ONE, write_type=WriteType.BATCH_LOG, required_responses=10000, received_responses=1, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) def test_unavailable(self): policy = FallthroughRetryPolicy() retry, consistency = policy.on_unavailable( query=None, consistency=ONE, required_replicas=1, alive_replicas=2, retry_num=1) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) retry, consistency = policy.on_unavailable( query=None, consistency=ONE, required_replicas=1, alive_replicas=2, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) retry, consistency = policy.on_unavailable( query=None, consistency=ONE, required_replicas=10000, alive_replicas=1, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) class DowngradingConsistencyRetryPolicyTest(unittest.TestCase): def test_read_timeout(self): policy = DowngradingConsistencyRetryPolicy() # if this is the second or greater attempt, rethrow retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=1, received_responses=2, data_retrieved=True, retry_num=1) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) # if we didn't get enough responses, retry at a lower consistency retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=4, received_responses=3, data_retrieved=True, retry_num=0) self.assertEqual(retry, RetryPolicy.RETRY) self.assertEqual(consistency, ConsistencyLevel.THREE) # if we didn't get enough responses, retry at a lower consistency retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=3, received_responses=2, data_retrieved=True, retry_num=0) self.assertEqual(retry, RetryPolicy.RETRY) self.assertEqual(consistency, ConsistencyLevel.TWO) # retry consistency level goes down based on the # of recv'd responses retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=3, received_responses=1, data_retrieved=True, retry_num=0) self.assertEqual(retry, RetryPolicy.RETRY) self.assertEqual(consistency, ConsistencyLevel.ONE) # if we got no responses, rethrow retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=3, received_responses=0, data_retrieved=True, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) # if we got enough response but no data, retry retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=3, received_responses=3, data_retrieved=False, retry_num=0) self.assertEqual(retry, RetryPolicy.RETRY) self.assertEqual(consistency, ONE) # if we got enough responses, but also got a data response, rethrow retry, consistency = policy.on_read_timeout( query=None, consistency=ONE, required_responses=2, received_responses=2, data_retrieved=True, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) def test_write_timeout(self): policy = DowngradingConsistencyRetryPolicy() # if this is the second or greater attempt, rethrow retry, consistency = policy.on_write_timeout( query=None, consistency=ONE, write_type=WriteType.SIMPLE, required_responses=1, received_responses=2, retry_num=1) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) for write_type in (WriteType.SIMPLE, WriteType.BATCH, WriteType.COUNTER): # ignore failures if at least one response (replica persisted) retry, consistency = policy.on_write_timeout( query=None, consistency=ONE, write_type=write_type, required_responses=1, received_responses=2, retry_num=0) self.assertEqual(retry, RetryPolicy.IGNORE) # retrhow if we can't be sure we have a replica retry, consistency = policy.on_write_timeout( query=None, consistency=ONE, write_type=write_type, required_responses=1, received_responses=0, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) # downgrade consistency level on unlogged batch writes retry, consistency = policy.on_write_timeout( query=None, consistency=ONE, write_type=WriteType.UNLOGGED_BATCH, required_responses=3, received_responses=1, retry_num=0) self.assertEqual(retry, RetryPolicy.RETRY) self.assertEqual(consistency, ConsistencyLevel.ONE) # retry batch log writes at the same consistency level retry, consistency = policy.on_write_timeout( query=None, consistency=ONE, write_type=WriteType.BATCH_LOG, required_responses=3, received_responses=1, retry_num=0) self.assertEqual(retry, RetryPolicy.RETRY) self.assertEqual(consistency, ONE) # timeout on an unknown write_type retry, consistency = policy.on_write_timeout( query=None, consistency=ONE, write_type=None, required_responses=1, received_responses=2, retry_num=0) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) def test_unavailable(self): policy = DowngradingConsistencyRetryPolicy() # if this is the second or greater attempt, rethrow retry, consistency = policy.on_unavailable( query=None, consistency=ONE, required_replicas=3, alive_replicas=1, retry_num=1) self.assertEqual(retry, RetryPolicy.RETHROW) self.assertEqual(consistency, None) # downgrade consistency on unavailable exceptions retry, consistency = policy.on_unavailable( query=None, consistency=ONE, required_replicas=3, alive_replicas=1, retry_num=0) self.assertEqual(retry, RetryPolicy.RETRY) self.assertEqual(consistency, ConsistencyLevel.ONE) class WhiteListRoundRobinPolicyTest(unittest.TestCase): def test_hosts_with_hostname(self): hosts = ['localhost'] policy = WhiteListRoundRobinPolicy(hosts) host = Host(DefaultEndPoint("127.0.0.1"), SimpleConvictionPolicy) policy.populate(None, [host]) qplan = list(policy.make_query_plan()) self.assertEqual(sorted(qplan), [host]) self.assertEqual(policy.distance(host), HostDistance.LOCAL) class AddressTranslatorTest(unittest.TestCase): def test_identity_translator(self): IdentityTranslator() @patch('socket.getfqdn', return_value='localhost') def test_ec2_multi_region_translator(self, *_): ec2t = EC2MultiRegionTranslator() addr = '127.0.0.1' translated = ec2t.translate(addr) self.assertIsNot(translated, addr) # verifies that the resolver path is followed self.assertEqual(translated, addr) # and that it resolves to the same address class HostFilterPolicyInitTest(unittest.TestCase): def setUp(self): self.child_policy, self.predicate = (Mock(name='child_policy'), Mock(name='predicate')) def _check_init(self, hfp): self.assertIs(hfp._child_policy, self.child_policy) self.assertIsInstance(hfp._hosts_lock, LockType) # we can't use a simple assertIs because we wrap the function arg0, arg1 = Mock(name='arg0'), Mock(name='arg1') hfp.predicate(arg0) hfp.predicate(arg1) self.predicate.assert_has_calls([call(arg0), call(arg1)]) def test_init_arg_order(self): self._check_init(HostFilterPolicy(self.child_policy, self.predicate)) def test_init_kwargs(self): self._check_init(HostFilterPolicy( predicate=self.predicate, child_policy=self.child_policy )) def test_immutable_predicate(self): expected_message_regex = "can't set attribute" hfp = HostFilterPolicy(child_policy=Mock(name='child_policy'), predicate=Mock(name='predicate')) with self.assertRaisesRegexp(AttributeError, expected_message_regex): hfp.predicate = object() class HostFilterPolicyDeferralTest(unittest.TestCase): def setUp(self): self.passthrough_hfp = HostFilterPolicy( child_policy=Mock(name='child_policy'), predicate=Mock(name='passthrough_predicate', return_value=True) ) self.filterall_hfp = HostFilterPolicy( child_policy=Mock(name='child_policy'), predicate=Mock(name='filterall_predicate', return_value=False) ) def _check_host_triggered_method(self, policy, name): arg, kwarg = Mock(name='arg'), Mock(name='kwarg') method, child_policy_method = (getattr(policy, name), getattr(policy._child_policy, name)) result = method(arg, kw=kwarg) # method calls the child policy's method... child_policy_method.assert_called_once_with(arg, kw=kwarg) # and returns its return value self.assertIs(result, child_policy_method.return_value) def test_defer_on_up_to_child_policy(self): self._check_host_triggered_method(self.passthrough_hfp, 'on_up') def test_defer_on_down_to_child_policy(self): self._check_host_triggered_method(self.passthrough_hfp, 'on_down') def test_defer_on_add_to_child_policy(self): self._check_host_triggered_method(self.passthrough_hfp, 'on_add') def test_defer_on_remove_to_child_policy(self): self._check_host_triggered_method(self.passthrough_hfp, 'on_remove') def test_filtered_host_on_up_doesnt_call_child_policy(self): self._check_host_triggered_method(self.filterall_hfp, 'on_up') def test_filtered_host_on_down_doesnt_call_child_policy(self): self._check_host_triggered_method(self.filterall_hfp, 'on_down') def test_filtered_host_on_add_doesnt_call_child_policy(self): self._check_host_triggered_method(self.filterall_hfp, 'on_add') def test_filtered_host_on_remove_doesnt_call_child_policy(self): self._check_host_triggered_method(self.filterall_hfp, 'on_remove') def _check_check_supported_deferral(self, policy): policy.check_supported() policy._child_policy.check_supported.assert_called_once() def test_check_supported_defers_to_child(self): self._check_check_supported_deferral(self.passthrough_hfp) def test_check_supported_defers_to_child_when_predicate_filtered(self): self._check_check_supported_deferral(self.filterall_hfp) class HostFilterPolicyDistanceTest(unittest.TestCase): def setUp(self): self.hfp = HostFilterPolicy( child_policy=Mock(name='child_policy', distance=Mock(name='distance')), predicate=lambda host: host.address == 'acceptme' ) self.ignored_host = Host(DefaultEndPoint('ignoreme'), conviction_policy_factory=Mock()) self.accepted_host = Host(DefaultEndPoint('acceptme'), conviction_policy_factory=Mock()) def test_ignored_with_filter(self): self.assertEqual(self.hfp.distance(self.ignored_host), HostDistance.IGNORED) self.assertNotEqual(self.hfp.distance(self.accepted_host), HostDistance.IGNORED) def test_accepted_filter_defers_to_child_policy(self): self.hfp._child_policy.distance.side_effect = distances = Mock(), Mock() # getting the distance for an ignored host shouldn't affect subsequent results self.hfp.distance(self.ignored_host) # first call of _child_policy with count() side effect self.assertEqual(self.hfp.distance(self.accepted_host), distances[0]) # second call of _child_policy with count() side effect self.assertEqual(self.hfp.distance(self.accepted_host), distances[1]) class HostFilterPolicyPopulateTest(unittest.TestCase): def test_populate_deferred_to_child(self): hfp = HostFilterPolicy( child_policy=Mock(name='child_policy'), predicate=lambda host: True ) mock_cluster, hosts = (Mock(name='cluster'), ['host1', 'host2', 'host3']) hfp.populate(mock_cluster, hosts) hfp._child_policy.populate.assert_called_once_with( cluster=mock_cluster, hosts=hosts ) def test_child_is_populated_with_filtered_hosts(self): hfp = HostFilterPolicy( child_policy=Mock(name='child_policy'), predicate=lambda host: False ) mock_cluster, hosts = (Mock(name='cluster'), ['acceptme0', 'acceptme1']) hfp.populate(mock_cluster, hosts) hfp._child_policy.populate.assert_called_once() self.assertEqual( hfp._child_policy.populate.call_args[1]['hosts'], ['acceptme0', 'acceptme1'] ) class HostFilterPolicyQueryPlanTest(unittest.TestCase): def test_query_plan_deferred_to_child(self): child_policy = Mock( name='child_policy', make_query_plan=Mock( return_value=[object(), object(), object()] ) ) hfp = HostFilterPolicy( child_policy=child_policy, predicate=lambda host: True ) working_keyspace, query = (Mock(name='working_keyspace'), Mock(name='query')) qp = list(hfp.make_query_plan(working_keyspace=working_keyspace, query=query)) hfp._child_policy.make_query_plan.assert_called_once_with( working_keyspace=working_keyspace, query=query ) self.assertEqual(qp, hfp._child_policy.make_query_plan.return_value) def test_wrap_token_aware(self): cluster = Mock(spec=Cluster) hosts = [Host(DefaultEndPoint("127.0.0.{}".format(i)), SimpleConvictionPolicy) for i in range(1, 6)] for host in hosts: host.set_up() def get_replicas(keyspace, packed_key): return hosts[:2] cluster.metadata.get_replicas.side_effect = get_replicas child_policy = TokenAwarePolicy(RoundRobinPolicy()) hfp = HostFilterPolicy( child_policy=child_policy, predicate=lambda host: host.address != "127.0.0.1" and host.address != "127.0.0.4" ) hfp.populate(cluster, hosts) # We don't allow randomness for ordering the replicas in RoundRobin hfp._child_policy._child_policy._position = 0 mocked_query = Mock() query_plan = hfp.make_query_plan("keyspace", mocked_query) # First the not filtered replica, and then the rest of the allowed hosts ordered query_plan = list(query_plan) self.assertEqual(query_plan[0], Host(DefaultEndPoint("127.0.0.2"), SimpleConvictionPolicy)) self.assertEqual(set(query_plan[1:]),{Host(DefaultEndPoint("127.0.0.3"), SimpleConvictionPolicy), Host(DefaultEndPoint("127.0.0.5"), SimpleConvictionPolicy)}) def test_create_whitelist(self): cluster = Mock(spec=Cluster) hosts = [Host(DefaultEndPoint("127.0.0.{}".format(i)), SimpleConvictionPolicy) for i in range(1, 6)] for host in hosts: host.set_up() child_policy = RoundRobinPolicy() hfp = HostFilterPolicy( child_policy=child_policy, predicate=lambda host: host.address == "127.0.0.1" or host.address == "127.0.0.4" ) hfp.populate(cluster, hosts) # We don't allow randomness for ordering the replicas in RoundRobin hfp._child_policy._position = 0 mocked_query = Mock() query_plan = hfp.make_query_plan("keyspace", mocked_query) # Only the filtered replicas should be allowed self.assertEqual(set(query_plan), {Host(DefaultEndPoint("127.0.0.1"), SimpleConvictionPolicy), Host(DefaultEndPoint("127.0.0.4"), SimpleConvictionPolicy)}) diff --git a/tests/unit/test_protocol.py b/tests/unit/test_protocol.py index 21223d2..b43b21e 100644 --- a/tests/unit/test_protocol.py +++ b/tests/unit/test_protocol.py @@ -1,174 +1,232 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + try: import unittest2 as unittest except ImportError: import unittest # noqa from mock import Mock + from cassandra import ProtocolVersion, UnsupportedOperation -from cassandra.protocol import (PrepareMessage, QueryMessage, ExecuteMessage, - BatchMessage) -from cassandra.query import SimpleStatement, BatchType +from cassandra.protocol import ( + PrepareMessage, QueryMessage, ExecuteMessage, UnsupportedOperation, + _PAGING_OPTIONS_FLAG, _WITH_SERIAL_CONSISTENCY_FLAG, + _PAGE_SIZE_FLAG, _WITH_PAGING_STATE_FLAG, + BatchMessage +) +from cassandra.query import BatchType +from cassandra.marshal import uint32_unpack +from cassandra.cluster import ContinuousPagingOptions + class MessageTest(unittest.TestCase): def test_prepare_message(self): """ Test to check the appropriate calls are made @since 3.9 @jira_ticket PYTHON-713 @expected_result the values are correctly written @test_category connection """ message = PrepareMessage("a") io = Mock() message.send_body(io, 4) self._check_calls(io, [(b'\x00\x00\x00\x01',), (b'a',)]) io.reset_mock() message.send_body(io, 5) self._check_calls(io, [(b'\x00\x00\x00\x01',), (b'a',), (b'\x00\x00\x00\x00',)]) def test_execute_message(self): message = ExecuteMessage('1', [], 4) io = Mock() message.send_body(io, 4) self._check_calls(io, [(b'\x00\x01',), (b'1',), (b'\x00\x04',), (b'\x01',), (b'\x00\x00',)]) io.reset_mock() message.result_metadata_id = 'foo' message.send_body(io, 5) self._check_calls(io, [(b'\x00\x01',), (b'1',), (b'\x00\x03',), (b'foo',), (b'\x00\x04',), (b'\x00\x00\x00\x01',), (b'\x00\x00',)]) def test_query_message(self): """ Test to check the appropriate calls are made @since 3.9 @jira_ticket PYTHON-713 @expected_result the values are correctly written @test_category connection """ message = QueryMessage("a", 3) io = Mock() message.send_body(io, 4) self._check_calls(io, [(b'\x00\x00\x00\x01',), (b'a',), (b'\x00\x03',), (b'\x00',)]) io.reset_mock() message.send_body(io, 5) self._check_calls(io, [(b'\x00\x00\x00\x01',), (b'a',), (b'\x00\x03',), (b'\x00\x00\x00\x00',)]) def _check_calls(self, io, expected): self.assertEqual( tuple(c[1] for c in io.write.mock_calls), tuple(expected) ) + def test_continuous_paging(self): + """ + Test to check continuous paging throws an Exception if it's not supported and the correct valuesa + are written to the buffer if the option is enabled. + + @since DSE 2.0b3 GRAPH 1.0b1 + @jira_ticket PYTHON-694 + @expected_result the values are correctly written + + @test_category connection + """ + max_pages = 4 + max_pages_per_second = 3 + continuous_paging_options = ContinuousPagingOptions(max_pages=max_pages, + max_pages_per_second=max_pages_per_second) + message = QueryMessage("a", 3, continuous_paging_options=continuous_paging_options) + io = Mock() + for version in [version for version in ProtocolVersion.SUPPORTED_VERSIONS + if not ProtocolVersion.has_continuous_paging_support(version)]: + self.assertRaises(UnsupportedOperation, message.send_body, io, version) + + io.reset_mock() + message.send_body(io, ProtocolVersion.DSE_V1) + + # continuous paging adds two write calls to the buffer + self.assertEqual(len(io.write.mock_calls), 6) + # Check that the appropriate flag is set to True + self.assertEqual(uint32_unpack(io.write.mock_calls[3][1][0]) & _WITH_SERIAL_CONSISTENCY_FLAG, 0) + self.assertEqual(uint32_unpack(io.write.mock_calls[3][1][0]) & _PAGE_SIZE_FLAG, 0) + self.assertEqual(uint32_unpack(io.write.mock_calls[3][1][0]) & _WITH_PAGING_STATE_FLAG, 0) + self.assertEqual(uint32_unpack(io.write.mock_calls[3][1][0]) & _PAGING_OPTIONS_FLAG, _PAGING_OPTIONS_FLAG) + + # Test max_pages and max_pages_per_second are correctly written + self.assertEqual(uint32_unpack(io.write.mock_calls[4][1][0]), max_pages) + self.assertEqual(uint32_unpack(io.write.mock_calls[5][1][0]), max_pages_per_second) + def test_prepare_flag(self): """ Test to check the prepare flag is properly set, This should only happen for V5 at the moment. @since 3.9 - @jira_ticket PYTHON-713 + @jira_ticket PYTHON-694, PYTHON-713 @expected_result the values are correctly written @test_category connection """ message = PrepareMessage("a") io = Mock() for version in ProtocolVersion.SUPPORTED_VERSIONS: message.send_body(io, version) if ProtocolVersion.uses_prepare_flags(version): self.assertEqual(len(io.write.mock_calls), 3) else: self.assertEqual(len(io.write.mock_calls), 2) io.reset_mock() def test_prepare_flag_with_keyspace(self): message = PrepareMessage("a", keyspace='ks') io = Mock() for version in ProtocolVersion.SUPPORTED_VERSIONS: if ProtocolVersion.uses_keyspace_flag(version): message.send_body(io, version) self._check_calls(io, [ (b'\x00\x00\x00\x01',), (b'a',), (b'\x00\x00\x00\x01',), (b'\x00\x02',), (b'ks',), ]) else: with self.assertRaises(UnsupportedOperation): message.send_body(io, version) io.reset_mock() def test_keyspace_flag_raises_before_v5(self): keyspace_message = QueryMessage('a', consistency_level=3, keyspace='ks') io = Mock(name='io') with self.assertRaisesRegexp(UnsupportedOperation, 'Keyspaces.*set'): keyspace_message.send_body(io, protocol_version=4) io.assert_not_called() def test_keyspace_written_with_length(self): io = Mock(name='io') base_expected = [ (b'\x00\x00\x00\x01',), (b'a',), (b'\x00\x03',), (b'\x00\x00\x00\x80',), # options w/ keyspace flag ] QueryMessage('a', consistency_level=3, keyspace='ks').send_body( io, protocol_version=5 ) self._check_calls(io, base_expected + [ (b'\x00\x02',), # length of keyspace string (b'ks',), ]) io.reset_mock() QueryMessage('a', consistency_level=3, keyspace='keyspace').send_body( io, protocol_version=5 ) self._check_calls(io, base_expected + [ (b'\x00\x08',), # length of keyspace string (b'keyspace',), ]) def test_batch_message_with_keyspace(self): self.maxDiff = None io = Mock(name='io') batch = BatchMessage( batch_type=BatchType.LOGGED, queries=((False, 'stmt a', ('param a',)), (False, 'stmt b', ('param b',)), (False, 'stmt c', ('param c',)) ), consistency_level=3, keyspace='ks' ) batch.send_body(io, protocol_version=5) self._check_calls(io, ((b'\x00',), (b'\x00\x03',), (b'\x00',), (b'\x00\x00\x00\x06',), (b'stmt a',), (b'\x00\x01',), (b'\x00\x00\x00\x07',), ('param a',), (b'\x00',), (b'\x00\x00\x00\x06',), (b'stmt b',), (b'\x00\x01',), (b'\x00\x00\x00\x07',), ('param b',), (b'\x00',), (b'\x00\x00\x00\x06',), (b'stmt c',), (b'\x00\x01',), (b'\x00\x00\x00\x07',), ('param c',), (b'\x00\x03',), (b'\x00\x00\x00\x80',), (b'\x00\x02',), (b'ks',)) ) diff --git a/tests/unit/test_response_future.py b/tests/unit/test_response_future.py index 87f1bd6..98d2156 100644 --- a/tests/unit/test_response_future.py +++ b/tests/unit/test_response_future.py @@ -1,574 +1,606 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa from mock import Mock, MagicMock, ANY from cassandra import ConsistencyLevel, Unavailable, SchemaTargetType, SchemaChangeType, OperationTimedOut from cassandra.cluster import Session, ResponseFuture, NoHostAvailable, ProtocolVersion from cassandra.connection import Connection, ConnectionException from cassandra.protocol import (ReadTimeoutErrorMessage, WriteTimeoutErrorMessage, UnavailableErrorMessage, ResultMessage, QueryMessage, OverloadedErrorMessage, IsBootstrappingErrorMessage, PreparedQueryNotFound, PrepareMessage, RESULT_KIND_ROWS, RESULT_KIND_SET_KEYSPACE, RESULT_KIND_SCHEMA_CHANGE, RESULT_KIND_PREPARED, ProtocolHandler) from cassandra.policies import RetryPolicy from cassandra.pool import NoConnectionsAvailable from cassandra.query import SimpleStatement class ResponseFutureTests(unittest.TestCase): def make_basic_session(self): - return Mock(spec=Session, row_factory=lambda *x: list(x)) + s = Mock(spec=Session) + s.row_factory = lambda col_names, rows: [(col_names, rows)] + return s def make_pool(self): pool = Mock() pool.is_shutdown = False pool.borrow_connection.return_value = [Mock(), Mock()] return pool def make_session(self): session = self.make_basic_session() session.cluster._default_load_balancing_policy.make_query_plan.return_value = ['ip1', 'ip2'] session._pools.get.return_value = self.make_pool() return session def make_response_future(self, session): query = SimpleStatement("SELECT * FROM foo") message = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE) return ResponseFuture(session, message, query, 1) - def make_mock_response(self, results): - return Mock(spec=ResultMessage, kind=RESULT_KIND_ROWS, results=results, paging_state=None, col_types=None) + def make_mock_response(self, col_names, rows): + return Mock(spec=ResultMessage, kind=RESULT_KIND_ROWS, column_names=col_names, parsed_rows=rows, paging_state=None, col_types=None) def test_result_message(self): session = self.make_basic_session() session.cluster._default_load_balancing_policy.make_query_plan.return_value = ['ip1', 'ip2'] pool = session._pools.get.return_value pool.is_shutdown = False connection = Mock(spec=Connection) pool.borrow_connection.return_value = (connection, 1) rf = self.make_response_future(session) rf.send_request() rf.session._pools.get.assert_called_once_with('ip1') pool.borrow_connection.assert_called_once_with(timeout=ANY) connection.send_msg.assert_called_once_with(rf.message, 1, cb=ANY, encoder=ProtocolHandler.encode_message, decoder=ProtocolHandler.decode_message, result_metadata=[]) - rf._set_result(None, None, None, self.make_mock_response([{'col': 'val'}])) - result = rf.result() - self.assertEqual(result, [{'col': 'val'}]) + expected_result = (object(), object()) + rf._set_result(None, None, None, self.make_mock_response(expected_result[0], expected_result[1])) + result = rf.result()[0] + self.assertEqual(result, expected_result) def test_unknown_result_class(self): session = self.make_session() pool = session._pools.get.return_value connection = Mock(spec=Connection) pool.borrow_connection.return_value = (connection, 1) rf = self.make_response_future(session) rf.send_request() rf._set_result(None, None, None, object()) self.assertRaises(ConnectionException, rf.result) def test_set_keyspace_result(self): session = self.make_session() rf = self.make_response_future(session) rf.send_request() result = Mock(spec=ResultMessage, kind=RESULT_KIND_SET_KEYSPACE, results="keyspace1") rf._set_result(None, None, None, result) rf._set_keyspace_completed({}) self.assertFalse(rf.result()) def test_schema_change_result(self): session = self.make_session() rf = self.make_response_future(session) rf.send_request() event_results={'target_type': SchemaTargetType.TABLE, 'change_type': SchemaChangeType.CREATED, 'keyspace': "keyspace1", "table": "table1"} result = Mock(spec=ResultMessage, kind=RESULT_KIND_SCHEMA_CHANGE, - results=event_results) + schema_change_event=event_results) connection = Mock() rf._set_result(None, connection, None, result) session.submit.assert_called_once_with(ANY, ANY, rf, connection, **event_results) def test_other_result_message_kind(self): session = self.make_session() rf = self.make_response_future(session) rf.send_request() - result = [1, 2, 3] - rf._set_result(None, None, None, Mock(spec=ResultMessage, kind=999, results=result)) - self.assertListEqual(list(rf.result()), result) + result = Mock(spec=ResultMessage, kind=999, results=[1, 2, 3]) + rf._set_result(None, None, None, result) + self.assertEqual(rf.result()[0], result) def test_heartbeat_defunct_deadlock(self): """ Heartbeat defuncts all connections and clears request queues. Response future times out and even if it has been removed from request queue, timeout exception must be thrown. Otherwise event loop will deadlock on eventual ResponseFuture.result() call. PYTHON-1044 """ connection = MagicMock(spec=Connection) connection._requests = {} pool = Mock() pool.is_shutdown = False pool.borrow_connection.return_value = [connection, 1] session = self.make_basic_session() session.cluster._default_load_balancing_policy.make_query_plan.return_value = [Mock(), Mock()] session._pools.get.return_value = pool query = SimpleStatement("SELECT * FROM foo") message = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE) rf = ResponseFuture(session, message, query, 1) rf.send_request() # Simulate Connection.error_all_requests() after heartbeat defuncts connection._requests = {} # Simulate ResponseFuture timing out rf._on_timeout() self.assertRaisesRegexp(OperationTimedOut, "Connection defunct by heartbeat", rf.result) def test_read_timeout_error_message(self): session = self.make_session() query = SimpleStatement("SELECT * FROM foo") message = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE) rf = ResponseFuture(session, message, query, 1) rf.send_request() result = Mock(spec=ReadTimeoutErrorMessage, info={"data_retrieved": "", "required_responses":2, "received_responses":1, "consistency": 1}) rf._set_result(None, None, None, result) self.assertRaises(Exception, rf.result) def test_write_timeout_error_message(self): session = self.make_session() query = SimpleStatement("INSERT INFO foo (a, b) VALUES (1, 2)") message = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE) rf = ResponseFuture(session, message, query, 1) rf.send_request() result = Mock(spec=WriteTimeoutErrorMessage, info={"write_type": 1, "required_responses":2, "received_responses":1, "consistency": 1}) rf._set_result(None, None, None, result) self.assertRaises(Exception, rf.result) def test_unavailable_error_message(self): session = self.make_session() query = SimpleStatement("INSERT INFO foo (a, b) VALUES (1, 2)") query.retry_policy = Mock() query.retry_policy.on_unavailable.return_value = (RetryPolicy.RETHROW, None) message = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE) rf = ResponseFuture(session, message, query, 1) rf._query_retries = 1 rf.send_request() result = Mock(spec=UnavailableErrorMessage, info={"required_replicas":2, "alive_replicas": 1, "consistency": 1}) rf._set_result(None, None, None, result) self.assertRaises(Exception, rf.result) + def test_request_error_with_prepare_message(self): + session = self.make_session() + query = SimpleStatement("SELECT * FROM foobar") + retry_policy = Mock() + retry_policy.on_request_error.return_value = (RetryPolicy.RETHROW, None) + message = PrepareMessage(query=query) + + rf = ResponseFuture(session, message, query, 1, retry_policy=retry_policy) + rf._query_retries = 1 + rf.send_request() + result = Mock(spec=OverloadedErrorMessage) + result.to_exception.return_value = result + rf._set_result(None, None, None, result) + self.assertIsInstance(rf._final_exception, OverloadedErrorMessage) + + rf = ResponseFuture(session, message, query, 1, retry_policy=retry_policy) + rf._query_retries = 1 + rf.send_request() + result = Mock(spec=ConnectionException) + rf._set_result(None, None, None, result) + self.assertIsInstance(rf._final_exception, ConnectionException) + def test_retry_policy_says_ignore(self): session = self.make_session() query = SimpleStatement("INSERT INFO foo (a, b) VALUES (1, 2)") message = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE) retry_policy = Mock() retry_policy.on_unavailable.return_value = (RetryPolicy.IGNORE, None) rf = ResponseFuture(session, message, query, 1, retry_policy=retry_policy) rf.send_request() result = Mock(spec=UnavailableErrorMessage, info={}) rf._set_result(None, None, None, result) self.assertFalse(rf.result()) def test_retry_policy_says_retry(self): session = self.make_session() pool = session._pools.get.return_value query = SimpleStatement("INSERT INFO foo (a, b) VALUES (1, 2)") message = QueryMessage(query=query, consistency_level=ConsistencyLevel.QUORUM) connection = Mock(spec=Connection) pool.borrow_connection.return_value = (connection, 1) retry_policy = Mock() retry_policy.on_unavailable.return_value = (RetryPolicy.RETRY, ConsistencyLevel.ONE) rf = ResponseFuture(session, message, query, 1, retry_policy=retry_policy) rf.send_request() rf.session._pools.get.assert_called_once_with('ip1') pool.borrow_connection.assert_called_once_with(timeout=ANY) connection.send_msg.assert_called_once_with(rf.message, 1, cb=ANY, encoder=ProtocolHandler.encode_message, decoder=ProtocolHandler.decode_message, result_metadata=[]) result = Mock(spec=UnavailableErrorMessage, info={}) host = Mock() rf._set_result(host, None, None, result) session.submit.assert_called_once_with(rf._retry_task, True, host) self.assertEqual(1, rf._query_retries) connection = Mock(spec=Connection) pool.borrow_connection.return_value = (connection, 2) # simulate the executor running this rf._retry_task(True, host) # it should try again with the same host since this was # an UnavailableException rf.session._pools.get.assert_called_with(host) pool.borrow_connection.assert_called_with(timeout=ANY) connection.send_msg.assert_called_with(rf.message, 2, cb=ANY, encoder=ProtocolHandler.encode_message, decoder=ProtocolHandler.decode_message, result_metadata=[]) def test_retry_with_different_host(self): session = self.make_session() pool = session._pools.get.return_value connection = Mock(spec=Connection) pool.borrow_connection.return_value = (connection, 1) rf = self.make_response_future(session) rf.message.consistency_level = ConsistencyLevel.QUORUM rf.send_request() rf.session._pools.get.assert_called_once_with('ip1') pool.borrow_connection.assert_called_once_with(timeout=ANY) connection.send_msg.assert_called_once_with(rf.message, 1, cb=ANY, encoder=ProtocolHandler.encode_message, decoder=ProtocolHandler.decode_message, result_metadata=[]) self.assertEqual(ConsistencyLevel.QUORUM, rf.message.consistency_level) result = Mock(spec=OverloadedErrorMessage, info={}) host = Mock() rf._set_result(host, None, None, result) session.submit.assert_called_once_with(rf._retry_task, False, host) # query_retries does get incremented for Overloaded/Bootstrapping errors (since 3.18) self.assertEqual(1, rf._query_retries) connection = Mock(spec=Connection) pool.borrow_connection.return_value = (connection, 2) # simulate the executor running this rf._retry_task(False, host) # it should try with a different host rf.session._pools.get.assert_called_with('ip2') pool.borrow_connection.assert_called_with(timeout=ANY) connection.send_msg.assert_called_with(rf.message, 2, cb=ANY, encoder=ProtocolHandler.encode_message, decoder=ProtocolHandler.decode_message, result_metadata=[]) # the consistency level should be the same self.assertEqual(ConsistencyLevel.QUORUM, rf.message.consistency_level) def test_all_retries_fail(self): session = self.make_session() pool = session._pools.get.return_value connection = Mock(spec=Connection) pool.borrow_connection.return_value = (connection, 1) rf = self.make_response_future(session) rf.send_request() rf.session._pools.get.assert_called_once_with('ip1') result = Mock(spec=IsBootstrappingErrorMessage, info={}) host = Mock() rf._set_result(host, None, None, result) # simulate the executor running this session.submit.assert_called_once_with(rf._retry_task, False, host) rf._retry_task(False, host) # it should try with a different host rf.session._pools.get.assert_called_with('ip2') result = Mock(spec=IsBootstrappingErrorMessage, info={}) rf._set_result(host, None, None, result) # simulate the executor running this session.submit.assert_called_with(rf._retry_task, False, host) rf._retry_task(False, host) self.assertRaises(NoHostAvailable, rf.result) def test_all_pools_shutdown(self): session = self.make_basic_session() session.cluster._default_load_balancing_policy.make_query_plan.return_value = ['ip1', 'ip2'] session._pools.get.return_value.is_shutdown = True rf = ResponseFuture(session, Mock(), Mock(), 1) rf.send_request() self.assertRaises(NoHostAvailable, rf.result) def test_first_pool_shutdown(self): session = self.make_basic_session() session.cluster._default_load_balancing_policy.make_query_plan.return_value = ['ip1', 'ip2'] # first return a pool with is_shutdown=True, then is_shutdown=False pool_shutdown = self.make_pool() pool_shutdown.is_shutdown = True pool_ok = self.make_pool() pool_ok.is_shutdown = True session._pools.get.side_effect = [pool_shutdown, pool_ok] rf = self.make_response_future(session) rf.send_request() - rf._set_result(None, None, None, self.make_mock_response([{'col': 'val'}])) + expected_result = (object(), object()) + rf._set_result(None, None, None, self.make_mock_response(expected_result[0], expected_result[1])) - result = rf.result() - self.assertEqual(result, [{'col': 'val'}]) + result = rf.result()[0] + self.assertEqual(result, expected_result) def test_timeout_getting_connection_from_pool(self): session = self.make_basic_session() session.cluster._default_load_balancing_policy.make_query_plan.return_value = ['ip1', 'ip2'] # the first pool will raise an exception on borrow_connection() exc = NoConnectionsAvailable() first_pool = Mock(is_shutdown=False) first_pool.borrow_connection.side_effect = exc # the second pool will return a connection second_pool = Mock(is_shutdown=False) connection = Mock(spec=Connection) second_pool.borrow_connection.return_value = (connection, 1) session._pools.get.side_effect = [first_pool, second_pool] rf = self.make_response_future(session) rf.send_request() - rf._set_result(None, None, None, self.make_mock_response([{'col': 'val'}])) - self.assertEqual(rf.result(), [{'col': 'val'}]) + expected_result = (object(), object()) + rf._set_result(None, None, None, self.make_mock_response(expected_result[0], expected_result[1])) + self.assertEqual(rf.result()[0], expected_result) # make sure the exception is recorded correctly self.assertEqual(rf._errors, {'ip1': exc}) def test_callback(self): session = self.make_session() rf = self.make_response_future(session) rf.send_request() callback = Mock() - expected_result = [{'col': 'val'}] + expected_result = (object(), object()) arg = "positional" kwargs = {'one': 1, 'two': 2} rf.add_callback(callback, arg, **kwargs) - rf._set_result(None, None, None, self.make_mock_response(expected_result)) + rf._set_result(None, None, None, self.make_mock_response(expected_result[0], expected_result[1])) - result = rf.result() + result = rf.result()[0] self.assertEqual(result, expected_result) - callback.assert_called_once_with(expected_result, arg, **kwargs) + callback.assert_called_once_with([expected_result], arg, **kwargs) # this should get called immediately now that the result is set - rf.add_callback(self.assertEqual, [{'col': 'val'}]) + rf.add_callback(self.assertEqual, [expected_result]) def test_errback(self): session = self.make_session() pool = session._pools.get.return_value connection = Mock(spec=Connection) pool.borrow_connection.return_value = (connection, 1) query = SimpleStatement("INSERT INFO foo (a, b) VALUES (1, 2)") message = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE) rf = ResponseFuture(session, message, query, 1) rf._query_retries = 1 rf.send_request() rf.add_errback(self.assertIsInstance, Exception) result = Mock(spec=UnavailableErrorMessage, info={"required_replicas":2, "alive_replicas": 1, "consistency": 1}) result.to_exception.return_value = Exception() rf._set_result(None, None, None, result) self.assertRaises(Exception, rf.result) # this should get called immediately now that the error is set rf.add_errback(self.assertIsInstance, Exception) def test_multiple_callbacks(self): session = self.make_session() rf = self.make_response_future(session) rf.send_request() callback = Mock() - expected_result = [{'col': 'val'}] + expected_result = (object(), object()) arg = "positional" kwargs = {'one': 1, 'two': 2} rf.add_callback(callback, arg, **kwargs) callback2 = Mock() arg2 = "another" kwargs2 = {'three': 3, 'four': 4} rf.add_callback(callback2, arg2, **kwargs2) - rf._set_result(None, None, None, self.make_mock_response(expected_result)) + rf._set_result(None, None, None, self.make_mock_response(expected_result[0], expected_result[1])) - result = rf.result() + result = rf.result()[0] self.assertEqual(result, expected_result) - callback.assert_called_once_with(expected_result, arg, **kwargs) - callback2.assert_called_once_with(expected_result, arg2, **kwargs2) + callback.assert_called_once_with([expected_result], arg, **kwargs) + callback2.assert_called_once_with([expected_result], arg2, **kwargs2) def test_multiple_errbacks(self): session = self.make_session() pool = session._pools.get.return_value connection = Mock(spec=Connection) pool.borrow_connection.return_value = (connection, 1) query = SimpleStatement("INSERT INFO foo (a, b) VALUES (1, 2)") message = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE) retry_policy = Mock() retry_policy.on_unavailable.return_value = (RetryPolicy.RETHROW, None) rf = ResponseFuture(session, message, query, 1, retry_policy=retry_policy) rf.send_request() callback = Mock() arg = "positional" kwargs = {'one': 1, 'two': 2} rf.add_errback(callback, arg, **kwargs) callback2 = Mock() arg2 = "another" kwargs2 = {'three': 3, 'four': 4} rf.add_errback(callback2, arg2, **kwargs2) expected_exception = Unavailable("message", 1, 2, 3) result = Mock(spec=UnavailableErrorMessage, info={"required_replicas":2, "alive_replicas": 1, "consistency": 1}) result.to_exception.return_value = expected_exception rf._set_result(None, None, None, result) rf._event.set() self.assertRaises(Exception, rf.result) callback.assert_called_once_with(expected_exception, arg, **kwargs) callback2.assert_called_once_with(expected_exception, arg2, **kwargs2) def test_add_callbacks(self): session = self.make_session() query = SimpleStatement("INSERT INFO foo (a, b) VALUES (1, 2)") message = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE) # test errback rf = ResponseFuture(session, message, query, 1) rf._query_retries = 1 rf.send_request() rf.add_callbacks( callback=self.assertEqual, callback_args=([{'col': 'val'}],), errback=self.assertIsInstance, errback_args=(Exception,)) result = Mock(spec=UnavailableErrorMessage, info={"required_replicas":2, "alive_replicas": 1, "consistency": 1}) result.to_exception.return_value = Exception() rf._set_result(None, None, None, result) self.assertRaises(Exception, rf.result) # test callback rf = ResponseFuture(session, message, query, 1) rf.send_request() callback = Mock() - expected_result = [{'col': 'val'}] + expected_result = (object(), object()) arg = "positional" kwargs = {'one': 1, 'two': 2} rf.add_callbacks( callback=callback, callback_args=(arg,), callback_kwargs=kwargs, errback=self.assertIsInstance, errback_args=(Exception,)) - rf._set_result(None, None, None, self.make_mock_response(expected_result)) - self.assertEqual(rf.result(), expected_result) + rf._set_result(None, None, None, self.make_mock_response(expected_result[0], expected_result[1])) + self.assertEqual(rf.result()[0], expected_result) - callback.assert_called_once_with(expected_result, arg, **kwargs) + callback.assert_called_once_with([expected_result], arg, **kwargs) def test_prepared_query_not_found(self): session = self.make_session() pool = session._pools.get.return_value connection = Mock(spec=Connection) pool.borrow_connection.return_value = (connection, 1) rf = self.make_response_future(session) rf.send_request() session.cluster.protocol_version = ProtocolVersion.V4 session.cluster._prepared_statements = MagicMock(dict) prepared_statement = session.cluster._prepared_statements.__getitem__.return_value prepared_statement.query_string = "SELECT * FROM foobar" prepared_statement.keyspace = "FooKeyspace" rf._connection.keyspace = "FooKeyspace" result = Mock(spec=PreparedQueryNotFound, info='a' * 16) rf._set_result(None, None, None, result) self.assertTrue(session.submit.call_args) args, kwargs = session.submit.call_args self.assertEqual(rf._reprepare, args[-5]) self.assertIsInstance(args[-4], PrepareMessage) self.assertEqual(args[-4].query, "SELECT * FROM foobar") def test_prepared_query_not_found_bad_keyspace(self): session = self.make_session() pool = session._pools.get.return_value connection = Mock(spec=Connection) pool.borrow_connection.return_value = (connection, 1) rf = self.make_response_future(session) rf.send_request() session.cluster.protocol_version = ProtocolVersion.V4 session.cluster._prepared_statements = MagicMock(dict) prepared_statement = session.cluster._prepared_statements.__getitem__.return_value prepared_statement.query_string = "SELECT * FROM foobar" prepared_statement.keyspace = "FooKeyspace" rf._connection.keyspace = "BarKeyspace" result = Mock(spec=PreparedQueryNotFound, info='a' * 16) rf._set_result(None, None, None, result) self.assertRaises(ValueError, rf.result) def test_repeat_orig_query_after_succesful_reprepare(self): + query_id = b'abc123' # Just a random binary string so we don't hit id mismatch exception session = self.make_session() rf = self.make_response_future(session) - response = Mock(spec=ResultMessage, kind=RESULT_KIND_PREPARED) + response = Mock(spec=ResultMessage, + kind=RESULT_KIND_PREPARED, + result_metadata_id='foo') response.results = (None, None, None, None, None) + response.query_id = query_id rf._query = Mock(return_value=True) rf._execute_after_prepare('host', None, None, response) rf._query.assert_called_once_with('host') rf.prepared_statement = Mock() + rf.prepared_statement.query_id = query_id rf._query = Mock(return_value=True) rf._execute_after_prepare('host', None, None, response) rf._query.assert_called_once_with('host') diff --git a/tests/unit/test_resultset.py b/tests/unit/test_resultset.py index 541ef6f..1af3e84 100644 --- a/tests/unit/test_resultset.py +++ b/tests/unit/test_resultset.py @@ -1,209 +1,216 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from cassandra.query import named_tuple_factory, dict_factory, tuple_factory try: import unittest2 as unittest except ImportError: import unittest # noqa from mock import Mock, PropertyMock, patch from cassandra.cluster import ResultSet class ResultSetTests(unittest.TestCase): def test_iter_non_paged(self): expected = list(range(10)) rs = ResultSet(Mock(has_more_pages=False), expected) itr = iter(rs) self.assertListEqual(list(itr), expected) def test_iter_paged(self): expected = list(range(10)) - response_future = Mock(has_more_pages=True) + response_future = Mock(has_more_pages=True, _continuous_paging_session=None) response_future.result.side_effect = (ResultSet(Mock(), expected[-5:]), ) # ResultSet is iterable, so it must be protected in order to be returned whole by the Mock rs = ResultSet(response_future, expected[:5]) itr = iter(rs) # this is brittle, depends on internal impl details. Would like to find a better way type(response_future).has_more_pages = PropertyMock(side_effect=(True, True, False)) # after init to avoid side effects being consumed by init self.assertListEqual(list(itr), expected) def test_list_non_paged(self): # list access on RS for backwards-compatibility expected = list(range(10)) rs = ResultSet(Mock(has_more_pages=False), expected) for i in range(10): self.assertEqual(rs[i], expected[i]) self.assertEqual(list(rs), expected) def test_list_paged(self): # list access on RS for backwards-compatibility expected = list(range(10)) - response_future = Mock(has_more_pages=True) + response_future = Mock(has_more_pages=True, _continuous_paging_session=None) response_future.result.side_effect = (ResultSet(Mock(), expected[-5:]), ) # ResultSet is iterable, so it must be protected in order to be returned whole by the Mock rs = ResultSet(response_future, expected[:5]) # this is brittle, depends on internal impl details. Would like to find a better way type(response_future).has_more_pages = PropertyMock(side_effect=(True, True, True, False)) # First two True are consumed on check entering list mode self.assertEqual(rs[9], expected[9]) self.assertEqual(list(rs), expected) def test_has_more_pages(self): response_future = Mock() response_future.has_more_pages.side_effect = PropertyMock(side_effect=(True, False)) rs = ResultSet(response_future, []) type(response_future).has_more_pages = PropertyMock(side_effect=(True, False)) # after init to avoid side effects being consumed by init self.assertTrue(rs.has_more_pages) self.assertFalse(rs.has_more_pages) def test_iterate_then_index(self): # RuntimeError if indexing with no pages expected = list(range(10)) rs = ResultSet(Mock(has_more_pages=False), expected) itr = iter(rs) # before consuming with self.assertRaises(RuntimeError): rs[0] list(itr) # after consuming with self.assertRaises(RuntimeError): rs[0] self.assertFalse(rs) self.assertFalse(list(rs)) # RuntimeError if indexing during or after pages - response_future = Mock(has_more_pages=True) + response_future = Mock(has_more_pages=True, _continuous_paging_session=None) response_future.result.side_effect = (ResultSet(Mock(), expected[-5:]), ) # ResultSet is iterable, so it must be protected in order to be returned whole by the Mock rs = ResultSet(response_future, expected[:5]) type(response_future).has_more_pages = PropertyMock(side_effect=(True, False)) itr = iter(rs) # before consuming with self.assertRaises(RuntimeError): rs[0] for row in itr: # while consuming with self.assertRaises(RuntimeError): rs[0] # after consuming with self.assertRaises(RuntimeError): rs[0] self.assertFalse(rs) self.assertFalse(list(rs)) def test_index_list_mode(self): # no pages expected = list(range(10)) rs = ResultSet(Mock(has_more_pages=False), expected) # index access before iteration causes list to be materialized self.assertEqual(rs[0], expected[0]) # resusable iteration self.assertListEqual(list(rs), expected) self.assertListEqual(list(rs), expected) self.assertTrue(rs) # pages - response_future = Mock(has_more_pages=True) + response_future = Mock(has_more_pages=True, _continuous_paging_session=None) response_future.result.side_effect = (ResultSet(Mock(), expected[-5:]), ) # ResultSet is iterable, so it must be protected in order to be returned whole by the Mock rs = ResultSet(response_future, expected[:5]) # this is brittle, depends on internal impl details. Would like to find a better way type(response_future).has_more_pages = PropertyMock(side_effect=(True, True, True, False)) # First two True are consumed on check entering list mode # index access before iteration causes list to be materialized self.assertEqual(rs[0], expected[0]) self.assertEqual(rs[9], expected[9]) # resusable iteration self.assertListEqual(list(rs), expected) self.assertListEqual(list(rs), expected) self.assertTrue(rs) def test_eq(self): # no pages expected = list(range(10)) rs = ResultSet(Mock(has_more_pages=False), expected) # eq before iteration causes list to be materialized self.assertEqual(rs, expected) # results can be iterated or indexed once we're materialized self.assertListEqual(list(rs), expected) self.assertEqual(rs[9], expected[9]) self.assertTrue(rs) # pages - response_future = Mock(has_more_pages=True) + response_future = Mock(has_more_pages=True, _continuous_paging_session=None) response_future.result.side_effect = (ResultSet(Mock(), expected[-5:]), ) # ResultSet is iterable, so it must be protected in order to be returned whole by the Mock rs = ResultSet(response_future, expected[:5]) type(response_future).has_more_pages = PropertyMock(side_effect=(True, True, True, False)) # eq before iteration causes list to be materialized self.assertEqual(rs, expected) # results can be iterated or indexed once we're materialized self.assertListEqual(list(rs), expected) self.assertEqual(rs[9], expected[9]) self.assertTrue(rs) def test_bool(self): self.assertFalse(ResultSet(Mock(has_more_pages=False), [])) self.assertTrue(ResultSet(Mock(has_more_pages=False), [1])) def test_was_applied(self): # unknown row factory raises with self.assertRaises(RuntimeError): ResultSet(Mock(), []).was_applied response_future = Mock(row_factory=named_tuple_factory) # no row with self.assertRaises(RuntimeError): ResultSet(response_future, []).was_applied # too many rows with self.assertRaises(RuntimeError): ResultSet(response_future, [tuple(), tuple()]).was_applied # various internal row factories for row_factory in (named_tuple_factory, tuple_factory): for applied in (True, False): rs = ResultSet(Mock(row_factory=row_factory), [(applied,)]) self.assertEqual(rs.was_applied, applied) row_factory = dict_factory for applied in (True, False): rs = ResultSet(Mock(row_factory=row_factory), [{'[applied]': applied}]) self.assertEqual(rs.was_applied, applied) def test_one(self): # no pages first, second = Mock(), Mock() rs = ResultSet(Mock(has_more_pages=False), [first, second]) self.assertEqual(rs.one(), first) + def test_all(self): + first, second = Mock(), Mock() + rs1 = ResultSet(Mock(has_more_pages=False), [first, second]) + rs2 = ResultSet(Mock(has_more_pages=False), [first, second]) + + self.assertEqual(rs1.all(), list(rs2)) + @patch('cassandra.cluster.warn') def test_indexing_deprecation(self, mocked_warn): # normally we'd use catch_warnings to test this, but that doesn't work # pre-Py3.0 for some reason first, second = Mock(), Mock() rs = ResultSet(Mock(has_more_pages=False), [first, second]) self.assertEqual(rs[0], first) self.assertEqual(len(mocked_warn.mock_calls), 1) index_warning_args = tuple(mocked_warn.mock_calls[0])[1] self.assertIn('indexing support will be removed in 4.0', str(index_warning_args[0])) self.assertIs(index_warning_args[1], DeprecationWarning) diff --git a/tests/unit/test_segment.py b/tests/unit/test_segment.py new file mode 100644 index 0000000..fc49339 --- /dev/null +++ b/tests/unit/test_segment.py @@ -0,0 +1,218 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +try: + import unittest2 as unittest +except ImportError: + import unittest # noqa + +import six + +from cassandra import DriverException +from cassandra.segment import Segment, CrcException +from cassandra.connection import segment_codec_no_compression, segment_codec_lz4 + + +def to_bits(b): + if six.PY2: + b = six.byte2int(b) + return '{:08b}'.format(b) + +class SegmentCodecTest(unittest.TestCase): + + small_msg = b'b' * 50 + max_msg = b'b' * Segment.MAX_PAYLOAD_LENGTH + large_msg = b'b' * (Segment.MAX_PAYLOAD_LENGTH + 1) + + @staticmethod + def _header_to_bits(data): + # unpack a header to bits + # data should be the little endian bytes sequence + if len(data) > 6: # compressed + data = data[:5] + bits = ''.join([to_bits(b) for b in reversed(data)]) + # return the compressed payload length, the uncompressed payload length, + # the self contained flag and the padding as bits + return bits[23:40] + bits[6:23] + bits[5:6] + bits[:5] + else: # uncompressed + data = data[:3] + bits = ''.join([to_bits(b) for b in reversed(data)]) + # return the payload length, the self contained flag and + # the padding as bits + return bits[7:24] + bits[6:7] + bits[:6] + + def test_encode_uncompressed_header(self): + buffer = six.BytesIO() + segment_codec_no_compression.encode_header(buffer, len(self.small_msg), -1, True) + self.assertEqual(buffer.tell(), 6) + self.assertEqual( + self._header_to_bits(buffer.getvalue()), + "00000000000110010" + "1" + "000000") + + @unittest.skipUnless(segment_codec_lz4, ' lz4 not installed') + def test_encode_compressed_header(self): + buffer = six.BytesIO() + compressed_length = len(segment_codec_lz4.compress(self.small_msg)) + segment_codec_lz4.encode_header(buffer, compressed_length, len(self.small_msg), True) + + self.assertEqual(buffer.tell(), 8) + self.assertEqual( + self._header_to_bits(buffer.getvalue()), + "{:017b}".format(compressed_length) + "00000000000110010" + "1" + "00000") + + def test_encode_uncompressed_header_with_max_payload(self): + buffer = six.BytesIO() + segment_codec_no_compression.encode_header(buffer, len(self.max_msg), -1, True) + self.assertEqual(buffer.tell(), 6) + self.assertEqual( + self._header_to_bits(buffer.getvalue()), + "11111111111111111" + "1" + "000000") + + def test_encode_header_fails_if_payload_too_big(self): + buffer = six.BytesIO() + for codec in [c for c in [segment_codec_no_compression, segment_codec_lz4] if c is not None]: + with self.assertRaises(DriverException): + codec.encode_header(buffer, len(self.large_msg), -1, False) + + def test_encode_uncompressed_header_not_self_contained_msg(self): + buffer = six.BytesIO() + # simulate the first chunk with the max size + segment_codec_no_compression.encode_header(buffer, len(self.max_msg), -1, False) + self.assertEqual(buffer.tell(), 6) + self.assertEqual( + self._header_to_bits(buffer.getvalue()), + ("11111111111111111" + "0" # not self contained + "000000")) + + @unittest.skipUnless(segment_codec_lz4, ' lz4 not installed') + def test_encode_compressed_header_with_max_payload(self): + buffer = six.BytesIO() + compressed_length = len(segment_codec_lz4.compress(self.max_msg)) + segment_codec_lz4.encode_header(buffer, compressed_length, len(self.max_msg), True) + self.assertEqual(buffer.tell(), 8) + self.assertEqual( + self._header_to_bits(buffer.getvalue()), + "{:017b}".format(compressed_length) + "11111111111111111" + "1" + "00000") + + @unittest.skipUnless(segment_codec_lz4, ' lz4 not installed') + def test_encode_compressed_header_not_self_contained_msg(self): + buffer = six.BytesIO() + # simulate the first chunk with the max size + compressed_length = len(segment_codec_lz4.compress(self.max_msg)) + segment_codec_lz4.encode_header(buffer, compressed_length, len(self.max_msg), False) + self.assertEqual(buffer.tell(), 8) + self.assertEqual( + self._header_to_bits(buffer.getvalue()), + ("{:017b}".format(compressed_length) + + "11111111111111111" + "0" # not self contained + "00000")) + + def test_decode_uncompressed_header(self): + buffer = six.BytesIO() + segment_codec_no_compression.encode_header(buffer, len(self.small_msg), -1, True) + buffer.seek(0) + header = segment_codec_no_compression.decode_header(buffer) + self.assertEqual(header.uncompressed_payload_length, -1) + self.assertEqual(header.payload_length, len(self.small_msg)) + self.assertEqual(header.is_self_contained, True) + + @unittest.skipUnless(segment_codec_lz4, ' lz4 not installed') + def test_decode_compressed_header(self): + buffer = six.BytesIO() + compressed_length = len(segment_codec_lz4.compress(self.small_msg)) + segment_codec_lz4.encode_header(buffer, compressed_length, len(self.small_msg), True) + buffer.seek(0) + header = segment_codec_lz4.decode_header(buffer) + self.assertEqual(header.uncompressed_payload_length, len(self.small_msg)) + self.assertEqual(header.payload_length, compressed_length) + self.assertEqual(header.is_self_contained, True) + + def test_decode_header_fails_if_corrupted(self): + buffer = six.BytesIO() + segment_codec_no_compression.encode_header(buffer, len(self.small_msg), -1, True) + # corrupt one byte + buffer.seek(buffer.tell()-1) + buffer.write(b'0') + buffer.seek(0) + + with self.assertRaises(CrcException): + segment_codec_no_compression.decode_header(buffer) + + def test_decode_uncompressed_self_contained_segment(self): + buffer = six.BytesIO() + segment_codec_no_compression.encode(buffer, self.small_msg) + + buffer.seek(0) + header = segment_codec_no_compression.decode_header(buffer) + segment = segment_codec_no_compression.decode(buffer, header) + + self.assertEqual(header.is_self_contained, True) + self.assertEqual(header.uncompressed_payload_length, -1) + self.assertEqual(header.payload_length, len(self.small_msg)) + self.assertEqual(segment.payload, self.small_msg) + + @unittest.skipUnless(segment_codec_lz4, ' lz4 not installed') + def test_decode_compressed_self_contained_segment(self): + buffer = six.BytesIO() + segment_codec_lz4.encode(buffer, self.small_msg) + + buffer.seek(0) + header = segment_codec_lz4.decode_header(buffer) + segment = segment_codec_lz4.decode(buffer, header) + + self.assertEqual(header.is_self_contained, True) + self.assertEqual(header.uncompressed_payload_length, len(self.small_msg)) + self.assertGreater(header.uncompressed_payload_length, header.payload_length) + self.assertEqual(segment.payload, self.small_msg) + + def test_decode_multi_segments(self): + buffer = six.BytesIO() + segment_codec_no_compression.encode(buffer, self.large_msg) + + buffer.seek(0) + # We should have 2 segments to read + headers = [] + segments = [] + headers.append(segment_codec_no_compression.decode_header(buffer)) + segments.append(segment_codec_no_compression.decode(buffer, headers[0])) + headers.append(segment_codec_no_compression.decode_header(buffer)) + segments.append(segment_codec_no_compression.decode(buffer, headers[1])) + + self.assertTrue(all([h.is_self_contained is False for h in headers])) + decoded_msg = segments[0].payload + segments[1].payload + self.assertEqual(decoded_msg, self.large_msg) + + @unittest.skipUnless(segment_codec_lz4, ' lz4 not installed') + def test_decode_fails_if_corrupted(self): + buffer = six.BytesIO() + segment_codec_lz4.encode(buffer, self.small_msg) + buffer.seek(buffer.tell()-1) + buffer.write(b'0') + buffer.seek(0) + header = segment_codec_lz4.decode_header(buffer) + with self.assertRaises(CrcException): + segment_codec_lz4.decode(buffer, header) + + @unittest.skipUnless(segment_codec_lz4, ' lz4 not installed') + def test_decode_tiny_msg_not_compressed(self): + buffer = six.BytesIO() + segment_codec_lz4.encode(buffer, b'b') + buffer.seek(0) + header = segment_codec_lz4.decode_header(buffer) + segment = segment_codec_lz4.decode(buffer, header) + self.assertEqual(header.uncompressed_payload_length, 0) + self.assertEqual(header.payload_length, 1) + self.assertEqual(segment.payload, b'b') diff --git a/tests/unit/test_timestamps.py b/tests/unit/test_timestamps.py index bbca352..8903fbc 100644 --- a/tests/unit/test_timestamps.py +++ b/tests/unit/test_timestamps.py @@ -1,278 +1,278 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa import mock from cassandra import timestamps -import time from threading import Thread, Lock + class _TimestampTestMixin(object): @mock.patch('cassandra.timestamps.time') def _call_and_check_results(self, patched_time_module, system_time_expected_stamp_pairs, timestamp_generator=None): """ For each element in an iterable of (system_time, expected_timestamp) pairs, call a :class:`cassandra.timestamps.MonotonicTimestampGenerator` with system_times as the underlying time.time() result, then assert that the result is expected_timestamp. Skips the check if expected_timestamp is None. """ patched_time_module.time = mock.Mock() system_times, expected_timestamps = zip(*system_time_expected_stamp_pairs) patched_time_module.time.side_effect = system_times tsg = timestamp_generator or timestamps.MonotonicTimestampGenerator() for expected in expected_timestamps: actual = tsg() if expected is not None: self.assertEqual(actual, expected) # assert we patched timestamps.time.time correctly with self.assertRaises(StopIteration): tsg() class TestTimestampGeneratorOutput(unittest.TestCase, _TimestampTestMixin): """ Mock time.time and test the output of MonotonicTimestampGenerator.__call__ given different patterns of changing results. """ def test_timestamps_during_and_after_same_system_time(self): """ + Timestamps should increase monotonically over repeated system time. + Test that MonotonicTimestampGenerator's output increases by 1 when the underlying system time is the same, then returns to normal when the system time increases again. @since 3.8.0 @expected_result Timestamps should increase monotonically over repeated system time. @test_category timing """ self._call_and_check_results( system_time_expected_stamp_pairs=( (15.0, 15 * 1e6), (15.0, 15 * 1e6 + 1), (15.0, 15 * 1e6 + 2), (15.01, 15.01 * 1e6)) ) def test_timestamps_during_and_after_backwards_system_time(self): """ + Timestamps should increase monotonically over system time going backwards. + Test that MonotonicTimestampGenerator's output increases by 1 when the underlying system time goes backward, then returns to normal when the system time increases again. - - @since 3.8.0 - @expected_result Timestamps should increase monotonically over system time going backwards. - @test_category timing """ self._call_and_check_results( system_time_expected_stamp_pairs=( (15.0, 15 * 1e6), (13.0, 15 * 1e6 + 1), (14.0, 15 * 1e6 + 2), (13.5, 15 * 1e6 + 3), (15.01, 15.01 * 1e6)) ) class TestTimestampGeneratorLogging(unittest.TestCase): def setUp(self): self.log_patcher = mock.patch('cassandra.timestamps.log') self.addCleanup(self.log_patcher.stop) self.patched_timestamp_log = self.log_patcher.start() def assertLastCallArgRegex(self, call, pattern): last_warn_args, last_warn_kwargs = call self.assertEqual(len(last_warn_args), 1) self.assertEqual(len(last_warn_kwargs), 0) self.assertRegexpMatches( last_warn_args[0], pattern, ) def test_basic_log_content(self): """ Tests there are logs @since 3.8.0 @jira_ticket PYTHON-676 @expected_result logs @test_category timing """ tsg = timestamps.MonotonicTimestampGenerator( warning_threshold=1e-6, warning_interval=1e-6 ) #The units of _last_warn is seconds tsg._last_warn = 12 tsg._next_timestamp(20, tsg.last) self.assertEqual(len(self.patched_timestamp_log.warning.call_args_list), 0) tsg._next_timestamp(16, tsg.last) self.assertEqual(len(self.patched_timestamp_log.warning.call_args_list), 1) self.assertLastCallArgRegex( self.patched_timestamp_log.warning.call_args, r'Clock skew detected:.*\b16\b.*\b4\b.*\b20\b' ) def test_disable_logging(self): """ Tests there are no logs when there is a clock skew if logging is disabled @since 3.8.0 @jira_ticket PYTHON-676 @expected_result no logs @test_category timing """ no_warn_tsg = timestamps.MonotonicTimestampGenerator(warn_on_drift=False) no_warn_tsg.last = 100 no_warn_tsg._next_timestamp(99, no_warn_tsg.last) self.assertEqual(len(self.patched_timestamp_log.warning.call_args_list), 0) def test_warning_threshold_respected_no_logging(self): """ Tests there are no logs if `warning_threshold` is not exceeded @since 3.8.0 @jira_ticket PYTHON-676 @expected_result no logs @test_category timing """ tsg = timestamps.MonotonicTimestampGenerator( warning_threshold=2e-6, ) tsg.last, tsg._last_warn = 100, 97 tsg._next_timestamp(98, tsg.last) self.assertEqual(len(self.patched_timestamp_log.warning.call_args_list), 0) def test_warning_threshold_respected_logs(self): """ Tests there are logs if `warning_threshold` is exceeded @since 3.8.0 @jira_ticket PYTHON-676 @expected_result logs @test_category timing """ tsg = timestamps.MonotonicTimestampGenerator( warning_threshold=1e-6, warning_interval=1e-6 ) tsg.last, tsg._last_warn = 100, 97 tsg._next_timestamp(98, tsg.last) self.assertEqual(len(self.patched_timestamp_log.warning.call_args_list), 1) def test_warning_interval_respected_no_logging(self): """ Tests there is only one log in the interval `warning_interval` @since 3.8.0 @jira_ticket PYTHON-676 @expected_result one log @test_category timing """ tsg = timestamps.MonotonicTimestampGenerator( warning_threshold=1e-6, warning_interval=2e-6 ) tsg.last = 100 tsg._next_timestamp(70, tsg.last) self.assertEqual(len(self.patched_timestamp_log.warning.call_args_list), 1) tsg._next_timestamp(71, tsg.last) self.assertEqual(len(self.patched_timestamp_log.warning.call_args_list), 1) def test_warning_interval_respected_logs(self): """ Tests there are logs again if the clock skew happens after`warning_interval` @since 3.8.0 @jira_ticket PYTHON-676 @expected_result logs @test_category timing """ tsg = timestamps.MonotonicTimestampGenerator( warning_interval=1e-6, warning_threshold=1e-6, ) tsg.last = 100 tsg._next_timestamp(70, tsg.last) self.assertEqual(len(self.patched_timestamp_log.warning.call_args_list), 1) tsg._next_timestamp(72, tsg.last) self.assertEqual(len(self.patched_timestamp_log.warning.call_args_list), 2) class TestTimestampGeneratorMultipleThreads(unittest.TestCase): def test_should_generate_incrementing_timestamps_for_all_threads(self): """ Tests when time is "stopped", values are assigned incrementally @since 3.8.0 @jira_ticket PYTHON-676 @expected_result the returned values increase @test_category timing """ lock = Lock() def request_time(): for _ in range(timestamp_to_generate): timestamp = tsg() with lock: generated_timestamps.append(timestamp) tsg = timestamps.MonotonicTimestampGenerator() fixed_time = 1 num_threads = 5 timestamp_to_generate = 1000 generated_timestamps = [] with mock.patch('time.time', new=mock.Mock(return_value=fixed_time)): threads = [] for _ in range(num_threads): threads.append(Thread(target=request_time)) for t in threads: t.start() for t in threads: t.join() self.assertEqual(len(generated_timestamps), num_threads * timestamp_to_generate) for i, timestamp in enumerate(sorted(generated_timestamps)): self.assertEqual(int(i + 1e6), timestamp) diff --git a/tests/unit/test_types.py b/tests/unit/test_types.py index c8f3011..562fd2c 100644 --- a/tests/unit/test_types.py +++ b/tests/unit/test_types.py @@ -1,386 +1,931 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa -from binascii import unhexlify import datetime import tempfile -import six import time +from binascii import unhexlify + +import six import cassandra -from cassandra.cqltypes import (BooleanType, lookup_casstype_simple, lookup_casstype, - LongType, DecimalType, SetType, cql_typename, - CassandraType, UTF8Type, parse_casstype_args, - SimpleDateType, TimeType, ByteType, ShortType, - EmptyValue, _CassandraType, DateType, int64_pack) +from cassandra import util +from cassandra.cqltypes import ( + CassandraType, DateRangeType, DateType, DecimalType, + EmptyValue, LongType, SetType, UTF8Type, + cql_typename, int8_pack, int64_pack, lookup_casstype, + lookup_casstype_simple, parse_casstype_args, + int32_pack, Int32Type, ListType, MapType +) from cassandra.encoder import cql_quote -from cassandra.protocol import (write_string, read_longstring, write_stringmap, - read_stringmap, read_inet, write_inet, - read_string, write_longstring) -from cassandra.query import named_tuple_factory from cassandra.pool import Host -from cassandra.policies import SimpleConvictionPolicy, ConvictionPolicy -from cassandra.util import Date, Time from cassandra.metadata import Token +from cassandra.policies import ConvictionPolicy, SimpleConvictionPolicy +from cassandra.protocol import ( + read_inet, read_longstring, read_string, + read_stringmap, write_inet, write_longstring, + write_string, write_stringmap +) +from cassandra.query import named_tuple_factory +from cassandra.util import ( + OPEN_BOUND, Date, DateRange, DateRangeBound, + DateRangePrecision, Time, ms_timestamp_from_datetime, + datetime_from_timestamp +) +from tests.unit.util import check_sequence_consistency class TypeTests(unittest.TestCase): def test_lookup_casstype_simple(self): """ Ensure lookup_casstype_simple returns the correct classes """ self.assertEqual(lookup_casstype_simple('AsciiType'), cassandra.cqltypes.AsciiType) self.assertEqual(lookup_casstype_simple('LongType'), cassandra.cqltypes.LongType) self.assertEqual(lookup_casstype_simple('BytesType'), cassandra.cqltypes.BytesType) self.assertEqual(lookup_casstype_simple('BooleanType'), cassandra.cqltypes.BooleanType) self.assertEqual(lookup_casstype_simple('CounterColumnType'), cassandra.cqltypes.CounterColumnType) self.assertEqual(lookup_casstype_simple('DecimalType'), cassandra.cqltypes.DecimalType) self.assertEqual(lookup_casstype_simple('DoubleType'), cassandra.cqltypes.DoubleType) self.assertEqual(lookup_casstype_simple('FloatType'), cassandra.cqltypes.FloatType) self.assertEqual(lookup_casstype_simple('InetAddressType'), cassandra.cqltypes.InetAddressType) self.assertEqual(lookup_casstype_simple('Int32Type'), cassandra.cqltypes.Int32Type) self.assertEqual(lookup_casstype_simple('UTF8Type'), cassandra.cqltypes.UTF8Type) self.assertEqual(lookup_casstype_simple('DateType'), cassandra.cqltypes.DateType) self.assertEqual(lookup_casstype_simple('SimpleDateType'), cassandra.cqltypes.SimpleDateType) self.assertEqual(lookup_casstype_simple('ByteType'), cassandra.cqltypes.ByteType) self.assertEqual(lookup_casstype_simple('ShortType'), cassandra.cqltypes.ShortType) self.assertEqual(lookup_casstype_simple('TimeUUIDType'), cassandra.cqltypes.TimeUUIDType) self.assertEqual(lookup_casstype_simple('TimeType'), cassandra.cqltypes.TimeType) self.assertEqual(lookup_casstype_simple('UUIDType'), cassandra.cqltypes.UUIDType) self.assertEqual(lookup_casstype_simple('IntegerType'), cassandra.cqltypes.IntegerType) self.assertEqual(lookup_casstype_simple('MapType'), cassandra.cqltypes.MapType) self.assertEqual(lookup_casstype_simple('ListType'), cassandra.cqltypes.ListType) self.assertEqual(lookup_casstype_simple('SetType'), cassandra.cqltypes.SetType) self.assertEqual(lookup_casstype_simple('CompositeType'), cassandra.cqltypes.CompositeType) self.assertEqual(lookup_casstype_simple('ColumnToCollectionType'), cassandra.cqltypes.ColumnToCollectionType) self.assertEqual(lookup_casstype_simple('ReversedType'), cassandra.cqltypes.ReversedType) self.assertEqual(lookup_casstype_simple('DurationType'), cassandra.cqltypes.DurationType) + self.assertEqual(lookup_casstype_simple('DateRangeType'), cassandra.cqltypes.DateRangeType) self.assertEqual(str(lookup_casstype_simple('unknown')), str(cassandra.cqltypes.mkUnrecognizedType('unknown'))) def test_lookup_casstype(self): """ Ensure lookup_casstype returns the correct classes """ self.assertEqual(lookup_casstype('AsciiType'), cassandra.cqltypes.AsciiType) self.assertEqual(lookup_casstype('LongType'), cassandra.cqltypes.LongType) self.assertEqual(lookup_casstype('BytesType'), cassandra.cqltypes.BytesType) self.assertEqual(lookup_casstype('BooleanType'), cassandra.cqltypes.BooleanType) self.assertEqual(lookup_casstype('CounterColumnType'), cassandra.cqltypes.CounterColumnType) self.assertEqual(lookup_casstype('DateType'), cassandra.cqltypes.DateType) self.assertEqual(lookup_casstype('DecimalType'), cassandra.cqltypes.DecimalType) self.assertEqual(lookup_casstype('DoubleType'), cassandra.cqltypes.DoubleType) self.assertEqual(lookup_casstype('FloatType'), cassandra.cqltypes.FloatType) self.assertEqual(lookup_casstype('InetAddressType'), cassandra.cqltypes.InetAddressType) self.assertEqual(lookup_casstype('Int32Type'), cassandra.cqltypes.Int32Type) self.assertEqual(lookup_casstype('UTF8Type'), cassandra.cqltypes.UTF8Type) self.assertEqual(lookup_casstype('DateType'), cassandra.cqltypes.DateType) self.assertEqual(lookup_casstype('TimeType'), cassandra.cqltypes.TimeType) self.assertEqual(lookup_casstype('ByteType'), cassandra.cqltypes.ByteType) self.assertEqual(lookup_casstype('ShortType'), cassandra.cqltypes.ShortType) self.assertEqual(lookup_casstype('TimeUUIDType'), cassandra.cqltypes.TimeUUIDType) self.assertEqual(lookup_casstype('UUIDType'), cassandra.cqltypes.UUIDType) self.assertEqual(lookup_casstype('IntegerType'), cassandra.cqltypes.IntegerType) self.assertEqual(lookup_casstype('MapType'), cassandra.cqltypes.MapType) self.assertEqual(lookup_casstype('ListType'), cassandra.cqltypes.ListType) self.assertEqual(lookup_casstype('SetType'), cassandra.cqltypes.SetType) self.assertEqual(lookup_casstype('CompositeType'), cassandra.cqltypes.CompositeType) self.assertEqual(lookup_casstype('ColumnToCollectionType'), cassandra.cqltypes.ColumnToCollectionType) self.assertEqual(lookup_casstype('ReversedType'), cassandra.cqltypes.ReversedType) self.assertEqual(lookup_casstype('DurationType'), cassandra.cqltypes.DurationType) + self.assertEqual(lookup_casstype('DateRangeType'), cassandra.cqltypes.DateRangeType) self.assertEqual(str(lookup_casstype('unknown')), str(cassandra.cqltypes.mkUnrecognizedType('unknown'))) self.assertRaises(ValueError, lookup_casstype, 'AsciiType~') def test_casstype_parameterized(self): self.assertEqual(LongType.cass_parameterized_type_with(()), 'LongType') self.assertEqual(LongType.cass_parameterized_type_with((), full=True), 'org.apache.cassandra.db.marshal.LongType') self.assertEqual(SetType.cass_parameterized_type_with([DecimalType], full=True), 'org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.DecimalType)') self.assertEqual(LongType.cql_parameterized_type(), 'bigint') subtypes = (cassandra.cqltypes.UTF8Type, cassandra.cqltypes.UTF8Type) self.assertEqual('map', cassandra.cqltypes.MapType.apply_parameters(subtypes).cql_parameterized_type()) def test_datetype_from_string(self): # Ensure all formats can be parsed, without exception for format in cassandra.cqltypes.cql_timestamp_formats: date_string = str(datetime.datetime.now().strftime(format)) cassandra.cqltypes.DateType.interpret_datestring(date_string) def test_cql_typename(self): """ Smoke test cql_typename """ self.assertEqual(cql_typename('DateType'), 'timestamp') self.assertEqual(cql_typename('org.apache.cassandra.db.marshal.ListType(IntegerType)'), 'list') def test_named_tuple_colname_substitution(self): colnames = ("func(abc)", "[applied]", "func(func(abc))", "foo_bar", "foo_bar_") rows = [(1, 2, 3, 4, 5)] result = named_tuple_factory(colnames, rows)[0] self.assertEqual(result[0], result.func_abc) self.assertEqual(result[1], result.applied) self.assertEqual(result[2], result.func_func_abc) self.assertEqual(result[3], result.foo_bar) self.assertEqual(result[4], result.foo_bar_) def test_parse_casstype_args(self): class FooType(CassandraType): typename = 'org.apache.cassandra.db.marshal.FooType' def __init__(self, subtypes, names): self.subtypes = subtypes self.names = names @classmethod def apply_parameters(cls, subtypes, names): return cls(subtypes, [unhexlify(six.b(name)) if name is not None else name for name in names]) class BarType(FooType): typename = 'org.apache.cassandra.db.marshal.BarType' ctype = parse_casstype_args(''.join(( 'org.apache.cassandra.db.marshal.FooType(', - '63697479:org.apache.cassandra.db.marshal.UTF8Type,', - 'BarType(61646472657373:org.apache.cassandra.db.marshal.UTF8Type),', - '7a6970:org.apache.cassandra.db.marshal.UTF8Type', + '63697479:org.apache.cassandra.db.marshal.UTF8Type,', + 'BarType(61646472657373:org.apache.cassandra.db.marshal.UTF8Type),', + '7a6970:org.apache.cassandra.db.marshal.UTF8Type', ')'))) self.assertEqual(FooType, ctype.__class__) self.assertEqual(UTF8Type, ctype.subtypes[0]) # middle subtype should be a BarType instance with its own subtypes and names self.assertIsInstance(ctype.subtypes[1], BarType) self.assertEqual([UTF8Type], ctype.subtypes[1].subtypes) self.assertEqual([b"address"], ctype.subtypes[1].names) self.assertEqual(UTF8Type, ctype.subtypes[2]) self.assertEqual([b'city', None, b'zip'], ctype.names) def test_empty_value(self): self.assertEqual(str(EmptyValue()), 'EMPTY') def test_datetype(self): now_time_seconds = time.time() now_datetime = datetime.datetime.utcfromtimestamp(now_time_seconds) # Cassandra timestamps in millis now_timestamp = now_time_seconds * 1e3 # same results serialized self.assertEqual(DateType.serialize(now_datetime, 0), DateType.serialize(now_timestamp, 0)) # deserialize # epoc expected = 0 self.assertEqual(DateType.deserialize(int64_pack(1000 * expected), 0), datetime.datetime.utcfromtimestamp(expected)) # beyond 32b expected = 2 ** 33 self.assertEqual(DateType.deserialize(int64_pack(1000 * expected), 0), datetime.datetime(2242, 3, 16, 12, 56, 32)) # less than epoc (PYTHON-119) expected = -770172256 self.assertEqual(DateType.deserialize(int64_pack(1000 * expected), 0), datetime.datetime(1945, 8, 5, 23, 15, 44)) # work around rounding difference among Python versions (PYTHON-230) expected = 1424817268.274 self.assertEqual(DateType.deserialize(int64_pack(int(1000 * expected)), 0), datetime.datetime(2015, 2, 24, 22, 34, 28, 274000)) # Large date overflow (PYTHON-452) expected = 2177403010.123 self.assertEqual(DateType.deserialize(int64_pack(int(1000 * expected)), 0), datetime.datetime(2038, 12, 31, 10, 10, 10, 123000)) + def test_collection_null_support(self): + """ + Test that null values in collection are decoded properly. + + @jira_ticket PYTHON-1123 + """ + int_list = ListType.apply_parameters([Int32Type]) + value = ( + int32_pack(2) + # num items + int32_pack(-1) + # size of item1 + int32_pack(4) + # size of item2 + int32_pack(42) # item2 + ) + self.assertEqual( + [None, 42], + int_list.deserialize(value, 3) + ) + + set_list = SetType.apply_parameters([Int32Type]) + self.assertEqual( + {None, 42}, + set(set_list.deserialize(value, 3)) + ) + + value = ( + int32_pack(2) + # num items + int32_pack(4) + # key size of item1 + int32_pack(42) + # key item1 + int32_pack(-1) + # value size of item1 + int32_pack(-1) + # key size of item2 + int32_pack(4) + # value size of item2 + int32_pack(42) # value of item2 + ) + + map_list = MapType.apply_parameters([Int32Type, Int32Type]) + self.assertEqual( + [(42, None), (None, 42)], + map_list.deserialize(value, 3)._items # OrderedMapSerializedKey + ) + def test_write_read_string(self): with tempfile.TemporaryFile() as f: value = u'test' write_string(f, value) f.seek(0) self.assertEqual(read_string(f), value) def test_write_read_longstring(self): with tempfile.TemporaryFile() as f: value = u'test' write_longstring(f, value) f.seek(0) self.assertEqual(read_longstring(f), value) def test_write_read_stringmap(self): with tempfile.TemporaryFile() as f: value = {'key': 'value'} write_stringmap(f, value) f.seek(0) self.assertEqual(read_stringmap(f), value) def test_write_read_inet(self): with tempfile.TemporaryFile() as f: value = ('192.168.1.1', 9042) write_inet(f, value) f.seek(0) self.assertEqual(read_inet(f), value) with tempfile.TemporaryFile() as f: value = ('2001:db8:0:f101::1', 9042) write_inet(f, value) f.seek(0) self.assertEqual(read_inet(f), value) def test_cql_quote(self): self.assertEqual(cql_quote(u'test'), "'test'") self.assertEqual(cql_quote('test'), "'test'") self.assertEqual(cql_quote(0), '0') -class TestOrdering(unittest.TestCase): - def _check_order_consistency(self, smaller, bigger, equal=False): - self.assertLessEqual(smaller, bigger) - self.assertGreaterEqual(bigger, smaller) - if equal: - self.assertEqual(smaller, bigger) - else: - self.assertNotEqual(smaller, bigger) - self.assertLess(smaller, bigger) - self.assertGreater(bigger, smaller) +ZERO = datetime.timedelta(0) + + +class UTC(datetime.tzinfo): + """UTC""" + + def utcoffset(self, dt): + return ZERO + + def tzname(self, dt): + return "UTC" + + def dst(self, dt): + return ZERO + + +try: + utc_timezone = datetime.timezone.utc +except AttributeError: + utc_timezone = UTC() + +class DateRangeTypeTests(unittest.TestCase): + dt = datetime.datetime(1990, 2, 3, 13, 58, 45, 777777) + timestamp = 1485963732404 + + def test_month_rounding_creation_failure(self): + """ + @jira_ticket PYTHON-912 + """ + feb_stamp = ms_timestamp_from_datetime( + datetime.datetime(2018, 2, 25, 18, 59, 59, 0) + ) + dr = DateRange(OPEN_BOUND, + DateRangeBound(feb_stamp, DateRangePrecision.MONTH)) + dt = datetime_from_timestamp(dr.upper_bound.milliseconds / 1000) + self.assertEqual(dt.day, 28) + + # Leap year + feb_stamp_leap_year = ms_timestamp_from_datetime( + datetime.datetime(2016, 2, 25, 18, 59, 59, 0) + ) + dr = DateRange(OPEN_BOUND, + DateRangeBound(feb_stamp_leap_year, DateRangePrecision.MONTH)) + dt = datetime_from_timestamp(dr.upper_bound.milliseconds / 1000) + self.assertEqual(dt.day, 29) + + def test_decode_precision(self): + self.assertEqual(DateRangeType._decode_precision(6), 'MILLISECOND') + + def test_decode_precision_error(self): + with self.assertRaises(ValueError): + DateRangeType._decode_precision(-1) + + def test_encode_precision(self): + self.assertEqual(DateRangeType._encode_precision('SECOND'), 5) + + def test_encode_precision_error(self): + with self.assertRaises(ValueError): + DateRangeType._encode_precision('INVALID') + + def test_deserialize_single_value(self): + serialized = (int8_pack(0) + + int64_pack(self.timestamp) + + int8_pack(3)) + self.assertEqual( + DateRangeType.deserialize(serialized, 5), + util.DateRange(value=util.DateRangeBound( + value=datetime.datetime(2017, 2, 1, 15, 42, 12, 404000), + precision='HOUR') + ) + ) + + def test_deserialize_closed_range(self): + serialized = (int8_pack(1) + + int64_pack(self.timestamp) + + int8_pack(2) + + int64_pack(self.timestamp) + + int8_pack(6)) + self.assertEqual( + DateRangeType.deserialize(serialized, 5), + util.DateRange( + lower_bound=util.DateRangeBound( + value=datetime.datetime(2017, 2, 1, 0, 0), + precision='DAY' + ), + upper_bound=util.DateRangeBound( + value=datetime.datetime(2017, 2, 1, 15, 42, 12, 404000), + precision='MILLISECOND' + ) + ) + ) + + def test_deserialize_open_high(self): + serialized = (int8_pack(2) + + int64_pack(self.timestamp) + + int8_pack(3)) + deserialized = DateRangeType.deserialize(serialized, 5) + self.assertEqual( + deserialized, + util.DateRange( + lower_bound=util.DateRangeBound( + value=datetime.datetime(2017, 2, 1, 15, 0), + precision='HOUR' + ), + upper_bound=util.OPEN_BOUND + ) + ) + + def test_deserialize_open_low(self): + serialized = (int8_pack(3) + + int64_pack(self.timestamp) + + int8_pack(4)) + deserialized = DateRangeType.deserialize(serialized, 5) + self.assertEqual( + deserialized, + util.DateRange( + lower_bound=util.OPEN_BOUND, + upper_bound=util.DateRangeBound( + value=datetime.datetime(2017, 2, 1, 15, 42, 20, 1000), + precision='MINUTE' + ) + ) + ) + + def test_deserialize_single_open(self): + self.assertEqual( + util.DateRange(value=util.OPEN_BOUND), + DateRangeType.deserialize(int8_pack(5), 5) + ) + + def test_serialize_single_value(self): + serialized = (int8_pack(0) + + int64_pack(self.timestamp) + + int8_pack(5)) + deserialized = DateRangeType.deserialize(serialized, 5) + self.assertEqual( + deserialized, + util.DateRange( + value=util.DateRangeBound( + value=datetime.datetime(2017, 2, 1, 15, 42, 12), + precision='SECOND' + ) + ) + ) + + def test_serialize_closed_range(self): + serialized = (int8_pack(1) + + int64_pack(self.timestamp) + + int8_pack(5) + + int64_pack(self.timestamp) + + int8_pack(0)) + deserialized = DateRangeType.deserialize(serialized, 5) + self.assertEqual( + deserialized, + util.DateRange( + lower_bound=util.DateRangeBound( + value=datetime.datetime(2017, 2, 1, 15, 42, 12), + precision='SECOND' + ), + upper_bound=util.DateRangeBound( + value=datetime.datetime(2017, 12, 31), + precision='YEAR' + ) + ) + ) + + def test_serialize_open_high(self): + serialized = (int8_pack(2) + + int64_pack(self.timestamp) + + int8_pack(2)) + deserialized = DateRangeType.deserialize(serialized, 5) + self.assertEqual( + deserialized, + util.DateRange( + lower_bound=util.DateRangeBound( + value=datetime.datetime(2017, 2, 1), + precision='DAY' + ), + upper_bound=util.OPEN_BOUND + ) + ) + + def test_serialize_open_low(self): + serialized = (int8_pack(2) + + int64_pack(self.timestamp) + + int8_pack(3)) + deserialized = DateRangeType.deserialize(serialized, 5) + self.assertEqual( + deserialized, + util.DateRange( + lower_bound=util.DateRangeBound( + value=datetime.datetime(2017, 2, 1, 15), + precision='HOUR' + ), + upper_bound=util.OPEN_BOUND + ) + ) + + def test_deserialize_both_open(self): + serialized = (int8_pack(4)) + deserialized = DateRangeType.deserialize(serialized, 5) + self.assertEqual( + deserialized, + util.DateRange( + lower_bound=util.OPEN_BOUND, + upper_bound=util.OPEN_BOUND + ) + ) + + def test_serialize_single_open(self): + serialized = DateRangeType.serialize(util.DateRange( + value=util.OPEN_BOUND, + ), 5) + self.assertEqual(int8_pack(5), serialized) + + def test_serialize_both_open(self): + serialized = DateRangeType.serialize(util.DateRange( + lower_bound=util.OPEN_BOUND, + upper_bound=util.OPEN_BOUND + ), 5) + self.assertEqual(int8_pack(4), serialized) + + def test_failure_to_serialize_no_value_object(self): + self.assertRaises(ValueError, DateRangeType.serialize, object(), 5) + + def test_failure_to_serialize_no_bounds_object(self): + class no_bounds_object(object): + value = lower_bound = None + self.assertRaises(ValueError, DateRangeType.serialize, no_bounds_object, 5) + + def test_serialized_value_round_trip(self): + vals = [six.b('\x01\x00\x00\x01%\xe9a\xf9\xd1\x06\x00\x00\x01v\xbb>o\xff\x00'), + six.b('\x01\x00\x00\x00\xdcm\x03-\xd1\x06\x00\x00\x01v\xbb>o\xff\x00')] + for serialized in vals: + self.assertEqual( + serialized, + DateRangeType.serialize(DateRangeType.deserialize(serialized, 0), 0) + ) + + def test_serialize_zero_datetime(self): + """ + Test serialization where timestamp = 0 + + Companion test for test_deserialize_zero_datetime + + @since 2.0.0 + @jira_ticket PYTHON-729 + @expected_result serialization doesn't raise an error + + @test_category data_types + """ + DateRangeType.serialize(util.DateRange( + lower_bound=(datetime.datetime(1970, 1, 1), 'YEAR'), + upper_bound=(datetime.datetime(1970, 1, 1), 'YEAR') + ), 5) + + def test_deserialize_zero_datetime(self): + """ + Test deserialization where timestamp = 0 + + Reproduces PYTHON-729 + + @since 2.0.0 + @jira_ticket PYTHON-729 + @expected_result deserialization doesn't raise an error + + @test_category data_types + """ + DateRangeType.deserialize( + (int8_pack(1) + + int64_pack(0) + int8_pack(0) + + int64_pack(0) + int8_pack(0)), + 5 + ) + + +class DateRangeDeserializationTests(unittest.TestCase): + """ + These tests iterate over different timestamp values + and assert deserialization gives the expected value + """ + + starting_lower_value = 1514744108923 + """ + Sample starting value for the lower bound for DateRange + """ + starting_upper_value = 2148761288922 + """ + Sample starting value for the upper bound for DateRange + """ + + epoch = datetime.datetime(1970, 1, 1, tzinfo=utc_timezone) + + def test_deserialize_date_range_milliseconds(self): + """ + Test rounding from DateRange for milliseconds + + @since 2.0.0 + @jira_ticket PYTHON-898 + @expected_result + + @test_category data_types + """ + for i in range(1000): + lower_value = self.starting_lower_value + i + upper_value = self.starting_upper_value + i + dr = DateRange(DateRangeBound(lower_value, DateRangePrecision.MILLISECOND), + DateRangeBound(upper_value, DateRangePrecision.MILLISECOND)) + self.assertEqual(lower_value, dr.lower_bound.milliseconds) + self.assertEqual(upper_value, dr.upper_bound.milliseconds) + + def test_deserialize_date_range_seconds(self): + """ + Test rounding from DateRange for milliseconds + + @since 2.0.0 + @jira_ticket PYTHON-898 + @expected_result + + @test_category data_types + """ + + def truncate_last_figures(number, n=3): + """ + Truncates last n digits of a number + """ + return int(str(number)[:-n] + '0' * n) + + for i in range(1000): + lower_value = self.starting_lower_value + i * 900 + upper_value = self.starting_upper_value + i * 900 + dr = DateRange(DateRangeBound(lower_value, DateRangePrecision.SECOND), + DateRangeBound(upper_value, DateRangePrecision.SECOND)) + + self.assertEqual(truncate_last_figures(lower_value), dr.lower_bound.milliseconds) + upper_value = truncate_last_figures(upper_value) + 999 + self.assertEqual(upper_value, dr.upper_bound.milliseconds) + + def test_deserialize_date_range_minutes(self): + """ + Test rounding from DateRange for seconds + + @since 2.4.0 + @jira_ticket PYTHON-898 + @expected_result + + @test_category data_types + """ + self._deserialize_date_range({"second": 0, "microsecond": 0}, + DateRangePrecision.MINUTE, + # This lambda function given a truncated date adds + # one day minus one microsecond in microseconds + lambda x: x + 59 * 1000 + 999, + lambda original_value, i: original_value + i * 900 * 50) + + def test_deserialize_date_range_hours(self): + """ + Test rounding from DateRange for hours + + @since 2.4.0 + @jira_ticket PYTHON-898 + @expected_result + + @test_category data_types + """ + self._deserialize_date_range({"minute": 0, "second": 0, "microsecond": 0}, + DateRangePrecision.HOUR, + # This lambda function given a truncated date adds + # one hour minus one microsecond in microseconds + lambda x: x + + 59 * 60 * 1000 + + 59 * 1000 + + 999, + lambda original_value, i: original_value + i * 900 * 50 * 60) + + def test_deserialize_date_range_day(self): + """ + Test rounding from DateRange for hours + + @since 2.4.0 + @jira_ticket PYTHON-898 + @expected_result + + @test_category data_types + """ + self._deserialize_date_range({"hour": 0, "minute": 0, "second": 0, "microsecond": 0}, + DateRangePrecision.DAY, + # This lambda function given a truncated date adds + # one day minus one microsecond in microseconds + lambda x: x + + 23 * 60 * 60 * 1000 + + 59 * 60 * 1000 + + 59 * 1000 + + 999, + lambda original_value, i: original_value + i * 900 * 50 * 60 * 24) + + @unittest.skip("This is currently failig, see PYTHON-912") + def test_deserialize_date_range_month(self): + """ + Test rounding from DateRange for months + + @since 2.4.0 + @jira_ticket PYTHON-898 + @expected_result + + @test_category data_types + """ + def get_upper_bound(seconds): + """ + function that given a truncated date in seconds from the epoch returns that same date + but with the microseconds set to 999999, seconds to 59, minutes to 59, hours to 23 + and days 28, 29, 30 or 31 depending on the month. + The way to do this is to add one month and leave the date at YEAR-MONTH-01 00:00:00 000000. + Then substract one millisecond. + """ + dt = datetime.datetime.fromtimestamp(seconds / 1000.0, tz=utc_timezone) + dt = dt + datetime.timedelta(days=32) + dt = dt.replace(day=1) - datetime.timedelta(microseconds=1) + return int((dt - self.epoch).total_seconds() * 1000) + self._deserialize_date_range({"day": 1, "hour": 0, "minute": 0, "second": 0, "microsecond": 0}, + DateRangePrecision.MONTH, + get_upper_bound, + lambda original_value, i: original_value + i * 900 * 50 * 60 * 24 * 30) + + def test_deserialize_date_range_year(self): + """ + Test rounding from DateRange for year + + @since 2.4.0 + @jira_ticket PYTHON-898 + @expected_result + + @test_category data_types + """ + def get_upper_bound(seconds): + """ + function that given a truncated date in seconds from the epoch returns that same date + but with the microseconds set to 999999, seconds to 59, minutes to 59, hours to 23 + days 28, 29, 30 or 31 depending on the month and months to 12. + The way to do this is to add one year and leave the date at YEAR-01-01 00:00:00 000000. + Then substract one millisecond. + """ + dt = datetime.datetime.fromtimestamp(seconds / 1000.0, tz=utc_timezone) + dt = dt + datetime.timedelta(days=370) + dt = dt.replace(day=1) - datetime.timedelta(microseconds=1) + + diff = time.mktime(dt.timetuple()) - time.mktime(self.epoch.timetuple()) + return diff * 1000 + 999 + # This doesn't work for big values because it loses precision + #return int((dt - self.epoch).total_seconds() * 1000) + self._deserialize_date_range({"month": 1, "day": 1, "hour": 0, "minute": 0, "second": 0, "microsecond": 0}, + DateRangePrecision.YEAR, + get_upper_bound, + lambda original_value, i: original_value + i * 900 * 50 * 60 * 24 * 30 * 12 * 7) + + def _deserialize_date_range(self, truncate_kwargs, precision, + round_up_truncated_upper_value, increment_loop_variable): + """ + This functions iterates over several DateRange objects determined by + lower_value upper_value which are given as a value that represents seconds since the epoch. + We want to make sure the lower_value is correctly rounded down and the upper value is correctly rounded up. + In the case of rounding down we verify that the rounded down value + has the appropriate fields set to the minimum they could possible have. That is + 1 for months, 1 for days, 0 for hours, 0 for minutes, 0 for seconds, 0 for microseconds. + We use the generic function truncate_date which depends on truncate_kwargs for this + + In the case of rounding up we verify that the rounded up value has the appropriate fields set + to the maximum they could possible have. This is calculated by round_up_truncated_upper_value + which input is the truncated value from before. It is passed as an argument as the way + of calculating this is is different for every precision. + + :param truncate_kwargs: determine what values to truncate in truncate_date + :param precision: :class:`~util.DateRangePrecision` + :param round_up_truncated_upper_value: this is a function that gets a truncated date and + returns a new date with some fields set to the maximum possible value + :param increment_loop_variable: this is a function that given a starting value and the iteration + value returns a new date to serve as lower_bound/upper_bound. We need this because the value by which + dates are incremented depends on if the precision is seconds, minutes, hours, days and months + :return: + """ + + def truncate_date(number): + """ + Given a date in seconds since the epoch truncates ups to a certain precision depending on + truncate_kwargs. + The return is the truncated date in seconds since the epoch. + For example if truncate_kwargs = {"hour": 0, "minute": 0, "second": 0, "microsecond": 0} the returned + value will be the original given date but with the hours, minutes, seconds and microseconds set to 0 + """ + dt = datetime.datetime.fromtimestamp(number / 1000.0, tz=utc_timezone) + dt = dt.replace(**truncate_kwargs) + return round((dt - self.epoch).total_seconds() * 1000.0) + + for i in range(1000): + # We increment the lower_value and upper_value according to increment_loop_variable + lower_value = increment_loop_variable(self.starting_lower_value, i) + upper_value = increment_loop_variable(self.starting_upper_value, i) + + # Inside the __init__ for DateRange the rounding up and down should happen + dr = DateRange(DateRangeBound(lower_value, precision), + DateRangeBound(upper_value, precision)) + + # We verify that rounded value corresponds with what we would expect + self.assertEqual(truncate_date(lower_value), dr.lower_bound.milliseconds) + upper_value = round_up_truncated_upper_value(truncate_date(upper_value)) + self.assertEqual(upper_value, dr.upper_bound.milliseconds) + + +class TestOrdering(unittest.TestCase): def _shuffle_lists(self, *args): return [item for sublist in zip(*args) for item in sublist] - def _check_sequence_consistency(self, ordered_sequence, equal=False): - for i, el in enumerate(ordered_sequence): - for previous in ordered_sequence[:i]: - self._check_order_consistency(previous, el, equal) - for posterior in ordered_sequence[i + 1:]: - self._check_order_consistency(el, posterior, equal) - def test_host_order(self): """ Test Host class is ordered consistently @since 3.9 @jira_ticket PYTHON-714 @expected_result the hosts are ordered correctly @test_category data_types """ hosts = [Host(addr, SimpleConvictionPolicy) for addr in ("127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4")] hosts_equal = [Host(addr, SimpleConvictionPolicy) for addr in ("127.0.0.1", "127.0.0.1")] hosts_equal_conviction = [Host("127.0.0.1", SimpleConvictionPolicy), Host("127.0.0.1", ConvictionPolicy)] - self._check_sequence_consistency(hosts) - self._check_sequence_consistency(hosts_equal, equal=True) - self._check_sequence_consistency(hosts_equal_conviction, equal=True) + check_sequence_consistency(self, hosts) + check_sequence_consistency(self, hosts_equal, equal=True) + check_sequence_consistency(self, hosts_equal_conviction, equal=True) def test_date_order(self): """ Test Date class is ordered consistently @since 3.9 @jira_ticket PYTHON-714 @expected_result the dates are ordered correctly @test_category data_types """ dates_from_string = [Date("2017-01-01"), Date("2017-01-05"), Date("2017-01-09"), Date("2017-01-13")] dates_from_string_equal = [Date("2017-01-01"), Date("2017-01-01")] - self._check_sequence_consistency(dates_from_string) - self._check_sequence_consistency(dates_from_string_equal, equal=True) + check_sequence_consistency(self, dates_from_string) + check_sequence_consistency(self, dates_from_string_equal, equal=True) date_format = "%Y-%m-%d" dates_from_value = [ Date((datetime.datetime.strptime(dtstr, date_format) - datetime.datetime(1970, 1, 1)).days) for dtstr in ("2017-01-02", "2017-01-06", "2017-01-10", "2017-01-14") ] dates_from_value_equal = [Date(1), Date(1)] - self._check_sequence_consistency(dates_from_value) - self._check_sequence_consistency(dates_from_value_equal, equal=True) + check_sequence_consistency(self, dates_from_value) + check_sequence_consistency(self, dates_from_value_equal, equal=True) dates_from_datetime = [Date(datetime.datetime.strptime(dtstr, date_format)) for dtstr in ("2017-01-03", "2017-01-07", "2017-01-11", "2017-01-15")] dates_from_datetime_equal = [Date(datetime.datetime.strptime("2017-01-01", date_format)), Date(datetime.datetime.strptime("2017-01-01", date_format))] - self._check_sequence_consistency(dates_from_datetime) - self._check_sequence_consistency(dates_from_datetime_equal, equal=True) + check_sequence_consistency(self, dates_from_datetime) + check_sequence_consistency(self, dates_from_datetime_equal, equal=True) dates_from_date = [ Date(datetime.datetime.strptime(dtstr, date_format).date()) for dtstr in ("2017-01-04", "2017-01-08", "2017-01-12", "2017-01-16") ] dates_from_date_equal = [datetime.datetime.strptime(dtstr, date_format) for dtstr in ("2017-01-09", "2017-01-9")] - self._check_sequence_consistency(dates_from_date) - self._check_sequence_consistency(dates_from_date_equal, equal=True) + check_sequence_consistency(self, dates_from_date) + check_sequence_consistency(self, dates_from_date_equal, equal=True) - self._check_sequence_consistency(self._shuffle_lists(dates_from_string, dates_from_value, + check_sequence_consistency(self, self._shuffle_lists(dates_from_string, dates_from_value, dates_from_datetime, dates_from_date)) def test_timer_order(self): """ Test Time class is ordered consistently @since 3.9 @jira_ticket PYTHON-714 @expected_result the times are ordered correctly @test_category data_types """ time_from_int = [Time(1000), Time(4000), Time(7000), Time(10000)] time_from_int_equal = [Time(1), Time(1)] - self._check_sequence_consistency(time_from_int) - self._check_sequence_consistency(time_from_int_equal, equal=True) + check_sequence_consistency(self, time_from_int) + check_sequence_consistency(self, time_from_int_equal, equal=True) time_from_datetime = [Time(datetime.time(hour=0, minute=0, second=0, microsecond=us)) for us in (2, 5, 8, 11)] time_from_datetime_equal = [Time(datetime.time(hour=0, minute=0, second=0, microsecond=us)) for us in (1, 1)] - self._check_sequence_consistency(time_from_datetime) - self._check_sequence_consistency(time_from_datetime_equal, equal=True) + check_sequence_consistency(self, time_from_datetime) + check_sequence_consistency(self, time_from_datetime_equal, equal=True) time_from_string = [Time("00:00:00.000003000"), Time("00:00:00.000006000"), Time("00:00:00.000009000"), Time("00:00:00.000012000")] time_from_string_equal = [Time("00:00:00.000004000"), Time("00:00:00.000004000")] - self._check_sequence_consistency(time_from_string) - self._check_sequence_consistency(time_from_string_equal, equal=True) + check_sequence_consistency(self, time_from_string) + check_sequence_consistency(self, time_from_string_equal, equal=True) - self._check_sequence_consistency(self._shuffle_lists(time_from_int, time_from_datetime, time_from_string)) + check_sequence_consistency(self, self._shuffle_lists(time_from_int, time_from_datetime, time_from_string)) def test_token_order(self): """ Test Token class is ordered consistently @since 3.9 @jira_ticket PYTHON-714 @expected_result the tokens are ordered correctly @test_category data_types """ tokens = [Token(1), Token(2), Token(3), Token(4)] tokens_equal = [Token(1), Token(1)] - self._check_sequence_consistency(tokens) - self._check_sequence_consistency(tokens_equal, equal=True) + check_sequence_consistency(self, tokens) + check_sequence_consistency(self, tokens_equal, equal=True) diff --git a/tests/unit/test_util_types.py b/tests/unit/test_util_types.py index 8c60bfe..b7dc837 100644 --- a/tests/unit/test_util_types.py +++ b/tests/unit/test_util_types.py @@ -1,296 +1,292 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import unittest2 as unittest except ImportError: import unittest # noqa import datetime from cassandra.util import Date, Time, Duration, Version class DateTests(unittest.TestCase): def test_from_datetime(self): expected_date = datetime.date(1492, 10, 12) d = Date(expected_date) self.assertEqual(str(d), str(expected_date)) def test_from_string(self): expected_date = datetime.date(1492, 10, 12) d = Date(expected_date) sd = Date('1492-10-12') self.assertEqual(sd, d) sd = Date('+1492-10-12') self.assertEqual(sd, d) def test_from_date(self): expected_date = datetime.date(1492, 10, 12) d = Date(expected_date) self.assertEqual(d.date(), expected_date) def test_from_days(self): sd = Date(0) self.assertEqual(sd, Date(datetime.date(1970, 1, 1))) sd = Date(-1) self.assertEqual(sd, Date(datetime.date(1969, 12, 31))) sd = Date(1) self.assertEqual(sd, Date(datetime.date(1970, 1, 2))) def test_limits(self): min_builtin = Date(datetime.date(1, 1, 1)) max_builtin = Date(datetime.date(9999, 12, 31)) self.assertEqual(Date(min_builtin.days_from_epoch), min_builtin) self.assertEqual(Date(max_builtin.days_from_epoch), max_builtin) # just proving we can construct with on offset outside buildin range self.assertEqual(Date(min_builtin.days_from_epoch - 1).days_from_epoch, min_builtin.days_from_epoch - 1) self.assertEqual(Date(max_builtin.days_from_epoch + 1).days_from_epoch, max_builtin.days_from_epoch + 1) def test_invalid_init(self): self.assertRaises(ValueError, Date, '-1999-10-10') self.assertRaises(TypeError, Date, 1.234) def test_str(self): date_str = '2015-03-16' self.assertEqual(str(Date(date_str)), date_str) def test_out_of_range(self): self.assertEqual(str(Date(2932897)), '2932897') self.assertEqual(repr(Date(1)), 'Date(1)') def test_equals(self): self.assertEqual(Date(1234), 1234) self.assertEqual(Date(1), datetime.date(1970, 1, 2)) self.assertFalse(Date(2932897) == datetime.date(9999, 12, 31)) # date can't represent year > 9999 self.assertEqual(Date(2932897), 2932897) class TimeTests(unittest.TestCase): def test_units_from_string(self): one_micro = 1000 one_milli = 1000 * one_micro one_second = 1000 * one_milli one_minute = 60 * one_second one_hour = 60 * one_minute tt = Time('00:00:00.000000001') self.assertEqual(tt.nanosecond_time, 1) tt = Time('00:00:00.000001') self.assertEqual(tt.nanosecond_time, one_micro) tt = Time('00:00:00.001') self.assertEqual(tt.nanosecond_time, one_milli) tt = Time('00:00:01') self.assertEqual(tt.nanosecond_time, one_second) tt = Time('00:01:00') self.assertEqual(tt.nanosecond_time, one_minute) tt = Time('01:00:00') self.assertEqual(tt.nanosecond_time, one_hour) tt = Time('01:00:00.') self.assertEqual(tt.nanosecond_time, one_hour) tt = Time('23:59:59.123456') self.assertEqual(tt.nanosecond_time, 23 * one_hour + 59 * one_minute + 59 * one_second + 123 * one_milli + 456 * one_micro) tt = Time('23:59:59.1234567') self.assertEqual(tt.nanosecond_time, 23 * one_hour + 59 * one_minute + 59 * one_second + 123 * one_milli + 456 * one_micro + 700) tt = Time('23:59:59.12345678') self.assertEqual(tt.nanosecond_time, 23 * one_hour + 59 * one_minute + 59 * one_second + 123 * one_milli + 456 * one_micro + 780) tt = Time('23:59:59.123456789') self.assertEqual(tt.nanosecond_time, 23 * one_hour + 59 * one_minute + 59 * one_second + 123 * one_milli + 456 * one_micro + 789) def test_micro_precision(self): Time('23:59:59.1') Time('23:59:59.12') Time('23:59:59.123') Time('23:59:59.1234') Time('23:59:59.12345') def test_from_int(self): tt = Time(12345678) self.assertEqual(tt.nanosecond_time, 12345678) def test_from_time(self): expected_time = datetime.time(12, 1, 2, 3) tt = Time(expected_time) self.assertEqual(tt, expected_time) def test_as_time(self): expected_time = datetime.time(12, 1, 2, 3) tt = Time(expected_time) self.assertEqual(tt.time(), expected_time) def test_equals(self): # util.Time self equality self.assertEqual(Time(1234), Time(1234)) def test_str_repr(self): time_str = '12:13:14.123456789' self.assertEqual(str(Time(time_str)), time_str) self.assertEqual(repr(Time(1)), 'Time(1)') def test_invalid_init(self): self.assertRaises(ValueError, Time, '1999-10-10 11:11:11.1234') self.assertRaises(TypeError, Time, 1.234) self.assertRaises(ValueError, Time, 123456789000000) self.assertRaises(TypeError, Time, datetime.datetime(2004, 12, 23, 11, 11, 1)) class DurationTests(unittest.TestCase): def test_valid_format(self): valid = Duration(1, 1, 1) self.assertEqual(valid.months, 1) self.assertEqual(valid.days, 1) self.assertEqual(valid.nanoseconds, 1) valid = Duration(nanoseconds=100000) self.assertEqual(valid.months, 0) self.assertEqual(valid.days, 0) self.assertEqual(valid.nanoseconds, 100000) valid = Duration() self.assertEqual(valid.months, 0) self.assertEqual(valid.days, 0) self.assertEqual(valid.nanoseconds, 0) valid = Duration(-10, -21, -1000) self.assertEqual(valid.months, -10) self.assertEqual(valid.days, -21) self.assertEqual(valid.nanoseconds, -1000) def test_equality(self): first = Duration(1, 1, 1) second = Duration(-1, 1, 1) self.assertNotEqual(first, second) first = Duration(1, 1, 1) second = Duration(1, 1, 1) self.assertEqual(first, second) first = Duration() second = Duration(0, 0, 0) self.assertEqual(first, second) first = Duration(1000, 10000, 2345345) second = Duration(1000, 10000, 2345345) self.assertEqual(first, second) first = Duration(12, 0 , 100) second = Duration(nanoseconds=100, months=12) self.assertEqual(first, second) def test_str(self): self.assertEqual(str(Duration(1, 1, 1)), "1mo1d1ns") self.assertEqual(str(Duration(1, 1, -1)), "-1mo1d1ns") self.assertEqual(str(Duration(1, 1, 1000000000000000)), "1mo1d1000000000000000ns") self.assertEqual(str(Duration(52, 23, 564564)), "52mo23d564564ns") class VersionTests(unittest.TestCase): def test_version_parsing(self): versions = [ ('2.0.0', (2, 0, 0, 0, 0)), ('3.1.0', (3, 1, 0, 0, 0)), ('2.4.54', (2, 4, 54, 0, 0)), ('3.1.1.12', (3, 1, 1, 12, 0)), ('3.55.1.build12', (3, 55, 1, 'build12', 0)), ('3.55.1.20190429-TEST', (3, 55, 1, 20190429, 'TEST')), ('4.0-SNAPSHOT', (4, 0, 0, 0, 'SNAPSHOT')), + ('1.0.5.4.3', (1, 0, 5, 4, 0)), + ('1-SNAPSHOT', (1, 0, 0, 0, 'SNAPSHOT')), + ('4.0.1.2.3.4.5-ABC-123-SNAP-TEST.blah', (4, 0, 1, 2, 'ABC-123-SNAP-TEST.blah')), + ('2.1.hello', (2, 1, 0, 0, 0)), + ('2.test.1', (2, 0, 0, 0, 0)), ] for str_version, expected_result in versions: v = Version(str_version) self.assertEqual(str_version, str(v)) self.assertEqual(v.major, expected_result[0]) self.assertEqual(v.minor, expected_result[1]) self.assertEqual(v.patch, expected_result[2]) self.assertEqual(v.build, expected_result[3]) self.assertEqual(v.prerelease, expected_result[4]) # not supported version formats - with self.assertRaises(ValueError): - Version('2.1.hello') - - with self.assertRaises(ValueError): - Version('2.test.1') - with self.assertRaises(ValueError): Version('test.1.0') - with self.assertRaises(ValueError): - Version('1.0.0.0.1') - def test_version_compare(self): # just tests a bunch of versions # major wins self.assertTrue(Version('3.3.0') > Version('2.5.0')) self.assertTrue(Version('3.3.0') > Version('2.5.0.66')) self.assertTrue(Version('3.3.0') > Version('2.5.21')) # minor wins self.assertTrue(Version('2.3.0') > Version('2.2.0')) self.assertTrue(Version('2.3.0') > Version('2.2.7')) self.assertTrue(Version('2.3.0') > Version('2.2.7.9')) # patch wins self.assertTrue(Version('2.3.1') > Version('2.3.0')) self.assertTrue(Version('2.3.1') > Version('2.3.0.4post0')) self.assertTrue(Version('2.3.1') > Version('2.3.0.44')) # various self.assertTrue(Version('2.3.0.1') > Version('2.3.0.0')) self.assertTrue(Version('2.3.0.680') > Version('2.3.0.670')) self.assertTrue(Version('2.3.0.681') > Version('2.3.0.680')) self.assertTrue(Version('2.3.0.1build0') > Version('2.3.0.1')) # 4th part fallback to str cmp self.assertTrue(Version('2.3.0.build0') > Version('2.3.0.1')) # 4th part fallback to str cmp self.assertTrue(Version('2.3.0') < Version('2.3.0.build')) self.assertTrue(Version('4-a') <= Version('4.0.0')) self.assertTrue(Version('4-a') <= Version('4.0-alpha1')) self.assertTrue(Version('4-a') <= Version('4.0-beta1')) self.assertTrue(Version('4.0.0') >= Version('4.0.0')) self.assertTrue(Version('4.0.0.421') >= Version('4.0.0')) self.assertTrue(Version('4.0.1') >= Version('4.0.0')) self.assertTrue(Version('2.3.0') == Version('2.3.0')) self.assertTrue(Version('2.3.32') == Version('2.3.32')) self.assertTrue(Version('2.3.32') == Version('2.3.32.0')) self.assertTrue(Version('2.3.0.build') == Version('2.3.0.build')) self.assertTrue(Version('4') == Version('4.0.0')) self.assertTrue(Version('4.0') == Version('4.0.0.0')) self.assertTrue(Version('4.0') > Version('3.9.3')) self.assertTrue(Version('4.0') > Version('4.0-SNAPSHOT')) self.assertTrue(Version('4.0-SNAPSHOT') == Version('4.0-SNAPSHOT')) self.assertTrue(Version('4.0.0-SNAPSHOT') == Version('4.0-SNAPSHOT')) self.assertTrue(Version('4.0.0-SNAPSHOT') == Version('4.0.0-SNAPSHOT')) self.assertTrue(Version('4.0.0.build5-SNAPSHOT') == Version('4.0.0.build5-SNAPSHOT')) self.assertTrue(Version('4.1-SNAPSHOT') > Version('4.0-SNAPSHOT')) self.assertTrue(Version('4.0.1-SNAPSHOT') > Version('4.0.0-SNAPSHOT')) self.assertTrue(Version('4.0.0.build6-SNAPSHOT') > Version('4.0.0.build5-SNAPSHOT')) self.assertTrue(Version('4.0-SNAPSHOT2') > Version('4.0-SNAPSHOT1')) self.assertTrue(Version('4.0-SNAPSHOT2') > Version('4.0.0-SNAPSHOT1')) self.assertTrue(Version('4.0.0-alpha1-SNAPSHOT') > Version('4.0.0-SNAPSHOT')) diff --git a/tests/unit/util.py b/tests/unit/util.py new file mode 100644 index 0000000..e57fa6c --- /dev/null +++ b/tests/unit/util.py @@ -0,0 +1,30 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +def check_sequence_consistency(unit_test, ordered_sequence, equal=False): + for i, el in enumerate(ordered_sequence): + for previous in ordered_sequence[:i]: + _check_order_consistency(unit_test, previous, el, equal) + for posterior in ordered_sequence[i + 1:]: + _check_order_consistency(unit_test, el, posterior, equal) + + +def _check_order_consistency(unit_test, smaller, bigger, equal=False): + unit_test.assertLessEqual(smaller, bigger) + unit_test.assertGreaterEqual(bigger, smaller) + if equal: + unit_test.assertEqual(smaller, bigger) + else: + unit_test.assertNotEqual(smaller, bigger) + unit_test.assertLess(smaller, bigger) + unit_test.assertGreater(bigger, smaller) diff --git a/tests/unit/utils.py b/tests/unit/utils.py index b3ac113..3c9cc34 100644 --- a/tests/unit/utils.py +++ b/tests/unit/utils.py @@ -1,18 +1,33 @@ +# Copyright DataStax, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + from concurrent.futures import Future from functools import wraps from cassandra.cluster import Session from mock import patch + def mock_session_pools(f): """ Helper decorator that allows tests to initialize :class:.`Session` objects without actually connecting to a Cassandra cluster. """ @wraps(f) def wrapper(*args, **kwargs): with patch.object(Session, "add_or_renew_pool") as mocked_add_or_renew_pool: future = Future() future.set_result(object()) mocked_add_or_renew_pool.return_value = future f(*args, **kwargs) return wrapper diff --git a/tests/integration/util.py b/tests/util.py similarity index 55% copy from tests/integration/util.py copy to tests/util.py index a2ce9d5..5c7ac24 100644 --- a/tests/integration/util.py +++ b/tests/util.py @@ -1,109 +1,74 @@ # Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -from tests.integration import PROTOCOL_VERSION -from functools import wraps + import time - - -def assert_quiescent_pool_state(test_case, cluster, wait=None): - """ - Checking the quiescent pool state checks that none of the requests ids have - been lost. However, the callback corresponding to a request_id is called - before the request_id is returned back to the pool, therefore - - session.execute("SELECT * from system.local") - assert_quiescent_pool_state(self, session.cluster) - - (with no wait) might fail because when execute comes back the request_id - hasn't yet been returned to the pool, therefore the wait. - """ - if wait is not None: - time.sleep(wait) - - for session in cluster.sessions: - pool_states = session.get_pool_state().values() - test_case.assertTrue(pool_states) - - for state in pool_states: - test_case.assertFalse(state['shutdown']) - test_case.assertGreater(state['open_count'], 0) - test_case.assertTrue(all((i == 0 for i in state['in_flights']))) - - for holder in cluster.get_connection_holders(): - for connection in holder.get_connections(): - # all ids are unique - req_ids = connection.request_ids - test_case.assertEqual(len(req_ids), len(set(req_ids))) - test_case.assertEqual(connection.highest_request_id, len(req_ids) - 1) - test_case.assertEqual(connection.highest_request_id, max(req_ids)) - if PROTOCOL_VERSION < 3: - test_case.assertEqual(connection.highest_request_id, connection.max_request_id) +from functools import wraps def wait_until(condition, delay, max_attempts): """ Executes a function at regular intervals while the condition is false and the amount of attempts < maxAttempts. :param condition: a function :param delay: the delay in second :param max_attempts: the maximum number of attempts. So the timeout of this function is delay*max_attempts """ attempt = 0 while not condition() and attempt < max_attempts: attempt += 1 time.sleep(delay) if attempt >= max_attempts: raise Exception("Condition is still False after {} attempts.".format(max_attempts)) def wait_until_not_raised(condition, delay, max_attempts): """ Executes a function at regular intervals while the condition doesn't raise an exception and the amount of attempts < maxAttempts. :param condition: a function :param delay: the delay in second :param max_attempts: the maximum number of attemps. So the timeout of this function will be delay*max_attempts """ def wrapped_condition(): try: - condition() + result = condition() except: - return False + return False, None - return True + return True, result attempt = 0 while attempt < (max_attempts-1): attempt += 1 - if wrapped_condition(): - return + success, result = wrapped_condition() + if success: + return result time.sleep(delay) # last attempt, let the exception raise - condition() + return condition() def late(seconds=1): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): time.sleep(seconds) func(*args, **kwargs) return wrapper return decorator diff --git a/tox.ini b/tox.ini index 629c3f2..d883a1f 100644 --- a/tox.ini +++ b/tox.ini @@ -1,44 +1,51 @@ [tox] -envlist = py{27,34,35,36,37},pypy +envlist = py{27,35,36,37,38},pypy [base] deps = nose mock<=1.0.1 six packaging cython eventlet twisted <15.5.0 + pure-sasl + kerberos futurist +lz4_dependency = py27,py35,py36,py37,py38: lz4 [testenv] deps = {[base]deps} + {[base]lz4_dependency} setenv = LIBEV_EMBED=0 CARES_EMBED=0 + LC_ALL=en_US.UTF-8 changedir = {envtmpdir} commands = nosetests --verbosity=2 --no-path-adjustment {toxinidir}/tests/unit/ [testenv:gevent_loop] deps = {[base]deps} - gevent + {[base]lz4_dependency} + gevent>=1.4,<1.5 setenv = LIBEV_EMBED=0 CARES_EMBED=0 EVENT_LOOP_MANAGER=gevent changedir = {envtmpdir} commands = nosetests --verbosity=2 --no-path-adjustment {toxinidir}/tests/unit/io/test_geventreactor.py [testenv:eventlet_loop] deps = {[base]deps} - gevent + {[base]lz4_dependency} + gevent>=1.4,<1.5 setenv = LIBEV_EMBED=0 CARES_EMBED=0 EVENT_LOOP_MANAGER=eventlet changedir = {envtmpdir} commands = nosetests --verbosity=2 --no-path-adjustment {toxinidir}/tests/unit/io/test_eventletreactor.py