-
Notifications
You must be signed in to change notification settings - Fork 10
/
m.php
executable file
·278 lines (238 loc) · 8.47 KB
/
m.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
<?php
srand(1);
class memcachedTools
{
public $filename = __DIR__ . '/memcacheData.txt';
public $fileMode = FILE_APPEND;
public $host = '127.0.0.1';
public $port = '11211';
public $memcached = null;
public $list = [];
public $limit = 10000000000000;
// internals
private $slabs;
private $memcachedSock;
private $mcEnd = ["END\r\n", "ERROR\r\n", "STORED\r\n", "NOT_STORED\r\n", "EXISTS\r\n", "NOT_FOUND\r\n", "DELETED\r\n"];
private $lastEnd;
public function __construct($host = '127.0.0.1:11211')
{
$this->memcached = new Memcached();
// $this->memcached->setOption(Memcached::OPT_TCP_KEEPALIVE, 200);
// $this->memcached->setOption(Memcached::OPT_TCP_NODELAY, true);
// $this->memcached->setOption(Memcached::OPT_NO_BLOCK, true);
$hostList = explode(',', $host);
foreach ($hostList as $host) {
list($host, $port,) = explode(':', $host);
if (!$port) {
$port = $this->port;
}
$this->memcached->addServer($host, $port);
}
}
// open tcp connection to server
// so we can run raw queries like stats cachedump, stats slabs etc...
// commands cheat-sheet below
// @link https://lzone.de/cheat-sheet/memcached
private function initMemcachedSock()
{
if (!is_resource($this->memcachedSock)) {
$this->memcachedSock = fsockopen($this->host, $this->port);
if (!$this->memcachedSock) {
die('Could not connect to memcached');
}
}
}
// old memcache package had support for slab stats and cache dump to extract all keys
// last release is 2013 http://pecl.php.net/package-stats.php?pid=294&rid=&cid=3
// http://pecl.php.net/package-changelog.php?package=memcache
//
// So we switch to using memcached package
// http://pecl.php.net/package-changelog.php?package=memcached
// to send commands to memcached via TCP / like telnet, nc etc...
private function mcQuery($command)
{
$this->initMemcachedSock();
$response = '';
fwrite($this->memcachedSock, $command . "\r\n");
while (!feof($this->memcachedSock)) {
$chunk = fread($this->memcachedSock, 8192);
$response .= $chunk;
$check = substr($response, -14);
foreach ($this->mcEnd as $end) {
if (substr($check, -strlen($end)) == $end) {
$response = substr($response, 0, -strlen($end));
$this->lastEnd = $end;
break 2;
}
}
}
return $response;
}
/**
* @return bool
*/
function writeKeysToFile()
{
$filePath = __DIR__ . '/' . $this->filename;
// if file name starts with / it means its absolute path
if (substr($this->filename, 0, 1) === "/") {
$filePath = $this->filename;
}
if (!count($this->list)) {
echo "No data found in Memcached\n";
return true;
}
foreach ($this->list as $row) {
$value = $this->memcached->get($row['key']);
$time = time();
$data = json_encode(
[
'key' => $row['key'],
'age' => ($row['age'] - $time),
'val' => base64_encode($value),
]
);
file_put_contents($filePath, $data . PHP_EOL, $this->fileMode);
}
echo "SUCCESS: Memcached Data has been saved to file :" . $filePath . "\n";
return true;
}
/**
* @return bool
*/
public function writeKeysToMemcached()
{
$filePath = __DIR__ . '/' . $this->filename;
// if file name starts with / it means its absolute path
if (substr($this->filename, 0, 1) === "/") {
$filePath = $this->filename;
}
if (!is_file($filePath)) {
echo "FAIL: Memcached Data could not be restored: " . $filePath . " Not Found\r\n";
return false;
}
$data = file_get_contents($filePath);
$allData = explode("\n", $data);
foreach ($allData as $key) {
$keyData = json_decode($key, true);
if (!isset($keyData['key'])) {
continue;
}
$this->memcached->set($keyData['key'], base64_decode($keyData['val']), $keyData['age']);
}
echo "SUCCESS: Memcached Data has been restored from file: " . $filePath . "\r\n";
return true;
}
/**
* get all keys in memcached
*
* @return array
*/
public function getAllKeys()
{
$allSlabs = $this->getSlabs();
foreach ($allSlabs as $id => $slab) {
$slabId = $id;
if (!is_numeric($slabId)) {
continue;
}
$cacheDump = $this->mcQuery('stats cachedump ' . (int)$slabId . ' ' . $this->limit);
$re = '/ITEM\s(\w+)\s\[.*([0-9]{10})\ss\]/m';
preg_match_all($re, $cacheDump, $entries, PREG_SET_ORDER, 0);
foreach ($entries as $eData) {
$key = $eData[1];
$this->list[$key] = [
'key' => $key,
'slabId' => $slabId,
'age' => $eData[2],
];
}
}
return $this->list;
}
/**
* get all memcached slaps
*
* @return array
*/
public function getSlabs()
{
if (null !== $this->slabs) {
return $this->slabs;
}
// echo "Getting slabs stats...\n";
$this->slabs = [];
$slabParamNames = [];
$res = $this->mcQuery("stats slabs");
foreach (explode("\r\n", $res) as $line) {
$line = substr($line, 5);
$data = explode(':', $line);
if (count($data) == 2) {
$slabId = $data[0];
$slabParam = explode(' ', $data[1], 2);
$this->slabs[$slabId]['id'] = $slabId;
$this->slabs[$slabId][$slabParam[0]] = $slabParam[1];
$slabParamNames[$slabParam[0]] = $slabParam[0];
}
}
return $this->slabs;
}
}
/**
* Run the main cli function
*
* @param $argv
*/
function runCli($argv)
{
$host = '127.0.0.1';
$port = '11211';
$action = null; // defining this variable for readability only
$allowedArguments = ['-h' => 'host', '-p' => 'port', '-op' => 'action', '-f' => 'file'];
$argValues = [];
foreach ($allowedArguments as $key => $value) {
$id = array_search($key, $argv);
if ($id) {
// one of the params host,port,action,file
${$value} = isset($argv[$id + 1]) ? $argv[$id + 1] : false;
}
}
// remove empty or nulls
$obj = new memcachedTools($host . ':' . $port);
// get the filename value (if present) and allocate to $obj->filename
if (isset($file) && trim($file) != '') {
$obj->filename = trim($file);
}
switch ($action) {
case 'backup':
$obj->getAllKeys();
$obj->writeKeysToFile();
break;
case 'restore':
$obj->writeKeysToMemcached();
break;
default:
echo <<<EOF
Example Usage:
php m.php -h 127.0.0.1 -p 11211 -op backup
php m.php -h 127.0.0.1 -p 11211 -op restore
-h : Memcache Host address ( default is 127.0.0.1 )
-p : Memcache Port ( default is 11211 )
-op : Operation is required ( available options is: restore, backup )
-f : File path (default is __DIR__.'/memcacheData.txt') relative path, or absolute path
NB: The -h address can now contain multiple memcache servers in a 'pool' configuration
these can be listed in an comma seperated list and each my optionally have a port
number associated with it by seperating with a colon thus:
192.168.1.100:11211,192.168.1.101,192.168.1.100:11211
In the above example the are two physical machines but 192.168.1.100 is running two
instances of memcached.
The servers MUST be listed here in the same order that is used to write to the pool
elsewhere in order for the keys to be correctly retrieved.
EOF;
break;
}
}
// check if the value is defined means its included or require by another file, so don't execute the cli function
if (!defined('INCLUDE_MODE')) {
runCli($argv);
}