Predis.php 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. <?php
  2. class PredisException extends Exception { }
  3. class Predis_ClientException extends PredisException { }
  4. class Predis_ServerException extends PredisException { }
  5. class Predis_MalformedServerResponse extends Predis_ServerException { }
  6. /* ------------------------------------------------------------------------- */
  7. class Predis_Client {
  8. // TODO: command arguments should be sanitized or checked for bad arguments
  9. // (e.g. CRLF in keys for inline commands)
  10. private $_connection, $_registeredCommands;
  11. public function __construct($host = Predis_Connection::DEFAULT_HOST, $port = Predis_Connection::DEFAULT_PORT) {
  12. $this->_registeredCommands = self::initializeDefaultCommands();
  13. $this->setConnection($this->createConnection(
  14. func_num_args() === 1 && is_array($host) || @stripos('redis://') === 0
  15. ? $host
  16. : array('host' => $host, 'port' => $port)
  17. ));
  18. }
  19. public function __destruct() {
  20. $this->_connection->disconnect();
  21. }
  22. public static function create(/* arguments */) {
  23. $argv = func_get_args();
  24. $argc = func_num_args();
  25. if ($argc == 1) {
  26. return new Predis_Client($argv[0]);
  27. }
  28. else if ($argc > 1) {
  29. $client = new Predis_Client();
  30. $cluster = new Predis_ConnectionCluster();
  31. foreach ($argv as $parameters) {
  32. // TODO: this is a bit dirty...
  33. $cluster->add($client->createConnection($parameters));
  34. }
  35. $client->setConnection($cluster);
  36. return $client;
  37. }
  38. else {
  39. return new Predis_Client();
  40. }
  41. }
  42. private function createConnection($parameters) {
  43. $params = new Predis_ConnectionParameters($parameters);
  44. $connection = new Predis_Connection($params);
  45. if ($params->password !== null) {
  46. $connection->pushInitCommand($this->createCommandInstance(
  47. 'auth', array($params->password)
  48. ));
  49. }
  50. if ($params->database !== null) {
  51. $connection->pushInitCommand($this->createCommandInstance(
  52. 'select', array($params->database)
  53. ));
  54. }
  55. return $connection;
  56. }
  57. private function setConnection(Predis_IConnection $connection) {
  58. $this->_connection = $connection;
  59. }
  60. public function connect() {
  61. $this->_connection->connect();
  62. }
  63. public function disconnect() {
  64. $this->_connection->disconnect();
  65. }
  66. public function isConnected() {
  67. return $this->_connection->isConnected();
  68. }
  69. public function getConnection() {
  70. return $this->_connection;
  71. }
  72. public function __call($method, $arguments) {
  73. $command = $this->createCommandInstance($method, $arguments);
  74. return $this->executeCommand($command);
  75. }
  76. public function createCommandInstance($method, $arguments = array()) {
  77. $commandClass = $this->_registeredCommands[$method];
  78. if ($commandClass === null) {
  79. throw new Predis_ClientException("'$method' is not a registered Redis command");
  80. }
  81. $command = new $commandClass();
  82. $command->setArgumentsArray($arguments);
  83. return $command;
  84. }
  85. private function executeCommandInternal(Predis_IConnection $connection, Predis_Command $command) {
  86. $connection->writeCommand($command);
  87. if ($command->closesConnection()) {
  88. return $connection->disconnect();
  89. }
  90. return $connection->readResponse($command);
  91. }
  92. public function executeCommand(Predis_Command $command) {
  93. return self::executeCommandInternal($this->_connection, $command);
  94. }
  95. public function executeCommandOnShards(Predis_Command $command) {
  96. $replies = array();
  97. if (is_a($this->_connection, 'Predis_ConnectionCluster')) {
  98. foreach($this->_connection as $connection) {
  99. $replies[] = self::executeCommandInternal($connection, $command);
  100. }
  101. }
  102. else {
  103. $replies[] = self::executeCommandInternal($this->_connection, $command);
  104. }
  105. return $replies;
  106. }
  107. public function rawCommand($rawCommandData, $closesConnection = false) {
  108. // TODO: rather than check the type of a connection instance, we should
  109. // check if it does respond to the rawCommand method.
  110. if (is_a($this->_connection, 'Predis_ConnectionCluster')) {
  111. throw new Predis_ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  112. }
  113. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  114. }
  115. public function pipeline() {
  116. return new Predis_CommandPipeline($this);
  117. }
  118. public function registerCommands(Array $commands) {
  119. foreach ($commands as $command => $aliases) {
  120. $this->registerCommand($command, $aliases);
  121. }
  122. }
  123. public function registerCommand($command, $aliases) {
  124. $commandReflection = new ReflectionClass($command);
  125. if (!$commandReflection->isSubclassOf('Predis_Command')) {
  126. throw new Predis_ClientException("Cannot register '$command' as it is not a valid Redis command");
  127. }
  128. if (is_array($aliases)) {
  129. foreach ($aliases as $alias) {
  130. $this->_registeredCommands[$alias] = $command;
  131. }
  132. }
  133. else {
  134. $this->_registeredCommands[$aliases] = $command;
  135. }
  136. }
  137. private static function initializeDefaultCommands() {
  138. // NOTE: we don't use Predis_Client::registerCommands for performance reasons.
  139. return array(
  140. /* miscellaneous commands */
  141. 'ping' => 'Predis_Commands_Ping',
  142. 'echo' => 'Predis_Commands_DoEcho',
  143. 'auth' => 'Predis_Commands_Auth',
  144. /* connection handling */
  145. 'quit' => 'Predis_Commands_Quit',
  146. /* commands operating on string values */
  147. 'set' => 'Predis_Commands_Set',
  148. 'setnx' => 'Predis_Commands_SetPreserve',
  149. 'setPreserve' => 'Predis_Commands_SetPreserve',
  150. 'mset' => 'Predis_Commands_SetMultiple',
  151. 'setMultiple' => 'Predis_Commands_SetMultiple',
  152. 'msetnx' => 'Predis_Commands_SetMultiplePreserve',
  153. 'setMultiplePreserve' => 'Predis_Commands_SetMultiplePreserve',
  154. 'get' => 'Predis_Commands_Get',
  155. 'mget' => 'Predis_Commands_GetMultiple',
  156. 'getMultiple' => 'Predis_Commands_GetMultiple',
  157. 'getset' => 'Predis_Commands_GetSet',
  158. 'getSet' => 'Predis_Commands_GetSet',
  159. 'incr' => 'Predis_Commands_Increment',
  160. 'increment' => 'Predis_Commands_Increment',
  161. 'incrby' => 'Predis_Commands_IncrementBy',
  162. 'incrementBy' => 'Predis_Commands_IncrementBy',
  163. 'decr' => 'Predis_Commands_Decrement',
  164. 'decrement' => 'Predis_Commands_Decrement',
  165. 'decrby' => 'Predis_Commands_DecrementBy',
  166. 'decrementBy' => 'Predis_Commands_DecrementBy',
  167. 'exists' => 'Predis_Commands_Exists',
  168. 'del' => 'Predis_Commands_Delete',
  169. 'delete' => 'Predis_Commands_Delete',
  170. 'type' => 'Predis_Commands_Type',
  171. /* commands operating on the key space */
  172. 'keys' => 'Predis_Commands_Keys',
  173. 'randomkey' => 'Predis_Commands_RandomKey',
  174. 'randomKey' => 'Predis_Commands_RandomKey',
  175. 'rename' => 'Predis_Commands_Rename',
  176. 'renamenx' => 'Predis_Commands_RenamePreserve',
  177. 'renamePreserve' => 'Predis_Commands_RenamePreserve',
  178. 'expire' => 'Predis_Commands_Expire',
  179. 'expireat' => 'Predis_Commands_ExpireAt',
  180. 'expireAt' => 'Predis_Commands_ExpireAt',
  181. 'dbsize' => 'Predis_Commands_DatabaseSize',
  182. 'databaseSize' => 'Predis_Commands_DatabaseSize',
  183. 'ttl' => 'Predis_Commands_TimeToLive',
  184. 'timeToLive' => 'Predis_Commands_TimeToLive',
  185. /* commands operating on lists */
  186. 'rpush' => 'Predis_Commands_ListPushTail',
  187. 'pushTail' => 'Predis_Commands_ListPushTail',
  188. 'lpush' => 'Predis_Commands_ListPushHead',
  189. 'pushHead' => 'Predis_Commands_ListPushHead',
  190. 'llen' => 'Predis_Commands_ListLength',
  191. 'listLength' => 'Predis_Commands_ListLength',
  192. 'lrange' => 'Predis_Commands_ListRange',
  193. 'listRange' => 'Predis_Commands_ListRange',
  194. 'ltrim' => 'Predis_Commands_ListTrim',
  195. 'listTrim' => 'Predis_Commands_ListTrim',
  196. 'lindex' => 'Predis_Commands_ListIndex',
  197. 'listIndex' => 'Predis_Commands_ListIndex',
  198. 'lset' => 'Predis_Commands_ListSet',
  199. 'listSet' => 'Predis_Commands_ListSet',
  200. 'lrem' => 'Predis_Commands_ListRemove',
  201. 'listRemove' => 'Predis_Commands_ListRemove',
  202. 'lpop' => 'Predis_Commands_ListPopFirst',
  203. 'popFirst' => 'Predis_Commands_ListPopFirst',
  204. 'rpop' => 'Predis_Commands_ListPopLast',
  205. 'popLast' => 'Predis_Commands_ListPopLast',
  206. 'rpoplpush' => 'Predis_Commands_ListPushTailPopFirst',
  207. 'listPopLastPushHead' => 'Predis_Commands_ListPopLastPushHead',
  208. /* commands operating on sets */
  209. 'sadd' => 'Predis_Commands_SetAdd',
  210. 'setAdd' => 'Predis_Commands_SetAdd',
  211. 'srem' => 'Predis_Commands_SetRemove',
  212. 'setRemove' => 'Predis_Commands_SetRemove',
  213. 'spop' => 'Predis_Commands_SetPop',
  214. 'setPop' => 'Predis_Commands_SetPop',
  215. 'smove' => 'Predis_Commands_SetMove',
  216. 'setMove' => 'Predis_Commands_SetMove',
  217. 'scard' => 'Predis_Commands_SetCardinality',
  218. 'setCardinality' => 'Predis_Commands_SetCardinality',
  219. 'sismember' => 'Predis_Commands_SetIsMember',
  220. 'setIsMember' => 'Predis_Commands_SetIsMember',
  221. 'sinter' => 'Predis_Commands_SetIntersection',
  222. 'setIntersection' => 'Predis_Commands_SetIntersection',
  223. 'sinterstore' => 'Predis_Commands_SetIntersectionStore',
  224. 'setIntersectionStore' => 'Predis_Commands_SetIntersectionStore',
  225. 'sunion' => 'Predis_Commands_SetUnion',
  226. 'setUnion' => 'Predis_Commands_SetUnion',
  227. 'sunionstore' => 'Predis_Commands_SetUnionStore',
  228. 'setUnionStore' => 'Predis_Commands_SetUnionStore',
  229. 'sdiff' => 'Predis_Commands_SetDifference',
  230. 'setDifference' => 'Predis_Commands_SetDifference',
  231. 'sdiffstore' => 'Predis_Commands_SetDifferenceStore',
  232. 'setDifferenceStore' => 'Predis_Commands_SetDifferenceStore',
  233. 'smembers' => 'Predis_Commands_SetMembers',
  234. 'setMembers' => 'Predis_Commands_SetMembers',
  235. 'srandmember' => 'Predis_Commands_SetRandomMember',
  236. 'setRandomMember' => 'Predis_Commands_SetRandomMember',
  237. /* commands operating on sorted sets */
  238. 'zadd' => 'Predis_Commands_ZSetAdd',
  239. 'zsetAdd' => 'Predis_Commands_ZSetAdd',
  240. 'zrem' => 'Predis_Commands_ZSetRemove',
  241. 'zsetRemove' => 'Predis_Commands_ZSetRemove',
  242. 'zrange' => 'Predis_Commands_ZSetRange',
  243. 'zsetRange' => 'Predis_Commands_ZSetRange',
  244. 'zrevrange' => 'Predis_Commands_ZSetReverseRange',
  245. 'zsetReverseRange' => 'Predis_Commands_ZSetReverseRange',
  246. 'zrangebyscore' => 'Predis_Commands_ZSetRangeByScore',
  247. 'zsetRangeByScore' => 'Predis_Commands_ZSetRangeByScore',
  248. 'zcard' => 'Predis_Commands_ZSetCardinality',
  249. 'zsetCardinality' => 'Predis_Commands_ZSetCardinality',
  250. 'zscore' => 'Predis_Commands_ZSetScore',
  251. 'zsetScore' => 'Predis_Commands_ZSetScore',
  252. 'zremrangebyscore' => 'Predis_Commands_ZSetRemoveRangeByScore',
  253. 'zsetRemoveRangeByScore' => 'Predis_Commands_ZSetRemoveRangeByScore',
  254. /* multiple databases handling commands */
  255. 'select' => 'Predis_Commands_SelectDatabase',
  256. 'selectDatabase' => 'Predis_Commands_SelectDatabase',
  257. 'move' => 'Predis_Commands_MoveKey',
  258. 'moveKey' => 'Predis_Commands_MoveKey',
  259. 'flushdb' => 'Predis_Commands_FlushDatabase',
  260. 'flushDatabase' => 'Predis_Commands_FlushDatabase',
  261. 'flushall' => 'Predis_Commands_FlushAll',
  262. 'flushDatabases' => 'Predis_Commands_FlushAll',
  263. /* sorting */
  264. 'sort' => 'Predis_Commands_Sort',
  265. /* remote server control commands */
  266. 'info' => 'Predis_Commands_Info',
  267. 'slaveof' => 'Predis_Commands_SlaveOf',
  268. 'slaveOf' => 'Predis_Commands_SlaveOf',
  269. /* persistence control commands */
  270. 'save' => 'Predis_Commands_Save',
  271. 'bgsave' => 'Predis_Commands_BackgroundSave',
  272. 'backgroundSave' => 'Predis_Commands_BackgroundSave',
  273. 'lastsave' => 'Predis_Commands_LastSave',
  274. 'lastSave' => 'Predis_Commands_LastSave',
  275. 'shutdown' => 'Predis_Commands_Shutdown'
  276. );
  277. }
  278. }
  279. /* ------------------------------------------------------------------------- */
  280. abstract class Predis_Command {
  281. private $_arguments;
  282. public abstract function getCommandId();
  283. public abstract function serializeRequest($command, $arguments);
  284. public function canBeHashed() {
  285. return true;
  286. }
  287. public function closesConnection() {
  288. return false;
  289. }
  290. protected function filterArguments(Array $arguments) {
  291. return $arguments;
  292. }
  293. public function setArguments(/* arguments */) {
  294. $this->_arguments = $this->filterArguments(func_get_args());
  295. }
  296. public function setArgumentsArray(Array $arguments) {
  297. $this->_arguments = $this->filterArguments($arguments);
  298. }
  299. protected function getArguments() {
  300. return isset($this->_arguments) ? $this->_arguments : array();
  301. }
  302. public function getArgument($index = 0) {
  303. return isset($this->_arguments[$index]) ? $this->_arguments[$index] : null;
  304. }
  305. public function parseResponse($data) {
  306. return $data;
  307. }
  308. public final function invoke() {
  309. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  310. }
  311. }
  312. abstract class Predis_InlineCommand extends Predis_Command {
  313. public function serializeRequest($command, $arguments) {
  314. if (isset($arguments[0]) && is_array($arguments[0])) {
  315. $arguments[0] = implode($arguments[0], ' ');
  316. }
  317. return $command . ' ' . implode($arguments, ' ') . Predis_Response::NEWLINE;
  318. }
  319. }
  320. abstract class Predis_BulkCommand extends Predis_Command {
  321. public function serializeRequest($command, $arguments) {
  322. $data = array_pop($arguments);
  323. if (is_array($data)) {
  324. $data = implode($data, ' ');
  325. }
  326. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  327. Predis_Response::NEWLINE . $data . Predis_Response::NEWLINE;
  328. }
  329. }
  330. abstract class Predis_MultiBulkCommand extends Predis_Command {
  331. public function serializeRequest($command, $arguments) {
  332. $buffer = array();
  333. $cmd_args = null;
  334. if (count($arguments) === 1 && is_array($arguments[0])) {
  335. $cmd_args = array();
  336. foreach ($arguments[0] as $k => $v) {
  337. $cmd_args[] = $k;
  338. $cmd_args[] = $v;
  339. }
  340. }
  341. else {
  342. $cmd_args = $arguments;
  343. }
  344. $buffer[] = '*' . ((string) count($cmd_args) + 1) . Predis_Response::NEWLINE;
  345. $buffer[] = '$' . strlen($command) . Predis_Response::NEWLINE . $command . Predis_Response::NEWLINE;
  346. foreach ($cmd_args as $argument) {
  347. $buffer[] = '$' . strlen($argument) . Predis_Response::NEWLINE . $argument . Predis_Response::NEWLINE;
  348. }
  349. return implode('', $buffer);
  350. }
  351. }
  352. /* ------------------------------------------------------------------------- */
  353. class Predis_Response {
  354. const NEWLINE = "\r\n";
  355. const OK = 'OK';
  356. const ERROR = 'ERR';
  357. const NULL = 'nil';
  358. private static $_prefixHandlers;
  359. private static function initializePrefixHandlers() {
  360. return array(
  361. // status
  362. '+' => array('Predis_Response', 'handleStatus'),
  363. // error
  364. '-' => array('Predis_Response', 'handleError'),
  365. // bulk
  366. '$' => array('Predis_Response', 'handleBulk'),
  367. // multibulk
  368. '*' => array('Predis_Response', 'handleMultiBulk'),
  369. // integer
  370. ':' => array('Predis_Response', 'handleInteger')
  371. );
  372. }
  373. public static function getPrefixHandler($prefix) {
  374. if (self::$_prefixHandlers == null) {
  375. self::$_prefixHandlers = self::initializePrefixHandlers();
  376. }
  377. $handler = self::$_prefixHandlers[$prefix];
  378. if ($handler === null) {
  379. throw new Predis_MalformedServerResponse("Unknown prefix '$prefix'");
  380. }
  381. return $handler;
  382. }
  383. public static function handleStatus($socket) {
  384. $status = rtrim(fgets($socket), Predis_Response::NEWLINE);
  385. return $status === Predis_Response::OK ? true : $status;
  386. }
  387. public static function handleError($socket) {
  388. $errorMessage = rtrim(fgets($socket), Predis_Response::NEWLINE);
  389. throw new Predis_ServerException(substr($errorMessage, 4));
  390. }
  391. public static function handleBulk($socket) {
  392. $dataLength = rtrim(fgets($socket), Predis_Response::NEWLINE);
  393. if (!is_numeric($dataLength)) {
  394. throw new Predis_ClientException("Cannot parse '$dataLength' as data length");
  395. }
  396. if ($dataLength > 0) {
  397. $value = stream_get_contents($socket, $dataLength);
  398. fread($socket, 2);
  399. return $value;
  400. }
  401. else if ($dataLength == 0) {
  402. // TODO: I just have a doubt here...
  403. fread($socket, 2);
  404. }
  405. return null;
  406. }
  407. public static function handleMultiBulk($socket) {
  408. $rawLength = rtrim(fgets($socket), Predis_Response::NEWLINE);
  409. if (!is_numeric($rawLength)) {
  410. throw new Predis_ClientException("Cannot parse '$rawLength' as data length");
  411. }
  412. $listLength = (int) $rawLength;
  413. if ($listLength === -1) {
  414. return null;
  415. }
  416. $list = array();
  417. if ($listLength > 0) {
  418. for ($i = 0; $i < $listLength; $i++) {
  419. $handler = Predis_Response::getPrefixHandler(fgetc($socket));
  420. $list[] = call_user_func($handler, $socket);
  421. }
  422. }
  423. return $list;
  424. }
  425. public static function handleInteger($socket) {
  426. $number = rtrim(fgets($socket), Predis_Response::NEWLINE);
  427. if (is_numeric($number)) {
  428. return (int) $number;
  429. }
  430. else {
  431. if ($number !== Predis_Response::NULL) {
  432. throw new Predis_ClientException("Cannot parse '$number' as numeric response");
  433. }
  434. return null;
  435. }
  436. }
  437. }
  438. class Predis_CommandPipeline {
  439. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  440. public function __construct(Predis_Client $redisClient) {
  441. $this->_redisClient = $redisClient;
  442. $this->_pipelineBuffer = array();
  443. $this->_returnValues = array();
  444. }
  445. public function __call($method, $arguments) {
  446. $command = $this->_redisClient->createCommandInstance($method, $arguments);
  447. $this->recordCommand($command);
  448. }
  449. private function recordCommand(Predis_Command $command) {
  450. $this->_pipelineBuffer[] = $command;
  451. }
  452. private function getRecordedCommands() {
  453. return $this->_pipelineBuffer;
  454. }
  455. public function flushPipeline() {
  456. if (count($this->_pipelineBuffer) === 0) {
  457. return;
  458. }
  459. $connection = $this->_redisClient->getConnection();
  460. $commands = &$this->getRecordedCommands();
  461. foreach ($commands as $command) {
  462. $connection->writeCommand($command);
  463. }
  464. foreach ($commands as $command) {
  465. $this->_returnValues[] = $connection->readResponse($command);
  466. }
  467. $this->_pipelineBuffer = array();
  468. }
  469. private function setRunning($bool) {
  470. // TODO: I am honest when I say that I don't like this approach.
  471. if ($bool == true && $this->_running == true) {
  472. throw new Predis_ClientException("This pipeline is already opened");
  473. }
  474. $this->_running = $bool;
  475. }
  476. public function execute() {
  477. $this->setRunning(true);
  478. $pipelineBlockException = null;
  479. try {
  480. $this->flushPipeline();
  481. }
  482. catch (Exception $exception) {
  483. $pipelineBlockException = $exception;
  484. }
  485. $this->setRunning(false);
  486. if ($pipelineBlockException !== null) {
  487. throw $pipelineBlockException;
  488. }
  489. return $this->_returnValues;
  490. }
  491. }
  492. /* ------------------------------------------------------------------------- */
  493. class Predis_ConnectionParameters {
  494. private $_parameters;
  495. public function __construct($parameters) {
  496. $this->_parameters = is_array($parameters)
  497. ? self::filterConnectionParams($parameters)
  498. : self::parseURI($parameters);
  499. }
  500. private static function parseURI($uri) {
  501. $parsed = @parse_url($uri);
  502. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  503. throw new Predis_ClientException("Invalid URI: $uri");
  504. }
  505. if (array_key_exists('query', $parsed)) {
  506. $details = array();
  507. foreach (explode('&', $parsed['query']) as $kv) {
  508. list($k, $v) = explode('=', $kv);
  509. switch ($k) {
  510. case 'database':
  511. $details['database'] = $v;
  512. break;
  513. case 'password':
  514. $details['password'] = $v;
  515. break;
  516. }
  517. }
  518. $parsed = array_merge($parsed, $details);
  519. }
  520. return self::filterConnectionParams($parsed);
  521. }
  522. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  523. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  524. }
  525. private static function filterConnectionParams($parameters) {
  526. return array(
  527. 'host' => self::getParamOrDefault($parameters, 'host', Predis_Connection::DEFAULT_HOST),
  528. 'port' => (int) self::getParamOrDefault($parameters, 'port', Predis_Connection::DEFAULT_PORT),
  529. 'database' => self::getParamOrDefault($parameters, 'database'),
  530. 'password' => self::getParamOrDefault($parameters, 'password')
  531. );
  532. }
  533. public function __get($parameter) {
  534. return $this->_parameters[$parameter];
  535. }
  536. }
  537. interface Predis_IConnection {
  538. public function connect();
  539. public function disconnect();
  540. public function isConnected();
  541. public function writeCommand(Predis_Command $command);
  542. public function readResponse(Predis_Command $command);
  543. }
  544. class Predis_Connection implements Predis_IConnection {
  545. const DEFAULT_HOST = '127.0.0.1';
  546. const DEFAULT_PORT = 6379;
  547. const CONNECTION_TIMEOUT = 2;
  548. const READ_WRITE_TIMEOUT = 5;
  549. private $_params, $_socket, $_initCmds;
  550. public function __construct(Predis_ConnectionParameters $parameters) {
  551. $this->_params = $parameters;
  552. $this->_initCmds = array();
  553. }
  554. public function __destruct() {
  555. $this->disconnect();
  556. }
  557. public function isConnected() {
  558. return is_resource($this->_socket);
  559. }
  560. public function connect() {
  561. if ($this->isConnected()) {
  562. throw new Predis_ClientException('Connection already estabilished');
  563. }
  564. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  565. $this->_socket = @stream_socket_client($uri, $errno, $errstr, self::CONNECTION_TIMEOUT);
  566. if (!$this->_socket) {
  567. throw new Predis_ClientException(trim($errstr), $errno);
  568. }
  569. stream_set_timeout($this->_socket, self::READ_WRITE_TIMEOUT);
  570. if (count($this->_initCmds) > 0){
  571. $this->sendInitializationCommands();
  572. }
  573. }
  574. public function disconnect() {
  575. if ($this->isConnected()) {
  576. fclose($this->_socket);
  577. }
  578. }
  579. public function pushInitCommand(Predis_Command $command){
  580. $this->_initCmds[] = $command;
  581. }
  582. private function sendInitializationCommands() {
  583. foreach ($this->_initCmds as $command) {
  584. $this->writeCommand($command);
  585. }
  586. foreach ($this->_initCmds as $command) {
  587. $this->readResponse($command);
  588. }
  589. }
  590. public function writeCommand(Predis_Command $command) {
  591. fwrite($this->getSocket(), $command->invoke());
  592. }
  593. public function readResponse(Predis_Command $command) {
  594. $socket = $this->getSocket();
  595. $handler = Predis_Response::getPrefixHandler(fgetc($socket));
  596. $response = $command->parseResponse(call_user_func($handler, $socket));
  597. return $response;
  598. }
  599. public function rawCommand($rawCommandData, $closesConnection = false) {
  600. $socket = $this->getSocket();
  601. fwrite($socket, $rawCommandData);
  602. if ($closesConnection) {
  603. return;
  604. }
  605. $handler = Predis_Response::getPrefixHandler(fgetc($socket));
  606. return $handler($socket);
  607. }
  608. public function getSocket() {
  609. if (!$this->isConnected()) {
  610. $this->connect();
  611. }
  612. return $this->_socket;
  613. }
  614. public function __toString() {
  615. return sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  616. }
  617. }
  618. class Predis_ConnectionCluster implements Predis_IConnection, IteratorAggregate {
  619. // TODO: storing a temporary map of commands hashes to hashring items (that
  620. // is, connections) could offer a notable speedup, but I am wondering
  621. // about the increased memory footprint.
  622. // TODO: find a clean way to handle connection failures of single nodes.
  623. private $_pool, $_ring;
  624. public function __construct() {
  625. $this->_pool = array();
  626. $this->_ring = new Utilities_HashRing();
  627. }
  628. public function __destruct() {
  629. $this->disconnect();
  630. }
  631. public function isConnected() {
  632. foreach ($this->_pool as $connection) {
  633. if ($connection->isConnected()) {
  634. return true;
  635. }
  636. }
  637. return false;
  638. }
  639. public function connect() {
  640. foreach ($this->_pool as $connection) {
  641. $connection->connect();
  642. }
  643. }
  644. public function disconnect() {
  645. foreach ($this->_pool as $connection) {
  646. $connection->disconnect();
  647. }
  648. }
  649. public function add(Predis_Connection $connection) {
  650. $this->_pool[] = $connection;
  651. $this->_ring->add($connection);
  652. }
  653. private function getConnectionFromRing(Predis_Command $command) {
  654. return $this->_ring->get(self::computeHash($command));
  655. }
  656. private static function computeHash(Predis_Command $command) {
  657. return crc32($command->getArgument(0));
  658. }
  659. private function getConnection(Predis_Command $command) {
  660. if ($command->canBeHashed() === false) {
  661. throw new Predis_ClientException(
  662. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  663. );
  664. }
  665. return $this->getConnectionFromRing($command);
  666. }
  667. public function getConnectionById($id = null) {
  668. return $this->_pool[$id === null ? 0 : $id];
  669. }
  670. public function getIterator() {
  671. return new ArrayIterator($this->_pool);
  672. }
  673. public function writeCommand(Predis_Command $command) {
  674. $this->getConnection($command)->writeCommand($command);
  675. }
  676. public function readResponse(Predis_Command $command) {
  677. return $this->getConnection($command)->readResponse($command);
  678. }
  679. }
  680. /* ------------------------------------------------------------------------- */
  681. class Utilities_HashRing {
  682. const DEFAULT_REPLICAS = 128;
  683. private $_ring, $_ringKeys, $_replicas;
  684. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  685. $this->_replicas = $replicas;
  686. $this->_ring = array();
  687. $this->_ringKeys = array();
  688. }
  689. public function add($node) {
  690. $nodeHash = (string) $node;
  691. for ($i = 0; $i < $this->_replicas; $i++) {
  692. $key = crc32($nodeHash . ':' . $i);
  693. $this->_ring[$key] = $node;
  694. }
  695. ksort($this->_ring, SORT_NUMERIC);
  696. $this->_ringKeys = array_keys($this->_ring);
  697. }
  698. public function remove($node) {
  699. $nodeHash = (string) $node;
  700. for ($i = 0; $i < $this->_replicas; $i++) {
  701. $key = crc32($nodeHash . ':' . $i);
  702. unset($this->_ring[$key]);
  703. $newRing = array();
  704. foreach ($this->_ringKeys as $rk) {
  705. if ($rk !== $key) {
  706. $newRing[] = $rk;
  707. }
  708. }
  709. $this->_ringKeys = $newRing;
  710. }
  711. }
  712. public function get($key) {
  713. return $this->_ring[$this->getNodeKey($key)];
  714. }
  715. private function getNodeKey($key) {
  716. $upper = count($this->_ringKeys) - 1;
  717. $lower = 0;
  718. $index = 0;
  719. while ($lower <= $upper) {
  720. $index = ($lower + $upper) / 2;
  721. $item = $this->_ringKeys[$index];
  722. if ($item === $key) {
  723. return $index;
  724. }
  725. else if ($item > $key) {
  726. $upper = $index - 1;
  727. }
  728. else {
  729. $lower = $index + 1;
  730. }
  731. }
  732. return $this->_ringKeys[$upper];
  733. }
  734. }
  735. /* ------------------------------------------------------------------------- */
  736. /* miscellaneous commands */
  737. class Predis_Commands_Ping extends Predis_InlineCommand {
  738. public function canBeHashed() { return false; }
  739. public function getCommandId() { return 'PING'; }
  740. public function parseResponse($data) {
  741. return $data === 'PONG' ? true : false;
  742. }
  743. }
  744. class Predis_Commands_DoEcho extends Predis_BulkCommand {
  745. public function canBeHashed() { return false; }
  746. public function getCommandId() { return 'ECHO'; }
  747. }
  748. class Predis_Commands_Auth extends Predis_InlineCommand {
  749. public function canBeHashed() { return false; }
  750. public function getCommandId() { return 'AUTH'; }
  751. }
  752. /* connection handling */
  753. class Predis_Commands_Quit extends Predis_InlineCommand {
  754. public function canBeHashed() { return false; }
  755. public function getCommandId() { return 'QUIT'; }
  756. public function closesConnection() { return true; }
  757. }
  758. /* commands operating on string values */
  759. class Predis_Commands_Set extends Predis_BulkCommand {
  760. public function getCommandId() { return 'SET'; }
  761. }
  762. class Predis_Commands_SetPreserve extends Predis_BulkCommand {
  763. public function getCommandId() { return 'SETNX'; }
  764. public function parseResponse($data) { return (bool) $data; }
  765. }
  766. class Predis_Commands_SetMultiple extends Predis_MultiBulkCommand {
  767. public function canBeHashed() { return false; }
  768. public function getCommandId() { return 'MSET'; }
  769. }
  770. class Predis_Commands_SetMultiplePreserve extends Predis_MultiBulkCommand {
  771. public function canBeHashed() { return false; }
  772. public function getCommandId() { return 'MSETNX'; }
  773. public function parseResponse($data) { return (bool) $data; }
  774. }
  775. class Predis_Commands_Get extends Predis_InlineCommand {
  776. public function getCommandId() { return 'GET'; }
  777. }
  778. class Predis_Commands_GetMultiple extends Predis_InlineCommand {
  779. public function canBeHashed() { return false; }
  780. public function getCommandId() { return 'MGET'; }
  781. }
  782. class Predis_Commands_GetSet extends Predis_BulkCommand {
  783. public function getCommandId() { return 'GETSET'; }
  784. }
  785. class Predis_Commands_Increment extends Predis_InlineCommand {
  786. public function getCommandId() { return 'INCR'; }
  787. }
  788. class Predis_Commands_IncrementBy extends Predis_InlineCommand {
  789. public function getCommandId() { return 'INCRBY'; }
  790. }
  791. class Predis_Commands_Decrement extends Predis_InlineCommand {
  792. public function getCommandId() { return 'DECR'; }
  793. }
  794. class Predis_Commands_DecrementBy extends Predis_InlineCommand {
  795. public function getCommandId() { return 'DECRBY'; }
  796. }
  797. class Predis_Commands_Exists extends Predis_InlineCommand {
  798. public function getCommandId() { return 'EXISTS'; }
  799. public function parseResponse($data) { return (bool) $data; }
  800. }
  801. class Predis_Commands_Delete extends Predis_InlineCommand {
  802. public function getCommandId() { return 'DEL'; }
  803. public function parseResponse($data) { return (bool) $data; }
  804. }
  805. class Predis_Commands_Type extends Predis_InlineCommand {
  806. public function getCommandId() { return 'TYPE'; }
  807. }
  808. /* commands operating on the key space */
  809. class Predis_Commands_Keys extends Predis_InlineCommand {
  810. public function canBeHashed() { return false; }
  811. public function getCommandId() { return 'KEYS'; }
  812. public function parseResponse($data) {
  813. // TODO: is this behaviour correct?
  814. return strlen($data) > 0 ? explode(' ', $data) : array();
  815. }
  816. }
  817. class Predis_Commands_RandomKey extends Predis_InlineCommand {
  818. public function canBeHashed() { return false; }
  819. public function getCommandId() { return 'RANDOMKEY'; }
  820. public function parseResponse($data) { return $data !== '' ? $data : null; }
  821. }
  822. class Predis_Commands_Rename extends Predis_InlineCommand {
  823. // TODO: doesn't RENAME break the hash-based client-side sharding?
  824. public function canBeHashed() { return false; }
  825. public function getCommandId() { return 'RENAME'; }
  826. }
  827. class Predis_Commands_RenamePreserve extends Predis_InlineCommand {
  828. public function canBeHashed() { return false; }
  829. public function getCommandId() { return 'RENAMENX'; }
  830. public function parseResponse($data) { return (bool) $data; }
  831. }
  832. class Predis_Commands_Expire extends Predis_InlineCommand {
  833. public function getCommandId() { return 'EXPIRE'; }
  834. public function parseResponse($data) { return (bool) $data; }
  835. }
  836. class Predis_Commands_ExpireAt extends Predis_InlineCommand {
  837. public function getCommandId() { return 'EXPIREAT'; }
  838. public function parseResponse($data) { return (bool) $data; }
  839. }
  840. class Predis_Commands_DatabaseSize extends Predis_InlineCommand {
  841. public function canBeHashed() { return false; }
  842. public function getCommandId() { return 'DBSIZE'; }
  843. }
  844. class Predis_Commands_TimeToLive extends Predis_InlineCommand {
  845. public function getCommandId() { return 'TTL'; }
  846. }
  847. /* commands operating on lists */
  848. class Predis_Commands_ListPushTail extends Predis_BulkCommand {
  849. public function getCommandId() { return 'RPUSH'; }
  850. }
  851. class Predis_Commands_ListPushHead extends Predis_BulkCommand {
  852. public function getCommandId() { return 'LPUSH'; }
  853. }
  854. class Predis_Commands_ListLength extends Predis_InlineCommand {
  855. public function getCommandId() { return 'LLEN'; }
  856. }
  857. class Predis_Commands_ListRange extends Predis_InlineCommand {
  858. public function getCommandId() { return 'LRANGE'; }
  859. }
  860. class Predis_Commands_ListTrim extends Predis_InlineCommand {
  861. public function getCommandId() { return 'LTRIM'; }
  862. }
  863. class Predis_Commands_ListIndex extends Predis_InlineCommand {
  864. public function getCommandId() { return 'LINDEX'; }
  865. }
  866. class Predis_Commands_ListSet extends Predis_BulkCommand {
  867. public function getCommandId() { return 'LSET'; }
  868. }
  869. class Predis_Commands_ListRemove extends Predis_BulkCommand {
  870. public function getCommandId() { return 'LREM'; }
  871. }
  872. class Predis_Commands_ListPopLastPushHead extends Predis_BulkCommand {
  873. public function getCommandId() { return 'RPOPLPUSH'; }
  874. }
  875. class Predis_Commands_ListPopFirst extends Predis_InlineCommand {
  876. public function getCommandId() { return 'LPOP'; }
  877. }
  878. class Predis_Commands_ListPopLast extends Predis_InlineCommand {
  879. public function getCommandId() { return 'RPOP'; }
  880. }
  881. /* commands operating on sets */
  882. class Predis_Commands_SetAdd extends Predis_BulkCommand {
  883. public function getCommandId() { return 'SADD'; }
  884. public function parseResponse($data) { return (bool) $data; }
  885. }
  886. class Predis_Commands_SetRemove extends Predis_BulkCommand {
  887. public function getCommandId() { return 'SREM'; }
  888. public function parseResponse($data) { return (bool) $data; }
  889. }
  890. class Predis_Commands_SetPop extends Predis_InlineCommand {
  891. public function getCommandId() { return 'SPOP'; }
  892. }
  893. class Predis_Commands_SetMove extends Predis_BulkCommand {
  894. public function canBeHashed() { return false; }
  895. public function getCommandId() { return 'SMOVE'; }
  896. public function parseResponse($data) { return (bool) $data; }
  897. }
  898. class Predis_Commands_SetCardinality extends Predis_InlineCommand {
  899. public function getCommandId() { return 'SCARD'; }
  900. }
  901. class Predis_Commands_SetIsMember extends Predis_BulkCommand {
  902. public function getCommandId() { return 'SISMEMBER'; }
  903. public function parseResponse($data) { return (bool) $data; }
  904. }
  905. class Predis_Commands_SetIntersection extends Predis_InlineCommand {
  906. public function getCommandId() { return 'SINTER'; }
  907. }
  908. class Predis_Commands_SetIntersectionStore extends Predis_InlineCommand {
  909. public function getCommandId() { return 'SINTERSTORE'; }
  910. }
  911. class Predis_Commands_SetUnion extends Predis_InlineCommand {
  912. public function getCommandId() { return 'SUNION'; }
  913. }
  914. class Predis_Commands_SetUnionStore extends Predis_InlineCommand {
  915. public function getCommandId() { return 'SUNIONSTORE'; }
  916. }
  917. class Predis_Commands_SetDifference extends Predis_InlineCommand {
  918. public function getCommandId() { return 'SDIFF'; }
  919. }
  920. class Predis_Commands_SetDifferenceStore extends Predis_InlineCommand {
  921. public function getCommandId() { return 'SDIFFSTORE'; }
  922. }
  923. class Predis_Commands_SetMembers extends Predis_InlineCommand {
  924. public function getCommandId() { return 'SMEMBERS'; }
  925. }
  926. class Predis_Commands_SetRandomMember extends Predis_InlineCommand {
  927. public function getCommandId() { return 'SRANDMEMBER'; }
  928. }
  929. /* commands operating on sorted sets */
  930. class Predis_Commands_ZSetAdd extends Predis_BulkCommand {
  931. public function getCommandId() { return 'ZADD'; }
  932. public function parseResponse($data) { return (bool) $data; }
  933. }
  934. class Predis_Commands_ZSetRemove extends Predis_BulkCommand {
  935. public function getCommandId() { return 'ZREM'; }
  936. public function parseResponse($data) { return (bool) $data; }
  937. }
  938. class Predis_Commands_ZSetRange extends Predis_InlineCommand {
  939. public function getCommandId() { return 'ZRANGE'; }
  940. }
  941. class Predis_Commands_ZSetReverseRange extends Predis_InlineCommand {
  942. public function getCommandId() { return 'ZREVRANGE'; }
  943. }
  944. class Predis_Commands_ZSetRangeByScore extends Predis_InlineCommand {
  945. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  946. }
  947. class Predis_Commands_ZSetCardinality extends Predis_InlineCommand {
  948. public function getCommandId() { return 'ZCARD'; }
  949. }
  950. class Predis_Commands_ZSetScore extends Predis_BulkCommand {
  951. public function getCommandId() { return 'ZSCORE'; }
  952. }
  953. class Predis_Commands_ZSetRemoveRangeByScore extends Predis_InlineCommand {
  954. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  955. }
  956. /* multiple databases handling commands */
  957. class Predis_Commands_SelectDatabase extends Predis_InlineCommand {
  958. public function canBeHashed() { return false; }
  959. public function getCommandId() { return 'SELECT'; }
  960. }
  961. class Predis_Commands_MoveKey extends Predis_InlineCommand {
  962. public function canBeHashed() { return false; }
  963. public function getCommandId() { return 'MOVE'; }
  964. public function parseResponse($data) { return (bool) $data; }
  965. }
  966. class Predis_Commands_FlushDatabase extends Predis_InlineCommand {
  967. public function canBeHashed() { return false; }
  968. public function getCommandId() { return 'FLUSHDB'; }
  969. }
  970. class Predis_Commands_FlushAll extends Predis_InlineCommand {
  971. public function canBeHashed() { return false; }
  972. public function getCommandId() { return 'FLUSHALL'; }
  973. }
  974. /* sorting */
  975. class Predis_Commands_Sort extends Predis_InlineCommand {
  976. public function getCommandId() { return 'SORT'; }
  977. public function filterArguments($arguments) {
  978. if (count($arguments) === 1) {
  979. return $arguments;
  980. }
  981. // TODO: add more parameters checks
  982. $query = array($arguments[0]);
  983. $sortParams = $arguments[1];
  984. if (isset($sortParams['by'])) {
  985. $query[] = 'BY ' . $sortParams['by'];
  986. }
  987. if (isset($sortParams['get'])) {
  988. $query[] = 'GET ' . $sortParams['get'];
  989. }
  990. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  991. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  992. }
  993. if (isset($sortParams['sort'])) {
  994. $query[] = strtoupper($sortParams['sort']);
  995. }
  996. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  997. $query[] = 'ALPHA';
  998. }
  999. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1000. $query[] = 'STORE ' . $sortParams['store'];
  1001. }
  1002. return $query;
  1003. }
  1004. }
  1005. /* persistence control commands */
  1006. class Predis_Commands_Save extends Predis_InlineCommand {
  1007. public function canBeHashed() { return false; }
  1008. public function getCommandId() { return 'SAVE'; }
  1009. }
  1010. class Predis_Commands_BackgroundSave extends Predis_InlineCommand {
  1011. public function canBeHashed() { return false; }
  1012. public function getCommandId() { return 'BGSAVE'; }
  1013. }
  1014. class Predis_Commands_LastSave extends Predis_InlineCommand {
  1015. public function canBeHashed() { return false; }
  1016. public function getCommandId() { return 'LASTSAVE'; }
  1017. }
  1018. class Predis_Commands_Shutdown extends Predis_InlineCommand {
  1019. public function canBeHashed() { return false; }
  1020. public function getCommandId() { return 'SHUTDOWN'; }
  1021. public function closesConnection() { return true; }
  1022. }
  1023. /* remote server control commands */
  1024. class Predis_Commands_Info extends Predis_InlineCommand {
  1025. public function canBeHashed() { return false; }
  1026. public function getCommandId() { return 'INFO'; }
  1027. public function parseResponse($data) {
  1028. $info = array();
  1029. $infoLines = explode("\r\n", $data, -1);
  1030. foreach ($infoLines as $row) {
  1031. list($k, $v) = explode(':', $row);
  1032. if (!preg_match('/^db\d+$/', $k)) {
  1033. $info[$k] = $v;
  1034. }
  1035. else {
  1036. $db = array();
  1037. foreach (explode(',', $v) as $dbvar) {
  1038. list($dbvk, $dbvv) = explode('=', $dbvar);
  1039. $db[trim($dbvk)] = $dbvv;
  1040. }
  1041. $info[$k] = $db;
  1042. }
  1043. }
  1044. return $info;
  1045. }
  1046. }
  1047. class SlaveOf extends Predis_InlineCommand {
  1048. public function canBeHashed() { return false; }
  1049. public function getCommandId() { return 'SLAVEOF'; }
  1050. public function filterArguments($arguments) {
  1051. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1052. }
  1053. }
  1054. ?>