PageRenderTime 39ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/library/Zend/Queue/Adapter/Memcacheq.php

https://bitbucket.org/ilyabazhenov/speakplace
PHP | 428 lines | 201 code | 54 blank | 173 comment | 28 complexity | 1d4f846b695cc14ea13e70b4cea08fac MD5 | raw file
  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-2011 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: Memcacheq.php 23775 2011-03-01 17:25:24Z ralph $
  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-2011 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. $this->_queues[] = $name;
  154. return true;
  155. }
  156. /**
  157. * Delete a queue and all of it's messages
  158. *
  159. * Returns false if the queue is not found, true if the queue exists
  160. *
  161. * @param string $name queue name
  162. * @return boolean
  163. * @throws Zend_Queue_Exception
  164. */
  165. public function delete($name)
  166. {
  167. $response = $this->_sendCommand('delete ' . $name, array('DELETED', 'NOT_FOUND'), true);
  168. if (in_array('DELETED', $response)) {
  169. $key = array_search($name, $this->_queues);
  170. if ($key !== false) {
  171. unset($this->_queues[$key]);
  172. }
  173. return true;
  174. }
  175. return false;
  176. }
  177. /**
  178. * Get an array of all available queues
  179. *
  180. * Not all adapters support getQueues(), use isSupported('getQueues')
  181. * to determine if the adapter supports this feature.
  182. *
  183. * @return array
  184. * @throws Zend_Queue_Exception
  185. */
  186. public function getQueues()
  187. {
  188. $this->_queues = array();
  189. $response = $this->_sendCommand('stats queue', array('END'));
  190. foreach ($response as $i => $line) {
  191. $this->_queues[] = str_replace('STAT ', '', $line);
  192. }
  193. return $this->_queues;
  194. }
  195. /**
  196. * Return the approximate number of messages in the queue
  197. *
  198. * @param Zend_Queue $queue
  199. * @return integer
  200. * @throws Zend_Queue_Exception (not supported)
  201. */
  202. public function count(Zend_Queue $queue=null)
  203. {
  204. require_once 'Zend/Queue/Exception.php';
  205. throw new Zend_Queue_Exception('count() is not supported in this adapter');
  206. }
  207. /********************************************************************
  208. * Messsage management functions
  209. *********************************************************************/
  210. /**
  211. * Send a message to the queue
  212. *
  213. * @param string $message Message to send to the active queue
  214. * @param Zend_Queue $queue
  215. * @return Zend_Queue_Message
  216. * @throws Zend_Queue_Exception
  217. */
  218. public function send($message, Zend_Queue $queue=null)
  219. {
  220. if ($queue === null) {
  221. $queue = $this->_queue;
  222. }
  223. if (!$this->isExists($queue->getName())) {
  224. require_once 'Zend/Queue/Exception.php';
  225. throw new Zend_Queue_Exception('Queue does not exist:' . $queue->getName());
  226. }
  227. $message = (string) $message;
  228. $data = array(
  229. 'message_id' => md5(uniqid(rand(), true)),
  230. 'handle' => null,
  231. 'body' => $message,
  232. 'md5' => md5($message),
  233. );
  234. $result = $this->_cache->set($queue->getName(), $message, 0, 0);
  235. if ($result === false) {
  236. require_once 'Zend/Queue/Exception.php';
  237. throw new Zend_Queue_Exception('failed to insert message into queue:' . $queue->getName());
  238. }
  239. $options = array(
  240. 'queue' => $queue,
  241. 'data' => $data,
  242. );
  243. $classname = $queue->getMessageClass();
  244. if (!class_exists($classname)) {
  245. require_once 'Zend/Loader.php';
  246. Zend_Loader::loadClass($classname);
  247. }
  248. return new $classname($options);
  249. }
  250. /**
  251. * Get messages in the queue
  252. *
  253. * @param integer $maxMessages Maximum number of messages to return
  254. * @param integer $timeout Visibility timeout for these messages
  255. * @param Zend_Queue $queue
  256. * @return Zend_Queue_Message_Iterator
  257. * @throws Zend_Queue_Exception
  258. */
  259. public function receive($maxMessages=null, $timeout=null, Zend_Queue $queue=null)
  260. {
  261. if ($maxMessages === null) {
  262. $maxMessages = 1;
  263. }
  264. if ($timeout === null) {
  265. $timeout = self::RECEIVE_TIMEOUT_DEFAULT;
  266. }
  267. if ($queue === null) {
  268. $queue = $this->_queue;
  269. }
  270. $msgs = array();
  271. if ($maxMessages > 0 ) {
  272. for ($i = 0; $i < $maxMessages; $i++) {
  273. $data = array(
  274. 'handle' => md5(uniqid(rand(), true)),
  275. 'body' => $this->_cache->get($queue->getName()),
  276. );
  277. $msgs[] = $data;
  278. }
  279. }
  280. $options = array(
  281. 'queue' => $queue,
  282. 'data' => $msgs,
  283. 'messageClass' => $queue->getMessageClass(),
  284. );
  285. $classname = $queue->getMessageSetClass();
  286. if (!class_exists($classname)) {
  287. require_once 'Zend/Loader.php';
  288. Zend_Loader::loadClass($classname);
  289. }
  290. return new $classname($options);
  291. }
  292. /**
  293. * Delete a message from the queue
  294. *
  295. * Returns true if the message is deleted, false if the deletion is
  296. * unsuccessful.
  297. *
  298. * @param Zend_Queue_Message $message
  299. * @return boolean
  300. * @throws Zend_Queue_Exception (unsupported)
  301. */
  302. public function deleteMessage(Zend_Queue_Message $message)
  303. {
  304. require_once 'Zend/Queue/Exception.php';
  305. throw new Zend_Queue_Exception('deleteMessage() is not supported in ' . get_class($this));
  306. }
  307. /********************************************************************
  308. * Supporting functions
  309. *********************************************************************/
  310. /**
  311. * Return a list of queue capabilities functions
  312. *
  313. * $array['function name'] = true or false
  314. * true is supported, false is not supported.
  315. *
  316. * @param string $name
  317. * @return array
  318. */
  319. public function getCapabilities()
  320. {
  321. return array(
  322. 'create' => true,
  323. 'delete' => true,
  324. 'send' => true,
  325. 'receive' => true,
  326. 'deleteMessage' => false,
  327. 'getQueues' => true,
  328. 'count' => false,
  329. 'isExists' => true,
  330. );
  331. }
  332. /********************************************************************
  333. * Functions that are not part of the Zend_Queue_Adapter_Abstract
  334. *********************************************************************/
  335. /**
  336. * sends a command to MemcacheQ
  337. *
  338. * The memcache functions by php cannot handle all types of requests
  339. * supported by MemcacheQ
  340. * Non-standard requests are handled by this function.
  341. *
  342. * @param string $command - command to send to memcacheQ
  343. * @param array $terminator - strings to indicate end of memcacheQ response
  344. * @param boolean $include_term - include terminator in response
  345. * @return array
  346. * @throws Zend_Queue_Exception if connection cannot be opened
  347. */
  348. protected function _sendCommand($command, array $terminator, $include_term=false)
  349. {
  350. if (!is_resource($this->_socket)) {
  351. $this->_socket = fsockopen($this->_host, $this->_port, $errno, $errstr, 10);
  352. }
  353. if ($this->_socket === false) {
  354. require_once 'Zend/Queue/Exception.php';
  355. throw new Zend_Queue_Exception("Could not open a connection to $this->_host:$this->_port errno=$errno : $errstr");
  356. }
  357. $response = array();
  358. $cmd = $command . self::EOL;
  359. fwrite($this->_socket, $cmd);
  360. $continue_reading = true;
  361. while (!feof($this->_socket) && $continue_reading) {
  362. $resp = trim(fgets($this->_socket, 1024));
  363. if (in_array($resp, $terminator)) {
  364. if ($include_term) {
  365. $response[] = $resp;
  366. }
  367. $continue_reading = false;
  368. } else {
  369. $response[] = $resp;
  370. }
  371. }
  372. return $response;
  373. }
  374. }