public static NetworkGroup delete(final OwnerFullName ownerFullName, final String groupName)
     throws MetadataException {
   if (defaultNetworkName().equals(groupName)) {
     createDefault(ownerFullName);
   }
   final EntityTransaction db = Entities.get(NetworkGroup.class);
   try {
     final NetworkGroup ret = Entities.uniqueResult(new NetworkGroup(ownerFullName, groupName));
     Entities.delete(ret);
     db.commit();
     return ret;
   } catch (final ConstraintViolationException ex) {
     Logs.exhaust().error(ex, ex);
     db.rollback();
     throw new IllegalMetadataAccessException(
         "Failed to delete security group: "
             + groupName
             + " for "
             + ownerFullName
             + " because of: "
             + Exceptions.causeString(ex),
         ex);
   } catch (final Exception ex) {
     Logs.exhaust().error(ex, ex);
     db.rollback();
     throw new NoSuchMetadataException(
         "Failed to find security group: " + groupName + " for " + ownerFullName, ex);
   }
 }
 public void abort() {
   for (final ResourceToken token : this.allocationTokens) {
     LOG.warn("Aborting resource token: " + token);
     Logs.exhaust().error("Aborting resource token", new RuntimeException());
     final EntityTransaction db = Entities.get(VmInstance.class);
     try {
       token.abort();
       db.commit();
     } catch (final Exception ex) {
       LOG.warn(ex.getMessage());
       Logs.exhaust().error(ex, ex);
       db.rollback();
     }
   }
 }
 TransactionState(final String ctx) {
   this.startTime = System.currentTimeMillis();
   this.txUuid = String.format("%s:%s", ctx, UUID.randomUUID().toString());
   this.stopWatch = new StopWatch();
   this.stopWatch.start();
   this.owner = Logs.isExtrrreeeme() ? Threads.currentStackString() : "n/a";
   try {
     this.eventLog(TxStep.BEGIN, TxEvent.CREATE);
     final EntityManagerFactory anemf =
         (EntityManagerFactoryImpl) PersistenceContexts.getEntityManagerFactory(ctx);
     checkParam(anemf, notNullValue());
     this.em = anemf.createEntityManager();
     checkParam(this.em, notNullValue());
     this.transaction = this.em.getTransaction();
     this.transaction.begin();
     this.session = new WeakReference<Session>((Session) this.em.getDelegate());
     this.eventLog(TxStep.END, TxEvent.CREATE);
   } catch (final Throwable ex) {
     Logs.exhaust().error(ex, ex);
     this.eventLog(TxStep.FAIL, TxEvent.CREATE);
     this.rollback();
     throw new RuntimeException(PersistenceExceptions.throwFiltered(ex));
   } finally {
     outstanding.put(this.txUuid, this);
   }
 }
  /**
   * Add launch permissions.
   *
   * @param accountIds
   */
  public void addPermissions(final List<String> accountIds) {
    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {
      final ImageInfo entity = Entities.merge(this);
      Iterables.all(
          accountIds,
          new Predicate<String>() {

            @Override
            public boolean apply(final String input) {
              try {
                final Account account = Accounts.lookupAccountById(input);
                ImageInfo.this.getPermissions().add(input);
              } catch (final Exception e) {
                try {
                  final User user = Accounts.lookupUserById(input);
                  ImageInfo.this.getPermissions().add(user.getAccount().getAccountNumber());
                } catch (AuthException ex) {
                  try {
                    final User user = Accounts.lookupUserByAccessKeyId(input);
                    ImageInfo.this.getPermissions().add(user.getAccount().getAccountNumber());
                  } catch (AuthException ex1) {
                    LOG.error(ex1, ex1);
                  }
                }
              }
              return true;
            }
          });
      db.commit();
    } catch (final Exception ex) {
      Logs.exhaust().error(ex, ex);
      db.rollback();
    }
  }
  /**
   * Remove launch permissions.
   *
   * @param accountIds
   */
  public void removePermissions(final List<String> accountIds) {

    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {
      final ImageInfo entity = Entities.merge(this);
      Iterables.all(
          accountIds,
          new Predicate<String>() {

            @Override
            public boolean apply(final String input) {
              try {
                final Account account = Accounts.lookupAccountById(input);
                ImageInfo.this.getPermissions().remove(input);
              } catch (final Exception e) {
                LOG.error(e, e);
              }
              return true;
            }
          });

      db.commit();
    } catch (final Exception ex) {
      Logs.exhaust().error(ex, ex);
      db.rollback();
    }
  }
 public static NetworkGroup lookupByNaturalId(final String uuid) throws NoSuchMetadataException {
   EntityTransaction db = Entities.get(NetworkGroup.class);
   try {
     NetworkGroup entity = Entities.uniqueResult(NetworkGroup.withNaturalId(uuid));
     db.commit();
     return entity;
   } catch (Exception ex) {
     Logs.exhaust().error(ex, ex);
     db.rollback();
     throw new NoSuchMetadataException("Failed to find security group: " + uuid, ex);
   }
 }
 @SuppressWarnings("unchecked")
 public ImageInfo grantPermission(final Account account) {
   EntityTransaction db = Entities.get(ImageInfo.class);
   try {
     ImageInfo entity = Entities.merge(this);
     entity.getPermissions().add(account.getAccountNumber());
     db.commit();
   } catch (Exception ex) {
     Logs.exhaust().error(ex, ex);
     db.rollback();
   }
   return this;
 }
 /** GRZE:REMOVE: /not/ OK. cross-module reference to private component data type. * */
 public boolean checkPermission(final String accountId) {
   EntityTransaction db = Entities.get(ImageInfo.class);
   try {
     ImageInfo entity = Entities.merge(this);
     boolean ret = this.getPermissions().contains(accountId) || this.getOwner().isOwner(accountId);
     db.commit();
     return ret;
   } catch (Exception ex) {
     Logs.exhaust().error(ex, ex);
     db.rollback();
     return false;
   }
 }
  public boolean addProductCode(final String prodCode) {

    EntityTransaction db = Entities.get(ImageInfo.class);
    try {
      ImageInfo entity = Entities.merge(this);
      entity.getProductCodes().add(prodCode);
      db.commit();
      return true;
    } catch (Exception ex) {
      Logs.exhaust().error(ex, ex);
      db.rollback();
      return false;
    }
  }
 public static NetworkGroup lookupByGroupId(
     @Nullable final OwnerFullName ownerFullName, final String groupId)
     throws NoSuchMetadataException {
   EntityTransaction db = Entities.get(NetworkGroup.class);
   try {
     NetworkGroup entity = Entities.uniqueResult(NetworkGroup.withGroupId(ownerFullName, groupId));
     db.commit();
     return entity;
   } catch (Exception ex) {
     Logs.exhaust().error(ex, ex);
     db.rollback();
     throw new NoSuchMetadataException("Failed to find security group: " + groupId, ex);
   }
 }
 public static NetworkGroup lookup(final OwnerFullName ownerFullName, final String groupName)
     throws MetadataException {
   if (defaultNetworkName().equals(groupName)) {
     createDefault(ownerFullName);
   }
   final EntityTransaction db = Entities.get(NetworkGroup.class);
   try {
     final NetworkGroup ret = Entities.uniqueResult(new NetworkGroup(ownerFullName, groupName));
     db.commit();
     return ret;
   } catch (final Exception ex) {
     Logs.exhaust().error(ex, ex);
     db.rollback();
     throw new NoSuchMetadataException(
         "Failed to find security group: " + groupName + " for " + ownerFullName, ex);
   }
 }
Exemple #12
0
 private final void eventLog(final TxStep txState, final TxEvent txAction) {
   if (Logs.isExtrrreeeme()) {
     final long oldSplit = this.splitTime;
     this.stopWatch.split();
     this.splitTime = this.stopWatch.getSplitTime();
     this.stopWatch.unsplit();
     final Long split = this.splitTime - oldSplit;
     Logs.exhaust()
         .debug(
             Joiner.on(":")
                 .join(
                     EventType.PERSISTENCE,
                     txState.event(txAction),
                     Long.toString(split),
                     this.getTxUuid()));
   }
 }
 @Override
 public boolean apply(Allocation allocInfo) {
   List<ResourceAllocator> finished = Lists.newArrayList();
   EntityTransaction db = Entities.get(NetworkGroup.class);
   try {
     for (ResourceAllocator allocator : restorers) {
       runAllocatorSafely(allocInfo, allocator);
       finished.add(allocator);
     }
     db.commit();
     return true;
   } catch (Exception ex) {
     Logs.exhaust().error(ex, ex);
     rollbackAllocations(allocInfo, finished, ex);
     db.rollback();
     throw Exceptions.toUndeclared(new NotEnoughResourcesException(ex.getMessage(), ex));
   }
 }
 public static List<NetworkGroup> lookupAll(
     final OwnerFullName ownerFullName, final String groupNamePattern) throws MetadataException {
   if (defaultNetworkName().equals(groupNamePattern)) {
     createDefault(ownerFullName);
   }
   final EntityTransaction db = Entities.get(NetworkGroup.class);
   try {
     final List<NetworkGroup> results =
         Entities.query(new NetworkGroup(ownerFullName, groupNamePattern));
     final List<NetworkGroup> ret = Lists.newArrayList(results);
     db.commit();
     return ret;
   } catch (final Exception ex) {
     Logs.exhaust().error(ex, ex);
     db.rollback();
     throw new NoSuchMetadataException(
         "Failed to find security group: " + groupNamePattern + " for " + ownerFullName, ex);
   }
 }
  @Override
  public void onResource(final RestrictedType resource, final String action) {
    EuarePolicyContext.clearContext();

    if (resource != null) {
      if (accepted.contains(resource.getClass())
          || (!rejected.contains(resource.getClass())
              && Account.class.isAssignableFrom(resource.getClass())))
        try {
          EuarePolicyContext.setEuarePolicyContextResource(
              TypeMappers.transform(resource, EuarePolicyContextResource.class));
          accepted.add(resource.getClass());
        } catch (IllegalArgumentException e) {
          rejected.add(resource.getClass());
          Logs.exhaust()
              .info(
                  "Policy context not set for resource type: "
                      + resource.getClass().getSimpleName());
        }
    }
  }
  @SuppressWarnings("unchecked")
  @Override
  public void onResource(final PolicyResourceInfo resource, final String action) {
    EuarePolicyContext.clearContext();

    if (resource != null && RestrictedType.class.isAssignableFrom(resource.getResourceClass())) {
      if (accepted.contains(resource.getResourceClass())
          || (!rejected.contains(resource.getResourceClass())
              && EuareAccount.class.isAssignableFrom(resource.getResourceClass())))
        try {
          EuarePolicyContext.setEuarePolicyContextResource(
              TypeMappers.transform(
                  resource.getResourceObject(), EuarePolicyContextResource.class));
          accepted.add((Class<? extends RestrictedType>) resource.getResourceClass());
        } catch (IllegalArgumentException e) {
          rejected.add((Class<? extends RestrictedType>) resource.getResourceClass());
          Logs.exhaust()
              .info(
                  "Policy context not set for resource type: "
                      + resource.getResourceClass().getSimpleName());
        }
    }
  }
 @Override
 public boolean apply(Allocation allocInfo) {
   if (EventRecord.isTraceEnabled(AdmissionControl.class)) {
     EventRecord.here(
             AdmissionControl.class, EventType.VM_RESERVED, LogUtil.dumpObject(allocInfo))
         .trace();
   }
   List<ResourceAllocator> finished = Lists.newArrayList();
   EntityTransaction db = Entities.get(NetworkGroup.class);
   try {
     for (ResourceAllocator allocator : allocators) {
       runAllocatorSafely(allocInfo, allocator);
       finished.add(allocator);
     }
     db.commit();
     return true;
   } catch (Exception ex) {
     Logs.exhaust().error(ex, ex);
     rollbackAllocations(allocInfo, finished, ex);
     db.rollback();
     throw Exceptions.toUndeclared(
         new NotEnoughResourcesException(Exceptions.getCauseMessage(ex), ex));
   }
 }
  public static NetworkGroup create(
      final OwnerFullName ownerFullName, final String groupName, final String groupDescription)
      throws MetadataException {
    UserFullName userFullName = null;
    if (ownerFullName instanceof UserFullName) {
      userFullName = (UserFullName) ownerFullName;
    } else {
      try {
        Account account = Accounts.lookupAccountById(ownerFullName.getAccountNumber());
        User admin =
            Iterables.find(
                account.getUsers(),
                new Predicate<User>() {

                  @Override
                  public boolean apply(User input) {
                    return input.isAccountAdmin();
                  }
                });
        userFullName = UserFullName.getInstance(admin);
      } catch (Exception ex) {
        LOG.error(ex, ex);
        throw new NoSuchMetadataException(
            "Failed to create group because owning user could not be identified.", ex);
      }
    }

    final EntityTransaction db = Entities.get(NetworkGroup.class);
    try {
      NetworkGroup net =
          Entities.uniqueResult(
              new NetworkGroup(
                  AccountFullName.getInstance(userFullName.getAccountNumber()), groupName));
      if (net == null) {
        final NetworkGroup entity =
            Entities.persist(new NetworkGroup(userFullName, groupName, groupDescription));
        db.commit();
        return entity;
      } else {
        db.rollback();
        throw new DuplicateMetadataException(
            "Failed to create group: " + groupName + " for " + userFullName.toString());
      }
    } catch (final NoSuchElementException ex) {
      final NetworkGroup entity =
          Entities.persist(new NetworkGroup(userFullName, groupName, groupDescription));
      db.commit();
      return entity;
    } catch (final ConstraintViolationException ex) {
      Logs.exhaust().error(ex);
      db.rollback();
      throw new DuplicateMetadataException(
          "Failed to create group: " + groupName + " for " + userFullName.toString(), ex);
    } catch (final Exception ex) {
      Logs.exhaust().error(ex, ex);
      db.rollback();
      throw new MetadataException(
          "Failed to create group: " + groupName + " for " + userFullName.toString(),
          PersistenceExceptions.transform(ex));
    }
  }