]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
Merge branch '1.0.x' of gitorious.org:statusnet/mainline into 1.0.x
[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      * Get multiple items from the database by key
69      * 
70      * @param string  $cls       Class to fetch
71      * @param string  $keyCol    name of column for key
72      * @param array   $keyVals   key values to fetch
73      * @param boolean $skipNulls return only non-null results?
74      * 
75      * @return array Array of objects, in order
76      */
77     function multiGet($cls, $keyCol, $keyVals, $skipNulls=true)
78     {
79         $result = self::pivotGet($cls, $keyCol, $keyVals);
80         
81         $values = array_values($result);
82         
83         if ($skipNulls) {
84                 $tmp = array();
85                 foreach ($values as $value) {
86                         if (!empty($value)) {
87                                 $tmp[] = $value;
88                         }
89                 }
90                 $values = $tmp;
91         }
92         
93         return new ArrayWrapper($values);
94     }
95     
96     /**
97      * Get multiple items from the database by key
98      * 
99      * @param string  $cls       Class to fetch
100      * @param string  $keyCol    name of column for key
101      * @param array   $keyVals   key values to fetch
102      * @param boolean $otherCols Other columns to hold fixed
103      * 
104      * @return array Array mapping $keyVals to objects, or null if not found
105      */
106     static function pivotGet($cls, $keyCol, $keyVals, $otherCols = array())
107     {
108         $result = array_fill_keys($keyVals, null);
109         
110         $toFetch = array();
111         
112         foreach ($keyVals as $keyVal) {
113                 
114                 $kv = array_merge($otherCols, array($keyCol => $keyVal));
115                 
116                 $i = self::multicache($cls, $kv);
117                 
118                 if ($i !== false) {
119                         $result[$keyVal] = $i;
120                 } else if (!empty($keyVal)) {
121                         $toFetch[] = $keyVal;
122                 }
123         }
124         
125         if (count($toFetch) > 0) {
126             $i = DB_DataObject::factory($cls);
127             if (empty($i)) {
128                 throw new Exception(_('Cannot instantiate class ' . $cls));
129             }
130             foreach ($otherCols as $otherKeyCol => $otherKeyVal) {
131                 $i->$otherKeyCol = $otherKeyVal;
132             }
133                 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
134                 if ($i->find()) {
135                         while ($i->fetch()) {
136                                 $copy = clone($i);
137                                 $copy->encache();
138                                 $result[$i->$keyCol] = $copy;
139                         }
140                 }
141                 
142                 // Save state of DB misses
143                 
144                 foreach ($toFetch as $keyVal) {
145                         if (empty($result[$keyVal])) {
146                                 $kv = array_merge($otherCols, array($keyCol => $keyVal));
147                         // save the fact that no such row exists
148                         $c = self::memcache();
149                         if (!empty($c)) {
150                         $ck = self::multicacheKey($cls, $kv);
151                         $c->set($ck, null);
152                         }       
153                         }
154                 }
155         }
156         
157         return $result;
158     }
159     
160     function listGet($cls, $keyCol, $keyVals)
161     {
162         $result = array_fill_keys($keyVals, array());
163         
164         $toFetch = array();
165         
166         foreach ($keyVals as $keyVal) {
167             $l = self::cacheGet(sprintf("%s:list:%s:%s", $cls, $keyCol, $keyVal));
168             if ($l !== false) {
169                 $result[$keyVal] = $l;
170             } else {
171                 $toFetch[] = $keyVal;
172             }
173         }
174         
175         if (count($toFetch) > 0) {
176                 $i = DB_DataObject::factory($cls);
177                 if (empty($i)) {
178                         throw new Exception(_('Cannot instantiate class ' . $cls));
179                 }
180                         $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
181                         if ($i->find()) {
182                                 while ($i->fetch()) {
183                                         $copy = clone($i);
184                                         $copy->encache();
185                                         $result[$i->$keyCol][] = $copy;
186                                 }
187                         }        
188                 foreach ($toFetch as $keyVal)
189                 {
190                         self::cacheSet(sprintf("%s:list:%s:%s", $cls, $keyCol, $keyVal),
191                                                    $result[$keyVal]);   
192                 }      
193         }
194         
195         return $result;        
196     }
197
198         function columnType($columnName)
199         {
200                 $keys = $this->table();
201                 if (!array_key_exists($columnName, $keys)) {
202                         throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
203                 }
204                 
205                 $def = $keys[$columnName];
206                 
207                 if ($def & DB_DATAOBJECT_INT) {
208                         return 'integer';
209                 } else {
210                         return 'string';
211                 }
212         }
213         
214     /**
215      * @fixme Should this return false on lookup fail to match staticGet?
216      */
217     function pkeyGet($cls, $kv)
218     {
219         $i = Memcached_DataObject::multicache($cls, $kv);
220         if ($i !== false) { // false == cache miss
221             return $i;
222         } else {
223             $i = DB_DataObject::factory($cls);
224             if (empty($i) || PEAR::isError($i)) {
225                 return false;
226             }
227             foreach ($kv as $k => $v) {
228                 if (is_null($v)) {
229                         // XXX: possible SQL injection...? Don't 
230                         // pass keys from the browser, eh.
231                         $i->whereAdd("$k is null");
232                 } else {
233                         $i->$k = $v;
234                 }
235             }
236             if ($i->find(true)) {
237                 $i->encache();
238             } else {
239                 $i = null;
240                 $c = self::memcache();
241                 if (!empty($c)) {
242                     $ck = self::multicacheKey($cls, $kv);
243                     $c->set($ck, null);
244                 }
245             }
246             return $i;
247         }
248     }
249
250     function insert()
251     {
252         $result = parent::insert();
253         if ($result) {
254             $this->fixupTimestamps();
255             $this->encache(); // in case of cached negative lookups
256         }
257         return $result;
258     }
259
260     function update($orig=null)
261     {
262         if (is_object($orig) && $orig instanceof Memcached_DataObject) {
263             $orig->decache(); # might be different keys
264         }
265         $result = parent::update($orig);
266         if ($result) {
267             $this->fixupTimestamps();
268             $this->encache();
269         }
270         return $result;
271     }
272
273     function delete()
274     {
275         $this->decache(); # while we still have the values!
276         return parent::delete();
277     }
278
279     static function memcache() {
280         return Cache::instance();
281     }
282
283     static function cacheKey($cls, $k, $v) {
284         if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
285             $e = new Exception();
286             common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
287                 str_replace("\n", " ", $e->getTraceAsString()));
288         }
289         $vstr = self::valueString($v);
290         return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
291     }
292
293     static function getcached($cls, $k, $v) {
294         $c = Memcached_DataObject::memcache();
295         if (!$c) {
296             return false;
297         } else {
298             $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
299             if (0 == strcasecmp($cls, 'User')) {
300                 // Special case for User
301                 if (is_object($obj) && is_object($obj->id)) {
302                     common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
303                     $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
304                     return false;
305                 }
306             }
307             return $obj;
308         }
309     }
310
311     function keyTypes()
312     {
313         // ini-based classes return number-indexed arrays. handbuilt
314         // classes return column => keytype. Make this uniform.
315
316         $keys = $this->keys();
317
318         $keyskeys = array_keys($keys);
319
320         if (is_string($keyskeys[0])) {
321             return $keys;
322         }
323
324         global $_DB_DATAOBJECT;
325         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
326             $this->databaseStructure();
327
328         }
329         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
330     }
331
332     function encache()
333     {
334         $c = $this->memcache();
335
336         if (!$c) {
337             return false;
338         } else if ($this->tableName() == 'user' && is_object($this->id)) {
339             // Special case for User bug
340             $e = new Exception();
341             common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
342                        str_replace("\n", " ", $e->getTraceAsString()));
343             return false;
344         } else {
345             $keys = $this->_allCacheKeys();
346
347             foreach ($keys as $key) {
348                 $c->set($key, $this);
349             }
350         }
351     }
352
353     function decache()
354     {
355         $c = $this->memcache();
356
357         if (!$c) {
358             return false;
359         }
360
361         $keys = $this->_allCacheKeys();
362
363         foreach ($keys as $key) {
364             $c->delete($key, $this);
365         }
366     }
367
368     function _allCacheKeys()
369     {
370         $ckeys = array();
371
372         $types = $this->keyTypes();
373         ksort($types);
374
375         $pkey = array();
376         $pval = array();
377
378         foreach ($types as $key => $type) {
379
380             assert(!empty($key));
381
382             if ($type == 'U') {
383                 if (empty($this->$key)) {
384                     continue;
385                 }
386                 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
387             } else if ($type == 'K' || $type == 'N') {
388                 $pkey[] = $key;
389                 $pval[] = self::valueString($this->$key);
390             } else {
391                 // Low level exception. No need for i18n as discussed with Brion.
392                 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
393             }
394         }
395
396         assert(count($pkey) > 0);
397
398         // XXX: should work for both compound and scalar pkeys
399         $pvals = implode(',', $pval);
400         $pkeys = implode(',', $pkey);
401
402         $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
403
404         return $ckeys;
405     }
406
407     function multicache($cls, $kv)
408     {
409         ksort($kv);
410         $c = self::memcache();
411         if (!$c) {
412             return false;
413         } else {
414             return $c->get(self::multicacheKey($cls, $kv));
415         }
416     }
417
418     static function multicacheKey($cls, $kv)
419     {
420         ksort($kv);
421         $pkeys = implode(',', array_keys($kv));
422         $pvals = implode(',', array_values($kv));
423         return self::cacheKey($cls, $pkeys, $pvals);
424     }
425
426     function getSearchEngine($table)
427     {
428         require_once INSTALLDIR.'/lib/search_engines.php';
429
430         if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
431             if ('mysql' === common_config('db', 'type')) {
432                 $type = common_config('search', 'type');
433                 if ($type == 'like') {
434                     $search_engine = new MySQLLikeSearch($this, $table);
435                 } else if ($type == 'fulltext') {
436                     $search_engine = new MySQLSearch($this, $table);
437                 } else {
438                     // Low level exception. No need for i18n as discussed with Brion.
439                     throw new ServerException('Unknown search type: ' . $type);
440                 }
441             } else {
442                 $search_engine = new PGSearch($this, $table);
443             }
444         }
445
446         return $search_engine;
447     }
448
449     static function cachedQuery($cls, $qry, $expiry=3600)
450     {
451         $c = Memcached_DataObject::memcache();
452         if (!$c) {
453             $inst = new $cls();
454             $inst->query($qry);
455             return $inst;
456         }
457         $key_part = Cache::keyize($cls).':'.md5($qry);
458         $ckey = Cache::key($key_part);
459         $stored = $c->get($ckey);
460
461         if ($stored !== false) {
462             return new ArrayWrapper($stored);
463         }
464
465         $inst = new $cls();
466         $inst->query($qry);
467         $cached = array();
468         while ($inst->fetch()) {
469             $cached[] = clone($inst);
470         }
471         $inst->free();
472         $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
473         return new ArrayWrapper($cached);
474     }
475
476     /**
477      * sends query to database - this is the private one that must work
478      *   - internal functions use this rather than $this->query()
479      *
480      * Overridden to do logging.
481      *
482      * @param  string  $string
483      * @access private
484      * @return mixed none or PEAR_Error
485      */
486     function _query($string)
487     {
488         if (common_config('db', 'annotate_queries')) {
489             $string = $this->annotateQuery($string);
490         }
491
492         $start = microtime(true);
493         $fail = false;
494         $result = null;
495         if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
496             common_perf_counter('query', $string);
497             try {
498                 $result = parent::_query($string);
499             } catch (Exception $e) {
500                 $fail = $e;
501             }
502             Event::handle('EndDBQuery', array($this, $string, &$result));
503         }
504         $delta = microtime(true) - $start;
505
506         $limit = common_config('db', 'log_slow_queries');
507         if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
508             $clean = $this->sanitizeQuery($string);
509             if ($fail) {
510                 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
511             } else {
512                 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
513             }
514             common_log(LOG_DEBUG, $msg);
515         }
516
517         if ($fail) {
518             throw $fail;
519         }
520         return $result;
521     }
522
523     /**
524      * Find the first caller in the stack trace that's not a
525      * low-level database function and add a comment to the
526      * query string. This should then be visible in process lists
527      * and slow query logs, to help identify problem areas.
528      *
529      * Also marks whether this was a web GET/POST or which daemon
530      * was running it.
531      *
532      * @param string $string SQL query string
533      * @return string SQL query string, with a comment in it
534      */
535     function annotateQuery($string)
536     {
537         $ignore = array('annotateQuery',
538                         '_query',
539                         'query',
540                         'get',
541                         'insert',
542                         'delete',
543                         'update',
544                         'find');
545         $ignoreStatic = array('staticGet',
546                               'pkeyGet',
547                               'cachedQuery');
548         $here = get_class($this); // if we get confused
549         $bt = debug_backtrace();
550
551         // Find the first caller that's not us?
552         foreach ($bt as $frame) {
553             $func = $frame['function'];
554             if (isset($frame['type']) && $frame['type'] == '::') {
555                 if (in_array($func, $ignoreStatic)) {
556                     continue;
557                 }
558                 $here = $frame['class'] . '::' . $func;
559                 break;
560             } else if (isset($frame['type']) && $frame['type'] == '->') {
561                 if ($frame['object'] === $this && in_array($func, $ignore)) {
562                     continue;
563                 }
564                 if (in_array($func, $ignoreStatic)) {
565                     continue; // @fixme this shouldn't be needed?
566                 }
567                 $here = get_class($frame['object']) . '->' . $func;
568                 break;
569             }
570             $here = $func;
571             break;
572         }
573
574         if (php_sapi_name() == 'cli') {
575             $context = basename($_SERVER['PHP_SELF']);
576         } else {
577             $context = $_SERVER['REQUEST_METHOD'];
578         }
579
580         // Slip the comment in after the first command,
581         // or DB_DataObject gets confused about handling inserts and such.
582         $parts = explode(' ', $string, 2);
583         $parts[0] .= " /* $context $here */";
584         return implode(' ', $parts);
585     }
586
587     // Sanitize a query for logging
588     // @fixme don't trim spaces in string literals
589     function sanitizeQuery($string)
590     {
591         $string = preg_replace('/\s+/', ' ', $string);
592         $string = trim($string);
593         return $string;
594     }
595
596     // We overload so that 'SET NAMES "utf8"' is called for
597     // each connection
598
599     function _connect()
600     {
601         global $_DB_DATAOBJECT;
602
603         $sum = $this->_getDbDsnMD5();
604
605         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
606             !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
607             $exists = true;
608         } else {
609             $exists = false;
610        }
611
612         // @fixme horrible evil hack!
613         //
614         // In multisite configuration we don't want to keep around a separate
615         // connection for every database; we could end up with thousands of
616         // connections open per thread. In an ideal world we might keep
617         // a connection per server and select different databases, but that'd
618         // be reliant on having the same db username/pass as well.
619         //
620         // MySQL connections are cheap enough we're going to try just
621         // closing out the old connection and reopening when we encounter
622         // a new DSN.
623         //
624         // WARNING WARNING if we end up actually using multiple DBs at a time
625         // we'll need some fancier logic here.
626         if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
627             foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
628                 if (!empty($conn)) {
629                     $conn->disconnect();
630                 }
631                 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
632             }
633         }
634
635         $result = parent::_connect();
636
637         if ($result && !$exists) {
638             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
639             if (common_config('db', 'type') == 'mysql' &&
640                 common_config('db', 'utf8')) {
641                 $conn = $DB->connection;
642                 if (!empty($conn)) {
643                     if ($DB instanceof DB_mysqli) {
644                         mysqli_set_charset($conn, 'utf8');
645                     } else if ($DB instanceof DB_mysql) {
646                         mysql_set_charset('utf8', $conn);
647                     }
648                 }
649             }
650             // Needed to make timestamp values usefully comparable.
651             if (common_config('db', 'type') == 'mysql') {
652                 parent::_query("set time_zone='+0:00'");
653             }
654         }
655
656         return $result;
657     }
658
659     // XXX: largely cadged from DB_DataObject
660
661     function _getDbDsnMD5()
662     {
663         if ($this->_database_dsn_md5) {
664             return $this->_database_dsn_md5;
665         }
666
667         $dsn = $this->_getDbDsn();
668
669         if (is_string($dsn)) {
670             $sum = md5($dsn);
671         } else {
672             /// support array based dsn's
673             $sum = md5(serialize($dsn));
674         }
675
676         return $sum;
677     }
678
679     function _getDbDsn()
680     {
681         global $_DB_DATAOBJECT;
682
683         if (empty($_DB_DATAOBJECT['CONFIG'])) {
684             DB_DataObject::_loadConfig();
685         }
686
687         $options = &$_DB_DATAOBJECT['CONFIG'];
688
689         // if the databse dsn dis defined in the object..
690
691         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
692
693         if (!$dsn) {
694
695             if (!$this->_database) {
696                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
697             }
698
699             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
700                 $dsn = $options["database_{$this->_database}"];
701             } else if (!empty($options['database'])) {
702                 $dsn = $options['database'];
703             }
704         }
705
706         if (!$dsn) {
707             // TRANS: Exception thrown when database name or Data Source Name could not be found.
708             throw new Exception(_("No database name or DSN found anywhere."));
709         }
710
711         return $dsn;
712     }
713
714     static function blow()
715     {
716         $c = self::memcache();
717
718         if (empty($c)) {
719             return false;
720         }
721
722         $args = func_get_args();
723
724         $format = array_shift($args);
725
726         $keyPart = vsprintf($format, $args);
727
728         $cacheKey = Cache::key($keyPart);
729
730         return $c->delete($cacheKey);
731     }
732
733     function fixupTimestamps()
734     {
735         // Fake up timestamp columns
736         $columns = $this->table();
737         foreach ($columns as $name => $type) {
738             if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
739                 $this->$name = common_sql_now();
740             }
741         }
742     }
743
744     function debugDump()
745     {
746         common_debug("debugDump: " . common_log_objstring($this));
747     }
748
749     function raiseError($message, $type = null, $behaviour = null)
750     {
751         $id = get_class($this);
752         if (!empty($this->id)) {
753             $id .= ':' . $this->id;
754         }
755         if ($message instanceof PEAR_Error) {
756             $message = $message->getMessage();
757         }
758         // Low level exception. No need for i18n as discussed with Brion.
759         throw new ServerException("[$id] DB_DataObject error [$type]: $message");
760     }
761
762     static function cacheGet($keyPart)
763     {
764         $c = self::memcache();
765
766         if (empty($c)) {
767             return false;
768         }
769
770         $cacheKey = Cache::key($keyPart);
771
772         return $c->get($cacheKey);
773     }
774
775     static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
776     {
777         $c = self::memcache();
778
779         if (empty($c)) {
780             return false;
781         }
782
783         $cacheKey = Cache::key($keyPart);
784
785         return $c->set($cacheKey, $value, $flag, $expiry);
786     }
787
788     static function valueString($v)
789     {
790         $vstr = null;
791         if (is_object($v) && $v instanceof DB_DataObject_Cast) {
792             switch ($v->type) {
793             case 'date':
794                 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
795                 break;
796             case 'blob':
797             case 'string':
798             case 'sql':
799             case 'datetime':
800             case 'time':
801                 // Low level exception. No need for i18n as discussed with Brion.
802                 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
803                 break;
804             default:
805                 // Low level exception. No need for i18n as discussed with Brion.
806                 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
807                 break;
808             }
809         } else {
810             $vstr = strval($v);
811         }
812         return $vstr;
813     }
814 }