@SuppressWarnings("unchecked")
 private boolean noOtherEnabled(final ServiceConfiguration config) {
   return Iterables.isEmpty(
       ServiceConfigurations.filter(
           CloudFormation.class,
           Predicates.and(
               ServiceConfigurations.filterHostLocal(),
               ServiceConfigurations.filterEnabled(),
               Predicates.not(Predicates.equalTo(config)))));
 }
 @Override
 public ServiceStatusDetail apply(final CheckException input) {
   final ServiceConfiguration config =
       ServiceConfigurations.lookupByName(input.getServiceName());
   return new ServiceStatusDetail() {
     {
       this.setSeverity(input.getSeverity().toString());
       this.setUuid(input.getCorrelationId());
       this.setTimestamp(input.getTimestamp().toString());
       this.setMessage(
           input.getMessage() != null
               ? input.getMessage()
               : "No summary information available.");
       this.setStackTrace(
           input.getStackString() != null
               ? input.getStackString()
               : Exceptions.string(
                   new RuntimeException(
                       "Error while mapping service event record:  No stack information available")));
       this.setServiceFullName(config.getFullName().toString());
       this.setServiceHost(config.getHostName());
       this.setServiceName(input.getServiceName());
     }
   };
 }
  public static ServiceConfiguration findService(final String name) {
    checkParam(name, notNullValue());
    Predicate<ServiceConfiguration> nameOrFullName =
        new Predicate<ServiceConfiguration>() {

          @Override
          public boolean apply(ServiceConfiguration input) {
            return name.equals(input.getName()) || name.equals(input.getFullName().toString());
          }
        };
    for (final ComponentId compId : ComponentIds.list()) {
      ServiceConfiguration a;
      try {
        return Iterables.find(Components.lookup(compId).services(), nameOrFullName);
      } catch (NoSuchElementException ex) {
        if (compId.isRegisterable()) {
          try {
            return ServiceConfigurations.lookupByName(compId.getClass(), name);
          } catch (Exception ex1) {
          }
        }
      }
    }
    throw new NoSuchElementException("Failed to lookup service named: " + name);
  }
  public static DescribeServicesResponseType describeService(final DescribeServicesType request) {
    final DescribeServicesResponseType reply = request.getReply();
    Topology.touch(request);
    if (request.getServices().isEmpty()) {
      final ComponentId compId =
          (request.getByServiceType() != null)
              ? ComponentIds.lookup(request.getByServiceType().toLowerCase())
              : Empyrean.INSTANCE;
      final boolean showEventStacks = Boolean.TRUE.equals(request.getShowEventStacks());
      final boolean showEvents = Boolean.TRUE.equals(request.getShowEvents()) || showEventStacks;

      final Function<ServiceConfiguration, ServiceStatusType> transformToStatus =
          ServiceConfigurations.asServiceStatus(showEvents, showEventStacks);
      final List<Predicate<ServiceConfiguration>> filters =
          new ArrayList<Predicate<ServiceConfiguration>>() {
            {
              if (request.getByPartition() != null) {
                Partitions.exists(request.getByPartition());
                this.add(Filters.partition(request.getByPartition()));
              }
              if (request.getByState() != null) {
                final Component.State stateFilter =
                    Component.State.valueOf(request.getByState().toUpperCase());
                this.add(Filters.state(stateFilter));
              }
              if (!request.getServiceNames().isEmpty()) {
                this.add(Filters.name(request.getServiceNames()));
              }
              this.add(Filters.host(request.getByHost()));
              this.add(
                  Filters.listAllOrInternal(
                      request.getListAll(),
                      request.getListUserServices(),
                      request.getListInternal()));
            }
          };
      final Predicate<Component> componentFilter = Filters.componentType(compId);
      final Predicate<ServiceConfiguration> configPredicate = Predicates.and(filters);

      List<ServiceConfiguration> replyConfigs = Lists.newArrayList();
      for (final Component comp : Components.list()) {
        if (componentFilter.apply(comp)) {
          Collection<ServiceConfiguration> acceptedConfigs =
              Collections2.filter(comp.services(), configPredicate);
          replyConfigs.addAll(acceptedConfigs);
        }
      }
      ImmutableList<ServiceConfiguration> sortedReplyConfigs =
          ServiceOrderings.defaultOrdering().immutableSortedCopy(replyConfigs);
      final Collection<ServiceStatusType> transformedReplyConfigs =
          Collections2.transform(sortedReplyConfigs, transformToStatus);
      reply.getServiceStatuses().addAll(transformedReplyConfigs);
    } else {
      for (ServiceId s : request.getServices()) {
        reply.getServiceStatuses().add(TypeMappers.transform(s, ServiceStatusType.class));
      }
    }
    return reply;
  }
 public static <T extends ServiceConfiguration, C extends ComponentId> List<T> list(
     final Class<C> type) throws PersistenceException {
   if (!ComponentId.class.isAssignableFrom(type)) {
     throw new PersistenceException(
         "Unknown configuration type passed: " + type.getCanonicalName());
   } else {
     final T example = (T) ServiceBuilders.lookup(type).newInstance();
     return ServiceConfigurations.list(example);
   }
 }
 /**
  * Update the {@link #partitionActiveNetworkTags} map by removing any {@code key} values which
  * no longer have a corresponding service registration.
  *
  * @throws PersistenceException
  */
 private void removeStalePartitions() throws PersistenceException {
   Set<String> partitions = Sets.newHashSet();
   for (ServiceConfiguration cc : ServiceConfigurations.list(ClusterController.class)) {
     partitions.add(cc.getPartition());
   }
   for (String stalePartition :
       Sets.difference(this.activeTagsByPartition.keySet(), partitions)) {
     this.activeTagsByPartition.removeAll(stalePartition);
   }
 }
    /*
     * Ensures that the proposed value is valid based on the set of valid values for OSGs
     * Additional DB lookup required for remote OSGs where the CLC doesn't have the OSG bits
     * installed and therefore doesn't have the same view of the set of valid values.
     * (non-Javadoc)
     * @see com.eucalyptus.configurable.PropertyChangeListener#fireChange(com.eucalyptus.configurable.ConfigurableProperty, java.lang.Object)
     */
    @Override
    public void fireChange(ConfigurableProperty t, String newValue)
        throws ConfigurablePropertyException {
      String existingValue = (String) t.getValue();

      List<ServiceConfiguration> objConfigs = null;
      try {
        objConfigs = ServiceConfigurations.list(ObjectStorage.class);
      } catch (NoSuchElementException e) {
        throw new ConfigurablePropertyException("No ObjectStorage configurations found");
      }

      final String proposedValue = newValue;
      final Set<String> validEntries = Sets.newHashSet();
      EntityTransaction tx = Entities.get(ObjectStorageConfiguration.class);
      try {
        if (!Iterables.any(
            Components.lookup(ObjectStorage.class).services(),
            new Predicate<ServiceConfiguration>() {
              @Override
              public boolean apply(ServiceConfiguration config) {
                if (config.isVmLocal()) {
                  // Service is local, so add entries to the valid list (in case of HA configs)
                  // and then check the local memory state
                  validEntries.addAll(ObjectStorageProviders.list());
                  return ObjectStorageProviders.contains(proposedValue);
                } else {
                  try {
                    // Remote SC, so check the db for the list of valid entries.
                    ObjectStorageConfiguration objConfig =
                        Entities.uniqueResult((ObjectStorageConfiguration) config);
                    for (String entry : Splitter.on(",").split(objConfig.getAvailableClients())) {
                      validEntries.add(entry);
                    }
                    return validEntries.contains(proposedValue);
                  } catch (Exception e) {
                    return false;
                  }
                }
              }
            })) {
          // Nothing matched.
          throw new ConfigurablePropertyException(
              "Cannot modify "
                  + t.getQualifiedName()
                  + "."
                  + t.getFieldName()
                  + " new value is not a valid value.  "
                  + "Legal values are: "
                  + Joiner.on(",").join(validEntries));
        }
      } finally {
        tx.rollback();
      }
    }
 @PrePersist
 private void updateRedundantConfig() {
   // Checks to see if other SCs exist in the same partition and uses the same backend config if it
   // exists.
   if (this.blockStorageManager == null && this.getPartition() != null) {
     for (ServiceConfiguration s :
         ServiceConfigurations.listPartition(Storage.class, this.getPartition())) {
       StorageControllerConfiguration otherSc = (StorageControllerConfiguration) s;
       this.blockStorageManager =
           otherSc.getBlockStorageManager() != null ? otherSc.getBlockStorageManager() : null;
     }
   }
 }
    public DescribeServicesResponseType user(final DescribeServicesType request) {
      final DescribeServicesResponseType reply = request.getReply();
      /**
       * Only show public services to normal users. Allow for filtering by component and state w/in
       * that set.
       */
      final List<Predicate<ServiceConfiguration>> filters =
          new ArrayList<Predicate<ServiceConfiguration>>() {
            {
              this.add(Filters.publicService());
              if (request.getByPartition() != null) {
                this.add(Filters.partition(request.getByPartition()));
              }
              if (request.getByState() != null) {
                this.add(
                    Filters.state(Component.State.valueOf(request.getByState().toUpperCase())));
              }
            }
          };
      final Predicate<Component> componentFilter =
          (Predicate<Component>)
              (request.getByServiceType() != null
                  ? Filters.componentType(
                      ComponentIds.lookup(request.getByServiceType().toLowerCase()))
                  : Predicates.alwaysTrue());
      final Predicate<ServiceConfiguration> configPredicate = Predicates.and(filters);

      final Collection<ServiceConfiguration> replyConfigs = Lists.newArrayList();
      for (final Component comp : Iterables.filter(Components.list(), componentFilter)) {
        replyConfigs.addAll(Collections2.filter(comp.services(), configPredicate));
      }
      final ImmutableList<ServiceConfiguration> sortedReplyConfigs =
          ServiceOrderings.defaultOrdering().immutableSortedCopy(replyConfigs);
      final Collection<ServiceStatusType> replyStatuses =
          Collections2.transform(
              sortedReplyConfigs, ServiceConfigurations.asServiceStatus(false, false));
      reply.getServiceStatuses().addAll(replyStatuses);
      return reply;
    }
 @Override
 public ServiceConfiguration newInstance() {
   ComponentId compId = this.getComponentId();
   return ServiceConfigurations.createEphemeral(compId);
 }
 @Override
 public ServiceConfiguration newInstance(
     String partition, String name, String host, Integer port) {
   ComponentId compId = this.getComponentId();
   return ServiceConfigurations.createEphemeral(compId);
 }
 public static <T extends ServiceConfiguration, C extends ComponentId> Iterable<T> filter(
     final Class<C> type, final Predicate<T> pred) throws PersistenceException {
   List<T> list = ServiceConfigurations.list(type);
   return Iterables.filter(list, pred);
 }
    @Override
    public void fireChange(ConfigurableProperty t, String newValue)
        throws ConfigurablePropertyException {
      String existingValue = (String) t.getValue();
      if (existingValue != null && !"<unset>".equals(existingValue)) {
        throw new ConfigurablePropertyException(
            "Cannot change extant storage backend configuration. You must deregister all SCs in the partition before you can change the configuration value");
      } else {
        // Try to figure out the partition name for the request
        String probablePartitionName = ((MultiDatabasePropertyEntry) t).getEntrySetName();
        if (probablePartitionName == null) {
          throw new ConfigurablePropertyException(
              "Could not determing partition name from property to check validity");
        }

        String[] parts = probablePartitionName.split("\\.");
        if (parts == null || parts.length == 0) {
          throw new ConfigurablePropertyException(
              "Could not determing partition name from property to check validity: "
                  + probablePartitionName);
        }
        probablePartitionName = parts[0];

        /*Look through the service configurations for each SC in the partition and see if the value is valid.
         * This step must work if we don't allow the user to change it once set.
         * The difficulty here is if 2 SCs are in an HA pair but have different backends installed (i.e. packages)
         * The implemented semantic is that if the proposed value is valid in either SC, then allow the change.
         */
        List<ServiceConfiguration> scConfigs = null;
        try {
          scConfigs = ServiceConfigurations.listPartition(Storage.class, probablePartitionName);
        } catch (NoSuchElementException e) {
          throw new ConfigurablePropertyException(
              "No Storage Controller configurations found for partition: " + probablePartitionName);
        }

        final String proposedValue = newValue;
        final Set<String> validEntries = Sets.newHashSet();
        EntityTransaction tx = Entities.get(StorageControllerConfiguration.class);
        try {
          if (!Iterables.any(
              scConfigs,
              new Predicate<ServiceConfiguration>() {
                @Override
                public boolean apply(ServiceConfiguration config) {
                  if (config.isVmLocal()) {
                    // Service is local, so add entries to the valid list (in case of HA configs)
                    // and then check the local memory state
                    validEntries.addAll(StorageManagers.list());
                    return StorageManagers.contains(proposedValue);
                  } else {
                    try {
                      // Remote SC, so check the db for the list of valid entries.
                      StorageControllerConfiguration scConfig =
                          Entities.uniqueResult((StorageControllerConfiguration) config);
                      for (String entry : Splitter.on(",").split(scConfig.getAvailableBackends())) {
                        validEntries.add(entry);
                      }
                      return validEntries.contains(proposedValue);
                    } catch (Exception e) {
                      return false;
                    }
                  }
                }
              })) {
            // Nothing matched.
            throw new ConfigurablePropertyException(
                "Cannot modify "
                    + t.getQualifiedName()
                    + "."
                    + t.getFieldName()
                    + " new value is not a valid value.  "
                    + "Legal values are: "
                    + Joiner.on(",").join(validEntries));
          }
        } finally {
          tx.rollback();
        }
      }
    }