Skip to content

Instantly share code, notes, and snippets.

@AntonioAngelino
Created February 10, 2015 01:52
Show Gist options
  • Select an option

  • Save AntonioAngelino/df72666f63f297e8ff7b to your computer and use it in GitHub Desktop.

Select an option

Save AntonioAngelino/df72666f63f297e8ff7b to your computer and use it in GitHub Desktop.
ElastiCache sample script
<?php
/**
* Cloud Academy Labs
*
* This CLI script shows how to use the AWS ElastiCache Memcached
* AutoDiscovery Connector for PHP.
*
* @Provider: Amazon Web Services
* @Service: ElastiCache
* @Date: 2015-01-31
* @Author: Antonio Angelino <antonio@cloudacademy.com>
* @See: http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/AutoDiscovery.html
*
*/
//------------------------------- UTILS -------------------------------
error_reporting(E_ERROR | E_WARNING | E_PARSE);
function genRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
class CliMessages {
private $stderr = null;
private $stdout = null;
public function __construct() {
$this->stdout = fopen("php://stdout", "w");
$this->stderr = fopen("php://stderr", "w");
}
public function __destruct(){
fclose($this->stdout);
fclose($this->stderr);
}
public function send_error_msg($msg) {
$msg = "\033[0;31m[ERROR] $msg\033[0m\n";
fwrite($this->stderr, $msg);
}
public function send_warn_msg($msg) {
$msg = "\033[1;35m[WARN] $msg\033[0m\n";
fwrite($this->stderr, $msg);
}
public function send_success_msg($msg) {
$msg = "\033[1;34m[OK] $msg\033[0m\n";
fwrite($this->stderr, $msg);
}
public function send_info_msg($msg) {
$msg = "\033[0;36m$msg\033[0m\n";
fwrite($this->stderr, $msg);
}
public function send_welcome_msg($script_name, $description) {
$ca = <<<EOF
\033[0;37m ___ _ _ _ _
/ __\ | ___ _ _ __| | /_\ ___ __ _ __| | ___ _ __ ___ _ _
/ / | |/ _ \| | | |/ _` | //_\\\ / __/ _` |/ _` |/ _ \ '_ ` _ \| | | |
/ /___| | (_) | |_| | (_| | / _ \ (_| (_| | (_| | __/ | | | | | |_| |
\____/|_|\___/ \__,_|\__,_| \_/ \_/\___\__,_|\__,_|\___|_| |_| |_|\__, | \033[0m
\033[0;32m https://cloudacademy.com/labs/ LABS \033[0m\033[0;37m|___/ \033[0m
$script_name
$description
------------------------------------------------------------------------
EOF;
fwrite($this->stdout, $ca);
}
}
//----------------------------- END UTILS -----------------------------
$CliMessages = new CliMessages();
$CliMessages->send_welcome_msg("AWS Elasticache :: Connection Tester Script",
"This CLI script shows how to use the AWS ElastiCache Memcached\n ".
"AutoDiscovery Connector for PHP.");
if (!class_exists('Memcached')) {
$CliMessages->send_error_msg("You MUST install the AWS Memcached Client!\n\t".
"Please check the lab documentation and try again.\n");
exit(1);
} else {
$CliMessages->send_success_msg("PHP Memcached Client is installed!\n");
}
/* Fetch and check the passed arguments */
$options = getopt("e::p::", array("endpoint::", "port::"));
$server_endpoint = ($options['endpoint']) ? $options['endpoint'] : $options['e'];
$server_port = ($options['port']) ? $options['port'] : (($options['p']) ? $options['p'] : 11211);
/* Check Passed params */
if(empty($server_endpoint)){
$CliMessages->send_error_msg("You MUST specify the cluster endpoint!\n\t".
"Usage: php test-client.php --endpoint=your.endpoint.here.cache.amazonaws.com\n");
exit(1);
}
$server_endpoint_parts = explode(':', $server_endpoint);
$server_endpoint = $server_endpoint_parts[0];
$server_port = (isset($server_endpoint_parts[1])) ? $server_endpoint_parts[1] : $server_port;
$CliMessages->send_info_msg("Cluster endpoint: $server_endpoint\n".
"Cluster port: $server_port \n");
/**
* The following will initialize a Memcached client to utilize the Auto Discovery feature.
*
* By configuring the client with the Dynamic client mode with single endpoint, the
* client will periodically use the configuration endpoint to retrieve the current cache
* cluster configuration. This allows scaling the cache cluster up or down in number of nodes
* without requiring any changes to the PHP application.
*/
$CliMessages->send_info_msg("Trying to connect to the Memcached Cluster...");
try {
$dynamic_client = new Memcached();
$dynamic_client->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
$dynamic_client->addServer($server_endpoint, $server_port);
//Check if the connection is ok...
if($dynamic_client->set('connCK_'.genRandomString(5), 'OK', 1)){
$CliMessages->send_success_msg("You are now connected to $server_endpoint cluster!\n");
} else {
$CliMessages->send_error_msg("Cannot connect to the $server_endpoint Memcached Cluster!\n\t".
"Please check the Security Group rules and try again.\n");
exit(1);
}
}
catch(Exception $e){
$CliMessages->send_error_msg("You MUST install the AWS Memcached Client!\n\t".
"Please check the lab documentation and try again.\n");
exit(1);
}
//Try to set some ElastiCache Keys to the Memcached cluster...
$CliMessages->send_info_msg("Trying to write data to $server_endpoint:");
for($i=0;$i<100;$i++) {
try {
$result = $dynamic_client->set('cloudlabs_'.$i, 'ElasticacheIsGreat! #'.$i, 60); // Store the data for 60 seconds in the cluster, the client will decide which node to store
if($result){
if($i %10 == 0 && $i != 0){
$CliMessages->send_success_msg("cloudlabs_".($i-10)." to cloudlabs_$i keys written.");
}
} else {
$CliMessages->send_error_msg("Cannot write cloudlabs_$i key. Error: {$e->getMessage()}\n");
exit(1);
}
} catch(Exception $e){
$CliMessages->send_error_msg("Cannot write cloudlabs_$i key. Error: {$e->getMessage()}\n");
exit(1);
}
}
//Try to read stored data from ElastiCache
$CliMessages->send_info_msg("\nTrying to read stored values from $server_endpoint:");
for($i=0;$i<10;$i++) {
try {
$storedVal = $dynamic_client->get('cloudlabs_'.$i);
$CliMessages->send_success_msg("\tcloudlabs_$i = $storedVal.");
} catch(Exception $e) {
$CliMessages->send_error_msg("Cannot read cloudlabs_$i key. Error: {$e->getMessage()}\n");
exit(1);
}
}
$CliMessages->send_info_msg("\nWell done, you are all set!\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment