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