]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
Merge branch '1.0.x' of git://gitorious.org/statusnet/mainline
[quix0rs-gnu-social.git] / classes / Memcached_DataObject.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 class Memcached_DataObject extends Safe_DataObject
23 {
24     /**
25      * Wrapper for DB_DataObject's static lookup using memcached
26      * as backing instead of an in-process cache array.
27      *
28      * @param string $cls classname of object type to load
29      * @param mixed $k key field name, or value for primary key
30      * @param mixed $v key field value, or leave out for primary key lookup
31      * @return mixed Memcached_DataObject subtype or false
32      */
33     function &staticGet($cls, $k, $v=null)
34     {
35         if (is_null($v)) {
36             $v = $k;
37             # XXX: HACK!
38             $i = new $cls;
39             $keys = $i->keys();
40             $k = $keys[0];
41             unset($i);
42         }
43         $i = Memcached_DataObject::getcached($cls, $k, $v);
44         if ($i === false) { // false == cache miss
45             $i = DB_DataObject::factory($cls);
46             if (empty($i)) {
47                 $i = false;
48                 return $i;
49             }
50             $result = $i->get($k, $v);
51             if ($result) {
52                 // Hit!
53                 $i->encache();
54             } else {
55                 // save the fact that no such row exists
56                 $c = self::memcache();
57                 if (!empty($c)) {
58                     $ck = self::cachekey($cls, $k, $v);
59                     $c->set($ck, null);
60                 }
61                 $i = false;
62             }
63         }
64         return $i;
65     }
66
67     /**
68      * @fixme Should this return false on lookup fail to match staticGet?
69      */
70     function pkeyGet($cls, $kv)
71     {
72         $i = Memcached_DataObject::multicache($cls, $kv);
73         if ($i !== false) { // false == cache miss
74             return $i;
75         } else {
76             $i = DB_DataObject::factory($cls);
77             if (empty($i)) {
78                 return false;
79             }
80             foreach ($kv as $k => $v) {
81                 $i->$k = $v;
82             }
83             if ($i->find(true)) {
84                 $i->encache();
85             } else {
86                 $i = null;
87                 $c = self::memcache();
88                 if (!empty($c)) {
89                     $ck = self::multicacheKey($cls, $kv);
90                     $c->set($ck, null);
91                 }
92             }
93             return $i;
94         }
95     }
96
97     function insert()
98     {
99         $result = parent::insert();
100         if ($result) {
101             $this->fixupTimestamps();
102             $this->encache(); // in case of cached negative lookups
103         }
104         return $result;
105     }
106
107     function update($orig=null)
108     {
109         if (is_object($orig) && $orig instanceof Memcached_DataObject) {
110             $orig->decache(); # might be different keys
111         }
112         $result = parent::update($orig);
113         if ($result) {
114             $this->fixupTimestamps();
115             $this->encache();
116         }
117         return $result;
118     }
119
120     function delete()
121     {
122         $this->decache(); # while we still have the values!
123         return parent::delete();
124     }
125
126     static function memcache() {
127         return Cache::instance();
128     }
129
130     static function cacheKey($cls, $k, $v) {
131         if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
132             $e = new Exception();
133             common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
134                 str_replace("\n", " ", $e->getTraceAsString()));
135         }
136         $vstr = self::valueString($v);
137         return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
138     }
139
140     static function getcached($cls, $k, $v) {
141         $c = Memcached_DataObject::memcache();
142         if (!$c) {
143             return false;
144         } else {
145             $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
146             if (0 == strcasecmp($cls, 'User')) {
147                 // Special case for User
148                 if (is_object($obj) && is_object($obj->id)) {
149                     common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
150                     $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
151                     return false;
152                 }
153             }
154             return $obj;
155         }
156     }
157
158     function keyTypes()
159     {
160         // ini-based classes return number-indexed arrays. handbuilt
161         // classes return column => keytype. Make this uniform.
162
163         $keys = $this->keys();
164
165         $keyskeys = array_keys($keys);
166
167         if (is_string($keyskeys[0])) {
168             return $keys;
169         }
170
171         global $_DB_DATAOBJECT;
172         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
173             $this->databaseStructure();
174
175         }
176         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
177     }
178
179     function encache()
180     {
181         $c = $this->memcache();
182
183         if (!$c) {
184             return false;
185         } else if ($this->tableName() == 'user' && is_object($this->id)) {
186             // Special case for User bug
187             $e = new Exception();
188             common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
189                        str_replace("\n", " ", $e->getTraceAsString()));
190             return false;
191         } else {
192             $keys = $this->_allCacheKeys();
193
194             foreach ($keys as $key) {
195                 $c->set($key, $this);
196             }
197         }
198     }
199
200     function decache()
201     {
202         $c = $this->memcache();
203
204         if (!$c) {
205             return false;
206         }
207
208         $keys = $this->_allCacheKeys();
209
210         foreach ($keys as $key) {
211             $c->delete($key, $this);
212         }
213     }
214
215     function _allCacheKeys()
216     {
217         $ckeys = array();
218
219         $types = $this->keyTypes();
220         ksort($types);
221
222         $pkey = array();
223         $pval = array();
224
225         foreach ($types as $key => $type) {
226
227             assert(!empty($key));
228
229             if ($type == 'U') {
230                 if (empty($this->$key)) {
231                     continue;
232                 }
233                 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
234             } else if ($type == 'K' || $type == 'N') {
235                 $pkey[] = $key;
236                 $pval[] = self::valueString($this->$key);
237             } else {
238                 // Low level exception. No need for i18n as discussed with Brion.
239                 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
240             }
241         }
242
243         assert(count($pkey) > 0);
244
245         // XXX: should work for both compound and scalar pkeys
246         $pvals = implode(',', $pval);
247         $pkeys = implode(',', $pkey);
248
249         $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
250
251         return $ckeys;
252     }
253
254     function multicache($cls, $kv)
255     {
256         ksort($kv);
257         $c = self::memcache();
258         if (!$c) {
259             return false;
260         } else {
261             return $c->get(self::multicacheKey($cls, $kv));
262         }
263     }
264
265     static function multicacheKey($cls, $kv)
266     {
267         ksort($kv);
268         $pkeys = implode(',', array_keys($kv));
269         $pvals = implode(',', array_values($kv));
270         return self::cacheKey($cls, $pkeys, $pvals);
271     }
272
273     function getSearchEngine($table)
274     {
275         require_once INSTALLDIR.'/lib/search_engines.php';
276         static $search_engine;
277         if (!isset($search_engine)) {
278             if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
279                 if ('mysql' === common_config('db', 'type')) {
280                     $type = common_config('search', 'type');
281                     if ($type == 'like') {
282                         $search_engine = new MySQLLikeSearch($this, $table);
283                     } else if ($type == 'fulltext') {
284                         $search_engine = new MySQLSearch($this, $table);
285                     } else {
286                         // Low level exception. No need for i18n as discussed with Brion.
287                         throw new ServerException('Unknown search type: ' . $type);
288                     }
289                 } else {
290                     $search_engine = new PGSearch($this, $table);
291                 }
292             }
293         }
294         return $search_engine;
295     }
296
297     static function cachedQuery($cls, $qry, $expiry=3600)
298     {
299         $c = Memcached_DataObject::memcache();
300         if (!$c) {
301             $inst = new $cls();
302             $inst->query($qry);
303             return $inst;
304         }
305         $key_part = Cache::keyize($cls).':'.md5($qry);
306         $ckey = Cache::key($key_part);
307         $stored = $c->get($ckey);
308
309         if ($stored !== false) {
310             return new ArrayWrapper($stored);
311         }
312
313         $inst = new $cls();
314         $inst->query($qry);
315         $cached = array();
316         while ($inst->fetch()) {
317             $cached[] = clone($inst);
318         }
319         $inst->free();
320         $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
321         return new ArrayWrapper($cached);
322     }
323
324     /**
325      * sends query to database - this is the private one that must work
326      *   - internal functions use this rather than $this->query()
327      *
328      * Overridden to do logging.
329      *
330      * @param  string  $string
331      * @access private
332      * @return mixed none or PEAR_Error
333      */
334     function _query($string)
335     {
336         if (common_config('db', 'annotate_queries')) {
337             $string = $this->annotateQuery($string);
338         }
339
340         $start = microtime(true);
341         $fail = false;
342         $result = null;
343         if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
344             try {
345                 $result = parent::_query($string);
346             } catch (Exception $e) {
347                 $fail = $e;
348             }
349             Event::handle('EndDBQuery', array($this, $string, &$result));
350         }
351         $delta = microtime(true) - $start;
352
353         $limit = common_config('db', 'log_slow_queries');
354         if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
355             $clean = $this->sanitizeQuery($string);
356             if ($fail) {
357                 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
358             } else {
359                 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
360             }
361             common_log(LOG_DEBUG, $msg);
362         }
363
364         if ($fail) {
365             throw $fail;
366         }
367         return $result;
368     }
369
370     /**
371      * Find the first caller in the stack trace that's not a
372      * low-level database function and add a comment to the
373      * query string. This should then be visible in process lists
374      * and slow query logs, to help identify problem areas.
375      *
376      * Also marks whether this was a web GET/POST or which daemon
377      * was running it.
378      *
379      * @param string $string SQL query string
380      * @return string SQL query string, with a comment in it
381      */
382     function annotateQuery($string)
383     {
384         $ignore = array('annotateQuery',
385                         '_query',
386                         'query',
387                         'get',
388                         'insert',
389                         'delete',
390                         'update',
391                         'find');
392         $ignoreStatic = array('staticGet',
393                               'pkeyGet',
394                               'cachedQuery');
395         $here = get_class($this); // if we get confused
396         $bt = debug_backtrace();
397
398         // Find the first caller that's not us?
399         foreach ($bt as $frame) {
400             $func = $frame['function'];
401             if (isset($frame['type']) && $frame['type'] == '::') {
402                 if (in_array($func, $ignoreStatic)) {
403                     continue;
404                 }
405                 $here = $frame['class'] . '::' . $func;
406                 break;
407             } else if (isset($frame['type']) && $frame['type'] == '->') {
408                 if ($frame['object'] === $this && in_array($func, $ignore)) {
409                     continue;
410                 }
411                 if (in_array($func, $ignoreStatic)) {
412                     continue; // @fixme this shouldn't be needed?
413                 }
414                 $here = get_class($frame['object']) . '->' . $func;
415                 break;
416             }
417             $here = $func;
418             break;
419         }
420
421         if (php_sapi_name() == 'cli') {
422             $context = basename($_SERVER['PHP_SELF']);
423         } else {
424             $context = $_SERVER['REQUEST_METHOD'];
425         }
426
427         // Slip the comment in after the first command,
428         // or DB_DataObject gets confused about handling inserts and such.
429         $parts = explode(' ', $string, 2);
430         $parts[0] .= " /* $context $here */";
431         return implode(' ', $parts);
432     }
433
434     // Sanitize a query for logging
435     // @fixme don't trim spaces in string literals
436     function sanitizeQuery($string)
437     {
438         $string = preg_replace('/\s+/', ' ', $string);
439         $string = trim($string);
440         return $string;
441     }
442
443     // We overload so that 'SET NAMES "utf8"' is called for
444     // each connection
445
446     function _connect()
447     {
448         global $_DB_DATAOBJECT;
449
450         $sum = $this->_getDbDsnMD5();
451
452         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
453             !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
454             $exists = true;
455         } else {
456             $exists = false;
457        }
458
459         // @fixme horrible evil hack!
460         //
461         // In multisite configuration we don't want to keep around a separate
462         // connection for every database; we could end up with thousands of
463         // connections open per thread. In an ideal world we might keep
464         // a connection per server and select different databases, but that'd
465         // be reliant on having the same db username/pass as well.
466         //
467         // MySQL connections are cheap enough we're going to try just
468         // closing out the old connection and reopening when we encounter
469         // a new DSN.
470         //
471         // WARNING WARNING if we end up actually using multiple DBs at a time
472         // we'll need some fancier logic here.
473         if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
474             foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
475                 if (!empty($conn)) {
476                     $conn->disconnect();
477                 }
478                 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
479             }
480         }
481
482         $result = parent::_connect();
483
484         if ($result && !$exists) {
485             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
486             if (common_config('db', 'type') == 'mysql' &&
487                 common_config('db', 'utf8')) {
488                 $conn = $DB->connection;
489                 if (!empty($conn)) {
490                     if ($DB instanceof DB_mysqli) {
491                         mysqli_set_charset($conn, 'utf8');
492                     } else if ($DB instanceof DB_mysql) {
493                         mysql_set_charset('utf8', $conn);
494                     }
495                 }
496             }
497         }
498
499         return $result;
500     }
501
502     // XXX: largely cadged from DB_DataObject
503
504     function _getDbDsnMD5()
505     {
506         if ($this->_database_dsn_md5) {
507             return $this->_database_dsn_md5;
508         }
509
510         $dsn = $this->_getDbDsn();
511
512         if (is_string($dsn)) {
513             $sum = md5($dsn);
514         } else {
515             /// support array based dsn's
516             $sum = md5(serialize($dsn));
517         }
518
519         return $sum;
520     }
521
522     function _getDbDsn()
523     {
524         global $_DB_DATAOBJECT;
525
526         if (empty($_DB_DATAOBJECT['CONFIG'])) {
527             DB_DataObject::_loadConfig();
528         }
529
530         $options = &$_DB_DATAOBJECT['CONFIG'];
531
532         // if the databse dsn dis defined in the object..
533
534         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
535
536         if (!$dsn) {
537
538             if (!$this->_database) {
539                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
540             }
541
542             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
543                 $dsn = $options["database_{$this->_database}"];
544             } else if (!empty($options['database'])) {
545                 $dsn = $options['database'];
546             }
547         }
548
549         if (!$dsn) {
550             // TRANS: Exception thrown when database name or Data Source Name could not be found.
551             throw new Exception(_("No database name or DSN found anywhere."));
552         }
553
554         return $dsn;
555     }
556
557     static function blow()
558     {
559         $c = self::memcache();
560
561         if (empty($c)) {
562             return false;
563         }
564
565         $args = func_get_args();
566
567         $format = array_shift($args);
568
569         $keyPart = vsprintf($format, $args);
570
571         $cacheKey = Cache::key($keyPart);
572
573         return $c->delete($cacheKey);
574     }
575
576     function fixupTimestamps()
577     {
578         // Fake up timestamp columns
579         $columns = $this->table();
580         foreach ($columns as $name => $type) {
581             if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
582                 $this->$name = common_sql_now();
583             }
584         }
585     }
586
587     function debugDump()
588     {
589         common_debug("debugDump: " . common_log_objstring($this));
590     }
591
592     function raiseError($message, $type = null, $behaviour = null)
593     {
594         $id = get_class($this);
595         if (!empty($this->id)) {
596             $id .= ':' . $this->id;
597         }
598         if ($message instanceof PEAR_Error) {
599             $message = $message->getMessage();
600         }
601         // Low level exception. No need for i18n as discussed with Brion.
602         throw new ServerException("[$id] DB_DataObject error [$type]: $message");
603     }
604
605     static function cacheGet($keyPart)
606     {
607         $c = self::memcache();
608
609         if (empty($c)) {
610             return false;
611         }
612
613         $cacheKey = Cache::key($keyPart);
614
615         return $c->get($cacheKey);
616     }
617
618     static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
619     {
620         $c = self::memcache();
621
622         if (empty($c)) {
623             return false;
624         }
625
626         $cacheKey = Cache::key($keyPart);
627
628         return $c->set($cacheKey, $value, $flag, $expiry);
629     }
630
631     static function valueString($v)
632     {
633         $vstr = null;
634         if (is_object($v) && $v instanceof DB_DataObject_Cast) {
635             switch ($v->type) {
636             case 'date':
637                 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
638                 break;
639             case 'blob':
640             case 'string':
641             case 'sql':
642             case 'datetime':
643             case 'time':
644                 // Low level exception. No need for i18n as discussed with Brion.
645                 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
646                 break;
647             default:
648                 // Low level exception. No need for i18n as discussed with Brion.
649                 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
650                 break;
651             }
652         } else {
653             $vstr = strval($v);
654         }
655         return $vstr;
656     }
657 }