repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/PhabricatorDatabaseRef.php
src/infrastructure/cluster/PhabricatorDatabaseRef.php
<?php final class PhabricatorDatabaseRef extends Phobject { const STATUS_OKAY = 'okay'; const STATUS_FAIL = 'fail'; const STATUS_AUTH = 'auth'; const STATUS_REPLICATION_CLIENT = 'replication-client'; const REPLICATION_OKAY = 'okay'; const REPLICATION_MASTER_REPLICA = 'master-replica'; const REPLICATION_REPLICA_NONE = 'replica-none'; const REPLICATION_SLOW = 'replica-slow'; const REPLICATION_NOT_REPLICATING = 'not-replicating'; const KEY_HEALTH = 'cluster.db.health'; const KEY_REFS = 'cluster.db.refs'; const KEY_INDIVIDUAL = 'cluster.db.individual'; private $host; private $port; private $user; private $pass; private $disabled; private $isMaster; private $isIndividual; private $connectionLatency; private $connectionStatus; private $connectionMessage; private $connectionException; private $replicaStatus; private $replicaMessage; private $replicaDelay; private $healthRecord; private $didFailToConnect; private $isDefaultPartition; private $applicationMap = array(); private $masterRef; private $replicaRefs = array(); private $usePersistentConnections; public function setHost($host) { $this->host = $host; return $this; } public function getHost() { return $this->host; } public function setPort($port) { $this->port = $port; return $this; } public function getPort() { return $this->port; } public function setUser($user) { $this->user = $user; return $this; } public function getUser() { return $this->user; } public function setPass(PhutilOpaqueEnvelope $pass) { $this->pass = $pass; return $this; } public function getPass() { return $this->pass; } public function setIsMaster($is_master) { $this->isMaster = $is_master; return $this; } public function getIsMaster() { return $this->isMaster; } public function setDisabled($disabled) { $this->disabled = $disabled; return $this; } public function getDisabled() { return $this->disabled; } public function setConnectionLatency($connection_latency) { $this->connectionLatency = $connection_latency; return $this; } public function getConnectionLatency() { return $this->connectionLatency; } public function setConnectionStatus($connection_status) { $this->connectionStatus = $connection_status; return $this; } public function getConnectionStatus() { if ($this->connectionStatus === null) { throw new PhutilInvalidStateException('queryAll'); } return $this->connectionStatus; } public function setConnectionMessage($connection_message) { $this->connectionMessage = $connection_message; return $this; } public function getConnectionMessage() { return $this->connectionMessage; } public function setReplicaStatus($replica_status) { $this->replicaStatus = $replica_status; return $this; } public function getReplicaStatus() { return $this->replicaStatus; } public function setReplicaMessage($replica_message) { $this->replicaMessage = $replica_message; return $this; } public function getReplicaMessage() { return $this->replicaMessage; } public function setReplicaDelay($replica_delay) { $this->replicaDelay = $replica_delay; return $this; } public function getReplicaDelay() { return $this->replicaDelay; } public function setIsIndividual($is_individual) { $this->isIndividual = $is_individual; return $this; } public function getIsIndividual() { return $this->isIndividual; } public function setIsDefaultPartition($is_default_partition) { $this->isDefaultPartition = $is_default_partition; return $this; } public function getIsDefaultPartition() { return $this->isDefaultPartition; } public function setUsePersistentConnections($use_persistent_connections) { $this->usePersistentConnections = $use_persistent_connections; return $this; } public function getUsePersistentConnections() { return $this->usePersistentConnections; } public function setApplicationMap(array $application_map) { $this->applicationMap = $application_map; return $this; } public function getApplicationMap() { return $this->applicationMap; } public function getPartitionStateForCommit() { $state = PhabricatorEnv::getEnvConfig('cluster.databases'); foreach ($state as $key => $value) { // Don't store passwords, since we don't care if they differ and // users may find it surprising. unset($state[$key]['pass']); } return phutil_json_encode($state); } public function setMasterRef(PhabricatorDatabaseRef $master_ref) { $this->masterRef = $master_ref; return $this; } public function getMasterRef() { return $this->masterRef; } public function addReplicaRef(PhabricatorDatabaseRef $replica_ref) { $this->replicaRefs[] = $replica_ref; return $this; } public function getReplicaRefs() { return $this->replicaRefs; } public function getDisplayName() { return $this->getRefKey(); } public function getRefKey() { $host = $this->getHost(); $port = $this->getPort(); if ($port !== null && strlen($port)) { return "{$host}:{$port}"; } return $host; } public static function getConnectionStatusMap() { return array( self::STATUS_OKAY => array( 'icon' => 'fa-exchange', 'color' => 'green', 'label' => pht('Okay'), ), self::STATUS_FAIL => array( 'icon' => 'fa-times', 'color' => 'red', 'label' => pht('Failed'), ), self::STATUS_AUTH => array( 'icon' => 'fa-key', 'color' => 'red', 'label' => pht('Invalid Credentials'), ), self::STATUS_REPLICATION_CLIENT => array( 'icon' => 'fa-eye-slash', 'color' => 'yellow', 'label' => pht('Missing Permission'), ), ); } public static function getReplicaStatusMap() { return array( self::REPLICATION_OKAY => array( 'icon' => 'fa-download', 'color' => 'green', 'label' => pht('Okay'), ), self::REPLICATION_MASTER_REPLICA => array( 'icon' => 'fa-database', 'color' => 'red', 'label' => pht('Replicating Master'), ), self::REPLICATION_REPLICA_NONE => array( 'icon' => 'fa-download', 'color' => 'red', 'label' => pht('Not A Replica'), ), self::REPLICATION_SLOW => array( 'icon' => 'fa-hourglass', 'color' => 'red', 'label' => pht('Slow Replication'), ), self::REPLICATION_NOT_REPLICATING => array( 'icon' => 'fa-exclamation-triangle', 'color' => 'red', 'label' => pht('Not Replicating'), ), ); } public static function getClusterRefs() { $cache = PhabricatorCaches::getRequestCache(); $refs = $cache->getKey(self::KEY_REFS); if (!$refs) { $refs = self::newRefs(); $cache->setKey(self::KEY_REFS, $refs); } return $refs; } public static function getLiveIndividualRef() { $cache = PhabricatorCaches::getRequestCache(); $ref = $cache->getKey(self::KEY_INDIVIDUAL); if (!$ref) { $ref = self::newIndividualRef(); $cache->setKey(self::KEY_INDIVIDUAL, $ref); } return $ref; } public static function newRefs() { $default_port = PhabricatorEnv::getEnvConfig('mysql.port'); $default_port = nonempty($default_port, 3306); $default_user = PhabricatorEnv::getEnvConfig('mysql.user'); $default_pass = PhabricatorEnv::getEnvConfig('mysql.pass'); $default_pass = phutil_string_cast($default_pass); $default_pass = new PhutilOpaqueEnvelope($default_pass); $config = PhabricatorEnv::getEnvConfig('cluster.databases'); return id(new PhabricatorDatabaseRefParser()) ->setDefaultPort($default_port) ->setDefaultUser($default_user) ->setDefaultPass($default_pass) ->newRefs($config); } public static function queryAll() { $refs = self::getActiveDatabaseRefs(); return self::queryRefs($refs); } private static function queryRefs(array $refs) { foreach ($refs as $ref) { $conn = $ref->newManagementConnection(); $t_start = microtime(true); $replica_status = false; try { $replica_status = queryfx_one($conn, 'SHOW SLAVE STATUS'); $ref->setConnectionStatus(self::STATUS_OKAY); } catch (AphrontAccessDeniedQueryException $ex) { $ref->setConnectionStatus(self::STATUS_REPLICATION_CLIENT); $ref->setConnectionMessage( pht( 'No permission to run "SHOW SLAVE STATUS". Grant this user '. '"REPLICATION CLIENT" permission to allow this server to '. 'monitor replica health.')); } catch (AphrontInvalidCredentialsQueryException $ex) { $ref->setConnectionStatus(self::STATUS_AUTH); $ref->setConnectionMessage($ex->getMessage()); } catch (AphrontQueryException $ex) { $ref->setConnectionStatus(self::STATUS_FAIL); $class = get_class($ex); $message = $ex->getMessage(); $ref->setConnectionMessage( pht( '%s: %s', get_class($ex), $ex->getMessage())); } $t_end = microtime(true); $ref->setConnectionLatency($t_end - $t_start); if ($replica_status !== false) { $is_replica = (bool)$replica_status; if ($ref->getIsMaster() && $is_replica) { $ref->setReplicaStatus(self::REPLICATION_MASTER_REPLICA); $ref->setReplicaMessage( pht( 'This host has a "master" role, but is replicating data from '. 'another host ("%s")!', idx($replica_status, 'Master_Host'))); } else if (!$ref->getIsMaster() && !$is_replica) { $ref->setReplicaStatus(self::REPLICATION_REPLICA_NONE); $ref->setReplicaMessage( pht( 'This host has a "replica" role, but is not replicating data '. 'from a master (no output from "SHOW SLAVE STATUS").')); } else { $ref->setReplicaStatus(self::REPLICATION_OKAY); } if ($is_replica) { $latency = idx($replica_status, 'Seconds_Behind_Master'); if (!strlen($latency)) { $ref->setReplicaStatus(self::REPLICATION_NOT_REPLICATING); } else { $latency = (int)$latency; $ref->setReplicaDelay($latency); if ($latency > 30) { $ref->setReplicaStatus(self::REPLICATION_SLOW); $ref->setReplicaMessage( pht( 'This replica is lagging far behind the master. Data is at '. 'risk!')); } } } } } return $refs; } public function newManagementConnection() { return $this->newConnection( array( 'retries' => 0, 'timeout' => 2, )); } public function newApplicationConnection($database) { return $this->newConnection( array( 'database' => $database, )); } public function isSevered() { // If we only have an individual database, never sever our connection to // it, at least for now. It's possible that using the same severing rules // might eventually make sense to help alleviate load-related failures, // but we should wait for all the cluster stuff to stabilize first. if ($this->getIsIndividual()) { return false; } if ($this->didFailToConnect) { return true; } $record = $this->getHealthRecord(); $is_healthy = $record->getIsHealthy(); if (!$is_healthy) { return true; } return false; } public function isReachable(AphrontDatabaseConnection $connection) { $record = $this->getHealthRecord(); $should_check = $record->getShouldCheck(); if ($this->isSevered() && !$should_check) { return false; } $this->connectionException = null; try { $connection->openConnection(); $reachable = true; } catch (AphrontSchemaQueryException $ex) { // We get one of these if the database we're trying to select does not // exist. In this case, just re-throw the exception. This is expected // during first-time setup, when databases like "config" will not exist // yet. throw $ex; } catch (Exception $ex) { $this->connectionException = $ex; $reachable = false; } if ($should_check) { $record->didHealthCheck($reachable); } if (!$reachable) { $this->didFailToConnect = true; } return $reachable; } public function checkHealth() { $health = $this->getHealthRecord(); $should_check = $health->getShouldCheck(); if ($should_check) { // This does an implicit health update. $connection = $this->newManagementConnection(); $this->isReachable($connection); } return $this; } private function getHealthRecordCacheKey() { $host = $this->getHost(); $port = $this->getPort(); $key = self::KEY_HEALTH; return "{$key}({$host}, {$port})"; } public function getHealthRecord() { if (!$this->healthRecord) { $this->healthRecord = new PhabricatorClusterServiceHealthRecord( $this->getHealthRecordCacheKey()); } return $this->healthRecord; } public function getConnectionException() { return $this->connectionException; } public static function getActiveDatabaseRefs() { $refs = array(); foreach (self::getMasterDatabaseRefs() as $ref) { $refs[] = $ref; } foreach (self::getReplicaDatabaseRefs() as $ref) { $refs[] = $ref; } return $refs; } public static function getAllMasterDatabaseRefs() { $refs = self::getClusterRefs(); if (!$refs) { return array(self::getLiveIndividualRef()); } $masters = array(); foreach ($refs as $ref) { if ($ref->getIsMaster()) { $masters[] = $ref; } } return $masters; } public static function getMasterDatabaseRefs() { $refs = self::getAllMasterDatabaseRefs(); return self::getEnabledRefs($refs); } public function isApplicationHost($database) { return isset($this->applicationMap[$database]); } public function loadRawMySQLConfigValue($key) { $conn = $this->newManagementConnection(); try { $value = queryfx_one($conn, 'SELECT @@%C', $key); // NOTE: Although MySQL allows us to escape configuration values as if // they are column names, the escaping is included in the column name // of the return value: if we select "@@`x`", we get back a column named // "@@`x`", not "@@x" as we might expect. $value = head($value); } catch (AphrontQueryException $ex) { $value = null; } return $value; } public static function getMasterDatabaseRefForApplication($application) { $masters = self::getMasterDatabaseRefs(); $application_master = null; $default_master = null; foreach ($masters as $master) { if ($master->isApplicationHost($application)) { $application_master = $master; break; } if ($master->getIsDefaultPartition()) { $default_master = $master; } } if ($application_master) { $masters = array($application_master); } else if ($default_master) { $masters = array($default_master); } else { $masters = array(); } $masters = self::getEnabledRefs($masters); $master = head($masters); return $master; } public static function newIndividualRef() { $default_user = PhabricatorEnv::getEnvConfig('mysql.user'); $default_pass = new PhutilOpaqueEnvelope( PhabricatorEnv::getEnvConfig('mysql.pass')); $default_host = PhabricatorEnv::getEnvConfig('mysql.host'); $default_port = PhabricatorEnv::getEnvConfig('mysql.port'); return id(new self()) ->setUser($default_user) ->setPass($default_pass) ->setHost($default_host) ->setPort($default_port) ->setIsIndividual(true) ->setIsMaster(true) ->setIsDefaultPartition(true) ->setUsePersistentConnections(false); } public static function getAllReplicaDatabaseRefs() { $refs = self::getClusterRefs(); if (!$refs) { return array(); } $replicas = array(); foreach ($refs as $ref) { if ($ref->getIsMaster()) { continue; } $replicas[] = $ref; } return $replicas; } public static function getReplicaDatabaseRefs() { $refs = self::getAllReplicaDatabaseRefs(); return self::getEnabledRefs($refs); } private static function getEnabledRefs(array $refs) { foreach ($refs as $key => $ref) { if ($ref->getDisabled()) { unset($refs[$key]); } } return $refs; } public static function getReplicaDatabaseRefForApplication($application) { $replicas = self::getReplicaDatabaseRefs(); $application_replicas = array(); $default_replicas = array(); foreach ($replicas as $replica) { $master = $replica->getMasterRef(); if ($master->isApplicationHost($application)) { $application_replicas[] = $replica; } if ($master->getIsDefaultPartition()) { $default_replicas[] = $replica; } } if ($application_replicas) { $replicas = $application_replicas; } else { $replicas = $default_replicas; } $replicas = self::getEnabledRefs($replicas); // TODO: We may have multiple replicas to choose from, and could make // more of an effort to pick the "best" one here instead of always // picking the first one. Once we've picked one, we should try to use // the same replica for the rest of the request, though. return head($replicas); } private function newConnection(array $options) { // If we believe the database is unhealthy, don't spend as much time // trying to connect to it, since it's likely to continue to fail and // hammering it can only make the problem worse. $record = $this->getHealthRecord(); if ($record->getIsHealthy()) { $default_retries = 3; $default_timeout = 10; } else { $default_retries = 0; $default_timeout = 2; } $spec = $options + array( 'user' => $this->getUser(), 'pass' => $this->getPass(), 'host' => $this->getHost(), 'port' => $this->getPort(), 'database' => null, 'retries' => $default_retries, 'timeout' => $default_timeout, 'persistent' => $this->getUsePersistentConnections(), ); $is_cli = (php_sapi_name() == 'cli'); $use_persistent = false; if (!empty($spec['persistent']) && !$is_cli) { $use_persistent = true; } unset($spec['persistent']); $connection = self::newRawConnection($spec); // If configured, use persistent connections. See T11672 for details. if ($use_persistent) { $connection->setPersistent($use_persistent); } // Unless this is a script running from the CLI, prevent any query from // running for more than 30 seconds. See T10849 for details. if (!$is_cli) { $connection->setQueryTimeout(30); } return $connection; } public static function newRawConnection(array $options) { if (extension_loaded('mysqli')) { return new AphrontMySQLiDatabaseConnection($options); } else { return new AphrontMySQLDatabaseConnection($options); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/PhabricatorDatabaseRefParser.php
src/infrastructure/cluster/PhabricatorDatabaseRefParser.php
<?php final class PhabricatorDatabaseRefParser extends Phobject { private $defaultPort = 3306; private $defaultUser; private $defaultPass; public function setDefaultPort($default_port) { $this->defaultPort = $default_port; return $this; } public function getDefaultPort() { return $this->defaultPort; } public function setDefaultUser($default_user) { $this->defaultUser = $default_user; return $this; } public function getDefaultUser() { return $this->defaultUser; } public function setDefaultPass($default_pass) { $this->defaultPass = $default_pass; return $this; } public function getDefaultPass() { return $this->defaultPass; } public function newRefs(array $config) { $default_port = $this->getDefaultPort(); $default_user = $this->getDefaultUser(); $default_pass = $this->getDefaultPass(); $refs = array(); $master_count = 0; foreach ($config as $key => $server) { $host = $server['host']; $port = idx($server, 'port', $default_port); $user = idx($server, 'user', $default_user); $disabled = idx($server, 'disabled', false); $pass = idx($server, 'pass'); if ($pass) { $pass = new PhutilOpaqueEnvelope($pass); } else { $pass = clone $default_pass; } $role = $server['role']; $is_master = ($role == 'master'); $use_persistent = (bool)idx($server, 'persistent', false); $ref = id(new PhabricatorDatabaseRef()) ->setHost($host) ->setPort($port) ->setUser($user) ->setPass($pass) ->setDisabled($disabled) ->setIsMaster($is_master) ->setUsePersistentConnections($use_persistent); if ($is_master) { $master_count++; } $refs[$key] = $ref; } $is_partitioned = ($master_count > 1); if ($is_partitioned) { $default_ref = null; $partition_map = array(); foreach ($refs as $key => $ref) { if (!$ref->getIsMaster()) { continue; } $server = $config[$key]; $partition = idx($server, 'partition'); if (!is_array($partition)) { throw new Exception( pht( 'This server is configured with multiple master databases, '. 'but master "%s" is missing a "partition" configuration key to '. 'define application partitioning.', $ref->getRefKey())); } $application_map = array(); foreach ($partition as $application) { if ($application === 'default') { if ($default_ref) { throw new Exception( pht( 'Multiple masters (databases "%s" and "%s") specify that '. 'they are the "default" partition. Only one master may be '. 'the default.', $ref->getRefKey(), $default_ref->getRefKey())); } else { $default_ref = $ref; $ref->setIsDefaultPartition(true); } } else if (isset($partition_map[$application])) { throw new Exception( pht( 'Multiple masters (databases "%s" and "%s") specify that '. 'they are the partition for application "%s". Each '. 'application may be allocated to only one partition.', $partition_map[$application]->getRefKey(), $ref->getRefKey(), $application)); } else { // TODO: We should check that the application is valid, to // prevent typos in application names. However, we do not // currently have an efficient way to enumerate all of the valid // application database names. $partition_map[$application] = $ref; $application_map[$application] = $application; } } $ref->setApplicationMap($application_map); } } else { // If we only have one master, make it the default. foreach ($refs as $ref) { if ($ref->getIsMaster()) { $ref->setIsDefaultPartition(true); } } } $ref_map = array(); $master_keys = array(); foreach ($refs as $ref) { $ref_key = $ref->getRefKey(); if (isset($ref_map[$ref_key])) { throw new Exception( pht( 'Multiple configured databases have the same internal '. 'key, "%s". You may have listed a database multiple times.', $ref_key)); } else { $ref_map[$ref_key] = $ref; if ($ref->getIsMaster()) { $master_keys[] = $ref_key; } } } foreach ($refs as $key => $ref) { if ($ref->getIsMaster()) { continue; } $server = $config[$key]; $partition = idx($server, 'partition'); if ($partition !== null) { throw new Exception( pht( 'Database "%s" is configured as a replica, but specifies a '. '"partition". Only master databases may have a partition '. 'configuration. Replicas use the same configuration as the '. 'master they follow.', $ref->getRefKey())); } $master_key = idx($server, 'master'); if ($master_key === null) { if ($is_partitioned) { throw new Exception( pht( 'Database "%s" is configured as a replica, but does not '. 'specify which "master" it follows in configuration. Valid '. 'masters are: %s.', $ref->getRefKey(), implode(', ', $master_keys))); } else if ($master_keys) { $master_key = head($master_keys); } else { throw new Exception( pht( 'Database "%s" is configured as a replica, but there is no '. 'master configured.', $ref->getRefKey())); } } if (!isset($ref_map[$master_key])) { throw new Exception( pht( 'Database "%s" is configured as a replica and specifies a '. 'master ("%s"), but that master is not a valid master. Valid '. 'masters are: %s.', $ref->getRefKey(), $master_key, implode(', ', $master_keys))); } $master_ref = $ref_map[$master_key]; $ref->setMasterRef($ref_map[$master_key]); $master_ref->addReplicaRef($ref); } return array_values($refs); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php
src/infrastructure/cluster/PhabricatorClusterServiceHealthRecord.php
<?php class PhabricatorClusterServiceHealthRecord extends Phobject { private $cacheKey; private $shouldCheck; private $isHealthy; private $upEventCount; private $downEventCount; public function __construct($cache_key) { $this->cacheKey = $cache_key; $this->readState(); } /** * Is the database currently healthy? */ public function getIsHealthy() { return $this->isHealthy; } /** * Should this request check database health? */ public function getShouldCheck() { return $this->shouldCheck; } /** * How many recent health checks were successful? */ public function getUpEventCount() { return $this->upEventCount; } /** * How many recent health checks failed? */ public function getDownEventCount() { return $this->downEventCount; } /** * Number of failures or successes we need to see in a row before we change * the state. */ public function getRequiredEventCount() { // NOTE: If you change this value, update the "Cluster: Databases" docs. return 5; } /** * Seconds to wait between health checks. */ public function getHealthCheckFrequency() { // NOTE: If you change this value, update the "Cluster: Databases" docs. return 3; } public function didHealthCheck($result) { $now = microtime(true); $check_frequency = $this->getHealthCheckFrequency(); $event_count = $this->getRequiredEventCount(); $record = $this->readHealthRecord(); $log = $record['log']; foreach ($log as $key => $event) { $when = idx($event, 'timestamp'); // If the log already has another nearby event, just ignore this one. // We raced with another process and our result can just be thrown away. if (($now - $when) <= $check_frequency) { return $this; } } $log[] = array( 'timestamp' => $now, 'up' => $result, ); // Throw away older events which are now obsolete. $log = array_slice($log, -$event_count); $count_up = 0; $count_down = 0; foreach ($log as $event) { if ($event['up']) { $count_up++; } else { $count_down++; } } // If all of the events are the same, change the state. if ($count_up == $event_count) { $record['up'] = true; } else if ($count_down == $event_count) { $record['up'] = false; } $record['log'] = $log; $this->writeHealthRecord($record); $this->isHealthy = $record['up']; $this->shouldCheck = false; $this->updateStatistics($record); return $this; } private function readState() { $now = microtime(true); $check_frequency = $this->getHealthCheckFrequency(); $record = $this->readHealthRecord(); $last_check = $record['lastCheck']; if (($now - $last_check) >= $check_frequency) { $record['lastCheck'] = $now; $this->writeHealthRecord($record); $this->shouldCheck = true; } else { $this->shouldCheck = false; } $this->isHealthy = $record['up']; $this->updateStatistics($record); } private function updateStatistics(array $record) { $this->upEventCount = 0; $this->downEventCount = 0; foreach ($record['log'] as $event) { if ($event['up']) { $this->upEventCount++; } else { $this->downEventCount++; } } } public function getCacheKey() { return $this->cacheKey; } private function readHealthRecord() { $cache = PhabricatorCaches::getSetupCache(); $cache_key = $this->getCacheKey(); $health_record = $cache->getKey($cache_key); if (!is_array($health_record)) { $health_record = array( 'up' => true, 'lastCheck' => 0, 'log' => array(), ); } return $health_record; } private function writeHealthRecord(array $record) { $cache = PhabricatorCaches::getSetupCache(); $cache_key = $this->getCacheKey(); $cache->setKey($cache_key, $record); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/exception/PhabricatorClusterImpossibleWriteException.php
src/infrastructure/cluster/exception/PhabricatorClusterImpossibleWriteException.php
<?php final class PhabricatorClusterImpossibleWriteException extends PhabricatorClusterException { public function getExceptionTitle() { return pht('Impossible Cluster Write'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/exception/PhabricatorClusterNoHostForRoleException.php
src/infrastructure/cluster/exception/PhabricatorClusterNoHostForRoleException.php
<?php final class PhabricatorClusterNoHostForRoleException extends Exception { public function __construct($role) { parent::__construct(pht('Search cluster has no hosts for role "%s".', $role)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/exception/PhabricatorClusterExceptionHandler.php
src/infrastructure/cluster/exception/PhabricatorClusterExceptionHandler.php
<?php final class PhabricatorClusterExceptionHandler extends PhabricatorRequestExceptionHandler { public function getRequestExceptionHandlerPriority() { return 300000; } public function getRequestExceptionHandlerDescription() { return pht('Handles runtime problems with cluster configuration.'); } public function canHandleRequestThrowable( AphrontRequest $request, $throwable) { return ($throwable instanceof PhabricatorClusterException); } public function handleRequestThrowable( AphrontRequest $request, $throwable) { $viewer = $this->getViewer($request); $title = $throwable->getExceptionTitle(); $dialog = id(new AphrontDialogView()) ->setTitle($title) ->setUser($viewer) ->appendParagraph($throwable->getMessage()) ->addCancelButton('/', pht('Proceed With Caution')); return id(new AphrontDialogResponse()) ->setDialog($dialog) ->setHTTPResponseCode(500); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/exception/PhabricatorClusterStrandedException.php
src/infrastructure/cluster/exception/PhabricatorClusterStrandedException.php
<?php final class PhabricatorClusterStrandedException extends PhabricatorClusterException { public function getExceptionTitle() { return pht('Unable to Reach Any Database'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/exception/PhabricatorClusterImproperWriteException.php
src/infrastructure/cluster/exception/PhabricatorClusterImproperWriteException.php
<?php final class PhabricatorClusterImproperWriteException extends PhabricatorClusterException { public function getExceptionTitle() { return pht('Improper Cluster Write'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/exception/PhabricatorClusterException.php
src/infrastructure/cluster/exception/PhabricatorClusterException.php
<?php abstract class PhabricatorClusterException extends Exception { abstract public function getExceptionTitle(); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/config/PhabricatorClusterSearchConfigType.php
src/infrastructure/cluster/config/PhabricatorClusterSearchConfigType.php
<?php final class PhabricatorClusterSearchConfigType extends PhabricatorJSONConfigType { const TYPEKEY = 'cluster.search'; public function validateStoredValue( PhabricatorConfigOption $option, $value) { self::validateValue($value); } public static function validateValue($value) { $engines = PhabricatorSearchService::loadAllFulltextStorageEngines(); foreach ($value as $index => $spec) { if (!is_array($spec)) { throw new Exception( pht( 'Search cluster configuration is not valid: each entry in the '. 'list must be a dictionary describing a search service, but '. 'the value with index "%s" is not a dictionary.', $index)); } try { PhutilTypeSpec::checkMap( $spec, array( 'type' => 'string', 'hosts' => 'optional list<map<string, wild>>', 'roles' => 'optional map<string, wild>', 'port' => 'optional int', 'protocol' => 'optional string', 'path' => 'optional string', 'version' => 'optional int', )); } catch (Exception $ex) { throw new Exception( pht( 'Search engine configuration has an invalid service '. 'specification (at index "%s"): %s.', $index, $ex->getMessage())); } if (!array_key_exists($spec['type'], $engines)) { throw new Exception( pht( 'Invalid search engine type: %s. Valid types are: %s.', $spec['type'], implode(', ', array_keys($engines)))); } if (isset($spec['hosts'])) { foreach ($spec['hosts'] as $hostindex => $host) { try { PhutilTypeSpec::checkMap( $host, array( 'host' => 'string', 'roles' => 'optional map<string, wild>', 'port' => 'optional int', 'protocol' => 'optional string', 'path' => 'optional string', 'version' => 'optional int', )); } catch (Exception $ex) { throw new Exception( pht( 'Search cluster configuration has an invalid host '. 'specification (at index "%s"): %s.', $hostindex, $ex->getMessage())); } } } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/config/PhabricatorClusterMailersConfigType.php
src/infrastructure/cluster/config/PhabricatorClusterMailersConfigType.php
<?php final class PhabricatorClusterMailersConfigType extends PhabricatorJSONConfigType { const TYPEKEY = 'cluster.mailers'; public function validateStoredValue( PhabricatorConfigOption $option, $value) { if ($value === null) { return; } if (!is_array($value)) { throw $this->newException( pht( 'Mailer cluster configuration is not valid: it should be a list '. 'of mailer configurations.')); } foreach ($value as $index => $spec) { if (!is_array($spec)) { throw $this->newException( pht( 'Mailer cluster configuration is not valid: each entry in the '. 'list must be a dictionary describing a mailer, but the value '. 'with index "%s" is not a dictionary.', $index)); } } $adapters = PhabricatorMailAdapter::getAllAdapters(); $map = array(); foreach ($value as $index => $spec) { try { PhutilTypeSpec::checkMap( $spec, array( 'key' => 'string', 'type' => 'string', 'priority' => 'optional int', 'options' => 'optional wild', 'inbound' => 'optional bool', 'outbound' => 'optional bool', 'media' => 'optional list<string>', )); } catch (Exception $ex) { throw $this->newException( pht( 'Mailer configuration has an invalid mailer specification '. '(at index "%s"): %s.', $index, $ex->getMessage())); } $key = $spec['key']; if (isset($map[$key])) { throw $this->newException( pht( 'Mailer configuration is invalid: multiple mailers have the same '. 'key ("%s"). Each mailer must have a unique key.', $key)); } $map[$key] = true; $priority = idx($spec, 'priority'); if ($priority !== null && $priority <= 0) { throw $this->newException( pht( 'Mailer configuration ("%s") is invalid: priority must be '. 'greater than 0.', $key)); } $type = $spec['type']; if (!isset($adapters[$type])) { throw $this->newException( pht( 'Mailer configuration ("%s") is invalid: mailer type ("%s") is '. 'unknown. Supported mailer types are: %s.', $key, $type, implode(', ', array_keys($adapters)))); } $options = idx($spec, 'options', array()); try { $defaults = $adapters[$type]->newDefaultOptions(); $options = $options + $defaults; id(clone $adapters[$type])->setOptions($options); } catch (Exception $ex) { throw $this->newException( pht( 'Mailer configuration ("%s") specifies invalid options for '. 'mailer: %s', $key, $ex->getMessage())); } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/config/PhabricatorClusterDatabasesConfigType.php
src/infrastructure/cluster/config/PhabricatorClusterDatabasesConfigType.php
<?php final class PhabricatorClusterDatabasesConfigType extends PhabricatorJSONConfigType { const TYPEKEY = 'cluster.databases'; public function validateStoredValue( PhabricatorConfigOption $option, $value) { foreach ($value as $index => $spec) { if (!is_array($spec)) { throw $this->newException( pht( 'Database cluster configuration is not valid: each entry in the '. 'list must be a dictionary describing a database host, but '. 'the value with index "%s" is not a dictionary.', $index)); } } $masters = array(); $map = array(); foreach ($value as $index => $spec) { try { PhutilTypeSpec::checkMap( $spec, array( 'host' => 'string', 'role' => 'string', 'port' => 'optional int', 'user' => 'optional string', 'pass' => 'optional string', 'disabled' => 'optional bool', 'master' => 'optional string', 'partition' => 'optional list<string>', 'persistent' => 'optional bool', )); } catch (Exception $ex) { throw $this->newException( pht( 'Database cluster configuration has an invalid host '. 'specification (at index "%s"): %s.', $index, $ex->getMessage())); } $role = $spec['role']; $host = $spec['host']; $port = idx($spec, 'port'); switch ($role) { case 'master': case 'replica': break; default: throw $this->newException( pht( 'Database cluster configuration describes an invalid '. 'host ("%s", at index "%s") with an unrecognized role ("%s"). '. 'Valid roles are "%s" or "%s".', $spec['host'], $index, $spec['role'], 'master', 'replica')); } if ($role === 'master') { $masters[] = $host; } // We can't guarantee that you didn't just give the same host two // different names in DNS, but this check can catch silly copy/paste // mistakes. $key = "{$host}:{$port}"; if (isset($map[$key])) { throw $this->newException( pht( 'Database cluster configuration is invalid: it describes the '. 'same host ("%s") multiple times. Each host should appear only '. 'once in the list.', $host)); } $map[$key] = true; } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/search/PhabricatorElasticsearchHost.php
src/infrastructure/cluster/search/PhabricatorElasticsearchHost.php
<?php final class PhabricatorElasticsearchHost extends PhabricatorSearchHost { private $version = 5; private $path = 'phabricator/'; private $protocol = 'http'; const KEY_REFS = 'search.elastic.refs'; public function setConfig($config) { $this->setRoles(idx($config, 'roles', $this->getRoles())) ->setHost(idx($config, 'host', $this->host)) ->setPort(idx($config, 'port', $this->port)) ->setProtocol(idx($config, 'protocol', $this->protocol)) ->setPath(idx($config, 'path', $this->path)) ->setVersion(idx($config, 'version', $this->version)); return $this; } public function getDisplayName() { return pht('Elasticsearch'); } public function getStatusViewColumns() { return array( pht('Protocol') => $this->getProtocol(), pht('Host') => $this->getHost(), pht('Port') => $this->getPort(), pht('Index Path') => $this->getPath(), pht('Elastic Version') => $this->getVersion(), pht('Roles') => implode(', ', array_keys($this->getRoles())), ); } public function setProtocol($protocol) { $this->protocol = $protocol; return $this; } public function getProtocol() { return $this->protocol; } public function setPath($path) { $this->path = $path; return $this; } public function getPath() { return $this->path; } public function setVersion($version) { $this->version = $version; return $this; } public function getVersion() { return $this->version; } public function getURI($to_path = null) { $uri = id(new PhutilURI('http://'.$this->getHost())) ->setProtocol($this->getProtocol()) ->setPort($this->getPort()) ->setPath($this->getPath()); if ($to_path) { $uri->appendPath($to_path); } return $uri; } public function getConnectionStatus() { $status = $this->getEngine()->indexIsSane($this); return $status ? parent::STATUS_OKAY : parent::STATUS_FAIL; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/search/PhabricatorMySQLSearchHost.php
src/infrastructure/cluster/search/PhabricatorMySQLSearchHost.php
<?php final class PhabricatorMySQLSearchHost extends PhabricatorSearchHost { public function setConfig($config) { $this->setRoles(idx($config, 'roles', array('read' => true, 'write' => true))); return $this; } public function getDisplayName() { return 'MySQL'; } public function getStatusViewColumns() { return array( pht('Protocol') => 'mysql', pht('Roles') => implode(', ', array_keys($this->getRoles())), ); } public function getProtocol() { return 'mysql'; } public function getHealthRecord() { if (!$this->healthRecord) { $ref = PhabricatorDatabaseRef::getMasterDatabaseRefForApplication( 'search'); $this->healthRecord = $ref->getHealthRecord(); } return $this->healthRecord; } public function getConnectionStatus() { PhabricatorDatabaseRef::queryAll(); $ref = PhabricatorDatabaseRef::getMasterDatabaseRefForApplication('search'); $status = $ref->getConnectionStatus(); return $status; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/search/PhabricatorSearchHost.php
src/infrastructure/cluster/search/PhabricatorSearchHost.php
<?php abstract class PhabricatorSearchHost extends Phobject { const KEY_REFS = 'cluster.search.refs'; const KEY_HEALTH = 'cluster.search.health'; protected $engine; protected $healthRecord; protected $roles = array(); protected $disabled; protected $host; protected $port; const STATUS_OKAY = 'okay'; const STATUS_FAIL = 'fail'; public function __construct(PhabricatorFulltextStorageEngine $engine) { $this->engine = $engine; } public function setDisabled($disabled) { $this->disabled = $disabled; return $this; } public function getDisabled() { return $this->disabled; } /** * @return PhabricatorFulltextStorageEngine */ public function getEngine() { return $this->engine; } public function isWritable() { return $this->hasRole('write'); } public function isReadable() { return $this->hasRole('read'); } public function hasRole($role) { return isset($this->roles[$role]) && $this->roles[$role] === true; } public function setRoles(array $roles) { foreach ($roles as $role => $val) { $this->roles[$role] = $val; } return $this; } public function getRoles() { $roles = array(); foreach ($this->roles as $key => $val) { if ($val) { $roles[$key] = $val; } } return $roles; } public function setPort($value) { $this->port = $value; return $this; } public function getPort() { return $this->port; } public function setHost($value) { $this->host = $value; return $this; } public function getHost() { return $this->host; } public function getHealthRecordCacheKey() { $host = $this->getHost(); $port = $this->getPort(); $key = self::KEY_HEALTH; return "{$key}({$host}, {$port})"; } /** * @return PhabricatorClusterServiceHealthRecord */ public function getHealthRecord() { if (!$this->healthRecord) { $this->healthRecord = new PhabricatorClusterServiceHealthRecord( $this->getHealthRecordCacheKey()); } return $this->healthRecord; } public function didHealthCheck($reachable) { $record = $this->getHealthRecord(); $should_check = $record->getShouldCheck(); if ($should_check) { $record->didHealthCheck($reachable); } } /** * @return string[] Get a list of fields to show in the status overview UI */ abstract public function getStatusViewColumns(); abstract public function getConnectionStatus(); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/cluster/search/PhabricatorSearchService.php
src/infrastructure/cluster/search/PhabricatorSearchService.php
<?php class PhabricatorSearchService extends Phobject { const KEY_REFS = 'cluster.search.refs'; protected $config; protected $disabled; protected $engine; protected $hosts = array(); protected $hostsConfig; protected $hostType; protected $roles = array(); const STATUS_OKAY = 'okay'; const STATUS_FAIL = 'fail'; const ROLE_WRITE = 'write'; const ROLE_READ = 'read'; public function __construct(PhabricatorFulltextStorageEngine $engine) { $this->engine = $engine; $this->hostType = $engine->getHostType(); } /** * @throws Exception */ public function newHost($config) { $host = clone($this->hostType); $host_config = $this->config + $config; $host->setConfig($host_config); $this->hosts[] = $host; return $host; } public function getEngine() { return $this->engine; } public function getDisplayName() { return $this->hostType->getDisplayName(); } public function getStatusViewColumns() { return $this->hostType->getStatusViewColumns(); } public function setConfig($config) { $this->config = $config; if (!isset($config['hosts'])) { $config['hosts'] = array( array( 'host' => idx($config, 'host'), 'port' => idx($config, 'port'), 'protocol' => idx($config, 'protocol'), 'roles' => idx($config, 'roles'), ), ); } foreach ($config['hosts'] as $host) { $this->newHost($host); } } public function getConfig() { return $this->config; } public static function getConnectionStatusMap() { return array( self::STATUS_OKAY => array( 'icon' => 'fa-exchange', 'color' => 'green', 'label' => pht('Okay'), ), self::STATUS_FAIL => array( 'icon' => 'fa-times', 'color' => 'red', 'label' => pht('Failed'), ), ); } public function isWritable() { return (bool)$this->getAllHostsForRole(self::ROLE_WRITE); } public function isReadable() { return (bool)$this->getAllHostsForRole(self::ROLE_READ); } public function getPort() { return idx($this->config, 'port'); } public function getProtocol() { return idx($this->config, 'protocol'); } public function getVersion() { return idx($this->config, 'version'); } public function getHosts() { return $this->hosts; } /** * Get a random host reference with the specified role, skipping hosts which * failed recent health checks. * @throws PhabricatorClusterNoHostForRoleException if no healthy hosts match. * @return PhabricatorSearchHost */ public function getAnyHostForRole($role) { $hosts = $this->getAllHostsForRole($role); shuffle($hosts); foreach ($hosts as $host) { $health = $host->getHealthRecord(); if ($health->getIsHealthy()) { return $host; } } throw new PhabricatorClusterNoHostForRoleException($role); } /** * Get all configured hosts for this service which have the specified role. * @return PhabricatorSearchHost[] */ public function getAllHostsForRole($role) { // if the role is explicitly set to false at the top level, then all hosts // have the role disabled. if (idx($this->config, $role) === false) { return array(); } $hosts = array(); foreach ($this->hosts as $host) { if ($host->hasRole($role)) { $hosts[] = $host; } } return $hosts; } /** * Get a reference to all configured fulltext search cluster services * @return PhabricatorSearchService[] */ public static function getAllServices() { $cache = PhabricatorCaches::getRequestCache(); $refs = $cache->getKey(self::KEY_REFS); if (!$refs) { $refs = self::newRefs(); $cache->setKey(self::KEY_REFS, $refs); } return $refs; } /** * Load all valid PhabricatorFulltextStorageEngine subclasses */ public static function loadAllFulltextStorageEngines() { return id(new PhutilClassMapQuery()) ->setAncestorClass('PhabricatorFulltextStorageEngine') ->setUniqueMethod('getEngineIdentifier') ->execute(); } /** * Create instances of PhabricatorSearchService based on configuration * @return PhabricatorSearchService[] */ public static function newRefs() { $services = PhabricatorEnv::getEnvConfig('cluster.search'); $engines = self::loadAllFulltextStorageEngines(); $refs = array(); foreach ($services as $config) { // Normally, we've validated configuration before we get this far, but // make sure we don't fatal if we end up here with a bogus configuration. if (!isset($engines[$config['type']])) { throw new Exception( pht( 'Configured search engine type "%s" is unknown. Valid engines '. 'are: %s.', $config['type'], implode(', ', array_keys($engines)))); } $engine = clone($engines[$config['type']]); $cluster = new self($engine); $cluster->setConfig($config); $engine->setService($cluster); $refs[] = $cluster; } return $refs; } /** * (re)index the document: attempt to pass the document to all writable * fulltext search hosts */ public static function reindexAbstractDocument( PhabricatorSearchAbstractDocument $document) { $exceptions = array(); foreach (self::getAllServices() as $service) { if (!$service->isWritable()) { continue; } $engine = $service->getEngine(); try { $engine->reindexAbstractDocument($document); } catch (Exception $ex) { $exceptions[] = $ex; } } if ($exceptions) { throw new PhutilAggregateException( pht( 'Writes to search services failed while reindexing document "%s".', $document->getPHID()), $exceptions); } } /** * Execute a full-text query and return a list of PHIDs of matching objects. * @return string[] * @throws PhutilAggregateException */ public static function executeSearch(PhabricatorSavedQuery $query) { $result_set = self::newResultSet($query); return $result_set->getPHIDs(); } public static function newResultSet(PhabricatorSavedQuery $query) { $exceptions = array(); // try all services until one succeeds foreach (self::getAllServices() as $service) { if (!$service->isReadable()) { continue; } try { $engine = $service->getEngine(); $phids = $engine->executeSearch($query); return id(new PhabricatorFulltextResultSet()) ->setPHIDs($phids) ->setFulltextTokens($engine->getFulltextTokens()); } catch (PhutilSearchQueryCompilerSyntaxException $ex) { // If there's a query compilation error, return it directly to the // user: they issued a query with bad syntax. throw $ex; } catch (Exception $ex) { $exceptions[] = $ex; } } $msg = pht('All of the configured Fulltext Search services failed.'); throw new PhutilAggregateException($msg, $exceptions); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/testing/PhabricatorTestCase.php
src/infrastructure/testing/PhabricatorTestCase.php
<?php abstract class PhabricatorTestCase extends PhutilTestCase { const NAMESPACE_PREFIX = 'phabricator_unittest_'; /** * If true, put Lisk in process-isolated mode for the duration of the tests so * that it will establish only isolated, side-effect-free database * connections. Defaults to true. * * NOTE: You should disable this only in rare circumstances. Unit tests should * not rely on external resources like databases, and should not produce * side effects. */ const PHABRICATOR_TESTCONFIG_ISOLATE_LISK = 'isolate-lisk'; /** * If true, build storage fixtures before running tests, and connect to them * during test execution. This will impose a performance penalty on test * execution (currently, it takes roughly one second to build the fixture) * but allows you to perform tests which require data to be read from storage * after writes. The fixture is shared across all test cases in this process. * Defaults to false. * * NOTE: All connections to fixture storage open transactions when established * and roll them back when tests complete. Each test must independently * write data it relies on; data will not persist across tests. * * NOTE: Enabling this implies disabling process isolation. */ const PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES = 'storage-fixtures'; private $configuration; private $env; private static $storageFixtureReferences = 0; private static $storageFixture; private static $storageFixtureObjectSeed = 0; private static $testsAreRunning = 0; protected function getPhabricatorTestCaseConfiguration() { return array(); } private function getComputedConfiguration() { $config = $this->getPhabricatorTestCaseConfiguration() + array( self::PHABRICATOR_TESTCONFIG_ISOLATE_LISK => true, self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => false, ); if ($config[self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES]) { // Fixtures don't make sense with process isolation. $config[self::PHABRICATOR_TESTCONFIG_ISOLATE_LISK] = false; } return $config; } public function willRunTestCases(array $test_cases) { $root = dirname(phutil_get_library_root('phabricator')); require_once $root.'/scripts/__init_script__.php'; $config = $this->getComputedConfiguration(); if ($config[self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES]) { ++self::$storageFixtureReferences; if (!self::$storageFixture) { self::$storageFixture = $this->newStorageFixture(); } } ++self::$testsAreRunning; } public function didRunTestCases(array $test_cases) { if (self::$storageFixture) { self::$storageFixtureReferences--; if (!self::$storageFixtureReferences) { self::$storageFixture = null; } } --self::$testsAreRunning; } protected function willRunTests() { $config = $this->getComputedConfiguration(); if ($config[self::PHABRICATOR_TESTCONFIG_ISOLATE_LISK]) { LiskDAO::beginIsolateAllLiskEffectsToCurrentProcess(); } $this->env = PhabricatorEnv::beginScopedEnv(); // NOTE: While running unit tests, we act as though all applications are // installed, regardless of the install's configuration. Tests which need // to uninstall applications are responsible for adjusting state themselves // (such tests are exceedingly rare). $this->env->overrideEnvConfig( 'phabricator.uninstalled-applications', array()); $this->env->overrideEnvConfig( 'phabricator.show-prototypes', true); // Reset application settings to defaults, particularly policies. $this->env->overrideEnvConfig( 'phabricator.application-settings', array()); // We can't stub this service right now, and it's not generally useful // to publish notifications about test execution. $this->env->overrideEnvConfig( 'notification.servers', array()); $this->env->overrideEnvConfig( 'phabricator.base-uri', 'http://phabricator.example.com'); $this->env->overrideEnvConfig( 'auth.email-domains', array()); // Tests do their own stubbing/voiding for events. $this->env->overrideEnvConfig('phabricator.silent', false); $this->env->overrideEnvConfig('cluster.read-only', false); $this->env->overrideEnvConfig( 'maniphest.custom-field-definitions', array()); } protected function didRunTests() { $config = $this->getComputedConfiguration(); if ($config[self::PHABRICATOR_TESTCONFIG_ISOLATE_LISK]) { LiskDAO::endIsolateAllLiskEffectsToCurrentProcess(); } try { if (phutil_is_hiphop_runtime()) { $this->env->__destruct(); } unset($this->env); } catch (Exception $ex) { throw new Exception( pht( 'Some test called %s, but is still holding '. 'a reference to the scoped environment!', 'PhabricatorEnv::beginScopedEnv()')); } } protected function willRunOneTest($test) { $config = $this->getComputedConfiguration(); if ($config[self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES]) { LiskDAO::beginIsolateAllLiskEffectsToTransactions(); } } protected function didRunOneTest($test) { $config = $this->getComputedConfiguration(); if ($config[self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES]) { LiskDAO::endIsolateAllLiskEffectsToTransactions(); } } protected function newStorageFixture() { $bytes = Filesystem::readRandomCharacters(24); $name = self::NAMESPACE_PREFIX.$bytes; return new PhabricatorStorageFixtureScopeGuard($name); } /** * Returns an integer seed to use when building unique identifiers (e.g., * non-colliding usernames). The seed is unstable and its value will change * between test runs, so your tests must not rely on it. * * @return int A unique integer. */ protected function getNextObjectSeed() { self::$storageFixtureObjectSeed += mt_rand(1, 100); return self::$storageFixtureObjectSeed; } protected function generateNewTestUser() { $seed = $this->getNextObjectSeed(); $user = id(new PhabricatorUser()) ->setRealName(pht('Test User %s', $seed)) ->setUserName("test{$seed}") ->setIsApproved(1); $email = id(new PhabricatorUserEmail()) ->setAddress("testuser{$seed}@example.com") ->setIsVerified(1); $editor = new PhabricatorUserEditor(); $editor->setActor($user); $editor->createNewUser($user, $email); // When creating a new test user, we prefill their setting cache as empty. // This is a little more efficient than doing a query to load the empty // settings. $user->attachRawCacheData( array( PhabricatorUserPreferencesCacheType::KEY_PREFERENCES => '[]', )); return $user; } /** * Throws unless tests are currently executing. This method can be used to * guard code which is specific to unit tests and should not normally be * reachable. * * If tests aren't currently being executed, throws an exception. */ public static function assertExecutingUnitTests() { if (!self::$testsAreRunning) { throw new Exception( pht( 'Executing test code outside of test execution! '. 'This code path can only be run during unit tests.')); } } protected function requireBinaryForTest($binary) { if (!Filesystem::binaryExists($binary)) { $this->assertSkipped( pht( 'No binary "%s" found on this system, skipping test.', $binary)); } } protected function newContentSource() { return PhabricatorContentSource::newForSource( PhabricatorUnitTestContentSource::SOURCECONST); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/testing/fixture/PhabricatorStorageFixtureScopeGuard.php
src/infrastructure/testing/fixture/PhabricatorStorageFixtureScopeGuard.php
<?php /** * Used by unit tests to build storage fixtures. */ final class PhabricatorStorageFixtureScopeGuard extends Phobject { private $name; public function __construct($name) { $this->name = $name; execx( 'php %s upgrade --force --namespace %s', $this->getStorageBinPath(), $this->name); PhabricatorLiskDAO::pushStorageNamespace($name); // Destructor is not called with fatal error. register_shutdown_function(array($this, 'destroy')); } public function destroy() { PhabricatorLiskDAO::popStorageNamespace(); // NOTE: We need to close all connections before destroying the databases. // If we do not, the "DROP DATABASE ..." statements may hang, waiting for // our connections to close. PhabricatorLiskDAO::closeAllConnections(); execx( 'php %s destroy --force --namespace %s', $this->getStorageBinPath(), $this->name); } private function getStorageBinPath() { $root = dirname(phutil_get_library_root('phabricator')); return $root.'/scripts/sql/manage_storage.php'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/testing/__tests__/PhabricatorTrivialTestCase.php
src/infrastructure/testing/__tests__/PhabricatorTrivialTestCase.php
<?php /** * Trivial example test case. */ final class PhabricatorTrivialTestCase extends PhabricatorTestCase { // NOTE: Update developer/unit_tests.diviner when updating this class! private $two; protected function willRunOneTest($test_name) { // You can execute setup steps which will run before each test in this // method. $this->two = 2; } public function testAllIsRightWithTheWorld() { $this->assertEqual(4, $this->two + $this->two, '2 + 2 = 4'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/syntax/PhabricatorDefaultSyntaxStyle.php
src/infrastructure/syntax/PhabricatorDefaultSyntaxStyle.php
<?php final class PhabricatorDefaultSyntaxStyle extends PhabricatorSyntaxStyle { const STYLEKEY = 'default'; public function getStyleName() { return pht('Default'); } public function getStyleMap() { return array( 'hll' => 'color: #ffffcc', 'c' => 'color: #74777d', 'cm' => 'color: #74777d', 'c1' => 'color: #74777d', 'cs' => 'color: #74777d', 'sd' => 'color: #000000', 'sh' => 'color: #000000', 's' => 'color: #766510', 'sb' => 'color: #766510', 'sc' => 'color: #766510', 's2' => 'color: #766510', 's1' => 'color: #766510', 'sx' => 'color: #766510', 'sr' => 'color: #bb6688', 'nv' => 'color: #001294', 'vi' => 'color: #001294', 'vg' => 'color: #001294', 'na' => 'color: #354bb3', 'kc' => 'color: #000a65', 'no' => 'color: #000a65', 'k' => 'color: #aa4000', 'kd' => 'color: #aa4000', 'kn' => 'color: #aa4000', 'kt' => 'color: #aa4000', 'cp' => 'color: #304a96', 'kp' => 'color: #304a96', 'kr' => 'color: #304a96', 'nb' => 'color: #304a96', 'bp' => 'color: #304a96', 'nc' => 'color: #00702a', 'nt' => 'color: #00702a', 'vc' => 'color: #00702a', 'nf' => 'color: #004012', 'nx' => 'color: #004012', 'o' => 'color: #aa2211', 'ss' => 'color: #aa2211', 'm' => 'color: #601200', 'mf' => 'color: #601200', 'mh' => 'color: #601200', 'mi' => 'color: #601200', 'mo' => 'color: #601200', 'il' => 'color: #601200', 'gd' => 'color: #a00000', 'gr' => 'color: #ff0000', 'gh' => 'color: #000080', 'gi' => 'color: #00a000', 'go' => 'color: #808080', 'gp' => 'color: #000080', 'gu' => 'color: #800080', 'gt' => 'color: #0040d0', 'nd' => 'color: #aa22ff', 'ni' => 'color: #92969d', 'ne' => 'color: #d2413a', 'nl' => 'color: #a0a000', 'nn' => 'color: #0000ff', 'ow' => 'color: #aa22ff', 'w' => 'color: #bbbbbb', 'se' => 'color: #bb6622', 'si' => 'color: #bb66bb', ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/syntax/PhabricatorSyntaxStyle.php
src/infrastructure/syntax/PhabricatorSyntaxStyle.php
<?php abstract class PhabricatorSyntaxStyle extends Phobject { abstract public function getStyleName(); abstract public function getStyleMap(); final public function getStyleOrder() { return (string)id(new PhutilSortVector()) ->addInt($this->isDefaultStyle() ? 0 : 1) ->addString($this->getStyleName()); } final public function getSyntaxStyleKey() { return $this->getPhobjectClassConstant('STYLEKEY'); } final public function isDefaultStyle() { return ($this->getSyntaxStyleKey() == 'default'); } public static function getAllStyles() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getSyntaxStyleKey') ->setSortMethod('getStyleName') ->execute(); } final public function getRemarkupStyleMap() { $map = array( 'rbw_r' => 'color: red', 'rbw_o' => 'color: orange', 'rbw_y' => 'color: yellow', 'rbw_g' => 'color: green', 'rbw_b' => 'color: blue', 'rbw_i' => 'color: indigo', 'rbw_v' => 'color: violet', ); return $map + $this->getStyleMap(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/field/PhabricatorPHIDListExportField.php
src/infrastructure/export/field/PhabricatorPHIDListExportField.php
<?php final class PhabricatorPHIDListExportField extends PhabricatorListExportField { public function getCharacterWidth() { return 32; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/field/PhabricatorStringExportField.php
src/infrastructure/export/field/PhabricatorStringExportField.php
<?php final class PhabricatorStringExportField extends PhabricatorExportField { public function getNaturalValue($value) { if ($value === null) { return $value; } if (!strlen($value)) { return null; } return (string)$value; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/field/PhabricatorIntExportField.php
src/infrastructure/export/field/PhabricatorIntExportField.php
<?php final class PhabricatorIntExportField extends PhabricatorExportField { public function getNaturalValue($value) { if ($value === null) { return $value; } return (int)$value; } /** * @phutil-external-symbol class PHPExcel_Cell_DataType */ public function formatPHPExcelCell($cell, $style) { $cell->setDataType(PHPExcel_Cell_DataType::TYPE_NUMERIC); } public function getCharacterWidth() { return 8; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/field/PhabricatorOptionExportField.php
src/infrastructure/export/field/PhabricatorOptionExportField.php
<?php final class PhabricatorOptionExportField extends PhabricatorExportField { private $options; public function setOptions(array $options) { $this->options = $options; return $this; } public function getOptions() { return $this->options; } public function getNaturalValue($value) { if ($value === null) { return $value; } if (!strlen($value)) { return null; } $options = $this->getOptions(); return array( 'value' => (string)$value, 'name' => (string)idx($options, $value, $value), ); } public function getTextValue($value) { $natural_value = $this->getNaturalValue($value); if ($natural_value === null) { return null; } return $natural_value['name']; } public function getPHPExcelValue($value) { return $this->getTextValue($value); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/field/PhabricatorStringListExportField.php
src/infrastructure/export/field/PhabricatorStringListExportField.php
<?php final class PhabricatorStringListExportField extends PhabricatorListExportField {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/field/PhabricatorIDExportField.php
src/infrastructure/export/field/PhabricatorIDExportField.php
<?php final class PhabricatorIDExportField extends PhabricatorExportField { public function getNaturalValue($value) { return (int)$value; } public function getCharacterWidth() { return 12; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/field/PhabricatorExportField.php
src/infrastructure/export/field/PhabricatorExportField.php
<?php abstract class PhabricatorExportField extends Phobject { private $key; private $label; public function setKey($key) { $this->key = $key; return $this; } public function getKey() { return $this->key; } public function setLabel($label) { $this->label = $label; return $this; } public function getLabel() { return $this->label; } public function getTextValue($value) { $natural_value = $this->getNaturalValue($value); if ($natural_value === null) { return null; } return (string)$natural_value; } public function getNaturalValue($value) { return $value; } public function getPHPExcelValue($value) { return $this->getTextValue($value); } /** * @phutil-external-symbol class PHPExcel_Cell_DataType */ public function formatPHPExcelCell($cell, $style) { $cell->setDataType(PHPExcel_Cell_DataType::TYPE_STRING); } public function getCharacterWidth() { return 24; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/field/PhabricatorPHIDExportField.php
src/infrastructure/export/field/PhabricatorPHIDExportField.php
<?php final class PhabricatorPHIDExportField extends PhabricatorExportField { public function getCharacterWidth() { return 32; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/field/PhabricatorEpochExportField.php
src/infrastructure/export/field/PhabricatorEpochExportField.php
<?php final class PhabricatorEpochExportField extends PhabricatorExportField { private $zone; public function getTextValue($value) { if ($value === null) { return ''; } if (!isset($this->zone)) { $this->zone = new DateTimeZone('UTC'); } try { $date = new DateTime('@'.$value); } catch (Exception $ex) { return null; } $date->setTimezone($this->zone); return $date->format('c'); } public function getNaturalValue($value) { if ($value === null) { return $value; } return (int)$value; } public function getPHPExcelValue($value) { $epoch = $this->getNaturalValue($value); if ($epoch === null) { return null; } $seconds_per_day = phutil_units('1 day in seconds'); $offset = ($seconds_per_day * 25569); return ($epoch + $offset) / $seconds_per_day; } /** * @phutil-external-symbol class PHPExcel_Style_NumberFormat */ public function formatPHPExcelCell($cell, $style) { $code = PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2; $style ->getNumberFormat() ->setFormatCode($code); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/field/PhabricatorListExportField.php
src/infrastructure/export/field/PhabricatorListExportField.php
<?php abstract class PhabricatorListExportField extends PhabricatorExportField { public function getTextValue($value) { return implode("\n", $value); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/field/PhabricatorURIExportField.php
src/infrastructure/export/field/PhabricatorURIExportField.php
<?php final class PhabricatorURIExportField extends PhabricatorExportField {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/field/PhabricatorDoubleExportField.php
src/infrastructure/export/field/PhabricatorDoubleExportField.php
<?php final class PhabricatorDoubleExportField extends PhabricatorExportField { public function getNaturalValue($value) { if ($value === null) { return $value; } return (double)$value; } /** * @phutil-external-symbol class PHPExcel_Cell_DataType */ public function formatPHPExcelCell($cell, $style) { $cell->setDataType(PHPExcel_Cell_DataType::TYPE_NUMERIC); } public function getCharacterWidth() { return 8; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/format/PhabricatorJSONExportFormat.php
src/infrastructure/export/format/PhabricatorJSONExportFormat.php
<?php final class PhabricatorJSONExportFormat extends PhabricatorExportFormat { const EXPORTKEY = 'json'; private $objects = array(); public function getExportFormatName() { return 'JSON (.json)'; } public function isExportFormatEnabled() { return true; } public function getFileExtension() { return 'json'; } public function getMIMEContentType() { return 'application/json'; } public function addObject($object, array $fields, array $map) { $values = array(); foreach ($fields as $key => $field) { $value = $map[$key]; $value = $field->getNaturalValue($value); $values[$key] = $value; } $this->objects[] = $values; } public function newFileData() { return id(new PhutilJSON()) ->encodeAsList($this->objects); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/format/PhabricatorExportFormat.php
src/infrastructure/export/format/PhabricatorExportFormat.php
<?php abstract class PhabricatorExportFormat extends Phobject { private $viewer; private $title; final public function getExportFormatKey() { return $this->getPhobjectClassConstant('EXPORTKEY'); } final public function setViewer(PhabricatorUser $viewer) { $this->viewer = $viewer; return $this; } final public function getViewer() { return $this->viewer; } final public function setTitle($title) { $this->title = $title; return $this; } final public function getTitle() { return $this->title; } abstract public function getExportFormatName(); abstract public function getMIMEContentType(); abstract public function getFileExtension(); public function addHeaders(array $fields) { return; } abstract public function addObject($object, array $fields, array $map); abstract public function newFileData(); public function isExportFormatEnabled() { return true; } final public static function getAllExportFormats() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getExportFormatKey') ->execute(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/format/PhabricatorExcelExportFormat.php
src/infrastructure/export/format/PhabricatorExcelExportFormat.php
<?php final class PhabricatorExcelExportFormat extends PhabricatorExportFormat { const EXPORTKEY = 'excel'; private $workbook; private $sheet; private $rowCursor; public function getExportFormatName() { return pht('Excel (.xlsx)'); } public function isExportFormatEnabled() { if (!extension_loaded('zip')) { return false; } return @include_once 'PHPExcel.php'; } public function getInstallInstructions() { if (!extension_loaded('zip')) { return pht(<<<EOHELP Data can not be exported to Excel because the "zip" PHP extension is not installed. Consult the setup issue in the Config application for guidance on installing the extension. EOHELP ); } return pht(<<<EOHELP Data can not be exported to Excel because the PHPExcel library is not installed. This software component is required to create Excel files. You can install PHPExcel from GitHub: > https://github.com/PHPOffice/PHPExcel Briefly: - Clone that repository somewhere on the sever (like `/path/to/example/PHPExcel`). - Update your PHP `%s` setting (in `php.ini`) to include the PHPExcel `Classes` directory (like `/path/to/example/PHPExcel/Classes`). EOHELP , 'include_path'); } public function getFileExtension() { return 'xlsx'; } public function getMIMEContentType() { return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; } /** * @phutil-external-symbol class PHPExcel_Cell_DataType */ public function addHeaders(array $fields) { $sheet = $this->getSheet(); $header_format = array( 'font' => array( 'bold' => true, ), ); $row = 1; $col = 0; foreach ($fields as $field) { $cell_value = $field->getLabel(); $cell_name = $this->getCellName($col, $row); $cell = $sheet->setCellValue( $cell_name, $cell_value, $return_cell = true); $sheet->getStyle($cell_name)->applyFromArray($header_format); $cell->setDataType(PHPExcel_Cell_DataType::TYPE_STRING); $width = $field->getCharacterWidth(); if ($width !== null) { $col_name = $this->getCellName($col); $sheet->getColumnDimension($col_name) ->setWidth($width); } $col++; } } public function addObject($object, array $fields, array $map) { $sheet = $this->getSheet(); $col = 0; foreach ($fields as $key => $field) { $cell_value = $map[$key]; $cell_value = $field->getPHPExcelValue($cell_value); $cell_name = $this->getCellName($col, $this->rowCursor); $cell = $sheet->setCellValue( $cell_name, $cell_value, $return_cell = true); $style = $sheet->getStyle($cell_name); $field->formatPHPExcelCell($cell, $style); $col++; } $this->rowCursor++; } /** * @phutil-external-symbol class PHPExcel_IOFactory */ public function newFileData() { $workbook = $this->getWorkbook(); $writer = PHPExcel_IOFactory::createWriter($workbook, 'Excel2007'); ob_start(); $writer->save('php://output'); $data = ob_get_clean(); return $data; } private function getWorkbook() { if (!$this->workbook) { $this->workbook = $this->newWorkbook(); } return $this->workbook; } /** * @phutil-external-symbol class PHPExcel */ private function newWorkbook() { include_once 'PHPExcel.php'; return new PHPExcel(); } private function getSheet() { if (!$this->sheet) { $workbook = $this->getWorkbook(); $sheet = $workbook->setActiveSheetIndex(0); $sheet->setTitle($this->getTitle()); $this->sheet = $sheet; // The row cursor starts on the second row, after the header row. $this->rowCursor = 2; } return $this->sheet; } /** * @phutil-external-symbol class PHPExcel_Cell */ private function getCellName($col, $row = null) { $col_name = PHPExcel_Cell::stringFromColumnIndex($col); if ($row === null) { return $col_name; } return $col_name.$row; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/format/PhabricatorCSVExportFormat.php
src/infrastructure/export/format/PhabricatorCSVExportFormat.php
<?php final class PhabricatorCSVExportFormat extends PhabricatorExportFormat { const EXPORTKEY = 'csv'; private $rows = array(); public function getExportFormatName() { return pht('Comma-Separated Values (.csv)'); } public function isExportFormatEnabled() { return true; } public function getFileExtension() { return 'csv'; } public function getMIMEContentType() { return 'text/csv'; } public function addHeaders(array $fields) { $headers = mpull($fields, 'getLabel'); $this->addRow($headers); } public function addObject($object, array $fields, array $map) { $values = array(); foreach ($fields as $key => $field) { $value = $map[$key]; $value = $field->getTextValue($value); $values[] = $value; } $this->addRow($values); } private function addRow(array $values) { $row = array(); foreach ($values as $value) { // Excel is extremely interested in executing arbitrary code it finds in // untrusted CSV files downloaded from the internet. When a cell looks // like it might be too tempting for Excel to ignore, mangle the value // to dissuade remote code execution. See T12800. if (preg_match('/^\s*[+=@-]/', $value)) { $value = '(!) '.$value; } if (preg_match('/\s|,|\"/', $value)) { $value = str_replace('"', '""', $value); $value = '"'.$value.'"'; } $row[] = $value; } $this->rows[] = implode(',', $row); } public function newFileData() { return implode("\n", $this->rows); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/format/PhabricatorTextExportFormat.php
src/infrastructure/export/format/PhabricatorTextExportFormat.php
<?php final class PhabricatorTextExportFormat extends PhabricatorExportFormat { const EXPORTKEY = 'text'; private $rows = array(); public function getExportFormatName() { return 'Tab-Separated Text (.txt)'; } public function isExportFormatEnabled() { return true; } public function getFileExtension() { return 'txt'; } public function getMIMEContentType() { return 'text/plain'; } public function addHeaders(array $fields) { $headers = mpull($fields, 'getLabel'); $this->addRow($headers); } public function addObject($object, array $fields, array $map) { $values = array(); foreach ($fields as $key => $field) { $value = $map[$key]; $value = $field->getTextValue($value); $values[] = $value; } $this->addRow($values); } private function addRow(array $values) { $row = array(); foreach ($values as $value) { $row[] = addcslashes($value, "\0..\37\\\177..\377"); } $this->rows[] = implode("\t", $row); } public function newFileData() { return implode("\n", $this->rows)."\n"; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/engine/PhabricatorProjectsExportEngineExtension.php
src/infrastructure/export/engine/PhabricatorProjectsExportEngineExtension.php
<?php final class PhabricatorProjectsExportEngineExtension extends PhabricatorExportEngineExtension { const EXTENSIONKEY = 'projects'; public function supportsObject($object) { return ($object instanceof PhabricatorProjectInterface); } public function newExportFields() { return array( id(new PhabricatorPHIDListExportField()) ->setKey('tagPHIDs') ->setLabel(pht('Tag PHIDs')), id(new PhabricatorStringListExportField()) ->setKey('tags') ->setLabel(pht('Tags')), ); } public function newExportData(array $objects) { $viewer = $this->getViewer(); $object_phids = mpull($objects, 'getPHID'); $projects_query = id(new PhabricatorEdgeQuery()) ->withSourcePHIDs($object_phids) ->withEdgeTypes( array( PhabricatorProjectObjectHasProjectEdgeType::EDGECONST, )); $projects_query->execute(); $handles = $viewer->loadHandles($projects_query->getDestinationPHIDs()); $map = array(); foreach ($objects as $object) { $object_phid = $object->getPHID(); $project_phids = $projects_query->getDestinationPHIDs( array($object_phid), array(PhabricatorProjectObjectHasProjectEdgeType::EDGECONST)); $handle_list = $handles->newSublist($project_phids); $handle_list = iterator_to_array($handle_list); $handle_names = mpull($handle_list, 'getName'); $handle_names = array_values($handle_names); $map[] = array( 'tagPHIDs' => $project_phids, 'tags' => $handle_names, ); } return $map; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/engine/PhabricatorExportEngineBulkJobType.php
src/infrastructure/export/engine/PhabricatorExportEngineBulkJobType.php
<?php final class PhabricatorExportEngineBulkJobType extends PhabricatorWorkerSingleBulkJobType { public function getBulkJobTypeKey() { return 'export'; } public function getJobName(PhabricatorWorkerBulkJob $job) { return pht('Data Export'); } public function getCurtainActions( PhabricatorUser $viewer, PhabricatorWorkerBulkJob $job) { $actions = array(); $file_phid = $job->getParameter('filePHID'); if (!$file_phid) { $actions[] = id(new PhabricatorActionView()) ->setHref('#') ->setIcon('fa-download') ->setDisabled(true) ->setName(pht('Exporting Data...')); } else { $file = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($file_phid)) ->executeOne(); if (!$file) { $actions[] = id(new PhabricatorActionView()) ->setHref('#') ->setIcon('fa-download') ->setDisabled(true) ->setName(pht('Temporary File Expired')); } else { $actions[] = id(new PhabricatorActionView()) ->setHref($file->getDownloadURI()) ->setIcon('fa-download') ->setName(pht('Download Data Export')); } } return $actions; } public function runTask( PhabricatorUser $actor, PhabricatorWorkerBulkJob $job, PhabricatorWorkerBulkTask $task) { $engine_class = $job->getParameter('engineClass'); if (!is_subclass_of($engine_class, 'PhabricatorApplicationSearchEngine')) { throw new Exception( pht( 'Unknown search engine class "%s".', $engine_class)); } $engine = newv($engine_class, array()) ->setViewer($actor); $query_key = $job->getParameter('queryKey'); if ($engine->isBuiltinQuery($query_key)) { $saved_query = $engine->buildSavedQueryFromBuiltin($query_key); } else if ($query_key) { $saved_query = id(new PhabricatorSavedQueryQuery()) ->setViewer($actor) ->withQueryKeys(array($query_key)) ->executeOne(); } else { $saved_query = null; } if (!$saved_query) { throw new Exception( pht( 'Failed to load saved query ("%s").', $query_key)); } $format_key = $job->getParameter('formatKey'); $all_formats = PhabricatorExportFormat::getAllExportFormats(); $format = idx($all_formats, $format_key); if (!$format) { throw new Exception( pht( 'Unknown export format ("%s").', $format_key)); } if (!$format->isExportFormatEnabled()) { throw new Exception( pht( 'Export format ("%s") is not enabled.', $format_key)); } $export_engine = id(new PhabricatorExportEngine()) ->setViewer($actor) ->setTitle($job->getParameter('title')) ->setFilename($job->getParameter('filename')) ->setSearchEngine($engine) ->setSavedQuery($saved_query) ->setExportFormat($format); $file = $export_engine->exportFile(); $job ->setParameter('filePHID', $file->getPHID()) ->save(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/engine/PhabricatorCustomFieldExportEngineExtension.php
src/infrastructure/export/engine/PhabricatorCustomFieldExportEngineExtension.php
<?php final class PhabricatorCustomFieldExportEngineExtension extends PhabricatorExportEngineExtension { const EXTENSIONKEY = 'custom-field'; private $object; public function supportsObject($object) { $this->object = $object; return ($object instanceof PhabricatorCustomFieldInterface); } public function newExportFields() { $prototype = $this->object; $fields = $this->newCustomFields($prototype); $results = array(); foreach ($fields as $field) { $field_key = $field->getModernFieldKey(); $results[] = $field->newExportField() ->setKey($field_key); } return $results; } public function newExportData(array $objects) { $viewer = $this->getViewer(); $field_map = array(); foreach ($objects as $object) { $object_phid = $object->getPHID(); $fields = PhabricatorCustomField::getObjectFields( $object, PhabricatorCustomField::ROLE_EXPORT); $fields ->setViewer($viewer) ->readFieldsFromObject($object); $field_map[$object_phid] = $fields; } $all_fields = array(); foreach ($field_map as $field_list) { foreach ($field_list->getFields() as $field) { $all_fields[] = $field; } } id(new PhabricatorCustomFieldStorageQuery()) ->addFields($all_fields) ->execute(); $results = array(); foreach ($objects as $object) { $object_phid = $object->getPHID(); $object_fields = $field_map[$object_phid]; $map = array(); foreach ($object_fields->getFields() as $field) { $key = $field->getModernFieldKey(); $map[$key] = $field->newExportData(); } $results[] = $map; } return $results; } private function newCustomFields($object) { $fields = PhabricatorCustomField::getObjectFields( $object, PhabricatorCustomField::ROLE_EXPORT); $fields->setViewer($this->getViewer()); return $fields->getFields(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/engine/PhabricatorSubscriptionsExportEngineExtension.php
src/infrastructure/export/engine/PhabricatorSubscriptionsExportEngineExtension.php
<?php final class PhabricatorSubscriptionsExportEngineExtension extends PhabricatorExportEngineExtension { const EXTENSIONKEY = 'subscriptions'; public function supportsObject($object) { return ($object instanceof PhabricatorSubscribableInterface); } public function newExportFields() { return array( id(new PhabricatorPHIDListExportField()) ->setKey('subscriberPHIDs') ->setLabel(pht('Subscriber PHIDs')), id(new PhabricatorStringListExportField()) ->setKey('subscribers') ->setLabel(pht('Subscribers')), ); } public function newExportData(array $objects) { $viewer = $this->getViewer(); $object_phids = mpull($objects, 'getPHID'); $projects_query = id(new PhabricatorEdgeQuery()) ->withSourcePHIDs($object_phids) ->withEdgeTypes( array( PhabricatorObjectHasSubscriberEdgeType::EDGECONST, )); $projects_query->execute(); $handles = $viewer->loadHandles($projects_query->getDestinationPHIDs()); $map = array(); foreach ($objects as $object) { $object_phid = $object->getPHID(); $project_phids = $projects_query->getDestinationPHIDs( array($object_phid), array(PhabricatorObjectHasSubscriberEdgeType::EDGECONST)); $handle_list = $handles->newSublist($project_phids); $handle_list = iterator_to_array($handle_list); $handle_names = mpull($handle_list, 'getName'); $handle_names = array_values($handle_names); $map[] = array( 'subscriberPHIDs' => $project_phids, 'subscribers' => $handle_names, ); } return $map; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/engine/PhabricatorLiskExportEngineExtension.php
src/infrastructure/export/engine/PhabricatorLiskExportEngineExtension.php
<?php final class PhabricatorLiskExportEngineExtension extends PhabricatorExportEngineExtension { const EXTENSIONKEY = 'lisk'; public function supportsObject($object) { if (!($object instanceof LiskDAO)) { return false; } if (!$object->getConfigOption(LiskDAO::CONFIG_TIMESTAMPS)) { return false; } return true; } public function newExportFields() { return array( id(new PhabricatorEpochExportField()) ->setKey('dateCreated') ->setLabel(pht('Created')), id(new PhabricatorEpochExportField()) ->setKey('dateModified') ->setLabel(pht('Modified')), ); } public function newExportData(array $objects) { $map = array(); foreach ($objects as $object) { $map[] = array( 'dateCreated' => $object->getDateCreated(), 'dateModified' => $object->getDateModified(), ); } return $map; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/engine/PhabricatorSpacesExportEngineExtension.php
src/infrastructure/export/engine/PhabricatorSpacesExportEngineExtension.php
<?php final class PhabricatorSpacesExportEngineExtension extends PhabricatorExportEngineExtension { const EXTENSIONKEY = 'spaces'; public function supportsObject($object) { $viewer = $this->getViewer(); if (!PhabricatorSpacesNamespaceQuery::getViewerSpacesExist($viewer)) { return false; } return ($object instanceof PhabricatorSpacesInterface); } public function newExportFields() { return array( id(new PhabricatorPHIDExportField()) ->setKey('spacePHID') ->setLabel(pht('Space PHID')), id(new PhabricatorStringExportField()) ->setKey('space') ->setLabel(pht('Space')), ); } public function newExportData(array $objects) { $viewer = $this->getViewer(); $space_phids = array(); foreach ($objects as $object) { $space_phids[] = PhabricatorSpacesNamespaceQuery::getObjectSpacePHID( $object); } $handles = $viewer->loadHandles($space_phids); $map = array(); foreach ($objects as $object) { $space_phid = PhabricatorSpacesNamespaceQuery::getObjectSpacePHID( $object); $map[] = array( 'spacePHID' => $space_phid, 'space' => $handles[$space_phid]->getName(), ); } return $map; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/engine/PhabricatorExportEngineExtension.php
src/infrastructure/export/engine/PhabricatorExportEngineExtension.php
<?php abstract class PhabricatorExportEngineExtension extends Phobject { private $viewer; final public function getExtensionKey() { return $this->getPhobjectClassConstant('EXTENSIONKEY'); } final public function setViewer($viewer) { $this->viewer = $viewer; return $this; } final public function getViewer() { return $this->viewer; } abstract public function supportsObject($object); abstract public function newExportFields(); abstract public function newExportData(array $objects); final public static function getAllExtensions() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getExtensionKey') ->execute(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/engine/PhabricatorExportFormatSetting.php
src/infrastructure/export/engine/PhabricatorExportFormatSetting.php
<?php final class PhabricatorExportFormatSetting extends PhabricatorInternalSetting { const SETTINGKEY = 'export.format'; public function getSettingName() { return pht('Export Format'); } public function getSettingDefaultValue() { return null; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/export/engine/PhabricatorExportEngine.php
src/infrastructure/export/engine/PhabricatorExportEngine.php
<?php final class PhabricatorExportEngine extends Phobject { private $viewer; private $searchEngine; private $savedQuery; private $exportFormat; private $filename; private $title; public function setViewer(PhabricatorUser $viewer) { $this->viewer = $viewer; return $this; } public function getViewer() { return $this->viewer; } public function setSearchEngine( PhabricatorApplicationSearchEngine $search_engine) { $this->searchEngine = $search_engine; return $this; } public function getSearchEngine() { return $this->searchEngine; } public function setSavedQuery(PhabricatorSavedQuery $saved_query) { $this->savedQuery = $saved_query; return $this; } public function getSavedQuery() { return $this->savedQuery; } public function setExportFormat( PhabricatorExportFormat $export_format) { $this->exportFormat = $export_format; return $this; } public function getExportFormat() { return $this->exportFormat; } public function setFilename($filename) { $this->filename = $filename; return $this; } public function getFilename() { return $this->filename; } public function setTitle($title) { $this->title = $title; return $this; } public function getTitle() { return $this->title; } public function newBulkJob(AphrontRequest $request) { $viewer = $this->getViewer(); $engine = $this->getSearchEngine(); $saved_query = $this->getSavedQuery(); $format = $this->getExportFormat(); $params = array( 'engineClass' => get_class($engine), 'queryKey' => $saved_query->getQueryKey(), 'formatKey' => $format->getExportFormatKey(), 'title' => $this->getTitle(), 'filename' => $this->getFilename(), ); $job = PhabricatorWorkerBulkJob::initializeNewJob( $viewer, new PhabricatorExportEngineBulkJobType(), $params); // We queue these jobs directly into STATUS_WAITING without requiring // a confirmation from the user. $xactions = array(); $xactions[] = id(new PhabricatorWorkerBulkJobTransaction()) ->setTransactionType(PhabricatorWorkerBulkJobTransaction::TYPE_STATUS) ->setNewValue(PhabricatorWorkerBulkJob::STATUS_WAITING); $editor = id(new PhabricatorWorkerBulkJobEditor()) ->setActor($viewer) ->setContentSourceFromRequest($request) ->setContinueOnMissingFields(true) ->applyTransactions($job, $xactions); return $job; } public function exportFile() { $viewer = $this->getViewer(); $engine = $this->getSearchEngine(); $saved_query = $this->getSavedQuery(); $format = $this->getExportFormat(); $title = $this->getTitle(); $filename = $this->getFilename(); $query = $engine->buildQueryFromSavedQuery($saved_query); $extension = $format->getFileExtension(); $mime_type = $format->getMIMEContentType(); $filename = $filename.'.'.$extension; $format = id(clone $format) ->setViewer($viewer) ->setTitle($title); $field_list = $engine->newExportFieldList(); $field_list = mpull($field_list, null, 'getKey'); $format->addHeaders($field_list); // Iterate over the query results in large pages so we don't have to hold // too much stuff in memory. $page_size = 1000; $page_cursor = null; do { $pager = $engine->newPagerForSavedQuery($saved_query); $pager->setPageSize($page_size); if ($page_cursor !== null) { $pager->setAfterID($page_cursor); } $objects = $engine->executeQuery($query, $pager); $objects = array_values($objects); $page_cursor = $pager->getNextPageID(); $export_data = $engine->newExport($objects); for ($ii = 0; $ii < count($objects); $ii++) { $format->addObject($objects[$ii], $field_list, $export_data[$ii]); } } while ($pager->getHasMoreResults()); $export_result = $format->newFileData(); // We have all the data in one big string and aren't actually // streaming it, but pretending that we are allows us to actviate // the chunk engine and store large files. $iterator = new ArrayIterator(array($export_result)); $source = id(new PhabricatorIteratorFileUploadSource()) ->setName($filename) ->setViewPolicy(PhabricatorPolicies::POLICY_NOONE) ->setMIMEType($mime_type) ->setRelativeTTL(phutil_units('60 minutes in seconds')) ->setAuthorPHID($viewer->getPHID()) ->setIterator($iterator); return $source->uploadFile(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/status/PhabricatorObjectStatus.php
src/infrastructure/status/PhabricatorObjectStatus.php
<?php abstract class PhabricatorObjectStatus extends Phobject { private $key; private $properties; protected function __construct($key = null, array $properties = array()) { $this->key = $key; $this->properties = $properties; } protected function getStatusProperty($key) { if (!array_key_exists($key, $this->properties)) { throw new Exception( pht( 'Attempting to access unknown status property ("%s").', $key)); } return $this->properties[$key]; } public function getKey() { return $this->key; } public function getIcon() { return $this->getStatusProperty('icon'); } public function getDisplayName() { return $this->getStatusProperty('name'); } public function getColor() { return $this->getStatusProperty('color'); } protected function getStatusSpecification($status) { $map = self::getStatusSpecifications(); if (isset($map[$status])) { return $map[$status]; } return array( 'key' => $status, 'name' => pht('Unknown ("%s")', $status), 'icon' => 'fa-question-circle', 'color' => 'indigo', ) + $this->newUnknownStatusSpecification($status); } protected function getStatusSpecifications() { $map = $this->newStatusSpecifications(); $result = array(); foreach ($map as $item) { if (!array_key_exists('key', $item)) { throw new Exception(pht('Status specification has no "key".')); } $key = $item['key']; if (isset($result[$key])) { throw new Exception( pht( 'Multiple status definitions share the same key ("%s").', $key)); } $result[$key] = $item; } return $result; } abstract protected function newStatusSpecifications(); protected function newUnknownStatusSpecification($status) { return array(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/log/PhabricatorProtocolLog.php
src/infrastructure/log/PhabricatorProtocolLog.php
<?php final class PhabricatorProtocolLog extends Phobject { private $logfile; private $mode; private $buffer = array(); public function __construct($logfile) { $this->logfile = $logfile; } public function didStartSession($session_name) { $this->setMode('!'); $this->buffer[] = $session_name; $this->flush(); } public function didEndSession() { $this->setMode('_'); $this->buffer[] = pht('<End of Session>'); $this->flush(); } public function didWriteBytes($bytes) { if (!strlen($bytes)) { return; } $this->setMode('>'); $this->buffer[] = $bytes; } public function didReadBytes($bytes) { if (!strlen($bytes)) { return; } $this->setMode('<'); $this->buffer[] = $bytes; } public function didReadFrame($frame) { $this->writeFrame('<*', $frame); } public function didWriteFrame($frame) { $this->writeFrame('>*', $frame); } private function writeFrame($header, $frame) { $this->flush(); $frame = explode("\n", $frame); foreach ($frame as $key => $line) { $frame[$key] = $header.' '.$this->escapeBytes($line); } $frame = implode("\n", $frame)."\n\n"; $this->writeMessage($frame); } private function setMode($mode) { if ($this->mode === $mode) { return $this; } if ($this->mode !== null) { $this->flush(); } $this->mode = $mode; return $this; } private function flush() { $mode = $this->mode; $bytes = $this->buffer; $this->mode = null; $this->buffer = array(); $bytes = implode('', $bytes); if (strlen($bytes)) { $this->writeBytes($mode, $bytes); } } private function writeBytes($mode, $bytes) { $header = $mode; $len = strlen($bytes); $out = array(); switch ($mode) { case '<': $out[] = pht('%s Write [%s bytes]', $header, new PhutilNumber($len)); break; case '>': $out[] = pht('%s Read [%s bytes]', $header, new PhutilNumber($len)); break; default: $out[] = pht( '%s %s', $header, $this->escapeBytes($bytes)); break; } switch ($mode) { case '<': case '>': $out[] = $this->renderBytes($header, $bytes); break; } $out = implode("\n", $out)."\n\n"; $this->writeMessage($out); } private function renderBytes($header, $bytes) { $bytes_per_line = 48; $bytes_per_chunk = 4; // Compute the width of the "bytes" display section, which looks like // this: // // > 00112233 44556677 abcdefgh // ^^^^^^^^^^^^^^^^^ // // We need to figure this out so we can align the plain text in the far // right column appropriately. // The character width of the "bytes" part of a full display line. If // we're rendering 48 bytes per line, we'll need 96 characters, since // each byte is printed as a 2-character hexadecimal code. $display_bytes = ($bytes_per_line * 2); // The character width of the number of spaces in between the "bytes" // chunks. If we're rendering 12 chunks per line, we'll put 11 spaces // in between them to separate them. $display_spaces = (($bytes_per_line / $bytes_per_chunk) - 1); $pad_bytes = $display_bytes + $display_spaces; // When the protocol is plaintext, try to break it on newlines so it's // easier to read. $pos = 0; $lines = array(); while (true) { $next_break = strpos($bytes, "\n", $pos); if ($next_break === false) { $len = strlen($bytes) - $pos; } else { $len = ($next_break - $pos) + 1; } $len = min($bytes_per_line, $len); $next_bytes = substr($bytes, $pos, $len); $chunk_parts = array(); foreach (str_split($next_bytes, $bytes_per_chunk) as $chunk) { $chunk_display = ''; for ($ii = 0; $ii < strlen($chunk); $ii++) { $chunk_display .= sprintf('%02x', ord($chunk[$ii])); } $chunk_parts[] = $chunk_display; } $chunk_parts = implode(' ', $chunk_parts); $chunk_parts = str_pad($chunk_parts, $pad_bytes, ' '); $lines[] = $header.' '.$chunk_parts.' '.$this->escapeBytes($next_bytes); $pos += $len; if ($pos >= strlen($bytes)) { break; } } $lines = implode("\n", $lines); return $lines; } private function escapeBytes($bytes) { $result = ''; for ($ii = 0; $ii < strlen($bytes); $ii++) { $c = $bytes[$ii]; $o = ord($c); if ($o >= 0x20 && $o <= 0x7F) { $result .= $c; } else { $result .= '.'; } } return $result; } private function writeMessage($message) { $f = fopen($this->logfile, 'a'); fwrite($f, $message); fflush($f); fclose($f); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/log/PhabricatorAccessLog.php
src/infrastructure/log/PhabricatorAccessLog.php
<?php final class PhabricatorAccessLog extends Phobject { private static $log; public static function init() { // NOTE: This currently has no effect, but some day we may reuse PHP // interpreters to run multiple requests. If we do, it has the effect of // throwing away the old log. self::$log = null; } public static function getLog() { if (!self::$log) { $path = PhabricatorEnv::getEnvConfig('log.access.path'); $format = PhabricatorEnv::getEnvConfig('log.access.format'); $format = nonempty( $format, "[%D]\t%p\t%h\t%r\t%u\t%C\t%m\t%U\t%R\t%c\t%T"); // NOTE: Path may be null. We still create the log, it just won't write // anywhere. $log = id(new PhutilDeferredLog($path, $format)) ->setFailQuietly(true) ->setData( array( 'D' => date('r'), 'h' => php_uname('n'), 'p' => getmypid(), 'e' => time(), 'I' => PhabricatorEnv::getEnvConfig('cluster.instance'), )); self::$log = $log; } return self::$log; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/log/PhabricatorSSHLog.php
src/infrastructure/log/PhabricatorSSHLog.php
<?php final class PhabricatorSSHLog extends Phobject { private static $log; public static function getLog() { if (!self::$log) { $path = PhabricatorEnv::getEnvConfig('log.ssh.path'); $format = PhabricatorEnv::getEnvConfig('log.ssh.format'); $format = nonempty( $format, "[%D]\t%p\t%h\t%r\t%s\t%S\t%u\t%C\t%U\t%c\t%T\t%i\t%o"); // NOTE: Path may be null. We still create the log, it just won't write // anywhere. $data = array( 'D' => date('r'), 'h' => php_uname('n'), 'p' => getmypid(), 'e' => time(), 'I' => PhabricatorEnv::getEnvConfig('cluster.instance'), ); $sudo_user = PhabricatorEnv::getEnvConfig('phd.user'); if ($sudo_user !== null && strlen($sudo_user)) { $data['S'] = $sudo_user; } if (function_exists('posix_geteuid')) { $system_uid = posix_geteuid(); $system_info = posix_getpwuid($system_uid); $data['s'] = idx($system_info, 'name'); } $client = getenv('SSH_CLIENT'); if (strlen($client)) { $remote_address = head(explode(' ', $client)); $data['r'] = $remote_address; } $log = id(new PhutilDeferredLog($path, $format)) ->setFailQuietly(true) ->setData($data); self::$log = $log; } return self::$log; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/PhutilDaemon.php
src/infrastructure/daemon/PhutilDaemon.php
<?php /** * Scaffolding for implementing robust background processing scripts. * * * Autoscaling * =========== * * Autoscaling automatically launches copies of a daemon when it is busy * (scaling the pool up) and stops them when they're idle (scaling the pool * down). This is appropriate for daemons which perform highly parallelizable * work. * * To make a daemon support autoscaling, the implementation should look * something like this: * * while (!$this->shouldExit()) { * if (work_available()) { * $this->willBeginWork(); * do_work(); * $this->sleep(0); * } else { * $this->willBeginIdle(); * $this->sleep(1); * } * } * * In particular, call @{method:willBeginWork} before becoming busy, and * @{method:willBeginIdle} when no work is available. If the daemon is launched * into an autoscale pool, this will cause the pool to automatically scale up * when busy and down when idle. * * See @{class:PhutilHighIntensityIntervalDaemon} for an example of a simple * autoscaling daemon. * * Launching a daemon which does not make these callbacks into an autoscale * pool will have no effect. * * @task overseer Communicating With the Overseer * @task autoscale Autoscaling Daemon Pools */ abstract class PhutilDaemon extends Phobject { const MESSAGETYPE_STDOUT = 'stdout'; const MESSAGETYPE_HEARTBEAT = 'heartbeat'; const MESSAGETYPE_BUSY = 'busy'; const MESSAGETYPE_IDLE = 'idle'; const MESSAGETYPE_DOWN = 'down'; const MESSAGETYPE_HIBERNATE = 'hibernate'; const WORKSTATE_BUSY = 'busy'; const WORKSTATE_IDLE = 'idle'; private $argv; private $traceMode; private $traceMemory; private $verbose; private $notifyReceived; private $inGracefulShutdown; private $workState = null; private $idleSince = null; private $scaledownDuration; final public function setVerbose($verbose) { $this->verbose = $verbose; return $this; } final public function getVerbose() { return $this->verbose; } final public function setScaledownDuration($scaledown_duration) { $this->scaledownDuration = $scaledown_duration; return $this; } final public function getScaledownDuration() { return $this->scaledownDuration; } final public function __construct(array $argv) { $this->argv = $argv; $router = PhutilSignalRouter::getRouter(); $handler_key = 'daemon.term'; if (!$router->getHandler($handler_key)) { $handler = new PhutilCallbackSignalHandler( SIGTERM, __CLASS__.'::onTermSignal'); $router->installHandler($handler_key, $handler); } pcntl_signal(SIGINT, array($this, 'onGracefulSignal')); pcntl_signal(SIGUSR2, array($this, 'onNotifySignal')); // Without discard mode, this consumes unbounded amounts of memory. Keep // memory bounded. PhutilServiceProfiler::getInstance()->enableDiscardMode(); $this->beginStdoutCapture(); } final public function __destruct() { $this->endStdoutCapture(); } final public function stillWorking() { $this->emitOverseerMessage(self::MESSAGETYPE_HEARTBEAT, null); if ($this->traceMemory) { $daemon = get_class($this); fprintf( STDERR, "%s %s %s\n", '<RAMS>', $daemon, pht( 'Memory Usage: %s KB', new PhutilNumber(memory_get_usage() / 1024, 1))); } } final public function shouldExit() { return $this->inGracefulShutdown; } final protected function shouldHibernate($duration) { // Don't hibernate if we don't have very long to sleep. if ($duration < 30) { return false; } // Never hibernate if we're part of a pool and could scale down instead. // We only hibernate the last process to drop the pool size to zero. if ($this->getScaledownDuration()) { return false; } // Don't hibernate for too long. $duration = min($duration, phutil_units('3 minutes in seconds')); $this->emitOverseerMessage( self::MESSAGETYPE_HIBERNATE, array( 'duration' => $duration, )); $this->log( pht( 'Preparing to hibernate for %s second(s).', new PhutilNumber($duration))); return true; } final protected function sleep($duration) { $this->notifyReceived = false; $this->willSleep($duration); $this->stillWorking(); $scale_down = $this->getScaledownDuration(); $max_sleep = 60; if ($scale_down) { $max_sleep = min($max_sleep, $scale_down); } if ($scale_down) { if ($this->workState == self::WORKSTATE_IDLE) { $dur = $this->getIdleDuration(); $this->log(pht('Idle for %s seconds.', $dur)); } } while ($duration > 0 && !$this->notifyReceived && !$this->shouldExit()) { // If this is an autoscaling clone and we've been idle for too long, // we're going to scale the pool down by exiting and not restarting. The // DOWN message tells the overseer that we don't want to be restarted. if ($scale_down) { if ($this->workState == self::WORKSTATE_IDLE) { if ($this->idleSince && ($this->idleSince + $scale_down < time())) { $this->inGracefulShutdown = true; $this->emitOverseerMessage(self::MESSAGETYPE_DOWN, null); $this->log( pht( 'Daemon was idle for more than %s second(s), '. 'scaling pool down.', new PhutilNumber($scale_down))); break; } } } sleep(min($duration, $max_sleep)); $duration -= $max_sleep; $this->stillWorking(); } } protected function willSleep($duration) { return; } public static function onTermSignal($signo) { self::didCatchSignal($signo); } final protected function getArgv() { return $this->argv; } final public function execute() { $this->willRun(); $this->run(); } abstract protected function run(); final public function setTraceMemory() { $this->traceMemory = true; return $this; } final public function getTraceMemory() { return $this->traceMemory; } final public function setTraceMode() { $this->traceMode = true; PhutilServiceProfiler::installEchoListener(); PhutilConsole::getConsole()->getServer()->setEnableLog(true); $this->didSetTraceMode(); return $this; } final public function getTraceMode() { return $this->traceMode; } final public function onGracefulSignal($signo) { self::didCatchSignal($signo); $this->inGracefulShutdown = true; } final public function onNotifySignal($signo) { self::didCatchSignal($signo); $this->notifyReceived = true; $this->onNotify($signo); } protected function onNotify($signo) { // This is a hook for subclasses. } protected function willRun() { // This is a hook for subclasses. } protected function didSetTraceMode() { // This is a hook for subclasses. } final protected function log($message) { if ($this->verbose) { $daemon = get_class($this); fprintf(STDERR, "%s %s %s\n", '<VERB>', $daemon, $message); } } private static function didCatchSignal($signo) { $signame = phutil_get_signal_name($signo); fprintf( STDERR, "%s Caught signal %s (%s).\n", '<SGNL>', $signo, $signame); } /* -( Communicating With the Overseer )------------------------------------ */ private function beginStdoutCapture() { ob_start(array($this, 'didReceiveStdout'), 2); } private function endStdoutCapture() { ob_end_flush(); } public function didReceiveStdout($data) { if (!strlen($data)) { return ''; } return $this->encodeOverseerMessage(self::MESSAGETYPE_STDOUT, $data); } private function encodeOverseerMessage($type, $data) { $structure = array($type); if ($data !== null) { $structure[] = $data; } return json_encode($structure)."\n"; } private function emitOverseerMessage($type, $data) { $this->endStdoutCapture(); echo $this->encodeOverseerMessage($type, $data); $this->beginStdoutCapture(); } public static function errorListener($event, $value, array $metadata) { // If the caller has redirected the error log to a file, PHP won't output // messages to stderr, so the overseer can't capture them. Install a // listener which just echoes errors to stderr, so the overseer is always // aware of errors. $console = PhutilConsole::getConsole(); $message = idx($metadata, 'default_message'); if ($message) { $console->writeErr("%s\n", $message); } if (idx($metadata, 'trace')) { $trace = PhutilErrorHandler::formatStacktrace($metadata['trace']); $console->writeErr("%s\n", $trace); } } /* -( Autoscaling )-------------------------------------------------------- */ /** * Prepare to become busy. This may autoscale the pool up. * * This notifies the overseer that the daemon has become busy. If daemons * that are part of an autoscale pool are continuously busy for a prolonged * period of time, the overseer may scale up the pool. * * @return this * @task autoscale */ protected function willBeginWork() { if ($this->workState != self::WORKSTATE_BUSY) { $this->workState = self::WORKSTATE_BUSY; $this->idleSince = null; $this->emitOverseerMessage(self::MESSAGETYPE_BUSY, null); } return $this; } /** * Prepare to idle. This may autoscale the pool down. * * This notifies the overseer that the daemon is no longer busy. If daemons * that are part of an autoscale pool are idle for a prolonged period of * time, they may exit to scale the pool down. * * @return this * @task autoscale */ protected function willBeginIdle() { if ($this->workState != self::WORKSTATE_IDLE) { $this->workState = self::WORKSTATE_IDLE; $this->idleSince = time(); $this->emitOverseerMessage(self::MESSAGETYPE_IDLE, null); } return $this; } protected function getIdleDuration() { if (!$this->idleSince) { return null; } $now = time(); return ($now - $this->idleSince); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/PhutilDaemonHandle.php
src/infrastructure/daemon/PhutilDaemonHandle.php
<?php final class PhutilDaemonHandle extends Phobject { const EVENT_DID_LAUNCH = 'daemon.didLaunch'; const EVENT_DID_LOG = 'daemon.didLogMessage'; const EVENT_DID_HEARTBEAT = 'daemon.didHeartbeat'; const EVENT_WILL_GRACEFUL = 'daemon.willGraceful'; const EVENT_WILL_EXIT = 'daemon.willExit'; private $pool; private $properties; private $future; private $argv; private $restartAt; private $busyEpoch; private $daemonID; private $deadline; private $heartbeat; private $stdoutBuffer; private $shouldRestart = true; private $shouldShutdown; private $hibernating = false; private $shouldSendExitEvent = false; private function __construct() { // <empty> } public static function newFromConfig(array $config) { PhutilTypeSpec::checkMap( $config, array( 'class' => 'string', 'argv' => 'optional list<string>', 'load' => 'optional list<string>', 'log' => 'optional string|null', 'down' => 'optional int', )); $config = $config + array( 'argv' => array(), 'load' => array(), 'log' => null, 'down' => 15, ); $daemon = new self(); $daemon->properties = $config; $daemon->daemonID = $daemon->generateDaemonID(); return $daemon; } public function setDaemonPool(PhutilDaemonPool $daemon_pool) { $this->pool = $daemon_pool; return $this; } public function getDaemonPool() { return $this->pool; } public function getBusyEpoch() { return $this->busyEpoch; } public function getDaemonClass() { return $this->getProperty('class'); } private function getProperty($key) { return idx($this->properties, $key); } public function setCommandLineArguments(array $arguments) { $this->argv = $arguments; return $this; } public function getCommandLineArguments() { return $this->argv; } public function getDaemonArguments() { return $this->getProperty('argv'); } public function didLaunch() { $this->restartAt = time(); $this->shouldSendExitEvent = true; $this->dispatchEvent( self::EVENT_DID_LAUNCH, array( 'argv' => $this->getCommandLineArguments(), 'explicitArgv' => $this->getDaemonArguments(), )); return $this; } public function isRunning() { return (bool)$this->getFuture(); } public function isHibernating() { return !$this->isRunning() && !$this->isDone() && $this->hibernating; } public function wakeFromHibernation() { if (!$this->isHibernating()) { return $this; } $this->logMessage( 'WAKE', pht( 'Process is being awakened from hibernation.')); $this->restartAt = time(); $this->update(); return $this; } public function isDone() { return (!$this->shouldRestart && !$this->isRunning()); } public function update() { if (!$this->isRunning()) { if (!$this->shouldRestart) { return; } if (!$this->restartAt || (time() < $this->restartAt)) { return; } if ($this->shouldShutdown) { return; } $this->startDaemonProcess(); } $future = $this->getFuture(); $result = null; $caught = null; if ($future->canResolve()) { $this->future = null; try { $result = $future->resolve(); } catch (Exception $ex) { $caught = $ex; } catch (Throwable $ex) { $caught = $ex; } } list($stdout, $stderr) = $future->read(); $future->discardBuffers(); if (strlen($stdout)) { $this->didReadStdout($stdout); } $stderr = trim($stderr); if (strlen($stderr)) { foreach (phutil_split_lines($stderr, false) as $line) { $this->logMessage('STDE', $line); } } if ($result !== null || $caught !== null) { if ($caught) { $message = pht( 'Process failed with exception: %s', $caught->getMessage()); $this->logMessage('FAIL', $message); } else { list($err) = $result; if ($err) { $this->logMessage('FAIL', pht('Process exited with error %s.', $err)); } else { $this->logMessage('DONE', pht('Process exited normally.')); } } if ($this->shouldShutdown) { $this->restartAt = null; } else { $this->scheduleRestart(); } } $this->updateHeartbeatEvent(); $this->updateHangDetection(); } private function updateHeartbeatEvent() { if ($this->heartbeat > time()) { return; } $this->heartbeat = time() + $this->getHeartbeatEventFrequency(); $this->dispatchEvent(self::EVENT_DID_HEARTBEAT); } private function updateHangDetection() { if (!$this->isRunning()) { return; } if (time() > $this->deadline) { $this->logMessage('HANG', pht('Hang detected. Restarting process.')); $this->annihilateProcessGroup(); $this->scheduleRestart(); } } private function scheduleRestart() { // Wait a minimum of a few sceconds before restarting, but we may wait // longer if the daemon has initiated hibernation. $default_restart = time() + self::getWaitBeforeRestart(); if ($default_restart >= $this->restartAt) { $this->restartAt = $default_restart; } $this->logMessage( 'WAIT', pht( 'Waiting %s second(s) to restart process.', new PhutilNumber($this->restartAt - time()))); } /** * Generate a unique ID for this daemon. * * @return string A unique daemon ID. */ private function generateDaemonID() { return substr(getmypid().':'.Filesystem::readRandomCharacters(12), 0, 12); } public function getDaemonID() { return $this->daemonID; } private function getFuture() { return $this->future; } private function getPID() { $future = $this->getFuture(); if (!$future) { return null; } if (!$future->hasPID()) { return null; } return $future->getPID(); } private function getCaptureBufferSize() { return 65535; } private function getRequiredHeartbeatFrequency() { return 86400; } public static function getWaitBeforeRestart() { return 5; } public static function getHeartbeatEventFrequency() { return 120; } private function getKillDelay() { return 3; } private function getDaemonCWD() { $root = dirname(phutil_get_library_root('phabricator')); return $root.'/scripts/daemon/exec/'; } private function newExecFuture() { $class = $this->getDaemonClass(); $argv = $this->getCommandLineArguments(); $buffer_size = $this->getCaptureBufferSize(); // NOTE: PHP implements proc_open() by running 'sh -c'. On most systems this // is bash, but on Ubuntu it's dash. When you proc_open() using bash, you // get one new process (the command you ran). When you proc_open() using // dash, you get two new processes: the command you ran and a parent // "dash -c" (or "sh -c") process. This means that the child process's PID // is actually the 'dash' PID, not the command's PID. To avoid this, use // 'exec' to replace the shell process with the real process; without this, // the child will call posix_getppid(), be given the pid of the 'sh -c' // process, and send it SIGUSR1 to keepalive which will terminate it // immediately. We also won't be able to do process group management because // the shell process won't properly posix_setsid() so the pgid of the child // won't be meaningful. $config = $this->properties; unset($config['class']); $config = phutil_json_encode($config); return id(new ExecFuture('exec ./exec_daemon.php %s %Ls', $class, $argv)) ->setCWD($this->getDaemonCWD()) ->setStdoutSizeLimit($buffer_size) ->setStderrSizeLimit($buffer_size) ->write($config); } /** * Dispatch an event to event listeners. * * @param string Event type. * @param dict Event parameters. * @return void */ private function dispatchEvent($type, array $params = array()) { $data = array( 'id' => $this->getDaemonID(), 'daemonClass' => $this->getDaemonClass(), 'childPID' => $this->getPID(), ) + $params; $event = new PhutilEvent($type, $data); try { PhutilEventEngine::dispatchEvent($event); } catch (Exception $ex) { phlog($ex); } } private function annihilateProcessGroup() { $pid = $this->getPID(); if ($pid) { $pgid = posix_getpgid($pid); if ($pgid) { posix_kill(-$pgid, SIGTERM); sleep($this->getKillDelay()); posix_kill(-$pgid, SIGKILL); } } } private function startDaemonProcess() { $this->logMessage('INIT', pht('Starting process.')); $this->deadline = time() + $this->getRequiredHeartbeatFrequency(); $this->heartbeat = time() + self::getHeartbeatEventFrequency(); $this->stdoutBuffer = ''; $this->hibernating = false; $future = $this->newExecFuture(); $this->future = $future; $pool = $this->getDaemonPool(); $overseer = $pool->getOverseer(); $overseer->addFutureToPool($future); } private function didReadStdout($data) { $this->stdoutBuffer .= $data; while (true) { $pos = strpos($this->stdoutBuffer, "\n"); if ($pos === false) { break; } $message = substr($this->stdoutBuffer, 0, $pos); $this->stdoutBuffer = substr($this->stdoutBuffer, $pos + 1); try { $structure = phutil_json_decode($message); } catch (PhutilJSONParserException $ex) { $structure = array(); } switch (idx($structure, 0)) { case PhutilDaemon::MESSAGETYPE_STDOUT: $this->logMessage('STDO', idx($structure, 1)); break; case PhutilDaemon::MESSAGETYPE_HEARTBEAT: $this->deadline = time() + $this->getRequiredHeartbeatFrequency(); break; case PhutilDaemon::MESSAGETYPE_BUSY: if (!$this->busyEpoch) { $this->busyEpoch = time(); } break; case PhutilDaemon::MESSAGETYPE_IDLE: $this->busyEpoch = null; break; case PhutilDaemon::MESSAGETYPE_DOWN: // The daemon is exiting because it doesn't have enough work and it // is trying to scale the pool down. We should not restart it. $this->shouldRestart = false; $this->shouldShutdown = true; break; case PhutilDaemon::MESSAGETYPE_HIBERNATE: $config = idx($structure, 1); $duration = (int)idx($config, 'duration', 0); $this->restartAt = time() + $duration; $this->hibernating = true; $this->busyEpoch = null; $this->logMessage( 'ZZZZ', pht( 'Process is preparing to hibernate for %s second(s).', new PhutilNumber($duration))); break; default: // If we can't parse this or it isn't a message we understand, just // emit the raw message. $this->logMessage('STDO', pht('<Malformed> %s', $message)); break; } } } public function didReceiveNotifySignal($signo) { $pid = $this->getPID(); if ($pid) { posix_kill($pid, $signo); } } public function didReceiveReloadSignal($signo) { $signame = phutil_get_signal_name($signo); if ($signame) { $sigmsg = pht( 'Reloading in response to signal %d (%s).', $signo, $signame); } else { $sigmsg = pht( 'Reloading in response to signal %d.', $signo); } $this->logMessage('RELO', $sigmsg, $signo); // This signal means "stop the current process gracefully, then launch // a new identical process once it exits". This can be used to update // daemons after code changes (the new processes will run the new code) // without aborting any running tasks. // We SIGINT the daemon but don't set the shutdown flag, so it will // naturally be restarted after it exits, as though it had exited after an // unhandled exception. $pid = $this->getPID(); if ($pid) { posix_kill($pid, SIGINT); } } public function didReceiveGracefulSignal($signo) { $this->shouldShutdown = true; $this->shouldRestart = false; $signame = phutil_get_signal_name($signo); if ($signame) { $sigmsg = pht( 'Graceful shutdown in response to signal %d (%s).', $signo, $signame); } else { $sigmsg = pht( 'Graceful shutdown in response to signal %d.', $signo); } $this->logMessage('DONE', $sigmsg, $signo); $pid = $this->getPID(); if ($pid) { posix_kill($pid, SIGINT); } } public function didReceiveTerminateSignal($signo) { $this->shouldShutdown = true; $this->shouldRestart = false; $signame = phutil_get_signal_name($signo); if ($signame) { $sigmsg = pht( 'Shutting down in response to signal %s (%s).', $signo, $signame); } else { $sigmsg = pht('Shutting down in response to signal %s.', $signo); } $this->logMessage('EXIT', $sigmsg, $signo); $this->annihilateProcessGroup(); } private function logMessage($type, $message, $context = null) { $this->getDaemonPool()->logMessage($type, $message, $context); $this->dispatchEvent( self::EVENT_DID_LOG, array( 'type' => $type, 'message' => $message, 'context' => $context, )); } public function didExit() { if ($this->shouldSendExitEvent) { $this->dispatchEvent(self::EVENT_WILL_EXIT); $this->shouldSendExitEvent = false; } return $this; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/PhutilDaemonOverseer.php
src/infrastructure/daemon/PhutilDaemonOverseer.php
<?php /** * Oversees a daemon and restarts it if it fails. * * @task signals Signal Handling */ final class PhutilDaemonOverseer extends Phobject { private $argv; private static $instance; private $config; private $pools = array(); private $traceMode; private $traceMemory; private $daemonize; private $log; private $libraries = array(); private $modules = array(); private $verbose; private $startEpoch; private $autoscale = array(); private $autoscaleConfig = array(); const SIGNAL_NOTIFY = 'signal/notify'; const SIGNAL_RELOAD = 'signal/reload'; const SIGNAL_GRACEFUL = 'signal/graceful'; const SIGNAL_TERMINATE = 'signal/terminate'; private $err = 0; private $inAbruptShutdown; private $inGracefulShutdown; private $futurePool; public function __construct(array $argv) { PhutilServiceProfiler::getInstance()->enableDiscardMode(); $args = new PhutilArgumentParser($argv); $args->setTagline(pht('daemon overseer')); $args->setSynopsis(<<<EOHELP **launch_daemon.php** [__options__] __daemon__ Launch and oversee an instance of __daemon__. EOHELP ); $args->parseStandardArguments(); $args->parse( array( array( 'name' => 'trace-memory', 'help' => pht('Enable debug memory tracing.'), ), array( 'name' => 'verbose', 'help' => pht('Enable verbose activity logging.'), ), array( 'name' => 'label', 'short' => 'l', 'param' => 'label', 'help' => pht( 'Optional process label. Makes "%s" nicer, no behavioral effects.', 'ps'), ), )); $argv = array(); if ($args->getArg('trace')) { $this->traceMode = true; $argv[] = '--trace'; } if ($args->getArg('trace-memory')) { $this->traceMode = true; $this->traceMemory = true; $argv[] = '--trace-memory'; } $verbose = $args->getArg('verbose'); if ($verbose) { $this->verbose = true; $argv[] = '--verbose'; } $label = $args->getArg('label'); if ($label) { $argv[] = '-l'; $argv[] = $label; } $this->argv = $argv; if (function_exists('posix_isatty') && posix_isatty(STDIN)) { fprintf(STDERR, pht('Reading daemon configuration from stdin...')."\n"); } $config = @file_get_contents('php://stdin'); $config = id(new PhutilJSONParser())->parse($config); $this->libraries = idx($config, 'load'); $this->log = idx($config, 'log'); $this->daemonize = idx($config, 'daemonize'); $this->config = $config; if (self::$instance) { throw new Exception( pht('You may not instantiate more than one Overseer per process.')); } self::$instance = $this; $this->startEpoch = time(); if (!idx($config, 'daemons')) { throw new PhutilArgumentUsageException( pht('You must specify at least one daemon to start!')); } if ($this->log) { // NOTE: Now that we're committed to daemonizing, redirect the error // log if we have a `--log` parameter. Do this at the last moment // so as many setup issues as possible are surfaced. ini_set('error_log', $this->log); } if ($this->daemonize) { // We need to get rid of these or the daemon will hang when we TERM it // waiting for something to read the buffers. TODO: Learn how unix works. fclose(STDOUT); fclose(STDERR); ob_start(); $pid = pcntl_fork(); if ($pid === -1) { throw new Exception(pht('Unable to fork!')); } else if ($pid) { exit(0); } $sid = posix_setsid(); if ($sid <= 0) { throw new Exception(pht('Failed to create new process session!')); } } $this->logMessage( 'OVER', pht( 'Started new daemon overseer (with PID "%s").', getmypid())); $this->modules = PhutilDaemonOverseerModule::getAllModules(); $this->installSignalHandlers(); } public function addLibrary($library) { $this->libraries[] = $library; return $this; } public function run() { $this->createDaemonPools(); $future_pool = $this->getFuturePool(); while (true) { if ($this->shouldReloadDaemons()) { $this->didReceiveSignal(SIGHUP); } $running_pools = false; foreach ($this->getDaemonPools() as $pool) { $pool->updatePool(); if (!$this->shouldShutdown()) { if ($pool->isHibernating()) { if ($this->shouldWakePool($pool)) { $pool->wakeFromHibernation(); } } } if ($pool->getDaemons()) { $running_pools = true; } } $this->updateMemory(); if ($future_pool->hasFutures()) { $future_pool->resolve(); } else { if (!$this->shouldShutdown()) { sleep(1); } } if (!$future_pool->hasFutures() && !$running_pools) { if ($this->shouldShutdown()) { break; } } } exit($this->err); } public function addFutureToPool(Future $future) { $this->getFuturePool()->addFuture($future); return $this; } private function getFuturePool() { if (!$this->futurePool) { $pool = new FuturePool(); // TODO: This only wakes if any daemons actually exit, or 1 second // passes. It would be a bit cleaner to wait on any I/O, but Futures // currently can't do that. $pool->getIteratorTemplate() ->setUpdateInterval(1); $this->futurePool = $pool; } return $this->futurePool; } private function createDaemonPools() { $configs = $this->config['daemons']; $forced_options = array( 'load' => $this->libraries, 'log' => $this->log, ); foreach ($configs as $config) { $config = $forced_options + $config; $pool = PhutilDaemonPool::newFromConfig($config) ->setOverseer($this) ->setCommandLineArguments($this->argv); $this->pools[] = $pool; } } private function getDaemonPools() { return $this->pools; } private function updateMemory() { if (!$this->traceMemory) { return; } $this->logMessage( 'RAMS', pht( 'Overseer Memory Usage: %s KB', new PhutilNumber(memory_get_usage() / 1024, 1))); } public function logMessage($type, $message, $context = null) { $always_log = false; switch ($type) { case 'OVER': case 'SGNL': case 'PIDF': $always_log = true; break; } if ($always_log || $this->traceMode || $this->verbose) { error_log(date('Y-m-d g:i:s A').' ['.$type.'] '.$message); } } /* -( Signal Handling )---------------------------------------------------- */ /** * @task signals */ private function installSignalHandlers() { $signals = array( SIGUSR2, SIGHUP, SIGINT, SIGTERM, ); foreach ($signals as $signal) { pcntl_signal($signal, array($this, 'didReceiveSignal')); } } /** * @task signals */ public function didReceiveSignal($signo) { $this->logMessage( 'SGNL', pht( 'Overseer ("%d") received signal %d ("%s").', getmypid(), $signo, phutil_get_signal_name($signo))); switch ($signo) { case SIGUSR2: $signal_type = self::SIGNAL_NOTIFY; break; case SIGHUP: $signal_type = self::SIGNAL_RELOAD; break; case SIGINT: // If we receive SIGINT more than once, interpret it like SIGTERM. if ($this->inGracefulShutdown) { return $this->didReceiveSignal(SIGTERM); } $this->inGracefulShutdown = true; $signal_type = self::SIGNAL_GRACEFUL; break; case SIGTERM: // If we receive SIGTERM more than once, terminate abruptly. $this->err = 128 + $signo; if ($this->inAbruptShutdown) { exit($this->err); } $this->inAbruptShutdown = true; $signal_type = self::SIGNAL_TERMINATE; break; default: throw new Exception( pht( 'Signal handler called with unknown signal type ("%d")!', $signo)); } foreach ($this->getDaemonPools() as $pool) { $pool->didReceiveSignal($signal_type, $signo); } } /* -( Daemon Modules )----------------------------------------------------- */ private function getModules() { return $this->modules; } private function shouldReloadDaemons() { $modules = $this->getModules(); $should_reload = false; foreach ($modules as $module) { try { // NOTE: Even if one module tells us to reload, we call the method on // each module anyway to make calls a little more predictable. if ($module->shouldReloadDaemons()) { $this->logMessage( 'RELO', pht( 'Reloading daemons (triggered by overseer module "%s").', get_class($module))); $should_reload = true; } } catch (Exception $ex) { phlog($ex); } } return $should_reload; } private function shouldWakePool(PhutilDaemonPool $pool) { $modules = $this->getModules(); $should_wake = false; foreach ($modules as $module) { try { if ($module->shouldWakePool($pool)) { $this->logMessage( 'WAKE', pht( 'Waking pool "%s" (triggered by overseer module "%s").', $pool->getPoolLabel(), get_class($module))); $should_wake = true; } } catch (Exception $ex) { phlog($ex); } } return $should_wake; } private function shouldShutdown() { return $this->inGracefulShutdown || $this->inAbruptShutdown; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/PhutilDaemonPool.php
src/infrastructure/daemon/PhutilDaemonPool.php
<?php final class PhutilDaemonPool extends Phobject { private $properties = array(); private $commandLineArguments; private $overseer; private $daemons = array(); private $argv; private $lastAutoscaleUpdate; private $inShutdown; private function __construct() { // <empty> } public static function newFromConfig(array $config) { PhutilTypeSpec::checkMap( $config, array( 'class' => 'string', 'label' => 'string', 'argv' => 'optional list<string>', 'load' => 'optional list<string>', 'log' => 'optional string|null', 'pool' => 'optional int', 'up' => 'optional int', 'down' => 'optional int', 'reserve' => 'optional int|float', )); $config = $config + array( 'argv' => array(), 'load' => array(), 'log' => null, 'pool' => 1, 'up' => 2, 'down' => 15, 'reserve' => 0, ); $pool = new self(); $pool->properties = $config; return $pool; } public function setOverseer(PhutilDaemonOverseer $overseer) { $this->overseer = $overseer; return $this; } public function getOverseer() { return $this->overseer; } public function setCommandLineArguments(array $arguments) { $this->commandLineArguments = $arguments; return $this; } public function getCommandLineArguments() { return $this->commandLineArguments; } private function shouldShutdown() { return $this->inShutdown; } private function newDaemon() { $config = $this->properties; if (count($this->daemons)) { $down_duration = $this->getPoolScaledownDuration(); } else { // TODO: For now, never scale pools down to 0. $down_duration = 0; } $forced_config = array( 'down' => $down_duration, ); $config = $forced_config + $config; $config = array_select_keys( $config, array( 'class', 'log', 'load', 'argv', 'down', )); $daemon = PhutilDaemonHandle::newFromConfig($config) ->setDaemonPool($this) ->setCommandLineArguments($this->getCommandLineArguments()); $daemon_id = $daemon->getDaemonID(); $this->daemons[$daemon_id] = $daemon; $daemon->didLaunch(); return $daemon; } public function getDaemons() { return $this->daemons; } public function didReceiveSignal($signal, $signo) { switch ($signal) { case PhutilDaemonOverseer::SIGNAL_GRACEFUL: case PhutilDaemonOverseer::SIGNAL_TERMINATE: $this->inShutdown = true; break; } foreach ($this->getDaemons() as $daemon) { switch ($signal) { case PhutilDaemonOverseer::SIGNAL_NOTIFY: $daemon->didReceiveNotifySignal($signo); break; case PhutilDaemonOverseer::SIGNAL_RELOAD: $daemon->didReceiveReloadSignal($signo); break; case PhutilDaemonOverseer::SIGNAL_GRACEFUL: $daemon->didReceiveGracefulSignal($signo); break; case PhutilDaemonOverseer::SIGNAL_TERMINATE: $daemon->didReceiveTerminateSignal($signo); break; default: throw new Exception( pht( 'Unknown signal "%s" ("%d").', $signal, $signo)); } } } public function getPoolLabel() { return $this->getPoolProperty('label'); } public function getPoolMaximumSize() { return $this->getPoolProperty('pool'); } public function getPoolScaleupDuration() { return $this->getPoolProperty('up'); } public function getPoolScaledownDuration() { return $this->getPoolProperty('down'); } public function getPoolMemoryReserve() { return $this->getPoolProperty('reserve'); } public function getPoolDaemonClass() { return $this->getPoolProperty('class'); } private function getPoolProperty($key) { return idx($this->properties, $key); } public function updatePool() { $daemons = $this->getDaemons(); foreach ($daemons as $key => $daemon) { $daemon->update(); if ($daemon->isDone()) { $daemon->didExit(); unset($this->daemons[$key]); if ($this->shouldShutdown()) { $this->logMessage( 'DOWN', pht( 'Pool "%s" is exiting, with %s daemon(s) remaining.', $this->getPoolLabel(), new PhutilNumber(count($this->daemons)))); } else { $this->logMessage( 'POOL', pht( 'Autoscale pool "%s" scaled down to %s daemon(s).', $this->getPoolLabel(), new PhutilNumber(count($this->daemons)))); } } } $this->updateAutoscale(); } public function isHibernating() { foreach ($this->getDaemons() as $daemon) { if (!$daemon->isHibernating()) { return false; } } return true; } public function wakeFromHibernation() { if (!$this->isHibernating()) { return $this; } $this->logMessage( 'WAKE', pht( 'Autoscale pool "%s" is being awakened from hibernation.', $this->getPoolLabel())); $did_wake_daemons = false; foreach ($this->getDaemons() as $daemon) { if ($daemon->isHibernating()) { $daemon->wakeFromHibernation(); $did_wake_daemons = true; } } if (!$did_wake_daemons) { // TODO: Pools currently can't scale down to 0 daemons, but we should // scale up immediately here once they can. } $this->updatePool(); return $this; } private function updateAutoscale() { if ($this->shouldShutdown()) { return; } // Don't try to autoscale more than once per second. This mostly stops the // logs from getting flooded in verbose mode. $now = time(); if ($this->lastAutoscaleUpdate >= $now) { return; } $this->lastAutoscaleUpdate = $now; $daemons = $this->getDaemons(); // If this pool is already at the maximum size, we can't launch any new // daemons. $max_size = $this->getPoolMaximumSize(); if (count($daemons) >= $max_size) { $this->logMessage( 'POOL', pht( 'Autoscale pool "%s" already at maximum size (%s of %s).', $this->getPoolLabel(), new PhutilNumber(count($daemons)), new PhutilNumber($max_size))); return; } $scaleup_duration = $this->getPoolScaleupDuration(); foreach ($daemons as $daemon) { $busy_epoch = $daemon->getBusyEpoch(); // If any daemons haven't started work yet, don't scale the pool up. if (!$busy_epoch) { $this->logMessage( 'POOL', pht( 'Autoscale pool "%s" has an idle daemon, declining to scale.', $this->getPoolLabel())); return; } // If any daemons started work very recently, wait a little while // to scale the pool up. $busy_for = ($now - $busy_epoch); if ($busy_for < $scaleup_duration) { $this->logMessage( 'POOL', pht( 'Autoscale pool "%s" has not been busy long enough to scale up '. '(busy for %s of %s seconds).', $this->getPoolLabel(), new PhutilNumber($busy_for), new PhutilNumber($scaleup_duration))); return; } } // If we have a configured memory reserve for this pool, it tells us that // we should not scale up unless there's at least that much memory left // on the system (for example, a reserve of 0.25 means that 25% of system // memory must be free to autoscale). // Note that the first daemon is exempt: we'll always launch at least one // daemon, regardless of any memory reservation. if (count($daemons)) { $reserve = $this->getPoolMemoryReserve(); if ($reserve) { // On some systems this may be slightly more expensive than other // checks, so we only do it once we're prepared to scale up. $memory = PhutilSystem::getSystemMemoryInformation(); $free_ratio = ($memory['free'] / $memory['total']); // If we don't have enough free memory, don't scale. if ($free_ratio <= $reserve) { $this->logMessage( 'POOL', pht( 'Autoscale pool "%s" does not have enough free memory to '. 'scale up (%s free of %s reserved).', $this->getPoolLabel(), new PhutilNumber($free_ratio, 3), new PhutilNumber($reserve, 3))); return; } } } $this->logMessage( 'AUTO', pht( 'Scaling pool "%s" up to %s daemon(s).', $this->getPoolLabel(), new PhutilNumber(count($daemons) + 1))); $this->newDaemon(); } public function logMessage($type, $message, $context = null) { return $this->getOverseer()->logMessage($type, $message, $context); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/PhabricatorDaemon.php
src/infrastructure/daemon/PhabricatorDaemon.php
<?php abstract class PhabricatorDaemon extends PhutilDaemon { protected function willRun() { parent::willRun(); $phabricator = phutil_get_library_root('phabricator'); $root = dirname($phabricator); require_once $root.'/scripts/__init_script__.php'; } protected function willSleep($duration) { LiskDAO::closeInactiveConnections(60); return; } public function getViewer() { return PhabricatorUser::getOmnipotentUser(); } /** * Format a command so it executes as the daemon user, if a daemon user is * defined. This wraps the provided command in `sudo -u ...`, roughly. * * @param PhutilCommandString Command to execute. * @return PhutilCommandString `sudo` version of the command. */ public static function sudoCommandAsDaemonUser($command) { $user = PhabricatorEnv::getEnvConfig('phd.user'); if (!$user) { // No daemon user is set, so just run this as ourselves. return $command; } // We may reach this method while already running as the daemon user: for // example, active and passive synchronization of clustered repositories // run the same commands through the same code, but as different users. // By default, `sudo` won't let you sudo to yourself, so we can get into // trouble if we're already running as the daemon user unless the host has // been configured to let the daemon user run commands as itself. // Since this is silly and more complicated than doing this check, don't // use `sudo` if we're already running as the correct user. if (function_exists('posix_getuid')) { $uid = posix_getuid(); $info = posix_getpwuid($uid); if ($info && $info['name'] == $user) { return $command; } } // Get the absolute path so we're safe against the caller wiping out // PATH. $sudo = Filesystem::resolveBinary('sudo'); if (!$sudo) { throw new Exception(pht("Unable to find 'sudo'!")); } // Flags here are: // // -E: Preserve the environment. // -n: Non-interactive. Exit with an error instead of prompting. // -u: Which user to sudo to. return csprintf('%s -E -n -u %s -- %C', $sudo, $user, $command); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/PhutilDaemonOverseerModule.php
src/infrastructure/daemon/PhutilDaemonOverseerModule.php
<?php /** * Overseer modules allow daemons to be externally influenced. * * See @{class:PhabricatorDaemonOverseerModule} for a concrete example. */ abstract class PhutilDaemonOverseerModule extends Phobject { private $throttles = array(); /** * This method is used to indicate to the overseer that daemons should reload. * * @return bool True if the daemons should reload, otherwise false. */ public function shouldReloadDaemons() { return false; } /** * Should a hibernating daemon pool be awoken immediately? * * @return bool True to awaken the pool immediately. */ public function shouldWakePool(PhutilDaemonPool $pool) { return false; } public static function getAllModules() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->execute(); } /** * Throttle checks from executing too often. * * If you throttle a check like this, it will only execute once every 2.5 * seconds: * * if ($this->shouldThrottle('some.check', 2.5)) { * return; * } * * @param string Throttle key. * @param float Duration in seconds. * @return bool True to throttle the check. */ protected function shouldThrottle($name, $duration) { $throttle = idx($this->throttles, $name, 0); $now = microtime(true); // If not enough time has elapsed, throttle the check. $elapsed = ($now - $throttle); if ($elapsed < $duration) { return true; } // Otherwise, mark the current time as the last time we ran the check, // then let it continue. $this->throttles[$name] = $now; return false; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/PhabricatorTriggerDaemon.php
src/infrastructure/daemon/workers/PhabricatorTriggerDaemon.php
<?php /** * Schedule and execute event triggers, which run code at specific times. * * Also performs garbage collection of old logs, caches, etc. * * @task garbage Garbage Collection */ final class PhabricatorTriggerDaemon extends PhabricatorDaemon { const COUNTER_VERSION = 'trigger.version'; const COUNTER_CURSOR = 'trigger.cursor'; private $garbageCollectors; private $nextCollection; private $anyNuanceData; private $nuanceSources; private $nuanceCursors; private $calendarEngine; protected function run() { // The trigger daemon is a low-level infrastructure daemon which schedules // and executes chronological events. Examples include a subscription which // generates a bill on the 12th of every month, or a reminder email 15 // minutes before a meeting. // Only one trigger daemon can run at a time, and very little work should // happen in the daemon process. In general, triggered events should // just schedule a task into the normal daemon worker queue and then // return. This allows the real work to take longer to execute without // disrupting other triggers. // The trigger mechanism guarantees that events will execute exactly once, // but does not guarantee that they will execute at precisely the specified // time. Under normal circumstances, they should execute within a minute or // so of the desired time, so this mechanism can be used for things like // meeting reminders. // If the trigger queue backs up (for example, because it is overwhelmed by // trigger updates, doesn't run for a while, or a trigger action is written // inefficiently) or the daemon queue backs up (usually for similar // reasons), events may execute an arbitrarily long time after they were // scheduled to execute. In some cases (like billing a subscription) this // may be desirable; in other cases (like sending a meeting reminder) the // action may want to check the current time and see if the event is still // relevant. // The trigger daemon works in two phases: // // 1. A scheduling phase processes recently updated triggers and // schedules them for future execution. For example, this phase would // see that a meeting trigger had been changed recently, determine // when the reminder for it should execute, and then schedule the // action to execute at that future date. // 2. An execution phase runs the actions for any scheduled events which // are due to execute. // // The major goal of this design is to deliver on the guarantee that events // will execute exactly once. It prevents race conditions in scheduling // and execution by ensuring there is only one writer for either of these // phases. Without this separation of responsibilities, web processes // trying to reschedule events after an update could race with other web // processes or the daemon. // We want to start the first GC cycle right away, not wait 4 hours. $this->nextCollection = PhabricatorTime::getNow(); do { PhabricatorCaches::destroyRequestCache(); $lock = PhabricatorGlobalLock::newLock('trigger'); try { $lock->lock(5); } catch (PhutilLockException $ex) { throw new PhutilProxyException( pht( 'Another process is holding the trigger lock. Usually, this '. 'means another copy of the trigger daemon is running elsewhere. '. 'Multiple processes are not permitted to update triggers '. 'simultaneously.'), $ex); } // Run the scheduling phase. This finds updated triggers which we have // not scheduled yet and schedules them. $last_version = $this->loadCurrentCursor(); $head_version = $this->loadCurrentVersion(); // The cursor points at the next record to process, so we can only skip // this step if we're ahead of the version number. if ($last_version <= $head_version) { $this->scheduleTriggers($last_version); } // Run the execution phase. This finds events which are due to execute // and runs them. $this->executeTriggers(); $lock->unlock(); $sleep_duration = $this->getSleepDuration(); $sleep_duration = $this->runNuanceImportCursors($sleep_duration); $sleep_duration = $this->runGarbageCollection($sleep_duration); $sleep_duration = $this->runCalendarNotifier($sleep_duration); if ($this->shouldHibernate($sleep_duration)) { break; } $this->sleep($sleep_duration); } while (!$this->shouldExit()); } /** * Process all of the triggers which have been updated since the last time * the daemon ran, scheduling them into the event table. * * @param int Cursor for the next version update to process. * @return void */ private function scheduleTriggers($cursor) { $limit = 100; $query = id(new PhabricatorWorkerTriggerQuery()) ->setViewer($this->getViewer()) ->withVersionBetween($cursor, null) ->setOrder(PhabricatorWorkerTriggerQuery::ORDER_VERSION) ->needEvents(true) ->setLimit($limit); while (true) { $triggers = $query->execute(); foreach ($triggers as $trigger) { $event = $trigger->getEvent(); if ($event) { $last_epoch = $event->getLastEventEpoch(); } else { $last_epoch = null; } $next_epoch = $trigger->getNextEventEpoch( $last_epoch, $is_reschedule = false); $new_event = PhabricatorWorkerTriggerEvent::initializeNewEvent($trigger) ->setLastEventEpoch($last_epoch) ->setNextEventEpoch($next_epoch); $new_event->openTransaction(); if ($event) { $event->delete(); } // Always save the new event. Note that we save it even if the next // epoch is `null`, indicating that it will never fire, because we // would lose the last epoch information if we delete it. // // In particular, some events may want to execute exactly once. // Retaining the last epoch allows them to do this, even if the // trigger is updated. $new_event->save(); // Move the cursor forward to make sure we don't reprocess this // trigger until it is updated again. $this->updateCursor($trigger->getTriggerVersion() + 1); $new_event->saveTransaction(); } // If we saw fewer than a full page of updated triggers, we're caught // up, so we can move on to the execution phase. if (count($triggers) < $limit) { break; } // Otherwise, skip past the stuff we just processed and grab another // page of updated triggers. $min = last($triggers)->getTriggerVersion() + 1; $query->withVersionBetween($min, null); $this->stillWorking(); } } /** * Run scheduled event triggers which are due for execution. * * @return void */ private function executeTriggers() { // We run only a limited number of triggers before ending the execution // phase. If we ran until exhaustion, we could end up executing very // out-of-date triggers if there was a long backlog: trigger changes // during this phase are not reflected in the event table until we run // another scheduling phase. // If we exit this phase with triggers still ready to execute we'll // jump back into the scheduling phase immediately, so this just makes // sure we don't spend an unreasonably long amount of time without // processing trigger updates and doing rescheduling. $limit = 100; $now = PhabricatorTime::getNow(); $triggers = id(new PhabricatorWorkerTriggerQuery()) ->setViewer($this->getViewer()) ->setOrder(PhabricatorWorkerTriggerQuery::ORDER_EXECUTION) ->withNextEventBetween(null, $now) ->needEvents(true) ->setLimit($limit) ->execute(); foreach ($triggers as $trigger) { $event = $trigger->getEvent(); // Execute the trigger action. $trigger->executeTrigger( $event->getLastEventEpoch(), $event->getNextEventEpoch()); // Now that we've executed the trigger, the current trigger epoch is // going to become the last epoch. $last_epoch = $event->getNextEventEpoch(); // If this is a recurring trigger, give it an opportunity to reschedule. $reschedule_epoch = $trigger->getNextEventEpoch( $last_epoch, $is_reschedule = true); // Don't reschedule events unless the next occurrence is in the future. if (($reschedule_epoch !== null) && ($last_epoch !== null) && ($reschedule_epoch <= $last_epoch)) { throw new Exception( pht( 'Trigger is attempting to perform a routine reschedule where '. 'the next event (at %s) does not occur after the previous event '. '(at %s). Routine reschedules must strictly move event triggers '. 'forward through time to avoid executing a trigger an infinite '. 'number of times instantaneously.', $reschedule_epoch, $last_epoch)); } $new_event = PhabricatorWorkerTriggerEvent::initializeNewEvent($trigger) ->setLastEventEpoch($last_epoch) ->setNextEventEpoch($reschedule_epoch); $event->openTransaction(); // Remove the event we just processed. $event->delete(); // See note in the scheduling phase about this; we save the new event // even if the next epoch is `null`. $new_event->save(); $event->saveTransaction(); } } /** * Get the number of seconds to sleep for before starting the next scheduling * phase. * * If no events are scheduled soon, we'll sleep briefly. Otherwise, * we'll sleep until the next scheduled event. * * @return int Number of seconds to sleep for. */ private function getSleepDuration() { $sleep = phutil_units('3 minutes in seconds'); $next_triggers = id(new PhabricatorWorkerTriggerQuery()) ->setViewer($this->getViewer()) ->setOrder(PhabricatorWorkerTriggerQuery::ORDER_EXECUTION) ->withNextEventBetween(0, null) ->setLimit(1) ->needEvents(true) ->execute(); if ($next_triggers) { $next_trigger = head($next_triggers); $next_epoch = $next_trigger->getEvent()->getNextEventEpoch(); $until = max(0, $next_epoch - PhabricatorTime::getNow()); $sleep = min($sleep, $until); } return $sleep; } /* -( Counters )----------------------------------------------------------- */ private function loadCurrentCursor() { return $this->loadCurrentCounter(self::COUNTER_CURSOR); } private function loadCurrentVersion() { return $this->loadCurrentCounter(self::COUNTER_VERSION); } private function updateCursor($value) { LiskDAO::overwriteCounterValue( id(new PhabricatorWorkerTrigger())->establishConnection('w'), self::COUNTER_CURSOR, $value); } private function loadCurrentCounter($counter_name) { return (int)LiskDAO::loadCurrentCounterValue( id(new PhabricatorWorkerTrigger())->establishConnection('w'), $counter_name); } /* -( Garbage Collection )------------------------------------------------- */ /** * Run the garbage collector for up to a specified number of seconds. * * @param int Number of seconds the GC may run for. * @return int Number of seconds remaining in the time budget. * @task garbage */ private function runGarbageCollection($duration) { $run_until = (PhabricatorTime::getNow() + $duration); // NOTE: We always run at least one GC cycle to make sure the GC can make // progress even if the trigger queue is busy. do { $more_garbage = $this->updateGarbageCollection(); if (!$more_garbage) { // If we don't have any more collection work to perform, we're all // done. break; } } while (PhabricatorTime::getNow() <= $run_until); $remaining = max(0, $run_until - PhabricatorTime::getNow()); return $remaining; } /** * Update garbage collection, possibly collecting a small amount of garbage. * * @return bool True if there is more garbage to collect. * @task garbage */ private function updateGarbageCollection() { // If we're ready to start the next collection cycle, load all the // collectors. $next = $this->nextCollection; if ($next && (PhabricatorTime::getNow() >= $next)) { $this->nextCollection = null; $all_collectors = PhabricatorGarbageCollector::getAllCollectors(); $this->garbageCollectors = $all_collectors; } // If we're in a collection cycle, continue collection. if ($this->garbageCollectors) { foreach ($this->garbageCollectors as $key => $collector) { $more_garbage = $collector->runCollector(); if (!$more_garbage) { unset($this->garbageCollectors[$key]); } // We only run one collection per call, to prevent triggers from being // thrown too far off schedule if there's a lot of garbage to collect. break; } if ($this->garbageCollectors) { // If we have more work to do, return true. return true; } // Otherwise, reschedule another cycle in 4 hours. $now = PhabricatorTime::getNow(); $wait = phutil_units('4 hours in seconds'); $this->nextCollection = $now + $wait; } return false; } /* -( Nuance Importers )--------------------------------------------------- */ private function runNuanceImportCursors($duration) { $run_until = (PhabricatorTime::getNow() + $duration); do { $more_data = $this->updateNuanceImportCursors(); if (!$more_data) { break; } } while (PhabricatorTime::getNow() <= $run_until); $remaining = max(0, $run_until - PhabricatorTime::getNow()); return $remaining; } private function updateNuanceImportCursors() { $nuance_app = 'PhabricatorNuanceApplication'; if (!PhabricatorApplication::isClassInstalled($nuance_app)) { return false; } // If we haven't loaded sources yet, load them first. if (!$this->nuanceSources && !$this->nuanceCursors) { $this->anyNuanceData = false; $sources = id(new NuanceSourceQuery()) ->setViewer($this->getViewer()) ->withIsDisabled(false) ->withHasImportCursors(true) ->execute(); if (!$sources) { return false; } $this->nuanceSources = array_reverse($sources); } // If we don't have any cursors, move to the next source and generate its // cursors. if (!$this->nuanceCursors) { $source = array_pop($this->nuanceSources); $definition = $source->getDefinition() ->setViewer($this->getViewer()) ->setSource($source); $cursors = $definition->getImportCursors(); $this->nuanceCursors = array_reverse($cursors); } // Update the next cursor. $cursor = array_pop($this->nuanceCursors); if ($cursor) { $more_data = $cursor->importFromSource(); if ($more_data) { $this->anyNuanceData = true; } } if (!$this->nuanceSources && !$this->nuanceCursors) { return $this->anyNuanceData; } return true; } /* -( Calendar Notifier )-------------------------------------------------- */ private function runCalendarNotifier($duration) { $run_until = (PhabricatorTime::getNow() + $duration); if (!$this->calendarEngine) { $this->calendarEngine = new PhabricatorCalendarNotificationEngine(); } $this->calendarEngine->publishNotifications(); $remaining = max(0, $run_until - PhabricatorTime::getNow()); return $remaining; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/PhabricatorTaskmasterDaemon.php
src/infrastructure/daemon/workers/PhabricatorTaskmasterDaemon.php
<?php final class PhabricatorTaskmasterDaemon extends PhabricatorDaemon { protected function run() { do { PhabricatorCaches::destroyRequestCache(); $tasks = id(new PhabricatorWorkerLeaseQuery()) ->setLimit(1) ->execute(); if ($tasks) { $this->willBeginWork(); foreach ($tasks as $task) { $id = $task->getID(); $class = $task->getTaskClass(); $this->log(pht('Working on task %d (%s)...', $id, $class)); $task = $task->executeTask(); $ex = $task->getExecutionException(); if ($ex) { if ($ex instanceof PhabricatorWorkerPermanentFailureException) { // NOTE: Make sure these reach the daemon log, even when not // running in verbose mode. See T12803 for discussion. $log_exception = new PhutilProxyException( pht( 'Task "%s" encountered a permanent failure and was '. 'cancelled.', $id), $ex); phlog($log_exception); } else if ($ex instanceof PhabricatorWorkerYieldException) { $this->log(pht('Task %s yielded.', $id)); } else { $this->log(pht('Task %d failed!', $id)); throw new PhutilProxyException( pht('Error while executing Task ID %d.', $id), $ex); } } else { $this->log(pht('Task %s complete! Moved to archive.', $id)); } } $sleep = 0; } else { if ($this->getIdleDuration() > 15) { $hibernate_duration = phutil_units('3 minutes in seconds'); if ($this->shouldHibernate($hibernate_duration)) { break; } } // When there's no work, sleep for one second. The pool will // autoscale down if we're continuously idle for an extended period // of time. $this->willBeginIdle(); $sleep = 1; } $this->sleep($sleep); } while (!$this->shouldExit()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/PhabricatorWorker.php
src/infrastructure/daemon/workers/PhabricatorWorker.php
<?php /** * @task config Configuring Retries and Failures */ abstract class PhabricatorWorker extends Phobject { private $data; private static $runAllTasksInProcess = false; private $queuedTasks = array(); private $currentWorkerTask; // NOTE: Lower priority numbers execute first. The priority numbers have to // have the same ordering that IDs do (lowest first) so MySQL can use a // multipart key across both of them efficiently. const PRIORITY_ALERTS = 1000; const PRIORITY_DEFAULT = 2000; const PRIORITY_COMMIT = 2500; const PRIORITY_BULK = 3000; const PRIORITY_INDEX = 3500; const PRIORITY_IMPORT = 4000; /** * Special owner indicating that the task has yielded. */ const YIELD_OWNER = '(yield)'; /* -( Configuring Retries and Failures )----------------------------------- */ /** * Return the number of seconds this worker needs hold a lease on the task for * while it performs work. For most tasks you can leave this at `null`, which * will give you a default lease (currently 2 hours). * * For tasks which may take a very long time to complete, you should return * an upper bound on the amount of time the task may require. * * @return int|null Number of seconds this task needs to remain leased for, * or null for a default lease. * * @task config */ public function getRequiredLeaseTime() { return null; } /** * Return the maximum number of times this task may be retried before it is * considered permanently failed. By default, tasks retry indefinitely. You * can throw a @{class:PhabricatorWorkerPermanentFailureException} to cause an * immediate permanent failure. * * @return int|null Number of times the task will retry before permanent * failure. Return `null` to retry indefinitely. * * @task config */ public function getMaximumRetryCount() { return null; } /** * Return the number of seconds a task should wait after a failure before * retrying. For most tasks you can leave this at `null`, which will give you * a short default retry period (currently 60 seconds). * * @param PhabricatorWorkerTask The task itself. This object is probably * useful mostly to examine the failure count * if you want to implement staggered retries, * or to examine the execution exception if * you want to react to different failures in * different ways. * @return int|null Number of seconds to wait between retries, * or null for a default retry period * (currently 60 seconds). * * @task config */ public function getWaitBeforeRetry(PhabricatorWorkerTask $task) { return null; } public function setCurrentWorkerTask(PhabricatorWorkerTask $task) { $this->currentWorkerTask = $task; return $this; } public function getCurrentWorkerTask() { return $this->currentWorkerTask; } public function getCurrentWorkerTaskID() { $task = $this->getCurrentWorkerTask(); if (!$task) { return null; } return $task->getID(); } abstract protected function doWork(); final public function __construct($data) { $this->data = $data; } final protected function getTaskData() { return $this->data; } final protected function getTaskDataValue($key, $default = null) { $data = $this->getTaskData(); if (!is_array($data)) { throw new PhabricatorWorkerPermanentFailureException( pht('Expected task data to be a dictionary.')); } return idx($data, $key, $default); } final public function executeTask() { $this->doWork(); } final public static function scheduleTask( $task_class, $data, $options = array()) { PhutilTypeSpec::checkMap( $options, array( 'priority' => 'optional int|null', 'objectPHID' => 'optional string|null', 'containerPHID' => 'optional string|null', 'delayUntil' => 'optional int|null', )); $priority = idx($options, 'priority'); if ($priority === null) { $priority = self::PRIORITY_DEFAULT; } $object_phid = idx($options, 'objectPHID'); $container_phid = idx($options, 'containerPHID'); $task = id(new PhabricatorWorkerActiveTask()) ->setTaskClass($task_class) ->setData($data) ->setPriority($priority) ->setObjectPHID($object_phid) ->setContainerPHID($container_phid); $delay = idx($options, 'delayUntil'); if ($delay) { $task->setLeaseExpires($delay); } if (self::$runAllTasksInProcess) { // Do the work in-process. $worker = newv($task_class, array($data)); while (true) { try { $worker->executeTask(); $worker->flushTaskQueue(); $task_result = PhabricatorWorkerArchiveTask::RESULT_SUCCESS; break; } catch (PhabricatorWorkerPermanentFailureException $ex) { $proxy = new PhutilProxyException( pht( 'In-process task ("%s") failed permanently.', $task_class), $ex); phlog($proxy); $task_result = PhabricatorWorkerArchiveTask::RESULT_FAILURE; break; } catch (PhabricatorWorkerYieldException $ex) { phlog( pht( 'In-process task "%s" yielded for %s seconds, sleeping...', $task_class, $ex->getDuration())); sleep($ex->getDuration()); } } // Now, save a task row and immediately archive it so we can return an // object with a valid ID. $task->openTransaction(); $task->save(); $archived = $task->archiveTask($task_result, 0); $task->saveTransaction(); return $archived; } else { $task->save(); return $task; } } public function renderForDisplay(PhabricatorUser $viewer) { return null; } /** * Set this flag to execute scheduled tasks synchronously, in the same * process. This is useful for debugging, and otherwise dramatically worse * in every way imaginable. */ public static function setRunAllTasksInProcess($all) { self::$runAllTasksInProcess = $all; } final protected function log($pattern /* , ... */) { $console = PhutilConsole::getConsole(); $argv = func_get_args(); call_user_func_array(array($console, 'writeLog'), $argv); return $this; } /** * Queue a task to be executed after this one succeeds. * * The followup task will be queued only if this task completes cleanly. * * @param string Task class to queue. * @param array Data for the followup task. * @param array Options for the followup task. * @return this */ final protected function queueTask( $class, array $data, array $options = array()) { $this->queuedTasks[] = array($class, $data, $options); return $this; } /** * Get tasks queued as followups by @{method:queueTask}. * * @return list<tuple<string, wild, int|null>> Queued task specifications. */ final protected function getQueuedTasks() { return $this->queuedTasks; } /** * Schedule any queued tasks, then empty the task queue. * * By default, the queue is flushed only if a task succeeds. You can call * this method to force the queue to flush before failing (for example, if * you are using queues to improve locking behavior). * * @param map<string, wild> Optional default options. * @return this */ final public function flushTaskQueue($defaults = array()) { foreach ($this->getQueuedTasks() as $task) { list($class, $data, $options) = $task; $options = $options + $defaults; self::scheduleTask($class, $data, $options); } $this->queuedTasks = array(); } /** * Awaken tasks that have yielded. * * Reschedules the specified tasks if they are currently queued in a yielded, * unleased, unretried state so they'll execute sooner. This can let the * queue avoid unnecessary waits. * * This method does not provide any assurances about when these tasks will * execute, or even guarantee that it will have any effect at all. * * @param list<id> List of task IDs to try to awaken. * @return void */ final public static function awakenTaskIDs(array $ids) { if (!$ids) { return; } $table = new PhabricatorWorkerActiveTask(); $conn_w = $table->establishConnection('w'); // NOTE: At least for now, we're keeping these tasks yielded, just // pretending that they threw a shorter yield than they really did. // Overlap the windows here to handle minor client/server time differences // and because it's likely correct to push these tasks to the head of their // respective priorities. There is a good chance they are ready to execute. $window = phutil_units('1 hour in seconds'); $epoch_ago = (PhabricatorTime::getNow() - $window); queryfx( $conn_w, 'UPDATE %T SET leaseExpires = %d WHERE id IN (%Ld) AND leaseOwner = %s AND leaseExpires > %d AND failureCount = 0', $table->getTableName(), $epoch_ago, $ids, self::YIELD_OWNER, $epoch_ago); } protected function newContentSource() { return PhabricatorContentSource::newForSource( PhabricatorDaemonContentSource::SOURCECONST); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/PhabricatorTaskmasterDaemonModule.php
src/infrastructure/daemon/workers/PhabricatorTaskmasterDaemonModule.php
<?php final class PhabricatorTaskmasterDaemonModule extends PhutilDaemonOverseerModule { public function shouldWakePool(PhutilDaemonPool $pool) { $class = $pool->getPoolDaemonClass(); if ($class != 'PhabricatorTaskmasterDaemon') { return false; } if ($this->shouldThrottle($class, 1)) { return false; } $table = new PhabricatorWorkerActiveTask(); $conn = $table->establishConnection('r'); $row = queryfx_one( $conn, 'SELECT id FROM %T WHERE leaseOwner IS NULL OR leaseExpires <= %d LIMIT 1', $table->getTableName(), PhabricatorTime::getNow()); if (!$row) { return false; } return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/engineextension/PhabricatorWorkerDestructionEngineExtension.php
src/infrastructure/daemon/workers/engineextension/PhabricatorWorkerDestructionEngineExtension.php
<?php final class PhabricatorWorkerDestructionEngineExtension extends PhabricatorDestructionEngineExtension { const EXTENSIONKEY = 'workers'; public function getExtensionName() { return pht('Worker Tasks'); } public function destroyObject( PhabricatorDestructionEngine $engine, $object) { $tasks = id(new PhabricatorWorkerActiveTask())->loadAllWhere( 'objectPHID = %s', $object->getPHID()); foreach ($tasks as $task) { $task->archiveTask( PhabricatorWorkerArchiveTask::RESULT_CANCELLED, 0); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/storage/PhabricatorWorkerDAO.php
src/infrastructure/daemon/workers/storage/PhabricatorWorkerDAO.php
<?php abstract class PhabricatorWorkerDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'worker'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/storage/PhabricatorWorkerTask.php
src/infrastructure/daemon/workers/storage/PhabricatorWorkerTask.php
<?php abstract class PhabricatorWorkerTask extends PhabricatorWorkerDAO { // NOTE: If you provide additional fields here, make sure they are handled // correctly in the archiving process. protected $taskClass; protected $leaseOwner; protected $leaseExpires; protected $failureCount; protected $dataID; protected $priority; protected $objectPHID; protected $containerPHID; private $data; private $executionException; protected function getConfiguration() { return array( self::CONFIG_COLUMN_SCHEMA => array( 'taskClass' => 'text64', 'leaseOwner' => 'text64?', 'leaseExpires' => 'epoch?', 'failureCount' => 'uint32', 'failureTime' => 'epoch?', 'priority' => 'uint32', 'objectPHID' => 'phid?', 'containerPHID' => 'phid?', ), self::CONFIG_KEY_SCHEMA => array( 'key_object' => array( 'columns' => array('objectPHID'), ), 'key_container' => array( 'columns' => array('containerPHID'), ), ), ) + parent::getConfiguration(); } final public function setExecutionException($execution_exception) { $this->executionException = $execution_exception; return $this; } final public function getExecutionException() { return $this->executionException; } final public function setData($data) { $this->data = $data; return $this; } final public function getData() { return $this->data; } final public function isArchived() { return ($this instanceof PhabricatorWorkerArchiveTask); } final public function getWorkerInstance() { $id = $this->getID(); $class = $this->getTaskClass(); try { // NOTE: If the class does not exist, the autoloader will throw an // exception. class_exists($class); } catch (PhutilMissingSymbolException $ex) { throw new PhabricatorWorkerPermanentFailureException( pht( "Task class '%s' does not exist!", $class)); } if (!is_subclass_of($class, 'PhabricatorWorker')) { throw new PhabricatorWorkerPermanentFailureException( pht( "Task class '%s' does not extend %s.", $class, 'PhabricatorWorker')); } return newv($class, array($this->getData())); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/storage/PhabricatorWorkerTrigger.php
src/infrastructure/daemon/workers/storage/PhabricatorWorkerTrigger.php
<?php final class PhabricatorWorkerTrigger extends PhabricatorWorkerDAO implements PhabricatorDestructibleInterface, PhabricatorPolicyInterface { protected $triggerVersion; protected $clockClass; protected $clockProperties; protected $actionClass; protected $actionProperties; private $action = self::ATTACHABLE; private $clock = self::ATTACHABLE; private $event = self::ATTACHABLE; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_AUX_PHID => true, self::CONFIG_SERIALIZATION => array( 'clockProperties' => self::SERIALIZATION_JSON, 'actionProperties' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'triggerVersion' => 'uint32', 'clockClass' => 'text64', 'actionClass' => 'text64', ), self::CONFIG_KEY_SCHEMA => array( 'key_trigger' => array( 'columns' => array('triggerVersion'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public function save() { $conn_w = $this->establishConnection('w'); $this->openTransaction(); $next_version = LiskDAO::loadNextCounterValue( $conn_w, PhabricatorTriggerDaemon::COUNTER_VERSION); $this->setTriggerVersion($next_version); $result = parent::save(); $this->saveTransaction(); return $this; } public function generatePHID() { return PhabricatorPHID::generateNewPHID( PhabricatorWorkerTriggerPHIDType::TYPECONST); } /** * Return the next time this trigger should execute. * * This method can be called either after the daemon executed the trigger * successfully (giving the trigger an opportunity to reschedule itself * into the future, if it is a recurring event) or after the trigger itself * is changed (usually because of an application edit). The `$is_reschedule` * parameter distinguishes between these cases. * * @param int|null Epoch of the most recent successful event execution. * @param bool `true` if we're trying to reschedule the event after * execution; `false` if this is in response to a trigger update. * @return int|null Return an epoch to schedule the next event execution, * or `null` to stop the event from executing again. */ public function getNextEventEpoch($last_epoch, $is_reschedule) { return $this->getClock()->getNextEventEpoch($last_epoch, $is_reschedule); } /** * Execute the event. * * @param int|null Epoch of previous execution, or null if this is the first * execution. * @param int Scheduled epoch of this execution. This may not be the same * as the current time. * @return void */ public function executeTrigger($last_event, $this_event) { return $this->getAction()->execute($last_event, $this_event); } public function getEvent() { return $this->assertAttached($this->event); } public function attachEvent(PhabricatorWorkerTriggerEvent $event = null) { $this->event = $event; return $this; } public function setAction(PhabricatorTriggerAction $action) { $this->actionClass = get_class($action); $this->actionProperties = $action->getProperties(); return $this->attachAction($action); } public function getAction() { return $this->assertAttached($this->action); } public function attachAction(PhabricatorTriggerAction $action) { $this->action = $action; return $this; } public function setClock(PhabricatorTriggerClock $clock) { $this->clockClass = get_class($clock); $this->clockProperties = $clock->getProperties(); return $this->attachClock($clock); } public function getClock() { return $this->assertAttached($this->clock); } public function attachClock(PhabricatorTriggerClock $clock) { $this->clock = $clock; return $this; } /** * Predict the epoch at which this trigger will next fire. * * @return int|null Epoch when the event will next fire, or `null` if it is * not planned to trigger. */ public function getNextEventPrediction() { // NOTE: We're basically echoing the database state here, so this won't // necessarily be accurate if the caller just updated the object but has // not saved it yet. That's a weird use case and would require more // gymnastics, so don't bother trying to get it totally correct for now. if ($this->getEvent()) { return $this->getEvent()->getNextEventEpoch(); } else { return $this->getNextEventEpoch(null, $is_reschedule = false); } } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $this->openTransaction(); queryfx( $this->establishConnection('w'), 'DELETE FROM %T WHERE triggerID = %d', id(new PhabricatorWorkerTriggerEvent())->getTableName(), $this->getID()); $this->delete(); $this->saveTransaction(); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ // NOTE: Triggers are low-level infrastructure and do not have real // policies, but implementing the policy interface allows us to use // infrastructure like handles. public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { return PhabricatorPolicies::getMostOpenPolicy(); } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/storage/PhabricatorWorkerSchemaSpec.php
src/infrastructure/daemon/workers/storage/PhabricatorWorkerSchemaSpec.php
<?php final class PhabricatorWorkerSchemaSpec extends PhabricatorConfigSchemaSpec { public function buildSchemata() { $this->buildEdgeSchemata(new PhabricatorWorkerBulkJob()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/storage/PhabricatorWorkerBulkJob.php
src/infrastructure/daemon/workers/storage/PhabricatorWorkerBulkJob.php
<?php /** * @task implementation Job Implementation */ final class PhabricatorWorkerBulkJob extends PhabricatorWorkerDAO implements PhabricatorPolicyInterface, PhabricatorSubscribableInterface, PhabricatorApplicationTransactionInterface, PhabricatorDestructibleInterface { const STATUS_CONFIRM = 'confirm'; const STATUS_WAITING = 'waiting'; const STATUS_RUNNING = 'running'; const STATUS_COMPLETE = 'complete'; protected $authorPHID; protected $jobTypeKey; protected $status; protected $parameters = array(); protected $size; protected $isSilent; private $jobImplementation = self::ATTACHABLE; protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_SERIALIZATION => array( 'parameters' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'jobTypeKey' => 'text32', 'status' => 'text32', 'size' => 'uint32', 'isSilent' => 'bool', ), self::CONFIG_KEY_SCHEMA => array( 'key_type' => array( 'columns' => array('jobTypeKey'), ), 'key_author' => array( 'columns' => array('authorPHID'), ), 'key_status' => array( 'columns' => array('status'), ), ), ) + parent::getConfiguration(); } public static function initializeNewJob( PhabricatorUser $actor, PhabricatorWorkerBulkJobType $type, array $parameters) { $job = id(new PhabricatorWorkerBulkJob()) ->setAuthorPHID($actor->getPHID()) ->setJobTypeKey($type->getBulkJobTypeKey()) ->setParameters($parameters) ->attachJobImplementation($type) ->setIsSilent(0); $job->setSize($job->computeSize()); return $job; } public function generatePHID() { return PhabricatorPHID::generateNewPHID( PhabricatorWorkerBulkJobPHIDType::TYPECONST); } public function getMonitorURI() { return '/daemon/bulk/monitor/'.$this->getID().'/'; } public function getManageURI() { return '/daemon/bulk/view/'.$this->getID().'/'; } public function getParameter($key, $default = null) { return idx($this->parameters, $key, $default); } public function setParameter($key, $value) { $this->parameters[$key] = $value; return $this; } public function loadTaskStatusCounts() { $table = new PhabricatorWorkerBulkTask(); $conn_r = $table->establishConnection('r'); $rows = queryfx_all( $conn_r, 'SELECT status, COUNT(*) N FROM %T WHERE bulkJobPHID = %s GROUP BY status', $table->getTableName(), $this->getPHID()); return ipull($rows, 'N', 'status'); } public function newContentSource() { return PhabricatorContentSource::newForSource( PhabricatorBulkContentSource::SOURCECONST, array( 'jobID' => $this->getID(), )); } public function getStatusIcon() { $map = array( self::STATUS_CONFIRM => 'fa-question', self::STATUS_WAITING => 'fa-clock-o', self::STATUS_RUNNING => 'fa-clock-o', self::STATUS_COMPLETE => 'fa-check grey', ); return idx($map, $this->getStatus(), 'none'); } public function getStatusName() { $map = array( self::STATUS_CONFIRM => pht('Confirming'), self::STATUS_WAITING => pht('Waiting'), self::STATUS_RUNNING => pht('Running'), self::STATUS_COMPLETE => pht('Complete'), ); return idx($map, $this->getStatus(), $this->getStatus()); } public function isConfirming() { return ($this->getStatus() == self::STATUS_CONFIRM); } /* -( Job Implementation )------------------------------------------------- */ protected function getJobImplementation() { return $this->assertAttached($this->jobImplementation); } public function attachJobImplementation(PhabricatorWorkerBulkJobType $type) { $this->jobImplementation = $type; return $this; } private function computeSize() { return $this->getJobImplementation()->getJobSize($this); } public function getCancelURI() { return $this->getJobImplementation()->getCancelURI($this); } public function getDoneURI() { return $this->getJobImplementation()->getDoneURI($this); } public function getDescriptionForConfirm() { return $this->getJobImplementation()->getDescriptionForConfirm($this); } public function createTasks() { return $this->getJobImplementation()->createTasks($this); } public function runTask( PhabricatorUser $actor, PhabricatorWorkerBulkTask $task) { return $this->getJobImplementation()->runTask($actor, $this, $task); } public function getJobName() { return $this->getJobImplementation()->getJobName($this); } public function getCurtainActions(PhabricatorUser $viewer) { return $this->getJobImplementation()->getCurtainActions($viewer, $this); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return PhabricatorPolicies::getMostOpenPolicy(); case PhabricatorPolicyCapability::CAN_EDIT: return $this->getAuthorPHID(); } } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return false; } public function describeAutomaticCapability($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_EDIT: return pht('Only the owner of a bulk job can edit it.'); default: return null; } } /* -( PhabricatorSubscribableInterface )----------------------------------- */ public function isAutomaticallySubscribed($phid) { return false; } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new PhabricatorWorkerBulkJobEditor(); } public function getApplicationTransactionTemplate() { return new PhabricatorWorkerBulkJobTransaction(); } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $this->openTransaction(); // We're only removing the actual task objects. This may leave stranded // workers in the queue itself, but they'll just flush out automatically // when they can't load bulk job data. $task_table = new PhabricatorWorkerBulkTask(); $conn_w = $task_table->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE bulkJobPHID = %s', $task_table->getPHID(), $this->getPHID()); $this->delete(); $this->saveTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/storage/PhabricatorWorkerTriggerEvent.php
src/infrastructure/daemon/workers/storage/PhabricatorWorkerTriggerEvent.php
<?php final class PhabricatorWorkerTriggerEvent extends PhabricatorWorkerDAO { protected $triggerID; protected $lastEventEpoch; protected $nextEventEpoch; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'lastEventEpoch' => 'epoch?', 'nextEventEpoch' => 'epoch?', ), self::CONFIG_KEY_SCHEMA => array( 'key_trigger' => array( 'columns' => array('triggerID'), 'unique' => true, ), 'key_next' => array( 'columns' => array('nextEventEpoch'), ), ), ) + parent::getConfiguration(); } public static function initializeNewEvent(PhabricatorWorkerTrigger $trigger) { $event = new PhabricatorWorkerTriggerEvent(); $event->setTriggerID($trigger->getID()); return $event; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/storage/PhabricatorWorkerBulkJobTransaction.php
src/infrastructure/daemon/workers/storage/PhabricatorWorkerBulkJobTransaction.php
<?php final class PhabricatorWorkerBulkJobTransaction extends PhabricatorApplicationTransaction { const TYPE_STATUS = 'bulkjob.status'; public function getApplicationName() { return 'worker'; } public function getApplicationTransactionType() { return PhabricatorWorkerBulkJobPHIDType::TYPECONST; } public function getTitle() { $author_phid = $this->getAuthorPHID(); $old = $this->getOldValue(); $new = $this->getNewValue(); $type = $this->getTransactionType(); switch ($type) { case self::TYPE_STATUS: if ($old === null) { return pht( '%s created this bulk job.', $this->renderHandleLink($author_phid)); } else { switch ($new) { case PhabricatorWorkerBulkJob::STATUS_WAITING: return pht( '%s confirmed this job.', $this->renderHandleLink($author_phid)); case PhabricatorWorkerBulkJob::STATUS_RUNNING: return pht( '%s marked this job as running.', $this->renderHandleLink($author_phid)); case PhabricatorWorkerBulkJob::STATUS_COMPLETE: return pht( '%s marked this job complete.', $this->renderHandleLink($author_phid)); } } break; } return parent::getTitle(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/storage/PhabricatorWorkerBulkTask.php
src/infrastructure/daemon/workers/storage/PhabricatorWorkerBulkTask.php
<?php final class PhabricatorWorkerBulkTask extends PhabricatorWorkerDAO { const STATUS_WAITING = 'waiting'; const STATUS_RUNNING = 'running'; const STATUS_DONE = 'done'; const STATUS_FAIL = 'fail'; protected $bulkJobPHID; protected $objectPHID; protected $status; protected $data = array(); protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_SERIALIZATION => array( 'data' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'status' => 'text32', ), self::CONFIG_KEY_SCHEMA => array( 'key_job' => array( 'columns' => array('bulkJobPHID', 'status'), ), 'key_object' => array( 'columns' => array('objectPHID'), ), ), ) + parent::getConfiguration(); } public static function initializeNewTask( PhabricatorWorkerBulkJob $job, $object_phid) { return id(new PhabricatorWorkerBulkTask()) ->setBulkJobPHID($job->getPHID()) ->setStatus(self::STATUS_WAITING) ->setObjectPHID($object_phid); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/storage/PhabricatorWorkerArchiveTask.php
src/infrastructure/daemon/workers/storage/PhabricatorWorkerArchiveTask.php
<?php final class PhabricatorWorkerArchiveTask extends PhabricatorWorkerTask { const RESULT_SUCCESS = 0; const RESULT_FAILURE = 1; const RESULT_CANCELLED = 2; protected $duration; protected $result; protected $archivedEpoch; protected function getConfiguration() { $parent = parent::getConfiguration(); $config = array( // We manage the IDs in this table; they are allocated in the ActiveTask // table and moved here without alteration. self::CONFIG_IDS => self::IDS_MANUAL, ) + $parent; $config[self::CONFIG_COLUMN_SCHEMA] = array( 'result' => 'uint32', 'duration' => 'uint64', 'archivedEpoch' => 'epoch?', ) + $config[self::CONFIG_COLUMN_SCHEMA]; $config[self::CONFIG_KEY_SCHEMA] = array( 'dateCreated' => array( 'columns' => array('dateCreated'), ), 'key_modified' => array( 'columns' => array('dateModified'), ), ) + $parent[self::CONFIG_KEY_SCHEMA]; return $config; } public function save() { if ($this->getID() === null) { throw new Exception(pht('Trying to archive a task with no ID.')); } $other = new PhabricatorWorkerActiveTask(); $conn_w = $this->establishConnection('w'); $this->openTransaction(); queryfx( $conn_w, 'DELETE FROM %T WHERE id = %d', $other->getTableName(), $this->getID()); $result = parent::insert(); $this->saveTransaction(); return $result; } public function delete() { $this->openTransaction(); if ($this->getDataID()) { $conn_w = $this->establishConnection('w'); $data_table = new PhabricatorWorkerTaskData(); queryfx( $conn_w, 'DELETE FROM %T WHERE id = %d', $data_table->getTableName(), $this->getDataID()); } $result = parent::delete(); $this->saveTransaction(); return $result; } public function unarchiveTask() { $this->openTransaction(); $active = id(new PhabricatorWorkerActiveTask()) ->setID($this->getID()) ->setTaskClass($this->getTaskClass()) ->setLeaseOwner(null) ->setLeaseExpires(0) ->setFailureCount(0) ->setDataID($this->getDataID()) ->setPriority($this->getPriority()) ->setObjectPHID($this->getObjectPHID()) ->setContainerPHID($this->getContainerPHID()) ->setDateCreated($this->getDateCreated()) ->insert(); $this->setDataID(null); $this->delete(); $this->saveTransaction(); return $active; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/storage/PhabricatorWorkerTaskData.php
src/infrastructure/daemon/workers/storage/PhabricatorWorkerTaskData.php
<?php final class PhabricatorWorkerTaskData extends PhabricatorWorkerDAO { protected $data; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_SERIALIZATION => array( 'data' => self::SERIALIZATION_JSON, ), ) + parent::getConfiguration(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/storage/PhabricatorWorkerActiveTask.php
src/infrastructure/daemon/workers/storage/PhabricatorWorkerActiveTask.php
<?php final class PhabricatorWorkerActiveTask extends PhabricatorWorkerTask { protected $failureTime; private $serverTime; private $localTime; protected function getConfiguration() { $parent = parent::getConfiguration(); $config = array( self::CONFIG_IDS => self::IDS_COUNTER, self::CONFIG_KEY_SCHEMA => array( 'taskClass' => array( 'columns' => array('taskClass'), ), 'leaseExpires' => array( 'columns' => array('leaseExpires'), ), 'key_failuretime' => array( 'columns' => array('failureTime'), ), 'key_owner' => array( 'columns' => array('leaseOwner', 'priority', 'id'), ), ) + $parent[self::CONFIG_KEY_SCHEMA], ); return $config + $parent; } public function setServerTime($server_time) { $this->serverTime = $server_time; $this->localTime = time(); return $this; } public function setLeaseDuration($lease_duration) { $this->checkLease(); $server_lease_expires = $this->serverTime + $lease_duration; $this->setLeaseExpires($server_lease_expires); // NOTE: This is primarily to allow unit tests to set negative lease // durations so they don't have to wait around for leases to expire. We // check that the lease is valid above. return $this->forceSaveWithoutLease(); } public function save() { $this->checkLease(); return $this->forceSaveWithoutLease(); } public function forceSaveWithoutLease() { $is_new = !$this->getID(); if ($is_new) { $this->failureCount = 0; } if ($is_new) { $data = new PhabricatorWorkerTaskData(); $data->setData($this->getData()); $data->save(); $this->setDataID($data->getID()); } return parent::save(); } protected function checkLease() { $owner = $this->leaseOwner; if (!$owner) { return; } if ($owner == PhabricatorWorker::YIELD_OWNER) { return; } $current_server_time = $this->serverTime + (time() - $this->localTime); if ($current_server_time >= $this->leaseExpires) { throw new Exception( pht( 'Trying to update Task %d (%s) after lease expiration!', $this->getID(), $this->getTaskClass())); } } public function delete() { throw new Exception( pht( 'Active tasks can not be deleted directly. '. 'Use %s to move tasks to the archive.', 'archiveTask()')); } public function archiveTask($result, $duration) { if ($this->getID() === null) { throw new Exception( pht("Attempting to archive a task which hasn't been saved!")); } $this->checkLease(); $archive = id(new PhabricatorWorkerArchiveTask()) ->setID($this->getID()) ->setTaskClass($this->getTaskClass()) ->setLeaseOwner($this->getLeaseOwner()) ->setLeaseExpires($this->getLeaseExpires()) ->setFailureCount($this->getFailureCount()) ->setDataID($this->getDataID()) ->setPriority($this->getPriority()) ->setObjectPHID($this->getObjectPHID()) ->setContainerPHID($this->getContainerPHID()) ->setResult($result) ->setDuration($duration) ->setDateCreated($this->getDateCreated()) ->setArchivedEpoch(PhabricatorTime::getNow()); // NOTE: This deletes the active task (this object)! $archive->save(); return $archive; } public function executeTask() { // We do this outside of the try .. catch because we don't have permission // to release the lease otherwise. $this->checkLease(); $did_succeed = false; $worker = null; $caught = null; try { $worker = $this->getWorkerInstance(); $worker->setCurrentWorkerTask($this); $maximum_failures = $worker->getMaximumRetryCount(); if ($maximum_failures !== null) { if ($this->getFailureCount() > $maximum_failures) { throw new PhabricatorWorkerPermanentFailureException( pht( 'Task %d has exceeded the maximum number of failures (%d).', $this->getID(), $maximum_failures)); } } $lease = $worker->getRequiredLeaseTime(); if ($lease !== null) { $this->setLeaseDuration($lease); } $t_start = microtime(true); $worker->executeTask(); $duration = phutil_microseconds_since($t_start); $result = $this->archiveTask( PhabricatorWorkerArchiveTask::RESULT_SUCCESS, $duration); $did_succeed = true; } catch (PhabricatorWorkerPermanentFailureException $ex) { $result = $this->archiveTask( PhabricatorWorkerArchiveTask::RESULT_FAILURE, 0); $result->setExecutionException($ex); } catch (PhabricatorWorkerYieldException $ex) { $this->setExecutionException($ex); $this->setLeaseOwner(PhabricatorWorker::YIELD_OWNER); $retry = $ex->getDuration(); $retry = max($retry, 5); // NOTE: As a side effect, this saves the object. $this->setLeaseDuration($retry); $result = $this; } catch (Exception $ex) { $caught = $ex; } catch (Throwable $ex) { $caught = $ex; } if ($caught) { $this->setExecutionException($ex); $this->setFailureCount($this->getFailureCount() + 1); $this->setFailureTime(time()); $retry = null; if ($worker) { $retry = $worker->getWaitBeforeRetry($this); } $retry = coalesce( $retry, PhabricatorWorkerLeaseQuery::getDefaultWaitBeforeRetry()); // NOTE: As a side effect, this saves the object. $this->setLeaseDuration($retry); $result = $this; } // NOTE: If this throws, we don't want it to cause the task to fail again, // so execute it out here and just let the exception escape. if ($did_succeed) { // Default the new task priority to our own priority. $defaults = array( 'priority' => (int)$this->getPriority(), ); $worker->flushTaskQueue($defaults); } return $result; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/management/PhabricatorWorkerTriggerManagementFireWorkflow.php
src/infrastructure/daemon/workers/management/PhabricatorWorkerTriggerManagementFireWorkflow.php
<?php final class PhabricatorWorkerTriggerManagementFireWorkflow extends PhabricatorWorkerTriggerManagementWorkflow { protected function didConstruct() { $this ->setName('fire') ->setExamples('**fire** --id __id__') ->setSynopsis( pht( 'Activates selected triggers, firing them immediately.')) ->setArguments( array_merge( array( array( 'name' => 'now', 'param' => 'time', 'help' => pht( 'Fire the trigger as though the current time is a given '. 'time. This allows you to test how a trigger would behave '. 'if activated in the past or future. Defaults to the actual '. 'current time.'), ), array( 'name' => 'last', 'param' => 'time', 'help' => pht( 'Fire the trigger as though the last event occurred at a '. 'given time. Defaults to the actual last event time.'), ), array( 'name' => 'next', 'param' => 'time', 'help' => pht( 'Fire the trigger as though the next event was scheduled '. 'at a given time. Defaults to the actual time when the '. 'event is next scheduled to fire.'), ), ), $this->getTriggerSelectionArguments())); } public function execute(PhutilArgumentParser $args) { $console = PhutilConsole::getConsole(); $viewer = $this->getViewer(); $triggers = $this->loadTriggers($args); $now = $args->getArg('now'); $now = $this->parseTimeArgument($now); if (!$now) { $now = PhabricatorTime::getNow(); } $time_guard = PhabricatorTime::pushTime($now, date_default_timezone_get()); $console->writeOut( "%s\n", pht( 'Set current time to %s.', phabricator_datetime(PhabricatorTime::getNow(), $viewer))); $last_time = $this->parseTimeArgument($args->getArg('last')); $next_time = $this->parseTimeArgument($args->getArg('next')); PhabricatorWorker::setRunAllTasksInProcess(true); foreach ($triggers as $trigger) { $console->writeOut( "%s\n", pht('Executing trigger %s.', $this->describeTrigger($trigger))); $event = $trigger->getEvent(); if ($event) { if (!$last_time) { $last_time = $event->getLastEventEpoch(); } if (!$next_time) { $next_time = $event->getNextEventEpoch(); } } if (!$next_time) { $console->writeOut( "%s\n", pht( 'Trigger is not scheduled to execute. Use --next to simulate '. 'a scheduled event.')); continue; } else { $console->writeOut( "%s\n", pht( 'Executing event as though it was scheduled to execute at %s.', phabricator_datetime($next_time, $viewer))); } if (!$last_time) { $console->writeOut( "%s\n", pht( 'Executing event as though it never previously executed.')); } else { $console->writeOut( "%s\n", pht( 'Executing event as though it previously executed at %s.', phabricator_datetime($last_time, $viewer))); } $trigger->executeTrigger($last_time, $next_time); $reschedule_time = $trigger->getNextEventEpoch( $next_time, $is_reschedule = true); if (!$reschedule_time) { $console->writeOut( "%s\n", pht( 'After executing under these conditions, this event would never '. 'execute again.')); } else { $console->writeOut( "%s\n", pht( 'After executing under these conditions, this event would '. 'next execute at %s.', phabricator_datetime($reschedule_time, $viewer))); } } return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementCancelWorkflow.php
src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementCancelWorkflow.php
<?php final class PhabricatorWorkerManagementCancelWorkflow extends PhabricatorWorkerManagementWorkflow { protected function didConstruct() { $this ->setName('cancel') ->setExamples('**cancel** __selectors__') ->setSynopsis( pht( 'Cancel selected tasks. The work these tasks represent will never '. 'be performed.')) ->setArguments($this->getTaskSelectionArguments()); } public function execute(PhutilArgumentParser $args) { $tasks = $this->loadTasks($args); if (!$tasks) { $this->logWarn( pht('NO TASKS'), pht('No tasks selected to cancel.')); return 0; } $cancel_count = 0; foreach ($tasks as $task) { $can_cancel = !$task->isArchived(); if (!$can_cancel) { $this->logWarn( pht('ARCHIVED'), pht( '%s is already archived, and can not be cancelled.', $this->describeTask($task))); continue; } // Forcibly break the lease if one exists, so we can archive the // task. $task ->setLeaseOwner(null) ->setLeaseExpires(PhabricatorTime::getNow()); $task->archiveTask(PhabricatorWorkerArchiveTask::RESULT_CANCELLED, 0); $this->logInfo( pht('CANCELLED'), pht( '%s was cancelled.', $this->describeTask($task))); $cancel_count++; } $this->logOkay( pht('DONE'), pht('Cancelled %s task(s).', new PhutilNumber($cancel_count))); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementRetryWorkflow.php
src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementRetryWorkflow.php
<?php final class PhabricatorWorkerManagementRetryWorkflow extends PhabricatorWorkerManagementWorkflow { protected function didConstruct() { $this ->setName('retry') ->setExamples('**retry** __selectors__') ->setSynopsis( pht( 'Retry selected tasks which previously failed permanently or '. 'were cancelled. Only archived tasks can be retried.')) ->setArguments( array_merge( array( array( 'name' => 'repeat', 'help' => pht( 'Repeat tasks which already completed successfully.'), ), ), $this->getTaskSelectionArguments())); } public function execute(PhutilArgumentParser $args) { $is_repeat = $args->getArg('repeat'); $tasks = $this->loadTasks($args); if (!$tasks) { $this->logWarn( pht('NO TASKS'), pht('No tasks selected to retry.')); return 0; } $retry_count = 0; foreach ($tasks as $task) { if (!$task->isArchived()) { $this->logWarn( pht('ACTIVE'), pht( '%s is already in the active task queue.', $this->describeTask($task))); continue; } $result_success = PhabricatorWorkerArchiveTask::RESULT_SUCCESS; if ($task->getResult() == $result_success) { if (!$is_repeat) { $this->logWarn( pht('SUCCEEDED'), pht( '%s has already succeeded, and will not be repeated. '. 'Use "--repeat" to repeat successful tasks.', $this->describeTask($task))); continue; } } $task->unarchiveTask(); $this->logInfo( pht('QUEUED'), pht( '%s was queued for retry.', $this->describeTask($task))); $retry_count++; } $this->logOkay( pht('DONE'), pht('Queued %s task(s) for retry.', new PhutilNumber($retry_count))); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementWorkflow.php
src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementWorkflow.php
<?php abstract class PhabricatorWorkerManagementWorkflow extends PhabricatorManagementWorkflow { protected function getTaskSelectionArguments() { return array( array( 'name' => 'id', 'param' => 'id', 'repeat' => true, 'help' => pht('Select one or more tasks by ID.'), ), array( 'name' => 'class', 'param' => 'name', 'help' => pht('Select tasks of a given class.'), ), array( 'name' => 'min-failure-count', 'param' => 'int', 'help' => pht('Select tasks with a minimum failure count.'), ), array( 'name' => 'max-failure-count', 'param' => 'int', 'help' => pht('Select tasks with a maximum failure count.'), ), array( 'name' => 'active', 'help' => pht('Select active tasks.'), ), array( 'name' => 'archived', 'help' => pht('Select archived tasks.'), ), array( 'name' => 'container', 'param' => 'name', 'help' => pht( 'Select tasks with the given container or containers.'), 'repeat' => true, ), array( 'name' => 'object', 'param' => 'name', 'repeat' => true, 'help' => pht( 'Select tasks affecting the given object or objects.'), ), array( 'name' => 'min-priority', 'param' => 'int', 'help' => pht('Select tasks with a minimum priority.'), ), array( 'name' => 'max-priority', 'param' => 'int', 'help' => pht('Select tasks with a maximum priority.'), ), array( 'name' => 'limit', 'param' => 'int', 'help' => pht('Limit selection to a maximum number of tasks.'), ), ); } protected function loadTasks(PhutilArgumentParser $args) { $ids = $args->getArg('id'); $class = $args->getArg('class'); $active = $args->getArg('active'); $archived = $args->getArg('archived'); $container_names = $args->getArg('container'); $object_names = $args->getArg('object'); $min_failures = $args->getArg('min-failure-count'); $max_failures = $args->getArg('max-failure-count'); $min_priority = $args->getArg('min-priority'); $max_priority = $args->getArg('max-priority'); $limit = $args->getArg('limit'); $any_constraints = false; if ($ids) { $any_constraints = true; } if ($class) { $any_constraints = true; } if ($active || $archived) { $any_constraints = true; if ($active && $archived) { throw new PhutilArgumentUsageException( pht( 'You can not specify both "--active" and "--archived" tasks: '. 'no tasks can match both constraints.')); } } if ($container_names) { $any_constraints = true; $container_phids = $this->loadObjectPHIDsFromArguments($container_names); } else { $container_phids = array(); } if ($object_names) { $any_constraints = true; $object_phids = $this->loadObjectPHIDsFromArguments($object_names); } else { $object_phids = array(); } if (($min_failures !== null) || ($max_failures !== null)) { $any_constraints = true; if (($min_failures !== null) && ($max_failures !== null)) { if ($min_failures > $max_failures) { throw new PhutilArgumentUsageException( pht( 'Specified "--min-failures" must not be larger than '. 'specified "--max-failures".')); } } } if (($min_priority !== null) || ($max_priority !== null)) { $any_constraints = true; if (($min_priority !== null) && ($max_priority !== null)) { if ($min_priority > $max_priority) { throw new PhutilArgumentUsageException( pht( 'Specified "--min-priority" may not be larger than '. 'specified "--max-priority".')); } } } if (!$any_constraints) { throw new PhutilArgumentUsageException( pht( 'Use constraint flags (like "--id" or "--class") to select which '. 'tasks to affect. Use "--help" for a list of supported constraint '. 'flags.')); } if ($limit !== null) { $limit = (int)$limit; if ($limit <= 0) { throw new PhutilArgumentUsageException( pht( 'Specified "--limit" must be a positive integer.')); } } $active_query = new PhabricatorWorkerActiveTaskQuery(); $archive_query = new PhabricatorWorkerArchiveTaskQuery(); if ($ids) { $active_query = $active_query->withIDs($ids); $archive_query = $archive_query->withIDs($ids); } if ($class) { $class_array = array($class); $active_query = $active_query->withClassNames($class_array); $archive_query = $archive_query->withClassNames($class_array); } if ($min_failures) { $active_query->withFailureCountBetween($min_failures, $max_failures); $archive_query->withFailureCountBetween($min_failures, $max_failures); } if ($container_phids) { $active_query->withContainerPHIDs($container_phids); $archive_query->withContainerPHIDs($container_phids); } if ($object_phids) { $active_query->withObjectPHIDs($object_phids); $archive_query->withObjectPHIDs($object_phids); } if ($min_priority || $max_priority) { $active_query->withPriorityBetween($min_priority, $max_priority); $archive_query->withPriorityBetween($min_priority, $max_priority); } if ($limit) { $active_query->setLimit($limit); $archive_query->setLimit($limit); } if ($archived) { $active_tasks = array(); } else { $active_tasks = $active_query->execute(); } if ($active) { $archive_tasks = array(); } else { $archive_tasks = $archive_query->execute(); } $tasks = mpull($active_tasks, null, 'getID') + mpull($archive_tasks, null, 'getID'); if ($limit) { $tasks = array_slice($tasks, 0, $limit, $preserve_keys = true); } if ($ids) { foreach ($ids as $id) { if (empty($tasks[$id])) { throw new PhutilArgumentUsageException( pht('No task with ID "%s" matches the constraints!', $id)); } } } // We check that IDs are valid, but for all other constraints it is // acceptable to select no tasks to act upon. // When we lock tasks properly, this gets populated as a side effect. Just // fake it when doing manual CLI stuff. This makes sure CLI yields have // their expires times set properly. foreach ($tasks as $task) { if ($task instanceof PhabricatorWorkerActiveTask) { $task->setServerTime(PhabricatorTime::getNow()); } } // If the user specified one or more "--id" flags, process the tasks in // the given order. Otherwise, process them in FIFO order so the sequence // is somewhat consistent with natural execution order. // NOTE: When "--limit" is used, we end up selecting the newest tasks // first. At time of writing, there's no way to order the queries // correctly, so just accept it as reasonable behavior. if ($ids) { $tasks = array_select_keys($tasks, $ids); } else { $tasks = msort($tasks, 'getID'); } return $tasks; } protected function describeTask(PhabricatorWorkerTask $task) { return pht('Task %d (%s)', $task->getID(), $task->getTaskClass()); } private function loadObjectPHIDsFromArguments(array $names) { $viewer = $this->getViewer(); $seen_names = array(); foreach ($names as $name) { if (isset($seen_names[$name])) { throw new PhutilArgumentUsageException( pht( 'Object "%s" is specified more than once. Specify only unique '. 'objects.', $name)); } $seen_names[$name] = true; } $object_query = id(new PhabricatorObjectQuery()) ->setViewer($viewer) ->withNames($names); $object_query->execute(); $name_map = $object_query->getNamedResults(); $phid_map = array(); foreach ($names as $name) { if (!isset($name_map[$name])) { throw new PhutilArgumentUsageException( pht( 'No object with name "%s" could be loaded.', $name)); } $phid = $name_map[$name]->getPHID(); if (isset($phid_map[$phid])) { throw new PhutilArgumentUsageException( pht( 'Names "%s" and "%s" identify the same object. Specify only '. 'unique objects.', $name, $phid_map[$phid])); } $phid_map[$phid] = $name; } return array_keys($phid_map); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementFreeWorkflow.php
src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementFreeWorkflow.php
<?php final class PhabricatorWorkerManagementFreeWorkflow extends PhabricatorWorkerManagementWorkflow { protected function didConstruct() { $this ->setName('free') ->setExamples('**free** __selectors__') ->setSynopsis( pht( 'Free leases on selected tasks. If the daemon holding the lease is '. 'still working on the task, this may cause the task to execute '. 'twice.')) ->setArguments($this->getTaskSelectionArguments()); } public function execute(PhutilArgumentParser $args) { $tasks = $this->loadTasks($args); if (!$tasks) { $this->logWarn( pht('NO TASKS'), pht('No tasks selected to free leases on.')); return 0; } $free_count = 0; foreach ($tasks as $task) { if ($task->isArchived()) { $this->logWarn( pht('ARCHIVED'), pht( '%s is archived; archived tasks do not have leases.', $this->describeTask($task))); continue; } if ($task->getLeaseOwner() === null) { $this->logWarn( pht('FREE'), pht( '%s has no active lease.', $this->describeTask($task))); continue; } $task ->setLeaseOwner(null) ->setLeaseExpires(PhabricatorTime::getNow()) ->save(); $this->logInfo( pht('LEASE FREED'), pht( '%s was freed from its lease.', $this->describeTask($task))); $free_count++; } $this->logOkay( pht('DONE'), pht('Freed %s task lease(s).', new PhutilNumber($free_count))); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/management/PhabricatorWorkerTriggerManagementWorkflow.php
src/infrastructure/daemon/workers/management/PhabricatorWorkerTriggerManagementWorkflow.php
<?php abstract class PhabricatorWorkerTriggerManagementWorkflow extends PhabricatorManagementWorkflow { protected function getTriggerSelectionArguments() { return array( array( 'name' => 'id', 'param' => 'id', 'repeat' => true, 'help' => pht('Select one or more triggers by ID.'), ), ); } protected function loadTriggers(PhutilArgumentParser $args) { $ids = $args->getArg('id'); if (!$ids) { throw new PhutilArgumentUsageException( pht('Use %s to select triggers by ID.', '--id')); } $triggers = id(new PhabricatorWorkerTriggerQuery()) ->setViewer($this->getViewer()) ->withIDs($ids) ->needEvents(true) ->execute(); $triggers = mpull($triggers, null, 'getID'); foreach ($ids as $id) { if (empty($triggers[$id])) { throw new PhutilArgumentUsageException( pht('No trigger exists with id "%s"!', $id)); } } return $triggers; } protected function describeTrigger(PhabricatorWorkerTrigger $trigger) { return pht('Trigger %d', $trigger->getID()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementFloodWorkflow.php
src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementFloodWorkflow.php
<?php final class PhabricatorWorkerManagementFloodWorkflow extends PhabricatorWorkerManagementWorkflow { protected function didConstruct() { $this ->setName('flood') ->setExamples('**flood**') ->setSynopsis( pht( 'Flood the queue with test tasks. This command is intended for '. 'use during development and debugging.')) ->setArguments( array( array( 'name' => 'duration', 'param' => 'seconds', 'help' => pht( 'Queue tasks which require a specific amount of wall time to '. 'complete. By default, tasks complete as quickly as possible.'), 'default' => 0, ), )); } public function execute(PhutilArgumentParser $args) { $console = PhutilConsole::getConsole(); $duration = (float)$args->getArg('duration'); $console->writeOut( "%s\n", pht('Adding many test tasks to worker queue. Use ^C to exit.')); $n = 0; while (true) { PhabricatorWorker::scheduleTask( 'PhabricatorTestWorker', array( 'duration' => $duration, )); if (($n++ % 100) === 0) { $console->writeOut('.'); } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementExecuteWorkflow.php
src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementExecuteWorkflow.php
<?php final class PhabricatorWorkerManagementExecuteWorkflow extends PhabricatorWorkerManagementWorkflow { protected function didConstruct() { $this ->setName('execute') ->setExamples('**execute** __selectors__') ->setSynopsis( pht( 'Execute a task explicitly. This command ignores leases, is '. 'dangerous, and may cause work to be performed twice.')) ->setArguments( array_merge( array( array( 'name' => 'retry', 'help' => pht('Retry archived tasks.'), ), array( 'name' => 'repeat', 'help' => pht('Repeat archived, successful tasks.'), ), ), $this->getTaskSelectionArguments())); } public function execute(PhutilArgumentParser $args) { $is_retry = $args->getArg('retry'); $is_repeat = $args->getArg('repeat'); $tasks = $this->loadTasks($args); if (!$tasks) { $this->logWarn( pht('NO TASKS'), pht('No tasks selected to execute.')); return 0; } $execute_count = 0; foreach ($tasks as $task) { $can_execute = !$task->isArchived(); if (!$can_execute) { if (!$is_retry) { $this->logWarn( pht('ARCHIVED'), pht( '%s is already archived, and will not be executed. '. 'Use "--retry" to execute archived tasks.', $this->describeTask($task))); continue; } $result_success = PhabricatorWorkerArchiveTask::RESULT_SUCCESS; if ($task->getResult() == $result_success) { if (!$is_repeat) { $this->logWarn( pht('SUCCEEDED'), pht( '%s has already succeeded, and will not be retried. '. 'Use "--repeat" to repeat successful tasks.', $this->describeTask($task))); continue; } } $this->logInfo( pht('UNARCHIVING'), pht( 'Unarchiving %s.', $this->describeTask($task))); $task = $task->unarchiveTask(); } // NOTE: This ignores leases, maybe it should respect them without // a parameter like --force? $task ->setLeaseOwner(null) ->setLeaseExpires(PhabricatorTime::getNow()) ->save(); $task_data = id(new PhabricatorWorkerTaskData())->loadOneWhere( 'id = %d', $task->getDataID()); $task->setData($task_data->getData()); $this->logInfo( pht('EXECUTE'), pht( 'Executing %s...', $this->describeTask($task))); $task = $task->executeTask(); $ex = $task->getExecutionException(); if ($ex) { throw $ex; } $execute_count++; } $this->logOkay( pht('DONE'), pht('Executed %s task(s).', new PhutilNumber($execute_count))); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementDelayWorkflow.php
src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementDelayWorkflow.php
<?php final class PhabricatorWorkerManagementDelayWorkflow extends PhabricatorWorkerManagementWorkflow { protected function didConstruct() { $this ->setName('delay') ->setExamples( implode( "\n", array( '**delay** __selectors__ --until __date__', '**delay** __selectors__ --until __YYYY-MM-DD__', '**delay** __selectors__ --until "6 hours"', '**delay** __selectors__ --until now', ))) ->setSynopsis( pht( 'Delay execution of selected tasks until the specified time.')) ->setArguments( array_merge( array( array( 'name' => 'until', 'param' => 'date', 'help' => pht( 'Select the date or time to delay the selected tasks until.'), ), ), $this->getTaskSelectionArguments())); } public function execute(PhutilArgumentParser $args) { $viewer = $this->getViewer(); $until = $args->getArg('until'); $until = $this->parseTimeArgument($until); if ($until === null) { throw new PhutilArgumentUsageException( pht( 'Specify how long to delay tasks for with "--until".')); } $tasks = $this->loadTasks($args); if (!$tasks) { $this->logWarn( pht('NO TASKS'), pht('No tasks selected to delay.')); return 0; } $delay_count = 0; foreach ($tasks as $task) { if ($task->isArchived()) { $this->logWarn( pht('ARCHIVED'), pht( '%s is already archived, and can not be delayed.', $this->describeTask($task))); continue; } if ($task->getLeaseOwner()) { $this->logWarn( pht('LEASED'), pht( '% is already leased, and can not be delayed.', $this->describeTask($task))); continue; } $task ->setLeaseExpires($until) ->save(); $this->logInfo( pht('DELAY'), pht( '%s was delayed until "%s".', $this->describeTask($task), phabricator_datetime($until, $viewer))); $delay_count++; } $this->logOkay( pht('DONE'), pht('Delayed %s task(s).', new PhutilNumber($delay_count))); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementPriorityWorkflow.php
src/infrastructure/daemon/workers/management/PhabricatorWorkerManagementPriorityWorkflow.php
<?php final class PhabricatorWorkerManagementPriorityWorkflow extends PhabricatorWorkerManagementWorkflow { protected function didConstruct() { $this ->setName('priority') ->setExamples('**priority** __selectors__ --priority __value__') ->setSynopsis( pht( 'Change the priority of selected tasks, causing them to execute '. 'before or after other tasks.')) ->setArguments( array_merge( array( array( 'name' => 'priority', 'param' => 'int', 'help' => pht( 'Set tasks to this priority. Tasks with a smaller priority '. 'value execute before tasks with a larger priority value.'), ), ), $this->getTaskSelectionArguments())); } public function execute(PhutilArgumentParser $args) { $new_priority = $args->getArg('priority'); if ($new_priority === null) { throw new PhutilArgumentUsageException( pht( 'Select a new priority for selected tasks with "--priority".')); } $new_priority = (int)$new_priority; if ($new_priority <= 0) { throw new PhutilArgumentUsageException( pht( 'Priority must be a positive integer.')); } $tasks = $this->loadTasks($args); if (!$tasks) { $this->logWarn( pht('NO TASKS'), pht('No tasks selected to reprioritize.')); return 0; } $priority_count = 0; foreach ($tasks as $task) { $can_reprioritize = !$task->isArchived(); if (!$can_reprioritize) { $this->logWarn( pht('ARCHIVED'), pht( '%s is already archived, and can not be reprioritized.', $this->describeTask($task))); continue; } $old_priority = (int)$task->getPriority(); if ($old_priority === $new_priority) { $this->logWarn( pht('UNCHANGED'), pht( '%s already has priority "%s".', $this->describeTask($task), $new_priority)); continue; } $task ->setPriority($new_priority) ->save(); $this->logInfo( pht('PRIORITY'), pht( '%s was reprioritized (from "%d" to "%d").', $this->describeTask($task), $old_priority, $new_priority)); $priority_count++; } $this->logOkay( pht('DONE'), pht('Reprioritized %s task(s).', new PhutilNumber($priority_count))); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/query/PhabricatorWorkerBulkJobQuery.php
src/infrastructure/daemon/workers/query/PhabricatorWorkerBulkJobQuery.php
<?php final class PhabricatorWorkerBulkJobQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $ids; private $phids; private $authorPHIDs; private $bulkJobTypes; private $statuses; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withPHIDs(array $phids) { $this->phids = $phids; return $this; } public function withAuthorPHIDs(array $author_phids) { $this->authorPHIDs = $author_phids; return $this; } public function withBulkJobTypes(array $job_types) { $this->bulkJobTypes = $job_types; return $this; } public function withStatuses(array $statuses) { $this->statuses = $statuses; return $this; } public function newResultObject() { return new PhabricatorWorkerBulkJob(); } protected function willFilterPage(array $page) { $map = PhabricatorWorkerBulkJobType::getAllJobTypes(); foreach ($page as $key => $job) { $implementation = idx($map, $job->getJobTypeKey()); if (!$implementation) { $this->didRejectResult($job); unset($page[$key]); continue; } $job->attachJobImplementation($implementation); } return $page; } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); if ($this->ids !== null) { $where[] = qsprintf( $conn, 'id IN (%Ld)', $this->ids); } if ($this->phids !== null) { $where[] = qsprintf( $conn, 'phid IN (%Ls)', $this->phids); } if ($this->authorPHIDs !== null) { $where[] = qsprintf( $conn, 'authorPHID IN (%Ls)', $this->authorPHIDs); } if ($this->bulkJobTypes !== null) { $where[] = qsprintf( $conn, 'bulkJobType IN (%Ls)', $this->bulkJobTypes); } if ($this->statuses !== null) { $where[] = qsprintf( $conn, 'status IN (%Ls)', $this->statuses); } return $where; } public function getQueryApplicationClass() { return 'PhabricatorDaemonsApplication'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/query/PhabricatorWorkerBulkJobSearchEngine.php
src/infrastructure/daemon/workers/query/PhabricatorWorkerBulkJobSearchEngine.php
<?php final class PhabricatorWorkerBulkJobSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Daemon Bulk Jobs'); } public function getApplicationClassName() { return 'PhabricatorDaemonsApplication'; } public function newQuery() { return id(new PhabricatorWorkerBulkJobQuery()); } public function canUseInPanelContext() { return false; } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); if ($map['authorPHIDs']) { $query->withAuthorPHIDs($map['authorPHIDs']); } return $query; } protected function buildCustomSearchFields() { return array( id(new PhabricatorUsersSearchField()) ->setLabel(pht('Authors')) ->setKey('authorPHIDs') ->setAliases(array('author', 'authors')), ); } protected function getURI($path) { return '/daemon/bulk/'.$path; } protected function getBuiltinQueryNames() { $names = array(); if ($this->requireViewer()->isLoggedIn()) { $names['authored'] = pht('Authored Jobs'); } $names['all'] = pht('All Jobs'); return $names; } public function buildSavedQueryFromBuiltin($query_key) { $query = $this->newSavedQuery(); $query->setQueryKey($query_key); switch ($query_key) { case 'all': return $query; case 'authored': return $query->setParameter( 'authorPHIDs', array($this->requireViewer()->getPHID())); } return parent::buildSavedQueryFromBuiltin($query_key); } protected function renderResultList( array $jobs, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($jobs, 'PhabricatorWorkerBulkJob'); $viewer = $this->requireViewer(); $list = id(new PHUIObjectItemListView()) ->setUser($viewer); foreach ($jobs as $job) { $size = pht('%s Bulk Task(s)', new PhutilNumber($job->getSize())); $item = id(new PHUIObjectItemView()) ->setObjectName(pht('Bulk Job %d', $job->getID())) ->setHeader($job->getJobName()) ->addAttribute(phabricator_datetime($job->getDateCreated(), $viewer)) ->setHref($job->getManageURI()) ->addIcon($job->getStatusIcon(), $job->getStatusName()) ->addIcon('none', $size); $list->addItem($item); } return id(new PhabricatorApplicationSearchResultView()) ->setContent($list); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/query/PhabricatorWorkerArchiveTaskQuery.php
src/infrastructure/daemon/workers/query/PhabricatorWorkerArchiveTaskQuery.php
<?php final class PhabricatorWorkerArchiveTaskQuery extends PhabricatorWorkerTaskQuery { public function execute() { $task_table = new PhabricatorWorkerArchiveTask(); $conn_r = $task_table->establishConnection('r'); $rows = queryfx_all( $conn_r, 'SELECT * FROM %T %Q %Q %Q', $task_table->getTableName(), $this->buildWhereClause($conn_r), $this->buildOrderClause($conn_r), $this->buildLimitClause($conn_r)); return $task_table->loadAllFromArray($rows); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/query/PhabricatorWorkerActiveTaskQuery.php
src/infrastructure/daemon/workers/query/PhabricatorWorkerActiveTaskQuery.php
<?php final class PhabricatorWorkerActiveTaskQuery extends PhabricatorWorkerTaskQuery { public function execute() { $task_table = new PhabricatorWorkerActiveTask(); $conn_r = $task_table->establishConnection('r'); $rows = queryfx_all( $conn_r, 'SELECT * FROM %T %Q %Q %Q', $task_table->getTableName(), $this->buildWhereClause($conn_r), $this->buildOrderClause($conn_r), $this->buildLimitClause($conn_r)); return $task_table->loadAllFromArray($rows); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/query/PhabricatorWorkerTaskQuery.php
src/infrastructure/daemon/workers/query/PhabricatorWorkerTaskQuery.php
<?php abstract class PhabricatorWorkerTaskQuery extends PhabricatorQuery { private $ids; private $dateModifiedSince; private $dateCreatedBefore; private $objectPHIDs; private $containerPHIDs; private $classNames; private $limit; private $minFailureCount; private $maxFailureCount; private $minPriority; private $maxPriority; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withDateModifiedSince($timestamp) { $this->dateModifiedSince = $timestamp; return $this; } public function withDateCreatedBefore($timestamp) { $this->dateCreatedBefore = $timestamp; return $this; } public function withObjectPHIDs(array $phids) { $this->objectPHIDs = $phids; return $this; } public function withContainerPHIDs(array $phids) { $this->containerPHIDs = $phids; return $this; } public function withClassNames(array $names) { $this->classNames = $names; return $this; } public function withFailureCountBetween($min, $max) { $this->minFailureCount = $min; $this->maxFailureCount = $max; return $this; } public function withPriorityBetween($min, $max) { $this->minPriority = $min; $this->maxPriority = $max; return $this; } public function setLimit($limit) { $this->limit = $limit; return $this; } protected function buildWhereClause(AphrontDatabaseConnection $conn) { $where = array(); if ($this->ids !== null) { $where[] = qsprintf( $conn, 'id in (%Ld)', $this->ids); } if ($this->objectPHIDs !== null) { $where[] = qsprintf( $conn, 'objectPHID IN (%Ls)', $this->objectPHIDs); } if ($this->containerPHIDs !== null) { $where[] = qsprintf( $conn, 'containerPHID IN (%Ls)', $this->containerPHIDs); } if ($this->dateModifiedSince !== null) { $where[] = qsprintf( $conn, 'dateModified > %d', $this->dateModifiedSince); } if ($this->dateCreatedBefore !== null) { $where[] = qsprintf( $conn, 'dateCreated < %d', $this->dateCreatedBefore); } if ($this->classNames !== null) { $where[] = qsprintf( $conn, 'taskClass IN (%Ls)', $this->classNames); } if ($this->minFailureCount !== null) { $where[] = qsprintf( $conn, 'failureCount >= %d', $this->minFailureCount); } if ($this->maxFailureCount !== null) { $where[] = qsprintf( $conn, 'failureCount <= %d', $this->maxFailureCount); } if ($this->minPriority !== null) { $where[] = qsprintf( $conn, 'priority >= %d', $this->minPriority); } if ($this->maxPriority !== null) { $where[] = qsprintf( $conn, 'priority <= %d', $this->maxPriority); } return $this->formatWhereClause($conn, $where); } protected function buildOrderClause(AphrontDatabaseConnection $conn) { // NOTE: The garbage collector executes this query with a date constraint, // and the query is inefficient if we don't use the same key for ordering. // See T9808 for discussion. if ($this->dateCreatedBefore) { return qsprintf($conn, 'ORDER BY dateCreated DESC, id DESC'); } else if ($this->dateModifiedSince) { return qsprintf($conn, 'ORDER BY dateModified DESC, id DESC'); } else { return qsprintf($conn, 'ORDER BY id DESC'); } } protected function buildLimitClause(AphrontDatabaseConnection $conn) { if ($this->limit) { return qsprintf($conn, 'LIMIT %d', $this->limit); } else { return qsprintf($conn, ''); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/query/PhabricatorWorkerTriggerQuery.php
src/infrastructure/daemon/workers/query/PhabricatorWorkerTriggerQuery.php
<?php final class PhabricatorWorkerTriggerQuery extends PhabricatorPolicyAwareQuery { // NOTE: This is a PolicyAware query so it can work with other infrastructure // like handles; triggers themselves are low-level and do not have // meaningful policies. const ORDER_ID = 'id'; const ORDER_EXECUTION = 'execution'; const ORDER_VERSION = 'version'; private $ids; private $phids; private $versionMin; private $versionMax; private $nextEpochMin; private $nextEpochMax; private $needEvents; private $order = self::ORDER_ID; public function getQueryApplicationClass() { return null; } public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withPHIDs(array $phids) { $this->phids = $phids; return $this; } public function withVersionBetween($min, $max) { $this->versionMin = $min; $this->versionMax = $max; return $this; } public function withNextEventBetween($min, $max) { $this->nextEpochMin = $min; $this->nextEpochMax = $max; return $this; } public function needEvents($need_events) { $this->needEvents = $need_events; return $this; } /** * Set the result order. * * Note that using `ORDER_EXECUTION` will also filter results to include only * triggers which have been scheduled to execute. You should not use this * ordering when querying for specific triggers, e.g. by ID or PHID. * * @param const Result order. * @return this */ public function setOrder($order) { $this->order = $order; return $this; } protected function nextPage(array $page) { // NOTE: We don't implement paging because we don't currently ever need // it and paging ORDER_EXECUTION is a hassle. // (Before T13266, we raised an exception here, but since "nextPage()" is // now called even if we don't page we can't do that anymore. Just do // nothing instead.) return null; } protected function loadPage() { $task_table = new PhabricatorWorkerTrigger(); $conn_r = $task_table->establishConnection('r'); $rows = queryfx_all( $conn_r, 'SELECT t.* FROM %T t %Q %Q %Q %Q', $task_table->getTableName(), $this->buildJoinClause($conn_r), $this->buildWhereClause($conn_r), $this->buildOrderClause($conn_r), $this->buildLimitClause($conn_r)); $triggers = $task_table->loadAllFromArray($rows); if ($triggers) { if ($this->needEvents) { $ids = mpull($triggers, 'getID'); $events = id(new PhabricatorWorkerTriggerEvent())->loadAllWhere( 'triggerID IN (%Ld)', $ids); $events = mpull($events, null, 'getTriggerID'); foreach ($triggers as $key => $trigger) { $event = idx($events, $trigger->getID()); $trigger->attachEvent($event); } } foreach ($triggers as $key => $trigger) { $clock_class = $trigger->getClockClass(); if (!is_subclass_of($clock_class, 'PhabricatorTriggerClock')) { unset($triggers[$key]); continue; } try { $argv = array($trigger->getClockProperties()); $clock = newv($clock_class, $argv); } catch (Exception $ex) { unset($triggers[$key]); continue; } $trigger->attachClock($clock); } foreach ($triggers as $key => $trigger) { $action_class = $trigger->getActionClass(); if (!is_subclass_of($action_class, 'PhabricatorTriggerAction')) { unset($triggers[$key]); continue; } try { $argv = array($trigger->getActionProperties()); $action = newv($action_class, $argv); } catch (Exception $ex) { unset($triggers[$key]); continue; } $trigger->attachAction($action); } } return $triggers; } protected function buildJoinClause(AphrontDatabaseConnection $conn) { $joins = array(); if (($this->nextEpochMin !== null) || ($this->nextEpochMax !== null) || ($this->order == self::ORDER_EXECUTION)) { $joins[] = qsprintf( $conn, 'JOIN %T e ON e.triggerID = t.id', id(new PhabricatorWorkerTriggerEvent())->getTableName()); } if ($joins) { return qsprintf($conn, '%LJ', $joins); } else { return qsprintf($conn, ''); } } protected function buildWhereClause(AphrontDatabaseConnection $conn) { $where = array(); if ($this->ids !== null) { $where[] = qsprintf( $conn, 't.id IN (%Ld)', $this->ids); } if ($this->phids !== null) { $where[] = qsprintf( $conn, 't.phid IN (%Ls)', $this->phids); } if ($this->versionMin !== null) { $where[] = qsprintf( $conn, 't.triggerVersion >= %d', $this->versionMin); } if ($this->versionMax !== null) { $where[] = qsprintf( $conn, 't.triggerVersion <= %d', $this->versionMax); } if ($this->nextEpochMin !== null) { $where[] = qsprintf( $conn, 'e.nextEventEpoch >= %d', $this->nextEpochMin); } if ($this->nextEpochMax !== null) { $where[] = qsprintf( $conn, 'e.nextEventEpoch <= %d', $this->nextEpochMax); } return $this->formatWhereClause($conn, $where); } private function buildOrderClause(AphrontDatabaseConnection $conn_r) { switch ($this->order) { case self::ORDER_ID: return qsprintf( $conn_r, 'ORDER BY id DESC'); case self::ORDER_EXECUTION: return qsprintf( $conn_r, 'ORDER BY e.nextEventEpoch ASC, e.id ASC'); case self::ORDER_VERSION: return qsprintf( $conn_r, 'ORDER BY t.triggerVersion ASC'); default: throw new Exception( pht( 'Unsupported order "%s".', $this->order)); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/query/PhabricatorWorkerLeaseQuery.php
src/infrastructure/daemon/workers/query/PhabricatorWorkerLeaseQuery.php
<?php /** * Select and lease tasks from the worker task queue. */ final class PhabricatorWorkerLeaseQuery extends PhabricatorQuery { const PHASE_LEASED = 'leased'; const PHASE_UNLEASED = 'unleased'; const PHASE_EXPIRED = 'expired'; private $ids; private $objectPHIDs; private $limit; private $skipLease; private $leased = false; public static function getDefaultWaitBeforeRetry() { return phutil_units('5 minutes in seconds'); } public static function getDefaultLeaseDuration() { return phutil_units('2 hours in seconds'); } /** * Set this flag to select tasks from the top of the queue without leasing * them. * * This can be used to show which tasks are coming up next without altering * the queue's behavior. * * @param bool True to skip the lease acquisition step. */ public function setSkipLease($skip) { $this->skipLease = $skip; return $this; } public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withObjectPHIDs(array $phids) { $this->objectPHIDs = $phids; return $this; } /** * Select only leased tasks, only unleased tasks, or both types of task. * * By default, queries select only unleased tasks (equivalent to passing * `false` to this method). You can pass `true` to select only leased tasks, * or `null` to ignore the lease status of tasks. * * If your result set potentially includes leased tasks, you must disable * leasing using @{method:setSkipLease}. These options are intended for use * when displaying task status information. * * @param mixed `true` to select only leased tasks, `false` to select only * unleased tasks (default), or `null` to select both. * @return this */ public function withLeasedTasks($leased) { $this->leased = $leased; return $this; } public function setLimit($limit) { $this->limit = $limit; return $this; } public function execute() { if (!$this->limit) { throw new Exception( pht('You must %s when leasing tasks.', 'setLimit()')); } if ($this->leased !== false) { if (!$this->skipLease) { throw new Exception( pht( 'If you potentially select leased tasks using %s, '. 'you MUST disable lease acquisition by calling %s.', 'withLeasedTasks()', 'setSkipLease()')); } } $task_table = new PhabricatorWorkerActiveTask(); $taskdata_table = new PhabricatorWorkerTaskData(); $lease_ownership_name = $this->getLeaseOwnershipName(); $conn_w = $task_table->establishConnection('w'); // Try to satisfy the request from new, unleased tasks first. If we don't // find enough tasks, try tasks with expired leases (i.e., tasks which have // previously failed). // If we're selecting leased tasks, look for them first. $phases = array(); if ($this->leased !== false) { $phases[] = self::PHASE_LEASED; } if ($this->leased !== true) { $phases[] = self::PHASE_UNLEASED; $phases[] = self::PHASE_EXPIRED; } $limit = $this->limit; $leased = 0; $task_ids = array(); foreach ($phases as $phase) { // NOTE: If we issue `UPDATE ... WHERE ... ORDER BY id ASC`, the query // goes very, very slowly. The `ORDER BY` triggers this, although we get // the same apparent results without it. Without the ORDER BY, binary // read slaves complain that the query isn't repeatable. To avoid both // problems, do a SELECT and then an UPDATE. $rows = queryfx_all( $conn_w, 'SELECT id, leaseOwner FROM %T %Q %Q %Q', $task_table->getTableName(), $this->buildCustomWhereClause($conn_w, $phase), $this->buildOrderClause($conn_w, $phase), $this->buildLimitClause($conn_w, $limit - $leased)); // NOTE: Sometimes, we'll race with another worker and they'll grab // this task before we do. We could reduce how often this happens by // selecting more tasks than we need, then shuffling them and trying // to lock only the number we're actually after. However, the amount // of time workers spend here should be very small relative to their // total runtime, so keep it simple for the moment. if ($rows) { if ($this->skipLease) { $leased += count($rows); $task_ids += array_fuse(ipull($rows, 'id')); } else { queryfx( $conn_w, 'UPDATE %T task SET leaseOwner = %s, leaseExpires = UNIX_TIMESTAMP() + %d %Q', $task_table->getTableName(), $lease_ownership_name, self::getDefaultLeaseDuration(), $this->buildUpdateWhereClause($conn_w, $phase, $rows)); $leased += $conn_w->getAffectedRows(); } if ($leased == $limit) { break; } } } if (!$leased) { return array(); } if ($this->skipLease) { $selection_condition = qsprintf( $conn_w, 'task.id IN (%Ld)', $task_ids); } else { $selection_condition = qsprintf( $conn_w, 'task.leaseOwner = %s AND leaseExpires > UNIX_TIMESTAMP()', $lease_ownership_name); } $data = queryfx_all( $conn_w, 'SELECT task.*, taskdata.data _taskData, UNIX_TIMESTAMP() _serverTime FROM %T task LEFT JOIN %T taskdata ON taskdata.id = task.dataID WHERE %Q %Q %Q', $task_table->getTableName(), $taskdata_table->getTableName(), $selection_condition, $this->buildOrderClause($conn_w, $phase), $this->buildLimitClause($conn_w, $limit)); $tasks = $task_table->loadAllFromArray($data); $tasks = mpull($tasks, null, 'getID'); foreach ($data as $row) { $tasks[$row['id']]->setServerTime($row['_serverTime']); if ($row['_taskData']) { $task_data = json_decode($row['_taskData'], true); } else { $task_data = null; } $tasks[$row['id']]->setData($task_data); } if ($this->skipLease) { // Reorder rows into the original phase order if this is a status query. $tasks = array_select_keys($tasks, $task_ids); } return $tasks; } protected function buildCustomWhereClause( AphrontDatabaseConnection $conn, $phase) { $where = array(); switch ($phase) { case self::PHASE_LEASED: $where[] = qsprintf( $conn, 'leaseOwner IS NOT NULL'); $where[] = qsprintf( $conn, 'leaseExpires >= UNIX_TIMESTAMP()'); break; case self::PHASE_UNLEASED: $where[] = qsprintf( $conn, 'leaseOwner IS NULL'); break; case self::PHASE_EXPIRED: $where[] = qsprintf( $conn, 'leaseExpires < UNIX_TIMESTAMP()'); break; default: throw new Exception(pht("Unknown phase '%s'!", $phase)); } if ($this->ids !== null) { $where[] = qsprintf($conn, 'id IN (%Ld)', $this->ids); } if ($this->objectPHIDs !== null) { $where[] = qsprintf($conn, 'objectPHID IN (%Ls)', $this->objectPHIDs); } return $this->formatWhereClause($conn, $where); } private function buildUpdateWhereClause( AphrontDatabaseConnection $conn, $phase, array $rows) { $where = array(); // NOTE: This is basically working around the MySQL behavior that // `IN (NULL)` doesn't match NULL. switch ($phase) { case self::PHASE_LEASED: throw new Exception( pht( 'Trying to lease tasks selected in the leased phase! This is '. 'intended to be impossible.')); case self::PHASE_UNLEASED: $where[] = qsprintf($conn, 'leaseOwner IS NULL'); $where[] = qsprintf($conn, 'id IN (%Ld)', ipull($rows, 'id')); break; case self::PHASE_EXPIRED: $in = array(); foreach ($rows as $row) { $in[] = qsprintf( $conn, '(id = %d AND leaseOwner = %s)', $row['id'], $row['leaseOwner']); } $where[] = qsprintf($conn, '%LO', $in); break; default: throw new Exception(pht('Unknown phase "%s"!', $phase)); } return $this->formatWhereClause($conn, $where); } private function buildOrderClause(AphrontDatabaseConnection $conn_w, $phase) { switch ($phase) { case self::PHASE_LEASED: // Ideally we'd probably order these by lease acquisition time, but // we don't have that handy and this is a good approximation. return qsprintf($conn_w, 'ORDER BY priority ASC, id ASC'); case self::PHASE_UNLEASED: // When selecting new tasks, we want to consume them in order of // increasing priority (and then FIFO). return qsprintf($conn_w, 'ORDER BY priority ASC, id ASC'); case self::PHASE_EXPIRED: // When selecting failed tasks, we want to consume them in roughly // FIFO order of their failures, which is not necessarily their original // queue order. // Particularly, this is important for tasks which use soft failures to // indicate that they are waiting on other tasks to complete: we need to // push them to the end of the queue after they fail, at least on // average, so we don't deadlock retrying the same blocked task over // and over again. return qsprintf($conn_w, 'ORDER BY leaseExpires ASC'); default: throw new Exception(pht('Unknown phase "%s"!', $phase)); } } private function buildLimitClause(AphrontDatabaseConnection $conn_w, $limit) { return qsprintf($conn_w, 'LIMIT %d', $limit); } private function getLeaseOwnershipName() { static $sequence = 0; // TODO: If the host name is very long, this can overflow the 64-character // column, so we pick just the first part of the host name. It might be // useful to just use a random hash as the identifier instead and put the // pid / time / host (which are somewhat useful diagnostically) elsewhere. // Likely, we could store a daemon ID instead and use that to identify // when and where code executed. See T6742. $host = php_uname('n'); $host = id(new PhutilUTF8StringTruncator()) ->setMaximumBytes(32) ->setTerminator('...') ->truncateString($host); $parts = array( getmypid(), time(), $host, ++$sequence, ); return implode(':', $parts); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/query/PhabricatorWorkerBulkJobTransactionQuery.php
src/infrastructure/daemon/workers/query/PhabricatorWorkerBulkJobTransactionQuery.php
<?php final class PhabricatorWorkerBulkJobTransactionQuery extends PhabricatorApplicationTransactionQuery { public function getTemplateApplicationTransaction() { return new PhabricatorWorkerBulkJobTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/bulk/PhabricatorWorkerBulkJobCreateWorker.php
src/infrastructure/daemon/workers/bulk/PhabricatorWorkerBulkJobCreateWorker.php
<?php final class PhabricatorWorkerBulkJobCreateWorker extends PhabricatorWorkerBulkJobWorker { protected function doWork() { $lock = $this->acquireJobLock(); $job = $this->loadJob(); $actor = $this->loadActor($job); $status = $job->getStatus(); switch ($status) { case PhabricatorWorkerBulkJob::STATUS_WAITING: // This is what we expect. Other statuses indicate some kind of race // is afoot. break; default: throw new PhabricatorWorkerPermanentFailureException( pht( 'Found unexpected job status ("%s").', $status)); } $tasks = $job->createTasks(); foreach ($tasks as $task) { $task->save(); } $this->updateJobStatus( $job, PhabricatorWorkerBulkJob::STATUS_RUNNING); $lock->unlock(); foreach ($tasks as $task) { PhabricatorWorker::scheduleTask( 'PhabricatorWorkerBulkJobTaskWorker', array( 'jobID' => $job->getID(), 'taskID' => $task->getID(), ), array( 'priority' => PhabricatorWorker::PRIORITY_BULK, )); } $this->updateJob($job); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/bulk/PhabricatorWorkerSingleBulkJobType.php
src/infrastructure/daemon/workers/bulk/PhabricatorWorkerSingleBulkJobType.php
<?php /** * An bulk job which can not be parallelized and executes only one task. */ abstract class PhabricatorWorkerSingleBulkJobType extends PhabricatorWorkerBulkJobType { public function getDescriptionForConfirm(PhabricatorWorkerBulkJob $job) { return null; } public function getJobSize(PhabricatorWorkerBulkJob $job) { return 1; } public function createTasks(PhabricatorWorkerBulkJob $job) { $tasks = array(); $tasks[] = PhabricatorWorkerBulkTask::initializeNewTask( $job, $job->getPHID()); return $tasks; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/bulk/PhabricatorWorkerBulkJobWorker.php
src/infrastructure/daemon/workers/bulk/PhabricatorWorkerBulkJobWorker.php
<?php abstract class PhabricatorWorkerBulkJobWorker extends PhabricatorWorker { final protected function acquireJobLock() { return PhabricatorGlobalLock::newLock('bulkjob.'.$this->getJobID()) ->lock(15); } final protected function acquireTaskLock() { return PhabricatorGlobalLock::newLock('bulktask.'.$this->getTaskID()) ->lock(15); } final protected function getJobID() { $data = $this->getTaskData(); $id = idx($data, 'jobID'); if (!$id) { throw new PhabricatorWorkerPermanentFailureException( pht('Worker has no job ID.')); } return $id; } final protected function getTaskID() { $data = $this->getTaskData(); $id = idx($data, 'taskID'); if (!$id) { throw new PhabricatorWorkerPermanentFailureException( pht('Worker has no task ID.')); } return $id; } final protected function loadJob() { $id = $this->getJobID(); $job = id(new PhabricatorWorkerBulkJobQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withIDs(array($id)) ->executeOne(); if (!$job) { throw new PhabricatorWorkerPermanentFailureException( pht('Worker has invalid job ID ("%s").', $id)); } return $job; } final protected function loadTask() { $id = $this->getTaskID(); $task = id(new PhabricatorWorkerBulkTask())->load($id); if (!$task) { throw new PhabricatorWorkerPermanentFailureException( pht('Worker has invalid task ID ("%s").', $id)); } return $task; } final protected function loadActor(PhabricatorWorkerBulkJob $job) { $actor_phid = $job->getAuthorPHID(); $actor = id(new PhabricatorPeopleQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs(array($actor_phid)) ->executeOne(); if (!$actor) { throw new PhabricatorWorkerPermanentFailureException( pht('Worker has invalid actor PHID ("%s").', $actor_phid)); } $can_edit = PhabricatorPolicyFilter::hasCapability( $actor, $job, PhabricatorPolicyCapability::CAN_EDIT); if (!$can_edit) { throw new PhabricatorWorkerPermanentFailureException( pht('Job actor does not have permission to edit job.')); } // Allow the worker to fill user caches inline; bulk jobs occasionally // need to access user preferences. $actor->setAllowInlineCacheGeneration(true); return $actor; } final protected function updateJob(PhabricatorWorkerBulkJob $job) { $has_work = $this->hasRemainingWork($job); if ($has_work) { return; } $lock = $this->acquireJobLock(); $job = $this->loadJob(); if ($job->getStatus() == PhabricatorWorkerBulkJob::STATUS_RUNNING) { if (!$this->hasRemainingWork($job)) { $this->updateJobStatus( $job, PhabricatorWorkerBulkJob::STATUS_COMPLETE); } } $lock->unlock(); } private function hasRemainingWork(PhabricatorWorkerBulkJob $job) { return (bool)queryfx_one( $job->establishConnection('r'), 'SELECT * FROM %T WHERE bulkJobPHID = %s AND status NOT IN (%Ls) LIMIT 1', id(new PhabricatorWorkerBulkTask())->getTableName(), $job->getPHID(), array( PhabricatorWorkerBulkTask::STATUS_DONE, PhabricatorWorkerBulkTask::STATUS_FAIL, )); } protected function updateJobStatus(PhabricatorWorkerBulkJob $job, $status) { $type_status = PhabricatorWorkerBulkJobTransaction::TYPE_STATUS; $xactions = array(); $xactions[] = id(new PhabricatorWorkerBulkJobTransaction()) ->setTransactionType($type_status) ->setNewValue($status); $daemon_source = $this->newContentSource(); $app_phid = id(new PhabricatorDaemonsApplication())->getPHID(); $editor = id(new PhabricatorWorkerBulkJobEditor()) ->setActor(PhabricatorUser::getOmnipotentUser()) ->setActingAsPHID($app_phid) ->setContentSource($daemon_source) ->setContinueOnMissingFields(true) ->applyTransactions($job, $xactions); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/bulk/PhabricatorWorkerBulkJobTaskWorker.php
src/infrastructure/daemon/workers/bulk/PhabricatorWorkerBulkJobTaskWorker.php
<?php final class PhabricatorWorkerBulkJobTaskWorker extends PhabricatorWorkerBulkJobWorker { protected function doWork() { $lock = $this->acquireTaskLock(); $task = $this->loadTask(); $status = $task->getStatus(); switch ($task->getStatus()) { case PhabricatorWorkerBulkTask::STATUS_WAITING: // This is what we expect. break; default: throw new PhabricatorWorkerPermanentFailureException( pht( 'Found unexpected task status ("%s").', $status)); } $task ->setStatus(PhabricatorWorkerBulkTask::STATUS_RUNNING) ->save(); $lock->unlock(); $job = $this->loadJob(); $actor = $this->loadActor($job); try { $job->runTask($actor, $task); $status = PhabricatorWorkerBulkTask::STATUS_DONE; } catch (Exception $ex) { phlog($ex); $status = PhabricatorWorkerBulkTask::STATUS_FAIL; } $task ->setStatus($status) ->save(); $this->updateJob($job); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/bulk/PhabricatorWorkerBulkJobType.php
src/infrastructure/daemon/workers/bulk/PhabricatorWorkerBulkJobType.php
<?php abstract class PhabricatorWorkerBulkJobType extends Phobject { abstract public function getJobName(PhabricatorWorkerBulkJob $job); abstract public function getBulkJobTypeKey(); abstract public function getJobSize(PhabricatorWorkerBulkJob $job); abstract public function getDescriptionForConfirm( PhabricatorWorkerBulkJob $job); abstract public function createTasks(PhabricatorWorkerBulkJob $job); abstract public function runTask( PhabricatorUser $actor, PhabricatorWorkerBulkJob $job, PhabricatorWorkerBulkTask $task); public function getDoneURI(PhabricatorWorkerBulkJob $job) { return $job->getManageURI(); } final public static function getAllJobTypes() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getBulkJobTypeKey') ->execute(); } public function getCurtainActions( PhabricatorUser $viewer, PhabricatorWorkerBulkJob $job) { if ($job->isConfirming()) { $continue_uri = $job->getMonitorURI(); } else { $continue_uri = $job->getDoneURI(); } $continue = id(new PhabricatorActionView()) ->setHref($continue_uri) ->setIcon('fa-arrow-circle-o-right') ->setName(pht('Continue')); return array( $continue, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/action/PhabricatorLogTriggerAction.php
src/infrastructure/daemon/workers/action/PhabricatorLogTriggerAction.php
<?php /** * Trivial action which logs a message. * * This action is primarily useful for testing triggers. */ final class PhabricatorLogTriggerAction extends PhabricatorTriggerAction { public function validateProperties(array $properties) { PhutilTypeSpec::checkMap( $properties, array( 'message' => 'string', )); } public function execute($last_epoch, $this_epoch) { $message = pht( '(%s -> %s @ %s) %s', $last_epoch ? date('Y-m-d g:i:s A', $last_epoch) : 'null', date('Y-m-d g:i:s A', $this_epoch), date('Y-m-d g:i:s A', PhabricatorTime::getNow()), $this->getProperty('message')); phlog($message); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/action/PhabricatorTriggerAction.php
src/infrastructure/daemon/workers/action/PhabricatorTriggerAction.php
<?php /** * A trigger action reacts to a scheduled event. * * Almost all events should use a @{class:PhabricatorScheduleTaskTriggerAction}. * Avoid introducing new actions without strong justification. See that class * for discussion of concerns. */ abstract class PhabricatorTriggerAction extends Phobject { private $properties; public function __construct(array $properties) { $this->validateProperties($properties); $this->properties = $properties; } public function getProperties() { return $this->properties; } public function getProperty($key, $default = null) { return idx($this->properties, $key, $default); } /** * Validate action configuration. * * @param map<string, wild> Map of action properties. * @return void */ abstract public function validateProperties(array $properties); /** * Execute this action. * * IMPORTANT: Trigger actions must execute quickly! * * In most cases, trigger actions should queue a worker task and then exit. * The actual trigger execution occurs in a locked section in the trigger * daemon and blocks all other triggers. By queueing a task instead of * performing processing directly, triggers can execute more involved actions * without blocking other triggers. * * Almost all events should use @{class:PhabricatorScheduleTaskTriggerAction} * to do this, ensuring that they execute quickly. * * An action may trigger a long time after it is scheduled. For example, * a meeting reminder may be scheduled at 9:45 AM, but the action may not * execute until later (for example, because the server was down for * maintenance). You can detect cases like this by comparing `$this_epoch` * (which holds the time the event was scheduled to execute at) to * `PhabricatorTime::getNow()` (which returns the current time). In the * case of a meeting reminder, you may want to ignore the action if it * executes too late to be useful (for example, after a meeting is over). * * Because actions should normally queue a task and there may be a second, * arbitrarily long delay between trigger execution and task execution, it * may be simplest to pass the trigger time to the task and then make the * decision to discard the action there. * * @param int|null Last time the event occurred, or null if it has never * triggered before. * @param int The scheduled time for the current action. This may be * significantly different from the current time. * @return void */ abstract public function execute($last_epoch, $this_epoch); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/action/PhabricatorScheduleTaskTriggerAction.php
src/infrastructure/daemon/workers/action/PhabricatorScheduleTaskTriggerAction.php
<?php /** * Trigger action which queues a task. * * Most triggers should take this action: triggers need to execute as quickly * as possible, and should generally queue tasks instead of doing any real * work. * * In some cases, triggers could execute more quickly by examining the * scheduled action time and comparing it to the current time, then exiting * early if the trigger is executing too far away from real time (for example, * it might not make sense to send a meeting reminder after a meeting already * happened). * * However, in most cases the task needs to have this logic anyway (because * there may be another arbitrarily long delay between when this code executes * and when the task executes), and the cost of queueing a task is very small, * and situations where triggers are executing far away from real time should * be rare (major downtime or serious problems with the pipeline). * * The properties of this action map to the parameters of * @{method:PhabricatorWorker::scheduleTask}. */ final class PhabricatorScheduleTaskTriggerAction extends PhabricatorTriggerAction { public function validateProperties(array $properties) { PhutilTypeSpec::checkMap( $properties, array( 'class' => 'string', 'data' => 'map<string, wild>', 'options' => 'map<string, wild>', )); } public function execute($last_epoch, $this_epoch) { PhabricatorWorker::scheduleTask( $this->getProperty('class'), $this->getProperty('data') + array( 'trigger.last-epoch' => $last_epoch, 'trigger.this-epoch' => $this_epoch, ), $this->getProperty('options')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/editor/PhabricatorWorkerBulkJobEditor.php
src/infrastructure/daemon/workers/editor/PhabricatorWorkerBulkJobEditor.php
<?php final class PhabricatorWorkerBulkJobEditor extends PhabricatorApplicationTransactionEditor { public function getEditorApplicationClass() { return 'PhabricatorDaemonsApplication'; } public function getEditorObjectsDescription() { return pht('Bulk Jobs'); } public function getTransactionTypes() { $types = parent::getTransactionTypes(); $types[] = PhabricatorWorkerBulkJobTransaction::TYPE_STATUS; $types[] = PhabricatorTransactions::TYPE_EDGE; return $types; } protected function getCustomTransactionOldValue( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorWorkerBulkJobTransaction::TYPE_STATUS: return $object->getStatus(); } } protected function getCustomTransactionNewValue( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorWorkerBulkJobTransaction::TYPE_STATUS: return $xaction->getNewValue(); } } protected function applyCustomInternalTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { $type = $xaction->getTransactionType(); $new = $xaction->getNewValue(); switch ($type) { case PhabricatorWorkerBulkJobTransaction::TYPE_STATUS: $object->setStatus($xaction->getNewValue()); return; } return parent::applyCustomInternalTransaction($object, $xaction); } protected function applyCustomExternalTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { $type = $xaction->getTransactionType(); $new = $xaction->getNewValue(); switch ($type) { case PhabricatorWorkerBulkJobTransaction::TYPE_STATUS: switch ($new) { case PhabricatorWorkerBulkJob::STATUS_WAITING: PhabricatorWorker::scheduleTask( 'PhabricatorWorkerBulkJobCreateWorker', array( 'jobID' => $object->getID(), ), array( 'priority' => PhabricatorWorker::PRIORITY_BULK, )); break; } return; } return parent::applyCustomExternalTransaction($object, $xaction); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false