3 final class DrydockManagementLeaseWorkflow
4 extends DrydockManagementWorkflow
{
6 protected function didConstruct() {
9 ->setSynopsis(pht('Lease a resource.'))
14 'param' => 'resource_type',
15 'help' => pht('Resource type.'),
20 'help' => pht('Set lease expiration time.'),
23 'name' => 'attributes',
26 'JSON file with lease attributes. Use "-" to read attributes '.
33 'help' => pht('Lease a given number of identical resources.'),
36 'name' => 'blueprint',
37 'param' => 'identifier',
39 'help' => pht('Lease resources from a specific blueprint.'),
44 public function execute(PhutilArgumentParser
$args) {
45 $viewer = $this->getViewer();
47 $resource_type = $args->getArg('type');
48 if (!phutil_nonempty_string($resource_type)) {
49 throw new PhutilArgumentUsageException(
51 'Specify a resource type with "--type".'));
54 $until = $args->getArg('until');
55 if (phutil_nonempty_string($until)) {
56 $until = strtotime($until);
58 throw new PhutilArgumentUsageException(
60 'Unable to parse argument to "--until".'));
64 $count = $args->getArgAsInteger('count');
66 throw new PhutilArgumentUsageException(
68 'Value provided to "--count" must be a nonzero, positive '.
72 $attributes_file = $args->getArg('attributes');
73 if (phutil_nonempty_string($attributes_file)) {
74 if ($attributes_file == '-') {
77 pht('Reading JSON attributes from stdin...'));
78 $data = file_get_contents('php://stdin');
80 $data = Filesystem
::readFile($attributes_file);
83 $attributes = phutil_json_decode($data);
85 $attributes = array();
88 $filter_identifiers = $args->getArg('blueprint');
89 if ($filter_identifiers) {
90 $filter_blueprints = $this->getBlueprintFilterMap($filter_identifiers);
92 $filter_blueprints = array();
95 $blueprint_phids = null;
98 for ($idx = 0; $idx < $count; $idx++
) {
99 $lease = id(new DrydockLease())
100 ->setResourceType($resource_type);
102 $drydock_phid = id(new PhabricatorDrydockApplication())->getPHID();
103 $lease->setAuthorizingPHID($drydock_phid);
106 $lease->setAttributes($attributes);
109 if ($blueprint_phids === null) {
110 $blueprint_phids = $this->newAllowedBlueprintPHIDs(
115 $lease->setAllowedBlueprintPHIDs($blueprint_phids);
118 $lease->setUntil($until);
121 // If something fatals or the user interrupts the process (for example,
122 // with "^C"), release the lease. We'll cancel this below, if the lease
123 // actually activates.
124 $lease->setReleaseOnDestruction(true);
129 // TODO: This would probably be better handled with PhutilSignalRouter,
130 // but it currently doesn't route SIGINT. We're initializing it to setup
131 // SIGTERM handling and make eventual migration easier.
132 $router = PhutilSignalRouter
::getRouter();
133 pcntl_signal(SIGINT
, array($this, 'didReceiveInterrupt'));
135 $t_start = microtime(true);
140 pht('Leases queued for activation:'));
142 foreach ($leases as $lease) {
143 $lease->queueForActivation();
147 PhabricatorEnv
::getProductionURI($lease->getURI()));
152 pht('Waiting for daemons to activate leases...'));
154 foreach ($leases as $lease) {
155 $this->waitUntilActive($lease);
158 // Now that we've survived activation and the lease is good, make it
160 foreach ($leases as $lease) {
161 $lease->setReleaseOnDestruction(false);
164 $t_end = microtime(true);
169 'Activation complete. Leases are permanent until manually '.
172 foreach ($leases as $lease) {
175 pht('$ ./bin/drydock release-lease --id %d', $lease->getID()));
181 'Leases activated in %sms.',
182 new PhutilNumber((int)(($t_end - $t_start) * 1000))));
187 public function didReceiveInterrupt($signo) {
188 // Doing this makes us run destructors, particularly the "release on
189 // destruction" trigger on the lease.
193 private function waitUntilActive(DrydockLease
$lease) {
194 $viewer = $this->getViewer();
197 $log_types = DrydockLogType
::getAllLogTypes();
200 while (!$is_active) {
203 $pager = id(new AphrontCursorPagerView())
204 ->setBeforeID($log_cursor);
206 // While we're waiting, show the user any logs which the daemons have
207 // generated to give them some clue about what's going on.
208 $logs = id(new DrydockLogQuery())
210 ->withLeasePHIDs(array($lease->getPHID()))
211 ->executeWithCursorPager($pager);
213 $logs = mpull($logs, null, 'getID');
215 $log_cursor = last_key($logs);
218 foreach ($logs as $log) {
219 $type_key = $log->getType();
220 if (isset($log_types[$type_key])) {
221 $type_object = id(clone $log_types[$type_key])
223 ->setViewer($viewer);
225 $log_data = $log->getData();
227 $type = $type_object->getLogTypeName();
228 $data = $type_object->renderLogForText($log_data);
230 $type = pht('Unknown ("%s")', $type_key);
235 "(Lease #%d) <%s> %B\n",
241 $status = $lease->getStatus();
244 case DrydockLeaseStatus
::STATUS_ACTIVE
:
247 case DrydockLeaseStatus
::STATUS_RELEASED
:
248 throw new Exception(pht('Lease has already been released!'));
249 case DrydockLeaseStatus
::STATUS_DESTROYED
:
250 throw new Exception(pht('Lease has already been destroyed!'));
251 case DrydockLeaseStatus
::STATUS_BROKEN
:
252 throw new Exception(pht('Lease has been broken!'));
253 case DrydockLeaseStatus
::STATUS_PENDING
:
254 case DrydockLeaseStatus
::STATUS_ACQUIRED
:
259 'Lease has unknown status "%s".',
271 private function getBlueprintFilterMap(array $identifiers) {
272 $viewer = $this->getViewer();
274 $query = id(new DrydockBlueprintQuery())
276 ->withIdentifiers($identifiers);
278 $blueprints = $query->execute();
279 $blueprints = mpull($blueprints, null, 'getPHID');
281 $map = $query->getIdentifierMap();
284 foreach ($identifiers as $identifier) {
285 if (!isset($map[$identifier])) {
286 throw new PhutilArgumentUsageException(
288 'Blueprint "%s" could not be loaded. Try a blueprint ID or '.
293 $blueprint = $map[$identifier];
295 $blueprint_phid = $blueprint->getPHID();
296 if (isset($seen[$blueprint_phid])) {
297 throw new PhutilArgumentUsageException(
299 'Blueprint "%s" is specified more than once (as "%s" and "%s").',
300 $blueprint->getBlueprintName(),
301 $seen[$blueprint_phid],
305 $seen[$blueprint_phid] = true;
308 return mpull($map, null, 'getPHID');
311 private function newAllowedBlueprintPHIDs(
313 array $filter_blueprints) {
314 assert_instances_of($filter_blueprints, 'DrydockBlueprint');
316 $viewer = $this->getViewer();
318 $impls = DrydockBlueprintImplementation
::getAllForAllocatingLease($lease);
321 throw new PhutilArgumentUsageException(
323 'No known blueprint class can ever allocate the specified '.
324 'lease. Check that the resource type is spelled correctly.'));
327 $classes = array_keys($impls);
329 $blueprints = id(new DrydockBlueprintQuery())
331 ->withBlueprintClasses($classes)
332 ->withDisabled(false)
336 throw new PhutilArgumentUsageException(
338 'No enabled blueprints exist with a blueprint class that can '.
339 'plausibly allocate resources to satisfy the requested lease.'));
342 $phids = mpull($blueprints, 'getPHID');
344 if ($filter_blueprints) {
345 $allowed_map = array_fuse($phids);
346 $filter_map = mpull($filter_blueprints, null, 'getPHID');
348 foreach ($filter_map as $filter_phid => $blueprint) {
349 if (!isset($allowed_map[$filter_phid])) {
350 throw new PhutilArgumentUsageException(
352 'Specified blueprint "%s" is not capable of satisfying the '.
354 $blueprint->getBlueprintName()));
358 $phids = mpull($filter_blueprints, 'getPHID');