Extension:Memcached

From MediaWiki.org
Jump to navigation Jump to search
MediaWiki extensions manualManual:Extensions
Crystal Clear action run.svg
Memcached

Release status:Extension status unmaintained

ImplementationTemplate:Extension#type Special page
DescriptionTemplate:Extension#description Provides an interface for checking if Memcached is working fine
Author(s)Template:Extension#username UA2004
Latest versionTemplate:Extension#version 1.0.1 (2014-01-04)
MediaWikiTemplate:Extension#mediawiki 1.19-1.28
Database changesTemplate:Extension#needs-updatephp No
LicenseTemplate:Extension#license No license specified
Download See the code section
Added rightsTemplate:Extension#rights

memcached

Translate the Memcached extension if it is available at translatewiki.net

Check usage and version matrix.

The Memcached extension provides an interface for checking if Memcached is working fine.

Description[edit]

When I installed Memcached on my wiki server I had a problem to regularly check if it works fine or should be restarted. Because sometimes it crashes and the wiki opens way too long which is annoying. I assume this happens when Memcached works many days non-stop. So I added a cron task to restart the Memcached service once a day in case it crashes again. But what if it crashes before the cron task runs? All users have to wait until it is restarted.

So every day I have to login through SSH to check the status of Memcached service. This is boring to type login and password each time. There should be an easier way. At first I found a PHP-script for checking Memcached status. It was good but was allowed to run by everyone who knew its file name. For security purpose we don't want anyone to find out the IP and port of our Memcached server(-s). Thus I came to the conclusion: it would be great to implement it as a MediaWiki extension and deny access for everyone but admin.

Since I didn't find any Memcached extension at all (which is shame because, for instance, APC extension exists for a long time), I decided to create my own. I've been modifying plenty of MediaWiki extensions for myself but never created one. This is my first separate extension so suggestions are welcome.

Usage[edit]

First of all, you need to install Memcached and define its servers in $wgMemCachedServers. Don't forget to install PECL memcache for PHP (do not confuse with PECL memcached which is currently not supported).

If you've already done it go to "Special:Memcached" and you'll see the list of memcached servers with their status (working, not working or no memcache service found).

Note Note: In theory, this extension can be used with the versions of MediaWiki older than 1.19 but this has not been tested.

Download instructions[edit]

Since I'm quite busy with different projects, I've got no time for MediaWiki git stuff. This extension consists of only two files so far and thus it's easier for me to just publish them here.

Installation[edit]

  • Add the following code at the bottom of your LocalSettings.php:
    require_once "$IP/extensions/Memcached/Memcached.php";
    
  • YesY Done - Navigate to Special:Version on your wiki to verify that the extension is successfully installed.
User rights
  • memcached - the right to view the Special:Memcached page. By default allowed only for bureaucrats. You may change it if you wish.

Code[edit]

Memcached.php[edit]

<?php
/**
 * A Memcached extension for MediaWiki
 * Originally written for ZeWiki
 * Provides an interface for checking if memcached is working fine
 *
 * @link https://www.mediawiki.org/wiki/Extension:Memcached Documentation
 * @link https://www.mediawiki.org/wiki/Extension_talk:Memcached Support
 *
 * @author UA2004 <ua2004 at ukr.net> for ZeWiki.com
 * @copyright Copyright (C) 2013, UA2004
 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0 or later
 */

if ( !defined( 'MEDIAWIKI' ) ) die();

define( 'Memcached_VERSION', '1.0.1' );

$wgExtensionCredits['specialpage'][] = array(
        'path'           => __FILE__,
	'name'           => 'Memcached',
	'author'         => 'UA2004',
	'url'            => 'https://www.mediawiki.org/wiki/Extension:Memcached',
	'version'        => Memcached_VERSION,
	'descriptionmsg' => 'memcached-desc',
	'license-name'   => 'GPL-2.0+',
);

$wgSpecialPages['Memcached'] = 'SpecialMemcached';
$wgExtensionMessagesFiles['Memcached'] = dirname(__FILE__) . '/Memcached.i18n.php';

$wgAvailableRights[] = 'memcached';
$wgGroupPermissions['*']['memcached'] = false;
$wgGroupPermissions['bureaucrat']['memcached'] = true;


class SpecialMemcached extends SpecialPage {
	const MEMC_OK = 1;
	const MEMC_ERROR = 0;
	const MEMC_NOT_FOUND = -1;

	public function __construct() {
		parent::__construct('Memcached');
	}

	public function execute() {
		global $wgOut, $wgRequest, $wgUser, $wgMemc, $wgMemCachedServers;

		wfProfileIn(__METHOD__);

		$this->setHeaders();
		$this->mTitle = SpecialPage::getTitleFor('Memcached');

		if (!$wgUser->isAllowed( 'memcached' )) {
			$this->displayRestrictionError();
			wfProfileOut(__METHOD__);
			return;
		}
		
		if (class_exists('Memcache')) {
			if(empty($wgMemCachedServers)) {
				$wgOut->addHTML('<h3>'.wfMessage('memcached-servers-not-set')->text().'</h3>');
			}
			else {
				$wgOut->addHTML(Xml::openElement('table', array('border'=>1)));
				foreach($wgMemCachedServers as $server) {
					switch($this->testMemcachedServer( $server )) {
						case self::MEMC_OK:
							$message = wfMessage('memcached-works')->text();
							$color = '#84eb82';
							break;
						case self::MEMC_ERROR:
							$message = wfMessage('memcached-not-working')->text();
							$color = '#ffde46';
							break;
						case self::MEMC_NOT_FOUND:
							$message = wfMessage('memcached-not-found')->text();
							$color = '#fe7f7a';
							break;
					}
					$wgOut->addHTML(Xml::openElement('tr', array('style'=>'background-color:'.$color)));
					$wgOut->addHTML(Xml::openElement('td'));
					$wgOut->addHTML($server);
					$wgOut->addHTML(Xml::closeElement('td'));
					$wgOut->addHTML(Xml::openElement('td'));
					$wgOut->addHTML($message);
					$wgOut->addHTML(Xml::closeElement('td'));
					$wgOut->addHTML(Xml::closeElement('tr'));
				}
				$wgOut->addHTML(Xml::closeElement('table'));
			}
		}
		else {
			$wgOut->addHTML('<h3>'.wfMessage('memcached-pecl-not-found')->text().'</h3>');
		}

		wfProfileOut(__METHOD__);
	}
	
	public function testMemcachedServer( $server ) {
		wfProfileIn(__METHOD__);
		
		$memcache = new Memcache;
		$isMemcacheAvailable = @$memcache->connect($server);

		if ($isMemcacheAvailable) {
			$key = wfMemcKey( 'zewiki', 'special', 'memcached', 'test' );
			$aData = $memcache->get($key);
			if ($aData) {
				return self::MEMC_OK;
			} else {
				$aData = array(
					'me' => 'you',
					'us' => 'them',
				);
				$memcache->set($key, $aData, 0, 300);
				$aData = $memcache->get($key);
				if ($aData) {
					return self::MEMC_OK;
				} else {
					return self::MEMC_ERROR;
				}
			}
		}
		else {
			return self::MEMC_NOT_FOUND;
		}
		
		wfProfileOut(__METHOD__);
	}

	protected function getGroupName() {
		return 'wiki';
	}
}

Memcached.i18n.php[edit]

<?php
/**
 * Internationalization file for Memcached extension
 */

$messages = array();

/** English
 * @author UA2004
 */
$messages['en'] = array(
	'memcached' => 'Memcached',
	'memcached-desc' => 'Provides an interface for checking if Memcached is working fine',
	'memcached-data-received' => 'Test data got from Memcached successfully!',
	'memcached-data-set' => 'Test data written in Memcached! Please refresh the page to see if it is working properly.',
	'memcached-works' => 'Memcached seems to be working fine!',
	'memcached-not-working' => 'Memcached DOES NOT seem to be working! Please restart it.',
	'memcached-not-found' => 'Memcached is not available on this server!',
	'memcached-pecl-not-found' => 'Memcache PECL is not available on this server!',
	'memcached-servers-not-set' => 'Memcached servers not set! Please add them into <b>$wgMemCachedServers</b> setting in your LocalSettings.php file.',
);

/** German (Deutsch)
 * @author Kghbln
 */
$messages['de'] = array(
	'memcached' => 'Memcached',
	'memcached-desc' => 'Stellt ein Interface zur Überprüfung des Status von Memcached bereit',
	'memcached-data-received' => 'Die Testdaten wurden erfolgreich von Memcached abgerufen.',
	'memcached-data-set' => 'Die Testdaten wurden an Memcached übermittelt. Bitte den Seitencache leeren, um zu prüfen, ob Memcached problemlos funktioniert.',
	'memcached-works' => 'Memcached scheint problemlos zu funktionieren.',
	'memcached-not-working' => 'Memcached scheint nicht problemlos zu funktionieren und sollte neu gestartet werden.',
	'memcached-not-found' => 'Memcached ist nicht auf dem Server verfügbar.',
	'memcached-pecl-not-found' => 'Memcache PECL ist nicht auf dem Server verfügbar.',
	'memcached-servers-not-set' => 'Die Memcached-Sever wurden nicht für MediaWiki konfiguriert. Der Parameter <code>$wgMemCachedServers</code> muß noch zur Datei „LocalSettings.php“ hinzugefügt werden.',
);

/** Ukrainian (українська)
 * @author UA2004
 */
$messages['uk'] = array(
	'memcached' => 'Memcached',
	'memcached-desc' => 'Надає інтерфейс для перевірки роботи служби Memcached на сервері',
	'memcached-data-received' => 'Тестові дані успішно зчитано з Memcached!',
	'memcached-data-set' => 'Тестові дані записано у Memcached! Будь ласка, оновіть сторінку, щоб побачити чи служба працює належним чином.',
	'memcached-works' => 'Служба Memcached працює!',
	'memcached-not-working' => 'Служба Memcached НЕ працює! Перезапустіть її, будь ласка.',
	'memcached-not-found' => 'Службу Memcached не знайдено на цьому сервері!',
	'memcached-pecl-not-found' => 'Розширення PECL memcache не знайдено на цьому сервері!',
	'memcached-servers-not-set' => 'Сервери Memcached не вказано! Будь ласка, додайте їх у змінну <b>$wgMemCachedServers</b> у файлі LocalSettings.php.',
);

/** French
 * @author cybernaute
 */
$messages['fr'] = array(
        'memcached' => 'Memcached',
        'memcached-desc' => 'Fournit une interface pour vérifier le fonctionnement de Memcached',
        'memcached-data-received' => 'Données tests Memcached obtenues avec succès !',
        'memcached-data-set' => 'Données de test écrites dans Memcached ! Veuillez rafraîchir la page pour voir si le résultat est correct.',
        'memcached-works' => 'Memcached semble fonctionner correctement!',
        'memcached-not-working' => 'Memcached semble NE PAS fonctionner correctement ! Veuillez le redémarrrer.',
        'memcached-not-found' => 'Memcached est indisponible sur ce serveur !',
        'memcached-pecl-not-found' => 'Memcache PECL est indisponible sur ce serveur !',
        'memcached-servers-not-set' => 'Les serveurs Memcached ne sont pas encore configureées ! Veuillez les ajouter en utilisant le paramètre <b>$wgMemCachedServers</b> dans votre fichier LocalSettings.php.',
);

See also[edit]

Other languages:Project:Language policy English  • українська