Memcacheq.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Queue
  17. * @subpackage Adapter
  18. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * @see Zend_Queue_Adapter_AdapterAbstract
  24. */
  25. require_once 'Zend/Queue/Adapter/AdapterAbstract.php';
  26. /**
  27. * Class for using connecting to a Zend_Cache-based queuing system
  28. *
  29. * @category Zend
  30. * @package Zend_Queue
  31. * @subpackage Adapter
  32. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  33. * @license http://framework.zend.com/license/new-bsd New BSD License
  34. */
  35. class Zend_Queue_Adapter_Memcacheq extends Zend_Queue_Adapter_AdapterAbstract
  36. {
  37. const DEFAULT_HOST = '127.0.0.1';
  38. const DEFAULT_PORT = 22201;
  39. const EOL = "\r\n";
  40. /**
  41. * @var Memcache
  42. */
  43. protected $_cache = null;
  44. /**
  45. * @var string
  46. */
  47. protected $_host = null;
  48. /**
  49. * @var integer
  50. */
  51. protected $_port = null;
  52. /**
  53. * @var resource
  54. */
  55. protected $_socket = null;
  56. /********************************************************************
  57. * Constructor / Destructor
  58. *********************************************************************/
  59. /**
  60. * Constructor
  61. *
  62. * @param array|Zend_Config $options
  63. * @param null|Zend_Queue $queue
  64. * @return void
  65. */
  66. public function __construct($options, Zend_Queue $queue = null)
  67. {
  68. if (!extension_loaded('memcache')) {
  69. require_once 'Zend/Queue/Exception.php';
  70. throw new Zend_Queue_Exception('Memcache extension does not appear to be loaded');
  71. }
  72. parent::__construct($options, $queue);
  73. $options = &$this->_options['driverOptions'];
  74. if (!array_key_exists('host', $options)) {
  75. $options['host'] = self::DEFAULT_HOST;
  76. }
  77. if (!array_key_exists('port', $options)) {
  78. $options['port'] = self::DEFAULT_PORT;
  79. }
  80. $this->_cache = new Memcache();
  81. $result = $this->_cache->connect($options['host'], $options['port']);
  82. if ($result === false) {
  83. require_once 'Zend/Queue/Exception.php';
  84. throw new Zend_Queue_Exception('Could not connect to MemcacheQ');
  85. }
  86. $this->_host = $options['host'];
  87. $this->_port = (int)$options['port'];
  88. }
  89. /**
  90. * Destructor
  91. *
  92. * @return void
  93. */
  94. public function __destruct()
  95. {
  96. if ($this->_cache instanceof Memcache) {
  97. $this->_cache->close();
  98. }
  99. if (is_resource($this->_socket)) {
  100. $cmd = 'quit' . self::EOL;
  101. fwrite($this->_socket, $cmd);
  102. fclose($this->_socket);
  103. }
  104. }
  105. /********************************************************************
  106. * Queue management functions
  107. *********************************************************************/
  108. /**
  109. * Does a queue already exist?
  110. *
  111. * Throws an exception if the adapter cannot determine if a queue exists.
  112. * use isSupported('isExists') to determine if an adapter can test for
  113. * queue existance.
  114. *
  115. * @param string $name
  116. * @return boolean
  117. * @throws Zend_Queue_Exception
  118. */
  119. public function isExists($name)
  120. {
  121. if (empty($this->_queues)) {
  122. $this->getQueues();
  123. }
  124. return in_array($name, $this->_queues);
  125. }
  126. /**
  127. * Create a new queue
  128. *
  129. * Visibility timeout is how long a message is left in the queue "invisible"
  130. * to other readers. If the message is acknowleged (deleted) before the
  131. * timeout, then the message is deleted. However, if the timeout expires
  132. * then the message will be made available to other queue readers.
  133. *
  134. * @param string $name queue name
  135. * @param integer $timeout default visibility timeout
  136. * @return boolean
  137. * @throws Zend_Queue_Exception
  138. */
  139. public function create($name, $timeout=null)
  140. {
  141. if ($this->isExists($name)) {
  142. return false;
  143. }
  144. if ($timeout === null) {
  145. $timeout = self::CREATE_TIMEOUT_DEFAULT;
  146. }
  147. // MemcacheQ does not have a method to "create" a queue
  148. // queues are created upon sending a packet.
  149. // We cannot use the send() and receive() functions because those
  150. // depend on the current name.
  151. $result = $this->_cache->set($name, 'creating queue', 0, 15);
  152. $result = $this->_cache->get($name);
  153. return true;
  154. }
  155. /**
  156. * Delete a queue and all of it's messages
  157. *
  158. * Returns false if the queue is not found, true if the queue exists
  159. *
  160. * @param string $name queue name
  161. * @return boolean
  162. * @throws Zend_Queue_Exception
  163. */
  164. public function delete($name)
  165. {
  166. $response = $this->_sendCommand('delete ' . $name, array('DELETED', 'NOT_FOUND'), true);
  167. if (in_array('DELETED', $response)) {
  168. return true;
  169. }
  170. return false;
  171. }
  172. /**
  173. * Get an array of all available queues
  174. *
  175. * Not all adapters support getQueues(), use isSupported('getQueues')
  176. * to determine if the adapter supports this feature.
  177. *
  178. * @return array
  179. * @throws Zend_Queue_Exception
  180. */
  181. public function getQueues()
  182. {
  183. $this->_queues = array();
  184. $response = $this->_sendCommand('stats queue', array('END'));
  185. foreach ($response as $i => $line) {
  186. $this->_queues[] = str_replace('STAT ', '', $line);
  187. }
  188. return $this->_queues;
  189. }
  190. /**
  191. * Return the approximate number of messages in the queue
  192. *
  193. * @param Zend_Queue $queue
  194. * @return integer
  195. * @throws Zend_Queue_Exception (not supported)
  196. */
  197. public function count(Zend_Queue $queue=null)
  198. {
  199. require_once 'Zend/Queue/Exception.php';
  200. throw new Zend_Queue_Exception('count() is not supported in this adapter');
  201. }
  202. /********************************************************************
  203. * Messsage management functions
  204. *********************************************************************/
  205. /**
  206. * Send a message to the queue
  207. *
  208. * @param string $message Message to send to the active queue
  209. * @param Zend_Queue $queue
  210. * @return Zend_Queue_Message
  211. * @throws Zend_Queue_Exception
  212. */
  213. public function send($message, Zend_Queue $queue=null)
  214. {
  215. if ($queue === null) {
  216. $queue = $this->_queue;
  217. }
  218. if (!$this->isExists($queue->getName())) {
  219. require_once 'Zend/Queue/Exception.php';
  220. throw new Zend_Queue_Exception('Queue does not exist:' . $queue->getName());
  221. }
  222. $message = (string) $message;
  223. $data = array(
  224. 'message_id' => md5(uniqid(rand(), true)),
  225. 'handle' => null,
  226. 'body' => $message,
  227. 'md5' => md5($message),
  228. );
  229. $result = $this->_cache->set($queue->getName(), $message, 0, 0);
  230. if ($result === false) {
  231. require_once 'Zend/Queue/Exception.php';
  232. throw new Zend_Queue_Exception('failed to insert message into queue:' . $queue->getName());
  233. }
  234. $options = array(
  235. 'queue' => $queue,
  236. 'data' => $data,
  237. );
  238. $classname = $queue->getMessageClass();
  239. if (!class_exists($classname)) {
  240. require_once 'Zend/Loader.php';
  241. Zend_Loader::loadClass($classname);
  242. }
  243. return new $classname($options);
  244. }
  245. /**
  246. * Get messages in the queue
  247. *
  248. * @param integer $maxMessages Maximum number of messages to return
  249. * @param integer $timeout Visibility timeout for these messages
  250. * @param Zend_Queue $queue
  251. * @return Zend_Queue_Message_Iterator
  252. * @throws Zend_Queue_Exception
  253. */
  254. public function receive($maxMessages=null, $timeout=null, Zend_Queue $queue=null)
  255. {
  256. if ($maxMessages === null) {
  257. $maxMessages = 1;
  258. }
  259. if ($timeout === null) {
  260. $timeout = self::RECEIVE_TIMEOUT_DEFAULT;
  261. }
  262. if ($queue === null) {
  263. $queue = $this->_queue;
  264. }
  265. $msgs = array();
  266. if ($maxMessages > 0 ) {
  267. for ($i = 0; $i < $maxMessages; $i++) {
  268. $data = array(
  269. 'handle' => md5(uniqid(rand(), true)),
  270. 'body' => $this->_cache->get($queue->getName()),
  271. );
  272. $msgs[] = $data;
  273. }
  274. }
  275. $options = array(
  276. 'queue' => $queue,
  277. 'data' => $msgs,
  278. 'messageClass' => $queue->getMessageClass(),
  279. );
  280. $classname = $queue->getMessageSetClass();
  281. if (!class_exists($classname)) {
  282. require_once 'Zend/Loader.php';
  283. Zend_Loader::loadClass($classname);
  284. }
  285. return new $classname($options);
  286. }
  287. /**
  288. * Delete a message from the queue
  289. *
  290. * Returns true if the message is deleted, false if the deletion is
  291. * unsuccessful.
  292. *
  293. * @param Zend_Queue_Message $message
  294. * @return boolean
  295. * @throws Zend_Queue_Exception (unsupported)
  296. */
  297. public function deleteMessage(Zend_Queue_Message $message)
  298. {
  299. require_once 'Zend/Queue/Exception.php';
  300. throw new Zend_Queue_Exception('deleteMessage() is not supported in ' . get_class($this));
  301. }
  302. /********************************************************************
  303. * Supporting functions
  304. *********************************************************************/
  305. /**
  306. * Return a list of queue capabilities functions
  307. *
  308. * $array['function name'] = true or false
  309. * true is supported, false is not supported.
  310. *
  311. * @param string $name
  312. * @return array
  313. */
  314. public function getCapabilities()
  315. {
  316. return array(
  317. 'create' => true,
  318. 'delete' => true,
  319. 'send' => true,
  320. 'receive' => true,
  321. 'deleteMessage' => false,
  322. 'getQueues' => true,
  323. 'count' => false,
  324. 'isExists' => true,
  325. );
  326. }
  327. /********************************************************************
  328. * Functions that are not part of the Zend_Queue_Adapter_Abstract
  329. *********************************************************************/
  330. /**
  331. * sends a command to MemcacheQ
  332. *
  333. * The memcache functions by php cannot handle all types of requests
  334. * supported by MemcacheQ
  335. * Non-standard requests are handled by this function.
  336. *
  337. * @param string $command - command to send to memcacheQ
  338. * @param array $terminator - strings to indicate end of memcacheQ response
  339. * @param boolean $include_term - include terminator in response
  340. * @return array
  341. * @throws Zend_Queue_Exception if connection cannot be opened
  342. */
  343. protected function _sendCommand($command, array $terminator, $include_term=false)
  344. {
  345. if (!is_resource($this->_socket)) {
  346. $this->_socket = fsockopen($this->_host, $this->_port, $errno, $errstr, 10);
  347. }
  348. if ($this->_socket === false) {
  349. require_once 'Zend/Queue/Exception.php';
  350. throw new Zend_Queue_Exception("Could not open a connection to $this->_host:$this->_port errno=$errno : $errstr");
  351. }
  352. $response = array();
  353. $cmd = $command . self::EOL;
  354. fwrite($this->_socket, $cmd);
  355. $continue_reading = true;
  356. while (!feof($this->_socket) && $continue_reading) {
  357. $resp = trim(fgets($this->_socket, 1024));
  358. if (in_array($resp, $terminator)) {
  359. if ($include_term) {
  360. $response[] = $resp;
  361. }
  362. $continue_reading = false;
  363. } else {
  364. $response[] = $resp;
  365. }
  366. }
  367. return $response;
  368. }
  369. }