Returns a Cluster Builder.
public static cluster ( ) : Cassandra\Cluster\Builder | ||
Résultat | Cassandra\Cluster\Builder | a Cluster Builder instance |
/** * Override this method in your own implementation to configure the Cassandra cluster instance. */ protected function initializeCluster() { // contact points can an array or a string, optionally having multiple // comma-separated node host names / IP addresses $contactPoints = $this->container->getParameter('cassandra_cluster.contact_points'); if (!is_array($contactPoints)) { $contactPoints = implode($contactPoints, ','); foreach ($contactPoints as &$contactPoint) { $contactPoint = trim($contactPoint); } } $cluster = \Cassandra::cluster(); if (PHP_VERSION_ID < 50600) { call_user_func_array(array($cluster, "withContactPoints"), $contactPoints); } else { // PHP > 5.6 implements variadic parameters $cluster->withContactPoints(...$contactPoints); } $cluster->withPersistentSessions(true); // always use persistent connections but be explicit about it if ($this->container->hasParameter('cassandra_cluster.credentials.username') && $this->container->hasParameter('cassandra_cluster.credentials.password')) { $username = $this->container->getParameter('cassandra_cluster.credentials.username'); $password = $this->container->getParameter('cassandra_cluster.credentials.password'); $cluster->withCredentials($username, $password); } $this->cluster = $cluster->build(); }
/** * Create the table and client side timestamp session for the timestamp * tests. */ public function setUp() { // Process parent setup steps parent::setUp(); // Create the table $query = "CREATE TABLE {$this->tableNamePrefix} (key int PRIMARY KEY, value_int int)"; $this->session->execute(new SimpleStatement($query)); // Generate the insert and select queries $this->insertQuery = "INSERT INTO {$this->tableNamePrefix} (key, value_int) VALUES (?, ?)"; $this->selectQuery = "SELECT writeTime(value_int) FROM {$this->tableNamePrefix} WHERE key = ?"; // Create the connection for client side timestamps $cluster = \Cassandra::cluster()->withContactPoints(Integration::IP_ADDRESS)->withTimestampGenerator(new TimestampGenerator\Monotonic())->build(); $this->clientSideTimestampSession = $cluster->connect($this->keyspaceName); }
<?php require_once 'vendor/autoload.php'; use CfCommunity\CfHelper\CfHelper; $cfHelper = CfHelper::getInstance(); # Get Cassandra VCAP_SERVICES values $serviceManager = $cfHelper->getServiceManager(); #Cassandra service has to have cassandra in the name $cassandraService = $serviceManager->getService('.*cassandra.*'); $node_ips = $cassandraService->getValue('node_ips'); $username = $cassandraService->getValue('username'); $password = $cassandraService->getValue('password'); #Datastax driver will autoconnect to rest of nodes based off one node connection $node = current($node_ips); #Connects to the Cassandra service $cluster = Cassandra::cluster()->withCredentials($username, $password)->withContactPoints($node)->build(); $session = $cluster->connect(); #Print keyspaces and tables $keyspaces = $session->schema()->keyspaces(); echo "<table border=\"1\">"; echo "<tr><th>Keyspace</th><th>Table</th></tr>"; foreach ($keyspaces as $keyspace) { foreach ($keyspace->tables() as $table) { echo sprintf("<tr><td>%s</td><td>%s</td></tr>\n", $keyspace->name(), $table->name()); } } echo "</table>";
/** * Create a new connection instance with the provided configuration */ public function __construct() { // Set up connection details $builder = \Cassandra::cluster(); // Fetch configured port and set it, if it's provided $port = config('cassandra.port'); if (!empty($port)) { $builder->withPort($port); } // Fetch configured default page size and set it, if it's provided $defaultPageSize = config('cassandra.defaultPageSize'); if (!empty($defaultPageSize)) { $builder->withDefaultPageSize($defaultPageSize); } // Fetch configured default consistency level and set it, if it's provided $defaultConsistency = config('cassandra.withDefaultConsistency'); if (!empty($defaultConsistency)) { $builder->withDefaultConsistency($defaultConsistency); } // Set contact end points call_user_func_array([$builder, "withContactPoints"], config('cassandra.contactpoints')); // Connect to cluster $this->cluster = $builder->build(); // Create a connect to the keyspace on cluster $this->session = $this->cluster->connect(config('cassandra.keyspace')); }
public function start() { $this->run('start', '--wait-other-notice', '--wait-for-binary-proto'); $builder = Cassandra::cluster()->withPersistentSessions(false)->withContactPoints('127.0.0.1'); if ($this->ssl || $this->clientAuth) { $sslOptions = Cassandra::ssl()->withTrustedCerts(realpath(__DIR__ . '/ssl/cassandra.pem'))->withVerifyFlags(Cassandra::VERIFY_PEER_CERT)->withClientCert(realpath(__DIR__ . '/ssl/driver.pem'))->withPrivateKey(realpath(__DIR__ . '/ssl/driver.key'), 'php-driver')->build(); $builder->withSSL($sslOptions); } for ($retries = 1; $retries <= 10; $retries++) { try { $this->cluster = $builder->build(); $this->session = $this->cluster->connect(); break; } catch (Cassandra\Exception\RuntimeException $e) { unset($this->session); unset($this->cluster); sleep($retries * 0.4); } } if (!isset($this->session)) { throw new RuntimeException("Unable to initialize a Session, check cassandra logs"); } }
<?php if (!extension_loaded('cassandra')) { die("Unable to load cassandra extension\n"); } try { $cluster = Cassandra::cluster()->withContactPoints('127.0.0.1')->build(); $session = $cluster->connect(); echo "connection success\n"; } catch (Cassandra\Exception $e) { echo "connection failure\n"; echo get_class($e) . ": " . $e->getMessage() . "\n"; }
function retrieveRecord($id) { $cluster = Cassandra::cluster()->build(); $session = $cluster->connect('europeana'); $statement = new Cassandra\SimpleStatement(sprintf("SELECT content FROM edm WHERE id = '%s'", $id)); $future = $session->executeAsync($statement); $result = $future->get(); $json = null; foreach ($result as $row) { $json = $row['content']; } return json_decode($json); }
/** * Create the integration helper instance. * * @param $className Name of the class for the executed test. * @param string $testName Name of the test being executed. * @param int $numberDC1Nodes Number of nodes in data center one * (DEFAULT: 1). * @param int $numberDC2Nodes Number of nodes in data center two * (DEFAULT: 0). * @param int $replicationFactor Replication factor override; default is * calculated based on number of data center * nodes; single data center is (nodes / 2) * rounded up. * @param bool $isClientAuthentication True if client authentication * should be enabled; false * otherwise (DEFAULT: false). * @param bool $isSSL True if SSL should be enabled; false otherwise * (DEFAULT: false). * @return Integration Instance of the Integration class created. */ public function __construct($className, $testName = "", $numberDC1Nodes = 1, $numberDC2Nodes = 0, $replicationFactor = -1, $isClientAuthentication = false, $isSSL = false) { // Generate the keyspace name for the test $this->keyspaceName = $this->getShortName($className); if (!empty($testName)) { $this->keyspaceName = $this->keyspaceName . "_" . $testName; } // Make all strings lowercase for case insensitive O/S (e.g. Windows) $this->keyspaceName = strtolower($this->keyspaceName); //Ensure the keyspace does not contain more to many characters if (strlen($this->keyspaceName) > self::KEYSPACE_MAXIMUM_LENGTH) { // Update the keyspace name with a unique ID $uniqueID = uniqid(); $this->keyspaceName = substr($this->keyspaceName, 0, self::KEYSPACE_MAXIMUM_LENGTH - strlen($uniqueID)) . $uniqueID; } // Create the Cassandra cluster for the test //TODO: Need to add the ability to switch the Cassandra version (command line) $this->ccm = new \CCM(self::CASSANDRA_VERSION, self::IS_CCM_SILENT); $this->ccm->setup($numberDC1Nodes, $numberDC2Nodes); if ($isClientAuthentication) { $this->ccm->setupClientVerification(); } if ($isSSL) { $this->ccm->setupSSL(); } $this->ccm->start(); // Determine replication strategy and generate the query $replicationStrategy = "'SimpleStrategy', 'replication_factor': "; if ($numberDC2Nodes > 0) { $replicationStrategy = "'NetworkTopologyStrategy', 'dc1': " . $numberDC1Nodes . ", " . "'dc2': " . $numberDC2Nodes; } else { if ($replicationFactor < 0) { $replicationFactor = $numberDC1Nodes % 2 == 0 ? $numberDC1Nodes / 2 : ($numberDC1Nodes + 1) / 2; } $replicationStrategy .= $replicationFactor; } $query = sprintf(Integration::SIMPLE_KEYSPACE_FORMAT, $this->keyspaceName, $replicationStrategy); if (self::isDebug() && self::isVerbose()) { fprintf(STDOUT, "Creating Keyspace: %s" . PHP_EOL, $query); } // Create the session and keyspace for the integration test $this->cluster = \Cassandra::cluster()->withContactPoints($this->getContactPoints(Integration::IP_ADDRESS, $numberDC1Nodes + $numberDC2Nodes))->withPersistentSessions(false)->build(); $this->session = $this->cluster->connect(); $statement = new SimpleStatement($query); $this->session->execute($statement); // Update the session to use the new keyspace by default $statement = new SimpleStatement("USE " . $this->keyspaceName); $this->session->execute($statement); // Get the server version the session is connected to $statement = new SimpleStatement(self::SELECT_SERVER_VERSION); $rows = $this->session->execute($statement); $this->serverVersion = $rows->first()["release_version"]; }
/** * Initialize the SQL datastore. */ protected function __construct() { $config = SimpleSAML_Configuration::getInstance(); $keyspace = $config->getString('store.cassandra.keyspace'); $nodes = $config->getArrayize('store.cassandra.nodes'); $use_ssl = $config->getBoolean('store.cassandra.use_ssl', false); $ssl_ca = $config->getString('store.cassandra.ssl_ca', null); $username = $config->getString('store.cassandra.username', null); $password = $config->getString('store.cassandra.password', null); $cluster = \Cassandra::cluster()->withContactPoints(implode(',', $nodes))->withDefaultConsistency(\Cassandra::CONSISTENCY_LOCAL_QUORUM); if (isset($username) && isset($password)) { $cluster = $cluster->withCredentials($username, $password); } if ($use_ssl) { $ssl = \Cassandra::ssl()->withVerifyFlags(\Cassandra::VERIFY_PEER_CERT); if ($ssl_ca) { $ssl = $ssl->withTrustedCerts($ssl_ca); } $ssl = $ssl->build(); $cluster = $cluster->withSSL($ssl); } $cluster = $cluster->build(); $this->db = $cluster->connect($keyspace); }
/** * Schema metadata support can be disabled. * * This test will ensure that the PHP driver supports the ability to enable * and disable the schema metadata when creating a session object. * * @test * @ticket PHP-61 */ public function testDisableSchemaMetadata() { // Create a new session with schema metadata disabled $cluster = \Cassandra::cluster()->withContactPoints(Integration::IP_ADDRESS)->withSchemaMetadata(false)->build(); $session = $cluster->connect(); // Get the schema from the new session $schema = $session->schema(); // Ensure the new session has no schema metadata $this->assertCount(0, $schema->keyspaces()); $this->assertNotEquals($this->schema->keyspaces(), $schema->keyspaces()); }
<?php // Debug mode ini_set('display_startup_errors', 1); ini_set('display_errors', 1); error_reporting(-1); // Connect to Cassandra $cluster = Cassandra::cluster()->withContactPoints('157.26.83.16')->withPort(9042)->build(); $keyspace = 'twitter'; $session = $cluster->connect($keyspace); // create session, optionally scoped to a keyspace // Default values $tValue = 1; $minVertices = 0; //*************************************/ // Change T //*************************************/ if (isset($_GET["value"])) { $tValue = $_GET["value"]; } //****************************************/ // Change minimum vertices in communities //****************************************/ if (isset($_GET["minVertices"])) { $minVertices = $_GET["minVertices"]; } $whereStatementForVertice = null; if ($minVertices > 0) { $whereStatementForVertice = "and nbv >= {$minVertices}"; } //*************************************/
function getWeatherDataCassandra($start, $end, $format, $idweatherstation, $idsensor, $header = true) { $rawData = ""; $cluster = Cassandra::cluster()->withContactPoints('10.195.62.172', '10.195.62.173', '10.195.62.174', '10.195.62.175', '10.195.62.176')->build(); $session = $cluster->connect() or die("Error connecting to the database"); $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "Connected to JAO CLUSTER: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); $debug = 1; $carry_return = "\r\n"; $initial_year = substr($start, 0, 4); $initial_month = substr($start, 5, 2); $initial_day = substr($start, 8, 2); $final_year = substr($end, 0, 4); $final_month = substr($end, 5, 2); $final_day = substr($end, 8, 2); $keyspace = 'weatherstation'; if (!empty($idsensor) && is_array($idsensor)) { $sensors = array_shift($idsensor); foreach ($idsensor as $sensor) { $sensors = $sensors . ', ' . $sensor; } unset($sensor); } else { die("Sensors NULL"); } if (!empty($idweatherstation) && is_array($idweatherstation)) { foreach ($idweatherstation as $meteo) { $year = $initial_year; $month = round($initial_month, 1); $day = round($initial_day, 1); $less_year = $final_year - $initial_year; $table = "data_" . $year; $query = "SELECT date_full, {$sensors} FROM {$keyspace}.{$table} WHERE weatherstation_id = ? AND date = ?"; $select = $session->prepare("{$query}"); $time_start = microtime(true); while ($less_year >= 0) { if ($month == 13) { $month = 1; } while ($month <= 12) { if ($day == 32) { $day = 1; } while ($day <= 31) { ####################### If month and day < 10 #################### if ($month < 10 && $day < 10) { $date = 0 . $month . '-' . 0 . $day; $options = new Cassandra\ExecutionOptions(array('arguments' => array($meteo, $date))); $result = $session->execute($select, $options); $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "CQL executed: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); foreach ($result as $row) { $rawData .= sprintf("%s; %s; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f\r\n", $meteo, $row['date_full'], $row['temperature'], $row['humidity'], $row['dewpoint'], $row['windspeed'], $row['winddirection'], $row['pressure']); } $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "Data retrieved and formatted: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); } elseif ($month < 10) { $date = 0 . $month . '-' . $day; $options = new Cassandra\ExecutionOptions(array('arguments' => array($meteo, $date))); $result = $session->execute($select, $options); $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "CQL executed: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); foreach ($result as $row) { $rawData .= sprintf("%s; %s; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f\r\n", $meteo, $row['date_full'], $row['temperature'], $row['humidity'], $row['dewpoint'], $row['windspeed'], $row['winddirection'], $row['pressure']); } $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "Data retrieved and formatted: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); } elseif ($day < 10) { $date = $month . '-' . 0 . $day; $options = new Cassandra\ExecutionOptions(array('arguments' => array($meteo, $date))); $result = $session->execute($select, $options); $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "CQL executed: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); foreach ($result as $row) { $rawData .= sprintf("%s; %s; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f\r\n", $meteo, $row['date_full'], $row['temperature'], $row['humidity'], $row['dewpoint'], $row['windspeed'], $row['winddirection'], $row['pressure']); } $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "Data retrieved and formatted: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); } else { $date = $month . '-' . $day; $options = new Cassandra\ExecutionOptions(array('arguments' => array($meteo, $date))); $result = $session->execute($select, $options); $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "CQL executed: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); foreach ($result as $row) { $rawData .= sprintf("%s; %s; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f; %0.3f\r\n", $meteo, $row['date_full'], $row['temperature'], $row['humidity'], $row['dewpoint'], $row['windspeed'], $row['winddirection'], $row['pressure']); } $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "Data retrieved and formatted: {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); } $day = $day + 1; if ($month == $final_month) { if ($day == $final_day + 1) { $day = 32; } } } $month = $month + 1; if ($year == $final_year) { if ($month == $final_month + 1) { $month = 13; } } } $year = $year + 1; $less_year = $less_year - 1; } $time_end = microtime(true); } } else { die("WeatherStation NULL"); } $weatherstationName = array_shift($idweatherstation); foreach ($idweatherstation as $weatherstation) { $weatherstationName = $weatherstationName . ', ' . $weatherstation; } unset($weatherstation); $headerData = "# weather station data of : " . $weatherstationName . $carry_return; if ($debug) { $headerData .= "# CQL= " . "SELECT " . $sensors . " FROM weatherstation.data_2015 WHERE weatherstationid = " . $weatherstationName . " AND date >= " . $start . " AND date <= " . $end . $carry_return; } $headerData .= "#" . $carry_return; $headerData .= "# WeatherStation; Date ; Humidity [%]; Temperature [celsius]; Dewpoint [celsius]; Wind Direction [degree]; Wind Speed [m/s]; Pressure [hPa]" . $carry_return; $headerData .= "#" . $carry_return; $execution_time = round($time_end - $time_start, 3); $access = date("Y/m/d H:i:s"); syslog(LOG_WARNING, "Execution Time: {$execution_time} [s], {$access} {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})"); if ($header) { return $headerData . $rawData; } else { return $rawData; } }
<html> <head> <meta charset="utf-8"/> <title>Retrieve keyspaces</title> </head> <body> <?php $cluster = Cassandra::cluster()->withContactPoints('10.195.62.172', '10.195.62.173', '10.195.62.174', '10.195.62.175', '10.195.62.176')->build(); $session = $cluster->connect(); echo sprintf("<p>Connected to %s</p>", 'JAO CLUSTER'); $keyspaces = $session->schema()->keyspaces(); #echo "<table border=\"1\">"; #echo "<tr><th>Keyspace</th><th>Table</th></tr>"; #foreach ($keyspaces as $keyspace) { # foreach ($keyspace->tables() as $table) { # echo sprintf("<tr><td>%s</td><td>%s</td></tr>\n", $keyspace->name(), $table->name()); # } #} #echo "</table>"; //$sensores = array("temperature","humidity","dewpoint","windspeed"); // // $idsensor = array_shift($sensores); // foreach( $sensores as $sensor) { // $idsensor = $idsensor . ', ' . $sensor ; // } // unset($sensor); // echo sprintf("Sensores: %s", $idsensor); // echo '<br>'; $initial_year = '2015'; $initial_month = '04';