code
stringlengths
15
9.96M
docstring
stringlengths
1
10.1k
func_name
stringlengths
1
124
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
6
186
url
stringlengths
50
236
license
stringclasses
4 values
public static function getRequestCache() { if (!self::$requestCache) { self::$requestCache = new PhutilInRequestKeyValueCache(); } return self::$requestCache; }
Get a request cache stack. This cache stack is destroyed after each logical request. In particular, it is destroyed periodically by the daemons, while `static` caches are not. @return PhutilKeyValueCacheStack Request cache stack.
getRequestCache
php
phorgeit/phorge
src/applications/cache/PhabricatorCaches.php
https://github.com/phorgeit/phorge/blob/master/src/applications/cache/PhabricatorCaches.php
Apache-2.0
public static function destroyRequestCache() { self::$requestCache = null; // See T12997. Force the GC to run when the request cache is destroyed to // clean up any cycles which may still be hanging around. if (function_exists('gc_collect_cycles')) { gc_collect_cycles(); } }
Destroy the request cache. This is called at the beginning of each logical request. @return void
destroyRequestCache
php
phorgeit/phorge
src/applications/cache/PhabricatorCaches.php
https://github.com/phorgeit/phorge/blob/master/src/applications/cache/PhabricatorCaches.php
Apache-2.0
public static function getImmutableCache() { static $cache; if (!$cache) { $caches = self::buildImmutableCaches(); $cache = self::newStackFromCaches($caches); } return $cache; }
Gets an immutable cache stack. This stack trades mutability away for improved performance. Normally, it is APC + DB. In the general case with multiple web frontends, this stack can not be cleared, so it is only appropriate for use if the value of a given key is permanent and immutable. @return PhutilKeyValueCacheStack Best immutable stack available. @task immutable
getImmutableCache
php
phorgeit/phorge
src/applications/cache/PhabricatorCaches.php
https://github.com/phorgeit/phorge/blob/master/src/applications/cache/PhabricatorCaches.php
Apache-2.0
private static function buildImmutableCaches() { $caches = array(); $apc = new PhutilAPCKeyValueCache(); if ($apc->isAvailable()) { $caches[] = $apc; } $caches[] = new PhabricatorKeyValueDatabaseCache(); return $caches; }
Build the immutable cache stack. @return list<PhutilKeyValueCache> List of caches. @task immutable
buildImmutableCaches
php
phorgeit/phorge
src/applications/cache/PhabricatorCaches.php
https://github.com/phorgeit/phorge/blob/master/src/applications/cache/PhabricatorCaches.php
Apache-2.0
public static function getRuntimeCache() { static $cache; if (!$cache) { $caches = self::buildRuntimeCaches(); $cache = self::newStackFromCaches($caches); } return $cache; }
Get a runtime cache stack. This stack is just APC. It's fast, it's effectively immutable, and it gets thrown away when the webserver restarts. This cache is suitable for deriving runtime caches, like a map of Conduit method names to provider classes. @return PhutilKeyValueCacheStack Best runtime stack available.
getRuntimeCache
php
phorgeit/phorge
src/applications/cache/PhabricatorCaches.php
https://github.com/phorgeit/phorge/blob/master/src/applications/cache/PhabricatorCaches.php
Apache-2.0
public static function getServerStateCache() { static $cache; if (!$cache) { $caches = self::buildSetupCaches('phabricator-server'); // NOTE: We are NOT adding a cache namespace here! This cache is shared // across all instances on the host. $caches = self::addProfilerToCaches($caches); $cache = id(new PhutilKeyValueCacheStack()) ->setCaches($caches); } return $cache; }
Highly specialized cache for storing server process state. We use this cache to track initial steps in the setup phase, before configuration is loaded. This cache does NOT use the cache namespace (it must be accessed before we build configuration), and is global across all instances on the host. @return PhutilKeyValueCacheStack Best available server state cache stack. @task setup
getServerStateCache
php
phorgeit/phorge
src/applications/cache/PhabricatorCaches.php
https://github.com/phorgeit/phorge/blob/master/src/applications/cache/PhabricatorCaches.php
Apache-2.0
public static function getSetupCache() { static $cache; if (!$cache) { $caches = self::buildSetupCaches('phabricator-setup'); $cache = self::newStackFromCaches($caches); } return $cache; }
Highly specialized cache for performing setup checks. We use this cache to determine if we need to run expensive setup checks when the page loads. Without it, we would need to run these checks every time. Normally, this cache is just APC. In the absence of APC, this cache degrades into a slow, quirky on-disk cache. NOTE: Do not use this cache for anything else! It is not a general-purpose cache! @return PhutilKeyValueCacheStack Most qualified available cache stack. @task setup
getSetupCache
php
phorgeit/phorge
src/applications/cache/PhabricatorCaches.php
https://github.com/phorgeit/phorge/blob/master/src/applications/cache/PhabricatorCaches.php
Apache-2.0
private static function buildSetupCaches($cache_name) { // If this is the CLI, just build a setup cache. if (php_sapi_name() == 'cli') { return array(); } // In most cases, we should have APC. This is an ideal cache for our // purposes -- it's fast and empties on server restart. $apc = new PhutilAPCKeyValueCache(); if ($apc->isAvailable()) { return array($apc); } // If we don't have APC, build a poor approximation on disk. This is still // much better than nothing; some setup steps are quite slow. $disk_path = self::getSetupCacheDiskCachePath($cache_name); if ($disk_path) { $disk = new PhutilOnDiskKeyValueCache(); $disk->setCacheFile($disk_path); $disk->setWait(0.1); if ($disk->isAvailable()) { return array($disk); } } return array(); }
@task setup
buildSetupCaches
php
phorgeit/phorge
src/applications/cache/PhabricatorCaches.php
https://github.com/phorgeit/phorge/blob/master/src/applications/cache/PhabricatorCaches.php
Apache-2.0
private static function getSetupCacheDiskCachePath($name) { // The difficulty here is in choosing a path which will change on server // restart (we MUST have this property), but as rarely as possible // otherwise (we desire this property to give the cache the best hit rate // we can). // Unfortunately, we don't have a very good strategy for minimizing the // churn rate of the cache. We previously tried to use the parent process // PID in some cases, but this was not reliable. See T9599 for one case of // this. $pid_basis = getmypid(); // If possible, we also want to know when the process launched, so we can // drop the cache if a process restarts but gets the same PID an earlier // process had. "/proc" is not available everywhere (e.g., not on OSX), but // check if we have it. $epoch_basis = null; $stat = @stat("/proc/{$pid_basis}"); if ($stat !== false) { $epoch_basis = $stat['ctime']; } $tmp_dir = sys_get_temp_dir(); $tmp_path = $tmp_dir.DIRECTORY_SEPARATOR.$name; if (!file_exists($tmp_path)) { @mkdir($tmp_path); } $is_ok = self::testTemporaryDirectory($tmp_path); if (!$is_ok) { $tmp_path = $tmp_dir; $is_ok = self::testTemporaryDirectory($tmp_path); if (!$is_ok) { // We can't find anywhere to write the cache, so just bail. return null; } } $tmp_name = 'setup-'.$pid_basis; if ($epoch_basis) { $tmp_name .= '.'.$epoch_basis; } $tmp_name .= '.cache'; return $tmp_path.DIRECTORY_SEPARATOR.$tmp_name; }
@task setup
getSetupCacheDiskCachePath
php
phorgeit/phorge
src/applications/cache/PhabricatorCaches.php
https://github.com/phorgeit/phorge/blob/master/src/applications/cache/PhabricatorCaches.php
Apache-2.0
public static function maybeDeflateData($value) { $len = strlen($value); if ($len <= 1024) { return null; } if (!function_exists('gzdeflate')) { return null; } $deflated = gzdeflate($value); if ($deflated === false) { return null; } $deflated_len = strlen($deflated); if ($deflated_len >= ($len / 2)) { return null; } return $deflated; }
Deflate a value, if deflation is available and has an impact. If the value is larger than 1KB, we have `gzdeflate()`, we successfully can deflate it, and it benefits from deflation, we deflate it. Otherwise we leave it as-is. Data can later be inflated with @{method:inflateData}. @param string $value String to attempt to deflate. @return string|null Deflated string, or null if it was not deflated. @task compress
maybeDeflateData
php
phorgeit/phorge
src/applications/cache/PhabricatorCaches.php
https://github.com/phorgeit/phorge/blob/master/src/applications/cache/PhabricatorCaches.php
Apache-2.0
public static function inflateData($value) { if (!function_exists('gzinflate')) { throw new Exception( pht( '%s is not available; unable to read deflated data!', 'gzinflate()')); } $value = gzinflate($value); if ($value === false) { throw new Exception(pht('Failed to inflate data!')); } return $value; }
Inflate data previously deflated by @{method:maybeDeflateData}. @param string $value Deflated data, from @{method:maybeDeflateData}. @return string Original, uncompressed data. @task compress
inflateData
php
phorgeit/phorge
src/applications/cache/PhabricatorCaches.php
https://github.com/phorgeit/phorge/blob/master/src/applications/cache/PhabricatorCaches.php
Apache-2.0
public static function loadLocks($owner_phid) { return id(new DrydockSlotLock())->loadAllWhere( 'ownerPHID = %s', $owner_phid); }
Load all locks held by a particular owner. @param string $owner_phid Owner PHID. @return list<DrydockSlotLock> All held locks. @task info
loadLocks
php
phorgeit/phorge
src/applications/drydock/storage/DrydockSlotLock.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockSlotLock.php
Apache-2.0
public static function isLockFree($lock) { return self::areLocksFree(array($lock)); }
Test if a lock is currently free. @param string $lock Lock key to test. @return bool True if the lock is currently free. @task info
isLockFree
php
phorgeit/phorge
src/applications/drydock/storage/DrydockSlotLock.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockSlotLock.php
Apache-2.0
public static function areLocksFree(array $locks) { $lock_map = self::loadHeldLocks($locks); return !$lock_map; }
Test if a list of locks are all currently free. @param list<string> $locks List of lock keys to test. @return bool True if all locks are currently free. @task info
areLocksFree
php
phorgeit/phorge
src/applications/drydock/storage/DrydockSlotLock.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockSlotLock.php
Apache-2.0
public static function releaseLocks($owner_phid) { $table = new DrydockSlotLock(); $conn_w = $table->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE ownerPHID = %s', $table->getTableName(), $owner_phid); }
Release all locks held by an owner. @param string $owner_phid Lock owner PHID. @return void @task locks
releaseLocks
php
phorgeit/phorge
src/applications/drydock/storage/DrydockSlotLock.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockSlotLock.php
Apache-2.0
public function setReleaseOnDestruction($release) { $this->releaseOnDestruction = $release; return $this; }
Flag this lease to be released when its destructor is called. This is mostly useful if you have a script which acquires, uses, and then releases a lease, as you don't need to explicitly handle exceptions to properly release the lease.
setReleaseOnDestruction
php
phorgeit/phorge
src/applications/drydock/storage/DrydockLease.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockLease.php
Apache-2.0
public function awakenTasks() { $awaken_ids = $this->getAttribute('internal.awakenTaskIDs'); if (is_array($awaken_ids) && $awaken_ids) { PhabricatorWorker::awakenTaskIDs($awaken_ids); } return $this; }
Awaken yielded tasks after a state change. @return $this
awakenTasks
php
phorgeit/phorge
src/applications/drydock/storage/DrydockLease.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockLease.php
Apache-2.0
public function canEverAllocateResourceForLease(DrydockLease $lease) { return $this->getImplementation()->canEverAllocateResourceForLease( $this, $lease); }
@task resource
canEverAllocateResourceForLease
php
phorgeit/phorge
src/applications/drydock/storage/DrydockBlueprint.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockBlueprint.php
Apache-2.0
public function canAllocateResourceForLease(DrydockLease $lease) { return $this->getImplementation()->canAllocateResourceForLease( $this, $lease); }
@task resource
canAllocateResourceForLease
php
phorgeit/phorge
src/applications/drydock/storage/DrydockBlueprint.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockBlueprint.php
Apache-2.0
public function allocateResource(DrydockLease $lease) { return $this->getImplementation()->allocateResource( $this, $lease); }
@task resource
allocateResource
php
phorgeit/phorge
src/applications/drydock/storage/DrydockBlueprint.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockBlueprint.php
Apache-2.0
public function activateResource(DrydockResource $resource) { return $this->getImplementation()->activateResource( $this, $resource); }
@task resource
activateResource
php
phorgeit/phorge
src/applications/drydock/storage/DrydockBlueprint.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockBlueprint.php
Apache-2.0
public function destroyResource(DrydockResource $resource) { $this->getImplementation()->destroyResource( $this, $resource); return $this; }
@task resource
destroyResource
php
phorgeit/phorge
src/applications/drydock/storage/DrydockBlueprint.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockBlueprint.php
Apache-2.0
public function getResourceName(DrydockResource $resource) { return $this->getImplementation()->getResourceName( $this, $resource); }
@task resource
getResourceName
php
phorgeit/phorge
src/applications/drydock/storage/DrydockBlueprint.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockBlueprint.php
Apache-2.0
public function canAcquireLeaseOnResource( DrydockResource $resource, DrydockLease $lease) { return $this->getImplementation()->canAcquireLeaseOnResource( $this, $resource, $lease); }
@task lease
canAcquireLeaseOnResource
php
phorgeit/phorge
src/applications/drydock/storage/DrydockBlueprint.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockBlueprint.php
Apache-2.0
public function acquireLease( DrydockResource $resource, DrydockLease $lease) { return $this->getImplementation()->acquireLease( $this, $resource, $lease); }
@task lease
acquireLease
php
phorgeit/phorge
src/applications/drydock/storage/DrydockBlueprint.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockBlueprint.php
Apache-2.0
public function activateLease( DrydockResource $resource, DrydockLease $lease) { return $this->getImplementation()->activateLease( $this, $resource, $lease); }
@task lease
activateLease
php
phorgeit/phorge
src/applications/drydock/storage/DrydockBlueprint.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockBlueprint.php
Apache-2.0
public function didReleaseLease( DrydockResource $resource, DrydockLease $lease) { $this->getImplementation()->didReleaseLease( $this, $resource, $lease); return $this; }
@task lease
didReleaseLease
php
phorgeit/phorge
src/applications/drydock/storage/DrydockBlueprint.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockBlueprint.php
Apache-2.0
public function destroyLease( DrydockResource $resource, DrydockLease $lease) { $this->getImplementation()->destroyLease( $this, $resource, $lease); return $this; }
@task lease
destroyLease
php
phorgeit/phorge
src/applications/drydock/storage/DrydockBlueprint.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/storage/DrydockBlueprint.php
Apache-2.0
public function activateLease( DrydockBlueprint $blueprint, DrydockResource $resource, DrydockLease $lease) { throw new PhutilMethodNotImplementedException(); }
@return void @task lease
activateLease
php
phorgeit/phorge
src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
Apache-2.0
public function shouldAllocateSupplementalResource( DrydockBlueprint $blueprint, DrydockResource $resource, DrydockLease $lease) { return false; }
Return true to try to allocate a new resource and expand the resource pool instead of permitting an otherwise valid acquisition on an existing resource. This allows the blueprint to provide a soft hint about when the resource pool should grow. Returning "true" in all cases generally makes sense when a blueprint controls a fixed pool of resources, like a particular number of physical hosts: you want to put all the hosts in service, so whenever it is possible to allocate a new host you want to do this. Returning "false" in all cases generally make sense when a blueprint has a flexible pool of expensive resources and you want to pack leases onto them as tightly as possible. @param DrydockBlueprint $blueprint The blueprint for an existing resource being acquired. @param DrydockResource $resource The resource being acquired, which we may want to build a supplemental resource for. @param DrydockLease $lease The current lease performing acquisition. @return bool True to prefer allocating a supplemental resource. @task lease
shouldAllocateSupplementalResource
php
phorgeit/phorge
src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
Apache-2.0
public function activateResource( DrydockBlueprint $blueprint, DrydockResource $resource) { throw new PhutilMethodNotImplementedException(); }
@task resource
activateResource
php
phorgeit/phorge
src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
Apache-2.0
public static function getAllForAllocatingLease( DrydockLease $lease) { $impls = self::getAllBlueprintImplementations(); $keep = array(); foreach ($impls as $key => $impl) { // Don't use disabled blueprint types. if (!$impl->isEnabled()) { continue; } // Don't use blueprint types which can't allocate the correct kind of // resource. if ($impl->getType() != $lease->getResourceType()) { continue; } if (!$impl->canAnyBlueprintEverAllocateResourceForLease($lease)) { continue; } $keep[$key] = $impl; } return $keep; }
Get all the @{class:DrydockBlueprintImplementation}s which can possibly build a resource to satisfy a lease. This method returns blueprints which might, at some time, be able to build a resource which can satisfy the lease. They may not be able to build that resource right now. @param DrydockLease $lease Requested lease. @return list<DrydockBlueprintImplementation> List of qualifying blueprint implementations.
getAllForAllocatingLease
php
phorgeit/phorge
src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
Apache-2.0
protected function shouldUseConcurrentResourceLimit() { return false; }
Does this implementation use concurrent resource limits? Implementations can override this method to opt into standard limit behavior, which provides a simple concurrent resource limit. @return bool True to use limits.
shouldUseConcurrentResourceLimit
php
phorgeit/phorge
src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
Apache-2.0
protected function getConcurrentResourceLimit(DrydockBlueprint $blueprint) { if ($this->shouldUseConcurrentResourceLimit()) { $limit = $blueprint->getFieldValue('allocator.limit'); $limit = (int)$limit; if ($limit > 0) { return $limit; } else { return null; } } return null; }
Get the effective concurrent resource limit for this blueprint. @param DrydockBlueprint $blueprint Blueprint to get the limit for. @return int|null Limit, or `null` for no limit.
getConcurrentResourceLimit
php
phorgeit/phorge
src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
Apache-2.0
protected function shouldLimitAllocatingPoolSize( DrydockBlueprint $blueprint) { // Limit on total number of active resources. $total_limit = $this->getConcurrentResourceLimit($blueprint); if ($total_limit === null) { return false; } $resource = new DrydockResource(); $conn = $resource->establishConnection('r'); $counts = queryfx_all( $conn, 'SELECT status, COUNT(*) N FROM %R WHERE blueprintPHID = %s AND status != %s GROUP BY status', $resource, $blueprint->getPHID(), DrydockResourceStatus::STATUS_DESTROYED); $counts = ipull($counts, 'N', 'status'); $n_alloc = idx($counts, DrydockResourceStatus::STATUS_PENDING, 0); $n_active = idx($counts, DrydockResourceStatus::STATUS_ACTIVE, 0); $n_broken = idx($counts, DrydockResourceStatus::STATUS_BROKEN, 0); $n_released = idx($counts, DrydockResourceStatus::STATUS_RELEASED, 0); // If we're at the limit on total active resources, limit additional // allocations. $n_total = ($n_alloc + $n_active + $n_broken + $n_released); if ($n_total >= $total_limit) { return true; } return false; }
Apply standard limits on resource allocation rate. @param DrydockBlueprint $blueprint The blueprint requesting an allocation. @return bool True if further allocations should be limited.
shouldLimitAllocatingPoolSize
php
phorgeit/phorge
src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
Apache-2.0
private function handleUpdate(DrydockLease $lease) { try { $this->updateLease($lease); } catch (DrydockAcquiredBrokenResourceException $ex) { // If this lease acquired a resource but failed to activate, we don't // need to break the lease. We can throw it back in the pool and let // it take another shot at acquiring a new resource. // Before we throw it back, release any locks the lease is holding. DrydockSlotLock::releaseLocks($lease->getPHID()); $lease ->setStatus(DrydockLeaseStatus::STATUS_PENDING) ->setResourcePHID(null) ->save(); $lease->logEvent( DrydockLeaseReacquireLogType::LOGCONST, array( 'class' => get_class($ex), 'message' => $ex->getMessage(), )); $this->yieldLease($lease, $ex); } catch (Exception $ex) { if ($this->isTemporaryException($ex)) { $this->yieldLease($lease, $ex); } else { $this->breakLease($lease, $ex); } } }
@task update
handleUpdate
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function updateLease(DrydockLease $lease) { $this->processLeaseCommands($lease); $lease_status = $lease->getStatus(); switch ($lease_status) { case DrydockLeaseStatus::STATUS_PENDING: $this->executeAllocator($lease); break; case DrydockLeaseStatus::STATUS_ACQUIRED: $this->activateLease($lease); break; case DrydockLeaseStatus::STATUS_ACTIVE: // Nothing to do. break; case DrydockLeaseStatus::STATUS_RELEASED: case DrydockLeaseStatus::STATUS_BROKEN: $this->destroyLease($lease); break; case DrydockLeaseStatus::STATUS_DESTROYED: break; } $this->yieldIfExpiringLease($lease); }
@task update
updateLease
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function yieldLease(DrydockLease $lease, Exception $ex) { $duration = $this->getYieldDurationFromException($ex); $lease->logEvent( DrydockLeaseActivationYieldLogType::LOGCONST, array( 'duration' => $duration, )); throw new PhabricatorWorkerYieldException($duration); }
@task update
yieldLease
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function processLeaseCommand( DrydockLease $lease, DrydockCommand $command) { switch ($command->getCommand()) { case DrydockCommand::COMMAND_RELEASE: $this->releaseLease($lease); break; } }
@task command
processLeaseCommand
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function executeAllocator(DrydockLease $lease) { $blueprints = $this->loadBlueprintsForAllocatingLease($lease); // If we get nothing back, that means no blueprint is defined which can // ever build the requested resource. This is a permanent failure, since // we don't expect to succeed no matter how many times we try. if (!$blueprints) { throw new PhabricatorWorkerPermanentFailureException( pht( 'No active Drydock blueprint exists which can ever allocate a '. 'resource for lease "%s".', $lease->getPHID())); } // First, try to find a suitable open resource which we can acquire a new // lease on. $resources = $this->loadAcquirableResourcesForLease($blueprints, $lease); list($free_resources, $used_resources) = $this->partitionResources( $lease, $resources); $resource = $this->leaseAnyResource($lease, $free_resources); if ($resource) { return $resource; } // We're about to try creating a resource. If we're already creating // something, just yield until that resolves. $this->yieldForPendingResources($lease); // We haven't been able to lease an existing resource yet, so now we try to // create one. We may still have some less-desirable "used" resources that // we'll sometimes try to lease later if we fail to allocate a new resource. $resource = $this->newLeasedResource($lease, $blueprints); if ($resource) { return $resource; } // We haven't been able to lease a desirable "free" resource or create a // new resource. Try to lease a "used" resource. $resource = $this->leaseAnyResource($lease, $used_resources); if ($resource) { return $resource; } // If this lease has already triggered a reclaim, just yield and wait for // it to resolve. $this->yieldForReclaimingResources($lease); // Try to reclaim a resource. This will yield if it reclaims something. $this->reclaimAnyResource($lease, $blueprints); // We weren't able to lease, create, or reclaim any resources. We just have // to wait for resources to become available. $lease->logEvent( DrydockLeaseWaitingForResourcesLogType::LOGCONST, array( 'blueprintPHIDs' => mpull($blueprints, 'getPHID'), )); throw new PhabricatorWorkerYieldException(15); }
Find or build a resource which can satisfy a given lease request, then acquire the lease. @param DrydockLease $lease Requested lease. @return void @task allocator
executeAllocator
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function loadBlueprintsForAllocatingLease( DrydockLease $lease) { $viewer = $this->getViewer(); $impls = DrydockBlueprintImplementation::getAllForAllocatingLease($lease); if (!$impls) { return array(); } $blueprint_phids = $lease->getAllowedBlueprintPHIDs(); if (!$blueprint_phids) { $lease->logEvent(DrydockLeaseNoBlueprintsLogType::LOGCONST); return array(); } $query = id(new DrydockBlueprintQuery()) ->setViewer($viewer) ->withPHIDs($blueprint_phids) ->withBlueprintClasses(array_keys($impls)) ->withDisabled(false); // The Drydock application itself is allowed to authorize anything. This // is primarily used for leases generated by CLI administrative tools. $drydock_phid = id(new PhabricatorDrydockApplication())->getPHID(); $authorizing_phid = $lease->getAuthorizingPHID(); if ($authorizing_phid != $drydock_phid) { $blueprints = id(clone $query) ->withAuthorizedPHIDs(array($authorizing_phid)) ->execute(); if (!$blueprints) { // If we didn't hit any blueprints, check if this is an authorization // problem: re-execute the query without the authorization constraint. // If the second query hits blueprints, the overall configuration is // fine but this is an authorization problem. If the second query also // comes up blank, this is some other kind of configuration issue so // we fall through to the default pathway. $all_blueprints = $query->execute(); if ($all_blueprints) { $lease->logEvent( DrydockLeaseNoAuthorizationsLogType::LOGCONST, array( 'authorizingPHID' => $authorizing_phid, )); return array(); } } } else { $blueprints = $query->execute(); } $keep = array(); foreach ($blueprints as $key => $blueprint) { if (!$blueprint->canEverAllocateResourceForLease($lease)) { continue; } $keep[$key] = $blueprint; } return $keep; }
Get all the concrete @{class:DrydockBlueprint}s which can possibly build a resource to satisfy a lease. @param DrydockLease $lease Requested lease. @return list<DrydockBlueprint> List of qualifying blueprints. @task allocator
loadBlueprintsForAllocatingLease
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function loadAcquirableResourcesForLease( array $blueprints, DrydockLease $lease) { assert_instances_of($blueprints, 'DrydockBlueprint'); $viewer = $this->getViewer(); $resources = id(new DrydockResourceQuery()) ->setViewer($viewer) ->withBlueprintPHIDs(mpull($blueprints, 'getPHID')) ->withTypes(array($lease->getResourceType())) ->withStatuses( array( DrydockResourceStatus::STATUS_ACTIVE, )) ->execute(); return $this->removeUnacquirableResources($resources, $lease); }
Load a list of all resources which a given lease can possibly be allocated against. @param list<DrydockBlueprint> $blueprints Blueprints which may produce suitable resources. @param DrydockLease $lease Requested lease. @return list<DrydockResource> Resources which may be able to allocate the lease. @task allocator
loadAcquirableResourcesForLease
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function removeOverallocatedBlueprints( array $blueprints, DrydockLease $lease) { assert_instances_of($blueprints, 'DrydockBlueprint'); $keep = array(); foreach ($blueprints as $key => $blueprint) { if (!$blueprint->canAllocateResourceForLease($lease)) { continue; } $keep[$key] = $blueprint; } return $keep; }
Remove blueprints which are too heavily allocated to build a resource for a lease from a list of blueprints. @param list<DrydockBlueprint> $blueprints List of blueprints. @return list<DrydockBlueprint> $lease List with blueprints that can not allocate a resource for the lease right now removed. @task allocator
removeOverallocatedBlueprints
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function rankBlueprints(array $blueprints, DrydockLease $lease) { assert_instances_of($blueprints, 'DrydockBlueprint'); // TODO: Implement improvements to this ranking algorithm if they become // available. shuffle($blueprints); return $blueprints; }
Rank blueprints by suitability for building a new resource for a particular lease. @param list<DrydockBlueprint> $blueprints List of blueprints. @param DrydockLease $lease Requested lease. @return list<DrydockBlueprint> Ranked list of blueprints. @task allocator
rankBlueprints
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function rankResources(array $resources, DrydockLease $lease) { assert_instances_of($resources, 'DrydockResource'); // TODO: Implement improvements to this ranking algorithm if they become // available. shuffle($resources); return $resources; }
Rank resources by suitability for allocating a particular lease. @param list<DrydockResource> $resources List of resources. @param DrydockLease $lease Requested lease. @return list<DrydockResource> Ranked list of resources. @task allocator
rankResources
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function allocateResource( DrydockBlueprint $blueprint, DrydockLease $lease) { $resource = $blueprint->allocateResource($lease); $this->validateAllocatedResource($blueprint, $resource, $lease); // If this resource was allocated as a pending resource, queue a task to // activate it. if ($resource->getStatus() == DrydockResourceStatus::STATUS_PENDING) { $lease->addAllocatedResourcePHIDs( array( $resource->getPHID(), )); $lease->save(); PhabricatorWorker::scheduleTask( 'DrydockResourceUpdateWorker', array( 'resourcePHID' => $resource->getPHID(), // This task will generally yield while the resource activates, so // wake it back up once the resource comes online. Most of the time, // we'll be able to lease the newly activated resource. 'awakenOnActivation' => array( $this->getCurrentWorkerTaskID(), ), ), array( 'objectPHID' => $resource->getPHID(), )); } return $resource; }
Perform an actual resource allocation with a particular blueprint. @param DrydockBlueprint $blueprint The blueprint to allocate a resource from. @param DrydockLease $lease Requested lease. @return DrydockResource Allocated resource. @task allocator
allocateResource
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function validateAllocatedResource( DrydockBlueprint $blueprint, $resource, DrydockLease $lease) { if (!($resource instanceof DrydockResource)) { throw new Exception( pht( 'Blueprint "%s" (of type "%s") is not properly implemented: %s must '. 'return an object of type %s or throw, but returned something else.', $blueprint->getBlueprintName(), $blueprint->getClassName(), 'allocateResource()', 'DrydockResource')); } if (!$resource->isAllocatedResource()) { throw new Exception( pht( 'Blueprint "%s" (of type "%s") is not properly implemented: %s '. 'must actually allocate the resource it returns.', $blueprint->getBlueprintName(), $blueprint->getClassName(), 'allocateResource()')); } $resource_type = $resource->getType(); $lease_type = $lease->getResourceType(); if ($resource_type !== $lease_type) { throw new Exception( pht( 'Blueprint "%s" (of type "%s") is not properly implemented: it '. 'built a resource of type "%s" to satisfy a lease requesting a '. 'resource of type "%s".', $blueprint->getBlueprintName(), $blueprint->getClassName(), $resource_type, $lease_type)); } }
Check that the resource a blueprint allocated is roughly the sort of object we expect. @param DrydockBlueprint $blueprint Blueprint which built the resource. @param wild $resource Thing which the blueprint claims is a valid resource. @param DrydockLease $lease Lease the resource was allocated for. @return void @task allocator
validateAllocatedResource
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function acquireLease( DrydockResource $resource, DrydockLease $lease) { $blueprint = $resource->getBlueprint(); $blueprint->acquireLease($resource, $lease); $this->validateAcquiredLease($blueprint, $resource, $lease); // If this lease has been acquired but not activated, queue a task to // activate it. if ($lease->getStatus() == DrydockLeaseStatus::STATUS_ACQUIRED) { $this->queueTask( __CLASS__, array( 'leasePHID' => $lease->getPHID(), ), array( 'objectPHID' => $lease->getPHID(), )); } }
Perform an actual lease acquisition on a particular resource. @param DrydockResource $resource Resource to acquire a lease on. @param DrydockLease $lease Lease to acquire. @return void @task acquire
acquireLease
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function validateAcquiredLease( DrydockBlueprint $blueprint, DrydockResource $resource, DrydockLease $lease) { if (!$lease->isAcquiredLease()) { throw new Exception( pht( 'Blueprint "%s" (of type "%s") is not properly implemented: it '. 'returned from "%s" without acquiring a lease.', $blueprint->getBlueprintName(), $blueprint->getClassName(), 'acquireLease()')); } $lease_phid = $lease->getResourcePHID(); $resource_phid = $resource->getPHID(); if ($lease_phid !== $resource_phid) { throw new Exception( pht( 'Blueprint "%s" (of type "%s") is not properly implemented: it '. 'returned from "%s" with a lease acquired on the wrong resource.', $blueprint->getBlueprintName(), $blueprint->getClassName(), 'acquireLease()')); } }
Make sure that a lease was really acquired properly. @param DrydockBlueprint $blueprint Blueprint which created the resource. @param DrydockResource $resource Resource which was acquired. @param DrydockLease $lease The lease which was supposedly acquired. @return void @task acquire
validateAcquiredLease
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function activateLease(DrydockLease $lease) { $resource = $lease->getResource(); if (!$resource) { throw new Exception( pht('Trying to activate lease with no resource.')); } $resource_status = $resource->getStatus(); if ($resource_status == DrydockResourceStatus::STATUS_PENDING) { throw new PhabricatorWorkerYieldException(15); } if ($resource_status != DrydockResourceStatus::STATUS_ACTIVE) { throw new DrydockAcquiredBrokenResourceException( pht( 'Trying to activate lease ("%s") on a resource ("%s") in '. 'the wrong status ("%s").', $lease->getPHID(), $resource->getPHID(), $resource_status)); } // NOTE: We can race resource destruction here. Between the time we // performed the read above and now, the resource might have closed, so // we may activate leases on dead resources. At least for now, this seems // fine: a resource dying right before we activate a lease on it should not // be distinguishable from a resource dying right after we activate a lease // on it. We end up with an active lease on a dead resource either way, and // can not prevent resources dying from lightning strikes. $blueprint = $resource->getBlueprint(); $blueprint->activateLease($resource, $lease); $this->validateActivatedLease($blueprint, $resource, $lease); }
@task activate
activateLease
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function validateActivatedLease( DrydockBlueprint $blueprint, DrydockResource $resource, DrydockLease $lease) { if (!$lease->isActivatedLease()) { throw new Exception( pht( 'Blueprint "%s" (of type "%s") is not properly implemented: it '. 'returned from "%s" without activating a lease.', $blueprint->getBlueprintName(), $blueprint->getClassName(), 'acquireLease()')); } }
@task activate
validateActivatedLease
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function releaseLease(DrydockLease $lease) { $lease ->setStatus(DrydockLeaseStatus::STATUS_RELEASED) ->save(); $lease->logEvent(DrydockLeaseReleasedLogType::LOGCONST); $resource = $lease->getResource(); if ($resource) { $blueprint = $resource->getBlueprint(); $blueprint->didReleaseLease($resource, $lease); } $this->destroyLease($lease); }
@task release
releaseLease
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
protected function breakLease(DrydockLease $lease, Exception $ex) { switch ($lease->getStatus()) { case DrydockLeaseStatus::STATUS_BROKEN: case DrydockLeaseStatus::STATUS_RELEASED: case DrydockLeaseStatus::STATUS_DESTROYED: throw new Exception( pht( 'Unexpected failure while destroying lease ("%s").', $lease->getPHID()), 0, $ex); } $lease ->setStatus(DrydockLeaseStatus::STATUS_BROKEN) ->save(); $lease->logEvent( DrydockLeaseActivationFailureLogType::LOGCONST, array( 'class' => get_class($ex), 'message' => $ex->getMessage(), )); $lease->awakenTasks(); $this->queueTask( __CLASS__, array( 'leasePHID' => $lease->getPHID(), ), array( 'objectPHID' => $lease->getPHID(), )); throw new PhabricatorWorkerPermanentFailureException( pht( 'Permanent failure while activating lease ("%s"): %s', $lease->getPHID(), $ex->getMessage())); }
@task break
breakLease
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function destroyLease(DrydockLease $lease) { $resource = $lease->getResource(); if ($resource) { $blueprint = $resource->getBlueprint(); $blueprint->destroyLease($resource, $lease); } DrydockSlotLock::releaseLocks($lease->getPHID()); $lease ->setStatus(DrydockLeaseStatus::STATUS_DESTROYED) ->save(); $lease->logEvent(DrydockLeaseDestroyedLogType::LOGCONST); $lease->awakenTasks(); }
@task destroy
destroyLease
php
phorgeit/phorge
src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php
Apache-2.0
private function handleUpdate(DrydockResource $resource) { try { $this->updateResource($resource); } catch (Exception $ex) { if ($this->isTemporaryException($ex)) { $this->yieldResource($resource, $ex); } else { $this->breakResource($resource, $ex); } } }
Update a resource, handling exceptions thrown during the update. @param DrydockResource $resource Resource to update. @return void @task update
handleUpdate
php
phorgeit/phorge
src/applications/drydock/worker/DrydockResourceUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockResourceUpdateWorker.php
Apache-2.0
private function updateResource(DrydockResource $resource) { $this->processResourceCommands($resource); $resource_status = $resource->getStatus(); switch ($resource_status) { case DrydockResourceStatus::STATUS_PENDING: $this->activateResource($resource); break; case DrydockResourceStatus::STATUS_ACTIVE: // Nothing to do. break; case DrydockResourceStatus::STATUS_RELEASED: case DrydockResourceStatus::STATUS_BROKEN: $this->destroyResource($resource); break; case DrydockResourceStatus::STATUS_DESTROYED: // Nothing to do. break; } $this->yieldIfExpiringResource($resource); }
Update a resource. @param DrydockResource $resource Resource to update. @return void @task update
updateResource
php
phorgeit/phorge
src/applications/drydock/worker/DrydockResourceUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockResourceUpdateWorker.php
Apache-2.0
private function yieldResource(DrydockResource $resource, Exception $ex) { $duration = $this->getYieldDurationFromException($ex); $resource->logEvent( DrydockResourceActivationYieldLogType::LOGCONST, array( 'duration' => $duration, )); throw new PhabricatorWorkerYieldException($duration); }
Convert a temporary exception into a yield. @param DrydockResource $resource Resource to yield. @param Exception $ex Temporary exception worker encountered. @task update
yieldResource
php
phorgeit/phorge
src/applications/drydock/worker/DrydockResourceUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockResourceUpdateWorker.php
Apache-2.0
private function processResourceCommand( DrydockResource $resource, DrydockCommand $command) { switch ($command->getCommand()) { case DrydockCommand::COMMAND_RELEASE: $this->releaseResource($resource, null); break; case DrydockCommand::COMMAND_RECLAIM: $reclaimer_phid = $command->getAuthorPHID(); $this->releaseResource($resource, $reclaimer_phid); break; } // If the command specifies that other worker tasks should be awakened // after it executes, awaken them now. $awaken_ids = $command->getProperty('awakenTaskIDs'); if (is_array($awaken_ids) && $awaken_ids) { PhabricatorWorker::awakenTaskIDs($awaken_ids); } }
@task command
processResourceCommand
php
phorgeit/phorge
src/applications/drydock/worker/DrydockResourceUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockResourceUpdateWorker.php
Apache-2.0
private function activateResource(DrydockResource $resource) { $blueprint = $resource->getBlueprint(); $blueprint->activateResource($resource); $this->validateActivatedResource($blueprint, $resource); $awaken_ids = $this->getTaskDataValue('awakenOnActivation'); if (is_array($awaken_ids) && $awaken_ids) { PhabricatorWorker::awakenTaskIDs($awaken_ids); } }
@task activate
activateResource
php
phorgeit/phorge
src/applications/drydock/worker/DrydockResourceUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockResourceUpdateWorker.php
Apache-2.0
private function validateActivatedResource( DrydockBlueprint $blueprint, DrydockResource $resource) { if (!$resource->isActivatedResource()) { throw new Exception( pht( 'Blueprint "%s" (of type "%s") is not properly implemented: %s '. 'must actually allocate the resource it returns.', $blueprint->getBlueprintName(), $blueprint->getClassName(), 'allocateResource()')); } }
@task activate
validateActivatedResource
php
phorgeit/phorge
src/applications/drydock/worker/DrydockResourceUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockResourceUpdateWorker.php
Apache-2.0
private function breakResource(DrydockResource $resource, Exception $ex) { switch ($resource->getStatus()) { case DrydockResourceStatus::STATUS_BROKEN: case DrydockResourceStatus::STATUS_RELEASED: case DrydockResourceStatus::STATUS_DESTROYED: // If the resource was already broken, just throw a normal exception. // This will retry the task eventually. throw new Exception( pht( 'Unexpected failure while destroying resource ("%s").', $resource->getPHID()), 0, $ex); } $resource ->setStatus(DrydockResourceStatus::STATUS_BROKEN) ->save(); $resource->scheduleUpdate(); $resource->logEvent( DrydockResourceActivationFailureLogType::LOGCONST, array( 'class' => get_class($ex), 'message' => $ex->getMessage(), )); throw new PhabricatorWorkerPermanentFailureException( pht( 'Permanent failure while activating resource ("%s"): %s', $resource->getPHID(), $ex->getMessage())); }
@task break
breakResource
php
phorgeit/phorge
src/applications/drydock/worker/DrydockResourceUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockResourceUpdateWorker.php
Apache-2.0
private function destroyResource(DrydockResource $resource) { $blueprint = $resource->getBlueprint(); $blueprint->destroyResource($resource); DrydockSlotLock::releaseLocks($resource->getPHID()); $resource ->setStatus(DrydockResourceStatus::STATUS_DESTROYED) ->save(); }
@task destroy
destroyResource
php
phorgeit/phorge
src/applications/drydock/worker/DrydockResourceUpdateWorker.php
https://github.com/phorgeit/phorge/blob/master/src/applications/drydock/worker/DrydockResourceUpdateWorker.php
Apache-2.0
public function loadLastModifiedCommitID($commit_id, $path_id, $time = 0.5) { $commit_id = (int)$commit_id; $path_id = (int)$path_id; $bucket_data = null; $data_key = null; $seen = array(); $t_start = microtime(true); $iterations = 0; while (true) { $bucket_key = $this->getBucketKey($commit_id); if (($data_key != $bucket_key) || $bucket_data === null) { $bucket_data = $this->getBucketData($bucket_key); $data_key = $bucket_key; } if (empty($bucket_data[$commit_id])) { // Rebuild the cache bucket, since the commit might be a very recent // one that we'll pick up by rebuilding. $bucket_data = $this->getBucketData($bucket_key, $bucket_data); if (empty($bucket_data[$commit_id])) { // A rebuild didn't help. This can occur legitimately if the commit // is new and hasn't parsed yet. return false; } // Otherwise, the rebuild gave us the data, so we can keep going. $did_fill = true; } else { $did_fill = false; } // Sanity check so we can survive and recover from bad data. if (isset($seen[$commit_id])) { phlog(pht('Unexpected infinite loop in %s!', __CLASS__)); return false; } else { $seen[$commit_id] = true; } // `$data` is a list: the commit's parent IDs, followed by `null`, // followed by the modified paths in ascending order. We figure out the // first parent first, then check if the path was touched. If the path // was touched, this is the commit we're after. If not, walk backward // in the tree. $items = $bucket_data[$commit_id]; $size = count($items); // Walk past the parent information. $parent_id = null; for ($ii = 0;; ++$ii) { if ($items[$ii] === null) { break; } if ($parent_id === null) { $parent_id = $items[$ii]; } } // Look for a modification to the path. for (; $ii < $size; ++$ii) { $item = $items[$ii]; if ($item > $path_id) { break; } if ($item === $path_id) { return $commit_id; } } if ($parent_id) { $commit_id = $parent_id; // Periodically check if we've spent too long looking for a result // in the cache, and return so we can fall back to a VCS operation. // This keeps us from having a degenerate worst case if, e.g., the // cache is cold and we need to inspect a very large number of blocks // to satisfy the query. ++$iterations; // If we performed a cache fill in this cycle, always check the time // limit, since cache fills may take a significant amount of time. if ($did_fill || ($iterations % 64 === 0)) { $t_end = microtime(true); if (($t_end - $t_start) > $time) { return false; } } continue; } // If we have an explicit 0, that means this commit really has no parents. // Usually, it is the first commit in the repository. if ($parent_id === 0) { return null; } // If we didn't find a parent, the parent data isn't available. We fail // to find an answer in the cache and fall back to querying the VCS. return false; } }
Search the graph cache for the most modification to a path. @param int $commit_id The commit ID to search ancestors of. @param int $path_id The path ID to search for changes to. @param float $time Maximum number of seconds to spend trying to satisfy this query using the graph cache. By default `0.5` (500ms). @return mixed Commit ID, or `null` if no ancestors exist, or `false` if the graph cache was unable to determine the answer. @task query
loadLastModifiedCommitID
php
phorgeit/phorge
src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php
Apache-2.0
private function getBucketKey($commit_id) { return (int)floor($commit_id / $this->getBucketSize()); }
Get the bucket key for a given commit ID. @param int $commit_id Commit ID. @return int Bucket key. @task cache
getBucketKey
php
phorgeit/phorge
src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php
Apache-2.0
private function getBucketCacheKey($bucket_key) { static $prefix; if ($prefix === null) { $self = get_class($this); $size = $this->getBucketSize(); $prefix = "{$self}:{$size}:2:"; } return $prefix.$bucket_key; }
Get the cache key for a given bucket key (from @{method:getBucketKey}). @param int $bucket_key Bucket key. @return string Cache key. @task cache
getBucketCacheKey
php
phorgeit/phorge
src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php
Apache-2.0
private function getBucketSize() { return 4096; }
Get the number of items per bucket. @return int Number of items to store per bucket. @task cache
getBucketSize
php
phorgeit/phorge
src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php
Apache-2.0
private function getBucketData($bucket_key, $rebuild_data = null) { $cache_key = $this->getBucketCacheKey($bucket_key); // TODO: This cache stuff could be handled more gracefully, but the // database cache currently requires values to be strings and needs // some tweaking to support this as part of a stack. Our cache semantics // here are also unusual (not purely readthrough) because this cache is // appendable. $cache_level1 = PhabricatorCaches::getRepositoryGraphL1Cache(); $cache_level2 = PhabricatorCaches::getRepositoryGraphL2Cache(); if ($rebuild_data === null) { $bucket_data = $cache_level1->getKey($cache_key); if ($bucket_data) { return $bucket_data; } $bucket_data = $cache_level2->getKey($cache_key); if ($bucket_data) { $unserialized = @unserialize($bucket_data); if ($unserialized) { // Fill APC if we got a database hit but missed in APC. $cache_level1->setKey($cache_key, $unserialized); return $unserialized; } } } if (!is_array($rebuild_data)) { $rebuild_data = array(); } $bucket_data = $this->rebuildBucket($bucket_key, $rebuild_data); // Don't bother writing the data if we didn't update anything. if ($bucket_data !== $rebuild_data) { $cache_level2->setKey($cache_key, serialize($bucket_data)); $cache_level1->setKey($cache_key, $bucket_data); } return $bucket_data; }
Retrieve or build a graph cache bucket from the cache. Normally, this operates as a readthrough cache call. It can also be used to force a cache update by passing the existing data to `$rebuild_data`. @param int $bucket_key Bucket key, from @{method:getBucketKey}. @param mixed $rebuild_data (optional) Current data, to force a cache rebuild of this bucket. @return array Data from the cache. @task cache
getBucketData
php
phorgeit/phorge
src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php
Apache-2.0
public function getCloneName() { $name = $this->getRepositorySlug(); // Make some reasonable effort to produce reasonable default directory // names from repository names. if (!phutil_nonempty_string($name)) { $name = $this->getName(); $name = phutil_utf8_strtolower($name); $name = preg_replace('@[ -/:->]+@', '-', $name); $name = trim($name, '-'); if (!phutil_nonempty_string($name)) { $name = $this->getCallsign(); } } return $name; }
Get the name of the directory this repository should clone or checkout into. For example, if the repository name is "Example Repository", a reasonable name might be "example-repository". This is used to help users get reasonable results when cloning repositories, since they generally do not want to clone into directories called "X/" or "Example Repository/". @return string
getCloneName
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
public static function parseRepositoryServicePath($request_path, $vcs) { $is_git = ($vcs == PhabricatorRepositoryType::REPOSITORY_TYPE_GIT); $patterns = array( '(^'. '(?P<base>/?(?:diffusion|source)/(?P<identifier>[^/]+))'. '(?P<path>.*)'. '\z)', ); $identifier = null; foreach ($patterns as $pattern) { $matches = null; if (!preg_match($pattern, $request_path, $matches)) { continue; } $identifier = $matches['identifier']; if ($is_git) { $identifier = preg_replace('/\\.git\z/', '', $identifier); } $base = $matches['base']; $path = $matches['path']; break; } if ($identifier === null) { return null; } return array( 'identifier' => $identifier, 'base' => $base, 'path' => $path, ); }
@return array|null
parseRepositoryServicePath
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
public function getRemoteURI() { return (string)$this->getRemoteURIObject(); }
Get the remote URI for this repository. @return string @task uri
getRemoteURI
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
public function getRemoteURIEnvelope() { $uri = $this->getRemoteURIObject(); $remote_protocol = $this->getRemoteProtocol(); if ($remote_protocol == 'http' || $remote_protocol == 'https') { // For SVN, we use `--username` and `--password` flags separately, so // don't add any credentials here. if (!$this->isSVN()) { $credential_phid = $this->getCredentialPHID(); if ($credential_phid) { $key = PassphrasePasswordKey::loadFromPHID( $credential_phid, PhabricatorUser::getOmnipotentUser()); $uri->setUser($key->getUsernameEnvelope()->openEnvelope()); $uri->setPass($key->getPasswordEnvelope()->openEnvelope()); } } } return new PhutilOpaqueEnvelope((string)$uri); }
Get the remote URI for this repository, including credentials if they're used by this repository. @return PhutilOpaqueEnvelope URI, possibly including credentials. @task uri
getRemoteURIEnvelope
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
public function getPublicCloneURI() { return (string)$this->getCloneURIObject(); }
Get the clone (or checkout) URI for this repository, without authentication information. @return string Repository URI. @task uri
getPublicCloneURI
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
public function getRemoteProtocol() { $uri = $this->getRemoteURIObject(); return $uri->getProtocol(); }
Get the protocol for the repository's remote. @return string Protocol, like "ssh" or "git". @task uri
getRemoteProtocol
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
public function getRemoteURIObject() { $raw_uri = $this->getDetail('remote-uri'); if (!phutil_nonempty_string($raw_uri)) { return new PhutilURI(''); } if (!strncmp($raw_uri, '/', 1)) { return new PhutilURI('file://'.$raw_uri); } return new PhutilURI($raw_uri); }
Get a parsed object representation of the repository's remote URI.. @return wild A @{class@arcanist:PhutilURI}. @task uri
getRemoteURIObject
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
public function getCloneURIObject() { if (!$this->isHosted()) { if ($this->isSVN()) { // Make sure we pick up the "Import Only" path for Subversion, so // the user clones the repository starting at the correct path, not // from the root. $base_uri = $this->getSubversionBaseURI(); $base_uri = new PhutilURI($base_uri); $path = $base_uri->getPath(); if (!$path) { $path = '/'; } // If the trailing "@" is not required to escape the URI, strip it for // readability. if (!preg_match('/@.*@/', $path)) { $path = rtrim($path, '@'); } $base_uri->setPath($path); return $base_uri; } else { return $this->getRemoteURIObject(); } } // TODO: This should be cleaned up to deal with all the new URI handling. $another_copy = id(new PhabricatorRepositoryQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs(array($this->getPHID())) ->needURIs(true) ->executeOne(); $clone_uris = $another_copy->getCloneURIs(); if (!$clone_uris) { return null; } return head($clone_uris)->getEffectiveURI(); }
Get the "best" clone/checkout URI for this repository, on any protocol.
getCloneURIObject
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
private function isSSHProtocol($protocol) { return ($protocol == 'ssh' || $protocol == 'svn+ssh'); }
Determine if a protocol is SSH or SSH-like. @param string $protocol A protocol string, like "http" or "ssh". @return bool True if the protocol is SSH-like. @task uri
isSSHProtocol
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
private function assertLocalExists() { if (!$this->usesLocalWorkingCopy()) { return; } $local = $this->getLocalPath(); Filesystem::assertExists($local); Filesystem::assertIsDirectory($local); Filesystem::assertReadable($local); }
Raise more useful errors when there are basic filesystem problems.
assertLocalExists
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
public function isWorkingCopyBare() { switch ($this->getVersionControlSystem()) { case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: return false; case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: $local = $this->getLocalPath(); if (Filesystem::pathExists($local.'/.git')) { return false; } else { return true; } } }
Determine if the working copy is bare or not. In Git, this corresponds to `--bare`. In Mercurial, `--noupdate`.
isWorkingCopyBare
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
public function loadUpdateInterval($minimum = 15) { // First, check if we've hit errors recently. If we have, wait one period // for each consecutive error. Normally, this corresponds to a backoff of // 15s, 30s, 45s, etc. $message_table = new PhabricatorRepositoryStatusMessage(); $conn = $message_table->establishConnection('r'); $error_count = queryfx_one( $conn, 'SELECT MAX(messageCount) error_count FROM %T WHERE repositoryID = %d AND statusType IN (%Ls) AND statusCode IN (%Ls)', $message_table->getTableName(), $this->getID(), array( PhabricatorRepositoryStatusMessage::TYPE_INIT, PhabricatorRepositoryStatusMessage::TYPE_FETCH, ), array( PhabricatorRepositoryStatusMessage::CODE_ERROR, )); $error_count = (int)$error_count['error_count']; if ($error_count > 0) { return (int)($minimum * $error_count); } // If a repository is still importing, always pull it as frequently as // possible. This prevents us from hanging for a long time at 99.9% when // importing an inactive repository. if ($this->isImporting()) { return $minimum; } $window_start = (PhabricatorTime::getNow() + $minimum); $table = id(new PhabricatorRepositoryCommit()); $last_commit = queryfx_one( $table->establishConnection('r'), 'SELECT epoch FROM %T WHERE repositoryID = %d AND epoch <= %d ORDER BY epoch DESC LIMIT 1', $table->getTableName(), $this->getID(), $window_start); if ($last_commit) { $time_since_commit = ($window_start - $last_commit['epoch']); } else { // If the repository has no commits, treat the creation date as // though it were the date of the last commit. This makes empty // repositories update quickly at first but slow down over time // if they don't see any activity. $time_since_commit = ($window_start - $this->getDateCreated()); } $last_few_days = phutil_units('3 days in seconds'); if ($time_since_commit <= $last_few_days) { // For repositories with activity in the recent past, we wait one // extra second for every 10 minutes since the last commit. This // shorter backoff is intended to handle weekends and other short // breaks from development. $smart_wait = ($time_since_commit / 600); } else { // For repositories without recent activity, we wait one extra second // for every 4 minutes since the last commit. This longer backoff // handles rarely used repositories, up to the maximum. $smart_wait = ($time_since_commit / 240); } // We'll never wait more than 6 hours to pull a repository. $longest_wait = phutil_units('6 hours in seconds'); $smart_wait = min($smart_wait, $longest_wait); $smart_wait = max($minimum, $smart_wait); return (int)$smart_wait; }
Load the pull frequency for this repository, based on the time since the last activity. We pull rarely used repositories less frequently. This finds the most recent commit which is older than the current time (which prevents us from spinning on repositories with a silly commit post-dated to some time in 2037). We adjust the pull frequency based on when the most recent commit occurred. @param int $minimum (optional) The minimum update interval to use, in seconds. @return int Repository update interval, in seconds.
loadUpdateInterval
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
public function getCopyTimeLimit() { return $this->getDetail('limit.copy'); }
Time limit for cloning or copying this repository. This limit is used to timeout operations like `git clone` or `git fetch` when doing intracluster synchronization, building working copies, etc. @return int Maximum number of seconds to spend copying this repository.
getCopyTimeLimit
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
public function getAlmanacServiceURI( PhabricatorUser $viewer, array $options) { $refs = $this->getAlmanacServiceRefs($viewer, $options); if (!$refs) { return null; } $ref = head($refs); return $ref->getURI(); }
Retrieve the service URI for the device hosting this repository. See @{method:newConduitClient} for a general discussion of interacting with repository services. This method provides lower-level resolution of services, returning raw URIs. @param PhabricatorUser $viewer Viewing user. @param map<string, wild> $options Constraints on selectable services. @return string|null URI, or `null` for local repositories.
getAlmanacServiceURI
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
public function newConduitClient( PhabricatorUser $viewer, $never_proxy = false) { $uri = $this->getAlmanacServiceURI( $viewer, array( 'neverProxy' => $never_proxy, 'protocols' => array( 'http', 'https', ), // At least today, no Conduit call can ever write to a repository, // so it's fine to send anything to a read-only node. 'writable' => false, )); if ($uri === null) { return null; } $domain = id(new PhutilURI(PhabricatorEnv::getURI('/')))->getDomain(); $client = id(new ConduitClient($uri)) ->setHost($domain); if ($viewer->isOmnipotent()) { // If the caller is the omnipotent user (normally, a daemon), we will // sign the request with this host's asymmetric keypair. $public_path = AlmanacKeys::getKeyPath('device.pub'); try { $public_key = Filesystem::readFile($public_path); } catch (Exception $ex) { throw new PhutilAggregateException( pht( 'Unable to read device public key while attempting to make '. 'authenticated method call within the cluster. '. 'Use `%s` to register keys for this device. Exception: %s', 'bin/almanac register', $ex->getMessage()), array($ex)); } $private_path = AlmanacKeys::getKeyPath('device.key'); try { $private_key = Filesystem::readFile($private_path); $private_key = new PhutilOpaqueEnvelope($private_key); } catch (Exception $ex) { throw new PhutilAggregateException( pht( 'Unable to read device private key while attempting to make '. 'authenticated method call within the cluster. '. 'Use `%s` to register keys for this device. Exception: %s', 'bin/almanac register', $ex->getMessage()), array($ex)); } $client->setSigningKeys($public_key, $private_key); } else { // If the caller is a normal user, we generate or retrieve a cluster // API token. $token = PhabricatorConduitToken::loadClusterTokenForUser($viewer); if ($token) { $client->setConduitToken($token->getToken()); } } return $client; }
Build a new Conduit client in order to make a service call to this repository. If the repository is hosted locally, this method may return `null`. The caller should use `ConduitCall` or other local logic to complete the request. By default, we will return a @{class:ConduitClient} for any repository with a service, even if that service is on the current device. We do this because this configuration does not make very much sense in a production context, but is very common in a test/development context (where the developer's machine is both the web host and the repository service). By proxying in development, we get more consistent behavior between development and production, and don't have a major untested codepath. The `$never_proxy` parameter can be used to prevent this local proxying. If the flag is passed: - The method will return `null` (implying a local service call) if the repository service is hosted on the current device. - The method will throw if it would need to return a client. This is used to prevent loops in Conduit: the first request will proxy, even in development, but the second request will be identified as a cluster request and forced not to proxy. For lower-level service resolution, see @{method:getAlmanacServiceURI}. @param PhabricatorUser $viewer Viewing user. @param bool $never_proxy (optional) `true` to throw if a client would be returned. @return ConduitClient|null Client, or `null` for local repositories.
newConduitClient
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepository.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepository.php
Apache-2.0
public function updateAuditStatus(array $requests) { assert_instances_of($requests, 'PhabricatorRepositoryAuditRequest'); $any_concern = false; $any_accept = false; $any_need = false; foreach ($requests as $request) { switch ($request->getAuditStatus()) { case PhabricatorAuditRequestStatus::AUDIT_REQUIRED: case PhabricatorAuditRequestStatus::AUDIT_REQUESTED: $any_need = true; break; case PhabricatorAuditRequestStatus::ACCEPTED: $any_accept = true; break; case PhabricatorAuditRequestStatus::CONCERNED: $any_concern = true; break; } } if ($any_concern) { if ($this->isAuditStatusNeedsVerification()) { // If the change is in "Needs Verification", we keep it there as // long as any auditors still have concerns. $status = DiffusionCommitAuditStatus::NEEDS_VERIFICATION; } else { $status = DiffusionCommitAuditStatus::CONCERN_RAISED; } } else if ($any_accept) { if ($any_need) { $status = DiffusionCommitAuditStatus::PARTIALLY_AUDITED; } else { $status = DiffusionCommitAuditStatus::AUDITED; } } else if ($any_need) { $status = DiffusionCommitAuditStatus::NEEDS_AUDIT; } else { $status = DiffusionCommitAuditStatus::NONE; } return $this->setAuditStatus($status); }
Synchronize a commit's overall audit status with the individual audit triggers.
updateAuditStatus
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepositoryCommit.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepositoryCommit.php
Apache-2.0
public function getLocalName() { $repository = $this->getRepository(); $identifier = $this->getCommitIdentifier(); return $repository->formatCommitName($identifier, $local = true); }
Return a local display name for use in the context of the containing repository. In Git and Mercurial, this returns only a short hash, like "abcdef012345". See @{method:getDisplayName} for a short name that always includes repository context. @return string Short human-readable name for use inside a repository.
getLocalName
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepositoryCommit.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepositoryCommit.php
Apache-2.0
public function toDictionary() { return array( 'repositoryID' => $this->getRepositoryID(), 'phid' => $this->getPHID(), 'commitIdentifier' => $this->getCommitIdentifier(), 'epoch' => $this->getEpoch(), 'authorPHID' => $this->getAuthorPHID(), 'auditStatus' => $this->getAuditStatus(), 'summary' => $this->getSummary(), 'importStatus' => $this->getImportStatus(), ); }
NOTE: this is not a complete serialization; only the 'protected' fields are involved. This is due to ease of (ab)using the Lisk abstraction to get this done, as well as complexity of the other fields.
toDictionary
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepositoryCommit.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepositoryCommit.php
Apache-2.0
public static function willWrite( AphrontDatabaseConnection $locked_connection, $repository_phid, $device_phid, array $write_properties, $lock_owner) { $version = new self(); $table = $version->getTableName(); queryfx( $locked_connection, 'INSERT INTO %T (repositoryPHID, devicePHID, repositoryVersion, isWriting, writeProperties, lockOwner) VALUES (%s, %s, %d, %d, %s, %s) ON DUPLICATE KEY UPDATE isWriting = VALUES(isWriting), writeProperties = VALUES(writeProperties), lockOwner = VALUES(lockOwner)', $table, $repository_phid, $device_phid, 0, 1, phutil_json_encode($write_properties), $lock_owner); }
Before a write, set the "isWriting" flag. This allows us to detect when we lose a node partway through a write and may have committed and acknowledged a write on a node that lost the lock partway through the write and is no longer reachable. In particular, if a node loses its connection to the database the global lock is released by default. This is a durable lock which stays locked by default.
willWrite
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepositoryWorkingCopyVersion.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepositoryWorkingCopyVersion.php
Apache-2.0
public static function didWrite( $repository_phid, $device_phid, $old_version, $new_version, $lock_owner) { $version = new self(); $conn_w = $version->establishConnection('w'); $table = $version->getTableName(); queryfx( $conn_w, 'UPDATE %T SET repositoryVersion = %d, isWriting = 0, lockOwner = NULL WHERE repositoryPHID = %s AND devicePHID = %s AND repositoryVersion = %d AND isWriting = 1 AND lockOwner = %s', $table, $new_version, $repository_phid, $device_phid, $old_version, $lock_owner); }
After a write, update the version and release the "isWriting" lock.
didWrite
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepositoryWorkingCopyVersion.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepositoryWorkingCopyVersion.php
Apache-2.0
public static function updateVersion( $repository_phid, $device_phid, $new_version) { $version = new self(); $conn_w = $version->establishConnection('w'); $table = $version->getTableName(); queryfx( $conn_w, 'INSERT INTO %T (repositoryPHID, devicePHID, repositoryVersion, isWriting) VALUES (%s, %s, %d, %d) ON DUPLICATE KEY UPDATE repositoryVersion = VALUES(repositoryVersion)', $table, $repository_phid, $device_phid, $new_version, 0); }
After a fetch, set the local version to the fetched version.
updateVersion
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepositoryWorkingCopyVersion.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepositoryWorkingCopyVersion.php
Apache-2.0
public static function demoteDevice( $repository_phid, $device_phid) { $version = new self(); $conn_w = $version->establishConnection('w'); $table = $version->getTableName(); queryfx( $conn_w, 'DELETE FROM %T WHERE repositoryPHID = %s AND devicePHID = %s', $table, $repository_phid, $device_phid); }
Explicitly demote a device.
demoteDevice
php
phorgeit/phorge
src/applications/repository/storage/PhabricatorRepositoryWorkingCopyVersion.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/storage/PhabricatorRepositoryWorkingCopyVersion.php
Apache-2.0
private function buildUpdateFuture( PhabricatorRepository $repository, $no_discovery) { $bin = dirname(phutil_get_library_root('phabricator')).'/bin/repository'; $flags = array(); if ($no_discovery) { $flags[] = '--no-discovery'; } $monogram = $repository->getMonogram(); $future = new ExecFuture('%s update %Ls -- %s', $bin, $flags, $monogram); // Sometimes, the underlying VCS commands will hang indefinitely. We've // observed this occasionally with GitHub, and other users have observed // it with other VCS servers. // To limit the damage this can cause, kill the update out after a // reasonable amount of time, under the assumption that it has hung. // Since it's hard to know what a "reasonable" amount of time is given that // users may be downloading a repository full of pirated movies over a // potato, these limits are fairly generous. Repositories exceeding these // limits can be manually pulled with `bin/repository update X`, which can // just run for as long as it wants. if ($repository->isImporting()) { $timeout = phutil_units('4 hours in seconds'); } else { $timeout = phutil_units('15 minutes in seconds'); } $future->setTimeout($timeout); // The default TERM inherited by this process is "unknown", which causes PHP // to produce a warning upon startup. Override it to squash this output to // STDERR. $future->updateEnv('TERM', 'dumb'); return $future; }
@task pull
buildUpdateFuture
php
phorgeit/phorge
src/applications/repository/daemon/PhabricatorRepositoryPullLocalDaemon.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/daemon/PhabricatorRepositoryPullLocalDaemon.php
Apache-2.0
private function loadLastUpdate(PhabricatorRepository $repository) { $table = new PhabricatorRepositoryStatusMessage(); $conn = $table->establishConnection('r'); $epoch = queryfx_one( $conn, 'SELECT MAX(epoch) last_update FROM %T WHERE repositoryID = %d AND statusType IN (%Ls)', $table->getTableName(), $repository->getID(), array( PhabricatorRepositoryStatusMessage::TYPE_INIT, PhabricatorRepositoryStatusMessage::TYPE_FETCH, )); if ($epoch) { return (int)$epoch['last_update']; } return PhabricatorTime::getNow(); }
@task pull
loadLastUpdate
php
phorgeit/phorge
src/applications/repository/daemon/PhabricatorRepositoryPullLocalDaemon.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/daemon/PhabricatorRepositoryPullLocalDaemon.php
Apache-2.0
private function resolveUpdateFuture( PhabricatorRepository $repository, ExecFuture $future, $min_sleep) { $display_name = $repository->getDisplayName(); $this->log(pht('Resolving update for "%s".', $display_name)); try { list($stdout, $stderr) = $future->resolvex(); } catch (Exception $ex) { $proxy = new Exception( pht( 'Error while updating the "%s" repository.', $display_name), 0, $ex); phlog($proxy); $smart_wait = $repository->loadUpdateInterval($min_sleep); return PhabricatorTime::getNow() + $smart_wait; } if (strlen($stderr)) { $stderr_msg = pht( 'Unexpected output while updating repository "%s": %s', $display_name, $stderr); phlog($stderr_msg); } $smart_wait = $repository->loadUpdateInterval($min_sleep); $this->log( pht( 'Based on activity in repository "%s", considering a wait of %s '. 'seconds before update.', $display_name, new PhutilNumber($smart_wait))); return PhabricatorTime::getNow() + $smart_wait; }
@task pull
resolveUpdateFuture
php
phorgeit/phorge
src/applications/repository/daemon/PhabricatorRepositoryPullLocalDaemon.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/daemon/PhabricatorRepositoryPullLocalDaemon.php
Apache-2.0
private function waitForUpdates($min_sleep, array $retry_after) { $this->log( pht('No repositories need updates right now, sleeping...')); $sleep_until = time() + $min_sleep; if ($retry_after) { $sleep_until = min($sleep_until, min($retry_after)); } while (($sleep_until - time()) > 0) { $sleep_duration = ($sleep_until - time()); if ($this->shouldHibernate($sleep_duration)) { return true; } $this->log( pht( 'Sleeping for %s more second(s)...', new PhutilNumber($sleep_duration))); $this->sleep(1); if ($this->shouldExit()) { $this->log(pht('Awakened from sleep by graceful shutdown!')); return false; } if ($this->loadRepositoryUpdateMessages()) { $this->log(pht('Awakened from sleep by pending updates!')); break; } } return false; }
Sleep for a short period of time, waiting for update messages from the @task pull
waitForUpdates
php
phorgeit/phorge
src/applications/repository/daemon/PhabricatorRepositoryPullLocalDaemon.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/daemon/PhabricatorRepositoryPullLocalDaemon.php
Apache-2.0
private function parseUntil($until_type, $until_name) { if ($this->isParsed($until_type, $until_name)) { return; } $hglog = $this->iterator; while ($hglog->valid()) { $line = $hglog->current(); $hglog->next(); $line = trim($line); if (!strlen($line)) { break; } list($rev, $node, $date, $parents) = explode("\1", $line); $rev = (int)$rev; $date = (int)head(explode('.', $date)); $this->dates[$node] = $date; $this->local[$rev] = $node; $this->localParents[$node] = $this->parseParents($parents, $rev); if ($this->isParsed($until_type, $until_name)) { return; } } throw new Exception( pht( "No such %s '%s' in repository!", $until_type, $until_name)); }
Parse until we have consumed some object. There are two types of parses: parse until we find a commit hash ($until_type = "node"), or parse until we find a local commit number ($until_type = "rev"). We use the former when looking up commits, and the latter when resolving parents.
parseUntil
php
phorgeit/phorge
src/applications/repository/daemon/PhabricatorMercurialGraphStream.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/daemon/PhabricatorMercurialGraphStream.php
Apache-2.0
private function isParsed($type, $name) { switch ($type) { case 'rev': return isset($this->local[$name]); case 'node': return isset($this->dates[$name]); } }
Returns true if the object specified by $type ('rev' or 'node') and $name (rev or node name) has been consumed from the hg process.
isParsed
php
phorgeit/phorge
src/applications/repository/daemon/PhabricatorMercurialGraphStream.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/daemon/PhabricatorMercurialGraphStream.php
Apache-2.0
public function discoverCommits() { $repository = $this->getRepository(); $lock = $this->newRepositoryLock($repository, 'repo.look', false); try { $lock->lock(); } catch (PhutilLockException $ex) { throw new DiffusionDaemonLockException( pht( 'Another process is currently discovering repository "%s", '. 'skipping discovery.', $repository->getDisplayName())); } try { $result = $this->discoverCommitsWithLock(); } catch (Exception $ex) { $lock->unlock(); throw $ex; } $lock->unlock(); return $result; }
@task discovery
discoverCommits
php
phorgeit/phorge
src/applications/repository/engine/PhabricatorRepositoryDiscoveryEngine.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/engine/PhabricatorRepositoryDiscoveryEngine.php
Apache-2.0
private function getRefGroupsForDiscovery(array $heads) { $heads = $this->sortRefs($heads); // See T13593. We hold a commit cache with a fixed maximum size. Split the // refs into chunks no larger than the cache size, so we don't overflow the // cache when testing them. $array_iterator = new ArrayIterator($heads); $chunk_iterator = new PhutilChunkedIterator( $array_iterator, self::MAX_COMMIT_CACHE_SIZE); return $chunk_iterator; }
@task git
getRefGroupsForDiscovery
php
phorgeit/phorge
src/applications/repository/engine/PhabricatorRepositoryDiscoveryEngine.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/engine/PhabricatorRepositoryDiscoveryEngine.php
Apache-2.0
private function sortRefs(array $refs) { $repository = $this->getRepository(); $publisher = $repository->newPublisher(); $head_refs = array(); $tail_refs = array(); foreach ($refs as $ref) { if ($publisher->isPermanentRef($ref)) { $head_refs[] = $ref; } else { $tail_refs[] = $ref; } } return array_merge($head_refs, $tail_refs); }
Sort refs so we process permanent refs first. This makes the whole import process a little cheaper, since we can publish these commits the first time through rather than catching them in the refs step. @task internal @param list<DiffusionRepositoryRef> $refs List of refs. @return list<DiffusionRepositoryRef> Sorted list of refs.
sortRefs
php
phorgeit/phorge
src/applications/repository/engine/PhabricatorRepositoryDiscoveryEngine.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/engine/PhabricatorRepositoryDiscoveryEngine.php
Apache-2.0
private function removeMissingCommits(array $identifiers) { if (!$identifiers) { return array(); } $resolved = id(new DiffusionLowLevelResolveRefsQuery()) ->setRepository($this->getRepository()) ->withRefs($identifiers) ->execute(); foreach ($identifiers as $key => $identifier) { if (empty($resolved[$identifier])) { unset($identifiers[$key]); } } return $identifiers; }
Remove commits which no longer exist in the repository from a list. After a force push and garbage collection, we may have branch cursors which point at commits which no longer exist. This can make commands issued later fail. See T5839 for discussion. @param list<string> $identifiers List of commit identifiers. @return list<string> List with nonexistent identifiers removed.
removeMissingCommits
php
phorgeit/phorge
src/applications/repository/engine/PhabricatorRepositoryRefEngine.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/engine/PhabricatorRepositoryRefEngine.php
Apache-2.0
private function loadGitRefPositions(PhabricatorRepository $repository) { $refs = id(new DiffusionLowLevelGitRefQuery()) ->setRepository($repository) ->execute(); return mgroup($refs, 'getRefType'); }
@task git
loadGitRefPositions
php
phorgeit/phorge
src/applications/repository/engine/PhabricatorRepositoryRefEngine.php
https://github.com/phorgeit/phorge/blob/master/src/applications/repository/engine/PhabricatorRepositoryRefEngine.php
Apache-2.0