Commit 041b2522 authored by Ryo Yamashita's avatar Ryo Yamashita Committed by Yas Naoi
Browse files

Issue #3293499 by Ryo Yamashita, yas: Refactor...

Issue #3293499 by Ryo Yamashita, yas: Refactor Drupal\aws_cloud\Controller\Ec2\ApiControllerInterface, Drupal\aws_cloud\Service\AwsCloud\AwsCloudOperationsServiceInterface, Drupal\openstack\Service\OpenStackOperationsService and more
parent c5c3d58e
Loading
Loading
Loading
Loading
+39 −30
Changes for modules/cloud_service_providers/aws_cloud/src/Controller/Ec2/ApiController.php: 39 added lines, 30 removed lines.
Original line number Diff line number Diff line
@@ -9,6 +9,7 @@ use Drupal\aws_cloud\Service\AwsCloud\AwsCloudOperationsServiceInterface;
use Drupal\aws_cloud\Service\CloudWatch\CloudWatchServiceInterface;
use Drupal\aws_cloud\Service\Ec2\Ec2ServiceInterface;
use Drupal\aws_cloud\Traits\AwsCloudEntityCheckTrait;
use Drupal\cloud\Entity\CloudConfig;
use Drupal\cloud\Plugin\cloud\config\CloudConfigPluginManagerInterface;
use Drupal\cloud\Service\CloudServiceInterface;
use Drupal\cloud\Traits\CloudContentEntityTrait;
@@ -152,7 +153,8 @@ class ApiController extends ControllerBase implements ApiControllerInterface {
    CloudConfigPluginManagerInterface $cloud_config_plugin_manager,
    CloudServiceInterface $cloud_service,
    EntityTypeManagerInterface $entity_type_manager,
    AccountInterface $current_user) {
    AccountInterface $current_user
  ) {

    $this->awsCloudOperationsService = $aws_cloud_operations_service;
    $this->ec2Service = $ec2_service;
@@ -176,7 +178,7 @@ class ApiController extends ControllerBase implements ApiControllerInterface {
   * @return ApiController
   *   return created object.
   */
  public static function create(ContainerInterface $container) {
  public static function create(ContainerInterface $container): ApiController {
    return new static(
      $container->get('aws_cloud.operations'),
      $container->get('aws_cloud.ec2'),
@@ -230,7 +232,7 @@ class ApiController extends ControllerBase implements ApiControllerInterface {
   * @param bool $updated
   *   Updated statuses.
   */
  protected function updateMessages($resource_type, bool $updated): void {
  protected function updateMessages(string $resource_type, bool $updated): void {
    $labels = $this->getDisplayLabels($resource_type);
    if ($updated) {
      $this->messageUser($this->t('Updated @resource_name.', ['@resource_name' => $labels['plural']]));
@@ -282,9 +284,12 @@ class ApiController extends ControllerBase implements ApiControllerInterface {
      ['cloud_context' => [$cloud_context]]
    );

    if (!empty($cloud_config_entities)) {
      $cloud_config = reset($cloud_config_entities);
    }
    /** @var \Drupal\cloud\Entity\CloudConfig $cloud_config */
    $cloud_config = !empty($cloud_config_entities)
      ? reset($cloud_config_entities)
      : CloudConfig::create([
        'cloud_context' => $cloud_context,
      ]);

    /** @var \Drupal\aws_cloud\Service\Ec2\Ec2Service */
    $ec2Service = $this->ec2Service;
@@ -509,28 +514,28 @@ class ApiController extends ControllerBase implements ApiControllerInterface {
  /**
   * {@inheritdoc}
   */
  public function listInstanceCallback($cloud_context): Response {
  public function listInstanceCallback(): Response {
    return $this->getViewResponse('aws_cloud_instance');
  }

  /**
   * {@inheritdoc}
   */
  public function listImageCallback($cloud_context): Response {
  public function listImageCallback(): Response {
    return $this->getViewResponse('aws_cloud_image');
  }

  /**
   * {@inheritdoc}
   */
  public function listSnapshotCallback($cloud_context): Response {
  public function listSnapshotCallback(): Response {
    return $this->getViewResponse('aws_cloud_snapshot');
  }

  /**
   * {@inheritdoc}
   */
  public function listVolumeCallback($cloud_context): Response {
  public function listVolumeCallback(): Response {
    return $this->getViewResponse('aws_cloud_volume');
  }

@@ -572,8 +577,13 @@ class ApiController extends ControllerBase implements ApiControllerInterface {
      return ($a['created'] < $b['created']) ? 1 : -1;
    });

    try {
      return new Response(json_encode($images));
    }
    catch (\JsonException $e) {
      $this->handleException($e);
    }
  }

  /**
   * {@inheritdoc}
@@ -648,7 +658,7 @@ class ApiController extends ControllerBase implements ApiControllerInterface {
   * @return \Symfony\Component\HttpFoundation\Response
   *   The response of list view.
   */
  private function getViewResponse($view_id): Response {
  private function getViewResponse(string $view_id): Response {
    $view = Views::getView($view_id);

    // Set the display machine name.
@@ -667,7 +677,7 @@ class ApiController extends ControllerBase implements ApiControllerInterface {
   * @param string $type
   *   The message type: error or message.
   */
  private function messageUser($message, $type = 'message'): void {
  private function messageUser(string $message, string $type = 'message'): void {
    switch ($type) {
      case 'error':
        $this->messenger->addError($message);
@@ -675,6 +685,8 @@ class ApiController extends ControllerBase implements ApiControllerInterface {

      case 'message':
        $this->messenger->addStatus($message);
        break;

      default:
        break;
    }
@@ -699,29 +711,17 @@ class ApiController extends ControllerBase implements ApiControllerInterface {
  }

  /**
   * Loads one entity of AWS Cloud instance by entity ID.
   *
   * @param string $entity_id
   *   The entity ID.
   *
   * @return \Drupal\Core\Entity\EntityInterface|null
   *   The entity data.
   * {@inheritdoc}
   */
  private function getInstanceEntity(string $entity_id) {
  public function getConsoleOutput(string $cloud_context, string $entity_id): JsonResponse {
    // Get entity data.
    /** @var \Drupal\aws_cloud\Entity\Ec2\InstanceInterface $entity */
    $entity = $this->entityTypeManager
      ->getStorage('aws_cloud_instance')
      ->load($entity_id);

    return $this->updateEntitySubmitForm(new FormState(), $entity)
    $entity = $this->updateEntitySubmitForm(new FormState(), $entity)
      ? $entity : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function getConsoleOutput(string $cloud_context, string $entity_id): JsonResponse {
    // Get entity data.
    $entity = $this->getInstanceEntity($entity_id);
    if (empty($entity)) {
      return new JsonResponse([
        'result' => 'NG',
@@ -784,6 +784,7 @@ class ApiController extends ControllerBase implements ApiControllerInterface {
    // branching is performed with a switch statement.
    $form_state = new IntermediateFormState();
    $method_name = '';
    try {
      switch ($command . '_' . $entity_type_id) {
        case 'associate_elastic_ip_aws_cloud_instance':
          $form_state->set('allocation_id', $request->get('allocation_id', ''));
@@ -796,7 +797,7 @@ class ApiController extends ControllerBase implements ApiControllerInterface {
          $form_state->set('image_name', $request->get('image_name', ''));
          $form_state->set('no_reboot', $request->get('no_reboot', 'false') === 'true');

        $method_name = 'createImagefromInstance';
          $method_name = 'createImageFromInstance';
          break;

        case 'delete_aws_cloud_instance':
@@ -833,6 +834,14 @@ class ApiController extends ControllerBase implements ApiControllerInterface {
          $method_name = 'stopInstance';
          break;
      }
    }
    catch (\JsonException $e) {
      $this->handleException($e);
      return new JsonResponse([
        'result' => 'NG',
        'reason' => 'Internal Server Error',
      ], 500);
    }

    // Execute the process.
    $result = NULL;
+12 −12
Changes for modules/cloud_service_providers/aws_cloud/src/Controller/Ec2/ApiControllerInterface.php: 12 added lines, 12 removed lines.
Original line number Diff line number Diff line
@@ -22,7 +22,7 @@ interface ApiControllerInterface {
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirect response object that may be returned by the controller.
   */
  public function updateInstanceList($cloud_context): RedirectResponse;
  public function updateInstanceList(string $cloud_context): RedirectResponse;

  /**
   * Update all images in particular cloud region.
@@ -33,7 +33,7 @@ interface ApiControllerInterface {
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirect response object that may be returned by the controller.
   */
  public function updateImageList($cloud_context): RedirectResponse;
  public function updateImageList(string $cloud_context): RedirectResponse;

  /**
   * Update all security groups in particular cloud region.
@@ -44,7 +44,7 @@ interface ApiControllerInterface {
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirect response object that may be returned by the controller.
   */
  public function updateSecurityGroupList($cloud_context): RedirectResponse;
  public function updateSecurityGroupList(string $cloud_context): RedirectResponse;

  /**
   * Update all network interfaces in particular cloud region.
@@ -55,7 +55,7 @@ interface ApiControllerInterface {
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirect response object that may be returned by the controller.
   */
  public function updateNetworkInterfaceList($cloud_context): RedirectResponse;
  public function updateNetworkInterfaceList(string $cloud_context): RedirectResponse;

  /**
   * Update all Elastic IPs in particular cloud region.
@@ -66,7 +66,7 @@ interface ApiControllerInterface {
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirect response object that may be returned by the controller.
   */
  public function updateElasticIpList($cloud_context): RedirectResponse;
  public function updateElasticIpList(string $cloud_context): RedirectResponse;

  /**
   * Update all key pairs in particular cloud region.
@@ -77,7 +77,7 @@ interface ApiControllerInterface {
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirect response object that may be returned by the controller.
   */
  public function updateKeyPairList($cloud_context): RedirectResponse;
  public function updateKeyPairList(string $cloud_context): RedirectResponse;

  /**
   * Update all volumes in particular cloud region.
@@ -88,7 +88,7 @@ interface ApiControllerInterface {
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirect response object that may be returned by the controller.
   */
  public function updateVolumeList($cloud_context): RedirectResponse;
  public function updateVolumeList(string $cloud_context): RedirectResponse;

  /**
   * Update all snapshots in particular cloud region.
@@ -99,7 +99,7 @@ interface ApiControllerInterface {
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirect response object that may be returned by the controller.
   */
  public function updateSnapshotList($cloud_context): RedirectResponse;
  public function updateSnapshotList(string $cloud_context): RedirectResponse;

  /**
   * Update all entities in a given region.
@@ -115,10 +115,10 @@ interface ApiControllerInterface {
   * @param string $cloud_context
   *   Cloud context string.
   *
   * @return Symfony\Component\HttpFoundation\Response
   * @return \Symfony\Component\HttpFoundation\Response
   *   A JSON response of images.
   */
  public function searchImages($cloud_context): Response;
  public function searchImages(string $cloud_context): Response;

  /**
   * Get instance metrics.
@@ -128,10 +128,10 @@ interface ApiControllerInterface {
   * @param \Drupal\aws_cloud\Entity\Ec2\InstanceInterface $aws_cloud_instance
   *   Cloud context string.
   *
   * @return Symfony\Component\HttpFoundation\JsonResponse
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   A JSON response of an instance's metrics.
   */
  public function getInstanceMetrics($cloud_context, InstanceInterface $aws_cloud_instance): JsonResponse;
  public function getInstanceMetrics(string $cloud_context, InstanceInterface $aws_cloud_instance): JsonResponse;

  /**
   * Get the count of AWS Cloud entities.
+6 −4
Changes for modules/cloud_service_providers/aws_cloud/src/Form/Ec2/InstanceConsoleOutputForm.php: 6 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -23,7 +23,7 @@ use Drupal\cloud\Service\AnsiStringRendererInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a form for console output of a Instance entity.
 * Provides a form for console output of an Instance entity.
 *
 * @ingroup aws_cloud
 */
@@ -71,7 +71,7 @@ class InstanceConsoleOutputForm extends AwsCloudContentForm {
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   *   The match of route.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter.
   * @param \Drupal\Core\Render\RendererInterface $renderer
@@ -124,7 +124,7 @@ class InstanceConsoleOutputForm extends AwsCloudContentForm {
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
  public static function create(ContainerInterface $container): InstanceConsoleOutputForm {
    return new static(
      $container->get('aws_cloud.operations'),
      $container->get('aws_cloud.ec2'),
@@ -150,7 +150,9 @@ class InstanceConsoleOutputForm extends AwsCloudContentForm {
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $cloud_context = ''): array {
    $output = $this->awsCloudOperationsService->getConsoleOutput($this->entity);
    /** @var \Drupal\aws_cloud\Entity\Ec2\InstanceInterface $entity */
    $entity = $this->entity;
    $output = $this->awsCloudOperationsService->getConsoleOutput($entity);
    $form['log'] = $this->ansiStringRenderer->render($output);
    return $form;
  }
+17 −14
Changes for modules/cloud_service_providers/aws_cloud/src/Service/AwsCloud/AwsCloudOperationsService.php: 17 added lines, 14 removed lines.
Original line number Diff line number Diff line
@@ -9,6 +9,7 @@ use Drupal\aws_cloud\Entity\Ec2\InstanceInterface;
use Drupal\aws_cloud\Form\Ec2\InstanceEditForm;
use Drupal\aws_cloud\Service\Ec2\Ec2ServiceInterface;
use Drupal\aws_cloud\Traits\AwsCloudEntityCheckTrait;
use Drupal\cloud\Entity\CloudConfig;
use Drupal\cloud\Entity\CloudConfigInterface;
use Drupal\cloud\Plugin\cloud\config\CloudConfigPluginManagerInterface;
use Drupal\cloud\Service\CloudServiceInterface;
@@ -212,7 +213,7 @@ class AwsCloudOperationsService implements AwsCloudOperationsServiceInterface {

    $this->trimTextfields($entity, $form, $form_state);

    $this->saveCloudContent($entity, $form, $form_state);
    $this->saveCloudContent($entity);
  }

  /**
@@ -326,7 +327,7 @@ class AwsCloudOperationsService implements AwsCloudOperationsServiceInterface {
  /**
   * {@inheritdoc}
   */
  public function createImagefromInstance(InstanceInterface $entity, array $form, FormStateInterface $form_state): bool {
  public function createImageFromInstance(InstanceInterface $entity, array $form, FormStateInterface $form_state): bool {
    try {
      if (!$this->updateEntitySubmitForm($form_state, $entity)) {
        return FALSE;
@@ -730,7 +731,7 @@ class AwsCloudOperationsService implements AwsCloudOperationsServiceInterface {
    }
    catch (\Exception $e) {
      $this->handleException($e);
      $this->processOperationErrorStatus($entity, 'stoped');
      $this->processOperationErrorStatus($entity, 'stopped');
      return FALSE;
    }

@@ -751,7 +752,7 @@ class AwsCloudOperationsService implements AwsCloudOperationsServiceInterface {
    }
    catch (\Exception $e) {
      $this->handleException($e);
      $this->processOperationErrorStatus($entity, 'stoped');
      $this->processOperationErrorStatus($entity, 'stopped');
      $form_state->setRedirect("view.{$entity->getEntityTypeId()}.list", ['cloud_context' => $entity->getCloudContext()]);
      return FALSE;
    }
@@ -762,21 +763,22 @@ class AwsCloudOperationsService implements AwsCloudOperationsServiceInterface {
   *
   * @param \Drupal\Core\Entity\FieldableEntityInterface $entity
   *   Interface for entities having fields.
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @throws \Drupal\Core\Entity\EntityMalformedException
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  private function saveCloudContent(FieldableEntityInterface $entity, array $form, FormStateInterface $form_state): int {
  private function saveCloudContent(FieldableEntityInterface $entity): int {
    if (!($entity instanceof CloudConfigInterface)) {
      /** @var \Drupal\Core\Entity\FieldableEntity */
      /** @var \Drupal\aws_cloud\Entity\Ec2\InstanceInterface $original_entity */
      $original_entity = $entity;
      $this->cloudConfigPluginManager->setCloudContext($original_entity->getCloudContext());
      $cloud_config = $this->cloudConfigPluginManager->loadConfigEntity();
    }
    else {
      $cloud_config = CloudConfig::create([
        'cloud_context' => $entity->getCloudContext(),
      ]);
    }

    if (!$entity->isNew() && !($entity instanceof CloudConfigInterface) && $cloud_config->isRemote()) {
      $status = SAVED_UPDATED;
@@ -787,7 +789,7 @@ class AwsCloudOperationsService implements AwsCloudOperationsServiceInterface {

    $status = $entity->save();

    // Add a updated status message and the log.
    // Add an updated status message and the log.
    switch ($status) {
      case SAVED_NEW:
        $passive_operation = 'created';
@@ -1174,7 +1176,8 @@ class AwsCloudOperationsService implements AwsCloudOperationsServiceInterface {
        $update_entities = FALSE;

        if (isset($current_allocation_id) && isset($current_association_id)) {
          // Instance already has allocation_id. Disassociate and reassociate.
          // Reassign the Elastic IP address to the instance.
          // (the Elastic IP address = ['AssociationId', 'InstanceId'])
          if ($current_allocation_id !== $new_elastic_ip) {
            $this->ec2Service->disassociateAddress([
              'AssociationId' => $current_association_id,
@@ -1214,13 +1217,13 @@ class AwsCloudOperationsService implements AwsCloudOperationsServiceInterface {
   * @param string $cloud_context
   *   The cloud context.
   *
   * @return \Drupal\aws_cloud\Entity\Ec2\ElasticIpInterface
   * @return \Drupal\aws_cloud\Entity\Ec2\ElasticIpInterface|false
   *   The loaded aws_cloud_elastic_ip entity.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  private function getElasticIp(string $allocation_id, string $cloud_context): ElasticIpInterface {
  private function getElasticIp(string $allocation_id, string $cloud_context): ElasticIpInterface|FALSE {
    $elastic_ip = FALSE;
    $results = $this->entityTypeManager
      ->getStorage('aws_cloud_elastic_ip')
+6 −6
Changes for modules/cloud_service_providers/aws_cloud/src/Service/AwsCloud/AwsCloudOperationsServiceInterface.php: 6 added lines, 6 removed lines.
Original line number Diff line number Diff line
@@ -26,7 +26,7 @@ interface AwsCloudOperationsServiceInterface {
   * @param \Drupal\Core\Entity\FieldableEntityInterface $entity
   *   Interface for entities having fields.
   * @param array $form
   *   The form array.
   *   An associative array containing the structure of the form.
   */
  public function copyFormItemValues(FieldableEntityInterface $entity, array $form): void;

@@ -36,7 +36,7 @@ interface AwsCloudOperationsServiceInterface {
   * @param \Drupal\Core\Entity\FieldableEntityInterface $entity
   *   Interface for entities having fields.
   * @param array $form
   *   The form array.
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state object.
   */
@@ -67,9 +67,9 @@ interface AwsCloudOperationsServiceInterface {
   * @param array $tag_map
   *   The map of tags.
   * @param string $entity_type
   *   The entity type.
   *   The type of entity.
   */
  public function setTagsInAws(EntityInterface $entity, $resource_id, array $tag_map, $entity_type = ''): void;
  public function setTagsInAws(EntityInterface $entity, string $resource_id, array $tag_map, string $entity_type = ''): void;

  /**
   * Update name and created_by tags.
@@ -79,7 +79,7 @@ interface AwsCloudOperationsServiceInterface {
   * @param string $aws_cloud_resource_id
   *   The AWS Cloud resource ID.
   */
  public function updateNameAndCreatedByTags(EntityInterface $entity, $aws_cloud_resource_id): void;
  public function updateNameAndCreatedByTags(EntityInterface $entity, string $aws_cloud_resource_id): void;

  /**
   * Associate an Elastic IP for AWS Cloud instance.
@@ -115,7 +115,7 @@ interface AwsCloudOperationsServiceInterface {
   * @throws \Drupal\Core\Entity\EntityMalformedException
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function createImagefromInstance(InstanceInterface $entity, array $form, FormStateInterface $form_state): bool;
  public function createImageFromInstance(InstanceInterface $entity, array $form, FormStateInterface $form_state): bool;

  /**
   * Delete an Instance.
Loading