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