Commit 4614616a authored by baldwinlouie's avatar baldwinlouie Committed by Yas Naoi
Browse files

Issue #3317433 by baldwinlouie, yas: Refactor to reassign K8s entities UIDs when a user is deleted

parent f9bbf959
Loading
Loading
Loading
Loading
+4 −20
Original line number Diff line number Diff line
@@ -491,7 +491,9 @@ function aws_cloud_entity_type_alter(array &$entity_types): void {
 * Implements hook_ENTITY_TYPE_predelete().
 */
function aws_cloud_user_predelete($account): void {
  $entity_types = aws_cloud_get_entity_list();
  /** @var Drupal\cloud\Service\CloudService $cloud_service */
  $cloud_service = \Drupal::service('cloud');
  $entity_types = $cloud_service->getProviderEntityTypes('aws_cloud');
  foreach ($entity_types ?: [] as $entity_type) {
    if (empty($entity_type)) {
      continue;
@@ -504,7 +506,7 @@ function aws_cloud_user_predelete($account): void {
    if (count($ids) === 0) {
      continue;
    }
    \Drupal::service('cloud')->reassignUids($ids, [
    $cloud_service->reassignUids($ids, [
      'uid' => 0,
    ], $entity_type->id(), FALSE, $account, [
      'aws_cloud_reassign_entity_uid_callback',
@@ -617,24 +619,6 @@ function aws_cloud_get_id_method(string $entity_type): string {
  return $id_class;
}

/**
 * Helper function to retrieve a list of entity types provided by aws_cloud.
 *
 * @return array
 *   Array of entity types.
 */
function aws_cloud_get_entity_list(): array {
  $entity_types = \Drupal::entityDefinitionUpdateManager()
    ->getEntityTypes();
  foreach ($entity_types ?: [] as $key => $entity) {
    if (!empty($entity)
      && str_starts_with($entity->id(), 'aws_cloud') === FALSE) {
      unset($entity_types[$key]);
    }
  }
  return $entity_types;
}

/**
 * Implements hook_entity_view().
 */
+134 −0
Original line number Diff line number Diff line
@@ -1853,6 +1853,140 @@ function k8s_cron(): void {

}

/**
 * Implements hook_ENTITY_TYPE_predelete().
 */
function k8s_user_predelete($account): void {
  /** @var Drupal\cloud\Service\CloudService $cloud_service */
  $cloud_service = \Drupal::service('cloud');
  $entity_types = $cloud_service->getProviderEntityTypes('k8s');
  foreach ($entity_types ?: [] as $entity_type) {
    if (empty($entity_type)) {
      continue;
    }
    $ids = \Drupal::entityTypeManager()
      ->getStorage($entity_type->id())
      ->getQuery()
      ->condition('uid', $account->id())
      ->execute();
    if (count($ids) === 0) {
      continue;
    }
    $cloud_service->reassignUids($ids, [
      'uid' => 0,
    ], $entity_type->id(), FALSE, $account, [], 'k8s_reassign_entity_uid_callback');
  }
}

/**
 * Additional callback during user delete operation.
 *
 * Callback queries the cloud_credit table and deletes any entities
 * where the user field = user being deleted.
 *
 * @param array $entities
 *   Array of entity ids.
 * @param array $updates
 *   Array of key/values to update.
 * @param string $entity_type
 *   The entity type.
 * @param bool $revision
 *   TRUE if the entities support revisions.
 * @param Drupal\user\Entity\User $account
 *   User entity.
 * @param array|\ArrayAccess $context
 *   An array of contextual key/values.
 */
function k8s_reassign_entity_uid_callback(array $entities, array $updates, string $entity_type, bool $revision, User $account, &$context): void {
  if (count($entities) === 0) {
    return;
  }

  // In case an exception thrown by the API, this callback function can
  // loop indefinitely.  Try to exit if there are no more entities left.
  if (isset($context['sandbox']['entities']) && count($context['sandbox']['entities']) === 0) {
    return;
  }

  if (!isset($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($entities);
    $context['sandbox']['entities'] = $entities;
  }
  try {
    $storage = \Drupal::entityTypeManager()->getStorage($entity_type);
    /** @var \Drupal\k8s\Service\K8sOperationsService $operation_service */
    $operation_service = \Drupal::service('k8s.operations');
    $count = min(5, count($context['sandbox']['entities']));
    $method = k8s_get_update_method($entity_type);

    for ($i = 1; $i <= $count; $i++) {
      $entity = array_shift($context['sandbox']['entities']);
      // Reset the cache and load a fresh copy of the $entity.
      $entity = $storage->load($entity);
      $operation_service->refreshEntity($entity, FALSE);

      CloudService::updateEntityValues($entity, $updates);
      $storage->resetCache([$entity->id()]);
      $entity = $storage->load($entity->id());

      if (empty($method) || !method_exists($operation_service, $method)) {
        // Skip to next entity.
        $context['sandbox']['progress']++;
        continue;
      }

      // Always set batch == FALSE when updating entities.
      // Starting a second non-progressive batch during batch processing
      // causes the initial batch to never return.
      $operation_service->$method($entity, ['detail' => $entity->getDetail()], FALSE);
      // Update our progress information.
      $context['sandbox']['progress']++;
    }
  }
  catch (\Exception $e) {
    \Drupal::service('cloud')->handleException($e);
    // Set progress value to max so batch processing completes.
    $context['sandbox']['progress'] = $context['sandbox']['max'];
  }

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

/**
 * Helper function to determine which k8s update method to call.
 *
 * This function is used when batch reassigning UIDs during user delete.
 *
 * @param string $entity_type
 *   The entity type string.
 *
 * @return string
 *   The method string.
 */
function k8s_get_update_method(string $entity_type) {
  $method = '';
  switch ($entity_type) {
    case 'k8s_namespace':
      $method = 'updateNamespace';
      break;

    // No update for these.
    case 'k8s_node':
    case 'k8s_schedule':
    case 'k8s_event':
      break;

    default:
      $method = 'updateEntity';
  }
  return $method;
}

/**
 * Convert the value of CPU to float value.
 *
+50 −161
Original line number Diff line number Diff line
@@ -284,11 +284,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($namespace['metadata']['annotations'])
      && !empty($namespace['metadata']['annotations'][$uid_tag_key])
        ? $namespace['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $uid = self::getUidFromAnnotation($namespace, $cloud_context);
    $entity->setOwnerById($uid > 0 ? $uid : 0);

    $entity->setStatus($status);
@@ -352,12 +348,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($pod['metadata']['annotations'])
      && !empty($pod['metadata']['annotations'][$uid_tag_key])
        ? $pod['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($pod, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -518,12 +509,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($deployment['metadata']['annotations'])
      && !empty($deployment['metadata']['annotations'][$uid_tag_key])
        ? $deployment['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($deployment, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -597,12 +583,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($replica_set['metadata']['annotations'])
      && !empty($replica_set['metadata']['annotations'][$uid_tag_key])
        ? $replica_set['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($replica_set, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -669,12 +650,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($service['metadata']['annotations'])
      && !empty($service['metadata']['annotations'][$uid_tag_key])
        ? $service['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($service, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -792,12 +768,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($cron_job['metadata']['annotations'])
      && !empty($cron_job['metadata']['annotations'][$uid_tag_key])
        ? $cron_job['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($cron_job, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -881,12 +852,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($job['metadata']['annotations'])
      && !empty($job['metadata']['annotations'][$uid_tag_key])
        ? $job['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($job, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -983,12 +949,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($resource_quota['metadata']['annotations'])
      && !empty($resource_quota['metadata']['annotations'][$uid_tag_key])
        ? $resource_quota['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($resource_quota, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -1066,12 +1027,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($limit_range['metadata']['annotations'])
      && !empty($limit_range['metadata']['annotations'][$uid_tag_key])
        ? $limit_range['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($limit_range, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -1174,12 +1130,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($secret['metadata']['annotations'])
      && !empty($secret['metadata']['annotations'][$uid_tag_key])
        ? $secret['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($secret, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -1251,12 +1202,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($config_map['metadata']['annotations'])
      && !empty($config_map['metadata']['annotations'][$uid_tag_key])
        ? $config_map['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($config_map, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -1327,12 +1273,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($network_policy['metadata']['annotations'])
      && !empty($network_policy['metadata']['annotations'][$uid_tag_key])
        ? $network_policy['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($network_policy, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -1415,12 +1356,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($role['metadata']['annotations'])
      && !empty($role['metadata']['annotations'][$uid_tag_key])
        ? $role['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($role, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -1504,12 +1440,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($cluster_role['metadata']['annotations'])
      && !empty($cluster_role['metadata']['annotations'][$uid_tag_key])
        ? $cluster_role['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($cluster_role, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -1591,12 +1522,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($storage_class['metadata']['annotations'])
      && !empty($storage_class['metadata']['annotations'][$uid_tag_key])
        ? $storage_class['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($storage_class, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -1668,12 +1594,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($stateful_set['metadata']['annotations'])
      && !empty($stateful_set['metadata']['annotations'][$uid_tag_key])
        ? $stateful_set['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($stateful_set, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -1747,12 +1668,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($persistent_volume['metadata']['annotations'])
      && !empty($persistent_volume['metadata']['annotations'][$uid_tag_key])
        ? $persistent_volume['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($persistent_volume, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -1834,12 +1750,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($ingress['metadata']['annotations'])
      && !empty($ingress['metadata']['annotations'][$uid_tag_key])
        ? $ingress['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($ingress, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -1952,12 +1863,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($daemon_set['metadata']['annotations'])
      && !empty($daemon_set['metadata']['annotations'][$uid_tag_key])
        ? $daemon_set['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($daemon_set, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -2058,12 +1964,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($endpoint['metadata']['annotations'])
      && !empty($endpoint['metadata']['annotations'][$uid_tag_key])
        ? $endpoint['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($endpoint, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -2209,12 +2110,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($persistent_volume_claim['metadata']['annotations'])
      && !empty($persistent_volume_claim['metadata']['annotations'][$uid_tag_key])
        ? $persistent_volume_claim['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($persistent_volume_claim, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -2282,12 +2178,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($cluster_role_binding['metadata']['annotations'])
      && !empty($cluster_role_binding['metadata']['annotations'][$uid_tag_key])
        ? $cluster_role_binding['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($cluster_role_binding, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -2372,12 +2263,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($role_binding['metadata']['annotations'])
      && !empty($role_binding['metadata']['annotations'][$uid_tag_key])
        ? $role_binding['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($role_binding, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -2506,12 +2392,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($api_service['metadata']['annotations'])
      && !empty($api_service['metadata']['annotations'][$uid_tag_key])
        ? $api_service['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($api_service, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -2608,12 +2489,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($service_account['metadata']['annotations'])
      && !empty($service_account['metadata']['annotations'][$uid_tag_key])
        ? $service_account['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($service_account, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -2701,12 +2577,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($priority_class['metadata']['annotations'])
      && !empty($priority_class['metadata']['annotations'][$uid_tag_key])
        ? $priority_class['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($priority_class, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -2772,12 +2643,7 @@ class K8sBatchOperations {
    }

    // Owner ID.
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    $uid = !empty($horizontal_pod_autoscaler['metadata']['annotations'])
      && !empty($horizontal_pod_autoscaler['metadata']['annotations'][$uid_tag_key])
        ? $horizontal_pod_autoscaler['metadata']['annotations'][$uid_tag_key]
        : NULL;
    $entity->setOwnerById($uid);
    $entity->setOwnerById(self::getUidFromAnnotation($horizontal_pod_autoscaler, $cloud_context));

    // Labels.
    self::setKeyValueTypeFieldValue(
@@ -2882,4 +2748,27 @@ class K8sBatchOperations {
    return !empty($resource_class) ? $resource_class::load($entity_id) : NULL;
  }

  /**
   * Get the UID stored in an entity annotation.
   *
   * @param array $entity_array
   *   Entity array with data from K8s api call.
   * @param string $cloud_context
   *   The cloud context.
   *
   * @return string|null
   *   String or NULL if uid tag cannot be retrieve.
   */
  public static function getUidFromAnnotation(array $entity_array, string $cloud_context): ?string {
    $uid_tag_key = \Drupal::service('cloud')->getTagKeyCreatedByUid('k8s', $cloud_context);
    // Accommodate any user tags that are set to 0 for anonymous.
    if (isset($entity_array['metadata']['annotations'][$uid_tag_key]) && $entity_array['metadata']['annotations'][$uid_tag_key] === '0') {
      return $entity_array['metadata']['annotations'][$uid_tag_key];
    }
    return !empty($entity_array['metadata']['annotations'])
    && !empty($entity_array['metadata']['annotations'][$uid_tag_key])
      ? $entity_array['metadata']['annotations'][$uid_tag_key]
      : NULL;
  }

}
+5 −2
Original line number Diff line number Diff line
@@ -4,6 +4,7 @@ namespace Drupal\k8s\Service\K8sClientExtension;

use Drupal\cloud\Traits\CloudContentEntityTrait;
use Drupal\k8s\Service\K8sServiceException;
use Drupal\cloud\Service\CloudResourceTagInterface;
use Maclof\Kubernetes\Client;
use Maclof\Kubernetes\Exceptions\BadRequestException;
use Maclof\Kubernetes\Exceptions\ApiServerException;
@@ -115,8 +116,10 @@ class K8sClient extends Client {
      if (is_array($value)) {
        $haystack[$key] = $this->removeEmptyProperties($value);
      }

      if (empty($haystack[$key])) {
      // The uid annotation can be assigned 0 (anonymous user) during user
      // delete operation.  Do not unset a string that starts with `drupal-k8s.`
      // which is the tag used to store UIDs in K8s.
      if (!str_starts_with($key, CloudResourceTagInterface::PREFIX_UID_TAG_NAME['k8s']) && empty($haystack[$key])) {
        unset($haystack[$key]);
      }
    }
+42 −21
Original line number Diff line number Diff line
@@ -89,9 +89,9 @@ class K8sOperationsService extends CloudServiceBase implements K8sOperationsServ
  /**
   * {@inheritdoc}
   */
  public function updateNamespace(ContentEntityInterface $entity, array $params): bool {
    $labels = $params['labels'];
    $annotations = $params['annotations'];
  public function updateNamespace(ContentEntityInterface $entity, array $params, bool $batch = TRUE): bool {
    $labels = $params['labels'] ?? [];
    $annotations = $params['annotations'] ?? [];
    empty($labels) ?: $entity->setLabels($labels);
    empty($annotations) ?: $entity->setAnnotations($annotations);

@@ -119,9 +119,7 @@ class K8sOperationsService extends CloudServiceBase implements K8sOperationsServ
        return TRUE;
      }

      $this->k8sService->updateNamespaces([
        'metadata.name' => $entity->getName(),
      ], FALSE);
      $this->refreshEntity($entity, $batch);

      $this->processOperationStatus($entity, 'updated');
    }
@@ -163,7 +161,7 @@ class K8sOperationsService extends CloudServiceBase implements K8sOperationsServ
  /**
   * {@inheritdoc}
   */
  public function updateEntity(ContentEntityInterface $entity, array $params): bool {
  public function updateEntity(ContentEntityInterface $entity, array $params, bool $batch = TRUE): bool {
    $detail = $params['detail'];
    $name_underscore = $this->getShortEntityTypeNameUnderscore($entity);
    $name_camel = $this->getShortEntityTypeNameCamel($entity);
@@ -199,11 +197,7 @@ class K8sOperationsService extends CloudServiceBase implements K8sOperationsServ
      }

      // Update the entity.
      $name_plural_camel = $this->getShortEntityTypeNamePluralCamel($entity);
      $method_name = "update${name_plural_camel}";
      $this->k8sService->$method_name([
        'metadata.name' => $entity->getName(),
      ], FALSE);
      $this->refreshEntity($entity, $batch);

      $this->processOperationStatus($entity, 'updated');
    }
@@ -226,6 +220,40 @@ class K8sOperationsService extends CloudServiceBase implements K8sOperationsServ
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function refreshEntity(EntityInterface $entity, bool $batch = TRUE): void {
    $this->k8sService->setCloudContext($entity->getCloudContext());
    if ($entity->getEntityTypeId() === 'k8s_namespace') {
      $method_name = ($batch === TRUE)
        ? 'updateNamespaces'
        : 'updateNamespacesWithoutBatch';

      $this->k8sService->$method_name([
        'metadata.name' => $entity->getName(),
      ], FALSE);

      return;
    }

    $name_plural_camel = $this->getShortEntityTypeNamePluralCamel($entity);
    $method_name = ($batch === TRUE)
      ? "update${name_plural_camel}"
      : "update${name_plural_camel}WithoutBatch";

    $params = [
      'metadata.name' => $entity->getName(),
    ];
    // Add namespace into query if possible.  Some entities can have
    // the same name.  Add namespace to make the query more specific.
    if (method_exists($entity, 'getNamespace')) {
      $params['metadata.namespace'] = $entity->getNamespace();
    }
    $this->k8sService->$method_name($params, FALSE);

  }

  /**
   * Create a Secret based on $yaml.
   *
@@ -826,11 +854,7 @@ class K8sOperationsService extends CloudServiceBase implements K8sOperationsServ
      $entity->save();

      // Update the entity.
      $name_plural_camel = $this->getShortEntityTypeNamePluralCamel($entity);
      $method_name = "update${name_plural_camel}";
      $this->k8sService->$method_name([
        'metadata.name' => $entity->getName(),
      ], FALSE);
      $this->refreshEntity($entity);

      $this->processOperationStatus($entity, 'created');

@@ -1211,10 +1235,7 @@ class K8sOperationsService extends CloudServiceBase implements K8sOperationsServ
      $entity->save();

      // Update the entity.
      $this->k8sService->updateDeployments([
        'metadata.namespace' => $entity->getNamespace(),
        'metadata.name' => $entity->getName(),
      ], FALSE);
      $this->refreshEntity($entity);

      $this->processOperationStatus($entity, 'scaled');
      return TRUE;
Loading