forked from ash2k/mogilefs-php-client-improved
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MogileFS.php
708 lines (636 loc) · 21.2 KB
/
MogileFS.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
<?php
/* MogileFS.php - Class for accessing the Mogile File System
* Copyright (C) 2007 Interactive Path, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* File Authors:
* Erik Osterman <[email protected]>
* Mikhail Mazursky <ash2kk AT gmail>
*
* Thanks to the MogileFS mailing list and the creator of the MediaWiki
* MogileFS client.
*/
/* Usage Example:
* $mfs = new MogileFS('socialverse', 'assets', 'tcp://127.0.0.1');
* //$mfs->setDebug(true);
* $start = microtime(true);
* $mfs->set('test123', microtime(true));
* printf("EXISTS: %d\n", $mfs->exists('test123'));
* print "GET: [" . $mfs->get('test123') . "]\n";
* $mfs->delete('test123');
* $stop = microtime(true);
* printf("%.4f\n", $stop - $start);
*/
class MogileFS {
const CMD_DELETE = 'DELETE';
const CMD_GET_DOMAINS = 'GET_DOMAINS';
const CMD_GET_PATHS = 'GET_PATHS';
const CMD_RENAME = 'RENAME';
const CMD_LIST_KEYS = 'LIST_KEYS';
const CMD_CREATE_OPEN = 'CREATE_OPEN';
const CMD_CREATE_CLOSE = 'CREATE_CLOSE';
const RES_SUCCESS = 'OK'; // Tracker success code
const RES_ERROR = 'ERR'; // Tracker error code
const ERR_OTHER = 1000;
const ERR_UNKNOWN_KEY = 1001;
const ERR_EMPTY_FILE = 1002;
const ERR_NONE_MATCH = 1003;
const DEFAULT_PORT = 7001; // Tracker port
protected $_domain;
protected $_class;
protected $_trackers;
protected $_socket;
protected $_connectTimeout;
protected $_trackerTimeout;
protected $_putTimeout;
protected $_getTimeout;
protected $_debug;
protected $_curlInfo;
protected $_curlError;
protected $_curlErrno;
/**
* Construct an instance.
*
* @param string $domain Domain
* @param string $class Class
* @param mixed $trackers Array of tracker URLs or a single tracker URL string
*/
public function __construct($domain, $class, $trackers) {
$this->setDomain($domain);
$this->setClass($class);
$this->setTrackers($trackers);
$this->setConnectTimeout(3.0);
$this->setTrackerTimeout(3.0);
$this->setPutTimeout(10.0);
$this->setGetTimeout(10.0);
$this->setDebug(false);
}
/**
* Get debug status.
*
* @return bool Debug status
*/
public function getDebug() {
return $this->_debug;
}
/**
* Set debug status.
*
* @param bool $debug Debug status
*/
public function setDebug($debug) {
$this->_debug = (bool) $debug;
}
/**
* Get tracker/storage connect timeout.
*
* @return float Tracker/storage connect timeout in seconds
*/
public function getConnectTimeout() {
return $this->_connectTimeout;
}
/**
* Set tracker/storage connect timeout.
*
* @param float $timeout Tracker/storage connect timeout in seconds
*/
public function setConnectTimeout($timeout) {
if ($timeout > 0)
$this->_connectTimeout = (float) $timeout;
else
throw new Exception(get_class($this) . '::setConnectTimeout expects a positive float');
}
/**
* Get tracker timeout.
*
* @return float Tracker timeout in seconds
*/
public function getTrackerTimeout() {
return $this->_trackerTimeout;
}
/**
* Set tracker timeout.
*
* @param float $timeout Tracker timeout in seconds
*/
public function setTrackerTimeout($timeout) {
if ($timeout > 0)
$this->_trackerTimeout = (float) $timeout;
else
throw new Exception(get_class($this) . '::setTrackerTimeout expects a positive float');
}
/**
* Get PUT timeout.
*
* @return float PUT timeout in seconds
*/
public function getPutTimeout() {
return $this->_putTimeout;
}
/**
* Set PUT timeout.
*
* @param float $timeout PUT timeout in seconds
*/
public function setPutTimeout($timeout) {
if ($timeout > 0)
$this->_putTimeout = (float) $timeout;
else
throw new Exception(get_class($this) . '::setPutTimeout expects a positive float');
}
/**
* Get GET timeout.
*
* @return float GET timeout in seconds
*/
public function getGetTimeout() {
return $this->_getTimeout;
}
/**
* Set GET timeout.
*
* @param float $timeout GET timeout in seconds
*/
public function setGetTimeout($timeout) {
if ($timeout > 0)
$this->_getTimeout = (float) $timeout;
else
throw new Exception(get_class($this) . '::setGetTimeout expects a positive float');
}
/**
* Get list of trackers.
*
* @return array Array of tracker URLs
*/
public function getTrackers() {
return $this->_trackers;
}
/**
* Set trackers.
*
* @param mixed $trackers Array of tracker URLs or a single tracker URL string
*/
public function setTrackers($trackers) {
if (is_string($trackers))
$this->_trackers = Array($trackers);
elseif (is_array($trackers))
$this->_trackers = $trackers;
else
throw new Exception(get_class($this) . '::setTrackers unrecognized trackers argument');
}
/**
* Get domain.
*
* @return string Domain
*/
public function getDomain() {
return $this->_domain;
}
/**
* Set domain.
*
* @param string $domain Domain
*/
public function setDomain($domain) {
if (is_string($domain))
$this->_domain = $domain;
else
throw new Exception(get_class($this) . '::setDomain unrecognized domain argument');
}
/**
* Get class.
*
* @return string Class
*/
public function getClass() {
return $this->_class;
}
/**
* Set class.
*
* @param string $class Class
*/
public function setClass($class) {
if (is_string($class))
$this->_class = $class;
else
throw new Exception(get_class($this) . '::setClass unrecognized class argument');
}
/**
* Get information about the last GET/PUT transfer from cURL.
*
* Information is provided by curl_getinfo(). Returns null if no information
* is available.
*
* @return array Information about the last transfer
*/
public function getCurlInfo() {
return $this->_curlInfo;
}
/**
* Get a clear text error message for the last GET/PUT transfer from cURL.
*
* Text error message is provided by curl_error(). Returns null if no
* message is available.
*
* @return string Text error message
*/
public function getCurlError() {
return $this->_curlError;
}
/**
* Get error number for the last GET/PUT transfer from cURL.
*
* Error number is provided by curl_errno(). Returns 0 if no error number
* is available.
*
* @return int Error number
*/
public function getCurlErrno() {
return $this->_curlErrno;
}
/**
* Scans through the list of trackers and tries to connect one.
*
* @return resource Connected socket
*/
protected function getConnection() {
if ($this->_socket && is_resource($this->_socket) && !feof($this->_socket))
return $this->_socket;
foreach ($this->_trackers as $tracker) {
$parts = parse_url($tracker);
$errno = null;
$errstr = null;
$this->_socket = fsockopen(
$parts['host'],
isset($parts['port']) ? $parts['port'] : self::DEFAULT_PORT,
$errno,
$errstr,
$this->_connectTimeout
);
if ($this->_socket) {
stream_set_timeout(
$this->_socket,
floor($this->_trackerTimeout),
($this->_trackerTimeout - floor($this->_trackerTimeout)) * 1000
);
return $this->_socket;
}
}
throw new Exception(get_class($this) . '::getConnection failed to obtain connection');
}
/**
* Send a request to tracker and parse the result.
*
* @param string $cmd Protocol command
* @param array $args OPTIONAL Arguments
*
* @return array Command's result
*/
protected function doRequest($cmd, Array $args = Array()) {
$args['domain'] = $this->_domain;
$args['class'] = $this->_class;
$params = '';
foreach ($args as $key => $value)
$params .= '&' . urlencode($key) . '=' . urlencode($value);
$socket = $this->getConnection();
$result = fwrite($socket, $cmd . $params . "\n");
if ($result === false) {
$this->close();
throw new Exception(get_class($this) . '::doRequest write failed');
}
$line = fgets($socket);
if ($line === false) {
$this->close();
throw new Exception(get_class($this) . '::doRequest read failed');
}
$words = explode(' ', $line);
if ($words[0] == self::RES_SUCCESS) {
parse_str(trim($words[1]), $result);
return $result;
}
if ($words[0] != self::RES_ERROR)
// Something really bad happened - lets close the connection
$this->close();
if (!isset($words[1]))
$words[1] = null;
switch ($words[1]) {
case 'unknown_key':
throw new Exception(get_class($this) . "::doRequest unknown_key {$args['key']}", self::ERR_UNKNOWN_KEY);
case 'empty_file':
throw new Exception(get_class($this) . "::doRequest empty_file {$args['key']}", self::ERR_EMPTY_FILE);
case 'none_match':
throw new Exception(get_class($this) . "::doRequest none_match {$args['key']}", self::ERR_NONE_MATCH);
default:
throw new Exception(get_class($this) . '::doRequest ' . trim(urldecode($line)), self::ERR_OTHER);
}
}
/**
* Get a list of domains.
*
* @return array Array of domains
*/
public function getDomains() {
$this->_curlInfo = null;
$this->_curlError = null;
$this->_curlErrno = 0;
$res = $this->doRequest(self::CMD_GET_DOMAINS);
$domains = Array();
for ($i = 1; $i <= $res['domains']; $i++) {
$dom = 'domain' . $i;
$classes = Array();
for ($j = 1; $j <= $res[$dom . 'classes']; $j++)
$classes[$res[$dom . 'class' . $j . 'name']] = $res[$dom . 'class' . $j . 'mindevcount'];
$domains[] = Array('name' => $res[$dom], 'classes' => $classes);
}
return $domains;
}
/**
* Check if a key exists.
*
* @param string $key Key
*
* @return bool True if key exists, false otherwise
*/
public function exists($key) {
try {
// Get 1 path maximum without verification
$this->getPaths($key, 1, true);
return true;
} catch (Exception $e) {
if ($e->getCode() == self::ERR_UNKNOWN_KEY)
return false;
throw $e;
}
}
/**
* Get an array of paths (URLs) of file's replicas.
*
* @param string $key Key
* @param int $pathcount OPTIONAL Maximum number of paths to get
* @param bool $noverify OPTIONAL Should tracker check each path for availability?
*
* @return array Array of paths
*/
public function getPaths($key, $pathcount = null, $noverify = false) {
$this->_curlInfo = null;
$this->_curlError = null;
$this->_curlErrno = 0;
if ($key === null)
throw new Exception(get_class($this) . '::getPaths key cannot be null');
$args = Array('key' => $key, 'noverify' => (int) (bool) $noverify);
if ($pathcount)
$args['pathcount'] = (int) $pathcount;
$result = $this->doRequest(self::CMD_GET_PATHS, $args);
unset($result['paths']);
return $result;
}
/**
* Delete a file from MogileFS.
*
* @param string $key Key
*/
public function delete($key) {
$this->_curlInfo = null;
$this->_curlError = null;
$this->_curlErrno = 0;
if ($key === null)
throw new Exception(get_class($this) . '::delete key cannot be null');
$this->doRequest(self::CMD_DELETE, Array('key' => $key));
}
/**
* Rename a file.
*
* @param string $from Current key
* @param string $to New key
*/
public function rename($from, $to) {
$this->_curlInfo = null;
$this->_curlError = null;
$this->_curlErrno = 0;
if ($from === null)
throw new Exception(get_class($this) . '::rename from key cannot be null');
if ($to === null)
throw new Exception(get_class($this) . '::rename to key cannot be null');
$this->doRequest(self::CMD_RENAME, Array('from_key' => $from, 'to_key' => $to));
}
/**
* List keys.
*
* @param string $prefix OPTIONAL Key prefix
* @param string $lastKey OPTIONAL Last key
* @param int $limit OPTIONAL Maximum number of keys to return
*
* @return array Array of keys
*/
public function listKeys($prefix = null, $lastKey = null, $limit = null) {
$this->_curlInfo = null;
$this->_curlError = null;
$this->_curlErrno = 0;
try {
return $this->doRequest(self::CMD_LIST_KEYS, Array(
'prefix' => $prefix,
'after' => $lastKey,
'limit' => $limit
));
} catch (Exception $e) {
if ($e->getCode() == self::ERR_NONE_MATCH)
return Array();
throw $e;
}
}
/**
* Get a file from storage and return it as a string.
*
* @param string $key Key
*
* @return string File contents
*/
public function get($key) {
$this->_curlInfo = null;
$this->_curlError = null;
$this->_curlErrno = 0;
if ($key === null)
throw new Exception(get_class($this) . '::get key cannot be null');
$paths = $this->getPaths($key, null, true);
$ch = curl_init();
if ($ch === false)
throw new Exception(get_class($this) . '::get curl_init failed');
$options = Array(
CURLOPT_VERBOSE => $this->_debug,
CURLOPT_CONNECTTIMEOUT_MS => $this->_connectTimeout * 1000,
CURLOPT_TIMEOUT_MS => $this->_getTimeout * 1000,
CURLOPT_FAILONERROR => true,
CURLOPT_RETURNTRANSFER => true
);
if (!curl_setopt_array($ch, $options)) {
curl_close($ch);
throw new Exception(get_class($this) . '::get curl_setopt_array failed');
}
foreach ($paths as $path) {
if (!curl_setopt($ch, CURLOPT_URL, $path)) {
curl_close($ch);
throw new Exception(get_class($this) . '::get curl_setopt failed');
}
$response = curl_exec($ch);
$this->_curlInfo = curl_getinfo($ch);
$this->_curlError = curl_error($ch);
$this->_curlErrno = curl_errno($ch);
if ($response === false)
continue; // Try next source
curl_close($ch);
return $response;
}
curl_close($ch);
throw new Exception(get_class($this) . "::get unable to retrieve {$key}");
}
/**
* Get a file from storage and send it directly to stdout by way of fpassthru().
*
* @param string $key Key
*/
public function getPassthru($key) {
$this->_curlInfo = null;
$this->_curlError = null;
$this->_curlErrno = 0;
if ($key === null)
throw new Exception(get_class($this) . '::getPassthru key cannot be null');
$paths = $this->getPaths($key);
$context = stream_context_create(array('http' => array('timeout' => $this->_connectTimeout)));
foreach ($paths as $path) {
$fh = fopen($path, 'rb', false, $context);
if ($fh === false)
continue;
stream_set_timeout(
$fh,
floor($this->_getTimeout),
($this->_getTimeout - floor($this->_getTimeout)) * 1000
);
$result = fpassthru($fh);
fclose($fh);
if ($result === false)
throw new Exception(get_class($this) . '::getPassthru failed');
return;
}
throw new Exception(get_class($this) . "::getPassthru unable to retrieve {$key}");
}
/**
* Save a resource to the MogileFS.
*
* @param string $key Key
* @param resource $fh File handle
* @param int $length File length
*/
public function setResource($key, $fh, $length) {
$this->_curlInfo = null;
$this->_curlError = null;
$this->_curlErrno = 0;
if ($key === null) {
fclose($fh);
throw new Exception(get_class($this) . '::setResource key cannot be null');
}
$location = $this->doRequest(self::CMD_CREATE_OPEN, Array('key' => $key));
$ch = curl_init($location['path']);
if ($ch === false) {
fclose($fh);
throw new Exception(get_class($this) . '::setResource curl_init failed');
}
$options = Array(
CURLOPT_VERBOSE => $this->_debug,
CURLOPT_INFILE => $fh,
CURLOPT_INFILESIZE => $length,
CURLOPT_CONNECTTIMEOUT_MS => $this->_connectTimeout * 1000,
CURLOPT_TIMEOUT_MS => $this->_putTimeout * 1000,
CURLOPT_PUT => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => Array('Expect: ')
);
if (!curl_setopt_array($ch, $options)) {
fclose($fh);
curl_close($ch);
throw new Exception(get_class($this) . '::setResource curl_setopt_array failed');
}
$response = curl_exec($ch);
fclose($fh);
$this->_curlInfo = curl_getinfo($ch);
$this->_curlError = curl_error($ch);
$this->_curlErrno = curl_errno($ch);
curl_close($ch);
if ($response === false)
throw new Exception(get_class($this) . "::setResource {$this->_curlError}");
if ($this->_curlInfo['http_code'] != 201) // Not HTTP 201 Created
throw new Exception(get_class($this) . "::setResource server returned HTTP {$this->_curlInfo['http_code']} code");
$this->doRequest(self::CMD_CREATE_CLOSE, Array(
'key' => $key,
'devid' => $location['devid'],
'fid' => $location['fid'],
'path' => $location['path']
));
}
/**
* Save data to the MogileFS.
*
* @param string $key Key
* @param string $value Data
*/
public function set($key, $value) {
$this->_curlInfo = null;
$this->_curlError = null;
$this->_curlErrno = 0;
if ($key === null)
throw new Exception(get_class($this) . '::set key cannot be null');
$fh = fopen('php://memory', 'rw');
if ($fh === false)
throw new Exception(get_class($this) . '::set failed to open memory stream');
if (fwrite($fh, $value) === false) {
fclose($fh);
throw new Exception(get_class($this) . '::set write failed');
}
if (!rewind($fh)) {
fclose($fh);
throw new Exception(get_class($this) . '::set rewind failed');
}
$this->setResource($key, $fh, strlen($value));
}
/**
* Save file to the MogileFS.
*
* @param string $key Key
* @param string $filename File name
*/
public function setFile($key, $filename) {
$this->_curlInfo = null;
$this->_curlError = null;
$this->_curlErrno = 0;
if ($key === null)
throw new Exception(get_class($this) . '::setFile key cannot be null');
$filesize = filesize($filename);
if ($filesize === false)
throw new Exception(get_class($this) . "::setFile failed to get file size of {$filename}");
$fh = fopen($filename, 'r');
if ($fh === false)
throw new Exception(get_class($this) . "::setFile failed to open path {$filename}");
$this->setResource($key, $fh, $filesize);
}
/**
* Close connection to tracker.
*/
public function close() {
if ($this->_socket) {
fclose($this->_socket);
$this->_socket = null;
}
}
}