Skip to content

Instantly share code, notes, and snippets.

@terwey
Created August 4, 2016 09:08
Show Gist options
  • Save terwey/8db2a2bd4c099bb76238b8a4350aec07 to your computer and use it in GitHub Desktop.
Save terwey/8db2a2bd4c099bb76238b8a4350aec07 to your computer and use it in GitHub Desktop.
<?php
$helpopts = array(
'host:' => 'Host/IP of the Elasticsearch node that runs the REST API',
'port::' => '(optional) Port for the Elasticsearch node',
'node:' => 'Node name for the Elasticsearch Indice',
'pretend' => 'Show sample of the to be dispatched POST Data',
'help' => 'Shows the available options'
);
$options = getopt('h', array_keys($helpopts));
$showhelp = false;
if (isset($options['h']) || isset($options['help'])) {
$showhelp = true;
}
if (!isset($options['host']) && !$showhelp) {
print 'host parameter is missing'.PHP_EOL;
$showhelp = true;
}
if (!isset($options['node']) && !$showhelp) {
print 'node parameter is missing'.PHP_EOL;
$showhelp = true;
}
if ($showhelp) {
foreach ($helpopts as $option => $help) {
$option = str_replace('::', '=', $option);
$option = str_replace(':', '=', $option);
print sprintf("%-20.20s %-60.60s\n", '--'.$option, $help);
}
print sprintf("%-20.20s %-60.60s\n", ' -h', $helpopts['help']);
exit();
}
$host = $options['host'];
$node = $options['node'];
$port = (isset($options['port'])) ? $options['port'] : '9200';
$json = file_get_contents(sprintf('http://%s:%s/_cluster/state', $host, $port));
$shards = json_decode($json, true);
foreach($shards['routing_table']['indices'] as $indice) {
foreach($indice['shards'] as $shards) {
foreach($shards as $shard) {
if ($shard['state'] == 'UNASSIGNED') {
$postdata = '{
"commands" : [ {
"allocate" : {
"index" : "'.$shard['index'].'",
"shard" : '.$shard['shard'].',
"node" : "'.$node.'",
"allow_primary" : true
}
}
]
}';
if (isset($options['pretend'])) {
echo $postdata.PHP_EOL;
exit();
}
#var_dump($shard);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents(sprintf('http://%s:%s/_cluster/reroute', $host, $port), false, $context);
$response = json_decode($result, true);
if ($response['acknowledged']) {
echo 'Shard acknowledged: '.$shard['index'].PHP_EOL;
} else if ($response['error']) {
var_dump($response);
exit();
} else {
echo 'Shard denied: '.$shard['index'].PHP_EOL;
}
sleep(60);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment