本文整理汇总了PHP中LBFactory类的典型用法代码示例。如果您正苦于以下问题:PHP LBFactory类的具体用法?PHP LBFactory怎么用?PHP LBFactory使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了LBFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testGetLBFactoryClass
/**
* @dataProvider getLBFactoryClassProvider
*/
public function testGetLBFactoryClass($expected, $deprecated)
{
$mockDB = $this->getMockBuilder('DatabaseMysql')->disableOriginalConstructor()->getMock();
$config = array('class' => $deprecated, 'connection' => $mockDB, 'sectionsByDB' => array(), 'sectionLoads' => array(), 'serverTemplate' => array());
$this->hideDeprecated('$wgLBFactoryConf must be updated. See RELEASE-NOTES for details');
$result = LBFactory::getLBFactoryClass($config);
$this->assertEquals($expected, $result);
}
示例2: __construct
/**
* @see LBFactory::__construct()
* @param array $conf Parameters of LBFactory::__construct() as well as:
* - servers : list of server configuration maps to Database::factory().
* Additionally, the server maps should have a 'load' key, which is used to decide
* how often clients connect to one server verses the others. A 'max lag' key should
* also be set on server maps, indicating how stale the data can be before the load
* balancer tries to avoid using it. The map can have 'is static' set to disable blocking
* replication sync checks (intended for archive servers with unchanging data).
* - externalClusters : map of cluster names to server arrays. The servers arrays have the
* same format as "servers" above.
*/
public function __construct(array $conf)
{
parent::__construct($conf);
$this->servers = isset($conf['servers']) ? $conf['servers'] : [];
foreach ($this->servers as $i => $server) {
if ($i == 0) {
$this->servers[$i]['master'] = true;
} else {
$this->servers[$i]['replica'] = true;
}
}
$this->externalClusters = isset($conf['externalClusters']) ? $conf['externalClusters'] : [];
$this->loadMonitorClass = isset($conf['loadMonitorClass']) ? $conf['loadMonitorClass'] : 'LoadMonitor';
}
示例3: finalSetup
/**
* Handle some last-minute setup here.
*/
public function finalSetup()
{
global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
global $wgDBadminuser, $wgDBadminpassword;
global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
# Turn off output buffering again, it might have been turned on in the settings files
if (ob_get_level()) {
ob_end_flush();
}
# Same with these
$wgCommandLineMode = true;
# Override $wgServer
if ($this->hasOption('server')) {
$wgServer = $this->getOption('server', $wgServer);
}
# If these were passed, use them
if ($this->mDbUser) {
$wgDBadminuser = $this->mDbUser;
}
if ($this->mDbPass) {
$wgDBadminpassword = $this->mDbPass;
}
if ($this->getDbType() == self::DB_ADMIN && isset($wgDBadminuser)) {
$wgDBuser = $wgDBadminuser;
$wgDBpassword = $wgDBadminpassword;
if ($wgDBservers) {
/**
* @var $wgDBservers array
*/
foreach ($wgDBservers as $i => $server) {
$wgDBservers[$i]['user'] = $wgDBuser;
$wgDBservers[$i]['password'] = $wgDBpassword;
}
}
if (isset($wgLBFactoryConf['serverTemplate'])) {
$wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
$wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
}
LBFactory::destroyInstance();
}
$this->afterFinalSetup();
$wgShowSQLErrors = true;
@set_time_limit(0);
$this->adjustMemoryLimit();
}
示例4: runUpdate
/**
* @param DeferrableUpdate $update
* @param LBFactory $lbFactory
* @param integer $stage
* @return ErrorPageError|null
*/
private static function runUpdate(DeferrableUpdate $update, LBFactory $lbFactory, $stage)
{
$guiError = null;
try {
$fnameTrxOwner = get_class($update) . '::doUpdate';
$lbFactory->beginMasterChanges($fnameTrxOwner);
$update->doUpdate();
$lbFactory->commitMasterChanges($fnameTrxOwner);
} catch (Exception $e) {
// Reporting GUI exceptions does not work post-send
if ($e instanceof ErrorPageError && $stage === self::PRESEND) {
$guiError = $e;
}
MWExceptionHandler::rollbackMasterChangesAndLog($e);
}
return $guiError;
}
示例5: finalSetup
/**
* Handle some last-minute setup here.
*/
public function finalSetup()
{
global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
global $wgDBadminuser, $wgDBadminpassword;
global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
# Turn off output buffering again, it might have been turned on in the settings files
if (ob_get_level()) {
ob_end_flush();
}
# Same with these
$wgCommandLineMode = true;
# Override $wgServer
if ($this->hasOption('server')) {
$wgServer = $this->getOption('server', $wgServer);
}
# If these were passed, use them
if ($this->mDbUser) {
$wgDBadminuser = $this->mDbUser;
}
if ($this->mDbPass) {
$wgDBadminpassword = $this->mDbPass;
}
if ($this->getDbType() == self::DB_ADMIN && isset($wgDBadminuser)) {
$wgDBuser = $wgDBadminuser;
$wgDBpassword = $wgDBadminpassword;
if ($wgDBservers) {
/**
* @var $wgDBservers array
*/
foreach ($wgDBservers as $i => $server) {
$wgDBservers[$i]['user'] = $wgDBuser;
$wgDBservers[$i]['password'] = $wgDBpassword;
}
}
if (isset($wgLBFactoryConf['serverTemplate'])) {
$wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
$wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
}
LBFactory::destroyInstance();
}
$this->afterFinalSetup();
$wgShowSQLErrors = true;
// @codingStandardsIgnoreStart Allow error supppression. wfSuppressWarnings()
// is not avaiable.
@set_time_limit(0);
// @codingStandardsIgnoreStart
$this->adjustMemoryLimit();
// Per-script profiling; useful for debugging
$forcedProfiler = $this->getOption('profiler');
if ($forcedProfiler === 'text') {
Profiler::setInstance(new ProfilerSimpleText(array()));
Profiler::instance()->setTemplated(true);
} elseif ($forcedProfiler === 'trace') {
Profiler::setInstance(new ProfilerSimpleTrace(array()));
Profiler::instance()->setTemplated(true);
}
}
示例6: exportGroup
protected function exportGroup(MessageGroup $group, $multi = false)
{
// Make sure all existing connections are dead,
// we can't use them in forked children.
LBFactory::destroyInstance();
$server = TTMServer::primary();
$id = $group->getId();
$sourceLanguage = $group->getSourceLanguage();
if ($multi) {
$stats = MessageGroupStats::forGroup($id);
$this->statusLine("Loaded stats for {$id}\n");
} else {
$this->statusLine("Loading stats... ", 4);
$stats = MessageGroupStats::forGroup($id);
$this->output("done!", 4);
$this->statusLine("Inserting sources: ", 5);
}
$collection = $group->initCollection($sourceLanguage);
$collection->filter('ignored');
$collection->filter('optional');
$collection->initMessages();
$sids = array();
$counter = 0;
foreach ($collection->keys() as $mkey => $title) {
$def = $collection[$mkey]->definition();
$sids[$mkey] = $server->insertSource($title, $sourceLanguage, $def);
if (++$counter % $this->mBatchSize === 0 && !$multi) {
wfWaitForSlaves(10);
$this->output('.', 5);
}
}
$total = count($sids);
if ($multi) {
$this->statusLine("Inserted {$total} source entries for {$id}\n");
} else {
$this->output("{$total} entries", 5);
$this->statusLine("Inserting translations...", 6);
}
$dbw = $server->getDB(DB_MASTER);
foreach ($stats as $targetLanguage => $numbers) {
if ($targetLanguage === $sourceLanguage) {
continue;
}
if ($numbers[MessageGroupStats::TRANSLATED] === 0) {
continue;
}
if (!$multi) {
$this->output(sprintf("%19s ", $targetLanguage), $targetLanguage);
}
$collection->resetForNewLanguage($targetLanguage);
$collection->filter('ignored');
$collection->filter('optional');
$collection->filter('translated', false);
$collection->loadTranslations();
$inserts = array();
foreach ($collection->keys() as $mkey => $title) {
$inserts[] = array('tmt_sid' => $sids[$mkey], 'tmt_lang' => $targetLanguage, 'tmt_text' => $collection[$mkey]->translation());
}
do {
$batch = array_splice($inserts, 0, $this->mBatchSize);
$dbw->insert('translate_tmt', $batch, __METHOD__);
if (!$multi) {
$this->output('.', $targetLanguage);
}
wfWaitForSlaves(10);
} while (count($inserts));
}
if ($multi) {
$this->statusLine("Inserted translations for {$id}\n");
}
}
示例7: wfGetLBFactory
/**
* Get the load balancer factory object
*
* @return LBFactory
*/
function wfGetLBFactory()
{
return LBFactory::singleton();
}
示例8: resetStateForFork
protected function resetStateForFork()
{
// Child, reseed because there is no bug in PHP:
// http://bugs.php.net/bug.php?id=42465
mt_srand(getmypid());
// Make sure all existing connections are dead,
// we can't use them in forked children.
LBFactory::destroyInstance();
}
示例9: scriptDone
private function scriptDone($script)
{
global $wgDBuser, $wgDBpassword, $wgDBadminuser, $wgDBadminpassword, $wgDBuserold, $wgDBpasswordold;
if ($script->getDbType() === Maintenance::DB_ADMIN && isset($wgDBadminuser)) {
$wgDBuser = $wgDBuserold;
$wgDBpassword = $wgDBpasswordold;
unset($GLOBALS['wgDBuserold'], $GLOBALS['wgDBpasswordold']);
LBFactory::destroyInstance();
}
$goptions = $this->metadata[$this->type]['option'];
$gargs = $this->metadata[$this->type]['arg'];
if ($goptions != array()) {
foreach ($goptions as $a) {
if ($a['type'] == 'textarea' && $a['tmpfile'] && file_exists($a['tmpfile'])) {
unlink($a['tmpfile']);
}
}
}
if ($gargs != array()) {
foreach ($gargs as $a) {
if ($a['type'] == 'textarea' && $a['tmpfile'] && file_exists($a['tmpfile'])) {
unlink($a['tmpfile']);
}
}
}
}
示例10: __construct
/**
* @see LBFactory::__construct()
*
* Template override precedence (highest => lowest):
* - templateOverridesByServer
* - masterTemplateOverrides
* - templateOverridesBySection/templateOverridesByCluster
* - externalTemplateOverrides
* - serverTemplate
* Overrides only work on top level keys (so nested values will not be merged).
*
* Server configuration maps should be of the format Database::factory() requires.
* Additionally, a 'max lag' key should also be set on server maps, indicating how stale the
* data can be before the load balancer tries to avoid using it. The map can have 'is static'
* set to disable blocking replication sync checks (intended for archive servers with
* unchanging data).
*
* @param array $conf Parameters of LBFactory::__construct() as well as:
* - sectionsByDB Map of database names to section names.
* - sectionLoads 2-d map. For each section, gives a map of server names to
* load ratios. For example:
* [
* 'section1' => [
* 'db1' => 100,
* 'db2' => 100
* ]
* ]
* - serverTemplate Server configuration map intended for Database::factory().
* Note that "host", "hostName" and "load" entries will be
* overridden by "sectionLoads" and "hostsByName".
* - groupLoadsBySection 3-d map giving server load ratios for each section/group.
* For example:
* [
* 'section1' => [
* 'group1' => [
* 'db1' => 100,
* 'db2' => 100
* ]
* ]
* ]
* - groupLoadsByDB 3-d map giving server load ratios by DB name.
* - hostsByName Map of hostname to IP address.
* - externalLoads Map of external storage cluster name to server load map.
* - externalTemplateOverrides Set of server configuration maps overriding
* "serverTemplate" for external storage.
* - templateOverridesByServer 2-d map overriding "serverTemplate" and
* "externalTemplateOverrides" on a server-by-server basis.
* Applies to both core and external storage.
* - templateOverridesBySection 2-d map overriding the server configuration maps by section.
* - templateOverridesByCluster 2-d map overriding the server configuration maps by external
* storage cluster.
* - masterTemplateOverrides Server configuration map overrides for all master servers.
* - loadMonitorClass Name of the LoadMonitor class to always use.
* - readOnlyBySection A map of section name to read-only message.
* Missing or false for read/write.
*/
public function __construct(array $conf)
{
parent::__construct($conf);
$this->conf = $conf;
$required = ['sectionsByDB', 'sectionLoads', 'serverTemplate'];
$optional = ['groupLoadsBySection', 'groupLoadsByDB', 'hostsByName', 'externalLoads', 'externalTemplateOverrides', 'templateOverridesByServer', 'templateOverridesByCluster', 'templateOverridesBySection', 'masterTemplateOverrides', 'readOnlyBySection', 'loadMonitorClass'];
foreach ($required as $key) {
if (!isset($conf[$key])) {
throw new InvalidArgumentException(__CLASS__ . ": {$key} is required.");
}
$this->{$key} = $conf[$key];
}
foreach ($optional as $key) {
if (isset($conf[$key])) {
$this->{$key} = $conf[$key];
}
}
}
示例11: function
*
* @note As of version 1.27, MediaWiki is only beginning to use dependency injection.
* The services defined here do not yet fully represent all services used by core,
* much of the code still relies on global state for this accessing services.
*
* @since 1.27
*
* @see docs/injection.txt for an overview of using dependency injection in the
* MediaWiki code base.
*/
use MediaWiki\Interwiki\ClassicInterwikiLookup;
use MediaWiki\Linker\LinkRendererFactory;
use MediaWiki\MediaWikiServices;
return ['DBLoadBalancerFactory' => function (MediaWikiServices $services) {
$config = $services->getMainConfig()->get('LBFactoryConf');
$class = LBFactory::getLBFactoryClass($config);
if (!isset($config['readOnlyReason'])) {
// TODO: replace the global wfConfiguredReadOnlyReason() with a service.
$config['readOnlyReason'] = wfConfiguredReadOnlyReason();
}
return new $class($config);
}, 'DBLoadBalancer' => function (MediaWikiServices $services) {
// just return the default LB from the DBLoadBalancerFactory service
return $services->getDBLoadBalancerFactory()->getMainLB();
}, 'SiteStore' => function (MediaWikiServices $services) {
$rawSiteStore = new DBSiteStore($services->getDBLoadBalancer());
// TODO: replace wfGetCache with a CacheFactory service.
// TODO: replace wfIsHHVM with a capabilities service.
$cache = wfGetCache(wfIsHHVM() ? CACHE_ACCEL : CACHE_ANYTHING);
return new CachingSiteStore($rawSiteStore, $cache);
}, 'SiteLookup' => function (MediaWikiServices $services) {
示例12: tearDown
function tearDown()
{
LBFactory::destroyInstance();
}
示例13: wfGetDB
}
$dbw = wfGetDB(DB_SLAVE);
// define socket which listens for a break signal
$socket = socket_create_listen("9876");
// port is freely chosen
socket_set_nonblock($socket);
// max number of threads to be considered to calculate sleeping time
define('MAX_THREADS_CONSIDERED', 10);
global $wgLoadBalancer;
print "-------------------------------------------------\n";
print " Running jobs... ({$rate} jobs/second) \t\t \n";
print "-------------------------------------------------\n";
for (;;) {
// determine the most lagged slave
// if $lag == -1, there's no slave.
list($host, $lag) = LBFactory::singleton()->getMainLB()->getMaxLag();
if ($lag == -1) {
// make sleeping time adaptive to database load.
$runningThreads = smwfGetNumOfRunningThreads($dbw);
$runningThreads = $runningThreads <= MAX_THREADS_CONSIDERED ? $runningThreads : MAX_THREADS_CONSIDERED;
// wait depending on user-defined $rate and server load
sleep(1 / $rate + $runningThreads);
} else {
// wait for most lagged slave to be *below* 1/$rate + 3 seconds lag time.
wfWaitForSlaves(1 / $rate + 3);
}
// get next job
$job = Job::pop();
// is there a break signal?
$accept_sock = @socket_accept($socket);
if ($accept_sock !== false) {
示例14: execute
/**
* execute
*
* Main entry point for class
*
* @author Krzysztof Krzyżaniak <eloy@wikia-inc.com>
*
* @return integer: wikia id or null if wikia is not handled by WikiFactory
*/
public function execute()
{
wfProfileIn(__METHOD__);
global $wgCityId, $wgDevelEnvironment, $wgDBservers, $wgLBFactoryConf, $wgDBserver, $wgContLang;
/**
* Hook to allow extensions to alter the initialization. For example,
* setting the mCityID then returning true will override which wiki
* to use.
*
* @author Sean Colombo
*/
if (!wfRunHooks('WikiFactory::execute', array(&$this))) {
wfProfileOut(__METHOD__);
return $this->mWikiID;
}
/**
* load balancer uses one method which demand wgContLang defined
* See BugId: 12474
*/
$wgContLang = new StubObject('wgContLang');
/**
* local cache, change to CACHE_ACCEL for local
*/
global $wgWikiFactoryCacheType;
$oMemc = wfGetCache($wgWikiFactoryCacheType);
if (empty($this->mAlwaysFromDB)) {
/**
* remember! for http requests we only known $this->mServerName
* (domain), $this->mCityId is unknown (set to false in constructor)
*/
wfProfileIn(__METHOD__ . "-domaincache");
$key = WikiFactory::getDomainKey($this->mServerName);
$this->mDomain = $oMemc->get($key);
$this->mDomain = isset($this->mDomain["id"]) ? $this->mDomain : array();
$this->debug("reading from cache, key {$key}");
wfProfileOut(__METHOD__ . "-domaincache");
}
if (!isset($this->mDomain["id"]) || $this->mAlwaysFromDB) {
wfProfileIn(__METHOD__ . "-domaindb");
/**
* first run or cache expired
*/
$dbr = $this->getDB();
/**
* interactive/cmdline case. We know city_id so we don't have to
* ask city_domains table
*/
if ($this->mCityID || $this->mCityDB) {
$oRow = $dbr->selectRow(array("city_list"), array("city_id", "city_public", "city_factory_timestamp", "city_url", "city_dbname"), $this->mCityID ? array("city_list.city_id" => $this->mCityID) : array("city_list.city_dbname" => $this->mCityDB), __METHOD__ . '::domaindb');
if (isset($oRow->city_id)) {
preg_match("/http[s]*\\:\\/\\/(.+)\$/", $oRow->city_url, $matches);
$host = rtrim($matches[1], "/");
$this->mCityID = $oRow->city_id;
$this->mWikiID = $oRow->city_id;
$this->mIsWikiaActive = $oRow->city_public;
$this->mCityHost = $host;
$this->mCityDB = $oRow->city_dbname;
$this->mTimestamp = $oRow->city_factory_timestamp;
$this->mDomain = array("id" => $oRow->city_id, "host" => $host, "active" => $oRow->city_public, "time" => $oRow->city_factory_timestamp, "db" => $this->mCityDB);
}
} else {
/**
* request from HTTPD case. We only know server name so we
* have to ask city_domains table
*/
$oRow = $dbr->selectRow(array("city_domains", "city_list"), array("city_list.city_id", "city_public", "city_factory_timestamp", "city_domain", "city_url", "city_dbname"), array("city_domains.city_id = city_list.city_id", "city_domains.city_domain" => $this->mServerName), __METHOD__ . '::servername');
if (isset($oRow->city_id) && $oRow->city_id > 0) {
$oRow->city_domain = strtolower($oRow->city_domain);
preg_match("/http[s]*\\:\\/\\/(.+)\$/", $oRow->city_url, $matches);
$host = rtrim($matches[1], "/");
if ($oRow->city_domain == $this->mServerName && $this->mServerName) {
$this->mWikiID = $oRow->city_id;
$this->mIsWikiaActive = $oRow->city_public;
$this->mCityHost = $host;
$this->mCityDB = $oRow->city_dbname;
$this->mTimestamp = $oRow->city_factory_timestamp;
$this->mDomain = array("id" => $oRow->city_id, "host" => $host, "active" => $oRow->city_public, "time" => $oRow->city_factory_timestamp, "db" => $oRow->city_dbname);
}
}
}
if (empty($this->mAlwaysFromDB) && !empty($this->mWikiID)) {
/**
* store value in cache
*/
$oMemc->set(WikiFactory::getDomainKey($this->mServerName), $this->mDomain, $this->mExpireDomainCacheTimeout);
}
$this->debug("city_id={$this->mWikiID}, reading from database key {$this->mServerName}");
wfProfileOut(__METHOD__ . "-domaindb");
} else {
/**
* data taken from cache
//.........这里部分代码省略.........
示例15: destroyInstance
/**
* Shut down, close connections and destroy the cached instance.
*
*/
static function destroyInstance()
{
if (self::$instance) {
self::$instance->shutdown();
self::$instance->forEachLBCallMethod('closeAll');
self::$instance = null;
}
}