/** Walks the contents of a ManagementContext, to create a corresponding memento. */
  public static BrooklynMemento newBrooklynMemento(ManagementContext managementContext) {
    BrooklynMementoImpl.Builder builder = BrooklynMementoImpl.builder();

    for (Application app : managementContext.getApplications()) {
      builder.applicationIds.add(app.getId());
    }
    for (Entity entity : managementContext.getEntityManager().getEntities()) {
      builder.entities.put(
          entity.getId(), ((EntityInternal) entity).getRebindSupport().getMemento());

      for (Location location : entity.getLocations()) {
        if (!builder.locations.containsKey(location.getId())) {
          for (Location locationInHierarchy : TreeUtils.findLocationsInHierarchy(location)) {
            if (!builder.locations.containsKey(locationInHierarchy.getId())) {
              builder.locations.put(
                  locationInHierarchy.getId(),
                  ((LocationInternal) locationInHierarchy).getRebindSupport().getMemento());
            }
          }
        }
      }
    }
    for (LocationMemento memento : builder.locations.values()) {
      if (memento.getParent() == null) {
        builder.topLevelLocationIds.add(memento.getId());
      }
    }

    BrooklynMemento result = builder.build();
    MementoValidators.validateMemento(result);
    return result;
  }
 @Test
 public void testResolvesPropertiesInSpec() throws Exception {
   Location location = resolve("localhost(privateKeyFile=myprivatekeyfile,name=myname)");
   assertTrue(location instanceof LocalhostMachineProvisioningLocation);
   assertEquals(location.getDisplayName(), "myname");
   assertEquals(location.getAllConfig(true).get("privateKeyFile"), "myprivatekeyfile");
 }
  public void addChild(Location child) {
    // Previously, setParent delegated to addChildLocation and we sometimes ended up with
    // duplicate entries here. Instead this now uses a similar scheme to
    // AbstractLocation.setParent/addChild (with any weaknesses for distribution that such a
    // scheme might have...).
    //
    // We continue to use a list to allow identical-looking locations, but they must be different
    // instances.

    synchronized (children) {
      for (Location contender : children) {
        if (contender == child) {
          // don't re-add; no-op
          return;
        }
      }

      children.add(child);
    }

    if (isManaged()) {
      Locations.manage(child, managementContext);
    } else if (managementContext != null) {
      if (((LocalLocationManager) managementContext.getLocationManager())
              .getLocationEvenIfPreManaged(child.getId())
          == null) {
        ((ManagementContextInternal) managementContext).prePreManage(child);
      }
    }

    children.add(child);
    child.setParent(this);
  }
 public boolean containsLocation(Location potentialDescendent) {
   Location loc = potentialDescendent;
   while (loc != null) {
     if (this == loc) return true;
     loc = loc.getParentLocation();
   }
   return false;
 }
  public boolean equals(Object o) {
    if (!(o instanceof Location)) {
      return false;
    }

    Location l = (Location) o;
    return getId().equals(l.getId());
  }
  @Test
  public void testResolvesDefaultName() throws Exception {
    Location location = resolve("localhost");
    assertTrue(location instanceof LocalhostMachineProvisioningLocation);
    assertEquals(location.getDisplayName(), "localhost");

    Location location2 = resolve("localhost()");
    assertTrue(location2 instanceof LocalhostMachineProvisioningLocation);
    assertEquals(location2.getDisplayName(), "localhost");
  }
 @Override
 @Deprecated
 public Object findLocationProperty(String key) {
   if (hasLocationProperty(key)) return getLocationProperty(key);
   if (parentLocation != null) return parentLocation.findLocationProperty(key);
   return null;
 }
 @Override
 public void onManageLocationFailed(Location location, Exception e) {
   manageLocationFailures.put(
       location,
       new IllegalStateException(
           "problem managing location " + location.getId() + " (" + location + ")", e));
   super.onManageLocationFailed(location, e);
 }
 @Override
 public PortMapping getPortMappingWithPrivateSide(Location l, int privatePort) {
   synchronized (mutex) {
     for (PortMapping m : mappings.values())
       if (l.equals(m.getTarget()) && privatePort == m.privatePort) return m;
   }
   return null;
 }
 /** returns the subset of port mappings associated with a given location */
 @Override
 public Collection<PortMapping> getLocationPublicIpIds(Location l) {
   List<PortMapping> result = new ArrayList<PortMapping>();
   synchronized (mutex) {
     for (PortMapping m : mappings.values()) if (l.equals(m.getTarget())) result.add(m);
   }
   return result;
 }
 @Override
 public HostAndPort lookup(Location l, int privatePort) {
   synchronized (mutex) {
     for (PortMapping m : mappings.values()) {
       if (l.equals(m.target) && privatePort == m.privatePort) return getPublicHostAndPort(m);
     }
   }
   return null;
 }
 protected boolean removeChildLocation(Location child) {
   boolean removed = childLocations.remove(child);
   if (removed) {
     if (child instanceof Closeable) {
       Closeables.closeQuietly((Closeable) child);
     }
     child.setParentLocation(null);
   }
   return removed;
 }
  @Test
  public void testCheckPointAndLoadMemento()
      throws IOException, TimeoutException, InterruptedException {
    BrooklynMemento reloadedMemento = loadMemento();

    assertNotNull(reloadedMemento);
    assertTrue(Iterables.contains(reloadedMemento.getEntityIds(), entity.getId()));
    assertEquals(Iterables.getOnlyElement(reloadedMemento.getLocationIds()), location.getId());
    assertEquals(Iterables.getOnlyElement(reloadedMemento.getPolicyIds()), policy.getId());
    assertEquals(Iterables.getOnlyElement(reloadedMemento.getEnricherIds()), enricher.getId());
  }
  @Test
  public void testDeleteAndLoadMemento()
      throws TimeoutException, InterruptedException, IOException {
    Entities.destroy(entity);

    BrooklynMemento reloadedMemento = loadMemento();

    assertNotNull(reloadedMemento);
    assertFalse(Iterables.contains(reloadedMemento.getEntityIds(), entity.getId()));
    assertEquals(Iterables.getOnlyElement(reloadedMemento.getLocationIds()), location.getId());
  }
  public static BasicLocationMemento.Builder newLocationMementoBuilder(Location location) {
    BasicLocationMemento.Builder builder = BasicLocationMemento.builder();

    Set<String> nonPersistableFlagNames =
        MutableMap.<String, Object>builder()
            .putAll(FlagUtils.getFieldsWithFlagsWithModifiers(location, Modifier.TRANSIENT))
            .putAll(FlagUtils.getFieldsWithFlagsWithModifiers(location, Modifier.STATIC))
            .put("id", String.class)
            .filterValues(Predicates.not(Predicates.instanceOf(ConfigKey.class)))
            .build()
            .keySet();
    Map<String, Object> persistableFlags =
        MutableMap.<String, Object>builder()
            .putAll(
                FlagUtils.getFieldsWithFlagsExcludingModifiers(
                    location, Modifier.STATIC ^ Modifier.TRANSIENT))
            .removeAll(nonPersistableFlagNames)
            .build();
    ConfigBag persistableConfig =
        new ConfigBag()
            .copy(((AbstractLocation) location).getLocalConfigBag())
            .removeAll(nonPersistableFlagNames);

    builder.type = location.getClass().getName();
    builder.typeClass = location.getClass();
    builder.id = location.getId();
    builder.displayName = location.getDisplayName();
    builder.copyConfig(persistableConfig);
    builder.locationConfig.putAll(persistableFlags);

    Location parentLocation = location.getParent();
    builder.parent = (parentLocation != null) ? parentLocation.getId() : null;

    for (Location child : location.getChildren()) {
      builder.children.add(child.getId());
    }

    return builder;
  }
Ejemplo n.º 16
0
  protected boolean removeChild(Location child) {
    boolean removed;
    synchronized (children) {
      removed = children.remove(child);
    }
    if (removed) {
      if (child instanceof Closeable) {
        Streams.closeQuietly((Closeable) child);
      }
      child.setParent(null);

      if (isManaged()) {
        managementContext.getLocationManager().unmanage(child);
      }
    }
    return removed;
  }
  public void addChildLocation(Location child) {
    // Previously, setParentLocation delegated to addChildLocation and we sometimes ended up with
    // duplicate entries here. Instead this now uses a similar scheme to
    // AbstractEntity.setParent/addChild (with any weaknesses for distribution that such a
    // scheme might have...).
    //
    // We continue to use a list to allow identical-looking locations, but they must be different
    // instances.

    for (Location contender : childLocations) {
      if (contender == child) {
        // don't re-add; no-op
        return;
      }
    }

    childLocations.add(child);
    child.setParentLocation(this);
  }
 @Override
 public boolean forgetPortMappings(Location l) {
   List<PortMapping> result = Lists.newArrayList();
   synchronized (mutex) {
     for (Iterator<PortMapping> iter = mappings.values().iterator(); iter.hasNext(); ) {
       PortMapping m = iter.next();
       if (l.equals(m.target)) {
         iter.remove();
         result.add(m);
         emitAssociationDeletedEvent(associationMetadataFromPortMapping(m));
       }
     }
   }
   if (log.isDebugEnabled()) log.debug("cleared all port mappings for " + l + " - " + result);
   if (!result.isEmpty()) {
     onChanged();
   }
   return !result.isEmpty();
 }
  public static BasicEntityMemento.Builder newEntityMementoBuilder(Entity entity) {
    EntityDynamicType definedType = EntityTypes.getDefinedEntityType(entity.getClass());
    BasicEntityMemento.Builder builder = BasicEntityMemento.builder();

    builder.id = entity.getId();
    builder.displayName = entity.getDisplayName();
    builder.type = entity.getClass().getName();
    builder.typeClass = entity.getClass();

    // TODO the dynamic attributeKeys and configKeys are computed in the BasicEntityMemento
    // whereas effectors are computed here -- should be consistent!
    // (probably best to compute attrKeys and configKeys here)
    builder.effectors.addAll(entity.getEntityType().getEffectors());
    builder.effectors.removeAll(definedType.getEffectors().values());

    builder.isTopLevelApp = (entity instanceof Application && entity.getParent() == null);

    Map<ConfigKey<?>, Object> localConfig =
        ((EntityInternal) entity).getConfigMap().getLocalConfig();
    for (Map.Entry<ConfigKey<?>, Object> entry : localConfig.entrySet()) {
      ConfigKey<?> key = checkNotNull(entry.getKey(), localConfig);
      Object value = configValueToPersistable(entry.getValue());
      builder.config.put(key, value);
    }

    Map<String, Object> localConfigUnmatched =
        MutableMap.copyOf(
            ((EntityInternal) entity).getConfigMap().getLocalConfigBag().getAllConfig());
    for (ConfigKey<?> key : localConfig.keySet()) {
      localConfigUnmatched.remove(key.getName());
    }
    for (Map.Entry<String, Object> entry : localConfigUnmatched.entrySet()) {
      String key = checkNotNull(entry.getKey(), localConfig);
      Object value = entry.getValue();
      // TODO Not transforming; that code is deleted in another pending PR anyway!
      builder.configUnmatched.put(key, value);
    }

    @SuppressWarnings("rawtypes")
    Map<AttributeSensor, Object> allAttributes = ((EntityInternal) entity).getAllAttributes();
    for (@SuppressWarnings("rawtypes")
    Map.Entry<AttributeSensor, Object> entry : allAttributes.entrySet()) {
      AttributeSensor<?> key = checkNotNull(entry.getKey(), allAttributes);
      Object value = entry.getValue();
      builder.attributes.put((AttributeSensor<?>) key, value);
    }

    for (Location location : entity.getLocations()) {
      builder.locations.add(location.getId());
    }

    for (Entity child : entity.getChildren()) {
      builder.children.add(child.getId());
    }

    for (Policy policy : entity.getPolicies()) {
      builder.policies.add(policy.getId());
    }

    for (Enricher enricher : entity.getEnrichers()) {
      builder.enrichers.add(enricher.getId());
    }

    Entity parentEntity = entity.getParent();
    builder.parent = (parentEntity != null) ? parentEntity.getId() : null;

    if (entity instanceof Group) {
      for (Entity member : ((Group) entity).getMembers()) {
        builder.members.add(member.getId());
      }
    }

    return builder;
  }
 @Test
 public void testWithOldStyleColon() throws Exception {
   Location location = resolve("localhost:(name=myname)");
   assertTrue(location instanceof LocalhostMachineProvisioningLocation);
   assertEquals(location.getDisplayName(), "myname");
 }