]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
Merge branch 'master' of gitorious.org:statusnet/mainline
[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) && !($v instanceof DB_DataObject_Cast))) {
132             $e = new Exception();
133             common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
134                 str_replace("\n", " ", $e->getTraceAsString()));
135         }
136         if (is_object($v) && $v instanceof DB_DataObject_Cast) {
137             switch ($v->type) {
138             case 'date':
139                 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
140                 break;
141             case 'blob':
142             case 'string':
143             case 'sql':
144             case 'datetime':
145             case 'time':
146                 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
147                 break;
148             default:
149                 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
150                 break;
151             }
152         } else {
153             $vstr = $v;
154         }
155         return common_cache_key(strtolower($cls).':'.$k.':'.$vstr);
156     }
157
158     static function getcached($cls, $k, $v) {
159         $c = Memcached_DataObject::memcache();
160         if (!$c) {
161             return false;
162         } else {
163             $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
164             if (0 == strcasecmp($cls, 'User')) {
165                 // Special case for User
166                 if (is_object($obj) && is_object($obj->id)) {
167                     common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
168                     $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
169                     return false;
170                 }
171             }
172             return $obj;
173         }
174     }
175
176     function keyTypes()
177     {
178         // ini-based classes return number-indexed arrays. handbuilt
179         // classes return column => keytype. Make this uniform.
180
181         $keys = $this->keys();
182
183         $keyskeys = array_keys($keys);
184
185         if (is_string($keyskeys[0])) {
186             return $keys;
187         }
188
189         global $_DB_DATAOBJECT;
190         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
191             $this->databaseStructure();
192
193         }
194         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
195     }
196
197     function encache()
198     {
199         $c = $this->memcache();
200
201         if (!$c) {
202             return false;
203         } else if ($this->tableName() == 'user' && is_object($this->id)) {
204             // Special case for User bug
205             $e = new Exception();
206             common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
207                        str_replace("\n", " ", $e->getTraceAsString()));
208             return false;
209         } else {
210                 $keys = $this->_allCacheKeys();
211
212                 foreach ($keys as $key) {
213                     $c->set($key, $this);
214                 }
215         }
216     }
217
218     function decache()
219     {
220         $c = $this->memcache();
221
222         if (!$c) {
223             return false;
224         }
225
226         $keys = $this->_allCacheKeys();
227
228         foreach ($keys as $key) {
229             $c->delete($key, $this);
230         }
231     }
232
233     function _allCacheKeys()
234     {
235         $ckeys = array();
236
237         $types = $this->keyTypes();
238         ksort($types);
239
240         $pkey = array();
241         $pval = array();
242
243         foreach ($types as $key => $type) {
244
245             assert(!empty($key));
246
247             if ($type == 'U') {
248                 if (empty($this->$key)) {
249                     continue;
250                 }
251                 $ckeys[] = $this->cacheKey($this->tableName(), $key, $this->$key);
252             } else if ($type == 'K' || $type == 'N') {
253                 $pkey[] = $key;
254                 $pval[] = $this->$key;
255             } else {
256                 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
257             }
258         }
259
260         assert(count($pkey) > 0);
261
262         // XXX: should work for both compound and scalar pkeys
263         $pvals = implode(',', $pval);
264         $pkeys = implode(',', $pkey);
265
266         $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
267
268         return $ckeys;
269     }
270
271     function multicache($cls, $kv)
272     {
273         ksort($kv);
274         $c = self::memcache();
275         if (!$c) {
276             return false;
277         } else {
278             return $c->get(self::multicacheKey($cls, $kv));
279         }
280     }
281
282     static function multicacheKey($cls, $kv)
283     {
284         ksort($kv);
285         $pkeys = implode(',', array_keys($kv));
286         $pvals = implode(',', array_values($kv));
287         return self::cacheKey($cls, $pkeys, $pvals);
288     }
289
290     function getSearchEngine($table)
291     {
292         require_once INSTALLDIR.'/lib/search_engines.php';
293         static $search_engine;
294         if (!isset($search_engine)) {
295             if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
296                 if ('mysql' === common_config('db', 'type')) {
297                     $type = common_config('search', 'type');
298                     if ($type == 'like') {
299                         $search_engine = new MySQLLikeSearch($this, $table);
300                     } else if ($type == 'fulltext') {
301                         $search_engine = new MySQLSearch($this, $table);
302                     } else {
303                         throw new ServerException('Unknown search type: ' . $type);
304                     }
305                 } else {
306                     $search_engine = new PGSearch($this, $table);
307                 }
308             }
309         }
310         return $search_engine;
311     }
312
313     static function cachedQuery($cls, $qry, $expiry=3600)
314     {
315         $c = Memcached_DataObject::memcache();
316         if (!$c) {
317             $inst = new $cls();
318             $inst->query($qry);
319             return $inst;
320         }
321         $key_part = common_keyize($cls).':'.md5($qry);
322         $ckey = common_cache_key($key_part);
323         $stored = $c->get($ckey);
324
325         if ($stored !== false) {
326             return new ArrayWrapper($stored);
327         }
328
329         $inst = new $cls();
330         $inst->query($qry);
331         $cached = array();
332         while ($inst->fetch()) {
333             $cached[] = clone($inst);
334         }
335         $inst->free();
336         $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
337         return new ArrayWrapper($cached);
338     }
339
340     /**
341      * sends query to database - this is the private one that must work
342      *   - internal functions use this rather than $this->query()
343      *
344      * Overridden to do logging.
345      *
346      * @param  string  $string
347      * @access private
348      * @return mixed none or PEAR_Error
349      */
350     function _query($string)
351     {
352         if (common_config('db', 'annotate_queries')) {
353             $string = $this->annotateQuery($string);
354         }
355
356         $start = microtime(true);
357         $result = parent::_query($string);
358         $delta = microtime(true) - $start;
359
360         $limit = common_config('db', 'log_slow_queries');
361         if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
362             $clean = $this->sanitizeQuery($string);
363             common_log(LOG_DEBUG, sprintf("DB query (%0.3fs): %s", $delta, $clean));
364         }
365         return $result;
366     }
367
368     /**
369      * Find the first caller in the stack trace that's not a
370      * low-level database function and add a comment to the
371      * query string. This should then be visible in process lists
372      * and slow query logs, to help identify problem areas.
373      *
374      * Also marks whether this was a web GET/POST or which daemon
375      * was running it.
376      *
377      * @param string $string SQL query string
378      * @return string SQL query string, with a comment in it
379      */
380     function annotateQuery($string)
381     {
382         $ignore = array('annotateQuery',
383                         '_query',
384                         'query',
385                         'get',
386                         'insert',
387                         'delete',
388                         'update',
389                         'find');
390         $ignoreStatic = array('staticGet',
391                               'pkeyGet',
392                               'cachedQuery');
393         $here = get_class($this); // if we get confused
394         $bt = debug_backtrace();
395
396         // Find the first caller that's not us?
397         foreach ($bt as $frame) {
398             $func = $frame['function'];
399             if (isset($frame['type']) && $frame['type'] == '::') {
400                 if (in_array($func, $ignoreStatic)) {
401                     continue;
402                 }
403                 $here = $frame['class'] . '::' . $func;
404                 break;
405             } else if (isset($frame['type']) && $frame['type'] == '->') {
406                 if ($frame['object'] === $this && in_array($func, $ignore)) {
407                     continue;
408                 }
409                 if (in_array($func, $ignoreStatic)) {
410                     continue; // @fixme this shouldn't be needed?
411                 }
412                 $here = get_class($frame['object']) . '->' . $func;
413                 break;
414             }
415             $here = $func;
416             break;
417         }
418
419         if (php_sapi_name() == 'cli') {
420             $context = basename($_SERVER['PHP_SELF']);
421         } else {
422             $context = $_SERVER['REQUEST_METHOD'];
423         }
424
425         // Slip the comment in after the first command,
426         // or DB_DataObject gets confused about handling inserts and such.
427         $parts = explode(' ', $string, 2);
428         $parts[0] .= " /* $context $here */";
429         return implode(' ', $parts);
430     }
431
432     // Sanitize a query for logging
433     // @fixme don't trim spaces in string literals
434     function sanitizeQuery($string)
435     {
436         $string = preg_replace('/\s+/', ' ', $string);
437         $string = trim($string);
438         return $string;
439     }
440
441     // We overload so that 'SET NAMES "utf8"' is called for
442     // each connection
443
444     function _connect()
445     {
446         global $_DB_DATAOBJECT;
447
448         $sum = $this->_getDbDsnMD5();
449
450         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
451             !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
452             $exists = true;
453         } else {
454             $exists = false;
455        }
456
457         // @fixme horrible evil hack!
458         //
459         // In multisite configuration we don't want to keep around a separate
460         // connection for every database; we could end up with thousands of
461         // connections open per thread. In an ideal world we might keep
462         // a connection per server and select different databases, but that'd
463         // be reliant on having the same db username/pass as well.
464         //
465         // MySQL connections are cheap enough we're going to try just
466         // closing out the old connection and reopening when we encounter
467         // a new DSN.
468         //
469         // WARNING WARNING if we end up actually using multiple DBs at a time
470         // we'll need some fancier logic here.
471         if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
472             foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
473                 if (!empty($conn)) {
474                     $conn->disconnect();
475                 }
476                 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
477             }
478         }
479
480         $result = parent::_connect();
481
482         if ($result && !$exists) {
483             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
484             if (common_config('db', 'type') == 'mysql' &&
485                 common_config('db', 'utf8')) {
486                 $conn = $DB->connection;
487                 if (!empty($conn)) {
488                     if ($DB instanceof DB_mysqli) {
489                         mysqli_set_charset($conn, 'utf8');
490                     } else if ($DB instanceof DB_mysql) {
491                         mysql_set_charset('utf8', $conn);
492                     }
493                 }
494             }
495         }
496
497         return $result;
498     }
499
500     // XXX: largely cadged from DB_DataObject
501
502     function _getDbDsnMD5()
503     {
504         if ($this->_database_dsn_md5) {
505             return $this->_database_dsn_md5;
506         }
507
508         $dsn = $this->_getDbDsn();
509
510         if (is_string($dsn)) {
511             $sum = md5($dsn);
512         } else {
513             /// support array based dsn's
514             $sum = md5(serialize($dsn));
515         }
516
517         return $sum;
518     }
519
520     function _getDbDsn()
521     {
522         global $_DB_DATAOBJECT;
523
524         if (empty($_DB_DATAOBJECT['CONFIG'])) {
525             DB_DataObject::_loadConfig();
526         }
527
528         $options = &$_DB_DATAOBJECT['CONFIG'];
529
530         // if the databse dsn dis defined in the object..
531
532         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
533
534         if (!$dsn) {
535
536             if (!$this->_database) {
537                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
538             }
539
540             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
541                 $dsn = $options["database_{$this->_database}"];
542             } else if (!empty($options['database'])) {
543                 $dsn = $options['database'];
544             }
545         }
546
547         if (!$dsn) {
548             throw new Exception("No database name / dsn found anywhere");
549         }
550
551         return $dsn;
552     }
553
554     static function blow()
555     {
556         $c = self::memcache();
557
558         if (empty($c)) {
559             return false;
560         }
561
562         $args = func_get_args();
563
564         $format = array_shift($args);
565
566         $keyPart = vsprintf($format, $args);
567
568         $cacheKey = common_cache_key($keyPart);
569
570         return $c->delete($cacheKey);
571     }
572
573     function fixupTimestamps()
574     {
575         // Fake up timestamp columns
576         $columns = $this->table();
577         foreach ($columns as $name => $type) {
578             if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
579                 $this->$name = common_sql_now();
580             }
581         }
582     }
583
584     function debugDump()
585     {
586         common_debug("debugDump: " . common_log_objstring($this));
587     }
588
589     function raiseError($message, $type = null, $behaviour = null)
590     {
591         $id = get_class($this);
592         if ($this->id) {
593             $id .= ':' . $this->id;
594         }
595         if ($message instanceof PEAR_Error) {
596             $message = $message->getMessage();
597         }
598         throw new ServerException("[$id] DB_DataObject error [$type]: $message");
599     }
600
601     static function cacheGet($keyPart)
602     {
603         $c = self::memcache();
604
605         if (empty($c)) {
606             return false;
607         }
608
609         $cacheKey = common_cache_key($keyPart);
610
611         return $c->get($cacheKey);
612     }
613
614     static function cacheSet($keyPart, $value)
615     {
616         $c = self::memcache();
617
618         if (empty($c)) {
619             return false;
620         }
621
622         $cacheKey = common_cache_key($keyPart);
623
624         return $c->set($cacheKey, $value);
625     }
626 }
627