public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $resource_type = $args->getArg('type');
     if (!$resource_type) {
         throw new PhutilArgumentUsageException(pht('Specify a resource type with `%s`.', '--type'));
     }
     $until = $args->getArg('until');
     if (strlen($until)) {
         $until = strtotime($until);
         if ($until <= 0) {
             throw new PhutilArgumentUsageException(pht('Unable to parse argument to "%s".', '--until'));
         }
     }
     $attributes = $args->getArg('attributes');
     if ($attributes) {
         $options = new PhutilSimpleOptions();
         $options->setCaseSensitive(true);
         $attributes = $options->parse($attributes);
     }
     $lease = id(new DrydockLease())->setResourceType($resource_type);
     if ($attributes) {
         $lease->setAttributes($attributes);
     }
     if ($until) {
         $lease->setUntil($until);
     }
     $lease->queueForActivation();
     echo tsprintf("%s\n", pht('Waiting for daemons to activate lease...'));
     $lease->waitUntilActive();
     echo tsprintf("%s\n", pht('Activated lease "%s".', $lease->getID()));
     return 0;
 }
 public function run()
 {
     static $color_map = array('Closed' => 'cyan', 'Needs Review' => 'magenta', 'Needs Revision' => 'red', 'Changes Planned' => 'red', 'Accepted' => 'green', 'No Revision' => 'blue', 'Abandoned' => 'default');
     $revisions = $this->getConduit()->callMethodSynchronous('differential.query', array('authors' => array($this->getUserPHID()), 'status' => 'status-open'));
     if (!$revisions) {
         echo pht('You have no open Differential revisions.') . "\n";
         return 0;
     }
     $repository_api = $this->getRepositoryAPI();
     $info = array();
     foreach ($revisions as $key => $revision) {
         $revision_path = Filesystem::resolvePath($revision['sourcePath']);
         $current_path = Filesystem::resolvePath($repository_api->getPath());
         if ($revision_path == $current_path) {
             $info[$key]['exists'] = 1;
         } else {
             $info[$key]['exists'] = 0;
         }
         $info[$key]['sort'] = sprintf('%d%04d%08d', $info[$key]['exists'], $revision['status'], $revision['id']);
         $info[$key]['statusName'] = $revision['statusName'];
         $info[$key]['color'] = idx($color_map, $revision['statusName'], 'default');
     }
     $table = id(new PhutilConsoleTable())->setShowHeader(false)->addColumn('exists', array('title' => ''))->addColumn('status', array('title' => pht('Status')))->addColumn('title', array('title' => pht('Title')));
     $info = isort($info, 'sort');
     foreach ($info as $key => $spec) {
         $revision = $revisions[$key];
         $table->addRow(array('exists' => $spec['exists'] ? tsprintf('**%s**', '*') : '', 'status' => tsprintf("<fg:{$spec['color']}>%s</fg>", $spec['statusName']), 'title' => tsprintf('**D%d:** %s', $revision['id'], $revision['title'])));
     }
     $table->draw();
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $source = $this->loadSource($args, 'source');
     $definition = $source->getDefinition()->setViewer($this->getViewer())->setSource($source);
     if (!$definition->hasImportCursors()) {
         throw new PhutilArgumentUsageException(pht('This source ("%s") does not expose import cursors.', $source->getName()));
     }
     $cursors = $definition->getImportCursors();
     if (!$cursors) {
         throw new PhutilArgumentUsageException(pht('This source ("%s") does not have any import cursors.', $source->getName()));
     }
     $select = $args->getArg('cursor');
     if (strlen($select)) {
         if (empty($cursors[$select])) {
             throw new PhutilArgumentUsageException(pht('This source ("%s") does not have a "%s" cursor. Available ' . 'cursors: %s.', $source->getName(), $select, implode(', ', array_keys($cursors))));
         } else {
             echo tsprintf("%s\n", pht('Importing cursor "%s" only.', $select));
             $cursors = array_select_keys($cursors, array($select));
         }
     } else {
         echo tsprintf("%s\n", pht('Importing all cursors: %s.', implode(', ', array_keys($cursors))));
         echo tsprintf("%s\n", pht('(Use --cursor to import only a particular cursor.)'));
     }
     foreach ($cursors as $cursor) {
         $cursor->importFromSource();
     }
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $ids = $args->getArg('id');
     if (!$ids) {
         throw new PhutilArgumentUsageException(pht('Specify one or more lease IDs to release with "%s".', '--id'));
     }
     $viewer = $this->getViewer();
     $drydock_phid = id(new PhabricatorDrydockApplication())->getPHID();
     $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;
         }
         if (!$lease->canRelease()) {
             echo tsprintf("%s\n", pht('Lease "%s" is not releasable.', $id));
             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".', $id));
     }
 }
 private function markReachable(PhabricatorRepository $repository)
 {
     if (!$repository->isGit()) {
         throw new PhutilArgumentUsageException(pht('Only Git repositories are supported, this repository ("%s") is ' . 'not a Git repository.', $repository->getDisplayName()));
     }
     $viewer = $this->getViewer();
     $commits = id(new DiffusionCommitQuery())->setViewer($viewer)->withRepository($repository)->execute();
     $flag = PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE;
     $graph = new PhabricatorGitGraphStream($repository);
     foreach ($commits as $commit) {
         $identifier = $commit->getCommitIdentifier();
         try {
             $graph->getCommitDate($identifier);
             $unreachable = false;
         } catch (Exception $ex) {
             $unreachable = true;
         }
         // The commit has proper reachability, so do nothing.
         if ($commit->isUnreachable() === $unreachable) {
             $this->untouchedCount++;
             continue;
         }
         if ($unreachable) {
             echo tsprintf("%s: %s\n", $commit->getMonogram(), pht('Marking commit unreachable.'));
             $commit->writeImportStatusFlag($flag);
         } else {
             echo tsprintf("%s: %s\n", $commit->getMonogram(), pht('Marking commit reachable.'));
             $commit->clearImportStatusFlag($flag);
         }
     }
 }
 public function execute(PhutilArgumentParser $args)
 {
     $viewer = $this->getViewer();
     $argv = $args->getArg('argv');
     if (count($argv) !== 2) {
         throw new PhutilArgumentUsageException(pht('Specify a commit and a revision to attach it to.'));
     }
     $commit_name = head($argv);
     $revision_name = last($argv);
     $commit = id(new DiffusionCommitQuery())->setViewer($viewer)->withIdentifiers(array($commit_name))->executeOne();
     if (!$commit) {
         throw new PhutilArgumentUsageException(pht('Commit "%s" does not exist.', $commit_name));
     }
     $revision = id(new PhabricatorObjectQuery())->setViewer($viewer)->withNames(array($revision_name))->executeOne();
     if (!$revision) {
         throw new PhutilArgumentUsageException(pht('Revision "%s" does not exist.', $revision_name));
     }
     if (!$revision instanceof DifferentialRevision) {
         throw new PhutilArgumentUsageException(pht('Object "%s" must be a Differential revision.', $revision_name));
     }
     // Reload the revision to get the active diff.
     $revision = id(new DifferentialRevisionQuery())->setViewer($viewer)->withIDs(array($revision->getID()))->needActiveDiffs(true)->executeOne();
     $differential_phid = id(new PhabricatorDifferentialApplication())->getPHID();
     $extraction_engine = id(new DifferentialDiffExtractionEngine())->setViewer($viewer)->setAuthorPHID($differential_phid);
     $content_source = PhabricatorContentSource::newForSource(PhabricatorContentSource::SOURCE_CONSOLE, array());
     $extraction_engine->updateRevisionWithCommit($revision, $commit, array(), $content_source);
     echo tsprintf("%s\n", pht('Attached "%s" to "%s".', $commit->getMonogram(), $revision->getMonogram()));
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $tasks = $this->loadTasks($args);
     foreach ($tasks as $task) {
         $can_execute = !$task->isArchived();
         if (!$can_execute) {
             $console->writeOut("**<bg:yellow> %s </bg>** %s\n", pht('ARCHIVED'), pht('%s is already archived, and can not be executed.', $this->describeTask($task)));
             continue;
         }
         // NOTE: This ignores leases, maybe it should respect them without
         // a parameter like --force?
         $task->setLeaseOwner(null);
         $task->setLeaseExpires(PhabricatorTime::getNow());
         $task->save();
         $task_data = id(new PhabricatorWorkerTaskData())->loadOneWhere('id = %d', $task->getDataID());
         $task->setData($task_data->getData());
         echo tsprintf("%s\n", pht('Executing task %d (%s)...', $task->getID(), $task->getTaskClass()));
         $task = $task->executeTask();
         $ex = $task->getExecutionException();
         if ($ex) {
             throw $ex;
         }
     }
     return 0;
 }
 public function testTsprintf()
 {
     $this->assertEqual('<NUL>', (string) tsprintf('%s', ""));
     $this->assertEqual('<ESC>[31mred<ESC>[39m', (string) tsprintf('%s', "red"));
     $block = "1\r\n2\r3\n4";
     $this->assertEqual('1<CR><LF>2<CR>3<LF>4', (string) tsprintf('%s', $block));
     $this->assertEqual("1\r\n2<CR>3\n4", (string) tsprintf('%B', $block));
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $repos = id(new PhabricatorRepositoryQuery())->setViewer($this->getViewer())->execute();
     if (!$repos) {
         $console->writeErr("%s\n", pht('There are no repositories.'));
         return 0;
     }
     $from = $args->getArg('from');
     if (!strlen($from)) {
         throw new Exception(pht('You must specify a path prefix to move from with --from.'));
     }
     $to = $args->getArg('to');
     if (!strlen($to)) {
         throw new Exception(pht('You must specify a path prefix to move to with --to.'));
     }
     $is_force = $args->getArg('force');
     $rows = array();
     $any_changes = false;
     foreach ($repos as $repo) {
         $src = $repo->getLocalPath();
         $row = array('repository' => $repo, 'move' => false, 'monogram' => $repo->getMonogram(), 'src' => $src, 'dst' => '');
         if (strncmp($src, $from, strlen($from))) {
             $row['action'] = pht('Ignore');
         } else {
             $dst = $to . substr($src, strlen($from));
             $row['action'] = tsprintf('**%s**', pht('Move'));
             $row['dst'] = $dst;
             $row['move'] = true;
             $any_changes = true;
         }
         $rows[] = $row;
     }
     $table = id(new PhutilConsoleTable())->addColumn('action', array('title' => pht('Action')))->addColumn('monogram', array('title' => pht('Repository')))->addColumn('src', array('title' => pht('Src')))->addColumn('dst', array('title' => pht('Dst')))->setBorders(true);
     foreach ($rows as $row) {
         $display = array_select_keys($row, array('action', 'monogram', 'src', 'dst'));
         $table->addRow($display);
     }
     $table->draw();
     if (!$any_changes) {
         $console->writeOut(pht('No matching repositories.') . "\n");
         return 0;
     }
     $prompt = pht('Apply these changes?');
     if (!$is_force && !phutil_console_confirm($prompt)) {
         throw new Exception(pht('Declining to apply changes.'));
     }
     foreach ($rows as $row) {
         if (empty($row['move'])) {
             continue;
         }
         $repo = $row['repository'];
         queryfx($repo->establishConnection('w'), 'UPDATE %T SET localPath = %s WHERE id = %d', $repo->getTableName(), $row['dst'], $repo->getID());
     }
     $console->writeOut(pht('Applied changes.') . "\n");
     return 0;
 }
 private function printStats(array $old_stats, array $new_stats)
 {
     echo tsprintf("    %s\n", pht('%s: %s -> %s', pht('Stored Bytes'), new PhutilNumber($old_stats['bytes']), new PhutilNumber($new_stats['bytes'])));
     echo tsprintf("    %s\n", pht('%s: %s -> %s', pht('Stored Chunks'), new PhutilNumber($old_stats['chunks']), new PhutilNumber($new_stats['chunks'])));
     echo tsprintf("    %s\n", pht('%s: %s -> %s', pht('Data Hash'), $old_stats['hash'], $new_stats['hash']));
     if ($old_stats['hash'] !== $new_stats['hash']) {
         throw new Exception(pht('Log data hashes differ! Something is tragically wrong!'));
     }
 }
 public function execute(PhutilArgumentParser $args)
 {
     $iterator = $this->buildIterator($args);
     if (!$iterator) {
         throw new PhutilArgumentUsageException(pht('Either specify a list of files to encode, or use --all to ' . 'encode all files.'));
     }
     $force = (bool) $args->getArg('force');
     $format_list = PhabricatorFileStorageFormat::getAllFormats();
     $format_list = array_keys($format_list);
     $format_list = implode(', ', $format_list);
     $format_key = $args->getArg('as');
     if (!strlen($format_key)) {
         throw new PhutilArgumentUsageException(pht('Use --as <format> to select a target encoding format. Available ' . 'formats are: %s.', $format_list));
     }
     $format = PhabricatorFileStorageFormat::getFormat($format_key);
     if (!$format) {
         throw new PhutilArgumentUsageException(pht('Storage format "%s" is not valid. Available formats are: %s.', $format_key, $format_list));
     }
     $key_name = $args->getArg('key');
     if (strlen($key_name)) {
         $format->selectMasterKey($key_name);
     }
     $engines = PhabricatorFileStorageEngine::loadAllEngines();
     $failed = array();
     foreach ($iterator as $file) {
         $monogram = $file->getMonogram();
         $engine_key = $file->getStorageEngine();
         $engine = idx($engines, $engine_key);
         if (!$engine) {
             echo tsprintf("%s\n", pht('%s: Uses unknown storage engine "%s".', $monogram, $engine_key));
             $failed[] = $file;
             continue;
         }
         if ($engine->isChunkEngine()) {
             echo tsprintf("%s\n", pht('%s: Stored as chunks, no data to encode directly.', $monogram));
             continue;
         }
         if ($file->getStorageFormat() == $format_key && !$force) {
             echo tsprintf("%s\n", pht('%s: Already encoded in target format.', $monogram));
             continue;
         }
         echo tsprintf("%s\n", pht('%s: Changing encoding from "%s" to "%s".', $monogram, $file->getStorageFormat(), $format_key));
         try {
             $file->migrateToStorageFormat($format);
             echo tsprintf("%s\n", pht('Done.'));
         } catch (Exception $ex) {
             echo tsprintf("%B\n", pht('Failed! %s', (string) $ex));
             $failed[] = $file;
         }
     }
     if ($failed) {
         $monograms = mpull($failed, 'getMonogram');
         echo tsprintf("%s\n", pht('Failures: %s.', implode(', ', $monograms)));
         return 1;
     }
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $key = $args->getArg('key');
     if (!strlen($key)) {
         throw new PhutilArgumentUsageException(pht('Specify an AWS S3 object key to access with --key.'));
     }
     $future = $this->newAWSFuture(new PhutilAWSS3Future())->setParametersForDeleteObject($key);
     $future->resolve();
     echo tsprintf("%s\n", pht('Deleted "%s".', $key));
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $iterator = $this->buildIterator($args);
     if (!$iterator) {
         throw new PhutilArgumentUsageException(pht('Either specify a list of files to cycle, or use --all to cycle ' . 'all files.'));
     }
     $format_map = PhabricatorFileStorageFormat::getAllFormats();
     $engines = PhabricatorFileStorageEngine::loadAllEngines();
     $key_name = $args->getArg('key');
     $failed = array();
     foreach ($iterator as $file) {
         $monogram = $file->getMonogram();
         $engine_key = $file->getStorageEngine();
         $engine = idx($engines, $engine_key);
         if (!$engine) {
             echo tsprintf("%s\n", pht('%s: Uses unknown storage engine "%s".', $monogram, $engine_key));
             $failed[] = $file;
             continue;
         }
         if ($engine->isChunkEngine()) {
             echo tsprintf("%s\n", pht('%s: Stored as chunks, declining to cycle directly.', $monogram));
             continue;
         }
         $format_key = $file->getStorageFormat();
         if (empty($format_map[$format_key])) {
             echo tsprintf("%s\n", pht('%s: Uses unknown storage format "%s".', $monogram, $format_key));
             $failed[] = $file;
             continue;
         }
         $format = clone $format_map[$format_key];
         $format->setFile($file);
         if (!$format->canCycleMasterKey()) {
             echo tsprintf("%s\n", pht('%s: Storage format ("%s") does not support key cycling.', $monogram, $format->getStorageFormatName()));
             continue;
         }
         echo tsprintf("%s\n", pht('%s: Cycling master key.', $monogram));
         try {
             if ($key_name) {
                 $format->selectMasterKey($key_name);
             }
             $file->cycleMasterStorageKey($format);
             echo tsprintf("%s\n", pht('Done.'));
         } catch (Exception $ex) {
             echo tsprintf("%B\n", pht('Failed! %s', (string) $ex));
             $failed[] = $file;
         }
     }
     if ($failed) {
         $monograms = mpull($failed, 'getMonogram');
         echo tsprintf("%s\n", pht('Failures: %s.', implode(', ', $monograms)));
         return 1;
     }
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $repos = $this->loadLocalRepositories($args, 'repos');
     if (!$repos) {
         throw new PhutilArgumentUsageException(pht('Specify one or more repositories to push to mirrors.'));
     }
     foreach ($repos as $repo) {
         echo tsprintf("%s\n", pht('Pushing "%s" to mirrors...', $repo->getDisplayName()));
         $engine = id(new PhabricatorRepositoryMirrorEngine())->setRepository($repo)->setVerbose($args->getArg('verbose'))->pushToMirrors();
     }
     echo tsprintf("%s\n", pht('Done.'));
     return 0;
 }
 public function didExecute(PhutilArgumentParser $args)
 {
     echo tsprintf("%s\n", pht('Committing configured partition map to databases...'));
     foreach ($this->getMasterAPIs() as $api) {
         $ref = $api->getRef();
         $conn = $ref->newManagementConnection();
         $state = $ref->getPartitionStateForCommit();
         queryfx($conn, 'INSERT INTO %T.%T (stateKey, stateValue) VALUES (%s, %s)
       ON DUPLICATE KEY UPDATE stateValue = VALUES(stateValue)', $api->getDatabaseName('meta_data'), PhabricatorStorageManagementAPI::TABLE_HOSTSTATE, 'cluster.databases', $state);
         echo tsprintf("%s\n", pht('Wrote configuration on database host "%s".', $ref->getRefKey()));
     }
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $styles = PhabricatorSyntaxStyle::getAllStyles();
     $root = dirname(phutil_get_library_root('phabricator'));
     $root = $root . '/webroot/rsrc/css/syntax/';
     foreach ($styles as $key => $style) {
         $content = $this->generateCSS($style);
         $path = $root . '/syntax-' . $key . '.css';
         Filesystem::writeFile($path, $content);
         echo tsprintf("%s\n", pht('Rebuilt "%s" syntax CSS.', basename($path)));
     }
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $key = $args->getArg('key');
     if (!strlen($key)) {
         throw new PhutilArgumentUsageException(pht('Specify an AWS S3 object key to access with --key.'));
     }
     $future = $this->newAWSFuture(new PhutilAWSS3Future());
     echo tsprintf("%s\n", pht('Reading data from stdin...'));
     $data = file_get_contents('php://stdin');
     $future->setParametersForPutObject($key, $data);
     $result = $future->resolve();
     echo tsprintf("%s\n", pht('Uploaded "%s".', $key));
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $config_key = 'phd.garbage-collection';
     $collector = $this->getCollector($args->getArg('collector'));
     $days = $args->getArg('days');
     $indefinite = $args->getArg('indefinite');
     $default = $args->getArg('default');
     $count = 0;
     if ($days !== null) {
         $count++;
     }
     if ($indefinite) {
         $count++;
     }
     if ($default) {
         $count++;
     }
     if (!$count) {
         throw new PhutilArgumentUsageException(pht('Choose a policy with "%s", "%s" or "%s".', '--days', '--indefinite', '--default'));
     }
     if ($count > 1) {
         throw new PhutilArgumentUsageException(pht('Options "%s", "%s" and "%s" represent mutually exclusive ways ' . 'to choose a policy. Specify only one.', '--days', '--indefinite', '--default'));
     }
     if ($days !== null) {
         $days = (int) $days;
         if ($days < 1) {
             throw new PhutilArgumentUsageException(pht('Specify a positive number of days to retain data for.'));
         }
     }
     $collector_const = $collector->getCollectorConstant();
     $value = PhabricatorEnv::getEnvConfig($config_key);
     if ($days !== null) {
         echo tsprintf("%s\n", pht('Setting retention policy for "%s" to %s day(s).', $collector->getCollectorName(), new PhutilNumber($days)));
         $value[$collector_const] = phutil_units($days . ' days in seconds');
     } else {
         if ($indefinite) {
             echo tsprintf("%s\n", pht('Setting "%s" to be retained indefinitely.', $collector->getCollectorName()));
             $value[$collector_const] = null;
         } else {
             echo tsprintf("%s\n", pht('Restoring "%s" to the default retention policy.', $collector->getCollectorName()));
             unset($value[$collector_const]);
         }
     }
     id(new PhabricatorConfigLocalSource())->setKeys(array($config_key => $value));
     echo tsprintf("%s\n", pht('Wrote new policy to local configuration.'));
     echo tsprintf("%s\n", pht('This change will take effect the next time the daemons are ' . 'restarted.'));
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $type = $args->getArg('type');
     if (!strlen($type)) {
         throw new PhutilArgumentUsageException(pht('Specify the type of key to generate with --type.'));
     }
     $format = PhabricatorFileStorageFormat::getFormat($type);
     if (!$format) {
         throw new PhutilArgumentUsageException(pht('No key type "%s" exists.', $type));
     }
     if (!$format->canGenerateNewKeyMaterial()) {
         throw new PhutilArgumentUsageException(pht('Storage format "%s" can not generate keys.', $format->getStorageFormatName()));
     }
     $material = $format->generateNewKeyMaterial();
     $structure = array('name' => 'generated-key-' . Filesystem::readRandomCharacters(12), 'type' => $type, 'material.base64' => $material);
     $json = id(new PhutilJSON())->encodeFormatted($structure);
     echo tsprintf("%s: %s\n\n%B\n", pht('Key Material'), $format->getStorageFormatName(), $json);
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $viewer = $this->getViewer();
     $resource_type = $args->getArg('type');
     if (!$resource_type) {
         throw new PhutilArgumentUsageException(pht('Specify a resource type with `%s`.', '--type'));
     }
     $until = $args->getArg('until');
     if (strlen($until)) {
         $until = strtotime($until);
         if ($until <= 0) {
             throw new PhutilArgumentUsageException(pht('Unable to parse argument to "%s".', '--until'));
         }
     }
     $attributes = $args->getArg('attributes');
     if ($attributes) {
         $options = new PhutilSimpleOptions();
         $options->setCaseSensitive(true);
         $attributes = $options->parse($attributes);
     }
     $lease = id(new DrydockLease())->setResourceType($resource_type);
     $drydock_phid = id(new PhabricatorDrydockApplication())->getPHID();
     $lease->setAuthorizingPHID($drydock_phid);
     // TODO: This is not hugely scalable, although this is a debugging workflow
     // so maybe it's fine. Do we even need `bin/drydock lease` in the long run?
     $all_blueprints = id(new DrydockBlueprintQuery())->setViewer($viewer)->execute();
     $allowed_phids = mpull($all_blueprints, 'getPHID');
     if (!$allowed_phids) {
         throw new Exception(pht('No blueprints exist which can plausibly allocate resources to ' . 'satisfy the requested lease.'));
     }
     $lease->setAllowedBlueprintPHIDs($allowed_phids);
     if ($attributes) {
         $lease->setAttributes($attributes);
     }
     if ($until) {
         $lease->setUntil($until);
     }
     $lease->queueForActivation();
     echo tsprintf("%s\n", pht('Waiting for daemons to activate lease...'));
     $lease->waitUntilActive();
     echo tsprintf("%s\n", pht('Activated lease "%s".', $lease->getID()));
     return 0;
 }
 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();
     }
 }
 public function execute(PhutilArgumentParser $args)
 {
     $viewer = $this->getViewer();
     $extract = $args->getArg('extract');
     if (!$extract) {
         throw new PhutilArgumentUsageException(pht('Specify a commit to extract the diff from.'));
     }
     if (count($extract) > 1) {
         throw new PhutilArgumentUsageException(pht('Specify exactly one commit to extract.'));
     }
     $extract = head($extract);
     $commit = id(new DiffusionCommitQuery())->setViewer($viewer)->withIdentifiers(array($extract))->executeOne();
     if (!$commit) {
         throw new PhutilArgumentUsageException(pht('Commit "%s" is not valid.', $extract));
     }
     $diff = id(new DifferentialDiffExtractionEngine())->setViewer($viewer)->newDiffFromCommit($commit);
     $uri = PhabricatorEnv::getProductionURI($diff->getURI());
     echo tsprintf("%s\n\n    %s\n", pht('Extracted diff from "%s":', $extract), $uri);
 }
 public function execute(PhutilArgumentParser $args)
 {
     $viewer = $this->getViewer();
     $repositories = $this->loadRepositories($args, 'repositories');
     if (!$repositories) {
         throw new PhutilArgumentUsageException(pht('Specify one or more repositories to clusterize.'));
     }
     $service_name = $args->getArg('service');
     $remove_service = $args->getArg('remove-service');
     if ($remove_service && $service_name) {
         throw new PhutilArgumentUsageException(pht('Specify --service or --remove-service, but not both.'));
     }
     if (!$service_name && !$remove_service) {
         throw new PhutilArgumentUsageException(pht('Specify --service or --remove-service.'));
     }
     if ($remove_service) {
         $service = null;
     } else {
         $service = id(new AlmanacServiceQuery())->setViewer($viewer)->withNames(array($service_name))->withServiceTypes(array(AlmanacClusterRepositoryServiceType::SERVICETYPE))->executeOne();
         if (!$service) {
             throw new PhutilArgumentUsageException(pht('No repository service "%s" exists.', $service_name));
         }
     }
     if ($service) {
         $service_phid = $service->getPHID();
     } else {
         $service_phid = null;
     }
     $content_source = $this->newContentSource();
     $diffusion_phid = id(new PhabricatorDiffusionApplication())->getPHID();
     foreach ($repositories as $repository) {
         $xactions = array();
         $xactions[] = id(new PhabricatorRepositoryTransaction())->setTransactionType(PhabricatorRepositoryTransaction::TYPE_SERVICE)->setNewValue($service_phid);
         id(new PhabricatorRepositoryEditor())->setActor($viewer)->setActingAsPHID($diffusion_phid)->setContentSource($content_source)->setContinueOnNoEffect(true)->setContinueOnMissingFields(true)->applyTransactions($repository, $xactions);
         if ($service) {
             echo tsprintf("%s\n", pht('Moved repository "%s" to cluster service "%s".', $repository->getDisplayName(), $service->getName()));
         } else {
             echo tsprintf("%s\n", pht('Removed repository "%s" from cluster service.', $repository->getDisplayName()));
         }
     }
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $console->writeErr("%s\n", pht('Analyzing table sizes (this may take a moment)...'));
     $api = $this->getAPI();
     $patches = $this->getPatches();
     $databases = $api->getDatabaseList($patches, $only_living = true);
     $conn_r = $api->getConn(null);
     $data = array();
     foreach ($databases as $database) {
         queryfx($conn_r, 'USE %C', $database);
         $tables = queryfx_all($conn_r, 'SHOW TABLE STATUS');
         $tables = ipull($tables, null, 'Name');
         $data[$database] = $tables;
     }
     $totals = array_fill_keys(array_keys($data), 0);
     $overall = 0;
     foreach ($data as $db => $tables) {
         foreach ($tables as $table => $info) {
             $table_size = $info['Data_length'] + $info['Index_length'];
             $data[$db][$table]['_totalSize'] = $table_size;
             $totals[$db] += $table_size;
             $overall += $table_size;
         }
     }
     asort($totals);
     $table = id(new PhutilConsoleTable())->setShowHeader(false)->setPadding(2)->addColumn('name', array('title' => pht('Database / Table')))->addColumn('size', array('title' => pht('Size')))->addColumn('percentage', array('title' => pht('Percentage')));
     foreach ($totals as $db => $size) {
         list($database_size, $database_percentage) = $this->formatSize($totals[$db], $overall);
         $table->addRow(array('name' => tsprintf('**%s**', $db), 'size' => tsprintf('**%s**', $database_size), 'percentage' => tsprintf('**%s**', $database_percentage)));
         $data[$db] = isort($data[$db], '_totalSize');
         foreach ($data[$db] as $table_name => $info) {
             list($table_size, $table_percentage) = $this->formatSize($info['_totalSize'], $overall);
             $table->addRow(array('name' => '    ' . $table_name, 'size' => $table_size, 'percentage' => $table_percentage));
         }
     }
     list($overall_size, $overall_percentage) = $this->formatSize($overall, $overall);
     $table->addRow(array('name' => tsprintf('**%s**', pht('TOTAL')), 'size' => tsprintf('**%s**', $overall_size), 'percentage' => tsprintf('**%s**', $overall_percentage)));
     $table->draw();
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $collector = $this->getCollector($args->getArg('collector'));
     echo tsprintf("%s\n", pht('Collecting "%s" garbage...', $collector->getCollectorName()));
     $any = false;
     while (true) {
         $more = $collector->runCollector();
         if ($more) {
             $any = true;
         } else {
             break;
         }
     }
     if ($any) {
         $message = pht('Finished collecting all the garbage.');
     } else {
         $message = pht('Could not find any garbage to collect.');
     }
     echo tsprintf("\n%s\n", $message);
     return 0;
 }
 protected function generate(array $generators)
 {
     $viewer = $this->getViewer();
     foreach ($generators as $generator) {
         $generator->setViewer($this->getViewer());
     }
     while (true) {
         $generator = $generators[array_rand($generators)];
         try {
             $object = $generator->generateObject();
         } catch (Exception $ex) {
             echo tsprintf("**<bg:yellow> %s </bg>** %s\n", pht('OOPS'), pht('Generator ("%s") was unable to generate an object.', $generator->getGeneratorName()));
             echo tsprintf("%B\n", $ex->getMessage());
             continue;
         }
         $object_phid = $object->getPHID();
         $handles = $viewer->loadHandles(array($object_phid));
         echo tsprintf("%s\n", pht('Generated "%s": %s', $handles[$object_phid]->getTypeName(), $handles[$object_phid]->getFullName()));
         sleep(1);
     }
 }
 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;
         }
     }
 }
 public function execute(PhutilArgumentParser $args)
 {
     $viewer = $this->getViewer();
     $ids = $args->getArg('ids');
     if (!$ids) {
         throw new PhutilArgumentUsageException(pht('Specify at least one import ID to reload.'));
     }
     $imports = id(new PhabricatorCalendarImportQuery())->setViewer($viewer)->withIDs($ids)->execute();
     $imports = mpull($imports, null, 'getID');
     foreach ($ids as $id) {
         if (empty($imports[$id])) {
             throw new PhutilArgumentUsageException(pht('Unable to load Calendar import with ID "%s".', $id));
         }
     }
     $imports = array_select_keys($imports, $ids);
     foreach ($imports as $import) {
         echo tsprintf("%s\n", pht('Importing "%s"...', $import->getDisplayName()));
         $engine = $import->getEngine();
         $engine->importEventsFromSource($viewer, $import, false);
     }
     echo tsprintf("%s\n", pht('Done.'));
     return 0;
 }
 public function execute(PhutilArgumentParser $args)
 {
     $this->setVerbose($args->getArg('verbose'));
     $console = PhutilConsole::getConsole();
     $repos = $this->loadLocalRepositories($args, 'repos');
     if (count($repos) !== 1) {
         throw new PhutilArgumentUsageException(pht('Specify exactly one repository to update.'));
     }
     $repository = head($repos);
     try {
         id(new PhabricatorRepositoryPullEngine())->setRepository($repository)->setVerbose($this->getVerbose())->pullRepository();
         $no_discovery = $args->getArg('no-discovery');
         if ($no_discovery) {
             return 0;
         }
         // TODO: It would be nice to discover only if we pulled something, but
         // this isn't totally trivial. It's slightly more complicated with
         // hosted repositories, too.
         $repository->writeStatusMessage(PhabricatorRepositoryStatusMessage::TYPE_NEEDS_UPDATE, null);
         $this->discoverRepository($repository);
         $this->checkIfRepositoryIsFullyImported($repository);
         $this->updateRepositoryRefs($repository);
         $this->mirrorRepository($repository);
         $repository->writeStatusMessage(PhabricatorRepositoryStatusMessage::TYPE_FETCH, PhabricatorRepositoryStatusMessage::CODE_OKAY);
     } catch (DiffusionDaemonLockException $ex) {
         // If we miss a pull or discover because some other process is already
         // doing the work, just bail out.
         echo tsprintf("%s\n", $ex->getMessage());
         return 0;
     } catch (Exception $ex) {
         $repository->writeStatusMessage(PhabricatorRepositoryStatusMessage::TYPE_FETCH, PhabricatorRepositoryStatusMessage::CODE_ERROR, array('message' => pht('Error updating working copy: %s', $ex->getMessage())));
         throw $ex;
     }
     echo tsprintf("%s\n", pht('Updated repository "%s".', $repository->getDisplayName()));
     return 0;
 }
Exemplo n.º 30
0
 protected function printCurrentTracking()
 {
     $conduit = $this->getConduit();
     $results = $conduit->callMethodSynchronous('phrequent.tracking', array());
     $results = $results['data'];
     if (count($results) === 0) {
         echo phutil_console_format("%s\n", pht('Not currently tracking time against any object.'));
         return 0;
     }
     $phids_to_lookup = array();
     foreach ($results as $result) {
         $phids_to_lookup[] = $result['phid'];
     }
     $phid_query = $conduit->callMethodSynchronous('phid.query', array('phids' => $phids_to_lookup));
     $phid_map = array();
     foreach ($phids_to_lookup as $lookup) {
         if (array_key_exists($lookup, $phid_query)) {
             $phid_map[$lookup] = $phid_query[$lookup]['fullName'];
         } else {
             $phid_map[$lookup] = pht('Unknown Object');
         }
     }
     $table = id(new PhutilConsoleTable())->addColumn('type', array('title' => pht('Status')))->addColumn('time', array('title' => pht('Tracked'), 'align' => 'right'))->addColumn('name', array('title' => pht('Name')))->setBorders(false);
     $i = 0;
     foreach ($results as $result) {
         if ($i === 0) {
             $column_type = pht('In Progress');
         } else {
             $column_type = pht('Suspended');
         }
         $table->addRow(array('type' => '(' . $column_type . ')', 'time' => tsprintf($result['time']), 'name' => $phid_map[$result['phid']]));
         $i++;
     }
     $table->draw();
     return 0;
 }