]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
Merge branch 'master' 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 DB_DataObject
23 {
24     /**
25      * Destructor to free global memory resources associated with
26      * this data object when it's unset or goes out of scope.
27      * DB_DataObject doesn't do this yet by itself.
28      */
29
30     function __destruct()
31     {
32         $this->free();
33         if (method_exists('DB_DataObject', '__destruct')) {
34             parent::__destruct();
35         }
36     }
37
38     /**
39      * Magic function called at serialize() time.
40      *
41      * We use this to drop a couple process-specific references
42      * from DB_DataObject which can cause trouble in future
43      * processes.
44      *
45      * @return array of variable names to include in serialization.
46      */
47     function __sleep()
48     {
49         $vars = array_keys(get_object_vars($this));
50         $skip = array('_DB_resultid', '_link_loaded');
51         return array_diff($vars, $skip);
52     }
53
54     /**
55      * Magic function called at unserialize() time.
56      *
57      * Clean out some process-specific variables which might
58      * be floating around from a previous process's cached
59      * objects.
60      *
61      * Old cached objects may still have them.
62      */
63     function __wakeup()
64     {
65         // Refers to global state info from a previous process.
66         // Clear this out so we don't accidentally break global
67         // state in *this* process.
68         $this->_DB_resultid = null;
69         // We don't have any local DBO refs, so clear these out.
70         $this->_link_loaded = false;
71     }
72
73     /**
74      * Wrapper for DB_DataObject's static lookup using memcached
75      * as backing instead of an in-process cache array.
76      *
77      * @param string $cls classname of object type to load
78      * @param mixed $k key field name, or value for primary key
79      * @param mixed $v key field value, or leave out for primary key lookup
80      * @return mixed Memcached_DataObject subtype or false
81      */
82     function &staticGet($cls, $k, $v=null)
83     {
84         if (is_null($v)) {
85             $v = $k;
86             # XXX: HACK!
87             $i = new $cls;
88             $keys = $i->keys();
89             $k = $keys[0];
90             unset($i);
91         }
92         $i = Memcached_DataObject::getcached($cls, $k, $v);
93         if ($i === false) { // false == cache miss
94             $i = DB_DataObject::factory($cls);
95             if (empty($i)) {
96                 $i = false;
97                 return $i;
98             }
99             $result = $i->get($k, $v);
100             if ($result) {
101                 // Hit!
102                 $i->encache();
103             } else {
104                 // save the fact that no such row exists
105                 $c = self::memcache();
106                 if (!empty($c)) {
107                     $ck = self::cachekey($cls, $k, $v);
108                     $c->set($ck, null);
109                 }
110                 $i = false;
111             }
112         }
113         return $i;
114     }
115
116     /**
117      * @fixme Should this return false on lookup fail to match staticGet?
118      */
119     function pkeyGet($cls, $kv)
120     {
121         $i = Memcached_DataObject::multicache($cls, $kv);
122         if ($i !== false) { // false == cache miss
123             return $i;
124         } else {
125             $i = DB_DataObject::factory($cls);
126             if (empty($i)) {
127                 return false;
128             }
129             foreach ($kv as $k => $v) {
130                 $i->$k = $v;
131             }
132             if ($i->find(true)) {
133                 $i->encache();
134             } else {
135                 $i = null;
136                 $c = self::memcache();
137                 if (!empty($c)) {
138                     $ck = self::multicacheKey($cls, $kv);
139                     $c->set($ck, null);
140                 }
141             }
142             return $i;
143         }
144     }
145
146     function insert()
147     {
148         $result = parent::insert();
149         if ($result) {
150             $this->fixupTimestamps();
151             $this->encache(); // in case of cached negative lookups
152         }
153         return $result;
154     }
155
156     function update($orig=null)
157     {
158         if (is_object($orig) && $orig instanceof Memcached_DataObject) {
159             $orig->decache(); # might be different keys
160         }
161         $result = parent::update($orig);
162         if ($result) {
163             $this->fixupTimestamps();
164             $this->encache();
165         }
166         return $result;
167     }
168
169     function delete()
170     {
171         $this->decache(); # while we still have the values!
172         return parent::delete();
173     }
174
175     static function memcache() {
176         return common_memcache();
177     }
178
179     static function cacheKey($cls, $k, $v) {
180         if (is_object($cls) || is_object($k) || is_object($v)) {
181             $e = new Exception();
182             common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
183                 str_replace("\n", " ", $e->getTraceAsString()));
184         }
185         return common_cache_key(strtolower($cls).':'.$k.':'.$v);
186     }
187
188     static function getcached($cls, $k, $v) {
189         $c = Memcached_DataObject::memcache();
190         if (!$c) {
191             return false;
192         } else {
193             $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
194             if (0 == strcasecmp($cls, 'User')) {
195                 // Special case for User
196                 if (is_object($obj) && is_object($obj->id)) {
197                     common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
198                     $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
199                     return false;
200                 }
201             }
202             return $obj;
203         }
204     }
205
206     function keyTypes()
207     {
208         // ini-based classes return number-indexed arrays. handbuilt
209         // classes return column => keytype. Make this uniform.
210
211         $keys = $this->keys();
212
213         $keyskeys = array_keys($keys);
214
215         if (is_string($keyskeys[0])) {
216             return $keys;
217         }
218
219         global $_DB_DATAOBJECT;
220         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
221             $this->databaseStructure();
222
223         }
224         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
225     }
226
227     function encache()
228     {
229         $c = $this->memcache();
230
231         if (!$c) {
232             return false;
233         } else if ($this->tableName() == 'user' && is_object($this->id)) {
234             // Special case for User bug
235             $e = new Exception();
236             common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
237                        str_replace("\n", " ", $e->getTraceAsString()));
238             return false;
239         } else {
240                 $keys = $this->_allCacheKeys();
241
242                 foreach ($keys as $key) {
243                     $c->set($key, $this);
244                 }
245         }
246     }
247
248     function decache()
249     {
250         $c = $this->memcache();
251
252         if (!$c) {
253             return false;
254         }
255
256         $keys = $this->_allCacheKeys();
257
258         foreach ($keys as $key) {
259             $c->delete($key, $this);
260         }
261     }
262
263     function _allCacheKeys()
264     {
265         $ckeys = array();
266
267         $types = $this->keyTypes();
268         ksort($types);
269
270         $pkey = array();
271         $pval = array();
272
273         foreach ($types as $key => $type) {
274
275             assert(!empty($key));
276
277             if ($type == 'U') {
278                 if (empty($this->$key)) {
279                     continue;
280                 }
281                 $ckeys[] = $this->cacheKey($this->tableName(), $key, $this->$key);
282             } else if ($type == 'K' || $type == 'N') {
283                 $pkey[] = $key;
284                 $pval[] = $this->$key;
285             } else {
286                 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
287             }
288         }
289
290         assert(count($pkey) > 0);
291
292         // XXX: should work for both compound and scalar pkeys
293         $pvals = implode(',', $pval);
294         $pkeys = implode(',', $pkey);
295
296         $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
297
298         return $ckeys;
299     }
300
301     function multicache($cls, $kv)
302     {
303         ksort($kv);
304         $c = self::memcache();
305         if (!$c) {
306             return false;
307         } else {
308             return $c->get(self::multicacheKey($cls, $kv));
309         }
310     }
311
312     static function multicacheKey($cls, $kv)
313     {
314         ksort($kv);
315         $pkeys = implode(',', array_keys($kv));
316         $pvals = implode(',', array_values($kv));
317         return self::cacheKey($cls, $pkeys, $pvals);
318     }
319
320     function getSearchEngine($table)
321     {
322         require_once INSTALLDIR.'/lib/search_engines.php';
323         static $search_engine;
324         if (!isset($search_engine)) {
325             if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
326                 if ('mysql' === common_config('db', 'type')) {
327                     $type = common_config('search', 'type');
328                     if ($type == 'like') {
329                         $search_engine = new MySQLLikeSearch($this, $table);
330                     } else if ($type == 'fulltext') {
331                         $search_engine = new MySQLSearch($this, $table);
332                     } else {
333                         throw new ServerException('Unknown search type: ' . $type);
334                     }
335                 } else {
336                     $search_engine = new PGSearch($this, $table);
337                 }
338             }
339         }
340         return $search_engine;
341     }
342
343     static function cachedQuery($cls, $qry, $expiry=3600)
344     {
345         $c = Memcached_DataObject::memcache();
346         if (!$c) {
347             $inst = new $cls();
348             $inst->query($qry);
349             return $inst;
350         }
351         $key_part = common_keyize($cls).':'.md5($qry);
352         $ckey = common_cache_key($key_part);
353         $stored = $c->get($ckey);
354
355         if ($stored !== false) {
356             return new ArrayWrapper($stored);
357         }
358
359         $inst = new $cls();
360         $inst->query($qry);
361         $cached = array();
362         while ($inst->fetch()) {
363             $cached[] = clone($inst);
364         }
365         $inst->free();
366         $c->set($ckey, $cached, MEMCACHE_COMPRESSED, $expiry);
367         return new ArrayWrapper($cached);
368     }
369
370     /**
371      * sends query to database - this is the private one that must work
372      *   - internal functions use this rather than $this->query()
373      *
374      * Overridden to do logging.
375      *
376      * @param  string  $string
377      * @access private
378      * @return mixed none or PEAR_Error
379      */
380     function _query($string)
381     {
382         $start = microtime(true);
383         $result = parent::_query($string);
384         $delta = microtime(true) - $start;
385
386         $limit = common_config('db', 'log_slow_queries');
387         if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
388             $clean = $this->sanitizeQuery($string);
389             common_log(LOG_DEBUG, sprintf("DB query (%0.3fs): %s", $delta, $clean));
390         }
391         return $result;
392     }
393
394     // Sanitize a query for logging
395     // @fixme don't trim spaces in string literals
396     function sanitizeQuery($string)
397     {
398         $string = preg_replace('/\s+/', ' ', $string);
399         $string = trim($string);
400         return $string;
401     }
402
403     // We overload so that 'SET NAMES "utf8"' is called for
404     // each connection
405
406     function _connect()
407     {
408         global $_DB_DATAOBJECT;
409
410         $sum = $this->_getDbDsnMD5();
411
412         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
413             !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
414             $exists = true;
415         } else {
416             $exists = false;
417        }
418
419         // @fixme horrible evil hack!
420         //
421         // In multisite configuration we don't want to keep around a separate
422         // connection for every database; we could end up with thousands of
423         // connections open per thread. In an ideal world we might keep
424         // a connection per server and select different databases, but that'd
425         // be reliant on having the same db username/pass as well.
426         //
427         // MySQL connections are cheap enough we're going to try just
428         // closing out the old connection and reopening when we encounter
429         // a new DSN.
430         //
431         // WARNING WARNING if we end up actually using multiple DBs at a time
432         // we'll need some fancier logic here.
433         if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
434             foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
435                 if (!empty($conn)) {
436                     $conn->disconnect();
437                 }
438                 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
439             }
440         }
441
442         $result = parent::_connect();
443
444         if ($result && !$exists) {
445             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
446             if (common_config('db', 'type') == 'mysql' &&
447                 common_config('db', 'utf8')) {
448                 $conn = $DB->connection;
449                 if (!empty($conn)) {
450                     if ($DB instanceof DB_mysqli) {
451                         mysqli_set_charset($conn, 'utf8');
452                     } else if ($DB instanceof DB_mysql) {
453                         mysql_set_charset('utf8', $conn);
454                     }
455                 }
456             }
457         }
458
459         return $result;
460     }
461
462     // XXX: largely cadged from DB_DataObject
463
464     function _getDbDsnMD5()
465     {
466         if ($this->_database_dsn_md5) {
467             return $this->_database_dsn_md5;
468         }
469
470         $dsn = $this->_getDbDsn();
471
472         if (is_string($dsn)) {
473             $sum = md5($dsn);
474         } else {
475             /// support array based dsn's
476             $sum = md5(serialize($dsn));
477         }
478
479         return $sum;
480     }
481
482     function _getDbDsn()
483     {
484         global $_DB_DATAOBJECT;
485
486         if (empty($_DB_DATAOBJECT['CONFIG'])) {
487             DB_DataObject::_loadConfig();
488         }
489
490         $options = &$_DB_DATAOBJECT['CONFIG'];
491
492         // if the databse dsn dis defined in the object..
493
494         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
495
496         if (!$dsn) {
497
498             if (!$this->_database) {
499                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
500             }
501
502             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
503                 $dsn = $options["database_{$this->_database}"];
504             } else if (!empty($options['database'])) {
505                 $dsn = $options['database'];
506             }
507         }
508
509         if (!$dsn) {
510             throw new Exception("No database name / dsn found anywhere");
511         }
512
513         return $dsn;
514     }
515
516     static function blow()
517     {
518         $c = self::memcache();
519
520         if (empty($c)) {
521             return false;
522         }
523
524         $args = func_get_args();
525
526         $format = array_shift($args);
527
528         $keyPart = vsprintf($format, $args);
529
530         $cacheKey = common_cache_key($keyPart);
531
532         return $c->delete($cacheKey);
533     }
534
535     function fixupTimestamps()
536     {
537         // Fake up timestamp columns
538         $columns = $this->table();
539         foreach ($columns as $name => $type) {
540             if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
541                 $this->$name = common_sql_now();
542             }
543         }
544     }
545
546     function debugDump()
547     {
548         common_debug("debugDump: " . common_log_objstring($this));
549     }
550 }