]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into testing
[quix0rs-gnu-social.git] / classes / Memcached_DataObject.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 class Memcached_DataObject extends Safe_DataObject
23 {
24     /**
25      * Wrapper for DB_DataObject's static lookup using memcached
26      * as backing instead of an in-process cache array.
27      *
28      * @param string $cls classname of object type to load
29      * @param mixed $k key field name, or value for primary key
30      * @param mixed $v key field value, or leave out for primary key lookup
31      * @return mixed Memcached_DataObject subtype or false
32      */
33     function &staticGet($cls, $k, $v=null)
34     {
35         if (is_null($v)) {
36             $v = $k;
37             # XXX: HACK!
38             $i = new $cls;
39             $keys = $i->keys();
40             $k = $keys[0];
41             unset($i);
42         }
43         $i = Memcached_DataObject::getcached($cls, $k, $v);
44         if ($i === false) { // false == cache miss
45             $i = DB_DataObject::factory($cls);
46             if (empty($i)) {
47                 $i = false;
48                 return $i;
49             }
50             $result = $i->get($k, $v);
51             if ($result) {
52                 // Hit!
53                 $i->encache();
54             } else {
55                 // save the fact that no such row exists
56                 $c = self::memcache();
57                 if (!empty($c)) {
58                     $ck = self::cachekey($cls, $k, $v);
59                     $c->set($ck, null);
60                 }
61                 $i = false;
62             }
63         }
64         return $i;
65     }
66
67     /**
68      * @fixme Should this return false on lookup fail to match staticGet?
69      */
70     function pkeyGet($cls, $kv)
71     {
72         $i = Memcached_DataObject::multicache($cls, $kv);
73         if ($i !== false) { // false == cache miss
74             return $i;
75         } else {
76             $i = DB_DataObject::factory($cls);
77             if (empty($i)) {
78                 return false;
79             }
80             foreach ($kv as $k => $v) {
81                 $i->$k = $v;
82             }
83             if ($i->find(true)) {
84                 $i->encache();
85             } else {
86                 $i = null;
87                 $c = self::memcache();
88                 if (!empty($c)) {
89                     $ck = self::multicacheKey($cls, $kv);
90                     $c->set($ck, null);
91                 }
92             }
93             return $i;
94         }
95     }
96
97     function insert()
98     {
99         $result = parent::insert();
100         if ($result) {
101             $this->fixupTimestamps();
102             $this->encache(); // in case of cached negative lookups
103         }
104         return $result;
105     }
106
107     function update($orig=null)
108     {
109         if (is_object($orig) && $orig instanceof Memcached_DataObject) {
110             $orig->decache(); # might be different keys
111         }
112         $result = parent::update($orig);
113         if ($result) {
114             $this->fixupTimestamps();
115             $this->encache();
116         }
117         return $result;
118     }
119
120     function delete()
121     {
122         $this->decache(); # while we still have the values!
123         return parent::delete();
124     }
125
126     static function memcache() {
127         return common_memcache();
128     }
129
130     static function cacheKey($cls, $k, $v) {
131         if (is_object($cls) || is_object($k) || is_object($v)) {
132             $e = new Exception();
133             common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
134                 str_replace("\n", " ", $e->getTraceAsString()));
135         }
136         return common_cache_key(strtolower($cls).':'.$k.':'.$v);
137     }
138
139     static function getcached($cls, $k, $v) {
140         $c = Memcached_DataObject::memcache();
141         if (!$c) {
142             return false;
143         } else {
144             $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
145             if (0 == strcasecmp($cls, 'User')) {
146                 // Special case for User
147                 if (is_object($obj) && is_object($obj->id)) {
148                     common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
149                     $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
150                     return false;
151                 }
152             }
153             return $obj;
154         }
155     }
156
157     function keyTypes()
158     {
159         // ini-based classes return number-indexed arrays. handbuilt
160         // classes return column => keytype. Make this uniform.
161
162         $keys = $this->keys();
163
164         $keyskeys = array_keys($keys);
165
166         if (is_string($keyskeys[0])) {
167             return $keys;
168         }
169
170         global $_DB_DATAOBJECT;
171         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
172             $this->databaseStructure();
173
174         }
175         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
176     }
177
178     function encache()
179     {
180         $c = $this->memcache();
181
182         if (!$c) {
183             return false;
184         } else if ($this->tableName() == 'user' && is_object($this->id)) {
185             // Special case for User bug
186             $e = new Exception();
187             common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
188                        str_replace("\n", " ", $e->getTraceAsString()));
189             return false;
190         } else {
191                 $keys = $this->_allCacheKeys();
192
193                 foreach ($keys as $key) {
194                     $c->set($key, $this);
195                 }
196         }
197     }
198
199     function decache()
200     {
201         $c = $this->memcache();
202
203         if (!$c) {
204             return false;
205         }
206
207         $keys = $this->_allCacheKeys();
208
209         foreach ($keys as $key) {
210             $c->delete($key, $this);
211         }
212     }
213
214     function _allCacheKeys()
215     {
216         $ckeys = array();
217
218         $types = $this->keyTypes();
219         ksort($types);
220
221         $pkey = array();
222         $pval = array();
223
224         foreach ($types as $key => $type) {
225
226             assert(!empty($key));
227
228             if ($type == 'U') {
229                 if (empty($this->$key)) {
230                     continue;
231                 }
232                 $ckeys[] = $this->cacheKey($this->tableName(), $key, $this->$key);
233             } else if ($type == 'K' || $type == 'N') {
234                 $pkey[] = $key;
235                 $pval[] = $this->$key;
236             } else {
237                 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
238             }
239         }
240
241         assert(count($pkey) > 0);
242
243         // XXX: should work for both compound and scalar pkeys
244         $pvals = implode(',', $pval);
245         $pkeys = implode(',', $pkey);
246
247         $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
248
249         return $ckeys;
250     }
251
252     function multicache($cls, $kv)
253     {
254         ksort($kv);
255         $c = self::memcache();
256         if (!$c) {
257             return false;
258         } else {
259             return $c->get(self::multicacheKey($cls, $kv));
260         }
261     }
262
263     static function multicacheKey($cls, $kv)
264     {
265         ksort($kv);
266         $pkeys = implode(',', array_keys($kv));
267         $pvals = implode(',', array_values($kv));
268         return self::cacheKey($cls, $pkeys, $pvals);
269     }
270
271     function getSearchEngine($table)
272     {
273         require_once INSTALLDIR.'/lib/search_engines.php';
274         static $search_engine;
275         if (!isset($search_engine)) {
276             if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
277                 if ('mysql' === common_config('db', 'type')) {
278                     $type = common_config('search', 'type');
279                     if ($type == 'like') {
280                         $search_engine = new MySQLLikeSearch($this, $table);
281                     } else if ($type == 'fulltext') {
282                         $search_engine = new MySQLSearch($this, $table);
283                     } else {
284                         throw new ServerException('Unknown search type: ' . $type);
285                     }
286                 } else {
287                     $search_engine = new PGSearch($this, $table);
288                 }
289             }
290         }
291         return $search_engine;
292     }
293
294     static function cachedQuery($cls, $qry, $expiry=3600)
295     {
296         $c = Memcached_DataObject::memcache();
297         if (!$c) {
298             $inst = new $cls();
299             $inst->query($qry);
300             return $inst;
301         }
302         $key_part = common_keyize($cls).':'.md5($qry);
303         $ckey = common_cache_key($key_part);
304         $stored = $c->get($ckey);
305
306         if ($stored !== false) {
307             return new ArrayWrapper($stored);
308         }
309
310         $inst = new $cls();
311         $inst->query($qry);
312         $cached = array();
313         while ($inst->fetch()) {
314             $cached[] = clone($inst);
315         }
316         $inst->free();
317         $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
318         return new ArrayWrapper($cached);
319     }
320
321     /**
322      * sends query to database - this is the private one that must work
323      *   - internal functions use this rather than $this->query()
324      *
325      * Overridden to do logging.
326      *
327      * @param  string  $string
328      * @access private
329      * @return mixed none or PEAR_Error
330      */
331     function _query($string)
332     {
333         $start = microtime(true);
334         $result = parent::_query($string);
335         $delta = microtime(true) - $start;
336
337         $limit = common_config('db', 'log_slow_queries');
338         if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
339             $clean = $this->sanitizeQuery($string);
340             common_log(LOG_DEBUG, sprintf("DB query (%0.3fs): %s", $delta, $clean));
341         }
342         return $result;
343     }
344
345     // Sanitize a query for logging
346     // @fixme don't trim spaces in string literals
347     function sanitizeQuery($string)
348     {
349         $string = preg_replace('/\s+/', ' ', $string);
350         $string = trim($string);
351         return $string;
352     }
353
354     // We overload so that 'SET NAMES "utf8"' is called for
355     // each connection
356
357     function _connect()
358     {
359         global $_DB_DATAOBJECT;
360
361         $sum = $this->_getDbDsnMD5();
362
363         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
364             !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
365             $exists = true;
366         } else {
367             $exists = false;
368        }
369
370         // @fixme horrible evil hack!
371         //
372         // In multisite configuration we don't want to keep around a separate
373         // connection for every database; we could end up with thousands of
374         // connections open per thread. In an ideal world we might keep
375         // a connection per server and select different databases, but that'd
376         // be reliant on having the same db username/pass as well.
377         //
378         // MySQL connections are cheap enough we're going to try just
379         // closing out the old connection and reopening when we encounter
380         // a new DSN.
381         //
382         // WARNING WARNING if we end up actually using multiple DBs at a time
383         // we'll need some fancier logic here.
384         if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
385             foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
386                 if (!empty($conn)) {
387                     $conn->disconnect();
388                 }
389                 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
390             }
391         }
392
393         $result = parent::_connect();
394
395         if ($result && !$exists) {
396             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
397             if (common_config('db', 'type') == 'mysql' &&
398                 common_config('db', 'utf8')) {
399                 $conn = $DB->connection;
400                 if (!empty($conn)) {
401                     if ($DB instanceof DB_mysqli) {
402                         mysqli_set_charset($conn, 'utf8');
403                     } else if ($DB instanceof DB_mysql) {
404                         mysql_set_charset('utf8', $conn);
405                     }
406                 }
407             }
408         }
409
410         return $result;
411     }
412
413     // XXX: largely cadged from DB_DataObject
414
415     function _getDbDsnMD5()
416     {
417         if ($this->_database_dsn_md5) {
418             return $this->_database_dsn_md5;
419         }
420
421         $dsn = $this->_getDbDsn();
422
423         if (is_string($dsn)) {
424             $sum = md5($dsn);
425         } else {
426             /// support array based dsn's
427             $sum = md5(serialize($dsn));
428         }
429
430         return $sum;
431     }
432
433     function _getDbDsn()
434     {
435         global $_DB_DATAOBJECT;
436
437         if (empty($_DB_DATAOBJECT['CONFIG'])) {
438             DB_DataObject::_loadConfig();
439         }
440
441         $options = &$_DB_DATAOBJECT['CONFIG'];
442
443         // if the databse dsn dis defined in the object..
444
445         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
446
447         if (!$dsn) {
448
449             if (!$this->_database) {
450                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
451             }
452
453             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
454                 $dsn = $options["database_{$this->_database}"];
455             } else if (!empty($options['database'])) {
456                 $dsn = $options['database'];
457             }
458         }
459
460         if (!$dsn) {
461             throw new Exception("No database name / dsn found anywhere");
462         }
463
464         return $dsn;
465     }
466
467     static function blow()
468     {
469         $c = self::memcache();
470
471         if (empty($c)) {
472             return false;
473         }
474
475         $args = func_get_args();
476
477         $format = array_shift($args);
478
479         $keyPart = vsprintf($format, $args);
480
481         $cacheKey = common_cache_key($keyPart);
482
483         return $c->delete($cacheKey);
484     }
485
486     function fixupTimestamps()
487     {
488         // Fake up timestamp columns
489         $columns = $this->table();
490         foreach ($columns as $name => $type) {
491             if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
492                 $this->$name = common_sql_now();
493             }
494         }
495     }
496
497     function debugDump()
498     {
499         common_debug("debugDump: " . common_log_objstring($this));
500     }
501
502     function raiseError($message, $type = null, $behaviour = null)
503     {
504         throw new ServerException("DB_DataObject error [$type]: $message");
505     }
506
507     static function cacheGet($keyPart)
508     {
509         $c = self::memcache();
510
511         if (empty($c)) {
512             return false;
513         }
514
515         $cacheKey = common_cache_key($keyPart);
516
517         return $c->get($cacheKey);
518     }
519
520     static function cacheSet($keyPart, $value)
521     {
522         $c = self::memcache();
523
524         if (empty($c)) {
525             return false;
526         }
527
528         $cacheKey = common_cache_key($keyPart);
529
530         return $c->set($cacheKey, $value);
531     }
532 }
533