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