Permalink
Browse files

MDL-38565 cache: cron routine to clean up old session data

1 parent 2e0b7de commit 73433c09951ae9fa66c1522899c9eddec7357d92 Sam Hemelryk committed Apr 17, 2013
Showing with 61 additions and 0 deletions.
  1. +58 −0 cache/classes/helper.php
  2. +3 −0 lib/cronlib.php
View
@@ -567,4 +567,62 @@ public static function get_site_version() {
global $CFG;
return (string)$CFG->version;
}
+
+ /**
+ * Runs cron routines for MUC.
+ */
+ public static function cron() {
+ self::clean_old_session_data(true);
+ }
+
+ /**
+ * Cleans old session data from cache stores used for session based definitions.
+ *
+ * @param bool $output If set to true output will be given.
+ */
+ public static function clean_old_session_data($output = false) {
+ global $CFG;
+ if ($output) {
+ mtrace('Cleaning up stale session data from cache stores.');
+ }
+ $factory = cache_factory::instance();
+ $config = $factory->create_config_instance();
+ $definitions = $config->get_definitions();
+ $purgetime = time() - $CFG->sessiontimeout;
+ foreach ($definitions as $definitionarray) {
+ // We are only interested in session caches.
+ if (!($definitionarray['mode'] & cache_store::MODE_SESSION)) {
+ continue;
+ }
+ $definition = $factory->create_definition($definitionarray['component'], $definitionarray['area']);
+ $stores = $config->get_stores_for_definition($definition);
+ // Initialise all of the stores used for that definition.
+ foreach (self::initialise_cachestore_instances($stores, $definition) as $store) {
+ // If the store doesn't support searching we can skip it.
+ if (!($store instanceof cache_is_searchable)) {
+ debugging('Cache stores used for session definitions should ideally be searchable.', DEBUG_DEVELOPER);
+ continue;
+ }
+ // Get all of the keys.
+ $keys = $store->find_by_prefix(cache_session::KEY_PREFIX);
+ $todelete = array();
+ foreach ($store->get_many($keys) as $key => $value) {
+ if (strpos($key, cache_session::KEY_PREFIX) !== 0 || !is_array($value) || !isset($value['lastaccess'])) {
+ continue;
+ }
+ if ((int)$value['lastaccess'] < $purgetime || true) {
+ $todelete[] = $key;
+ }
+ }
+ if (count($todelete)) {
+ $outcome = (int)$store->delete_many($todelete);
+ if ($output) {
+ $strdef = s($definition->get_id());
+ $strstore = s($store->my_name());
+ mtrace("- Removed {$outcome} old {$strdef} sessions from the '{$strstore}' cache store.");
+ }
+ }
+ }
+ }
+ }
}
View
@@ -435,6 +435,9 @@ function cron_run() {
mtrace('done.');
}
+ mtrace('Running cache cron routines');
+ cache_helper::cron();
+ mtrace('done.');
// Run automated backups if required - these may take a long time to execute
require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');

0 comments on commit 73433c0

Please sign in to comment.