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/applications/drydock/storage/DrydockBlueprint.php | src/applications/drydock/storage/DrydockBlueprint.php | <?php
/**
* @task resource Allocating Resources
* @task lease Acquiring Leases
*/
final class DrydockBlueprint extends DrydockDAO
implements
PhabricatorApplicationTransactionInterface,
PhabricatorPolicyInterface,
PhabricatorCustomFieldInterface,
PhabricatorNgramsInterface,
PhabricatorProjectInterface,
PhabricatorConduitResultInterface {
protected $className;
protected $blueprintName;
protected $viewPolicy;
protected $editPolicy;
protected $details = array();
protected $isDisabled;
private $implementation = self::ATTACHABLE;
private $customFields = self::ATTACHABLE;
private $fields = null;
public static function initializeNewBlueprint(PhabricatorUser $actor) {
$app = id(new PhabricatorApplicationQuery())
->setViewer($actor)
->withClasses(array('PhabricatorDrydockApplication'))
->executeOne();
$view_policy = $app->getPolicy(
DrydockDefaultViewCapability::CAPABILITY);
$edit_policy = $app->getPolicy(
DrydockDefaultEditCapability::CAPABILITY);
return id(new DrydockBlueprint())
->setViewPolicy($view_policy)
->setEditPolicy($edit_policy)
->setBlueprintName('')
->setIsDisabled(0);
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_SERIALIZATION => array(
'details' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'className' => 'text255',
'blueprintName' => 'sort255',
'isDisabled' => 'bool',
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
DrydockBlueprintPHIDType::TYPECONST);
}
public function getImplementation() {
return $this->assertAttached($this->implementation);
}
public function attachImplementation(DrydockBlueprintImplementation $impl) {
$this->implementation = $impl;
return $this;
}
public function hasImplementation() {
return ($this->implementation !== self::ATTACHABLE);
}
public function getDetail($key, $default = null) {
return idx($this->details, $key, $default);
}
public function setDetail($key, $value) {
$this->details[$key] = $value;
return $this;
}
public function getFieldValue($key) {
$key = "std:drydock:core:{$key}";
$fields = $this->loadCustomFields();
$field = idx($fields, $key);
if (!$field) {
throw new Exception(
pht(
'Unknown blueprint field "%s"!',
$key));
}
return $field->getBlueprintFieldValue();
}
private function loadCustomFields() {
if ($this->fields === null) {
$field_list = PhabricatorCustomField::getObjectFields(
$this,
PhabricatorCustomField::ROLE_VIEW);
$field_list->readFieldsFromStorage($this);
$this->fields = $field_list->getFields();
}
return $this->fields;
}
public function logEvent($type, array $data = array()) {
$log = id(new DrydockLog())
->setEpoch(PhabricatorTime::getNow())
->setType($type)
->setData($data);
$log->setBlueprintPHID($this->getPHID());
return $log->save();
}
public function getURI() {
$id = $this->getID();
return "/drydock/blueprint/{$id}/";
}
/* -( Allocating Resources )----------------------------------------------- */
/**
* @task resource
*/
public function canEverAllocateResourceForLease(DrydockLease $lease) {
return $this->getImplementation()->canEverAllocateResourceForLease(
$this,
$lease);
}
/**
* @task resource
*/
public function canAllocateResourceForLease(DrydockLease $lease) {
return $this->getImplementation()->canAllocateResourceForLease(
$this,
$lease);
}
/**
* @task resource
*/
public function allocateResource(DrydockLease $lease) {
return $this->getImplementation()->allocateResource(
$this,
$lease);
}
/**
* @task resource
*/
public function activateResource(DrydockResource $resource) {
return $this->getImplementation()->activateResource(
$this,
$resource);
}
/**
* @task resource
*/
public function destroyResource(DrydockResource $resource) {
$this->getImplementation()->destroyResource(
$this,
$resource);
return $this;
}
/**
* @task resource
*/
public function getResourceName(DrydockResource $resource) {
return $this->getImplementation()->getResourceName(
$this,
$resource);
}
/* -( Acquiring Leases )--------------------------------------------------- */
/**
* @task lease
*/
public function canAcquireLeaseOnResource(
DrydockResource $resource,
DrydockLease $lease) {
return $this->getImplementation()->canAcquireLeaseOnResource(
$this,
$resource,
$lease);
}
/**
* @task lease
*/
public function acquireLease(
DrydockResource $resource,
DrydockLease $lease) {
return $this->getImplementation()->acquireLease(
$this,
$resource,
$lease);
}
/**
* @task lease
*/
public function activateLease(
DrydockResource $resource,
DrydockLease $lease) {
return $this->getImplementation()->activateLease(
$this,
$resource,
$lease);
}
/**
* @task lease
*/
public function didReleaseLease(
DrydockResource $resource,
DrydockLease $lease) {
$this->getImplementation()->didReleaseLease(
$this,
$resource,
$lease);
return $this;
}
/**
* @task lease
*/
public function destroyLease(
DrydockResource $resource,
DrydockLease $lease) {
$this->getImplementation()->destroyLease(
$this,
$resource,
$lease);
return $this;
}
public function getInterface(
DrydockResource $resource,
DrydockLease $lease,
$type) {
$interface = $this->getImplementation()
->getInterface($this, $resource, $lease, $type);
if (!$interface) {
throw new Exception(
pht(
'Unable to build resource interface of type "%s".',
$type));
}
return $interface;
}
public function shouldAllocateSupplementalResource(
DrydockResource $resource,
DrydockLease $lease) {
return $this->getImplementation()->shouldAllocateSupplementalResource(
$this,
$resource,
$lease);
}
/* -( PhabricatorApplicationTransactionInterface )------------------------- */
public function getApplicationTransactionEditor() {
return new DrydockBlueprintEditor();
}
public function getApplicationTransactionTemplate() {
return new DrydockBlueprintTransaction();
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
);
}
public function getPolicy($capability) {
switch ($capability) {
case PhabricatorPolicyCapability::CAN_VIEW:
return $this->getViewPolicy();
case PhabricatorPolicyCapability::CAN_EDIT:
return $this->getEditPolicy();
}
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return false;
}
/* -( PhabricatorCustomFieldInterface )------------------------------------ */
public function getCustomFieldSpecificationForRole($role) {
return array();
}
public function getCustomFieldBaseClass() {
return 'DrydockBlueprintCustomField';
}
public function getCustomFields() {
return $this->assertAttached($this->customFields);
}
public function attachCustomFields(PhabricatorCustomFieldAttachment $fields) {
$this->customFields = $fields;
return $this;
}
/* -( PhabricatorNgramsInterface )----------------------------------------- */
public function newNgrams() {
return array(
id(new DrydockBlueprintNameNgrams())
->setValue($this->getBlueprintName()),
);
}
/* -( PhabricatorConduitResultInterface )---------------------------------- */
public function getFieldSpecificationsForConduit() {
return array(
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('name')
->setType('string')
->setDescription(pht('The name of this blueprint.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('type')
->setType('string')
->setDescription(pht('The type of resource this blueprint provides.')),
);
}
public function getFieldValuesForConduit() {
return array(
'name' => $this->getBlueprintName(),
'type' => $this->getImplementation()->getType(),
);
}
public function getConduitSearchAttachments() {
return array(
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/storage/DrydockAuthorization.php | src/applications/drydock/storage/DrydockAuthorization.php | <?php
final class DrydockAuthorization extends DrydockDAO
implements
PhabricatorPolicyInterface,
PhabricatorConduitResultInterface {
const OBJECTAUTH_ACTIVE = 'active';
const OBJECTAUTH_INACTIVE = 'inactive';
const BLUEPRINTAUTH_REQUESTED = 'requested';
const BLUEPRINTAUTH_AUTHORIZED = 'authorized';
const BLUEPRINTAUTH_DECLINED = 'declined';
protected $blueprintPHID;
protected $blueprintAuthorizationState;
protected $objectPHID;
protected $objectAuthorizationState;
private $blueprint = self::ATTACHABLE;
private $object = self::ATTACHABLE;
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_COLUMN_SCHEMA => array(
'blueprintAuthorizationState' => 'text32',
'objectAuthorizationState' => 'text32',
),
self::CONFIG_KEY_SCHEMA => array(
'key_unique' => array(
'columns' => array('objectPHID', 'blueprintPHID'),
'unique' => true,
),
'key_blueprint' => array(
'columns' => array('blueprintPHID', 'blueprintAuthorizationState'),
),
'key_object' => array(
'columns' => array('objectPHID', 'objectAuthorizationState'),
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
DrydockAuthorizationPHIDType::TYPECONST);
}
public function attachBlueprint(DrydockBlueprint $blueprint) {
$this->blueprint = $blueprint;
return $this;
}
public function getBlueprint() {
return $this->assertAttached($this->blueprint);
}
public function attachObject($object) {
$this->object = $object;
return $this;
}
public function getObject() {
return $this->assertAttached($this->object);
}
public static function getBlueprintStateIcon($state) {
$map = array(
self::BLUEPRINTAUTH_REQUESTED => 'fa-exclamation-circle pink',
self::BLUEPRINTAUTH_AUTHORIZED => 'fa-check-circle green',
self::BLUEPRINTAUTH_DECLINED => 'fa-times red',
);
return idx($map, $state, null);
}
public static function getBlueprintStateName($state) {
$map = array(
self::BLUEPRINTAUTH_REQUESTED => pht('Requested'),
self::BLUEPRINTAUTH_AUTHORIZED => pht('Authorized'),
self::BLUEPRINTAUTH_DECLINED => pht('Declined'),
);
return idx($map, $state, pht('<Unknown: %s>', $state));
}
public static function getObjectStateName($state) {
$map = array(
self::OBJECTAUTH_ACTIVE => pht('Active'),
self::OBJECTAUTH_INACTIVE => pht('Inactive'),
);
return idx($map, $state, pht('<Unknown: %s>', $state));
}
public function isAuthorized() {
$state = $this->getBlueprintAuthorizationState();
return ($state == self::BLUEPRINTAUTH_AUTHORIZED);
}
/**
* Apply external authorization effects after a user changes the value of a
* blueprint selector control an object.
*
* @param PhabricatorUser User applying the change.
* @param phid Object PHID change is being applied to.
* @param list<phid> Old blueprint PHIDs.
* @param list<phid> New blueprint PHIDs.
* @return void
*/
public static function applyAuthorizationChanges(
PhabricatorUser $viewer,
$object_phid,
array $old,
array $new) {
$old_phids = array_fuse($old);
$new_phids = array_fuse($new);
$rem_phids = array_diff_key($old_phids, $new_phids);
$add_phids = array_diff_key($new_phids, $old_phids);
$altered_phids = $rem_phids + $add_phids;
if (!$altered_phids) {
return;
}
$authorizations = id(new DrydockAuthorizationQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withObjectPHIDs(array($object_phid))
->withBlueprintPHIDs($altered_phids)
->execute();
$authorizations = mpull($authorizations, null, 'getBlueprintPHID');
$state_active = self::OBJECTAUTH_ACTIVE;
$state_inactive = self::OBJECTAUTH_INACTIVE;
$state_requested = self::BLUEPRINTAUTH_REQUESTED;
// Disable the object side of the authorization for any existing
// authorizations.
foreach ($rem_phids as $rem_phid) {
$authorization = idx($authorizations, $rem_phid);
if (!$authorization) {
continue;
}
$authorization
->setObjectAuthorizationState($state_inactive)
->save();
}
// For new authorizations, either add them or reactivate them depending
// on the current state.
foreach ($add_phids as $add_phid) {
$needs_update = false;
$authorization = idx($authorizations, $add_phid);
if (!$authorization) {
$authorization = id(new DrydockAuthorization())
->setObjectPHID($object_phid)
->setObjectAuthorizationState($state_active)
->setBlueprintPHID($add_phid)
->setBlueprintAuthorizationState($state_requested);
$needs_update = true;
} else {
$current_state = $authorization->getObjectAuthorizationState();
if ($current_state != $state_active) {
$authorization->setObjectAuthorizationState($state_active);
$needs_update = true;
}
}
if ($needs_update) {
$authorization->save();
}
}
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
);
}
public function getPolicy($capability) {
return $this->getBlueprint()->getPolicy($capability);
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return $this->getBlueprint()->hasAutomaticCapability($capability, $viewer);
}
public function describeAutomaticCapability($capability) {
return pht(
'An authorization inherits the policies of the blueprint it '.
'authorizes access to.');
}
/* -( PhabricatorConduitResultInterface )---------------------------------- */
public function getFieldSpecificationsForConduit() {
return array(
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('blueprintPHID')
->setType('phid')
->setDescription(pht(
'PHID of the blueprint this request was made for.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('blueprintAuthorizationState')
->setType('map<string, wild>')
->setDescription(pht('Authorization state of this request.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('objectPHID')
->setType('phid')
->setDescription(pht(
'PHID of the object which requested authorization.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('objectAuthorizationState')
->setType('map<string, wild>')
->setDescription(pht('Authorization state of the requesting object.')),
);
}
public function getFieldValuesForConduit() {
$blueprint_state = $this->getBlueprintAuthorizationState();
$object_state = $this->getObjectAuthorizationState();
return array(
'blueprintPHID' => $this->getBlueprintPHID(),
'blueprintAuthorizationState' => array(
'value' => $blueprint_state,
'name' => self::getBlueprintStateName($blueprint_state),
),
'objectPHID' => $this->getObjectPHID(),
'objectAuthorizationState' => array(
'value' => $object_state,
'name' => self::getObjectStateName($object_state),
),
);
}
public function getConduitSearchAttachments() {
return array(
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/management/DrydockManagementReleaseLeaseWorkflow.php | src/applications/drydock/management/DrydockManagementReleaseLeaseWorkflow.php | <?php
final class DrydockManagementReleaseLeaseWorkflow
extends DrydockManagementWorkflow {
protected function didConstruct() {
$this
->setName('release-lease')
->setSynopsis(pht('Release a lease.'))
->setArguments(
array(
array(
'name' => 'id',
'param' => 'id',
'repeat' => true,
'help' => pht('Lease ID to release.'),
),
array(
'name' => 'all',
'help' => pht('Release all leases. Dangerous!'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$is_all = $args->getArg('all');
$ids = $args->getArg('id');
if (!$ids && !$is_all) {
throw new PhutilArgumentUsageException(
pht(
'Select which leases you want to release. See "--help" for '.
'guidance.'));
}
$viewer = $this->getViewer();
$statuses = $this->getReleaseableLeaseStatuses();
$query = id(new DrydockLeaseQuery())
->setViewer($viewer)
->withStatuses(mpull($statuses, 'getKey'));
if ($ids) {
$query->withIDs($ids);
}
$leases = $query->execute();
if ($ids) {
$id_map = mpull($leases, null, 'getID');
foreach ($ids as $id) {
$lease = idx($id_map, $id);
if (!$lease) {
throw new PhutilArgumentUsageException(
pht('Lease "%s" does not exist.', $id));
}
}
$leases = array_select_keys($id_map, $ids);
}
if (!$leases) {
echo tsprintf(
"%s\n",
pht('No leases selected for release.'));
return 0;
}
$drydock_phid = id(new PhabricatorDrydockApplication())->getPHID();
PhabricatorWorker::setRunAllTasksInProcess(true);
foreach ($leases as $lease) {
if (!$lease->canRelease()) {
echo tsprintf(
"%s\n",
pht(
'Lease "%s" is not releasable.',
$lease->getDisplayName()));
continue;
}
$command = DrydockCommand::initializeNewCommand($viewer)
->setTargetPHID($lease->getPHID())
->setAuthorPHID($drydock_phid)
->setCommand(DrydockCommand::COMMAND_RELEASE)
->save();
$lease->scheduleUpdate();
echo tsprintf(
"%s\n",
pht(
'Scheduled release of lease "%s".',
$lease->getDisplayName()));
}
}
private function getReleaseableLeaseStatuses() {
$statuses = DrydockLeaseStatus::getAllStatuses();
foreach ($statuses as $key => $status) {
$statuses[$key] = DrydockLeaseStatus::newStatusObject($status);
}
foreach ($statuses as $key => $status) {
if (!$status->canRelease()) {
unset($statuses[$key]);
}
}
return $statuses;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/management/DrydockManagementLeaseWorkflow.php | src/applications/drydock/management/DrydockManagementLeaseWorkflow.php | <?php
final class DrydockManagementLeaseWorkflow
extends DrydockManagementWorkflow {
protected function didConstruct() {
$this
->setName('lease')
->setSynopsis(pht('Lease a resource.'))
->setArguments(
array(
array(
'name' => 'type',
'param' => 'resource_type',
'help' => pht('Resource type.'),
),
array(
'name' => 'until',
'param' => 'time',
'help' => pht('Set lease expiration time.'),
),
array(
'name' => 'attributes',
'param' => 'file',
'help' => pht(
'JSON file with lease attributes. Use "-" to read attributes '.
'from stdin.'),
),
array(
'name' => 'count',
'param' => 'N',
'default' => 1,
'help' => pht('Lease a given number of identical resources.'),
),
array(
'name' => 'blueprint',
'param' => 'identifier',
'repeat' => true,
'help' => pht('Lease resources from a specific blueprint.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$resource_type = $args->getArg('type');
if (!phutil_nonempty_string($resource_type)) {
throw new PhutilArgumentUsageException(
pht(
'Specify a resource type with "--type".'));
}
$until = $args->getArg('until');
if (phutil_nonempty_string($until)) {
$until = strtotime($until);
if ($until <= 0) {
throw new PhutilArgumentUsageException(
pht(
'Unable to parse argument to "--until".'));
}
}
$count = $args->getArgAsInteger('count');
if ($count < 1) {
throw new PhutilArgumentUsageException(
pht(
'Value provided to "--count" must be a nonzero, positive '.
'number.'));
}
$attributes_file = $args->getArg('attributes');
if (phutil_nonempty_string($attributes_file)) {
if ($attributes_file == '-') {
echo tsprintf(
"%s\n",
pht('Reading JSON attributes from stdin...'));
$data = file_get_contents('php://stdin');
} else {
$data = Filesystem::readFile($attributes_file);
}
$attributes = phutil_json_decode($data);
} else {
$attributes = array();
}
$filter_identifiers = $args->getArg('blueprint');
if ($filter_identifiers) {
$filter_blueprints = $this->getBlueprintFilterMap($filter_identifiers);
} else {
$filter_blueprints = array();
}
$blueprint_phids = null;
$leases = array();
for ($idx = 0; $idx < $count; $idx++) {
$lease = id(new DrydockLease())
->setResourceType($resource_type);
$drydock_phid = id(new PhabricatorDrydockApplication())->getPHID();
$lease->setAuthorizingPHID($drydock_phid);
if ($attributes) {
$lease->setAttributes($attributes);
}
if ($blueprint_phids === null) {
$blueprint_phids = $this->newAllowedBlueprintPHIDs(
$lease,
$filter_blueprints);
}
$lease->setAllowedBlueprintPHIDs($blueprint_phids);
if ($until) {
$lease->setUntil($until);
}
// If something fatals or the user interrupts the process (for example,
// with "^C"), release the lease. We'll cancel this below, if the lease
// actually activates.
$lease->setReleaseOnDestruction(true);
$leases[] = $lease;
}
// TODO: This would probably be better handled with PhutilSignalRouter,
// but it currently doesn't route SIGINT. We're initializing it to setup
// SIGTERM handling and make eventual migration easier.
$router = PhutilSignalRouter::getRouter();
pcntl_signal(SIGINT, array($this, 'didReceiveInterrupt'));
$t_start = microtime(true);
echo tsprintf(
"%s\n\n",
pht('Leases queued for activation:'));
foreach ($leases as $lease) {
$lease->queueForActivation();
echo tsprintf(
" __%s__\n",
PhabricatorEnv::getProductionURI($lease->getURI()));
}
echo tsprintf(
"\n%s\n\n",
pht('Waiting for daemons to activate leases...'));
foreach ($leases as $lease) {
$this->waitUntilActive($lease);
}
// Now that we've survived activation and the lease is good, make it
// durable.
foreach ($leases as $lease) {
$lease->setReleaseOnDestruction(false);
}
$t_end = microtime(true);
echo tsprintf(
"\n%s\n\n",
pht(
'Activation complete. Leases are permanent until manually '.
'released with:'));
foreach ($leases as $lease) {
echo tsprintf(
" %s\n",
pht('$ ./bin/drydock release-lease --id %d', $lease->getID()));
}
echo tsprintf(
"\n%s\n",
pht(
'Leases activated in %sms.',
new PhutilNumber((int)(($t_end - $t_start) * 1000))));
return 0;
}
public function didReceiveInterrupt($signo) {
// Doing this makes us run destructors, particularly the "release on
// destruction" trigger on the lease.
exit(128 + $signo);
}
private function waitUntilActive(DrydockLease $lease) {
$viewer = $this->getViewer();
$log_cursor = 0;
$log_types = DrydockLogType::getAllLogTypes();
$is_active = false;
while (!$is_active) {
$lease->reload();
$pager = id(new AphrontCursorPagerView())
->setBeforeID($log_cursor);
// While we're waiting, show the user any logs which the daemons have
// generated to give them some clue about what's going on.
$logs = id(new DrydockLogQuery())
->setViewer($viewer)
->withLeasePHIDs(array($lease->getPHID()))
->executeWithCursorPager($pager);
if ($logs) {
$logs = mpull($logs, null, 'getID');
ksort($logs);
$log_cursor = last_key($logs);
}
foreach ($logs as $log) {
$type_key = $log->getType();
if (isset($log_types[$type_key])) {
$type_object = id(clone $log_types[$type_key])
->setLog($log)
->setViewer($viewer);
$log_data = $log->getData();
$type = $type_object->getLogTypeName();
$data = $type_object->renderLogForText($log_data);
} else {
$type = pht('Unknown ("%s")', $type_key);
$data = null;
}
echo tsprintf(
"(Lease #%d) <%s> %B\n",
$lease->getID(),
$type,
$data);
}
$status = $lease->getStatus();
switch ($status) {
case DrydockLeaseStatus::STATUS_ACTIVE:
$is_active = true;
break;
case DrydockLeaseStatus::STATUS_RELEASED:
throw new Exception(pht('Lease has already been released!'));
case DrydockLeaseStatus::STATUS_DESTROYED:
throw new Exception(pht('Lease has already been destroyed!'));
case DrydockLeaseStatus::STATUS_BROKEN:
throw new Exception(pht('Lease has been broken!'));
case DrydockLeaseStatus::STATUS_PENDING:
case DrydockLeaseStatus::STATUS_ACQUIRED:
break;
default:
throw new Exception(
pht(
'Lease has unknown status "%s".',
$status));
}
if ($is_active) {
break;
} else {
sleep(1);
}
}
}
private function getBlueprintFilterMap(array $identifiers) {
$viewer = $this->getViewer();
$query = id(new DrydockBlueprintQuery())
->setViewer($viewer)
->withIdentifiers($identifiers);
$blueprints = $query->execute();
$blueprints = mpull($blueprints, null, 'getPHID');
$map = $query->getIdentifierMap();
$seen = array();
foreach ($identifiers as $identifier) {
if (!isset($map[$identifier])) {
throw new PhutilArgumentUsageException(
pht(
'Blueprint "%s" could not be loaded. Try a blueprint ID or '.
'PHID.',
$identifier));
}
$blueprint = $map[$identifier];
$blueprint_phid = $blueprint->getPHID();
if (isset($seen[$blueprint_phid])) {
throw new PhutilArgumentUsageException(
pht(
'Blueprint "%s" is specified more than once (as "%s" and "%s").',
$blueprint->getBlueprintName(),
$seen[$blueprint_phid],
$identifier));
}
$seen[$blueprint_phid] = true;
}
return mpull($map, null, 'getPHID');
}
private function newAllowedBlueprintPHIDs(
DrydockLease $lease,
array $filter_blueprints) {
assert_instances_of($filter_blueprints, 'DrydockBlueprint');
$viewer = $this->getViewer();
$impls = DrydockBlueprintImplementation::getAllForAllocatingLease($lease);
if (!$impls) {
throw new PhutilArgumentUsageException(
pht(
'No known blueprint class can ever allocate the specified '.
'lease. Check that the resource type is spelled correctly.'));
}
$classes = array_keys($impls);
$blueprints = id(new DrydockBlueprintQuery())
->setViewer($viewer)
->withBlueprintClasses($classes)
->withDisabled(false)
->execute();
if (!$blueprints) {
throw new PhutilArgumentUsageException(
pht(
'No enabled blueprints exist with a blueprint class that can '.
'plausibly allocate resources to satisfy the requested lease.'));
}
$phids = mpull($blueprints, 'getPHID');
if ($filter_blueprints) {
$allowed_map = array_fuse($phids);
$filter_map = mpull($filter_blueprints, null, 'getPHID');
foreach ($filter_map as $filter_phid => $blueprint) {
if (!isset($allowed_map[$filter_phid])) {
throw new PhutilArgumentUsageException(
pht(
'Specified blueprint "%s" is not capable of satisfying the '.
'configured lease.',
$blueprint->getBlueprintName()));
}
}
$phids = mpull($filter_blueprints, 'getPHID');
}
return $phids;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/management/DrydockManagementWorkflow.php | src/applications/drydock/management/DrydockManagementWorkflow.php | <?php
abstract class DrydockManagementWorkflow
extends PhabricatorManagementWorkflow {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/management/DrydockManagementReleaseResourceWorkflow.php | src/applications/drydock/management/DrydockManagementReleaseResourceWorkflow.php | <?php
final class DrydockManagementReleaseResourceWorkflow
extends DrydockManagementWorkflow {
protected function didConstruct() {
$this
->setName('release-resource')
->setSynopsis(pht('Release a resource.'))
->setArguments(
array(
array(
'name' => 'id',
'param' => 'id',
'repeat' => true,
'help' => pht('Resource ID to release.'),
),
array(
'name' => 'all',
'help' => pht('Release all resources. Dangerous!'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$is_all = $args->getArg('all');
$ids = $args->getArg('id');
if (!$ids && !$is_all) {
throw new PhutilArgumentUsageException(
pht(
'Specify which resources you want to release. See "--help" for '.
'guidance.'));
}
$viewer = $this->getViewer();
$statuses = $this->getReleaseableResourceStatuses();
$query = id(new DrydockResourceQuery())
->setViewer($viewer)
->withStatuses(mpull($statuses, 'getKey'));
if ($ids) {
$query->withIDs($ids);
}
$resources = $query->execute();
if ($ids) {
$id_map = mpull($resources, null, 'getID');
foreach ($ids as $id) {
$resource = idx($resources, $id);
if (!$resource) {
throw new PhutilArgumentUsageException(
pht('Resource "%s" does not exist.', $id));
}
}
$resources = array_select_keys($id_map, $ids);
}
if (!$resources) {
echo tsprintf(
"%s\n",
pht('No resources selected for release.'));
return 0;
}
$drydock_phid = id(new PhabricatorDrydockApplication())->getPHID();
PhabricatorWorker::setRunAllTasksInProcess(true);
foreach ($resources as $resource) {
if (!$resource->canRelease()) {
echo tsprintf(
"%s\n",
pht(
'Resource "%s" is not releasable.',
$resource->getDisplayName()));
continue;
}
$command = DrydockCommand::initializeNewCommand($viewer)
->setTargetPHID($resource->getPHID())
->setAuthorPHID($drydock_phid)
->setCommand(DrydockCommand::COMMAND_RELEASE)
->save();
$resource->scheduleUpdate();
echo tsprintf(
"%s\n",
pht(
'Scheduled release of resource "%s".',
$resource->getDisplayName()));
}
return 0;
}
private function getReleaseableResourceStatuses() {
$statuses = DrydockResourceStatus::getAllStatuses();
foreach ($statuses as $key => $status) {
$statuses[$key] = DrydockResourceStatus::newStatusObject($status);
}
foreach ($statuses as $key => $status) {
if (!$status->canRelease()) {
unset($statuses[$key]);
}
}
return $statuses;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/management/DrydockManagementCommandWorkflow.php | src/applications/drydock/management/DrydockManagementCommandWorkflow.php | <?php
final class DrydockManagementCommandWorkflow
extends DrydockManagementWorkflow {
protected function didConstruct() {
$this
->setName('command')
->setSynopsis(pht('Run a command on a leased resource.'))
->setArguments(
array(
array(
'name' => 'lease',
'param' => 'id',
'help' => pht('Lease ID.'),
),
array(
'name' => 'argv',
'wildcard' => true,
'help' => pht('Command to execute.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$lease_id = $args->getArg('lease');
if (!$lease_id) {
throw new PhutilArgumentUsageException(
pht(
'Use "--lease" to specify a lease.'));
}
$argv = $args->getArg('argv');
if (!$argv) {
throw new PhutilArgumentUsageException(
pht(
'Specify a command to run.'));
}
$lease = id(new DrydockLeaseQuery())
->setViewer($this->getViewer())
->withIDs(array($lease_id))
->executeOne();
if (!$lease) {
throw new Exception(
pht(
'Unable to load lease with ID "%s"!',
$lease_id));
}
// TODO: Check lease state, etc.
$interface = $lease->getInterface(DrydockCommandInterface::INTERFACE_TYPE);
list($stdout, $stderr) = call_user_func_array(
array($interface, 'execx'),
array('%Ls', $argv));
fwrite(STDOUT, $stdout);
fwrite(STDERR, $stderr);
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/management/DrydockManagementReclaimWorkflow.php | src/applications/drydock/management/DrydockManagementReclaimWorkflow.php | <?php
final class DrydockManagementReclaimWorkflow
extends DrydockManagementWorkflow {
protected function didConstruct() {
$this
->setName('reclaim')
->setSynopsis(pht('Reclaim unused resources.'))
->setArguments(array());
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$drydock_phid = id(new PhabricatorDrydockApplication())->getPHID();
PhabricatorWorker::setRunAllTasksInProcess(true);
$resources = id(new DrydockResourceQuery())
->setViewer($viewer)
->withStatuses(
array(
DrydockResourceStatus::STATUS_ACTIVE,
))
->execute();
foreach ($resources as $resource) {
$command = DrydockCommand::initializeNewCommand($viewer)
->setTargetPHID($resource->getPHID())
->setAuthorPHID($drydock_phid)
->setCommand(DrydockCommand::COMMAND_RECLAIM)
->save();
$resource->scheduleUpdate();
$resource = $resource->reload();
$name = pht(
'Resource %d: %s',
$resource->getID(),
$resource->getResourceName());
switch ($resource->getStatus()) {
case DrydockResourceStatus::STATUS_RELEASED:
case DrydockResourceStatus::STATUS_DESTROYED:
echo tsprintf(
"%s\n",
pht(
'Resource "%s" was reclaimed.',
$name));
break;
default:
echo tsprintf(
"%s\n",
pht(
'Resource "%s" could not be reclaimed.',
$name));
break;
}
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/management/DrydockManagementUpdateLeaseWorkflow.php | src/applications/drydock/management/DrydockManagementUpdateLeaseWorkflow.php | <?php
final class DrydockManagementUpdateLeaseWorkflow
extends DrydockManagementWorkflow {
protected function didConstruct() {
$this
->setName('update-lease')
->setSynopsis(pht('Update a lease.'))
->setArguments(
array(
array(
'name' => 'id',
'param' => 'id',
'repeat' => true,
'help' => pht('Lease ID to update.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$ids = $args->getArg('id');
if (!$ids) {
throw new PhutilArgumentUsageException(
pht(
'Specify one or more lease IDs to update with "%s".',
'--id'));
}
$leases = id(new DrydockLeaseQuery())
->setViewer($viewer)
->withIDs($ids)
->execute();
PhabricatorWorker::setRunAllTasksInProcess(true);
foreach ($ids as $id) {
$lease = idx($leases, $id);
if (!$lease) {
echo tsprintf(
"%s\n",
pht('Lease "%s" does not exist.', $id));
continue;
}
echo tsprintf(
"%s\n",
pht('Updating lease "%s".', $id));
$lease->scheduleUpdate();
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/management/DrydockManagementUpdateResourceWorkflow.php | src/applications/drydock/management/DrydockManagementUpdateResourceWorkflow.php | <?php
final class DrydockManagementUpdateResourceWorkflow
extends DrydockManagementWorkflow {
protected function didConstruct() {
$this
->setName('update-resource')
->setSynopsis(pht('Update a resource.'))
->setArguments(
array(
array(
'name' => 'id',
'param' => 'id',
'repeat' => true,
'help' => pht('Resource ID to update.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$ids = $args->getArg('id');
if (!$ids) {
throw new PhutilArgumentUsageException(
pht(
'Specify one or more resource IDs to update with "%s".',
'--id'));
}
$resources = id(new DrydockResourceQuery())
->setViewer($viewer)
->withIDs($ids)
->execute();
PhabricatorWorker::setRunAllTasksInProcess(true);
foreach ($ids as $id) {
$resource = idx($resources, $id);
if (!$resource) {
echo tsprintf(
"%s\n",
pht('Resource "%s" does not exist.', $id));
continue;
}
echo tsprintf(
"%s\n",
pht('Updating resource "%s".', $id));
$resource->scheduleUpdate();
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | <?php
/**
* @task update Updating Leases
* @task command Processing Commands
* @task allocator Drydock Allocator
* @task acquire Acquiring Leases
* @task activate Activating Leases
* @task release Releasing Leases
* @task break Breaking Leases
* @task destroy Destroying Leases
*/
final class DrydockLeaseUpdateWorker extends DrydockWorker {
protected function doWork() {
$lease_phid = $this->getTaskDataValue('leasePHID');
$hash = PhabricatorHash::digestForIndex($lease_phid);
$lock_key = 'drydock.lease:'.$hash;
$lock = PhabricatorGlobalLock::newLock($lock_key)
->lock(1);
try {
$lease = $this->loadLease($lease_phid);
$this->handleUpdate($lease);
} catch (Exception $ex) {
$lock->unlock();
$this->flushDrydockTaskQueue();
throw $ex;
}
$lock->unlock();
}
/* -( Updating Leases )---------------------------------------------------- */
/**
* @task update
*/
private function handleUpdate(DrydockLease $lease) {
try {
$this->updateLease($lease);
} catch (DrydockAcquiredBrokenResourceException $ex) {
// If this lease acquired a resource but failed to activate, we don't
// need to break the lease. We can throw it back in the pool and let
// it take another shot at acquiring a new resource.
// Before we throw it back, release any locks the lease is holding.
DrydockSlotLock::releaseLocks($lease->getPHID());
$lease
->setStatus(DrydockLeaseStatus::STATUS_PENDING)
->setResourcePHID(null)
->save();
$lease->logEvent(
DrydockLeaseReacquireLogType::LOGCONST,
array(
'class' => get_class($ex),
'message' => $ex->getMessage(),
));
$this->yieldLease($lease, $ex);
} catch (Exception $ex) {
if ($this->isTemporaryException($ex)) {
$this->yieldLease($lease, $ex);
} else {
$this->breakLease($lease, $ex);
}
}
}
/**
* @task update
*/
private function updateLease(DrydockLease $lease) {
$this->processLeaseCommands($lease);
$lease_status = $lease->getStatus();
switch ($lease_status) {
case DrydockLeaseStatus::STATUS_PENDING:
$this->executeAllocator($lease);
break;
case DrydockLeaseStatus::STATUS_ACQUIRED:
$this->activateLease($lease);
break;
case DrydockLeaseStatus::STATUS_ACTIVE:
// Nothing to do.
break;
case DrydockLeaseStatus::STATUS_RELEASED:
case DrydockLeaseStatus::STATUS_BROKEN:
$this->destroyLease($lease);
break;
case DrydockLeaseStatus::STATUS_DESTROYED:
break;
}
$this->yieldIfExpiringLease($lease);
}
/**
* @task update
*/
private function yieldLease(DrydockLease $lease, Exception $ex) {
$duration = $this->getYieldDurationFromException($ex);
$lease->logEvent(
DrydockLeaseActivationYieldLogType::LOGCONST,
array(
'duration' => $duration,
));
throw new PhabricatorWorkerYieldException($duration);
}
/* -( Processing Commands )------------------------------------------------ */
/**
* @task command
*/
private function processLeaseCommands(DrydockLease $lease) {
if (!$lease->canReceiveCommands()) {
return;
}
$this->checkLeaseExpiration($lease);
$commands = $this->loadCommands($lease->getPHID());
foreach ($commands as $command) {
if (!$lease->canReceiveCommands()) {
break;
}
$this->processLeaseCommand($lease, $command);
$command
->setIsConsumed(true)
->save();
}
}
/**
* @task command
*/
private function processLeaseCommand(
DrydockLease $lease,
DrydockCommand $command) {
switch ($command->getCommand()) {
case DrydockCommand::COMMAND_RELEASE:
$this->releaseLease($lease);
break;
}
}
/* -( Drydock Allocator )-------------------------------------------------- */
/**
* Find or build a resource which can satisfy a given lease request, then
* acquire the lease.
*
* @param DrydockLease Requested lease.
* @return void
* @task allocator
*/
private function executeAllocator(DrydockLease $lease) {
$blueprints = $this->loadBlueprintsForAllocatingLease($lease);
// If we get nothing back, that means no blueprint is defined which can
// ever build the requested resource. This is a permanent failure, since
// we don't expect to succeed no matter how many times we try.
if (!$blueprints) {
throw new PhabricatorWorkerPermanentFailureException(
pht(
'No active Drydock blueprint exists which can ever allocate a '.
'resource for lease "%s".',
$lease->getPHID()));
}
// First, try to find a suitable open resource which we can acquire a new
// lease on.
$resources = $this->loadAcquirableResourcesForLease($blueprints, $lease);
list($free_resources, $used_resources) = $this->partitionResources(
$lease,
$resources);
$resource = $this->leaseAnyResource($lease, $free_resources);
if ($resource) {
return $resource;
}
// We're about to try creating a resource. If we're already creating
// something, just yield until that resolves.
$this->yieldForPendingResources($lease);
// We haven't been able to lease an existing resource yet, so now we try to
// create one. We may still have some less-desirable "used" resources that
// we'll sometimes try to lease later if we fail to allocate a new resource.
$resource = $this->newLeasedResource($lease, $blueprints);
if ($resource) {
return $resource;
}
// We haven't been able to lease a desirable "free" resource or create a
// new resource. Try to lease a "used" resource.
$resource = $this->leaseAnyResource($lease, $used_resources);
if ($resource) {
return $resource;
}
// If this lease has already triggered a reclaim, just yield and wait for
// it to resolve.
$this->yieldForReclaimingResources($lease);
// Try to reclaim a resource. This will yield if it reclaims something.
$this->reclaimAnyResource($lease, $blueprints);
// We weren't able to lease, create, or reclaim any resources. We just have
// to wait for resources to become available.
$lease->logEvent(
DrydockLeaseWaitingForResourcesLogType::LOGCONST,
array(
'blueprintPHIDs' => mpull($blueprints, 'getPHID'),
));
throw new PhabricatorWorkerYieldException(15);
}
private function reclaimAnyResource(DrydockLease $lease, array $blueprints) {
assert_instances_of($blueprints, 'DrydockBlueprint');
$blueprints = $this->rankBlueprints($blueprints, $lease);
// Try to actively reclaim unused resources. If we succeed, jump back
// into the queue in an effort to claim it.
foreach ($blueprints as $blueprint) {
$reclaimed = $this->reclaimResources($blueprint, $lease);
if ($reclaimed) {
$lease->logEvent(
DrydockLeaseReclaimLogType::LOGCONST,
array(
'resourcePHIDs' => array($reclaimed->getPHID()),
));
// Yield explicitly here: we'll be awakened when the resource is
// reclaimed.
throw new PhabricatorWorkerYieldException(15);
}
}
}
private function yieldForPendingResources(DrydockLease $lease) {
// See T13677. If this lease has already triggered the allocation of
// one or more resources and they are still pending, just yield and
// wait for them.
$viewer = $this->getViewer();
$phids = $lease->getAllocatedResourcePHIDs();
if (!$phids) {
return null;
}
$resources = id(new DrydockResourceQuery())
->setViewer($viewer)
->withPHIDs($phids)
->withStatuses(
array(
DrydockResourceStatus::STATUS_PENDING,
))
->setLimit(1)
->execute();
if (!$resources) {
return;
}
$lease->logEvent(
DrydockLeaseWaitingForActivationLogType::LOGCONST,
array(
'resourcePHIDs' => mpull($resources, 'getPHID'),
));
throw new PhabricatorWorkerYieldException(15);
}
private function yieldForReclaimingResources(DrydockLease $lease) {
$viewer = $this->getViewer();
$phids = $lease->getReclaimedResourcePHIDs();
if (!$phids) {
return;
}
$resources = id(new DrydockResourceQuery())
->setViewer($viewer)
->withPHIDs($phids)
->withStatuses(
array(
DrydockResourceStatus::STATUS_ACTIVE,
DrydockResourceStatus::STATUS_RELEASED,
))
->setLimit(1)
->execute();
if (!$resources) {
return;
}
$lease->logEvent(
DrydockLeaseWaitingForReclamationLogType::LOGCONST,
array(
'resourcePHIDs' => mpull($resources, 'getPHID'),
));
throw new PhabricatorWorkerYieldException(15);
}
private function newLeasedResource(
DrydockLease $lease,
array $blueprints) {
assert_instances_of($blueprints, 'DrydockBlueprint');
$usable_blueprints = $this->removeOverallocatedBlueprints(
$blueprints,
$lease);
// If we get nothing back here, some blueprint claims it can eventually
// satisfy the lease, just not right now. This is a temporary failure,
// and we expect allocation to succeed eventually.
// Return, try to lease a "used" resource, and continue from there.
if (!$usable_blueprints) {
return null;
}
$usable_blueprints = $this->rankBlueprints($usable_blueprints, $lease);
$new_resources = $this->newResources($lease, $usable_blueprints);
if (!$new_resources) {
// If we were unable to create any new resources, return and
// try to lease a "used" resource.
return null;
}
$new_resources = $this->removeUnacquirableResources(
$new_resources,
$lease);
if (!$new_resources) {
// If we make it here, we just built a resource but aren't allowed
// to acquire it. We expect this to happen if the resource prevents
// acquisition until it activates, which is common when a resource
// needs to perform setup steps.
// Explicitly yield and wait for activation, since we don't want to
// lease a "used" resource.
throw new PhabricatorWorkerYieldException(15);
}
$resource = $this->leaseAnyResource($lease, $new_resources);
if ($resource) {
return $resource;
}
// We may not be able to lease a resource even if we just built it:
// another process may snatch it up before we can lease it. This should
// be rare, but is not concerning. Just try to build another resource.
// We likely could try to build the next resource immediately, but err on
// the side of caution and yield for now, at least until this code is
// better vetted.
throw new PhabricatorWorkerYieldException(15);
}
private function partitionResources(
DrydockLease $lease,
array $resources) {
assert_instances_of($resources, 'DrydockResource');
$viewer = $this->getViewer();
$lease_statuses = array(
DrydockLeaseStatus::STATUS_PENDING,
DrydockLeaseStatus::STATUS_ACQUIRED,
DrydockLeaseStatus::STATUS_ACTIVE,
);
// Partition resources into "free" resources (which we can try to lease
// immediately) and "used" resources, which we can only to lease after we
// fail to allocate a new resource.
// "Free" resources are unleased and/or prefer reuse over allocation.
// "Used" resources are leased and prefer allocation over reuse.
$free_resources = array();
$used_resources = array();
foreach ($resources as $resource) {
$blueprint = $resource->getBlueprint();
if (!$blueprint->shouldAllocateSupplementalResource($resource, $lease)) {
$free_resources[] = $resource;
continue;
}
$leases = id(new DrydockLeaseQuery())
->setViewer($viewer)
->withResourcePHIDs(array($resource->getPHID()))
->withStatuses($lease_statuses)
->setLimit(1)
->execute();
if (!$leases) {
$free_resources[] = $resource;
continue;
}
$used_resources[] = $resource;
}
return array($free_resources, $used_resources);
}
private function newResources(
DrydockLease $lease,
array $blueprints) {
assert_instances_of($blueprints, 'DrydockBlueprint');
$resources = array();
$exceptions = array();
foreach ($blueprints as $blueprint) {
$caught = null;
try {
$resources[] = $this->allocateResource($blueprint, $lease);
// Bail after allocating one resource, we don't need any more than
// this.
break;
} catch (Exception $ex) {
$caught = $ex;
} catch (Throwable $ex) {
$caught = $ex;
}
if ($caught) {
// This failure is not normally expected, so log it. It can be
// caused by something mundane and recoverable, however (see below
// for discussion).
// We log to the blueprint separately from the log to the lease:
// the lease is not attached to a blueprint yet so the lease log
// will not show up on the blueprint; more than one blueprint may
// fail; and the lease is not really impacted (and won't log) if at
// least one blueprint actually works.
$blueprint->logEvent(
DrydockResourceAllocationFailureLogType::LOGCONST,
array(
'class' => get_class($caught),
'message' => $caught->getMessage(),
));
$exceptions[] = $caught;
}
}
if (!$resources) {
// If one or more blueprints claimed that they would be able to allocate
// resources but none are actually able to allocate resources, log the
// failure and yield so we try again soon.
// This can happen if some unexpected issue occurs during allocation
// (for example, a call to build a VM fails for some reason) or if we
// raced another allocator and the blueprint is now full.
$ex = new PhutilAggregateException(
pht(
'All blueprints failed to allocate a suitable new resource when '.
'trying to allocate lease ("%s").',
$lease->getPHID()),
$exceptions);
$lease->logEvent(
DrydockLeaseAllocationFailureLogType::LOGCONST,
array(
'class' => get_class($ex),
'message' => $ex->getMessage(),
));
return null;
}
return $resources;
}
private function leaseAnyResource(
DrydockLease $lease,
array $resources) {
assert_instances_of($resources, 'DrydockResource');
if (!$resources) {
return null;
}
$resources = $this->rankResources($resources, $lease);
$exceptions = array();
$yields = array();
$allocated = null;
foreach ($resources as $resource) {
try {
$this->acquireLease($resource, $lease);
$allocated = $resource;
break;
} catch (DrydockResourceLockException $ex) {
// We need to lock the resource to actually acquire it. If we aren't
// able to acquire the lock quickly enough, we can yield and try again
// later.
$yields[] = $ex;
} catch (DrydockSlotLockException $ex) {
// This also just indicates we ran into some kind of contention,
// probably from another lease. Just yield.
$yields[] = $ex;
} catch (DrydockAcquiredBrokenResourceException $ex) {
// If a resource was reclaimed or destroyed by the time we actually
// got around to acquiring it, we just got unlucky.
$yields[] = $ex;
} catch (PhabricatorWorkerYieldException $ex) {
// We can be told to yield, particularly by the supplemental allocator
// trying to give us a supplemental resource.
$yields[] = $ex;
} catch (Exception $ex) {
$exceptions[] = $ex;
}
}
if ($allocated) {
return $allocated;
}
if ($yields) {
throw new PhabricatorWorkerYieldException(15);
}
throw new PhutilAggregateException(
pht(
'Unable to acquire lease "%s" on any resource.',
$lease->getPHID()),
$exceptions);
}
/**
* Get all the concrete @{class:DrydockBlueprint}s which can possibly
* build a resource to satisfy a lease.
*
* @param DrydockLease Requested lease.
* @return list<DrydockBlueprint> List of qualifying blueprints.
* @task allocator
*/
private function loadBlueprintsForAllocatingLease(
DrydockLease $lease) {
$viewer = $this->getViewer();
$impls = DrydockBlueprintImplementation::getAllForAllocatingLease($lease);
if (!$impls) {
return array();
}
$blueprint_phids = $lease->getAllowedBlueprintPHIDs();
if (!$blueprint_phids) {
$lease->logEvent(DrydockLeaseNoBlueprintsLogType::LOGCONST);
return array();
}
$query = id(new DrydockBlueprintQuery())
->setViewer($viewer)
->withPHIDs($blueprint_phids)
->withBlueprintClasses(array_keys($impls))
->withDisabled(false);
// The Drydock application itself is allowed to authorize anything. This
// is primarily used for leases generated by CLI administrative tools.
$drydock_phid = id(new PhabricatorDrydockApplication())->getPHID();
$authorizing_phid = $lease->getAuthorizingPHID();
if ($authorizing_phid != $drydock_phid) {
$blueprints = id(clone $query)
->withAuthorizedPHIDs(array($authorizing_phid))
->execute();
if (!$blueprints) {
// If we didn't hit any blueprints, check if this is an authorization
// problem: re-execute the query without the authorization constraint.
// If the second query hits blueprints, the overall configuration is
// fine but this is an authorization problem. If the second query also
// comes up blank, this is some other kind of configuration issue so
// we fall through to the default pathway.
$all_blueprints = $query->execute();
if ($all_blueprints) {
$lease->logEvent(
DrydockLeaseNoAuthorizationsLogType::LOGCONST,
array(
'authorizingPHID' => $authorizing_phid,
));
return array();
}
}
} else {
$blueprints = $query->execute();
}
$keep = array();
foreach ($blueprints as $key => $blueprint) {
if (!$blueprint->canEverAllocateResourceForLease($lease)) {
continue;
}
$keep[$key] = $blueprint;
}
return $keep;
}
/**
* Load a list of all resources which a given lease can possibly be
* allocated against.
*
* @param list<DrydockBlueprint> Blueprints which may produce suitable
* resources.
* @param DrydockLease Requested lease.
* @return list<DrydockResource> Resources which may be able to allocate
* the lease.
* @task allocator
*/
private function loadAcquirableResourcesForLease(
array $blueprints,
DrydockLease $lease) {
assert_instances_of($blueprints, 'DrydockBlueprint');
$viewer = $this->getViewer();
$resources = id(new DrydockResourceQuery())
->setViewer($viewer)
->withBlueprintPHIDs(mpull($blueprints, 'getPHID'))
->withTypes(array($lease->getResourceType()))
->withStatuses(
array(
DrydockResourceStatus::STATUS_ACTIVE,
))
->execute();
return $this->removeUnacquirableResources($resources, $lease);
}
/**
* Remove resources which can not be acquired by a given lease from a list.
*
* @param list<DrydockResource> Candidate resources.
* @param DrydockLease Acquiring lease.
* @return list<DrydockResource> Resources which the lease may be able to
* acquire.
* @task allocator
*/
private function removeUnacquirableResources(
array $resources,
DrydockLease $lease) {
$keep = array();
foreach ($resources as $key => $resource) {
$blueprint = $resource->getBlueprint();
if (!$blueprint->canAcquireLeaseOnResource($resource, $lease)) {
continue;
}
$keep[$key] = $resource;
}
return $keep;
}
/**
* Remove blueprints which are too heavily allocated to build a resource for
* a lease from a list of blueprints.
*
* @param list<DrydockBlueprint> List of blueprints.
* @return list<DrydockBlueprint> List with blueprints that can not allocate
* a resource for the lease right now removed.
* @task allocator
*/
private function removeOverallocatedBlueprints(
array $blueprints,
DrydockLease $lease) {
assert_instances_of($blueprints, 'DrydockBlueprint');
$keep = array();
foreach ($blueprints as $key => $blueprint) {
if (!$blueprint->canAllocateResourceForLease($lease)) {
continue;
}
$keep[$key] = $blueprint;
}
return $keep;
}
/**
* Rank blueprints by suitability for building a new resource for a
* particular lease.
*
* @param list<DrydockBlueprint> List of blueprints.
* @param DrydockLease Requested lease.
* @return list<DrydockBlueprint> Ranked list of blueprints.
* @task allocator
*/
private function rankBlueprints(array $blueprints, DrydockLease $lease) {
assert_instances_of($blueprints, 'DrydockBlueprint');
// TODO: Implement improvements to this ranking algorithm if they become
// available.
shuffle($blueprints);
return $blueprints;
}
/**
* Rank resources by suitability for allocating a particular lease.
*
* @param list<DrydockResource> List of resources.
* @param DrydockLease Requested lease.
* @return list<DrydockResource> Ranked list of resources.
* @task allocator
*/
private function rankResources(array $resources, DrydockLease $lease) {
assert_instances_of($resources, 'DrydockResource');
// TODO: Implement improvements to this ranking algorithm if they become
// available.
shuffle($resources);
return $resources;
}
/**
* Perform an actual resource allocation with a particular blueprint.
*
* @param DrydockBlueprint The blueprint to allocate a resource from.
* @param DrydockLease Requested lease.
* @return DrydockResource Allocated resource.
* @task allocator
*/
private function allocateResource(
DrydockBlueprint $blueprint,
DrydockLease $lease) {
$resource = $blueprint->allocateResource($lease);
$this->validateAllocatedResource($blueprint, $resource, $lease);
// If this resource was allocated as a pending resource, queue a task to
// activate it.
if ($resource->getStatus() == DrydockResourceStatus::STATUS_PENDING) {
$lease->addAllocatedResourcePHIDs(
array(
$resource->getPHID(),
));
$lease->save();
PhabricatorWorker::scheduleTask(
'DrydockResourceUpdateWorker',
array(
'resourcePHID' => $resource->getPHID(),
// This task will generally yield while the resource activates, so
// wake it back up once the resource comes online. Most of the time,
// we'll be able to lease the newly activated resource.
'awakenOnActivation' => array(
$this->getCurrentWorkerTaskID(),
),
),
array(
'objectPHID' => $resource->getPHID(),
));
}
return $resource;
}
/**
* Check that the resource a blueprint allocated is roughly the sort of
* object we expect.
*
* @param DrydockBlueprint Blueprint which built the resource.
* @param wild Thing which the blueprint claims is a valid resource.
* @param DrydockLease Lease the resource was allocated for.
* @return void
* @task allocator
*/
private function validateAllocatedResource(
DrydockBlueprint $blueprint,
$resource,
DrydockLease $lease) {
if (!($resource instanceof DrydockResource)) {
throw new Exception(
pht(
'Blueprint "%s" (of type "%s") is not properly implemented: %s must '.
'return an object of type %s or throw, but returned something else.',
$blueprint->getBlueprintName(),
$blueprint->getClassName(),
'allocateResource()',
'DrydockResource'));
}
if (!$resource->isAllocatedResource()) {
throw new Exception(
pht(
'Blueprint "%s" (of type "%s") is not properly implemented: %s '.
'must actually allocate the resource it returns.',
$blueprint->getBlueprintName(),
$blueprint->getClassName(),
'allocateResource()'));
}
$resource_type = $resource->getType();
$lease_type = $lease->getResourceType();
if ($resource_type !== $lease_type) {
throw new Exception(
pht(
'Blueprint "%s" (of type "%s") is not properly implemented: it '.
'built a resource of type "%s" to satisfy a lease requesting a '.
'resource of type "%s".',
$blueprint->getBlueprintName(),
$blueprint->getClassName(),
$resource_type,
$lease_type));
}
}
private function reclaimResources(
DrydockBlueprint $blueprint,
DrydockLease $lease) {
$viewer = $this->getViewer();
$resources = id(new DrydockResourceQuery())
->setViewer($viewer)
->withBlueprintPHIDs(array($blueprint->getPHID()))
->withStatuses(
array(
DrydockResourceStatus::STATUS_ACTIVE,
))
->execute();
// TODO: We could be much smarter about this and try to release long-unused
// resources, resources with many similar copies, old resources, resources
// that are cheap to rebuild, etc.
shuffle($resources);
foreach ($resources as $resource) {
if ($this->canReclaimResource($resource)) {
$this->reclaimResource($resource, $lease);
return $resource;
}
}
return null;
}
/* -( Acquiring Leases )--------------------------------------------------- */
/**
* Perform an actual lease acquisition on a particular resource.
*
* @param DrydockResource Resource to acquire a lease on.
* @param DrydockLease Lease to acquire.
* @return void
* @task acquire
*/
private function acquireLease(
DrydockResource $resource,
DrydockLease $lease) {
$blueprint = $resource->getBlueprint();
$blueprint->acquireLease($resource, $lease);
$this->validateAcquiredLease($blueprint, $resource, $lease);
// If this lease has been acquired but not activated, queue a task to
// activate it.
if ($lease->getStatus() == DrydockLeaseStatus::STATUS_ACQUIRED) {
$this->queueTask(
__CLASS__,
array(
'leasePHID' => $lease->getPHID(),
),
array(
'objectPHID' => $lease->getPHID(),
));
}
}
/**
* Make sure that a lease was really acquired properly.
*
* @param DrydockBlueprint Blueprint which created the resource.
* @param DrydockResource Resource which was acquired.
* @param DrydockLease The lease which was supposedly acquired.
* @return void
* @task acquire
*/
private function validateAcquiredLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
if (!$lease->isAcquiredLease()) {
throw new Exception(
pht(
'Blueprint "%s" (of type "%s") is not properly implemented: it '.
'returned from "%s" without acquiring a lease.',
$blueprint->getBlueprintName(),
$blueprint->getClassName(),
'acquireLease()'));
}
$lease_phid = $lease->getResourcePHID();
$resource_phid = $resource->getPHID();
if ($lease_phid !== $resource_phid) {
throw new Exception(
pht(
'Blueprint "%s" (of type "%s") is not properly implemented: it '.
'returned from "%s" with a lease acquired on the wrong resource.',
$blueprint->getBlueprintName(),
$blueprint->getClassName(),
'acquireLease()'));
}
}
/* -( Activating Leases )-------------------------------------------------- */
/**
* @task activate
*/
private function activateLease(DrydockLease $lease) {
$resource = $lease->getResource();
if (!$resource) {
throw new Exception(
pht('Trying to activate lease with no resource.'));
}
$resource_status = $resource->getStatus();
if ($resource_status == DrydockResourceStatus::STATUS_PENDING) {
throw new PhabricatorWorkerYieldException(15);
}
if ($resource_status != DrydockResourceStatus::STATUS_ACTIVE) {
throw new DrydockAcquiredBrokenResourceException(
pht(
'Trying to activate lease ("%s") on a resource ("%s") in '.
'the wrong status ("%s").',
$lease->getPHID(),
$resource->getPHID(),
$resource_status));
}
// NOTE: We can race resource destruction here. Between the time we
// performed the read above and now, the resource might have closed, so
// we may activate leases on dead resources. At least for now, this seems
// fine: a resource dying right before we activate a lease on it should not
// be distinguishable from a resource dying right after we activate a lease
// on it. We end up with an active lease on a dead resource either way, and
// can not prevent resources dying from lightning strikes.
$blueprint = $resource->getBlueprint();
$blueprint->activateLease($resource, $lease);
$this->validateActivatedLease($blueprint, $resource, $lease);
}
/**
* @task activate
*/
private function validateActivatedLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
if (!$lease->isActivatedLease()) {
throw new Exception(
pht(
'Blueprint "%s" (of type "%s") is not properly implemented: it '.
'returned from "%s" without activating a lease.',
$blueprint->getBlueprintName(),
$blueprint->getClassName(),
'acquireLease()'));
}
}
/* -( Releasing Leases )--------------------------------------------------- */
/**
* @task release
*/
private function releaseLease(DrydockLease $lease) {
$lease
->setStatus(DrydockLeaseStatus::STATUS_RELEASED)
->save();
$lease->logEvent(DrydockLeaseReleasedLogType::LOGCONST);
$resource = $lease->getResource();
if ($resource) {
$blueprint = $resource->getBlueprint();
$blueprint->didReleaseLease($resource, $lease);
}
$this->destroyLease($lease);
}
/* -( Breaking Leases )---------------------------------------------------- */
/**
* @task break
*/
protected function breakLease(DrydockLease $lease, Exception $ex) {
switch ($lease->getStatus()) {
case DrydockLeaseStatus::STATUS_BROKEN:
case DrydockLeaseStatus::STATUS_RELEASED:
case DrydockLeaseStatus::STATUS_DESTROYED:
throw new PhutilProxyException(
pht(
'Unexpected failure while destroying lease ("%s").',
$lease->getPHID()),
$ex);
}
$lease
->setStatus(DrydockLeaseStatus::STATUS_BROKEN)
->save();
$lease->logEvent(
DrydockLeaseActivationFailureLogType::LOGCONST,
array(
'class' => get_class($ex),
'message' => $ex->getMessage(),
));
$lease->awakenTasks();
$this->queueTask(
__CLASS__,
array(
'leasePHID' => $lease->getPHID(),
),
array(
'objectPHID' => $lease->getPHID(),
));
throw new PhabricatorWorkerPermanentFailureException(
pht(
'Permanent failure while activating lease ("%s"): %s',
$lease->getPHID(),
$ex->getMessage()));
}
/* -( Destroying Leases )-------------------------------------------------- */
/**
* @task destroy
*/
private function destroyLease(DrydockLease $lease) {
$resource = $lease->getResource();
if ($resource) {
$blueprint = $resource->getBlueprint();
$blueprint->destroyLease($resource, $lease);
}
DrydockSlotLock::releaseLocks($lease->getPHID());
$lease
->setStatus(DrydockLeaseStatus::STATUS_DESTROYED)
->save();
$lease->logEvent(DrydockLeaseDestroyedLogType::LOGCONST);
$lease->awakenTasks();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/worker/DrydockWorker.php | src/applications/drydock/worker/DrydockWorker.php | <?php
abstract class DrydockWorker extends PhabricatorWorker {
protected function getViewer() {
return PhabricatorUser::getOmnipotentUser();
}
protected function loadLease($lease_phid) {
$viewer = $this->getViewer();
$lease = id(new DrydockLeaseQuery())
->setViewer($viewer)
->withPHIDs(array($lease_phid))
->executeOne();
if (!$lease) {
throw new PhabricatorWorkerPermanentFailureException(
pht('No such lease "%s"!', $lease_phid));
}
return $lease;
}
protected function loadResource($resource_phid) {
$viewer = $this->getViewer();
$resource = id(new DrydockResourceQuery())
->setViewer($viewer)
->withPHIDs(array($resource_phid))
->executeOne();
if (!$resource) {
throw new PhabricatorWorkerPermanentFailureException(
pht('No such resource "%s"!', $resource_phid));
}
return $resource;
}
protected function loadOperation($operation_phid) {
$viewer = $this->getViewer();
$operation = id(new DrydockRepositoryOperationQuery())
->setViewer($viewer)
->withPHIDs(array($operation_phid))
->executeOne();
if (!$operation) {
throw new PhabricatorWorkerPermanentFailureException(
pht('No such operation "%s"!', $operation_phid));
}
return $operation;
}
protected function loadCommands($target_phid) {
$viewer = $this->getViewer();
$commands = id(new DrydockCommandQuery())
->setViewer($viewer)
->withTargetPHIDs(array($target_phid))
->withConsumed(false)
->execute();
$commands = msort($commands, 'getID');
return $commands;
}
protected function checkLeaseExpiration(DrydockLease $lease) {
$this->checkObjectExpiration($lease);
}
protected function checkResourceExpiration(DrydockResource $resource) {
$this->checkObjectExpiration($resource);
}
private function checkObjectExpiration($object) {
// Check if the resource or lease has expired. If it has, we're going to
// send it a release command.
// This command is sent from within the update worker so it is handled
// immediately, but doing this generates a log and improves consistency.
$expires = $object->getUntil();
if (!$expires) {
return;
}
$now = PhabricatorTime::getNow();
if ($expires > $now) {
return;
}
$viewer = $this->getViewer();
$drydock_phid = id(new PhabricatorDrydockApplication())->getPHID();
$command = DrydockCommand::initializeNewCommand($viewer)
->setTargetPHID($object->getPHID())
->setAuthorPHID($drydock_phid)
->setCommand(DrydockCommand::COMMAND_RELEASE)
->save();
}
protected function yieldIfExpiringLease(DrydockLease $lease) {
if (!$lease->canReceiveCommands()) {
return;
}
$this->yieldIfExpiring($lease->getUntil());
}
protected function yieldIfExpiringResource(DrydockResource $resource) {
if (!$resource->canReceiveCommands()) {
return;
}
$this->yieldIfExpiring($resource->getUntil());
}
private function yieldIfExpiring($expires) {
if (!$expires) {
return;
}
if (!$this->getTaskDataValue('isExpireTask')) {
return;
}
$now = PhabricatorTime::getNow();
throw new PhabricatorWorkerYieldException($expires - $now);
}
protected function isTemporaryException(Exception $ex) {
if ($ex instanceof PhabricatorWorkerYieldException) {
return true;
}
if ($ex instanceof DrydockSlotLockException) {
return true;
}
if ($ex instanceof PhutilAggregateException) {
$any_temporary = false;
foreach ($ex->getExceptions() as $sub) {
if ($this->isTemporaryException($sub)) {
$any_temporary = true;
break;
}
}
if ($any_temporary) {
return true;
}
}
if ($ex instanceof PhutilProxyException) {
return $this->isTemporaryException($ex->getPreviousException());
}
return false;
}
protected function getYieldDurationFromException(Exception $ex) {
if ($ex instanceof PhabricatorWorkerYieldException) {
return $ex->getDuration();
}
if ($ex instanceof DrydockSlotLockException) {
return 5;
}
return 15;
}
protected function flushDrydockTaskQueue() {
// NOTE: By default, queued tasks are not scheduled if the current task
// fails. This is a good, safe default behavior. For example, it can
// protect us from executing side effect tasks too many times, like
// sending extra email.
// However, it is not the behavior we want in Drydock, because we queue
// followup tasks after lease and resource failures and want them to
// execute in order to clean things up.
// At least for now, we just explicitly flush the queue before exiting
// with a failure to make sure tasks get queued up properly.
try {
$this->flushTaskQueue();
} catch (Exception $ex) {
// If this fails, we want to swallow the exception so the caller throws
// the original error, since we're more likely to be able to understand
// and fix the problem if we have the original error than if we replace
// it with this one.
phlog($ex);
}
return $this;
}
protected function canReclaimResource(DrydockResource $resource) {
$viewer = $this->getViewer();
// Don't reclaim a resource if it has been updated recently. If two
// leases are fighting, we don't want them to keep reclaiming resources
// from one another forever without making progress, so make resources
// immune to reclamation for a little while after they activate or update.
$now = PhabricatorTime::getNow();
$max_epoch = ($now - phutil_units('3 minutes in seconds'));
// TODO: It would be nice to use a more narrow time here, like "last
// activation or lease release", but we don't currently store that
// anywhere.
$updated = $resource->getDateModified();
if ($updated > $max_epoch) {
return false;
}
$statuses = array(
DrydockLeaseStatus::STATUS_PENDING,
DrydockLeaseStatus::STATUS_ACQUIRED,
DrydockLeaseStatus::STATUS_ACTIVE,
DrydockLeaseStatus::STATUS_RELEASED,
DrydockLeaseStatus::STATUS_BROKEN,
);
// Don't reclaim resources that have any active leases.
$leases = id(new DrydockLeaseQuery())
->setViewer($viewer)
->withResourcePHIDs(array($resource->getPHID()))
->withStatuses($statuses)
->setLimit(1)
->execute();
if ($leases) {
return false;
}
// See T13676. Don't reclaim a resource if a lease recently released.
$leases = id(new DrydockLeaseQuery())
->setViewer($viewer)
->withResourcePHIDs(array($resource->getPHID()))
->withStatuses(
array(
DrydockLeaseStatus::STATUS_DESTROYED,
))
->withDateModifiedBetween($max_epoch, null)
->setLimit(1)
->execute();
if ($leases) {
return false;
}
return true;
}
protected function reclaimResource(
DrydockResource $resource,
DrydockLease $lease) {
$viewer = $this->getViewer();
// Mark the lease as reclaiming this resource. It won't be allowed to start
// another reclaim as long as this resource is still in the process of
// being reclaimed.
$lease->addReclaimedResourcePHIDs(array($resource->getPHID()));
// When the resource releases, we we want to reawaken this task since it
// should (usually) be able to start building a new resource right away.
$worker_task_id = $this->getCurrentWorkerTaskID();
$command = DrydockCommand::initializeNewCommand($viewer)
->setTargetPHID($resource->getPHID())
->setAuthorPHID($lease->getPHID())
->setCommand(DrydockCommand::COMMAND_RECLAIM)
->setProperty('awakenTaskIDs', array($worker_task_id));
$lease->openTransaction();
$lease->save();
$command->save();
$lease->saveTransaction();
$resource->scheduleUpdate();
return $this;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/worker/DrydockRepositoryOperationUpdateWorker.php | src/applications/drydock/worker/DrydockRepositoryOperationUpdateWorker.php | <?php
final class DrydockRepositoryOperationUpdateWorker
extends DrydockWorker {
protected function doWork() {
$operation_phid = $this->getTaskDataValue('operationPHID');
$hash = PhabricatorHash::digestForIndex($operation_phid);
$lock_key = 'drydock.operation:'.$hash;
$lock = PhabricatorGlobalLock::newLock($lock_key)
->lock(1);
try {
$operation = $this->loadOperation($operation_phid);
$this->handleUpdate($operation);
} catch (Exception $ex) {
$lock->unlock();
throw $ex;
}
$lock->unlock();
}
private function handleUpdate(DrydockRepositoryOperation $operation) {
$operation_state = $operation->getOperationState();
switch ($operation_state) {
case DrydockRepositoryOperation::STATE_WAIT:
$operation
->setOperationState(DrydockRepositoryOperation::STATE_WORK)
->save();
break;
case DrydockRepositoryOperation::STATE_WORK:
break;
case DrydockRepositoryOperation::STATE_DONE:
case DrydockRepositoryOperation::STATE_FAIL:
// No more processing for these requests.
return;
}
// TODO: We should probably check for other running operations with lower
// IDs and the same repository target and yield to them here? That is,
// enforce sequential evaluation of operations against the same target so
// that if you land "A" and then land "B", we always finish "A" first.
// For now, just let stuff happen in any order. We can't lease until
// we know we're good to move forward because we might deadlock if we do:
// we're waiting for another operation to complete, and that operation is
// waiting for a lease we're holding.
try {
$lease = $this->loadWorkingCopyLease($operation);
$interface = $lease->getInterface(
DrydockCommandInterface::INTERFACE_TYPE);
// No matter what happens here, destroy the lease away once we're done.
$lease->setReleaseOnDestruction(true);
$operation->attachWorkingCopyLease($lease);
$operation->logEvent(DrydockOperationWorkLogType::LOGCONST);
$operation->applyOperation($interface);
} catch (PhabricatorWorkerYieldException $ex) {
throw $ex;
} catch (Exception $ex) {
$operation
->setOperationState(DrydockRepositoryOperation::STATE_FAIL)
->save();
throw $ex;
}
$operation
->setOperationState(DrydockRepositoryOperation::STATE_DONE)
->save();
// TODO: Once we have sequencing, we could awaken the next operation
// against this target after finishing or failing.
}
private function loadWorkingCopyLease(
DrydockRepositoryOperation $operation) {
$viewer = $this->getViewer();
// TODO: This is very similar to leasing in Harbormaster, maybe we can
// share some of the logic?
$working_copy = new DrydockWorkingCopyBlueprintImplementation();
$working_copy_type = $working_copy->getType();
$lease_phid = $operation->getProperty('exec.leasePHID');
if ($lease_phid) {
$lease = id(new DrydockLeaseQuery())
->setViewer($viewer)
->withPHIDs(array($lease_phid))
->executeOne();
if (!$lease) {
throw new PhabricatorWorkerPermanentFailureException(
pht(
'Lease "%s" could not be loaded.',
$lease_phid));
}
} else {
$repository = $operation->getRepository();
$allowed_phids = $repository->getAutomationBlueprintPHIDs();
$authorizing_phid = $repository->getPHID();
$lease = DrydockLease::initializeNewLease()
->setResourceType($working_copy_type)
->setOwnerPHID($operation->getPHID())
->setAuthorizingPHID($authorizing_phid)
->setAllowedBlueprintPHIDs($allowed_phids);
$map = $this->buildRepositoryMap($operation);
$lease->setAttribute('repositories.map', $map);
$task_id = $this->getCurrentWorkerTaskID();
if ($task_id) {
$lease->setAwakenTaskIDs(array($task_id));
}
$operation
->setWorkingCopyLeasePHID($lease->getPHID())
->save();
$lease->queueForActivation();
}
if ($lease->isActivating()) {
throw new PhabricatorWorkerYieldException(15);
}
if (!$lease->isActive()) {
$vcs_error = $working_copy->getCommandError($lease);
if ($vcs_error) {
$operation
->setCommandError($vcs_error)
->save();
}
throw new PhabricatorWorkerPermanentFailureException(
pht(
'Lease "%s" never activated.',
$lease->getPHID()));
}
return $lease;
}
private function buildRepositoryMap(DrydockRepositoryOperation $operation) {
$repository = $operation->getRepository();
$target = $operation->getRepositoryTarget();
list($type, $name) = explode(':', $target, 2);
switch ($type) {
case 'branch':
$spec = array(
'branch' => $name,
);
break;
case 'none':
$spec = array();
break;
default:
throw new Exception(
pht(
'Unknown repository operation target type "%s" (in target "%s").',
$type,
$target));
}
$spec['merges'] = $operation->getWorkingCopyMerges();
$map = array();
$map[$repository->getCloneName()] = array(
'phid' => $repository->getPHID(),
'default' => true,
) + $spec;
return $map;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/worker/DrydockResourceUpdateWorker.php | src/applications/drydock/worker/DrydockResourceUpdateWorker.php | <?php
/**
* @task update Updating Resources
* @task command Processing Commands
* @task activate Activating Resources
* @task release Releasing Resources
* @task break Breaking Resources
* @task destroy Destroying Resources
*/
final class DrydockResourceUpdateWorker extends DrydockWorker {
protected function doWork() {
$resource_phid = $this->getTaskDataValue('resourcePHID');
$hash = PhabricatorHash::digestForIndex($resource_phid);
$lock_key = 'drydock.resource:'.$hash;
$lock = PhabricatorGlobalLock::newLock($lock_key)
->lock(1);
try {
$resource = $this->loadResource($resource_phid);
$this->handleUpdate($resource);
} catch (Exception $ex) {
$lock->unlock();
$this->flushDrydockTaskQueue();
throw $ex;
}
$lock->unlock();
}
/* -( Updating Resources )------------------------------------------------- */
/**
* Update a resource, handling exceptions thrown during the update.
*
* @param DrydockReosource Resource to update.
* @return void
* @task update
*/
private function handleUpdate(DrydockResource $resource) {
try {
$this->updateResource($resource);
} catch (Exception $ex) {
if ($this->isTemporaryException($ex)) {
$this->yieldResource($resource, $ex);
} else {
$this->breakResource($resource, $ex);
}
}
}
/**
* Update a resource.
*
* @param DrydockResource Resource to update.
* @return void
* @task update
*/
private function updateResource(DrydockResource $resource) {
$this->processResourceCommands($resource);
$resource_status = $resource->getStatus();
switch ($resource_status) {
case DrydockResourceStatus::STATUS_PENDING:
$this->activateResource($resource);
break;
case DrydockResourceStatus::STATUS_ACTIVE:
// Nothing to do.
break;
case DrydockResourceStatus::STATUS_RELEASED:
case DrydockResourceStatus::STATUS_BROKEN:
$this->destroyResource($resource);
break;
case DrydockResourceStatus::STATUS_DESTROYED:
// Nothing to do.
break;
}
$this->yieldIfExpiringResource($resource);
}
/**
* Convert a temporary exception into a yield.
*
* @param DrydockResource Resource to yield.
* @param Exception Temporary exception worker encountered.
* @task update
*/
private function yieldResource(DrydockResource $resource, Exception $ex) {
$duration = $this->getYieldDurationFromException($ex);
$resource->logEvent(
DrydockResourceActivationYieldLogType::LOGCONST,
array(
'duration' => $duration,
));
throw new PhabricatorWorkerYieldException($duration);
}
/* -( Processing Commands )------------------------------------------------ */
/**
* @task command
*/
private function processResourceCommands(DrydockResource $resource) {
if (!$resource->canReceiveCommands()) {
return;
}
$this->checkResourceExpiration($resource);
$commands = $this->loadCommands($resource->getPHID());
foreach ($commands as $command) {
if (!$resource->canReceiveCommands()) {
break;
}
$this->processResourceCommand($resource, $command);
$command
->setIsConsumed(true)
->save();
}
}
/**
* @task command
*/
private function processResourceCommand(
DrydockResource $resource,
DrydockCommand $command) {
switch ($command->getCommand()) {
case DrydockCommand::COMMAND_RELEASE:
$this->releaseResource($resource, null);
break;
case DrydockCommand::COMMAND_RECLAIM:
$reclaimer_phid = $command->getAuthorPHID();
$this->releaseResource($resource, $reclaimer_phid);
break;
}
// If the command specifies that other worker tasks should be awakened
// after it executes, awaken them now.
$awaken_ids = $command->getProperty('awakenTaskIDs');
if (is_array($awaken_ids) && $awaken_ids) {
PhabricatorWorker::awakenTaskIDs($awaken_ids);
}
}
/* -( Activating Resources )----------------------------------------------- */
/**
* @task activate
*/
private function activateResource(DrydockResource $resource) {
$blueprint = $resource->getBlueprint();
$blueprint->activateResource($resource);
$this->validateActivatedResource($blueprint, $resource);
$awaken_ids = $this->getTaskDataValue('awakenOnActivation');
if (is_array($awaken_ids) && $awaken_ids) {
PhabricatorWorker::awakenTaskIDs($awaken_ids);
}
}
/**
* @task activate
*/
private function validateActivatedResource(
DrydockBlueprint $blueprint,
DrydockResource $resource) {
if (!$resource->isActivatedResource()) {
throw new Exception(
pht(
'Blueprint "%s" (of type "%s") is not properly implemented: %s '.
'must actually allocate the resource it returns.',
$blueprint->getBlueprintName(),
$blueprint->getClassName(),
'allocateResource()'));
}
}
/* -( Releasing Resources )------------------------------------------------ */
/**
* @task release
*/
private function releaseResource(
DrydockResource $resource,
$reclaimer_phid) {
if ($reclaimer_phid) {
if (!$this->canReclaimResource($resource)) {
return;
}
$resource->logEvent(
DrydockResourceReclaimLogType::LOGCONST,
array(
'reclaimerPHID' => $reclaimer_phid,
));
}
$viewer = $this->getViewer();
$drydock_phid = id(new PhabricatorDrydockApplication())->getPHID();
$resource
->setStatus(DrydockResourceStatus::STATUS_RELEASED)
->save();
$statuses = array(
DrydockLeaseStatus::STATUS_PENDING,
DrydockLeaseStatus::STATUS_ACQUIRED,
DrydockLeaseStatus::STATUS_ACTIVE,
);
$leases = id(new DrydockLeaseQuery())
->setViewer($viewer)
->withResourcePHIDs(array($resource->getPHID()))
->withStatuses($statuses)
->execute();
foreach ($leases as $lease) {
$command = DrydockCommand::initializeNewCommand($viewer)
->setTargetPHID($lease->getPHID())
->setAuthorPHID($drydock_phid)
->setCommand(DrydockCommand::COMMAND_RELEASE)
->save();
$lease->scheduleUpdate();
}
$this->destroyResource($resource);
}
/* -( Breaking Resources )------------------------------------------------- */
/**
* @task break
*/
private function breakResource(DrydockResource $resource, Exception $ex) {
switch ($resource->getStatus()) {
case DrydockResourceStatus::STATUS_BROKEN:
case DrydockResourceStatus::STATUS_RELEASED:
case DrydockResourceStatus::STATUS_DESTROYED:
// If the resource was already broken, just throw a normal exception.
// This will retry the task eventually.
throw new PhutilProxyException(
pht(
'Unexpected failure while destroying resource ("%s").',
$resource->getPHID()),
$ex);
}
$resource
->setStatus(DrydockResourceStatus::STATUS_BROKEN)
->save();
$resource->scheduleUpdate();
$resource->logEvent(
DrydockResourceActivationFailureLogType::LOGCONST,
array(
'class' => get_class($ex),
'message' => $ex->getMessage(),
));
throw new PhabricatorWorkerPermanentFailureException(
pht(
'Permanent failure while activating resource ("%s"): %s',
$resource->getPHID(),
$ex->getMessage()));
}
/* -( Destroying Resources )----------------------------------------------- */
/**
* @task destroy
*/
private function destroyResource(DrydockResource $resource) {
$blueprint = $resource->getBlueprint();
$blueprint->destroyResource($resource);
DrydockSlotLock::releaseLocks($resource->getPHID());
$resource
->setStatus(DrydockResourceStatus::STATUS_DESTROYED)
->save();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockRepositoryOperationQuery.php | src/applications/drydock/query/DrydockRepositoryOperationQuery.php | <?php
final class DrydockRepositoryOperationQuery extends DrydockQuery {
private $ids;
private $phids;
private $objectPHIDs;
private $repositoryPHIDs;
private $operationStates;
private $operationTypes;
private $isDismissed;
private $authorPHIDs;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withObjectPHIDs(array $object_phids) {
$this->objectPHIDs = $object_phids;
return $this;
}
public function withRepositoryPHIDs(array $repository_phids) {
$this->repositoryPHIDs = $repository_phids;
return $this;
}
public function withOperationStates(array $states) {
$this->operationStates = $states;
return $this;
}
public function withOperationTypes(array $types) {
$this->operationTypes = $types;
return $this;
}
public function withIsDismissed($dismissed) {
$this->isDismissed = $dismissed;
return $this;
}
public function withAuthorPHIDs(array $phids) {
$this->authorPHIDs = $phids;
return $this;
}
public function newResultObject() {
return new DrydockRepositoryOperation();
}
protected function willFilterPage(array $operations) {
$implementations = DrydockRepositoryOperationType::getAllOperationTypes();
$viewer = $this->getViewer();
foreach ($operations as $key => $operation) {
$impl = idx($implementations, $operation->getOperationType());
if (!$impl) {
$this->didRejectResult($operation);
unset($operations[$key]);
continue;
}
$impl = id(clone $impl)
->setViewer($viewer)
->setOperation($operation);
$operation->attachImplementation($impl);
}
$repository_phids = mpull($operations, 'getRepositoryPHID');
if ($repository_phids) {
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withPHIDs($repository_phids)
->execute();
$repositories = mpull($repositories, null, 'getPHID');
} else {
$repositories = array();
}
foreach ($operations as $key => $operation) {
$repository = idx($repositories, $operation->getRepositoryPHID());
if (!$repository) {
$this->didRejectResult($operation);
unset($operations[$key]);
continue;
}
$operation->attachRepository($repository);
}
return $operations;
}
protected function didFilterPage(array $operations) {
$object_phids = mpull($operations, 'getObjectPHID');
if ($object_phids) {
$objects = id(new PhabricatorObjectQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withPHIDs($object_phids)
->execute();
$objects = mpull($objects, null, 'getPHID');
} else {
$objects = array();
}
foreach ($operations as $key => $operation) {
$object = idx($objects, $operation->getObjectPHID());
$operation->attachObject($object);
}
return $operations;
}
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->objectPHIDs !== null) {
$where[] = qsprintf(
$conn,
'objectPHID IN (%Ls)',
$this->objectPHIDs);
}
if ($this->repositoryPHIDs !== null) {
$where[] = qsprintf(
$conn,
'repositoryPHID IN (%Ls)',
$this->repositoryPHIDs);
}
if ($this->operationStates !== null) {
$where[] = qsprintf(
$conn,
'operationState IN (%Ls)',
$this->operationStates);
}
if ($this->operationTypes !== null) {
$where[] = qsprintf(
$conn,
'operationType IN (%Ls)',
$this->operationTypes);
}
if ($this->isDismissed !== null) {
$where[] = qsprintf(
$conn,
'isDismissed = %d',
(int)$this->isDismissed);
}
if ($this->authorPHIDs !== null) {
$where[] = qsprintf(
$conn,
'authorPHID IN (%Ls)',
$this->authorPHIDs);
}
return $where;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockAuthorizationSearchEngine.php | src/applications/drydock/query/DrydockAuthorizationSearchEngine.php | <?php
final class DrydockAuthorizationSearchEngine
extends PhabricatorApplicationSearchEngine {
private $blueprint;
public function setBlueprint(DrydockBlueprint $blueprint) {
$this->blueprint = $blueprint;
return $this;
}
public function getBlueprint() {
return $this->blueprint;
}
public function getResultTypeDescription() {
return pht('Drydock Authorizations');
}
public function getApplicationClassName() {
return 'PhabricatorDrydockApplication';
}
public function canUseInPanelContext() {
return false;
}
public function newQuery() {
$query = new DrydockAuthorizationQuery();
$blueprint = $this->getBlueprint();
if ($blueprint) {
$query->withBlueprintPHIDs(array($blueprint->getPHID()));
}
return $query;
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['blueprintPHIDs']) {
$query->withBlueprintPHIDs($map['blueprintPHIDs']);
}
if ($map['objectPHIDs']) {
$query->withObjectPHIDs($map['objectPHIDs']);
}
return $query;
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorSearchDatasourceField())
->setLabel(pht('Blueprints'))
->setKey('blueprintPHIDs')
->setConduitParameterType(new ConduitPHIDListParameterType())
->setDescription(pht('Search authorizations for specific blueprints.'))
->setAliases(array('blueprint', 'blueprints'))
->setDatasource(new DrydockBlueprintDatasource()),
id(new PhabricatorPHIDsSearchField())
->setLabel(pht('Objects'))
->setKey('objectPHIDs')
->setDescription(pht('Search authorizations from specific objects.'))
->setAliases(array('object', 'objects')),
);
}
protected function getHiddenFields() {
return array(
'blueprintPHIDs',
'objectPHIDs',
);
}
protected function getURI($path) {
$blueprint = $this->getBlueprint();
if (!$blueprint) {
throw new PhutilInvalidStateException('setBlueprint');
}
$id = $blueprint->getID();
return "/drydock/blueprint/{$id}/authorizations/".$path;
}
protected function getBuiltinQueryNames() {
return array(
'all' => pht('All Authorizations'),
);
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $authorizations,
PhabricatorSavedQuery $query,
array $handles) {
$list = id(new DrydockAuthorizationListView())
->setUser($this->requireViewer())
->setAuthorizations($authorizations);
$result = new PhabricatorApplicationSearchResultView();
$result->setTable($list);
return $result;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockResourceSearchEngine.php | src/applications/drydock/query/DrydockResourceSearchEngine.php | <?php
final class DrydockResourceSearchEngine
extends PhabricatorApplicationSearchEngine {
private $blueprint;
public function setBlueprint(DrydockBlueprint $blueprint) {
$this->blueprint = $blueprint;
return $this;
}
public function getBlueprint() {
return $this->blueprint;
}
public function getResultTypeDescription() {
return pht('Drydock Resources');
}
public function getApplicationClassName() {
return 'PhabricatorDrydockApplication';
}
public function newQuery() {
$query = new DrydockResourceQuery();
$blueprint = $this->getBlueprint();
if ($blueprint) {
$query->withBlueprintPHIDs(array($blueprint->getPHID()));
}
return $query;
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['statuses']) {
$query->withStatuses($map['statuses']);
}
if ($map['blueprintPHIDs']) {
$query->withBlueprintPHIDs($map['blueprintPHIDs']);
}
return $query;
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorSearchCheckboxesField())
->setLabel(pht('Statuses'))
->setKey('statuses')
->setOptions(DrydockResourceStatus::getStatusMap()),
id(new PhabricatorPHIDsSearchField())
->setLabel(pht('Blueprints'))
->setKey('blueprintPHIDs')
->setAliases(array('blueprintPHID', 'blueprints', 'blueprint'))
->setDescription(
pht('Search for resources generated by particular blueprints.')),
);
}
protected function getURI($path) {
$blueprint = $this->getBlueprint();
if ($blueprint) {
$id = $blueprint->getID();
return "/drydock/blueprint/{$id}/resources/".$path;
} else {
return '/drydock/resource/'.$path;
}
}
protected function getBuiltinQueryNames() {
return array(
'active' => pht('Active Resources'),
'all' => pht('All Resources'),
);
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'active':
return $query->setParameter(
'statuses',
array(
DrydockResourceStatus::STATUS_PENDING,
DrydockResourceStatus::STATUS_ACTIVE,
));
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $resources,
PhabricatorSavedQuery $query,
array $handles) {
$list = id(new DrydockResourceListView())
->setUser($this->requireViewer())
->setResources($resources);
$result = new PhabricatorApplicationSearchResultView();
$result->setTable($list);
return $result;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockLogSearchEngine.php | src/applications/drydock/query/DrydockLogSearchEngine.php | <?php
final class DrydockLogSearchEngine extends PhabricatorApplicationSearchEngine {
private $blueprint;
private $resource;
private $lease;
private $operation;
public function setBlueprint(DrydockBlueprint $blueprint) {
$this->blueprint = $blueprint;
return $this;
}
public function getBlueprint() {
return $this->blueprint;
}
public function setResource(DrydockResource $resource) {
$this->resource = $resource;
return $this;
}
public function getResource() {
return $this->resource;
}
public function setLease(DrydockLease $lease) {
$this->lease = $lease;
return $this;
}
public function getLease() {
return $this->lease;
}
public function setOperation(DrydockRepositoryOperation $operation) {
$this->operation = $operation;
return $this;
}
public function getOperation() {
return $this->operation;
}
public function canUseInPanelContext() {
// Prevent use on Dashboard panels since all log queries currently need a
// parent object and these don't seem particularly useful in any case.
return false;
}
public function getResultTypeDescription() {
return pht('Drydock Logs');
}
public function getApplicationClassName() {
return 'PhabricatorDrydockApplication';
}
public function newQuery() {
$query = new DrydockLogQuery();
$blueprint = $this->getBlueprint();
if ($blueprint) {
$query->withBlueprintPHIDs(array($blueprint->getPHID()));
}
$resource = $this->getResource();
if ($resource) {
$query->withResourcePHIDs(array($resource->getPHID()));
}
$lease = $this->getLease();
if ($lease) {
$query->withLeasePHIDs(array($lease->getPHID()));
}
$operation = $this->getOperation();
if ($operation) {
$query->withOperationPHIDs(array($operation->getPHID()));
}
return $query;
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
return $query;
}
protected function buildCustomSearchFields() {
return array();
}
protected function getURI($path) {
$blueprint = $this->getBlueprint();
if ($blueprint) {
$id = $blueprint->getID();
return "/drydock/blueprint/{$id}/logs/{$path}";
}
$resource = $this->getResource();
if ($resource) {
$id = $resource->getID();
return "/drydock/resource/{$id}/logs/{$path}";
}
$lease = $this->getLease();
if ($lease) {
$id = $lease->getID();
return "/drydock/lease/{$id}/logs/{$path}";
}
$operation = $this->getOperation();
if ($operation) {
$id = $operation->getID();
return "/drydock/operation/{$id}/logs/{$path}";
}
throw new Exception(
pht(
'Search engine has no blueprint, resource, lease, or operation.'));
}
protected function getBuiltinQueryNames() {
return array(
'all' => pht('All Logs'),
);
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $logs,
PhabricatorSavedQuery $query,
array $handles) {
$list = id(new DrydockLogListView())
->setUser($this->requireViewer())
->setLogs($logs);
$result = new PhabricatorApplicationSearchResultView();
$result->setTable($list);
return $result;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockAuthorizationQuery.php | src/applications/drydock/query/DrydockAuthorizationQuery.php | <?php
final class DrydockAuthorizationQuery extends DrydockQuery {
private $ids;
private $phids;
private $blueprintPHIDs;
private $objectPHIDs;
private $blueprintStates;
private $objectStates;
public static function isFullyAuthorized(
$object_phid,
array $blueprint_phids) {
if (!$blueprint_phids) {
return true;
}
$authorizations = id(new self())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withObjectPHIDs(array($object_phid))
->withBlueprintPHIDs($blueprint_phids)
->execute();
$authorizations = mpull($authorizations, null, 'getBlueprintPHID');
foreach ($blueprint_phids as $phid) {
$authorization = idx($authorizations, $phid);
if (!$authorization) {
return false;
}
if (!$authorization->isAuthorized()) {
return false;
}
}
return true;
}
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withBlueprintPHIDs(array $phids) {
$this->blueprintPHIDs = $phids;
return $this;
}
public function withObjectPHIDs(array $phids) {
$this->objectPHIDs = $phids;
return $this;
}
public function withBlueprintStates(array $states) {
$this->blueprintStates = $states;
return $this;
}
public function withObjectStates(array $states) {
$this->objectStates = $states;
return $this;
}
public function newResultObject() {
return new DrydockAuthorization();
}
protected function willFilterPage(array $authorizations) {
$blueprint_phids = mpull($authorizations, 'getBlueprintPHID');
if ($blueprint_phids) {
$blueprints = id(new DrydockBlueprintQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withPHIDs($blueprint_phids)
->execute();
$blueprints = mpull($blueprints, null, 'getPHID');
} else {
$blueprints = array();
}
foreach ($authorizations as $key => $authorization) {
$blueprint = idx($blueprints, $authorization->getBlueprintPHID());
if (!$blueprint) {
$this->didRejectResult($authorization);
unset($authorizations[$key]);
continue;
}
$authorization->attachBlueprint($blueprint);
}
$object_phids = mpull($authorizations, 'getObjectPHID');
if ($object_phids) {
$objects = id(new PhabricatorObjectQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withPHIDs($object_phids)
->execute();
$objects = mpull($objects, null, 'getPHID');
} else {
$objects = array();
}
foreach ($authorizations as $key => $authorization) {
$object = idx($objects, $authorization->getObjectPHID());
if (!$object) {
$this->didRejectResult($authorization);
unset($authorizations[$key]);
continue;
}
$authorization->attachObject($object);
}
return $authorizations;
}
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->blueprintPHIDs !== null) {
$where[] = qsprintf(
$conn,
'blueprintPHID IN (%Ls)',
$this->blueprintPHIDs);
}
if ($this->objectPHIDs !== null) {
$where[] = qsprintf(
$conn,
'objectPHID IN (%Ls)',
$this->objectPHIDs);
}
if ($this->blueprintStates !== null) {
$where[] = qsprintf(
$conn,
'blueprintAuthorizationState IN (%Ls)',
$this->blueprintStates);
}
if ($this->objectStates !== null) {
$where[] = qsprintf(
$conn,
'objectAuthorizationState IN (%Ls)',
$this->objectStates);
}
return $where;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockRepositoryOperationSearchEngine.php | src/applications/drydock/query/DrydockRepositoryOperationSearchEngine.php | <?php
final class DrydockRepositoryOperationSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Drydock Repository Operations');
}
public function getApplicationClassName() {
return 'PhabricatorDrydockApplication';
}
public function newQuery() {
return id(new DrydockRepositoryOperationQuery());
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['repositoryPHIDs']) {
$query->withRepositoryPHIDs($map['repositoryPHIDs']);
}
if ($map['authorPHIDs']) {
$query->withAuthorPHIDs($map['authorPHIDs']);
}
if ($map['states']) {
$query->withOperationStates($map['states']);
}
return $query;
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorSearchDatasourceField())
->setLabel(pht('Repositories'))
->setKey('repositoryPHIDs')
->setAliases(array('repository', 'repositories', 'repositoryPHID'))
->setDatasource(new DiffusionRepositoryFunctionDatasource()),
// NOTE: Repository operations aren't necessarily created by a real
// user, but for now they normally are. Just use a user typeahead until
// more use cases arise.
id(new PhabricatorUsersSearchField())
->setLabel(pht('Authors'))
->setKey('authorPHIDs')
->setAliases(array('author', 'authors', 'authorPHID')),
id(new PhabricatorSearchCheckboxesField())
->setLabel(pht('States'))
->setKey('states')
->setAliases(array('state'))
->setOptions(DrydockRepositoryOperation::getOperationStateNameMap()),
);
}
protected function getURI($path) {
return '/drydock/operation/'.$path;
}
protected function getBuiltinQueryNames() {
return array(
'all' => pht('All Operations'),
);
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $operations,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($operations, 'DrydockRepositoryOperation');
$viewer = $this->requireViewer();
$view = new PHUIObjectItemListView();
foreach ($operations as $operation) {
$id = $operation->getID();
$item = id(new PHUIObjectItemView())
->setHeader($operation->getOperationDescription($viewer))
->setHref($this->getApplicationURI("operation/{$id}/"))
->setObjectName(pht('Repository Operation %d', $id));
$state = $operation->getOperationState();
$icon = DrydockRepositoryOperation::getOperationStateIcon($state);
$name = DrydockRepositoryOperation::getOperationStateName($state);
$item->setStatusIcon($icon, $name);
$created = phabricator_datetime($operation->getDateCreated(), $viewer);
$item->addIcon(null, $created);
$item->addByline(
array(
pht('Via:'),
' ',
$viewer->renderHandle($operation->getAuthorPHID()),
));
$object_phid = $operation->getObjectPHID();
$repository_phid = $operation->getRepositoryPHID();
$item->addAttribute($viewer->renderHandle($object_phid));
if ($repository_phid !== $object_phid) {
$item->addAttribute($viewer->renderHandle($repository_phid));
}
$view->addItem($item);
}
$result = id(new PhabricatorApplicationSearchResultView())
->setObjectList($view)
->setNoDataString(pht('No matching operations.'));
return $result;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockLogQuery.php | src/applications/drydock/query/DrydockLogQuery.php | <?php
final class DrydockLogQuery extends DrydockQuery {
private $ids;
private $blueprintPHIDs;
private $resourcePHIDs;
private $leasePHIDs;
private $operationPHIDs;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withBlueprintPHIDs(array $phids) {
$this->blueprintPHIDs = $phids;
return $this;
}
public function withResourcePHIDs(array $phids) {
$this->resourcePHIDs = $phids;
return $this;
}
public function withLeasePHIDs(array $phids) {
$this->leasePHIDs = $phids;
return $this;
}
public function withOperationPHIDs(array $phids) {
$this->operationPHIDs = $phids;
return $this;
}
public function newResultObject() {
return new DrydockLog();
}
protected function didFilterPage(array $logs) {
$blueprint_phids = array_filter(mpull($logs, 'getBlueprintPHID'));
if ($blueprint_phids) {
$blueprints = id(new DrydockBlueprintQuery())
->setParentQuery($this)
->setViewer($this->getViewer())
->withPHIDs($blueprint_phids)
->execute();
$blueprints = mpull($blueprints, null, 'getPHID');
} else {
$blueprints = array();
}
foreach ($logs as $key => $log) {
$blueprint = null;
$blueprint_phid = $log->getBlueprintPHID();
if ($blueprint_phid) {
$blueprint = idx($blueprints, $blueprint_phid);
}
$log->attachBlueprint($blueprint);
}
$resource_phids = array_filter(mpull($logs, 'getResourcePHID'));
if ($resource_phids) {
$resources = id(new DrydockResourceQuery())
->setParentQuery($this)
->setViewer($this->getViewer())
->withPHIDs($resource_phids)
->execute();
$resources = mpull($resources, null, 'getPHID');
} else {
$resources = array();
}
foreach ($logs as $key => $log) {
$resource = null;
$resource_phid = $log->getResourcePHID();
if ($resource_phid) {
$resource = idx($resources, $resource_phid);
}
$log->attachResource($resource);
}
$lease_phids = array_filter(mpull($logs, 'getLeasePHID'));
if ($lease_phids) {
$leases = id(new DrydockLeaseQuery())
->setParentQuery($this)
->setViewer($this->getViewer())
->withPHIDs($lease_phids)
->execute();
$leases = mpull($leases, null, 'getPHID');
} else {
$leases = array();
}
foreach ($logs as $key => $log) {
$lease = null;
$lease_phid = $log->getLeasePHID();
if ($lease_phid) {
$lease = idx($leases, $lease_phid);
}
$log->attachLease($lease);
}
$operation_phids = array_filter(mpull($logs, 'getOperationPHID'));
if ($operation_phids) {
$operations = id(new DrydockRepositoryOperationQuery())
->setParentQuery($this)
->setViewer($this->getViewer())
->withPHIDs($operation_phids)
->execute();
$operations = mpull($operations, null, 'getPHID');
} else {
$operations = array();
}
foreach ($logs as $key => $log) {
$operation = null;
$operation_phid = $log->getOperationPHID();
if ($operation_phid) {
$operation = idx($operations, $operation_phid);
}
$log->attachOperation($operation);
}
return $logs;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ls)',
$this->ids);
}
if ($this->blueprintPHIDs !== null) {
$where[] = qsprintf(
$conn,
'blueprintPHID IN (%Ls)',
$this->blueprintPHIDs);
}
if ($this->resourcePHIDs !== null) {
$where[] = qsprintf(
$conn,
'resourcePHID IN (%Ls)',
$this->resourcePHIDs);
}
if ($this->leasePHIDs !== null) {
$where[] = qsprintf(
$conn,
'leasePHID IN (%Ls)',
$this->leasePHIDs);
}
if ($this->operationPHIDs !== null) {
$where[] = qsprintf(
$conn,
'operationPHID IN (%Ls)',
$this->operationPHIDs);
}
return $where;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockQuery.php | src/applications/drydock/query/DrydockQuery.php | <?php
abstract class DrydockQuery extends PhabricatorCursorPagedPolicyAwareQuery {
public function getQueryApplicationClass() {
return 'PhabricatorDrydockApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockCommandQuery.php | src/applications/drydock/query/DrydockCommandQuery.php | <?php
final class DrydockCommandQuery extends DrydockQuery {
private $ids;
private $targetPHIDs;
private $consumed;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withTargetPHIDs(array $phids) {
$this->targetPHIDs = $phids;
return $this;
}
public function withConsumed($consumed) {
$this->consumed = $consumed;
return $this;
}
public function newResultObject() {
return new DrydockCommand();
}
protected function willFilterPage(array $commands) {
$target_phids = mpull($commands, 'getTargetPHID');
$targets = id(new PhabricatorObjectQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withPHIDs($target_phids)
->execute();
$targets = mpull($targets, null, 'getPHID');
foreach ($commands as $key => $command) {
$target = idx($targets, $command->getTargetPHID());
if (!$target) {
$this->didRejectResult($command);
unset($commands[$key]);
continue;
}
$command->attachCommandTarget($target);
}
return $commands;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->targetPHIDs !== null) {
$where[] = qsprintf(
$conn,
'targetPHID IN (%Ls)',
$this->targetPHIDs);
}
if ($this->consumed !== null) {
$where[] = qsprintf(
$conn,
'isConsumed = %d',
(int)$this->consumed);
}
return $where;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockResourceQuery.php | src/applications/drydock/query/DrydockResourceQuery.php | <?php
final class DrydockResourceQuery extends DrydockQuery {
private $ids;
private $phids;
private $statuses;
private $types;
private $blueprintPHIDs;
private $datasourceQuery;
private $needUnconsumedCommands;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withTypes(array $types) {
$this->types = $types;
return $this;
}
public function withStatuses(array $statuses) {
$this->statuses = $statuses;
return $this;
}
public function withBlueprintPHIDs(array $blueprint_phids) {
$this->blueprintPHIDs = $blueprint_phids;
return $this;
}
public function withDatasourceQuery($query) {
$this->datasourceQuery = $query;
return $this;
}
public function needUnconsumedCommands($need) {
$this->needUnconsumedCommands = $need;
return $this;
}
public function newResultObject() {
return new DrydockResource();
}
protected function willFilterPage(array $resources) {
$blueprint_phids = mpull($resources, 'getBlueprintPHID');
$blueprints = id(new DrydockBlueprintQuery())
->setViewer($this->getViewer())
->withPHIDs($blueprint_phids)
->execute();
$blueprints = mpull($blueprints, null, 'getPHID');
foreach ($resources as $key => $resource) {
$blueprint = idx($blueprints, $resource->getBlueprintPHID());
if (!$blueprint) {
$this->didRejectResult($resource);
unset($resources[$key]);
continue;
}
$resource->attachBlueprint($blueprint);
}
return $resources;
}
protected function didFilterPage(array $resources) {
if ($this->needUnconsumedCommands) {
$commands = id(new DrydockCommandQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withTargetPHIDs(mpull($resources, 'getPHID'))
->withConsumed(false)
->execute();
$commands = mgroup($commands, 'getTargetPHID');
foreach ($resources as $resource) {
$list = idx($commands, $resource->getPHID(), array());
$resource->attachUnconsumedCommands($list);
}
}
return $resources;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'resource.id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'resource.phid IN (%Ls)',
$this->phids);
}
if ($this->types !== null) {
$where[] = qsprintf(
$conn,
'resource.type IN (%Ls)',
$this->types);
}
if ($this->statuses !== null) {
$where[] = qsprintf(
$conn,
'resource.status IN (%Ls)',
$this->statuses);
}
if ($this->blueprintPHIDs !== null) {
$where[] = qsprintf(
$conn,
'resource.blueprintPHID IN (%Ls)',
$this->blueprintPHIDs);
}
if ($this->datasourceQuery !== null) {
$where[] = qsprintf(
$conn,
'resource.name LIKE %>',
$this->datasourceQuery);
}
return $where;
}
protected function getPrimaryTableAlias() {
return 'resource';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockLeaseQuery.php | src/applications/drydock/query/DrydockLeaseQuery.php | <?php
final class DrydockLeaseQuery extends DrydockQuery {
private $ids;
private $phids;
private $resourcePHIDs;
private $ownerPHIDs;
private $statuses;
private $datasourceQuery;
private $needUnconsumedCommands;
private $minModified;
private $maxModified;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withResourcePHIDs(array $phids) {
$this->resourcePHIDs = $phids;
return $this;
}
public function withOwnerPHIDs(array $phids) {
$this->ownerPHIDs = $phids;
return $this;
}
public function withStatuses(array $statuses) {
$this->statuses = $statuses;
return $this;
}
public function withDatasourceQuery($query) {
$this->datasourceQuery = $query;
return $this;
}
public function withDateModifiedBetween($min_epoch, $max_epoch) {
$this->minModified = $min_epoch;
$this->maxModified = $max_epoch;
return $this;
}
public function needUnconsumedCommands($need) {
$this->needUnconsumedCommands = $need;
return $this;
}
public function newResultObject() {
return new DrydockLease();
}
protected function willFilterPage(array $leases) {
$resource_phids = array_filter(mpull($leases, 'getResourcePHID'));
if ($resource_phids) {
$resources = id(new DrydockResourceQuery())
->setParentQuery($this)
->setViewer($this->getViewer())
->withPHIDs(array_unique($resource_phids))
->execute();
$resources = mpull($resources, null, 'getPHID');
} else {
$resources = array();
}
foreach ($leases as $key => $lease) {
$resource = null;
if ($lease->getResourcePHID()) {
$resource = idx($resources, $lease->getResourcePHID());
if (!$resource) {
$this->didRejectResult($lease);
unset($leases[$key]);
continue;
}
}
$lease->attachResource($resource);
}
return $leases;
}
protected function didFilterPage(array $leases) {
if ($this->needUnconsumedCommands) {
$commands = id(new DrydockCommandQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withTargetPHIDs(mpull($leases, 'getPHID'))
->withConsumed(false)
->execute();
$commands = mgroup($commands, 'getTargetPHID');
foreach ($leases as $lease) {
$list = idx($commands, $lease->getPHID(), array());
$lease->attachUnconsumedCommands($list);
}
}
return $leases;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->resourcePHIDs !== null) {
$where[] = qsprintf(
$conn,
'resourcePHID IN (%Ls)',
$this->resourcePHIDs);
}
if ($this->ownerPHIDs !== null) {
$where[] = qsprintf(
$conn,
'ownerPHID IN (%Ls)',
$this->ownerPHIDs);
}
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->statuses !== null) {
$where[] = qsprintf(
$conn,
'status IN (%Ls)',
$this->statuses);
}
if ($this->datasourceQuery !== null) {
$where[] = qsprintf(
$conn,
'id = %d',
(int)$this->datasourceQuery);
}
if ($this->minModified !== null) {
$where[] = qsprintf(
$conn,
'dateModified >= %d',
$this->minModified);
}
if ($this->maxModified !== null) {
$where[] = qsprintf(
$conn,
'dateModified <= %d',
$this->maxModified);
}
return $where;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockBlueprintQuery.php | src/applications/drydock/query/DrydockBlueprintQuery.php | <?php
final class DrydockBlueprintQuery extends DrydockQuery {
private $ids;
private $phids;
private $blueprintClasses;
private $datasourceQuery;
private $disabled;
private $authorizedPHIDs;
private $identifiers;
private $identifierIDs;
private $identifierPHIDs;
private $identifierMap;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withBlueprintClasses(array $classes) {
$this->blueprintClasses = $classes;
return $this;
}
public function withDatasourceQuery($query) {
$this->datasourceQuery = $query;
return $this;
}
public function withDisabled($disabled) {
$this->disabled = $disabled;
return $this;
}
public function withAuthorizedPHIDs(array $phids) {
$this->authorizedPHIDs = $phids;
return $this;
}
public function withNameNgrams($ngrams) {
return $this->withNgramsConstraint(
new DrydockBlueprintNameNgrams(),
$ngrams);
}
public function withIdentifiers(array $identifiers) {
if (!$identifiers) {
throw new Exception(
pht(
'Can not issue a query with an empty identifier list.'));
}
$this->identifiers = $identifiers;
$ids = array();
$phids = array();
foreach ($identifiers as $identifier) {
if (ctype_digit($identifier)) {
$ids[] = $identifier;
} else {
$phids[] = $identifier;
}
}
$this->identifierIDs = $ids;
$this->identifierPHIDs = $phids;
return $this;
}
public function getIdentifierMap() {
if ($this->identifierMap === null) {
throw new Exception(
pht(
'Execute a query with identifiers before getting the '.
'identifier map.'));
}
return $this->identifierMap;
}
public function newResultObject() {
return new DrydockBlueprint();
}
protected function getPrimaryTableAlias() {
return 'blueprint';
}
protected function willExecute() {
if ($this->identifiers) {
$this->identifierMap = array();
} else {
$this->identifierMap = null;
}
}
protected function willFilterPage(array $blueprints) {
$impls = DrydockBlueprintImplementation::getAllBlueprintImplementations();
foreach ($blueprints as $key => $blueprint) {
$impl = idx($impls, $blueprint->getClassName());
if (!$impl) {
$this->didRejectResult($blueprint);
unset($blueprints[$key]);
continue;
}
$impl = clone $impl;
$blueprint->attachImplementation($impl);
}
if ($this->identifiers) {
$id_map = mpull($blueprints, null, 'getID');
$phid_map = mpull($blueprints, null, 'getPHID');
$map = $this->identifierMap;
foreach ($this->identifierIDs as $id) {
if (isset($id_map[$id])) {
$map[$id] = $id_map[$id];
}
}
foreach ($this->identifierPHIDs as $phid) {
if (isset($phid_map[$phid])) {
$map[$phid] = $phid_map[$phid];
}
}
// Just for consistency, reorder the map to match input order.
$map = array_select_keys($map, $this->identifiers);
$this->identifierMap = $map;
}
return $blueprints;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'blueprint.id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'blueprint.phid IN (%Ls)',
$this->phids);
}
if ($this->datasourceQuery !== null) {
$where[] = qsprintf(
$conn,
'blueprint.blueprintName LIKE %>',
$this->datasourceQuery);
}
if ($this->blueprintClasses !== null) {
$where[] = qsprintf(
$conn,
'blueprint.className IN (%Ls)',
$this->blueprintClasses);
}
if ($this->disabled !== null) {
$where[] = qsprintf(
$conn,
'blueprint.isDisabled = %d',
(int)$this->disabled);
}
if ($this->identifiers !== null) {
$parts = array();
if ($this->identifierIDs) {
$parts[] = qsprintf(
$conn,
'blueprint.id IN (%Ld)',
$this->identifierIDs);
}
if ($this->identifierPHIDs) {
$parts[] = qsprintf(
$conn,
'blueprint.phid IN (%Ls)',
$this->identifierPHIDs);
}
$where[] = qsprintf(
$conn,
'%LO',
$parts);
}
return $where;
}
protected function shouldGroupQueryResultRows() {
if ($this->authorizedPHIDs !== null) {
return true;
}
return parent::shouldGroupQueryResultRows();
}
protected function buildJoinClauseParts(AphrontDatabaseConnection $conn) {
$joins = parent::buildJoinClauseParts($conn);
if ($this->authorizedPHIDs !== null) {
$joins[] = qsprintf(
$conn,
'JOIN %T authorization
ON authorization.blueprintPHID = blueprint.phid
AND authorization.objectPHID IN (%Ls)
AND authorization.objectAuthorizationState = %s
AND authorization.blueprintAuthorizationState = %s',
id(new DrydockAuthorization())->getTableName(),
$this->authorizedPHIDs,
DrydockAuthorization::OBJECTAUTH_ACTIVE,
DrydockAuthorization::BLUEPRINTAUTH_AUTHORIZED);
}
return $joins;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockLeaseSearchEngine.php | src/applications/drydock/query/DrydockLeaseSearchEngine.php | <?php
final class DrydockLeaseSearchEngine
extends PhabricatorApplicationSearchEngine {
private $resource;
public function setResource($resource) {
$this->resource = $resource;
return $this;
}
public function getResource() {
return $this->resource;
}
public function getResultTypeDescription() {
return pht('Drydock Leases');
}
public function getApplicationClassName() {
return 'PhabricatorDrydockApplication';
}
public function newQuery() {
$query = new DrydockLeaseQuery();
$resource = $this->getResource();
if ($resource) {
$query->withResourcePHIDs(array($resource->getPHID()));
}
return $query;
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['statuses']) {
$query->withStatuses($map['statuses']);
}
if ($map['ownerPHIDs']) {
$query->withOwnerPHIDs($map['ownerPHIDs']);
}
if ($map['resourcePHIDs']) {
$query->withResourcePHIDs($map['resourcePHIDs']);
}
return $query;
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorSearchCheckboxesField())
->setLabel(pht('Statuses'))
->setKey('statuses')
->setOptions(DrydockLeaseStatus::getStatusMap()),
id(new PhabricatorPHIDsSearchField())
->setLabel(pht('Owners'))
->setKey('ownerPHIDs')
->setAliases(array('owner', 'owners', 'ownerPHID'))
->setDescription(pht('Search leases by owner.')),
id(new PhabricatorPHIDsSearchField())
->setLabel(pht('Resources'))
->setKey('resourcePHIDs')
->setAliases(array('resorucePHID', 'resource', 'resources'))
->setDescription(pht('Search leases by resource.')),
);
}
protected function getURI($path) {
$resource = $this->getResource();
if ($resource) {
$id = $resource->getID();
return "/drydock/resource/{$id}/leases/".$path;
} else {
return '/drydock/lease/'.$path;
}
}
protected function getBuiltinQueryNames() {
return array(
'active' => pht('Active Leases'),
'all' => pht('All Leases'),
);
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'active':
return $query->setParameter(
'statuses',
array(
DrydockLeaseStatus::STATUS_PENDING,
DrydockLeaseStatus::STATUS_ACQUIRED,
DrydockLeaseStatus::STATUS_ACTIVE,
));
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $leases,
PhabricatorSavedQuery $saved,
array $handles) {
$list = id(new DrydockLeaseListView())
->setUser($this->requireViewer())
->setLeases($leases);
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/applications/drydock/query/DrydockBlueprintSearchEngine.php | src/applications/drydock/query/DrydockBlueprintSearchEngine.php | <?php
final class DrydockBlueprintSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Drydock Blueprints');
}
public function getApplicationClassName() {
return 'PhabricatorDrydockApplication';
}
public function newQuery() {
return id(new DrydockBlueprintQuery());
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['match'] !== null) {
$query->withNameNgrams($map['match']);
}
if ($map['isDisabled'] !== null) {
$query->withDisabled($map['isDisabled']);
}
return $query;
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorSearchTextField())
->setLabel(pht('Name Contains'))
->setKey('match')
->setDescription(pht('Search for blueprints by name substring.')),
id(new PhabricatorSearchThreeStateField())
->setLabel(pht('Disabled'))
->setKey('isDisabled')
->setOptions(
pht('(Show All)'),
pht('Show Only Disabled Blueprints'),
pht('Hide Disabled Blueprints')),
);
}
protected function getURI($path) {
return '/drydock/blueprint/'.$path;
}
protected function getBuiltinQueryNames() {
return array(
'active' => pht('Active Blueprints'),
'all' => pht('All Blueprints'),
);
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'active':
return $query->setParameter('isDisabled', false);
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $blueprints,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($blueprints, 'DrydockBlueprint');
$viewer = $this->requireViewer();
if ($blueprints) {
$edge_query = id(new PhabricatorEdgeQuery())
->withSourcePHIDs(mpull($blueprints, 'getPHID'))
->withEdgeTypes(
array(
PhabricatorProjectObjectHasProjectEdgeType::EDGECONST,
));
$edge_query->execute();
}
$view = new PHUIObjectItemListView();
foreach ($blueprints as $blueprint) {
$impl = $blueprint->getImplementation();
$item = id(new PHUIObjectItemView())
->setHeader($blueprint->getBlueprintName())
->setHref($blueprint->getURI())
->setObjectName(pht('Blueprint %d', $blueprint->getID()));
if (!$impl->isEnabled()) {
$item->setDisabled(true);
$item->addIcon('fa-chain-broken grey', pht('Implementation'));
}
if ($blueprint->getIsDisabled()) {
$item->setDisabled(true);
$item->addIcon('fa-ban grey', pht('Disabled'));
}
$impl_icon = $impl->getBlueprintIcon();
$impl_name = $impl->getBlueprintName();
$impl_icon = id(new PHUIIconView())
->setIcon($impl_icon, 'lightgreytext');
$item->addAttribute(array($impl_icon, ' ', $impl_name));
$phid = $blueprint->getPHID();
$project_phids = $edge_query->getDestinationPHIDs(array($phid));
if ($project_phids) {
$project_handles = $viewer->loadHandles($project_phids);
$item->addAttribute(
id(new PHUIHandleTagListView())
->setLimit(4)
->setSlim(true)
->setHandles($project_handles));
}
$view->addItem($item);
}
$result = new PhabricatorApplicationSearchResultView();
$result->setObjectList($view);
$result->setNoDataString(pht('No blueprints found.'));
return $result;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/query/DrydockBlueprintTransactionQuery.php | src/applications/drydock/query/DrydockBlueprintTransactionQuery.php | <?php
final class DrydockBlueprintTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new DrydockBlueprintTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/interface/DrydockInterface.php | src/applications/drydock/interface/DrydockInterface.php | <?php
abstract class DrydockInterface extends Phobject {
private $config = array();
abstract public function getInterfaceType();
final public function setConfig($key, $value) {
$this->config[$key] = $value;
return $this;
}
final protected function getConfig($key, $default = null) {
return idx($this->config, $key, $default);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/interface/webroot/DrydockWebrootInterface.php | src/applications/drydock/interface/webroot/DrydockWebrootInterface.php | <?php
abstract class DrydockWebrootInterface extends DrydockInterface {
final public function getInterfaceType() {
return 'webroot';
}
abstract public function getURI();
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/interface/webroot/DrydockApacheWebrootInterface.php | src/applications/drydock/interface/webroot/DrydockApacheWebrootInterface.php | <?php
final class DrydockApacheWebrootInterface extends DrydockWebrootInterface {
public function getURI() {
return $this->getConfig('uri');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/interface/command/DrydockCommandInterface.php | src/applications/drydock/interface/command/DrydockCommandInterface.php | <?php
abstract class DrydockCommandInterface extends DrydockInterface {
const INTERFACE_TYPE = 'command';
private $workingDirectoryStack = array();
public function pushWorkingDirectory($working_directory) {
$this->workingDirectoryStack[] = $working_directory;
return $this;
}
public function popWorkingDirectory() {
if (!$this->workingDirectoryStack) {
throw new Exception(
pht(
'Unable to pop working directory, directory stack is empty.'));
}
return array_pop($this->workingDirectoryStack);
}
public function peekWorkingDirectory() {
if ($this->workingDirectoryStack) {
return last($this->workingDirectoryStack);
}
return null;
}
final public function getInterfaceType() {
return self::INTERFACE_TYPE;
}
final public function exec($command) {
$argv = func_get_args();
$exec = call_user_func_array(
array($this, 'getExecFuture'),
$argv);
return $exec->resolve();
}
final public function execx($command) {
$argv = func_get_args();
$exec = call_user_func_array(
array($this, 'getExecFuture'),
$argv);
return $exec->resolvex();
}
abstract public function getExecFuture($command);
protected function applyWorkingDirectoryToArgv(array $argv) {
$directory = $this->peekWorkingDirectory();
if ($directory !== null) {
$cmd = $argv[0];
$cmd = "(cd %s && {$cmd})";
$argv = array_merge(
array($cmd),
array($directory),
array_slice($argv, 1));
}
return $argv;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/interface/command/DrydockSSHCommandInterface.php | src/applications/drydock/interface/command/DrydockSSHCommandInterface.php | <?php
final class DrydockSSHCommandInterface extends DrydockCommandInterface {
private $credential;
private $connectTimeout;
private function loadCredential() {
if ($this->credential === null) {
$credential_phid = $this->getConfig('credentialPHID');
$this->credential = PassphraseSSHKey::loadFromPHID(
$credential_phid,
PhabricatorUser::getOmnipotentUser());
}
return $this->credential;
}
public function setConnectTimeout($timeout) {
$this->connectTimeout = $timeout;
return $this;
}
public function getExecFuture($command) {
$credential = $this->loadCredential();
$argv = func_get_args();
$argv = $this->applyWorkingDirectoryToArgv($argv);
$full_command = call_user_func_array('csprintf', $argv);
$flags = array();
// See T13121. Attempt to suppress the "Permanently added X to list of
// known hosts" message without suppressing anything important.
$flags[] = '-o';
$flags[] = 'LogLevel=ERROR';
$flags[] = '-o';
$flags[] = 'StrictHostKeyChecking=no';
$flags[] = '-o';
$flags[] = 'UserKnownHostsFile=/dev/null';
$flags[] = '-o';
$flags[] = 'BatchMode=yes';
if ($this->connectTimeout) {
$flags[] = '-o';
$flags[] = 'ConnectTimeout='.$this->connectTimeout;
}
return new ExecFuture(
'ssh %Ls -l %P -p %s -i %P %s -- %s',
$flags,
$credential->getUsernameEnvelope(),
$this->getConfig('port'),
$credential->getKeyfileEnvelope(),
$this->getConfig('host'),
$full_command);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/interface/filesystem/DrydockFilesystemInterface.php | src/applications/drydock/interface/filesystem/DrydockFilesystemInterface.php | <?php
abstract class DrydockFilesystemInterface extends DrydockInterface {
final public function getInterfaceType() {
return 'filesystem';
}
/**
* Reads a file on the Drydock resource and returns the contents of the file.
*/
abstract public function readFile($path);
/**
* Reads a file on the Drydock resource and saves it as a PhabricatorFile.
*/
abstract public function saveFile($path, $name);
/**
* Writes a file to the Drydock resource.
*/
abstract public function writeFile($path, $data);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/interface/filesystem/DrydockSFTPFilesystemInterface.php | src/applications/drydock/interface/filesystem/DrydockSFTPFilesystemInterface.php | <?php
final class DrydockSFTPFilesystemInterface extends DrydockFilesystemInterface {
private $passphraseSSHKey;
private function openCredentialsIfNotOpen() {
if ($this->passphraseSSHKey !== null) {
return;
}
$credential = id(new PassphraseCredentialQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withIDs(array($this->getConfig('credential')))
->needSecrets(true)
->executeOne();
if ($credential->getProvidesType() !==
PassphraseSSHPrivateKeyCredentialType::PROVIDES_TYPE) {
throw new Exception(pht('Only private key credentials are supported.'));
}
$this->passphraseSSHKey = PassphraseSSHKey::loadFromPHID(
$credential->getPHID(),
PhabricatorUser::getOmnipotentUser());
}
private function getExecFuture($path) {
$this->openCredentialsIfNotOpen();
return new ExecFuture(
'sftp -o "StrictHostKeyChecking no" -P %s -i %P %P@%s',
$this->getConfig('port'),
$this->passphraseSSHKey->getKeyfileEnvelope(),
$this->passphraseSSHKey->getUsernameEnvelope(),
$this->getConfig('host'));
}
public function readFile($path) {
$target = new TempFile();
$future = $this->getExecFuture($path);
$future->write(csprintf('get %s %s', $path, $target));
$future->resolvex();
return Filesystem::readFile($target);
}
public function saveFile($path, $name) {
$data = $this->readFile($path);
$file = PhabricatorFile::newFromFileData(
$data,
array('name' => $name));
$file->setName($name);
$file->save();
return $file;
}
public function writeFile($path, $data) {
$source = new TempFile();
Filesystem::writeFile($source, $data);
$future = $this->getExecFuture($path);
$future->write(csprintf('put %s %s', $source, $path));
$future->resolvex();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/customfield/DrydockBlueprintCustomField.php | src/applications/drydock/customfield/DrydockBlueprintCustomField.php | <?php
abstract class DrydockBlueprintCustomField
extends PhabricatorCustomField {
abstract public function getBlueprintFieldValue();
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/customfield/DrydockBlueprintCoreCustomField.php | src/applications/drydock/customfield/DrydockBlueprintCoreCustomField.php | <?php
final class DrydockBlueprintCoreCustomField
extends DrydockBlueprintCustomField
implements PhabricatorStandardCustomFieldInterface {
public function getStandardCustomFieldNamespace() {
return 'drydock:core';
}
public function createFields($object) {
// If this is a generic object without an attached implementation (for
// example, via ApplicationSearch), just don't build any custom fields.
if (!$object->hasImplementation()) {
return array();
}
$impl = $object->getImplementation();
$specs = $impl->getFieldSpecifications();
return PhabricatorStandardCustomField::buildStandardFields($this, $specs);
}
public function shouldUseStorage() {
return false;
}
public function readValueFromObject(PhabricatorCustomFieldInterface $object) {
$key = $this->getProxy()->getRawStandardFieldKey();
$this->setValueFromStorage($object->getDetail($key));
$this->didSetValueFromStorage();
}
public function applyApplicationTransactionInternalEffects(
PhabricatorApplicationTransaction $xaction) {
$object = $this->getObject();
$key = $this->getProxy()->getRawStandardFieldKey();
$this->setValueFromApplicationTransactions($xaction->getNewValue());
$value = $this->getValueForStorage();
$object->setDetail($key, $value);
}
public function getBlueprintFieldValue() {
return $this->getProxy()->getFieldValue();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/editor/DrydockBlueprintEditEngine.php | src/applications/drydock/editor/DrydockBlueprintEditEngine.php | <?php
final class DrydockBlueprintEditEngine
extends PhabricatorEditEngine {
private $blueprintImplementation;
const ENGINECONST = 'drydock.blueprint';
public function isEngineConfigurable() {
return false;
}
public function getEngineName() {
return pht('Drydock Blueprints');
}
public function getSummaryHeader() {
return pht('Edit Drydock Blueprint Configurations');
}
public function getSummaryText() {
return pht('This engine is used to edit Drydock blueprints.');
}
public function getEngineApplicationClass() {
return 'PhabricatorDrydockApplication';
}
public function setBlueprintImplementation(
DrydockBlueprintImplementation $impl) {
$this->blueprintImplementation = $impl;
return $this;
}
public function getBlueprintImplementation() {
return $this->blueprintImplementation;
}
protected function newEditableObject() {
$viewer = $this->getViewer();
$blueprint = DrydockBlueprint::initializeNewBlueprint($viewer);
$impl = $this->getBlueprintImplementation();
if ($impl) {
$blueprint
->setClassName(get_class($impl))
->attachImplementation(clone $impl);
}
return $blueprint;
}
protected function newEditableObjectFromConduit(array $raw_xactions) {
$type = null;
foreach ($raw_xactions as $raw_xaction) {
if ($raw_xaction['type'] !== 'type') {
continue;
}
$type = $raw_xaction['value'];
}
if ($type === null) {
throw new Exception(
pht(
'When creating a new Drydock blueprint via the Conduit API, you '.
'must provide a "type" transaction to select a type.'));
}
$map = DrydockBlueprintImplementation::getAllBlueprintImplementations();
if (!isset($map[$type])) {
throw new Exception(
pht(
'Blueprint type "%s" is unrecognized. Valid types are: %s.',
$type,
implode(', ', array_keys($map))));
}
$impl = clone $map[$type];
$this->setBlueprintImplementation($impl);
return $this->newEditableObject();
}
protected function newEditableObjectForDocumentation() {
// In order to generate the proper list of fields/transactions for a
// blueprint, a blueprint's type needs to be known upfront, and there's
// currently no way to pre-specify the type. Hardcoding an implementation
// here prevents the fatal on the Conduit API page and allows transactions
// to be edited.
$impl = new DrydockWorkingCopyBlueprintImplementation();
$this->setBlueprintImplementation($impl);
return $this->newEditableObject();
}
protected function newObjectQuery() {
return new DrydockBlueprintQuery();
}
protected function getObjectCreateTitleText($object) {
return pht('Create Blueprint');
}
protected function getObjectCreateButtonText($object) {
return pht('Create Blueprint');
}
protected function getObjectEditTitleText($object) {
return pht('Edit Blueprint: %s', $object->getBlueprintName());
}
protected function getObjectEditShortText($object) {
return pht('Edit Blueprint');
}
protected function getObjectCreateShortText() {
return pht('Create Blueprint');
}
protected function getObjectName() {
return pht('Blueprint');
}
protected function getEditorURI() {
return '/drydock/blueprint/edit/';
}
protected function getObjectCreateCancelURI($object) {
return '/drydock/blueprint/';
}
protected function getObjectViewURI($object) {
$id = $object->getID();
return "/drydock/blueprint/{$id}/";
}
protected function getCreateNewObjectPolicy() {
return $this->getApplication()->getPolicy(
DrydockCreateBlueprintsCapability::CAPABILITY);
}
protected function buildCustomEditFields($object) {
$impl = $object->getImplementation();
return array(
// This field appears in the web UI
id(new PhabricatorStaticEditField())
->setKey('displayType')
->setLabel(pht('Blueprint Type'))
->setDescription(pht('Type of blueprint.'))
->setValue($impl->getBlueprintName()),
id(new PhabricatorTextEditField())
->setKey('type')
->setLabel(pht('Type'))
->setIsFormField(false)
->setTransactionType(
DrydockBlueprintTypeTransaction::TRANSACTIONTYPE)
->setDescription(pht('When creating a blueprint, set the type.'))
->setConduitDescription(pht('Set the blueprint type.'))
->setConduitTypeDescription(pht('Blueprint type.'))
->setValue($object->getClassName()),
id(new PhabricatorTextEditField())
->setKey('name')
->setLabel(pht('Name'))
->setDescription(pht('Name of the blueprint.'))
->setTransactionType(DrydockBlueprintNameTransaction::TRANSACTIONTYPE)
->setIsRequired(true)
->setValue($object->getBlueprintName()),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/editor/DrydockBlueprintEditor.php | src/applications/drydock/editor/DrydockBlueprintEditor.php | <?php
final class DrydockBlueprintEditor
extends PhabricatorApplicationTransactionEditor {
public function getEditorApplicationClass() {
return 'PhabricatorDrydockApplication';
}
public function getEditorObjectsDescription() {
return pht('Drydock Blueprints');
}
public function getCreateObjectTitle($author, $object) {
return pht('%s created this blueprint.', $author);
}
public function getCreateObjectTitleForFeed($author, $object) {
return pht('%s created %s.', $author, $object);
}
protected function supportsSearch() {
return true;
}
public function getTransactionTypes() {
$types = parent::getTransactionTypes();
$types[] = PhabricatorTransactions::TYPE_VIEW_POLICY;
$types[] = PhabricatorTransactions::TYPE_EDIT_POLICY;
return $types;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/xaction/DrydockBlueprintTypeTransaction.php | src/applications/drydock/xaction/DrydockBlueprintTypeTransaction.php | <?php
final class DrydockBlueprintTypeTransaction
extends DrydockBlueprintTransactionType {
const TRANSACTIONTYPE = 'drydock.blueprint.type';
public function generateOldValue($object) {
return $object->getClassName();
}
public function applyInternalEffects($object, $value) {
$object->setClassName($value);
}
public function getTitle() {
// These transactions can only be applied during object creation and never
// generate a timeline event.
return null;
}
public function validateTransactions($object, array $xactions) {
$errors = array();
$name = $object->getClassName();
if ($this->isEmptyTextTransaction($name, $xactions)) {
$errors[] = $this->newRequiredError(
pht('You must select a blueprint type when creating a blueprint.'));
}
$map = DrydockBlueprintImplementation::getAllBlueprintImplementations();
foreach ($xactions as $xaction) {
if (!$this->isNewObject()) {
$errors[] = $this->newInvalidError(
pht(
'The type of a blueprint can not be changed once it has '.
'been created.'),
$xaction);
continue;
}
$new = $xaction->getNewValue();
if (!isset($map[$new])) {
$errors[] = $this->newInvalidError(
pht(
'Blueprint type "%s" is not valid. Valid types are: %s.',
$new,
implode(', ', array_keys($map))));
continue;
}
}
return $errors;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/xaction/DrydockBlueprintDisableTransaction.php | src/applications/drydock/xaction/DrydockBlueprintDisableTransaction.php | <?php
final class DrydockBlueprintDisableTransaction
extends DrydockBlueprintTransactionType {
const TRANSACTIONTYPE = 'drydock:blueprint:disabled';
public function generateOldValue($object) {
return (bool)$object->getIsDisabled();
}
public function generateNewValue($object, $value) {
return (bool)$value;
}
public function applyInternalEffects($object, $value) {
$object->setIsDisabled((int)$value);
}
public function getTitle() {
$new = $this->getNewValue();
if ($new) {
return pht(
'%s disabled this blueprint.',
$this->renderAuthor());
} else {
return pht(
'%s enabled this blueprint.',
$this->renderAuthor());
}
}
public function getTitleForFeed() {
$new = $this->getNewValue();
if ($new) {
return pht(
'%s disabled %s.',
$this->renderAuthor(),
$this->renderObject());
} else {
return pht(
'%s enabled %s.',
$this->renderAuthor(),
$this->renderObject());
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/xaction/DrydockBlueprintTransactionType.php | src/applications/drydock/xaction/DrydockBlueprintTransactionType.php | <?php
abstract class DrydockBlueprintTransactionType
extends PhabricatorModularTransactionType {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/xaction/DrydockBlueprintNameTransaction.php | src/applications/drydock/xaction/DrydockBlueprintNameTransaction.php | <?php
final class DrydockBlueprintNameTransaction
extends DrydockBlueprintTransactionType {
const TRANSACTIONTYPE = 'drydock:blueprint:name';
public function generateOldValue($object) {
return $object->getBlueprintName();
}
public function applyInternalEffects($object, $value) {
$object->setBlueprintName($value);
}
public function getTitle() {
return pht(
'%s renamed this blueprint from %s to %s.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
}
public function getTitleForFeed() {
$old = $this->getOldValue();
$new = $this->getNewValue();
return pht(
'%s renamed %s from %s to %s.',
$this->renderAuthor(),
$this->renderObject(),
$this->renderOldValue(),
$this->renderNewValue());
}
public function validateTransactions($object, array $xactions) {
$errors = array();
$name = $object->getBlueprintName();
if ($this->isEmptyTextTransaction($name, $xactions)) {
$errors[] = $this->newRequiredError(
pht('Blueprints must have a name.'));
}
$max_length = $object->getColumnMaximumByteLength('blueprintName');
foreach ($xactions as $xaction) {
$new_value = $xaction->getNewValue();
$new_length = strlen($new_value);
if ($new_length > $max_length) {
$errors[] = $this->newInvalidError(
pht('Blueprint names can be no longer than %s characters.',
new PhutilNumber($max_length)));
}
}
return $errors;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/exception/DrydockSlotLockException.php | src/applications/drydock/exception/DrydockSlotLockException.php | <?php
final class DrydockSlotLockException extends Exception {
private $lockMap;
public function __construct(array $locks) {
$this->lockMap = $locks;
if ($locks) {
$lock_list = array();
foreach ($locks as $lock => $owner_phid) {
$lock_list[] = pht('"%s" (owned by "%s")', $lock, $owner_phid);
}
$message = pht(
'Unable to acquire slot locks: %s.',
implode(', ', $lock_list));
} else {
$message = pht('Unable to acquire slot locks.');
}
parent::__construct($message);
}
public function getLockMap() {
return $this->lockMap;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/exception/DrydockResourceLockException.php | src/applications/drydock/exception/DrydockResourceLockException.php | <?php
final class DrydockResourceLockException
extends Exception {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/exception/DrydockCommandError.php | src/applications/drydock/exception/DrydockCommandError.php | <?php
final class DrydockCommandError extends Phobject {
private $phase;
private $displayCommand;
private $command;
private $error;
private $stdout;
private $stderr;
public static function newFromCommandException(CommandException $ex) {
$error = new self();
$error->command = (string)$ex->getCommand();
$error->error = $ex->getError();
$error->stdout = $ex->getStdout();
$error->stderr = $ex->getStderr();
return $error;
}
public function setPhase($phase) {
$this->phase = $phase;
return $this;
}
public function getPhase() {
return $this->phase;
}
public function setDisplayCommand($display_command) {
$this->displayCommand = (string)$display_command;
return $this;
}
public function getDisplayCommand() {
return $this->displayCommand;
}
public function toDictionary() {
$display_command = $this->getDisplayCommand();
if ($display_command === null) {
$display_command = $this->command;
}
return array(
'phase' => $this->getPhase(),
'command' => $display_command,
'raw' => $this->command,
'err' => $this->error,
'stdout' => $this->stdout,
'stderr' => $this->stderr,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/exception/DrydockAcquiredBrokenResourceException.php | src/applications/drydock/exception/DrydockAcquiredBrokenResourceException.php | <?php
final class DrydockAcquiredBrokenResourceException
extends Exception {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/operation/DrydockLandRepositoryOperation.php | src/applications/drydock/operation/DrydockLandRepositoryOperation.php | <?php
final class DrydockLandRepositoryOperation
extends DrydockRepositoryOperationType {
const OPCONST = 'land';
const PHASE_PUSH = 'op.land.push';
const PHASE_COMMIT = 'op.land.commit';
public function getOperationDescription(
DrydockRepositoryOperation $operation,
PhabricatorUser $viewer) {
return pht('Land Revision');
}
public function getOperationCurrentStatus(
DrydockRepositoryOperation $operation,
PhabricatorUser $viewer) {
$target = $operation->getRepositoryTarget();
$repository = $operation->getRepository();
switch ($operation->getOperationState()) {
case DrydockRepositoryOperation::STATE_WAIT:
return pht(
'Waiting to land revision into %s on %s...',
$repository->getMonogram(),
$target);
case DrydockRepositoryOperation::STATE_WORK:
return pht(
'Landing revision into %s on %s...',
$repository->getMonogram(),
$target);
case DrydockRepositoryOperation::STATE_DONE:
return pht(
'Revision landed into %s.',
$repository->getMonogram());
}
}
public function getWorkingCopyMerges(DrydockRepositoryOperation $operation) {
$repository = $operation->getRepository();
$merges = array();
$object = $operation->getObject();
if ($object instanceof DifferentialRevision) {
$diff = $this->loadDiff($operation);
$merges[] = array(
'src.uri' => $repository->getStagingURI(),
'src.ref' => $diff->getStagingRef(),
);
} else {
throw new Exception(
pht(
'Invalid or unknown object ("%s") for land operation, expected '.
'Differential Revision.',
$operation->getObjectPHID()));
}
return $merges;
}
public function applyOperation(
DrydockRepositoryOperation $operation,
DrydockInterface $interface) {
$viewer = $this->getViewer();
$repository = $operation->getRepository();
$cmd = array();
$arg = array();
$object = $operation->getObject();
if ($object instanceof DifferentialRevision) {
$revision = $object;
$diff = $this->loadDiff($operation);
$dict = $diff->getDiffAuthorshipDict();
$author_name = idx($dict, 'authorName');
$author_email = idx($dict, 'authorEmail');
$api_method = 'differential.getcommitmessage';
$api_params = array(
'revision_id' => $revision->getID(),
);
$commit_message = id(new ConduitCall($api_method, $api_params))
->setUser($viewer)
->execute();
} else {
throw new Exception(
pht(
'Invalid or unknown object ("%s") for land operation, expected '.
'Differential Revision.',
$operation->getObjectPHID()));
}
$target = $operation->getRepositoryTarget();
list($type, $name) = explode(':', $target, 2);
switch ($type) {
case 'branch':
$push_dst = 'refs/heads/'.$name;
break;
default:
throw new Exception(
pht(
'Unknown repository operation target type "%s" (in target "%s").',
$type,
$target));
}
$committer_info = $this->getCommitterInfo($operation);
// NOTE: We're doing this commit with "-F -" so we don't run into trouble
// with enormous commit messages which might otherwise exceed the maximum
// size of a command.
$future = $interface->getExecFuture(
'git -c user.name=%s -c user.email=%s commit --author %s -F - --',
$committer_info['name'],
$committer_info['email'],
"{$author_name} <{$author_email}>");
$future->write($commit_message);
try {
$future->resolvex();
} catch (CommandException $ex) {
$display_command = csprintf('git commit');
// TODO: One reason this can fail is if the changes have already been
// merged. We could try to detect that.
$error = DrydockCommandError::newFromCommandException($ex)
->setPhase(self::PHASE_COMMIT)
->setDisplayCommand($display_command);
$operation->setCommandError($error->toDictionary());
throw $ex;
}
try {
$interface->execx(
'git push origin -- %s:%s',
'HEAD',
$push_dst);
} catch (CommandException $ex) {
$display_command = csprintf(
'git push origin %R:%R',
'HEAD',
$push_dst);
$error = DrydockCommandError::newFromCommandException($ex)
->setPhase(self::PHASE_PUSH)
->setDisplayCommand($display_command);
$operation->setCommandError($error->toDictionary());
throw $ex;
}
}
private function getCommitterInfo(DrydockRepositoryOperation $operation) {
$viewer = $this->getViewer();
$committer_name = null;
$author_phid = $operation->getAuthorPHID();
$object = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withPHIDs(array($author_phid))
->executeOne();
if ($object) {
if ($object instanceof PhabricatorUser) {
$committer_name = $object->getUsername();
}
}
if (!strlen($committer_name)) {
$committer_name = pht('autocommitter');
}
// TODO: Probably let users choose a VCS email address in settings. For
// now just make something up so we don't leak anyone's stuff.
return array(
'name' => $committer_name,
'email' => 'autocommitter@example.com',
);
}
private function loadDiff(DrydockRepositoryOperation $operation) {
$viewer = $this->getViewer();
$revision = $operation->getObject();
$diff_phid = $operation->getProperty('differential.diffPHID');
$diff = id(new DifferentialDiffQuery())
->setViewer($viewer)
->withPHIDs(array($diff_phid))
->executeOne();
if (!$diff) {
throw new Exception(
pht(
'Unable to load diff "%s".',
$diff_phid));
}
$diff_revid = $diff->getRevisionID();
$revision_id = $revision->getID();
if ($diff_revid != $revision_id) {
throw new Exception(
pht(
'Diff ("%s") has wrong revision ID ("%s", expected "%s").',
$diff_phid,
$diff_revid,
$revision_id));
}
return $diff;
}
public function getBarrierToLanding(
PhabricatorUser $viewer,
DifferentialRevision $revision) {
$repository = $revision->getRepository();
if (!$repository) {
return array(
'title' => pht('No Repository'),
'body' => pht(
'This revision is not associated with a known repository. Only '.
'revisions associated with a tracked repository can be landed '.
'automatically.'),
);
}
if (!$repository->canPerformAutomation()) {
return array(
'title' => pht('No Repository Automation'),
'body' => pht(
'The repository this revision is associated with ("%s") is not '.
'configured to support automation. Configure automation for the '.
'repository to enable revisions to be landed automatically.',
$repository->getMonogram()),
);
}
// Check if this diff was pushed to a staging area.
$diff = id(new DifferentialDiffQuery())
->setViewer($viewer)
->withIDs(array($revision->getActiveDiff()->getID()))
->needProperties(true)
->executeOne();
// Older diffs won't have this property. They may still have been pushed.
// At least for now, assume staging changes are present if the property
// is missing. This should smooth the transition to the more formal
// approach.
$has_staging = $diff->hasDiffProperty('arc.staging');
if ($has_staging) {
$staging = $diff->getProperty('arc.staging');
if (!is_array($staging)) {
$staging = array();
}
$status = idx($staging, 'status');
if ($status != ArcanistDiffWorkflow::STAGING_PUSHED) {
return $this->getBarrierToLandingFromStagingStatus($status);
}
}
// TODO: At some point we should allow installs to give "land reviewed
// code" permission to more users than "push any commit", because it is
// a much less powerful operation. For now, just require push so this
// doesn't do anything users can't do on their own.
$can_push = PhabricatorPolicyFilter::hasCapability(
$viewer,
$repository,
DiffusionPushCapability::CAPABILITY);
if (!$can_push) {
return array(
'title' => pht('Unable to Push'),
'body' => pht(
'You do not have permission to push to the repository this '.
'revision is associated with ("%s"), so you can not land it.',
$repository->getMonogram()),
);
}
if ($revision->isAccepted()) {
// We can land accepted revisions, so continue below. Otherwise, raise
// an error with tailored messaging for the most common cases.
} else if ($revision->isAbandoned()) {
return array(
'title' => pht('Revision Abandoned'),
'body' => pht(
'This revision has been abandoned. Only accepted revisions '.
'may land.'),
);
} else if ($revision->isClosed()) {
return array(
'title' => pht('Revision Closed'),
'body' => pht(
'This revision has already been closed. Only open, accepted '.
'revisions may land.'),
);
} else {
return array(
'title' => pht('Revision Not Accepted'),
'body' => pht(
'This revision is still under review. Only revisions which '.
'have been accepted may land.'),
);
}
// Check for other operations. Eventually this should probably be more
// general (e.g., it's OK to land to multiple different branches
// simultaneously) but just put this in as a sanity check for now.
$other_operations = id(new DrydockRepositoryOperationQuery())
->setViewer($viewer)
->withObjectPHIDs(array($revision->getPHID()))
->withOperationTypes(
array(
$this->getOperationConstant(),
))
->withOperationStates(
array(
DrydockRepositoryOperation::STATE_WAIT,
DrydockRepositoryOperation::STATE_WORK,
DrydockRepositoryOperation::STATE_DONE,
))
->execute();
if ($other_operations) {
$any_done = false;
foreach ($other_operations as $operation) {
if ($operation->isDone()) {
$any_done = true;
break;
}
}
if ($any_done) {
return array(
'title' => pht('Already Complete'),
'body' => pht('This revision has already landed.'),
);
} else {
return array(
'title' => pht('Already In Flight'),
'body' => pht('This revision is already landing.'),
);
}
}
return null;
}
private function getBarrierToLandingFromStagingStatus($status) {
switch ($status) {
case ArcanistDiffWorkflow::STAGING_USER_SKIP:
return array(
'title' => pht('Staging Area Skipped'),
'body' => pht(
'The diff author used the %s flag to skip pushing this change to '.
'staging. Changes must be pushed to staging before they can be '.
'landed from the web.',
phutil_tag('tt', array(), '--skip-staging')),
);
case ArcanistDiffWorkflow::STAGING_DIFF_RAW:
return array(
'title' => pht('Raw Diff Source'),
'body' => pht(
'The diff was generated from a raw input source, so the change '.
'could not be pushed to staging. Changes must be pushed to '.
'staging before they can be landed from the web.'),
);
case ArcanistDiffWorkflow::STAGING_REPOSITORY_UNKNOWN:
return array(
'title' => pht('Unknown Repository'),
'body' => pht(
'When the diff was generated, the client was not able to '.
'determine which repository it belonged to, so the change '.
'was not pushed to staging. Changes must be pushed to staging '.
'before they can be landed from the web.'),
);
case ArcanistDiffWorkflow::STAGING_REPOSITORY_UNAVAILABLE:
return array(
'title' => pht('Staging Unavailable'),
'body' => pht(
'When this diff was generated, the server was running an older '.
'version of the software which did not support staging areas, so '.
'the change was not pushed to staging. Changes must be pushed '.
'to staging before they can be landed from the web.'),
);
case ArcanistDiffWorkflow::STAGING_REPOSITORY_UNSUPPORTED:
return array(
'title' => pht('Repository Unsupported'),
'body' => pht(
'When this diff was generated, the server was running an older '.
'version of the software which did not support staging areas for '.
'this version control system, so the change was not pushed to '.
'staging. Changes must be pushed to staging before they can be '.
'landed from the web.'),
);
case ArcanistDiffWorkflow::STAGING_REPOSITORY_UNCONFIGURED:
return array(
'title' => pht('Repository Unconfigured'),
'body' => pht(
'When this diff was generated, the repository was not configured '.
'with a staging area, so the change was not pushed to staging. '.
'Changes must be pushed to staging before they can be landed '.
'from the web.'),
);
case ArcanistDiffWorkflow::STAGING_CLIENT_UNSUPPORTED:
return array(
'title' => pht('Client Support Unavailable'),
'body' => pht(
'When this diff was generated, the client did not support '.
'staging areas for this version control system, so the change '.
'was not pushed to staging. Changes must be pushed to staging '.
'before they can be landed from the web. Updating the client '.
'may resolve this issue.'),
);
default:
return array(
'title' => pht('Unknown Error'),
'body' => pht(
'When this diff was generated, it was not pushed to staging for '.
'an unknown reason (the status code was "%s"). Changes must be '.
'pushed to staging before they can be landed from the web. '.
'The server may be running an out-of-date version of this '.
'software, and updating may provide more information about this '.
'error.',
$status),
);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/operation/DrydockRepositoryOperationType.php | src/applications/drydock/operation/DrydockRepositoryOperationType.php | <?php
abstract class DrydockRepositoryOperationType extends Phobject {
private $viewer;
private $operation;
private $interface;
abstract public function applyOperation(
DrydockRepositoryOperation $operation,
DrydockInterface $interface);
abstract public function getOperationDescription(
DrydockRepositoryOperation $operation,
PhabricatorUser $viewer);
abstract public function getOperationCurrentStatus(
DrydockRepositoryOperation $operation,
PhabricatorUser $viewer);
public function getWorkingCopyMerges(DrydockRepositoryOperation $operation) {
return array();
}
final public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
final public function getViewer() {
return $this->viewer;
}
final public function setOperation(DrydockRepositoryOperation $operation) {
$this->operation = $operation;
return $this;
}
final public function getOperation() {
return $this->operation;
}
final public function setInterface(DrydockInterface $interface) {
$this->interface = $interface;
return $this;
}
final public function getInterface() {
if (!$this->interface) {
throw new PhutilInvalidStateException('setInterface');
}
return $this->interface;
}
final public function getOperationConstant() {
return $this->getPhobjectClassConstant('OPCONST', 32);
}
final public static function getAllOperationTypes() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getOperationConstant')
->execute();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/operation/DrydockTestRepositoryOperation.php | src/applications/drydock/operation/DrydockTestRepositoryOperation.php | <?php
final class DrydockTestRepositoryOperation
extends DrydockRepositoryOperationType {
const OPCONST = 'test';
public function getOperationDescription(
DrydockRepositoryOperation $operation,
PhabricatorUser $viewer) {
return pht('Test Configuration');
}
public function getOperationCurrentStatus(
DrydockRepositoryOperation $operation,
PhabricatorUser $viewer) {
$repository = $operation->getRepository();
switch ($operation->getOperationState()) {
case DrydockRepositoryOperation::STATE_WAIT:
return pht(
'Waiting to test configuration for %s...',
$repository->getMonogram());
case DrydockRepositoryOperation::STATE_WORK:
return pht(
'Testing configuration for %s. This may take a moment if Drydock '.
'has to clone the repository for the first time.',
$repository->getMonogram());
case DrydockRepositoryOperation::STATE_DONE:
return pht(
'Success! Automation is configured properly and Drydock can '.
'operate on %s.',
$repository->getMonogram());
}
}
public function applyOperation(
DrydockRepositoryOperation $operation,
DrydockInterface $interface) {
$repository = $operation->getRepository();
if ($repository->isGit()) {
$interface->execx('git status');
} else if ($repository->isHg()) {
$interface->execx('hg status');
} else if ($repository->isSVN()) {
$interface->execx('svn status');
} else {
throw new PhutilMethodNotImplementedException();
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/blueprint/DrydockWorkingCopyBlueprintImplementation.php | src/applications/drydock/blueprint/DrydockWorkingCopyBlueprintImplementation.php | <?php
final class DrydockWorkingCopyBlueprintImplementation
extends DrydockBlueprintImplementation {
const PHASE_SQUASHMERGE = 'squashmerge';
const PHASE_REMOTEFETCH = 'blueprint.workingcopy.fetch.remote';
const PHASE_MERGEFETCH = 'blueprint.workingcopy.fetch.staging';
public function isEnabled() {
return true;
}
public function getBlueprintName() {
return pht('Working Copy');
}
public function getBlueprintIcon() {
return 'fa-folder-open';
}
public function getDescription() {
return pht('Allows Drydock to check out working copies of repositories.');
}
public function canAnyBlueprintEverAllocateResourceForLease(
DrydockLease $lease) {
return true;
}
public function canEverAllocateResourceForLease(
DrydockBlueprint $blueprint,
DrydockLease $lease) {
return true;
}
public function canAllocateResourceForLease(
DrydockBlueprint $blueprint,
DrydockLease $lease) {
$viewer = $this->getViewer();
if ($this->shouldLimitAllocatingPoolSize($blueprint)) {
return false;
}
return true;
}
public function canAcquireLeaseOnResource(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
// Don't hand out leases on working copies which have not activated, since
// it may take an arbitrarily long time for them to acquire a host.
if (!$resource->isActive()) {
return false;
}
$need_map = $lease->getAttribute('repositories.map');
if (!is_array($need_map)) {
return false;
}
$have_map = $resource->getAttribute('repositories.map');
if (!is_array($have_map)) {
return false;
}
$have_as = ipull($have_map, 'phid');
$need_as = ipull($need_map, 'phid');
foreach ($need_as as $need_directory => $need_phid) {
if (empty($have_as[$need_directory])) {
// This resource is missing a required working copy.
return false;
}
if ($have_as[$need_directory] != $need_phid) {
// This resource has a required working copy, but it contains
// the wrong repository.
return false;
}
unset($have_as[$need_directory]);
}
if ($have_as && $lease->getAttribute('repositories.strict')) {
// This resource has extra repositories, but the lease is strict about
// which repositories are allowed to exist.
return false;
}
if (!DrydockSlotLock::isLockFree($this->getLeaseSlotLock($resource))) {
return false;
}
return true;
}
public function acquireLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
$lease
->needSlotLock($this->getLeaseSlotLock($resource))
->acquireOnResource($resource);
}
private function getLeaseSlotLock(DrydockResource $resource) {
$resource_phid = $resource->getPHID();
return "workingcopy.lease({$resource_phid})";
}
public function allocateResource(
DrydockBlueprint $blueprint,
DrydockLease $lease) {
$resource = $this->newResourceTemplate($blueprint);
$resource_phid = $resource->getPHID();
$blueprint_phids = $blueprint->getFieldValue('blueprintPHIDs');
$host_lease = $this->newLease($blueprint)
->setResourceType('host')
->setOwnerPHID($resource_phid)
->setAttribute('workingcopy.resourcePHID', $resource_phid)
->setAllowedBlueprintPHIDs($blueprint_phids);
$resource->setAttribute('host.leasePHID', $host_lease->getPHID());
$map = $this->getWorkingCopyRepositoryMap($lease);
$resource->setAttribute('repositories.map', $map);
$slot_lock = $this->getConcurrentResourceLimitSlotLock($blueprint);
if ($slot_lock !== null) {
$resource->needSlotLock($slot_lock);
}
$resource->allocateResource();
$host_lease->queueForActivation();
return $resource;
}
private function getWorkingCopyRepositoryMap(DrydockLease $lease) {
$attribute = 'repositories.map';
$map = $lease->getAttribute($attribute);
// TODO: Leases should validate their attributes more formally.
if (!is_array($map) || !$map) {
$message = array();
if ($map === null) {
$message[] = pht(
'Working copy lease is missing required attribute "%s".',
$attribute);
} else {
$message[] = pht(
'Working copy lease has invalid attribute "%s".',
$attribute);
}
$message[] = pht(
'Attribute "repositories.map" should be a map of repository '.
'specifications.');
$message = implode("\n\n", $message);
throw new Exception($message);
}
foreach ($map as $key => $value) {
$map[$key] = array_select_keys(
$value,
array(
'phid',
));
}
return $map;
}
public function activateResource(
DrydockBlueprint $blueprint,
DrydockResource $resource) {
$lease = $this->loadHostLease($resource);
$this->requireActiveLease($lease);
$command_type = DrydockCommandInterface::INTERFACE_TYPE;
$interface = $lease->getInterface($command_type);
// TODO: Make this configurable.
$resource_id = $resource->getID();
$root = "/var/drydock/workingcopy-{$resource_id}";
$map = $resource->getAttribute('repositories.map');
$futures = array();
$repositories = $this->loadRepositories(ipull($map, 'phid'));
foreach ($map as $directory => $spec) {
// TODO: Validate directory isn't goofy like "/etc" or "../../lol"
// somewhere?
$repository = $repositories[$spec['phid']];
$path = "{$root}/repo/{$directory}/";
$future = $interface->getExecFuture(
'git clone -- %s %s',
(string)$repository->getCloneURIObject(),
$path);
$future->setTimeout($repository->getEffectiveCopyTimeLimit());
$futures[$directory] = $future;
}
foreach (new FutureIterator($futures) as $key => $future) {
$future->resolvex();
}
$resource
->setAttribute('workingcopy.root', $root)
->activateResource();
}
public function destroyResource(
DrydockBlueprint $blueprint,
DrydockResource $resource) {
try {
$lease = $this->loadHostLease($resource);
} catch (Exception $ex) {
// If we can't load the lease, assume we don't need to take any actions
// to destroy it.
return;
}
// Destroy the lease on the host.
$lease->setReleaseOnDestruction(true);
if ($lease->isActive()) {
// Destroy the working copy on disk.
$command_type = DrydockCommandInterface::INTERFACE_TYPE;
$interface = $lease->getInterface($command_type);
$root_key = 'workingcopy.root';
$root = $resource->getAttribute($root_key);
if (strlen($root)) {
$interface->execx('rm -rf -- %s', $root);
}
}
}
public function getResourceName(
DrydockBlueprint $blueprint,
DrydockResource $resource) {
return pht('Working Copy');
}
public function activateLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
$host_lease = $this->loadHostLease($resource);
$command_type = DrydockCommandInterface::INTERFACE_TYPE;
$interface = $host_lease->getInterface($command_type);
$map = $lease->getAttribute('repositories.map');
$root = $resource->getAttribute('workingcopy.root');
$repositories = $this->loadRepositories(ipull($map, 'phid'));
$default = null;
foreach ($map as $directory => $spec) {
$repository = $repositories[$spec['phid']];
$interface->pushWorkingDirectory("{$root}/repo/{$directory}/");
$cmd = array();
$arg = array();
$cmd[] = 'git clean -d --force';
$cmd[] = 'git fetch';
$commit = idx($spec, 'commit');
$branch = idx($spec, 'branch');
$ref = idx($spec, 'ref');
// Reset things first, in case previous builds left anything staged or
// dirty. Note that we don't reset to "HEAD" because that does not work
// in empty repositories.
$cmd[] = 'git reset --hard';
if ($commit !== null) {
$cmd[] = 'git checkout %s --';
$arg[] = $commit;
} else if ($branch !== null) {
$cmd[] = 'git checkout %s --';
$arg[] = $branch;
$cmd[] = 'git reset --hard origin/%s';
$arg[] = $branch;
}
$this->newExecvFuture($interface, $cmd, $arg)
->setTimeout($repository->getEffectiveCopyTimeLimit())
->resolvex();
if (idx($spec, 'default')) {
$default = $directory;
}
// If we're fetching a ref from a remote, do that separately so we can
// raise a more tailored error.
if ($ref) {
$cmd = array();
$arg = array();
$ref_uri = $ref['uri'];
$ref_ref = $ref['ref'];
$cmd[] = 'git fetch --no-tags -- %s +%s:%s';
$arg[] = $ref_uri;
$arg[] = $ref_ref;
$arg[] = $ref_ref;
$cmd[] = 'git checkout %s --';
$arg[] = $ref_ref;
try {
$this->newExecvFuture($interface, $cmd, $arg)
->setTimeout($repository->getEffectiveCopyTimeLimit())
->resolvex();
} catch (CommandException $ex) {
$display_command = csprintf(
'git fetch %R %R',
$ref_uri,
$ref_ref);
$error = DrydockCommandError::newFromCommandException($ex)
->setPhase(self::PHASE_REMOTEFETCH)
->setDisplayCommand($display_command);
$lease->setAttribute(
'workingcopy.vcs.error',
$error->toDictionary());
throw $ex;
}
}
$merges = idx($spec, 'merges');
if ($merges) {
foreach ($merges as $merge) {
$this->applyMerge($lease, $interface, $merge);
}
}
$interface->popWorkingDirectory();
}
if ($default === null) {
$default = head_key($map);
}
// TODO: Use working storage?
$lease->setAttribute('workingcopy.default', "{$root}/repo/{$default}/");
$lease->activateOnResource($resource);
}
public function didReleaseLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
// We leave working copies around even if there are no leases on them,
// since the cost to maintain them is nearly zero but rebuilding them is
// moderately expensive and it's likely that they'll be reused.
return;
}
public function destroyLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
// When we activate a lease we just reset the working copy state and do
// not create any new state, so we don't need to do anything special when
// destroying a lease.
return;
}
public function getType() {
return 'working-copy';
}
public function getInterface(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease,
$type) {
switch ($type) {
case DrydockCommandInterface::INTERFACE_TYPE:
$host_lease = $this->loadHostLease($resource);
$command_interface = $host_lease->getInterface($type);
$path = $lease->getAttribute('workingcopy.default');
$command_interface->pushWorkingDirectory($path);
return $command_interface;
}
}
private function loadRepositories(array $phids) {
$viewer = $this->getViewer();
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($viewer)
->withPHIDs($phids)
->execute();
$repositories = mpull($repositories, null, 'getPHID');
foreach ($phids as $phid) {
if (empty($repositories[$phid])) {
throw new Exception(
pht(
'Repository PHID "%s" does not exist.',
$phid));
}
}
foreach ($repositories as $repository) {
$repository_vcs = $repository->getVersionControlSystem();
switch ($repository_vcs) {
case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
break;
default:
throw new Exception(
pht(
'Repository ("%s") has unsupported VCS ("%s").',
$repository->getPHID(),
$repository_vcs));
}
}
return $repositories;
}
private function loadHostLease(DrydockResource $resource) {
$viewer = $this->getViewer();
$lease_phid = $resource->getAttribute('host.leasePHID');
$lease = id(new DrydockLeaseQuery())
->setViewer($viewer)
->withPHIDs(array($lease_phid))
->executeOne();
if (!$lease) {
throw new Exception(
pht(
'Unable to load lease ("%s").',
$lease_phid));
}
return $lease;
}
protected function getCustomFieldSpecifications() {
return array(
'blueprintPHIDs' => array(
'name' => pht('Use Blueprints'),
'type' => 'blueprints',
'required' => true,
),
);
}
protected function shouldUseConcurrentResourceLimit() {
return true;
}
private function applyMerge(
DrydockLease $lease,
DrydockCommandInterface $interface,
array $merge) {
$src_uri = $merge['src.uri'];
$src_ref = $merge['src.ref'];
try {
$interface->execx(
'git fetch --no-tags -- %s +%s:%s',
$src_uri,
$src_ref,
$src_ref);
} catch (CommandException $ex) {
$display_command = csprintf(
'git fetch %R +%R:%R',
$src_uri,
$src_ref,
$src_ref);
$error = DrydockCommandError::newFromCommandException($ex)
->setPhase(self::PHASE_MERGEFETCH)
->setDisplayCommand($display_command);
$lease->setAttribute('workingcopy.vcs.error', $error->toDictionary());
throw $ex;
}
// NOTE: This can never actually generate a commit because we pass
// "--squash", but git sometimes runs code to check that a username and
// email are configured anyway.
$real_command = csprintf(
'git -c user.name=%s -c user.email=%s merge --no-stat --squash -- %R',
'drydock',
'drydock@phabricator',
$src_ref);
try {
$interface->execx('%C', $real_command);
} catch (CommandException $ex) {
$display_command = csprintf(
'git merge --squash %R',
$src_ref);
$error = DrydockCommandError::newFromCommandException($ex)
->setPhase(self::PHASE_SQUASHMERGE)
->setDisplayCommand($display_command);
$lease->setAttribute('workingcopy.vcs.error', $error->toDictionary());
throw $ex;
}
}
public function getCommandError(DrydockLease $lease) {
return $lease->getAttribute('workingcopy.vcs.error');
}
private function execxv(
DrydockCommandInterface $interface,
array $commands,
array $arguments) {
return $this->newExecvFuture($interface, $commands, $arguments)->resolvex();
}
private function newExecvFuture(
DrydockCommandInterface $interface,
array $commands,
array $arguments) {
$commands = implode(' && ', $commands);
$argv = array_merge(array($commands), $arguments);
return call_user_func_array(array($interface, 'getExecFuture'), $argv);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/blueprint/DrydockBlueprintImplementation.php | src/applications/drydock/blueprint/DrydockBlueprintImplementation.php | <?php
/**
* @task lease Lease Acquisition
* @task resource Resource Allocation
* @task interface Resource Interfaces
* @task log Logging
*/
abstract class DrydockBlueprintImplementation extends Phobject {
abstract public function getType();
abstract public function isEnabled();
abstract public function getBlueprintName();
abstract public function getDescription();
public function getBlueprintIcon() {
return 'fa-map-o';
}
public function getFieldSpecifications() {
$fields = array();
$fields += $this->getCustomFieldSpecifications();
if ($this->shouldUseConcurrentResourceLimit()) {
$fields += array(
'allocator.limit' => array(
'name' => pht('Limit'),
'caption' => pht(
'Maximum number of resources this blueprint can have active '.
'concurrently.'),
'type' => 'int',
),
);
}
return $fields;
}
protected function getCustomFieldSpecifications() {
return array();
}
public function getViewer() {
return PhabricatorUser::getOmnipotentUser();
}
/* -( Lease Acquisition )-------------------------------------------------- */
/**
* Enforce basic checks on lease/resource compatibility. Allows resources to
* reject leases if they are incompatible, even if the resource types match.
*
* For example, if a resource represents a 32-bit host, this method might
* reject leases that need a 64-bit host. The blueprint might also reject
* a resource if the lease needs 8GB of RAM and the resource only has 6GB
* free.
*
* This method should not acquire locks or expect anything to be locked. This
* is a coarse compatibility check between a lease and a resource.
*
* @param DrydockBlueprint Concrete blueprint to allocate for.
* @param DrydockResource Candidate resource to allocate the lease on.
* @param DrydockLease Pending lease that wants to allocate here.
* @return bool True if the resource and lease are compatible.
* @task lease
*/
abstract public function canAcquireLeaseOnResource(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease);
/**
* Acquire a lease. Allows resources to perform setup as leases are brought
* online.
*
* If acquisition fails, throw an exception.
*
* @param DrydockBlueprint Blueprint which built the resource.
* @param DrydockResource Resource to acquire a lease on.
* @param DrydockLease Requested lease.
* @return void
* @task lease
*/
abstract public function acquireLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease);
/**
* @return void
* @task lease
*/
public function activateLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
throw new PhutilMethodNotImplementedException();
}
/**
* React to a lease being released.
*
* This callback is primarily useful for automatically releasing resources
* once all leases are released.
*
* @param DrydockBlueprint Blueprint which built the resource.
* @param DrydockResource Resource a lease was released on.
* @param DrydockLease Recently released lease.
* @return void
* @task lease
*/
abstract public function didReleaseLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease);
/**
* Destroy any temporary data associated with a lease.
*
* If a lease creates temporary state while held, destroy it here.
*
* @param DrydockBlueprint Blueprint which built the resource.
* @param DrydockResource Resource the lease is acquired on.
* @param DrydockLease The lease being destroyed.
* @return void
* @task lease
*/
abstract public function destroyLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease);
/**
* Return true to try to allocate a new resource and expand the resource
* pool instead of permitting an otherwise valid acquisition on an existing
* resource.
*
* This allows the blueprint to provide a soft hint about when the resource
* pool should grow.
*
* Returning "true" in all cases generally makes sense when a blueprint
* controls a fixed pool of resources, like a particular number of physical
* hosts: you want to put all the hosts in service, so whenever it is
* possible to allocate a new host you want to do this.
*
* Returning "false" in all cases generally make sense when a blueprint
* has a flexible pool of expensive resources and you want to pack leases
* onto them as tightly as possible.
*
* @param DrydockBlueprint The blueprint for an existing resource being
* acquired.
* @param DrydockResource The resource being acquired, which we may want to
* build a supplemental resource for.
* @param DrydockLease The current lease performing acquisition.
* @return bool True to prefer allocating a supplemental resource.
*
* @task lease
*/
public function shouldAllocateSupplementalResource(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
return false;
}
/* -( Resource Allocation )------------------------------------------------ */
/**
* Enforce fundamental implementation/lease checks. Allows implementations to
* reject a lease which no concrete blueprint can ever satisfy.
*
* For example, if a lease only builds ARM hosts and the lease needs a
* PowerPC host, it may be rejected here.
*
* This is the earliest rejection phase, and followed by
* @{method:canEverAllocateResourceForLease}.
*
* This method should not actually check if a resource can be allocated
* right now, or even if a blueprint which can allocate a suitable resource
* really exists, only if some blueprint may conceivably exist which could
* plausibly be able to build a suitable resource.
*
* @param DrydockLease Requested lease.
* @return bool True if some concrete blueprint of this implementation's
* type might ever be able to build a resource for the lease.
* @task resource
*/
abstract public function canAnyBlueprintEverAllocateResourceForLease(
DrydockLease $lease);
/**
* Enforce basic blueprint/lease checks. Allows blueprints to reject a lease
* which they can not build a resource for.
*
* This is the second rejection phase. It follows
* @{method:canAnyBlueprintEverAllocateResourceForLease} and is followed by
* @{method:canAllocateResourceForLease}.
*
* This method should not check if a resource can be built right now, only
* if the blueprint as configured may, at some time, be able to build a
* suitable resource.
*
* @param DrydockBlueprint Blueprint which may be asked to allocate a
* resource.
* @param DrydockLease Requested lease.
* @return bool True if this blueprint can eventually build a suitable
* resource for the lease, as currently configured.
* @task resource
*/
abstract public function canEverAllocateResourceForLease(
DrydockBlueprint $blueprint,
DrydockLease $lease);
/**
* Enforce basic availability limits. Allows blueprints to reject resource
* allocation if they are currently overallocated.
*
* This method should perform basic capacity/limit checks. For example, if
* it has a limit of 6 resources and currently has 6 resources allocated,
* it might reject new leases.
*
* This method should not acquire locks or expect locks to be acquired. This
* is a coarse check to determine if the operation is likely to succeed
* right now without needing to acquire locks.
*
* It is expected that this method will sometimes return `true` (indicating
* that a resource can be allocated) but find that another allocator has
* eaten up free capacity by the time it actually tries to build a resource.
* This is normal and the allocator will recover from it.
*
* @param DrydockBlueprint The blueprint which may be asked to allocate a
* resource.
* @param DrydockLease Requested lease.
* @return bool True if this blueprint appears likely to be able to allocate
* a suitable resource.
* @task resource
*/
abstract public function canAllocateResourceForLease(
DrydockBlueprint $blueprint,
DrydockLease $lease);
/**
* Allocate a suitable resource for a lease.
*
* This method MUST acquire, hold, and manage locks to prevent multiple
* allocations from racing. World state is not locked before this method is
* called. Blueprints are entirely responsible for any lock handling they
* need to perform.
*
* @param DrydockBlueprint The blueprint which should allocate a resource.
* @param DrydockLease Requested lease.
* @return DrydockResource Allocated resource.
* @task resource
*/
abstract public function allocateResource(
DrydockBlueprint $blueprint,
DrydockLease $lease);
/**
* @task resource
*/
public function activateResource(
DrydockBlueprint $blueprint,
DrydockResource $resource) {
throw new PhutilMethodNotImplementedException();
}
/**
* Destroy any temporary data associated with a resource.
*
* If a resource creates temporary state when allocated, destroy that state
* here. For example, you might shut down a virtual host or destroy a working
* copy on disk.
*
* @param DrydockBlueprint Blueprint which built the resource.
* @param DrydockResource Resource being destroyed.
* @return void
* @task resource
*/
abstract public function destroyResource(
DrydockBlueprint $blueprint,
DrydockResource $resource);
/**
* Get a human readable name for a resource.
*
* @param DrydockBlueprint Blueprint which built the resource.
* @param DrydockResource Resource to get the name of.
* @return string Human-readable resource name.
* @task resource
*/
abstract public function getResourceName(
DrydockBlueprint $blueprint,
DrydockResource $resource);
/* -( Resource Interfaces )------------------------------------------------ */
abstract public function getInterface(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease,
$type);
/* -( Logging )------------------------------------------------------------ */
public static function getAllBlueprintImplementations() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->execute();
}
/**
* Get all the @{class:DrydockBlueprintImplementation}s which can possibly
* build a resource to satisfy a lease.
*
* This method returns blueprints which might, at some time, be able to
* build a resource which can satisfy the lease. They may not be able to
* build that resource right now.
*
* @param DrydockLease Requested lease.
* @return list<DrydockBlueprintImplementation> List of qualifying blueprint
* implementations.
*/
public static function getAllForAllocatingLease(
DrydockLease $lease) {
$impls = self::getAllBlueprintImplementations();
$keep = array();
foreach ($impls as $key => $impl) {
// Don't use disabled blueprint types.
if (!$impl->isEnabled()) {
continue;
}
// Don't use blueprint types which can't allocate the correct kind of
// resource.
if ($impl->getType() != $lease->getResourceType()) {
continue;
}
if (!$impl->canAnyBlueprintEverAllocateResourceForLease($lease)) {
continue;
}
$keep[$key] = $impl;
}
return $keep;
}
public static function getNamedImplementation($class) {
return idx(self::getAllBlueprintImplementations(), $class);
}
protected function newResourceTemplate(DrydockBlueprint $blueprint) {
$resource = id(new DrydockResource())
->setBlueprintPHID($blueprint->getPHID())
->attachBlueprint($blueprint)
->setType($this->getType())
->setStatus(DrydockResourceStatus::STATUS_PENDING);
// Pre-allocate the resource PHID.
$resource->setPHID($resource->generatePHID());
return $resource;
}
protected function newLease(DrydockBlueprint $blueprint) {
return DrydockLease::initializeNewLease()
->setAuthorizingPHID($blueprint->getPHID());
}
protected function requireActiveLease(DrydockLease $lease) {
$lease_status = $lease->getStatus();
switch ($lease_status) {
case DrydockLeaseStatus::STATUS_PENDING:
case DrydockLeaseStatus::STATUS_ACQUIRED:
throw new PhabricatorWorkerYieldException(15);
case DrydockLeaseStatus::STATUS_ACTIVE:
return;
default:
throw new Exception(
pht(
'Lease ("%s") is in bad state ("%s"), expected "%s".',
$lease->getPHID(),
$lease_status,
DrydockLeaseStatus::STATUS_ACTIVE));
}
}
/**
* Does this implementation use concurrent resource limits?
*
* Implementations can override this method to opt into standard limit
* behavior, which provides a simple concurrent resource limit.
*
* @return bool True to use limits.
*/
protected function shouldUseConcurrentResourceLimit() {
return false;
}
/**
* Get the effective concurrent resource limit for this blueprint.
*
* @param DrydockBlueprint Blueprint to get the limit for.
* @return int|null Limit, or `null` for no limit.
*/
protected function getConcurrentResourceLimit(DrydockBlueprint $blueprint) {
if ($this->shouldUseConcurrentResourceLimit()) {
$limit = $blueprint->getFieldValue('allocator.limit');
$limit = (int)$limit;
if ($limit > 0) {
return $limit;
} else {
return null;
}
}
return null;
}
protected function getConcurrentResourceLimitSlotLock(
DrydockBlueprint $blueprint) {
$limit = $this->getConcurrentResourceLimit($blueprint);
if ($limit === null) {
return;
}
$blueprint_phid = $blueprint->getPHID();
// TODO: This logic shouldn't do anything awful, but is a little silly. It
// would be nice to unify the "huge limit" and "small limit" cases
// eventually but it's a little tricky.
// If the limit is huge, just pick a random slot. This is just stopping
// us from exploding if someone types a billion zillion into the box.
if ($limit > 1024) {
$slot = mt_rand(0, $limit - 1);
return "allocator({$blueprint_phid}).limit({$slot})";
}
// For reasonable limits, actually check for an available slot.
$slots = range(0, $limit - 1);
shuffle($slots);
$lock_names = array();
foreach ($slots as $slot) {
$lock_names[] = "allocator({$blueprint_phid}).limit({$slot})";
}
$locks = DrydockSlotLock::loadHeldLocks($lock_names);
$locks = mpull($locks, null, 'getLockKey');
foreach ($lock_names as $lock_name) {
if (empty($locks[$lock_name])) {
return $lock_name;
}
}
// If we found no free slot, just return whatever we checked last (which
// is just a random slot). There's a small chance we'll get lucky and the
// lock will be free by the time we try to take it, but usually we'll just
// fail to grab the lock, throw an appropriate lock exception, and get back
// on the right path to retry later.
return $lock_name;
}
/**
* Apply standard limits on resource allocation rate.
*
* @param DrydockBlueprint The blueprint requesting an allocation.
* @return bool True if further allocations should be limited.
*/
protected function shouldLimitAllocatingPoolSize(
DrydockBlueprint $blueprint) {
// Limit on total number of active resources.
$total_limit = $this->getConcurrentResourceLimit($blueprint);
if ($total_limit === null) {
return false;
}
$resource = new DrydockResource();
$conn = $resource->establishConnection('r');
$counts = queryfx_all(
$conn,
'SELECT status, COUNT(*) N FROM %R
WHERE blueprintPHID = %s AND status != %s
GROUP BY status',
$resource,
$blueprint->getPHID(),
DrydockResourceStatus::STATUS_DESTROYED);
$counts = ipull($counts, 'N', 'status');
$n_alloc = idx($counts, DrydockResourceStatus::STATUS_PENDING, 0);
$n_active = idx($counts, DrydockResourceStatus::STATUS_ACTIVE, 0);
$n_broken = idx($counts, DrydockResourceStatus::STATUS_BROKEN, 0);
$n_released = idx($counts, DrydockResourceStatus::STATUS_RELEASED, 0);
// If we're at the limit on total active resources, limit additional
// allocations.
$n_total = ($n_alloc + $n_active + $n_broken + $n_released);
if ($n_total >= $total_limit) {
return true;
}
return false;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/blueprint/DrydockAlmanacServiceHostBlueprintImplementation.php | src/applications/drydock/blueprint/DrydockAlmanacServiceHostBlueprintImplementation.php | <?php
final class DrydockAlmanacServiceHostBlueprintImplementation
extends DrydockBlueprintImplementation {
private $services;
private $freeBindings;
public function isEnabled() {
$almanac_app = 'PhabricatorAlmanacApplication';
return PhabricatorApplication::isClassInstalled($almanac_app);
}
public function getBlueprintName() {
return pht('Almanac Hosts');
}
public function getBlueprintIcon() {
return 'fa-server';
}
public function getDescription() {
return pht(
'Allows Drydock to lease existing hosts defined in an Almanac service '.
'pool.');
}
public function canAnyBlueprintEverAllocateResourceForLease(
DrydockLease $lease) {
return true;
}
public function canEverAllocateResourceForLease(
DrydockBlueprint $blueprint,
DrydockLease $lease) {
$services = $this->loadServices($blueprint);
$bindings = $this->getActiveBindings($services);
if (!$bindings) {
// If there are no devices bound to the services for this blueprint,
// we can not allocate resources.
return false;
}
return true;
}
public function shouldAllocateSupplementalResource(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
// We want to use every host in an Almanac service, since the amount of
// hardware is fixed and there's normally no value in packing leases onto a
// subset of it. Always build a new supplemental resource if we can.
return true;
}
public function canAllocateResourceForLease(
DrydockBlueprint $blueprint,
DrydockLease $lease) {
// We will only allocate one resource per unique device bound to the
// services for this blueprint. Make sure we have a free device somewhere.
$free_bindings = $this->loadFreeBindings($blueprint);
if (!$free_bindings) {
return false;
}
return true;
}
public function allocateResource(
DrydockBlueprint $blueprint,
DrydockLease $lease) {
$free_bindings = $this->loadFreeBindings($blueprint);
shuffle($free_bindings);
$exceptions = array();
foreach ($free_bindings as $binding) {
$device = $binding->getDevice();
$device_name = $device->getName();
$binding_phid = $binding->getPHID();
$resource = $this->newResourceTemplate($blueprint)
->setActivateWhenAllocated(true)
->setAttribute('almanacDeviceName', $device_name)
->setAttribute('almanacServicePHID', $binding->getServicePHID())
->setAttribute('almanacBindingPHID', $binding_phid)
->needSlotLock("almanac.host.binding({$binding_phid})");
try {
return $resource->allocateResource();
} catch (Exception $ex) {
$exceptions[] = $ex;
}
}
throw new PhutilAggregateException(
pht('Unable to allocate any binding as a resource.'),
$exceptions);
}
public function destroyResource(
DrydockBlueprint $blueprint,
DrydockResource $resource) {
// We don't create anything when allocating hosts, so we don't need to do
// any cleanup here.
return;
}
public function getResourceName(
DrydockBlueprint $blueprint,
DrydockResource $resource) {
$device_name = $resource->getAttribute(
'almanacDeviceName',
pht('<Unknown>'));
return pht('Host (%s)', $device_name);
}
public function canAcquireLeaseOnResource(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
// Require the binding to a given host be active before we'll hand out more
// leases on the corresponding resource.
$binding = $this->loadBindingForResource($resource);
if ($binding->getIsDisabled()) {
return false;
}
return true;
}
public function acquireLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
$lease
->setActivateWhenAcquired(true)
->acquireOnResource($resource);
}
public function didReleaseLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
// Almanac hosts stick around indefinitely so we don't need to recycle them
// if they don't have any leases.
return;
}
public function destroyLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
// We don't create anything when activating a lease, so we don't need to
// throw anything away.
return;
}
public function getType() {
return 'host';
}
public function getInterface(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease,
$type) {
switch ($type) {
case DrydockCommandInterface::INTERFACE_TYPE:
$credential_phid = $blueprint->getFieldValue('credentialPHID');
$binding = $this->loadBindingForResource($resource);
$interface = $binding->getInterface();
return id(new DrydockSSHCommandInterface())
->setConfig('credentialPHID', $credential_phid)
->setConfig('host', $interface->getAddress())
->setConfig('port', $interface->getPort());
}
}
protected function getCustomFieldSpecifications() {
return array(
'almanacServicePHIDs' => array(
'name' => pht('Almanac Services'),
'type' => 'datasource',
'datasource.class' => 'AlmanacServiceDatasource',
'datasource.parameters' => array(
'serviceTypes' => $this->getAlmanacServiceTypes(),
),
'required' => true,
),
'credentialPHID' => array(
'name' => pht('Credentials'),
'type' => 'credential',
'credential.provides' =>
PassphraseSSHPrivateKeyCredentialType::PROVIDES_TYPE,
'credential.type' =>
PassphraseSSHPrivateKeyTextCredentialType::CREDENTIAL_TYPE,
),
);
}
private function loadServices(DrydockBlueprint $blueprint) {
if (!$this->services) {
$service_phids = $blueprint->getFieldValue('almanacServicePHIDs');
if (!$service_phids) {
throw new Exception(
pht(
'This blueprint ("%s") does not define any Almanac Service PHIDs.',
$blueprint->getBlueprintName()));
}
$viewer = $this->getViewer();
$services = id(new AlmanacServiceQuery())
->setViewer($viewer)
->withPHIDs($service_phids)
->withServiceTypes($this->getAlmanacServiceTypes())
->needActiveBindings(true)
->execute();
$services = mpull($services, null, 'getPHID');
if (count($services) != count($service_phids)) {
$missing_phids = array_diff($service_phids, array_keys($services));
throw new Exception(
pht(
'Some of the Almanac Services defined by this blueprint '.
'could not be loaded. They may be invalid, no longer exist, '.
'or be of the wrong type: %s.',
implode(', ', $missing_phids)));
}
$this->services = $services;
}
return $this->services;
}
private function getActiveBindings(array $services) {
assert_instances_of($services, 'AlmanacService');
$bindings = array_mergev(mpull($services, 'getActiveBindings'));
return mpull($bindings, null, 'getPHID');
}
private function loadFreeBindings(DrydockBlueprint $blueprint) {
if ($this->freeBindings === null) {
$viewer = $this->getViewer();
$pool = id(new DrydockResourceQuery())
->setViewer($viewer)
->withBlueprintPHIDs(array($blueprint->getPHID()))
->withStatuses(
array(
DrydockResourceStatus::STATUS_PENDING,
DrydockResourceStatus::STATUS_ACTIVE,
DrydockResourceStatus::STATUS_BROKEN,
DrydockResourceStatus::STATUS_RELEASED,
))
->execute();
$allocated_phids = array();
foreach ($pool as $resource) {
$allocated_phids[] = $resource->getAttribute('almanacBindingPHID');
}
$allocated_phids = array_fuse($allocated_phids);
$services = $this->loadServices($blueprint);
$bindings = $this->getActiveBindings($services);
$free = array();
foreach ($bindings as $binding) {
if (empty($allocated_phids[$binding->getPHID()])) {
$free[] = $binding;
}
}
$this->freeBindings = $free;
}
return $this->freeBindings;
}
private function getAlmanacServiceTypes() {
return array(
AlmanacDrydockPoolServiceType::SERVICETYPE,
);
}
private function loadBindingForResource(DrydockResource $resource) {
$binding_phid = $resource->getAttribute('almanacBindingPHID');
if (!$binding_phid) {
throw new Exception(
pht(
'Drydock resource ("%s") has no Almanac binding PHID, so its '.
'binding can not be loaded.',
$resource->getPHID()));
}
$viewer = $this->getViewer();
$binding = id(new AlmanacBindingQuery())
->setViewer($viewer)
->withPHIDs(array($binding_phid))
->executeOne();
if (!$binding) {
throw new Exception(
pht(
'Unable to load Almanac binding ("%s") for resource ("%s").',
$binding_phid,
$resource->getPHID()));
}
return $binding;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/blueprint/__tests__/DrydockBlueprintImplementationTestCase.php | src/applications/drydock/blueprint/__tests__/DrydockBlueprintImplementationTestCase.php | <?php
final class DrydockBlueprintImplementationTestCase extends PhabricatorTestCase {
public function testGetAllBlueprintImplementations() {
DrydockBlueprintImplementation::getAllBlueprintImplementations();
$this->assertTrue(true);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/application/PhabricatorDrydockApplication.php | src/applications/drydock/application/PhabricatorDrydockApplication.php | <?php
final class PhabricatorDrydockApplication extends PhabricatorApplication {
public function getBaseURI() {
return '/drydock/';
}
public function getName() {
return pht('Drydock');
}
public function getShortDescription() {
return pht('Allocate Software Resources');
}
public function getIcon() {
return 'fa-truck';
}
public function getTitleGlyph() {
return "\xE2\x98\x82";
}
public function getFlavorText() {
return pht('A nautical adventure.');
}
public function getApplicationGroup() {
return self::GROUP_UTILITIES;
}
public function getHelpDocumentationArticles(PhabricatorUser $viewer) {
return array(
array(
'name' => pht('Drydock User Guide'),
'href' => PhabricatorEnv::getDoclink('Drydock User Guide'),
),
);
}
public function getRoutes() {
return array(
'/drydock/' => array(
'' => 'DrydockConsoleController',
'(?P<type>blueprint)/' => array(
'(?:query/(?P<queryKey>[^/]+)/)?' => 'DrydockBlueprintListController',
'(?P<id>[1-9]\d*)/' => array(
'' => 'DrydockBlueprintViewController',
'(?P<action>disable|enable)/' =>
'DrydockBlueprintDisableController',
'resources/(?:query/(?P<queryKey>[^/]+)/)?' =>
'DrydockResourceListController',
'logs/(?:query/(?P<queryKey>[^/]+)/)?' =>
'DrydockLogListController',
'authorizations/(?:query/(?P<queryKey>[^/]+)/)?' =>
'DrydockAuthorizationListController',
),
$this->getEditRoutePattern('edit/')
=> 'DrydockBlueprintEditController',
),
'(?P<type>resource)/' => array(
'(?:query/(?P<queryKey>[^/]+)/)?' => 'DrydockResourceListController',
'(?P<id>[1-9]\d*)/' => array(
'' => 'DrydockResourceViewController',
'release/' => 'DrydockResourceReleaseController',
'leases/(?:query/(?P<queryKey>[^/]+)/)?' =>
'DrydockLeaseListController',
'logs/(?:query/(?P<queryKey>[^/]+)/)?' =>
'DrydockLogListController',
),
),
'(?P<type>lease)/' => array(
'(?:query/(?P<queryKey>[^/]+)/)?' => 'DrydockLeaseListController',
'(?P<id>[1-9]\d*)/' => array(
'' => 'DrydockLeaseViewController',
'release/' => 'DrydockLeaseReleaseController',
'logs/(?:query/(?P<queryKey>[^/]+)/)?' =>
'DrydockLogListController',
),
),
'(?P<type>authorization)/' => array(
'(?P<id>[1-9]\d*)/' => array(
'' => 'DrydockAuthorizationViewController',
'(?P<action>authorize|decline)/' =>
'DrydockAuthorizationAuthorizeController',
),
),
'(?P<type>operation)/' => array(
'(?:query/(?P<queryKey>[^/]+)/)?'
=> 'DrydockRepositoryOperationListController',
'(?P<id>[1-9]\d*)/' => array(
'' => 'DrydockRepositoryOperationViewController',
'status/' => 'DrydockRepositoryOperationStatusController',
'dismiss/' => 'DrydockRepositoryOperationDismissController',
'logs/(?:query/(?P<queryKey>[^/]+)/)?' =>
'DrydockLogListController',
),
),
),
);
}
protected function getCustomCapabilities() {
return array(
DrydockDefaultViewCapability::CAPABILITY => array(
'template' => DrydockBlueprintPHIDType::TYPECONST,
'capability' => PhabricatorPolicyCapability::CAN_VIEW,
),
DrydockDefaultEditCapability::CAPABILITY => array(
'default' => PhabricatorPolicies::POLICY_ADMIN,
'template' => DrydockBlueprintPHIDType::TYPECONST,
'capability' => PhabricatorPolicyCapability::CAN_EDIT,
),
DrydockCreateBlueprintsCapability::CAPABILITY => array(
'default' => PhabricatorPolicies::POLICY_ADMIN,
),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/garbagecollector/DrydockLogGarbageCollector.php | src/applications/drydock/garbagecollector/DrydockLogGarbageCollector.php | <?php
final class DrydockLogGarbageCollector
extends PhabricatorGarbageCollector {
const COLLECTORCONST = 'drydock.logs';
public function getCollectorName() {
return pht('Drydock Logs');
}
public function getDefaultRetentionPolicy() {
return phutil_units('30 days in seconds');
}
protected function collectGarbage() {
$log_table = new DrydockLog();
$conn_w = $log_table->establishConnection('w');
queryfx(
$conn_w,
'DELETE FROM %T WHERE epoch <= %d LIMIT 100',
$log_table->getTableName(),
$this->getGarbageEpoch());
return ($conn_w->getAffectedRows() == 100);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/view/DrydockLeaseListView.php | src/applications/drydock/view/DrydockLeaseListView.php | <?php
final class DrydockLeaseListView extends AphrontView {
private $leases;
public function setLeases(array $leases) {
assert_instances_of($leases, 'DrydockLease');
$this->leases = $leases;
return $this;
}
public function render() {
$leases = $this->leases;
$viewer = $this->getUser();
$view = new PHUIObjectItemListView();
foreach ($leases as $lease) {
$item = id(new PHUIObjectItemView())
->setUser($viewer)
->setHeader($lease->getLeaseName())
->setHref('/drydock/lease/'.$lease->getID().'/');
$resource_phid = $lease->getResourcePHID();
if ($resource_phid) {
$item->addAttribute(
$viewer->renderHandle($resource_phid));
} else {
$item->addAttribute(
pht(
'Resource: %s',
$lease->getResourceType()));
}
$item->setEpoch($lease->getDateCreated());
$icon = $lease->getStatusIcon();
$color = $lease->getStatusColor();
$label = $lease->getStatusDisplayName();
$item->setStatusIcon("{$icon} {$color}", $label);
$view->addItem($item);
}
return $view;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/view/DrydockAuthorizationListView.php | src/applications/drydock/view/DrydockAuthorizationListView.php | <?php
final class DrydockAuthorizationListView extends AphrontView {
private $authorizations;
private $noDataString;
public function setAuthorizations(array $authorizations) {
assert_instances_of($authorizations, 'DrydockAuthorization');
$this->authorizations = $authorizations;
return $this;
}
public function setNoDataString($string) {
$this->noDataString = $string;
return $this;
}
public function getNoDataString() {
return $this->noDataString;
}
public function render() {
$viewer = $this->getUser();
$authorizations = $this->authorizations;
$view = new PHUIObjectItemListView();
$nodata = $this->getNoDataString();
if ($nodata) {
$view->setNoDataString($nodata);
}
$handles = $viewer->loadHandles(mpull($authorizations, 'getObjectPHID'));
foreach ($authorizations as $authorization) {
$id = $authorization->getID();
$object_phid = $authorization->getObjectPHID();
$handle = $handles[$object_phid];
$item = id(new PHUIObjectItemView())
->setHref("/drydock/authorization/{$id}/")
->setObjectName(pht('Authorization %d', $id))
->setHeader($handle->getFullName());
$item->addAttribute($handle->getTypeName());
$object_state = $authorization->getObjectAuthorizationState();
$item->addAttribute(
DrydockAuthorization::getObjectStateName($object_state));
$state = $authorization->getBlueprintAuthorizationState();
$icon = DrydockAuthorization::getBlueprintStateIcon($state);
$name = DrydockAuthorization::getBlueprintStateName($state);
$item->setStatusIcon($icon, $name);
$view->addItem($item);
}
return $view;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/view/DrydockObjectAuthorizationView.php | src/applications/drydock/view/DrydockObjectAuthorizationView.php | <?php
final class DrydockObjectAuthorizationView extends AphrontView {
private $objectPHID;
private $blueprintPHIDs;
public function setObjectPHID($object_phid) {
$this->objectPHID = $object_phid;
return $this;
}
public function getObjectPHID() {
return $this->objectPHID;
}
public function setBlueprintPHIDs(array $blueprint_phids) {
$this->blueprintPHIDs = $blueprint_phids;
return $this;
}
public function getBlueprintPHIDs() {
return $this->blueprintPHIDs;
}
public function render() {
$viewer = $this->getUser();
$blueprint_phids = $this->getBlueprintPHIDs();
$object_phid = $this->getObjectPHID();
// NOTE: We're intentionally letting you see the authorization state on
// blueprints you can't see because this has a tremendous potential to
// be extremely confusing otherwise. You still can't see the blueprints
// themselves, but you can know if the object is authorized on something.
if ($blueprint_phids) {
$handles = $viewer->loadHandles($blueprint_phids);
$authorizations = id(new DrydockAuthorizationQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withObjectPHIDs(array($object_phid))
->withBlueprintPHIDs($blueprint_phids)
->execute();
$authorizations = mpull($authorizations, null, 'getBlueprintPHID');
} else {
$handles = array();
$authorizations = array();
}
$warnings = array();
$items = array();
foreach ($blueprint_phids as $phid) {
$authorization = idx($authorizations, $phid);
if (!$authorization) {
continue;
}
$handle = $handles[$phid];
$item = id(new PHUIStatusItemView())
->setTarget($handle->renderLink());
$state = $authorization->getBlueprintAuthorizationState();
$item->setIcon(
DrydockAuthorization::getBlueprintStateIcon($state),
null,
DrydockAuthorization::getBlueprintStateName($state));
switch ($state) {
case DrydockAuthorization::BLUEPRINTAUTH_REQUESTED:
case DrydockAuthorization::BLUEPRINTAUTH_DECLINED:
$warnings[] = $authorization;
break;
}
$items[] = $item;
}
$status = new PHUIStatusListView();
if ($warnings) {
$status->addItem(
id(new PHUIStatusItemView())
->setIcon('fa-exclamation-triangle', 'pink')
->setTarget(
pht(
'WARNING: There are %s unapproved authorization(s)!',
new PhutilNumber(count($warnings)))));
}
foreach ($items as $item) {
$status->addItem($item);
}
return $status;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/view/DrydockLogListView.php | src/applications/drydock/view/DrydockLogListView.php | <?php
final class DrydockLogListView extends AphrontView {
private $logs;
private $hideBlueprints;
private $hideResources;
private $hideLeases;
private $hideOperations;
public function setHideBlueprints($hide_blueprints) {
$this->hideBlueprints = $hide_blueprints;
return $this;
}
public function getHideBlueprints() {
return $this->hideBlueprints;
}
public function setHideResources($hide_resources) {
$this->hideResources = $hide_resources;
return $this;
}
public function getHideResources() {
return $this->hideResources;
}
public function setHideLeases($hide_leases) {
$this->hideLeases = $hide_leases;
return $this;
}
public function getHideLeases() {
return $this->hideLeases;
}
public function setHideOperations($hide_operations) {
$this->hideOperations = $hide_operations;
return $this;
}
public function getHideOperations() {
return $this->hideOperations;
}
public function setLogs(array $logs) {
assert_instances_of($logs, 'DrydockLog');
$this->logs = $logs;
return $this;
}
public function render() {
$logs = $this->logs;
$viewer = $this->getUser();
$view = new PHUIObjectItemListView();
$types = DrydockLogType::getAllLogTypes();
$rows = array();
foreach ($logs as $log) {
$blueprint_phid = $log->getBlueprintPHID();
if ($blueprint_phid) {
$blueprint = $viewer->renderHandle($blueprint_phid);
} else {
$blueprint = null;
}
$resource_phid = $log->getResourcePHID();
if ($resource_phid) {
$resource = $viewer->renderHandle($resource_phid);
} else {
$resource = null;
}
$lease_phid = $log->getLeasePHID();
if ($lease_phid) {
$lease = $viewer->renderHandle($lease_phid);
} else {
$lease = null;
}
$operation_phid = $log->getOperationPHID();
if ($operation_phid) {
$operation = $viewer->renderHandle($operation_phid);
} else {
$operation = null;
}
if ($log->isComplete()) {
$type_key = $log->getType();
if (isset($types[$type_key])) {
$type_object = id(clone $types[$type_key])
->setLog($log)
->setViewer($viewer);
$log_data = $log->getData();
$type = $type_object->getLogTypeName();
$icon = $type_object->getLogTypeIcon($log_data);
$data = $type_object->renderLogForHTML($log_data);
$data = phutil_escape_html_newlines($data);
} else {
$type = pht('<Unknown: %s>', $type_key);
$data = null;
$icon = 'fa-question-circle red';
}
} else {
$type = phutil_tag('em', array(), pht('Restricted'));
$data = phutil_tag(
'em',
array(),
pht('You do not have permission to view this log event.'));
$icon = 'fa-lock grey';
}
$rows[] = array(
$blueprint,
$resource,
$lease,
$operation,
id(new PHUIIconView())->setIcon($icon),
$type,
$data,
phabricator_datetime($log->getEpoch(), $viewer),
);
}
$table = id(new AphrontTableView($rows))
->setDeviceReadyTable(true)
->setHeaders(
array(
pht('Blueprint'),
pht('Resource'),
pht('Lease'),
pht('Operation'),
null,
pht('Type'),
pht('Data'),
pht('Date'),
))
->setColumnVisibility(
array(
!$this->getHideBlueprints(),
!$this->getHideResources(),
!$this->getHideLeases(),
!$this->getHideOperations(),
))
->setColumnClasses(
array(
'',
'',
'',
'',
'icon',
'',
'wide',
'',
));
return $table;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/view/DrydockRepositoryOperationStatusView.php | src/applications/drydock/view/DrydockRepositoryOperationStatusView.php | <?php
final class DrydockRepositoryOperationStatusView
extends AphrontView {
private $operation;
private $boxView;
public function setOperation(DrydockRepositoryOperation $operation) {
$this->operation = $operation;
return $this;
}
public function getOperation() {
return $this->operation;
}
public function setBoxView(PHUIObjectBoxView $box_view) {
$this->boxView = $box_view;
return $this;
}
public function getBoxView() {
return $this->boxView;
}
public function render() {
$viewer = $this->getUser();
$operation = $this->getOperation();
$list = $this->renderUnderwayState();
// If the operation is currently underway, refresh the status view.
if ($operation->isUnderway()) {
$status_id = celerity_generate_unique_node_id();
$id = $operation->getID();
$list->setID($status_id);
Javelin::initBehavior(
'drydock-live-operation-status',
array(
'statusID' => $status_id,
'updateURI' => "/drydock/operation/{$id}/status/",
));
}
$box_view = $this->getBoxView();
if (!$box_view) {
$box_view = id(new PHUIObjectBoxView())
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setHeaderText(pht('Operation Status'));
}
$box_view->setObjectList($list);
return $box_view;
}
public function renderUnderwayState() {
$viewer = $this->getUser();
$operation = $this->getOperation();
$id = $operation->getID();
$state = $operation->getOperationState();
$icon = DrydockRepositoryOperation::getOperationStateIcon($state);
$name = DrydockRepositoryOperation::getOperationStateName($state);
$item = id(new PHUIObjectItemView())
->setHref("/drydock/operation/{$id}/")
->setObjectName(pht('Operation %d', $id))
->setHeader($operation->getOperationDescription($viewer))
->setStatusIcon($icon, $name);
if ($state != DrydockRepositoryOperation::STATE_FAIL) {
$item->addAttribute($operation->getOperationCurrentStatus($viewer));
} else {
$vcs_error = $operation->getCommandError();
if ($vcs_error) {
switch ($vcs_error['phase']) {
case DrydockWorkingCopyBlueprintImplementation::PHASE_SQUASHMERGE:
$message = pht(
'This change did not merge cleanly. This usually indicates '.
'that the change is out of date and needs to be updated.');
break;
case DrydockWorkingCopyBlueprintImplementation::PHASE_REMOTEFETCH:
$message = pht(
'This change could not be fetched from the remote.');
break;
case DrydockWorkingCopyBlueprintImplementation::PHASE_MERGEFETCH:
$message = pht(
'This change could not be fetched from the remote staging '.
'area. It may not have been pushed, or may have been removed.');
break;
case DrydockLandRepositoryOperation::PHASE_COMMIT:
$message = pht(
'Committing this change failed. It may already have been '.
'merged.');
break;
case DrydockLandRepositoryOperation::PHASE_PUSH:
$message = pht(
'The push failed. This usually indicates '.
'that the change is breaking some rules or '.
'some custom commit hook has failed.');
break;
default:
$message = pht(
'Operation encountered an error while performing repository '.
'operations.');
break;
}
$item->addAttribute($message);
$table = $this->renderVCSErrorTable($vcs_error);
list($links, $info) = $this->renderDetailToggles($table);
$item->addAttribute($links);
$item->appendChild($info);
} else {
$item->addAttribute(pht('Operation encountered an error.'));
}
$is_dismissed = $operation->getIsDismissed();
$item->addAction(
id(new PHUIListItemView())
->setName('Dismiss')
->setIcon('fa-times')
->setDisabled($is_dismissed)
->setWorkflow(true)
->setHref("/drydock/operation/{$id}/dismiss/"));
}
return id(new PHUIObjectItemListView())
->addItem($item);
}
private function renderVCSErrorTable(array $vcs_error) {
$rows = array();
$rows[] = array(
pht('Command'),
phutil_censor_credentials($vcs_error['command']),
);
$rows[] = array(pht('Error'), $vcs_error['err']);
$rows[] = array(
pht('Stdout'),
phutil_censor_credentials($vcs_error['stdout']),
);
$rows[] = array(
pht('Stderr'),
phutil_censor_credentials($vcs_error['stderr']),
);
$table = id(new AphrontTableView($rows))
->setColumnClasses(
array(
'header',
'wide prewrap',
));
return $table;
}
private function renderDetailToggles(AphrontTableView $table) {
$show_id = celerity_generate_unique_node_id();
$hide_id = celerity_generate_unique_node_id();
$info_id = celerity_generate_unique_node_id();
Javelin::initBehavior('phabricator-reveal-content');
$show_details = javelin_tag(
'a',
array(
'id' => $show_id,
'href' => '#',
'sigil' => 'reveal-content',
'mustcapture' => true,
'meta' => array(
'hideIDs' => array($show_id),
'showIDs' => array($hide_id, $info_id),
),
),
pht('Show Details'));
$hide_details = javelin_tag(
'a',
array(
'id' => $hide_id,
'href' => '#',
'sigil' => 'reveal-content',
'mustcapture' => true,
'style' => 'display: none',
'meta' => array(
'hideIDs' => array($hide_id, $info_id),
'showIDs' => array($show_id),
),
),
pht('Hide Details'));
$info = javelin_tag(
'div',
array(
'id' => $info_id,
'style' => 'display: none',
),
$table);
$links = array(
$show_details,
$hide_details,
);
return array($links, $info);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/view/DrydockResourceListView.php | src/applications/drydock/view/DrydockResourceListView.php | <?php
final class DrydockResourceListView extends AphrontView {
private $resources;
public function setResources(array $resources) {
assert_instances_of($resources, 'DrydockResource');
$this->resources = $resources;
return $this;
}
public function render() {
$resources = $this->resources;
$viewer = $this->getUser();
$view = new PHUIObjectItemListView();
foreach ($resources as $resource) {
$id = $resource->getID();
$item = id(new PHUIObjectItemView())
->setHref("/drydock/resource/{$id}/")
->setObjectName(pht('Resource %d', $id))
->setHeader($resource->getResourceName());
$icon = $resource->getStatusIcon();
$color = $resource->getStatusColor();
$label = $resource->getStatusDisplayName();
$item->setStatusIcon("{$icon} {$color}", $label);
$view->addItem($item);
}
return $view;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseActivatedLogType.php | src/applications/drydock/logtype/DrydockLeaseActivatedLogType.php | <?php
final class DrydockLeaseActivatedLogType extends DrydockLogType {
const LOGCONST = 'core.lease.activated';
public function getLogTypeName() {
return pht('Lease Activated');
}
public function getLogTypeIcon(array $data) {
return 'fa-link green';
}
public function renderLog(array $data) {
return pht('Lease activated.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockResourceAllocationFailureLogType.php | src/applications/drydock/logtype/DrydockResourceAllocationFailureLogType.php | <?php
final class DrydockResourceAllocationFailureLogType extends DrydockLogType {
const LOGCONST = 'core.resource.allocation-failure';
public function getLogTypeName() {
return pht('Allocation Failed');
}
public function getLogTypeIcon(array $data) {
return 'fa-times red';
}
public function renderLog(array $data) {
$class = idx($data, 'class');
$message = idx($data, 'message');
return pht(
'Blueprint failed to allocate a resource after claiming it would '.
'be able to: [%s] %s',
$class,
$message);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseReclaimLogType.php | src/applications/drydock/logtype/DrydockLeaseReclaimLogType.php | <?php
final class DrydockLeaseReclaimLogType extends DrydockLogType {
const LOGCONST = 'core.lease.reclaim';
public function getLogTypeName() {
return pht('Reclaimed Resources');
}
public function getLogTypeIcon(array $data) {
return 'fa-refresh yellow';
}
public function renderLog(array $data) {
$resource_phids = idx($data, 'resourcePHIDs', array());
return pht(
'Reclaimed resource %s.',
$this->renderHandleList($resource_phids));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseWaitingForActivationLogType.php | src/applications/drydock/logtype/DrydockLeaseWaitingForActivationLogType.php | <?php
final class DrydockLeaseWaitingForActivationLogType extends DrydockLogType {
const LOGCONST = 'core.lease.waiting-for-activation';
public function getLogTypeName() {
return pht('Waiting For Activation');
}
public function getLogTypeIcon(array $data) {
return 'fa-clock-o yellow';
}
public function renderLog(array $data) {
$resource_phids = idx($data, 'resourcePHIDs', array());
return pht(
'Waiting for activation of resources: %s.',
$this->renderHandleList($resource_phids));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockTextLogType.php | src/applications/drydock/logtype/DrydockTextLogType.php | <?php
/**
* Simple convenience log type for logging arbitrary text.
*
* Drydock logs can be given formal types, which allows them to be translated
* and filtered. If you don't particularly care about fancy logging features,
* you can use this log type to just dump some text into the log. Maybe you
* could upgrade to more formal logging later.
*/
final class DrydockTextLogType extends DrydockLogType {
const LOGCONST = 'core.text';
public function getLogTypeName() {
return pht('Text');
}
public function getLogTypeIcon(array $data) {
return 'fa-file-text-o grey';
}
public function renderLog(array $data) {
return idx($data, 'text');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockSlotLockFailureLogType.php | src/applications/drydock/logtype/DrydockSlotLockFailureLogType.php | <?php
final class DrydockSlotLockFailureLogType extends DrydockLogType {
const LOGCONST = 'core.resource.slot-lock.failure';
public function getLogTypeName() {
return pht('Slot Lock Failure');
}
public function getLogTypeIcon(array $data) {
return 'fa-lock yellow';
}
public function renderLog(array $data) {
$locks = idx($data, 'locks', array());
if ($locks) {
return pht(
'Failed to acquire slot locks: %s.',
implode(', ', array_keys($locks)));
} else {
return pht('Failed to acquire slot locks.');
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseWaitingForReclamationLogType.php | src/applications/drydock/logtype/DrydockLeaseWaitingForReclamationLogType.php | <?php
final class DrydockLeaseWaitingForReclamationLogType extends DrydockLogType {
const LOGCONST = 'core.lease.waiting-for-reclamation';
public function getLogTypeName() {
return pht('Waiting For Reclamation');
}
public function getLogTypeIcon(array $data) {
return 'fa-clock-o yellow';
}
public function renderLog(array $data) {
$resource_phids = idx($data, 'resourcePHIDs', array());
return pht(
'Waiting for reclamation of resources: %s.',
$this->renderHandleList($resource_phids));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseActivationFailureLogType.php | src/applications/drydock/logtype/DrydockLeaseActivationFailureLogType.php | <?php
final class DrydockLeaseActivationFailureLogType extends DrydockLogType {
const LOGCONST = 'core.lease.activation-failure';
public function getLogTypeName() {
return pht('Activation Failed');
}
public function getLogTypeIcon(array $data) {
return 'fa-times red';
}
public function renderLog(array $data) {
$class = idx($data, 'class');
$message = idx($data, 'message');
return pht('Lease activation failed: [%s] %s', $class, $message);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseWaitingForResourcesLogType.php | src/applications/drydock/logtype/DrydockLeaseWaitingForResourcesLogType.php | <?php
final class DrydockLeaseWaitingForResourcesLogType extends DrydockLogType {
const LOGCONST = 'core.lease.waiting-for-resources';
public function getLogTypeName() {
return pht('Waiting For Resource');
}
public function getLogTypeIcon(array $data) {
return 'fa-clock-o yellow';
}
public function renderLog(array $data) {
$blueprint_phids = idx($data, 'blueprintPHIDs', array());
return pht(
'Waiting for available resources from: %s.',
$this->renderHandleList($blueprint_phids));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseAllocationFailureLogType.php | src/applications/drydock/logtype/DrydockLeaseAllocationFailureLogType.php | <?php
final class DrydockLeaseAllocationFailureLogType extends DrydockLogType {
const LOGCONST = 'core.lease.allocation-failure';
public function getLogTypeName() {
return pht('Allocation Failed');
}
public function getLogTypeIcon(array $data) {
return 'fa-times red';
}
public function renderLog(array $data) {
$class = idx($data, 'class');
$message = idx($data, 'message');
return pht(
'One or more blueprints promised a new resource, but failed when '.
'allocating: [%s] %s',
$class,
$message);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseDestroyedLogType.php | src/applications/drydock/logtype/DrydockLeaseDestroyedLogType.php | <?php
final class DrydockLeaseDestroyedLogType extends DrydockLogType {
const LOGCONST = 'core.lease.destroyed';
public function getLogTypeName() {
return pht('Lease Destroyed');
}
public function getLogTypeIcon(array $data) {
return 'fa-link grey';
}
public function renderLog(array $data) {
return pht('Lease destroyed.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockOperationWorkLogType.php | src/applications/drydock/logtype/DrydockOperationWorkLogType.php | <?php
final class DrydockOperationWorkLogType extends DrydockLogType {
const LOGCONST = 'core.operation.work';
public function getLogTypeName() {
return pht('Started Work');
}
public function getLogTypeIcon(array $data) {
return 'fa-check green';
}
public function renderLog(array $data) {
return pht('Started this operation in a working copy.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseAcquiredLogType.php | src/applications/drydock/logtype/DrydockLeaseAcquiredLogType.php | <?php
final class DrydockLeaseAcquiredLogType extends DrydockLogType {
const LOGCONST = 'core.lease.acquired';
public function getLogTypeName() {
return pht('Lease Acquired');
}
public function getLogTypeIcon(array $data) {
return 'fa-link yellow';
}
public function renderLog(array $data) {
return pht('Lease acquired.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseReleasedLogType.php | src/applications/drydock/logtype/DrydockLeaseReleasedLogType.php | <?php
final class DrydockLeaseReleasedLogType extends DrydockLogType {
const LOGCONST = 'core.lease.released';
public function getLogTypeName() {
return pht('Lease Released');
}
public function getLogTypeIcon(array $data) {
return 'fa-link black';
}
public function renderLog(array $data) {
return pht('Lease released.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockResourceReclaimLogType.php | src/applications/drydock/logtype/DrydockResourceReclaimLogType.php | <?php
final class DrydockResourceReclaimLogType extends DrydockLogType {
const LOGCONST = 'core.resource.reclaim';
public function getLogTypeName() {
return pht('Reclaimed');
}
public function getLogTypeIcon(array $data) {
return 'fa-refresh red';
}
public function renderLog(array $data) {
$reclaimer_phid = idx($data, 'reclaimerPHID');
return pht(
'Resource reclaimed by %s.',
$this->renderHandle($reclaimer_phid));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseReacquireLogType.php | src/applications/drydock/logtype/DrydockLeaseReacquireLogType.php | <?php
final class DrydockLeaseReacquireLogType extends DrydockLogType {
const LOGCONST = 'core.lease.reacquire';
public function getLogTypeName() {
return pht('Reacquiring Resource');
}
public function getLogTypeIcon(array $data) {
return 'fa-refresh yellow';
}
public function renderLog(array $data) {
$class = idx($data, 'class');
$message = idx($data, 'message');
return pht(
'Lease acquired a resource but failed to activate; acquisition '.
'will be retried: [%s] %s',
$class,
$message);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseActivationYieldLogType.php | src/applications/drydock/logtype/DrydockLeaseActivationYieldLogType.php | <?php
final class DrydockLeaseActivationYieldLogType extends DrydockLogType {
const LOGCONST = 'core.lease.activation-yield';
public function getLogTypeName() {
return pht('Waiting for Activation');
}
public function getLogTypeIcon(array $data) {
return 'fa-clock-o green';
}
public function renderLog(array $data) {
$duration = idx($data, 'duration');
return pht(
'Waiting %s second(s) for lease to activate.',
new PhutilNumber($duration));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseNoBlueprintsLogType.php | src/applications/drydock/logtype/DrydockLeaseNoBlueprintsLogType.php | <?php
final class DrydockLeaseNoBlueprintsLogType extends DrydockLogType {
const LOGCONST = 'core.lease.no-blueprints';
public function getLogTypeName() {
return pht('No Blueprints');
}
public function getLogTypeIcon(array $data) {
return 'fa-map-o red';
}
public function renderLog(array $data) {
return pht('This lease does not list any usable blueprints.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseNoAuthorizationsLogType.php | src/applications/drydock/logtype/DrydockLeaseNoAuthorizationsLogType.php | <?php
final class DrydockLeaseNoAuthorizationsLogType extends DrydockLogType {
const LOGCONST = 'core.lease.no-authorizations';
public function getLogTypeName() {
return pht('No Authorizations');
}
public function getLogTypeIcon(array $data) {
return 'fa-map-o red';
}
public function renderLog(array $data) {
$authorizing_phid = idx($data, 'authorizingPHID');
return pht(
'The object which authorized this lease (%s) is not authorized to use '.
'any of the blueprints the lease lists. Approve the authorizations '.
'before using the lease.',
$this->renderHandle($authorizing_phid));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLeaseQueuedLogType.php | src/applications/drydock/logtype/DrydockLeaseQueuedLogType.php | <?php
final class DrydockLeaseQueuedLogType extends DrydockLogType {
const LOGCONST = 'core.lease.queued';
public function getLogTypeName() {
return pht('Lease Queued');
}
public function getLogTypeIcon(array $data) {
return 'fa-link blue';
}
public function renderLog(array $data) {
return pht('Lease queued for acquisition.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockLogType.php | src/applications/drydock/logtype/DrydockLogType.php | <?php
abstract class DrydockLogType extends Phobject {
private $viewer;
private $log;
private $renderingMode = 'text';
abstract public function getLogTypeName();
abstract public function getLogTypeIcon(array $data);
abstract public function renderLog(array $data);
final public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
final public function getViewer() {
return $this->viewer;
}
final public function setLog(DrydockLog $log) {
$this->log = $log;
return $this;
}
final public function getLog() {
return $this->log;
}
final public function getLogTypeConstant() {
return $this->getPhobjectClassConstant('LOGCONST', 64);
}
final public static function getAllLogTypes() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getLogTypeConstant')
->execute();
}
final public function renderLogForText($data) {
$this->renderingMode = 'text';
return $this->renderLog($data);
}
final public function renderLogForHTML($data) {
$this->renderingMode = 'html';
return $this->renderLog($data);
}
final protected function renderHandle($phid) {
$viewer = $this->getViewer();
$handle = $viewer->renderHandle($phid);
if ($this->renderingMode == 'html') {
return $handle->render();
} else {
return $handle->setAsText(true)->render();
}
}
final protected function renderHandleList(array $phids) {
$viewer = $this->getViewer();
$handle_list = $viewer->renderHandleList($phids);
if ($this->renderingMode == 'html') {
return $handle_list->render();
} else {
return $handle_list->setAsText(true)->render();
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockResourceActivationYieldLogType.php | src/applications/drydock/logtype/DrydockResourceActivationYieldLogType.php | <?php
final class DrydockResourceActivationYieldLogType extends DrydockLogType {
const LOGCONST = 'core.resource.activation-yield';
public function getLogTypeName() {
return pht('Waiting for Activation');
}
public function getLogTypeIcon(array $data) {
return 'fa-clock-o green';
}
public function renderLog(array $data) {
$duration = idx($data, 'duration');
return pht(
'Waiting %s second(s) for resource to activate.',
new PhutilNumber($duration));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/logtype/DrydockResourceActivationFailureLogType.php | src/applications/drydock/logtype/DrydockResourceActivationFailureLogType.php | <?php
final class DrydockResourceActivationFailureLogType extends DrydockLogType {
const LOGCONST = 'core.resource.activation-failure';
public function getLogTypeName() {
return pht('Activation Failed');
}
public function getLogTypeIcon(array $data) {
return 'fa-times red';
}
public function renderLog(array $data) {
$class = idx($data, 'class');
$message = idx($data, 'message');
return pht('Resource activation failed: [%s] %s', $class, $message);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/phid/DrydockLeasePHIDType.php | src/applications/drydock/phid/DrydockLeasePHIDType.php | <?php
final class DrydockLeasePHIDType extends PhabricatorPHIDType {
const TYPECONST = 'DRYL';
public function getTypeName() {
return pht('Drydock Lease');
}
public function getTypeIcon() {
return 'fa-link';
}
public function newObject() {
return new DrydockLease();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDrydockApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new DrydockLeaseQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$lease = $objects[$phid];
$id = $lease->getID();
$handle->setName(pht(
'Lease %d',
$id));
$handle->setURI("/drydock/lease/{$id}/");
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/phid/DrydockRepositoryOperationPHIDType.php | src/applications/drydock/phid/DrydockRepositoryOperationPHIDType.php | <?php
final class DrydockRepositoryOperationPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'DRYO';
public function getTypeName() {
return pht('Repository Operation');
}
public function newObject() {
return new DrydockRepositoryOperation();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDrydockApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new DrydockRepositoryOperationQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$operation = $objects[$phid];
$id = $operation->getID();
$handle->setName(pht('Repository Operation %d', $id));
$handle->setURI("/drydock/operation/{$id}/");
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/phid/DrydockResourcePHIDType.php | src/applications/drydock/phid/DrydockResourcePHIDType.php | <?php
final class DrydockResourcePHIDType extends PhabricatorPHIDType {
const TYPECONST = 'DRYR';
public function getTypeName() {
return pht('Drydock Resource');
}
public function getTypeIcon() {
return 'fa-map';
}
public function newObject() {
return new DrydockResource();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDrydockApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new DrydockResourceQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$resource = $objects[$phid];
$id = $resource->getID();
$handle->setName(
pht(
'Resource %d: %s',
$id,
$resource->getResourceName()));
$handle->setURI("/drydock/resource/{$id}/");
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/phid/DrydockBlueprintPHIDType.php | src/applications/drydock/phid/DrydockBlueprintPHIDType.php | <?php
final class DrydockBlueprintPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'DRYB';
public function getTypeName() {
return pht('Blueprint');
}
public function getTypeIcon() {
return 'fa-map-o';
}
public function newObject() {
return new DrydockBlueprint();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDrydockApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new DrydockBlueprintQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$blueprint = $objects[$phid];
$id = $blueprint->getID();
$name = $blueprint->getBlueprintName();
$handle
->setName($name)
->setFullName(pht('Blueprint %d: %s', $id, $name))
->setURI("/drydock/blueprint/{$id}/");
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/phid/DrydockAuthorizationPHIDType.php | src/applications/drydock/phid/DrydockAuthorizationPHIDType.php | <?php
final class DrydockAuthorizationPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'DRYA';
public function getTypeName() {
return pht('Drydock Authorization');
}
public function newObject() {
return new DrydockAuthorization();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDrydockApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new DrydockAuthorizationQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$authorization = $objects[$phid];
$id = $authorization->getID();
$handle->setName(pht('Drydock Authorization %d', $id));
$handle->setURI("/drydock/authorization/{$id}/");
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/conduit/DrydockResourceSearchConduitAPIMethod.php | src/applications/drydock/conduit/DrydockResourceSearchConduitAPIMethod.php | <?php
final class DrydockResourceSearchConduitAPIMethod
extends PhabricatorSearchEngineAPIMethod {
public function getAPIMethodName() {
return 'drydock.resource.search';
}
public function newSearchEngine() {
return new DrydockResourceSearchEngine();
}
public function getMethodSummary() {
return pht('Retrieve information about Drydock resources.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/conduit/DrydockAuthorizationSearchConduitAPIMethod.php | src/applications/drydock/conduit/DrydockAuthorizationSearchConduitAPIMethod.php | <?php
final class DrydockAuthorizationSearchConduitAPIMethod
extends PhabricatorSearchEngineAPIMethod {
public function getAPIMethodName() {
return 'drydock.authorization.search';
}
public function newSearchEngine() {
return new DrydockAuthorizationSearchEngine();
}
public function getMethodSummary() {
return pht('Retrieve information about Drydock authorizations.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/conduit/DrydockLeaseSearchConduitAPIMethod.php | src/applications/drydock/conduit/DrydockLeaseSearchConduitAPIMethod.php | <?php
final class DrydockLeaseSearchConduitAPIMethod
extends PhabricatorSearchEngineAPIMethod {
public function getAPIMethodName() {
return 'drydock.lease.search';
}
public function newSearchEngine() {
return new DrydockLeaseSearchEngine();
}
public function getMethodSummary() {
return pht('Retrieve information about Drydock leases.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/conduit/DrydockBlueprintSearchConduitAPIMethod.php | src/applications/drydock/conduit/DrydockBlueprintSearchConduitAPIMethod.php | <?php
final class DrydockBlueprintSearchConduitAPIMethod
extends PhabricatorSearchEngineAPIMethod {
public function getAPIMethodName() {
return 'drydock.blueprint.search';
}
public function newSearchEngine() {
return new DrydockBlueprintSearchEngine();
}
public function getMethodSummary() {
return pht('Retrieve information about Drydock blueprints.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/conduit/DrydockBlueprintEditConduitAPIMethod.php | src/applications/drydock/conduit/DrydockBlueprintEditConduitAPIMethod.php | <?php
final class DrydockBlueprintEditConduitAPIMethod
extends PhabricatorEditEngineAPIMethod {
public function getAPIMethodName() {
return 'drydock.blueprint.edit';
}
public function newEditEngine() {
return new DrydockBlueprintEditEngine();
}
public function getMethodSummary() {
return pht(
'Apply transactions to create or edit a blueprint.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/typeahead/DrydockBlueprintDatasource.php | src/applications/drydock/typeahead/DrydockBlueprintDatasource.php | <?php
final class DrydockBlueprintDatasource
extends PhabricatorTypeaheadDatasource {
public function getPlaceholderText() {
return pht('Type a blueprint name...');
}
public function getBrowseTitle() {
return pht('Browse Blueprints');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDrydockApplication';
}
public function loadResults() {
$viewer = $this->getViewer();
$raw_query = $this->getRawQuery();
$blueprints = id(new DrydockBlueprintQuery())
->setViewer($viewer)
->withDatasourceQuery($raw_query)
->execute();
$handles = id(new PhabricatorHandleQuery())
->setViewer($viewer)
->withPHIDs(mpull($blueprints, 'getPHID'))
->execute();
$results = array();
foreach ($blueprints as $blueprint) {
$handle = $handles[$blueprint->getPHID()];
$result = id(new PhabricatorTypeaheadResult())
->setName($handle->getFullName())
->setPHID($handle->getPHID());
if ($blueprint->getIsDisabled()) {
$result->setClosed(pht('Disabled'));
}
$result->addAttribute(
$blueprint->getImplementation()->getBlueprintName());
$results[] = $result;
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/typeahead/DrydockResourceDatasource.php | src/applications/drydock/typeahead/DrydockResourceDatasource.php | <?php
final class DrydockResourceDatasource
extends PhabricatorTypeaheadDatasource {
public function getPlaceholderText() {
return pht('Type a resource name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDrydockApplication';
}
public function loadResults() {
$viewer = $this->getViewer();
$raw_query = $this->getRawQuery();
$resources = id(new DrydockResourceQuery())
->setViewer($viewer)
->withDatasourceQuery($raw_query)
->execute();
$handles = id(new PhabricatorHandleQuery())
->setViewer($viewer)
->withPHIDs(mpull($resources, 'getPHID'))
->execute();
$results = array();
foreach ($handles as $handle) {
$results[] = id(new PhabricatorTypeaheadResult())
->setName($handle->getName())
->setPHID($handle->getPHID());
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/typeahead/DrydockLeaseDatasource.php | src/applications/drydock/typeahead/DrydockLeaseDatasource.php | <?php
final class DrydockLeaseDatasource
extends PhabricatorTypeaheadDatasource {
public function getPlaceholderText() {
return pht('Type a lease ID (exact match)...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDrydockApplication';
}
public function loadResults() {
$viewer = $this->getViewer();
$raw_query = $this->getRawQuery();
$leases = id(new DrydockLeaseQuery())
->setViewer($viewer)
->withDatasourceQuery($raw_query)
->execute();
$handles = id(new PhabricatorHandleQuery())
->setViewer($viewer)
->withPHIDs(mpull($leases, 'getPHID'))
->execute();
$results = array();
foreach ($handles as $handle) {
$results[] = id(new PhabricatorTypeaheadResult())
->setName($handle->getName())
->setPHID($handle->getPHID());
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/drydock/capability/DrydockCreateBlueprintsCapability.php | src/applications/drydock/capability/DrydockCreateBlueprintsCapability.php | <?php
final class DrydockCreateBlueprintsCapability
extends PhabricatorPolicyCapability {
const CAPABILITY = 'drydock.blueprint.create';
public function getCapabilityName() {
return pht('Can Create Blueprints');
}
public function describeCapabilityRejection() {
return pht('You do not have permission to create Drydock blueprints.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.