Java Code Examples for org.apache.brooklyn.api.entity.Entity#getLocations()

The following examples show how to use org.apache.brooklyn.api.entity.Entity#getLocations() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DynamicRegionsFabricImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void removeRegion(String id) {
    Entity entity = getManagementContext().getEntityManager().getEntity(id);
    Preconditions.checkNotNull(entity, "No entity found for %s", id);
    Preconditions.checkArgument(this.equals(entity.getParent()), "Wrong parent (%s) for %s", entity.getParent(), entity);
    Collection<Location> childLocations = entity.getLocations();
    
    if (entity instanceof Startable) {
        try {
            Entities.invokeEffector(this, entity, Startable.STOP).get();
        } catch (Exception e) {
            Exceptions.propagateIfFatal(e);
            log.warn("Error stopping "+entity+" ("+e+"); proceeding to remove it anyway");
            log.debug("Error stopping "+entity+" ("+e+"); proceeding to remove it anyway", e);
        }
    }
    removeChild(entity);
    removeLocations(childLocations);
}
 
Example 2
Source File: DynamicFabricTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testExistingChildrenStartedRoundRobiningAcrossLocations() throws Exception {
    List<Location> locs = ImmutableList.of(loc1, loc2);
    
    DynamicFabric fabric = app.createAndManageChild(EntitySpec.create(DynamicFabric.class)
        .configure(DynamicFabric.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
    
    List<TestEntity> existingChildren = Lists.newArrayList();
    for (int i = 0; i < 4; i++) {
        existingChildren.add(fabric.addChild(EntitySpec.create(TestEntity.class)));
    }
    app.start(locs);

    // Expect only these existing children
    Asserts.assertEqualsIgnoringOrder(fabric.getChildren(), existingChildren);
    Asserts.assertEqualsIgnoringOrder(fabric.getMembers(), existingChildren);

    // Expect one location per existing child (round-robin)
    // Expect one location per existing child
    List<Location> remainingLocs = MutableList.<Location>builder().addAll(locs).addAll(locs).build();
    for (Entity existingChild : existingChildren) {
        Collection<Location> childLocs = existingChild.getLocations();
        assertEquals(childLocs.size(), 1, "childLocs="+childLocs);
        assertTrue(remainingLocs.remove(Iterables.get(childLocs, 0)), "childLocs="+childLocs+"; remainingLocs="+remainingLocs+"; allLocs="+locs);
    }
}
 
Example 3
Source File: DynamicFabricTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testExistingChildrenStarted() throws Exception {
    List<Location> locs = ImmutableList.of(loc1, loc2, loc3);
    
    DynamicFabric fabric = app.createAndManageChild(EntitySpec.create(DynamicFabric.class)
        .configure(DynamicFabric.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
    
    List<TestEntity> existingChildren = Lists.newArrayList();
    for (int i = 0; i < 3; i++) {
        existingChildren.add(fabric.addChild(EntitySpec.create(TestEntity.class)));
    }
    app.start(locs);

    // Expect only these existing children
    Asserts.assertEqualsIgnoringOrder(fabric.getChildren(), existingChildren);
    Asserts.assertEqualsIgnoringOrder(fabric.getMembers(), existingChildren);

    // Expect one location per existing child
    List<Location> remainingLocs = MutableList.copyOf(locs);
    for (Entity existingChild : existingChildren) {
        Collection<Location> childLocs = existingChild.getLocations();
        assertEquals(childLocs.size(), 1, "childLocs="+childLocs);
        assertTrue(remainingLocs.removeAll(childLocs));
    }
}
 
Example 4
Source File: DynamicFabricTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testExistingChildrenToppedUpWhenNewMembersIfMoreLocations() throws Exception {
    List<Location> locs = ImmutableList.of(loc1, loc2, loc3);
    
    DynamicFabric fabric = app.createAndManageChild(EntitySpec.create(DynamicFabric.class)
        .configure(DynamicFabric.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
    
    TestEntity existingChild = fabric.addChild(EntitySpec.create(TestEntity.class));
    
    app.start(locs);

    // Expect three children: the existing one, and one per other location
    assertEquals(fabric.getChildren().size(), 3, "children="+fabric.getChildren());
    assertTrue(fabric.getChildren().contains(existingChild), "children="+fabric.getChildren()+"; existingChild="+existingChild);
    Asserts.assertEqualsIgnoringOrder(fabric.getMembers(), fabric.getChildren());

    List<Location> remainingLocs = MutableList.<Location>builder().addAll(locs).build();
    for (Entity child : fabric.getChildren()) {
        Collection<Location> childLocs = child.getLocations();
        assertEquals(childLocs.size(), 1, "childLocs="+childLocs);
        assertTrue(remainingLocs.remove(Iterables.get(childLocs, 0)), "childLocs="+childLocs+"; remainingLocs="+remainingLocs+"; allLocs="+locs);
    }
}
 
Example 5
Source File: LocalEntityManager.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void unmanageOwnedLocations(Entity e) {
    for (Location loc : e.getLocations()) {
        NamedStringTag ownerEntityTag = BrooklynTags.findFirst(BrooklynTags.OWNER_ENTITY_ID, loc.tags().getTags());
        if (ownerEntityTag != null) {
            if (e.getId().equals(ownerEntityTag.getContents())) {
                managementContext.getLocationManager().unmanage(loc);
            } else {
                // A location is "owned" if it was created as part of the EntitySpec of an entity (by Brooklyn).
                // To share a location between entities create it yourself and pass it to any entities that needs it.
                log.debug("Unmanaging entity {}, which contains a location {} owned by another entity {}. " +
                        "Not automatically unmanaging the location (it will be unmanaged when its owning " +
                        "entity is unmanaged).",
                        new Object[] {e, loc, ownerEntityTag.getContents()});
            }
        }
    }
}
 
Example 6
Source File: EntityLocationUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void countLeafEntitiesByLocatedLocations(Entity target, Entity locatedParent, Map<Location, Integer> result) {
    if (isLocatedLocation(target))
        locatedParent = target;
    if (!target.getChildren().isEmpty()) {
        // non-leaf - inspect children
        for (Entity child: target.getChildren()) 
            countLeafEntitiesByLocatedLocations(child, locatedParent, result);
    } else {
        // leaf node - increment location count
        if (locatedParent!=null) {
            for (Location l: locatedParent.getLocations()) {
                Location ll = getMostGeneralLocatedLocation(l);
                if (ll!=null) {
                    Integer count = result.get(ll);
                    if (count==null) count = 1;
                    else count++;
                    result.put(ll, count);
                }
            }
        }
    }
}
 
Example 7
Source File: EntitiesYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testWith2EntityLocations() throws Exception {
    Entity app = createAndStartApplication(loadYaml("test-entity-basic-template.yaml",  
        "  locations:",
        "  - localhost:(name=localhost name)",
        "  - byon:(hosts=\"1.1.1.1\", name=byon name)"));
    waitForApplicationTasks(app);
    Assert.assertEquals(app.getLocations().size(), 0);
    Assert.assertEquals(app.getChildren().size(), 1);
    Entity entity = app.getChildren().iterator().next();
    Assert.assertEquals(entity.getLocations().size(), 2);
    Location localhostLocation = null, byonLocation = null; 
    for (Location location : entity.getLocations()) {
        if (location.getDisplayName().equals("localhost name"))
            localhostLocation = location;
        else if (location.getDisplayName().equals("byon name"))
            byonLocation = location;
    }
    Assert.assertNotNull(localhostLocation);
    Assert.assertNotNull(byonLocation);
}
 
Example 8
Source File: EntityResource.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public List<LocationSummary> getLocations(String application, String entity) {
    List<LocationSummary> result = Lists.newArrayList();
    Entity e = brooklyn().getEntity(application, entity);
    for (Location l : e.getLocations()) {
        result.add(LocationTransformer.newInstance(mgmt(), l, LocationDetailLevel.NONE, ui.getBaseUriBuilder()));
    }
    return result;
}
 
Example 9
Source File: DynamicClusterImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Multimap<Location, Entity> getMembersByLocation() {
    Multimap<Location, Entity> result = LinkedHashMultimap.create();
    for (Entity member : getMembers()) {
        Collection<Location> memberLocs = member.getLocations();
        Location memberLoc = Iterables.getFirst(memberLocs, null);
        if (memberLoc != null) {
            result.put(memberLoc, member);
        }
    }
    return result;
}
 
Example 10
Source File: ZabbixServerImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public void removed(Entity member) {
    synchronized (mutex) {
        for (Location location : member.getLocations()) {
            entityLocations.remove(location, member);
        }
    }
}
 
Example 11
Source File: FollowTheSunPolicy.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Location apply(Entity e) {
    Collection<Location> locs = e.getLocations();
    if (locs.isEmpty()) return null;
    Location contender = Iterables.get(locs, 0);
    while (contender.getParent() != null && !(contender instanceof MachineProvisioningLocation)) {
        contender = contender.getParent();
    }
    return contender;
}
 
Example 12
Source File: PeriodicDeltaChangeListener.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated since 1.0.0; its use is enabled via BrooklynFeatureEnablement.FEATURE_REFERENCED_OBJECTS_PERSISTENCE_PROPERTY,
 *             to preserve backwards compatibility for legacy implementations of entities, policies, etc.
 */
@Deprecated
private void addReferencedObjects(DeltaCollector deltaCollector) {
    MutableSet<BrooklynObject> referencedObjects = MutableSet.of();
    
    // collect references
    for (Entity entity : deltaCollector.entities) {
        // FIXME How to let the policy/location tell us about changes? Don't do this every time!
        for (Location location : entity.getLocations()) {
            Collection<Location> findLocationsInHierarchy = TreeUtils.findLocationsInHierarchy(location);
            referencedObjects.addAll(findLocationsInHierarchy);
        }
        if (persistPoliciesEnabled) {
            referencedObjects.addAll(entity.policies());
        }
        if (persistEnrichersEnabled) {
            referencedObjects.addAll(entity.enrichers());
        }
        if (persistFeedsEnabled) {
            referencedObjects.addAll(((EntityInternal)entity).feeds().getFeeds());
        }
    }
    
    for (BrooklynObject instance : referencedObjects) {
        deltaCollector.addIfNotRemoved(instance);
    }
}
 
Example 13
Source File: HostGeoInfo.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static HostGeoInfo fromEntity(Entity e) {
    for (Location l : e.getLocations()) {
        HostGeoInfo hgi = fromLocation(l);
        if (hgi != null)
            return hgi;
    }
    return null;
}
 
Example 14
Source File: Locations.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** if no locations are supplied, returns locations on the entity, or in the ancestors, until it finds a non-empty set,
 * or ultimately the empty set if no locations are anywhere */ 
public static Collection<? extends Location> getLocationsCheckingAncestors(Collection<? extends Location> locations, Entity entity) {
    // look in ancestors if location not set here
    Entity ancestor = entity;
    while ((locations==null || locations.isEmpty()) && ancestor!=null) {
        locations = ancestor.getLocations();
        ancestor = ancestor.getParent();
    }
    return locations;
}
 
Example 15
Source File: EffectorTasks.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** Finds a unique {@link MachineLocation} attached to the supplied entity
 * @throws IllegalStateException if there is not a unique such {@link SshMachineLocation} */
public static <T extends MachineLocation> T getMachine(Entity entity, Class<T> clazz) {
    try {
        return Machines.findUniqueMachineLocation(entity.getLocations(), clazz).get();
    } catch (Exception e) {
        throw new IllegalStateException("Entity "+entity+" (in "+Tasks.current()+") requires a single " + clazz.getName() + ", but has "+entity.getLocations(), e);
    }
}
 
Example 16
Source File: DslComponent.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Collection<Location> getLocations(Entity entity) {
    // TODO Arguably this should not look at ancestors. For example, in a `SoftwareProcess`
    // then after start() its location with be a `MachineLocation`. But before start has 
    // completed, we'll retrieve the `MachineProvisioningLocation` from its parent.
    
    Collection<? extends Location> locations = entity.getLocations();
    locations = Locations.getLocationsCheckingAncestors(locations, entity);
    return ImmutableList.copyOf(locations);
}
 
Example 17
Source File: EntityLocationUtils.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected boolean isLocatedLocation(Entity target) {
    for (Location l: target.getLocations())
        if (isLocatedLocation(l)) return true;
    return false;
}
 
Example 18
Source File: DynamicClusterImpl.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * <strong>Note</strong> for sub-classes; this method can be called while synchronized on {@link #mutex}.
 */
@Override
public String replaceMember(String memberId) {
    Entity member = getEntityManager().getEntity(memberId);
    LOG.info("In {}, replacing member {} ({})", new Object[] {this, memberId, member});

    if (member == null) {
        throw new NoSuchElementException("In "+this+", entity "+memberId+" cannot be resolved, so not replacing");
    }

    synchronized (mutex) {
        if (!getMembers().contains(member)) {
            throw new NoSuchElementException("In "+this+", entity "+member+" is not a member so not replacing");
        }

        Location memberLoc = null;
        if (isAvailabilityZoneEnabled()) {
            // this member's location could be a machine provisioned by a sub-location, or the actual sub-location
            List<Location> subLocations = findSubLocations(getLocation(true));
            Collection<Location> actualMemberLocs = member.getLocations();
            boolean foundMatch = false;
            for (Iterator<Location> iter = actualMemberLocs.iterator(); !foundMatch && iter.hasNext();) {
                Location actualMemberLoc = iter.next();
                Location contenderMemberLoc = actualMemberLoc;
                do {
                    if (subLocations.contains(contenderMemberLoc)) {
                        memberLoc = contenderMemberLoc;
                        foundMatch = true;
                        LOG.debug("In {} replacing member {} ({}), inferred its sub-location is {}", new Object[] {this, memberId, member, memberLoc});
                    }
                    contenderMemberLoc = contenderMemberLoc.getParent();
                } while (!foundMatch && contenderMemberLoc != null);
            }
            if (!foundMatch) {
                if (actualMemberLocs.isEmpty()) {
                    memberLoc = subLocations.get(0);
                    LOG.warn("In {} replacing member {} ({}), has no locations; falling back to first availability zone: {}", new Object[] {this, memberId, member, memberLoc});
                } else {
                    memberLoc = Iterables.tryFind(actualMemberLocs, Predicates.instanceOf(MachineProvisioningLocation.class)).or(Iterables.getFirst(actualMemberLocs, null));
                    LOG.warn("In {} replacing member {} ({}), could not find matching sub-location; falling back to its actual location: {}", new Object[] {this, memberId, member, memberLoc});
                }
            } else if (memberLoc == null) {
                // impossible to get here, based on logic above!
                throw new IllegalStateException("Unexpected condition! cluster="+this+"; member="+member+"; actualMemberLocs="+actualMemberLocs);
            }
        } else {
            // Replacing member, so new member should be in the same location as that being replaced.
            // Expect this to agree with `getMemberSpec().getLocations()` (if set). If not, then 
            // presumably there was a reason this specific member was started somewhere else!
            memberLoc = getLocation(false);
        }

        Entity replacement = replaceMember(member, memberLoc, ImmutableMap.of());
        return replacement.getId();
    }
}
 
Example 19
Source File: PortAttributeSensorAndConfigKey.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
protected Integer convertConfigToSensor(PortRange value, Entity entity) {
    if (value==null) return null;
    Collection<? extends Location> locations = entity.getLocations();
    if (!locations.isEmpty()) {
        Maybe<? extends Location> lo = Locations.findUniqueMachineLocation(locations);
        if (!lo.isPresent()) {
            // Try a unique location which isn't a machine provisioner
            Iterator<? extends Location> li = Iterables.filter(locations,
                    Predicates.not(Predicates.instanceOf(MachineProvisioningLocation.class))).iterator();
            if (li.hasNext()) lo = Maybe.of(li.next());
            if (li.hasNext()) lo = Maybe.absent();
        }
        // Fall back to selecting the single location
        if (!lo.isPresent() && locations.size() == 1) {
            lo = Maybe.of(locations.iterator().next());
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("Convert config to sensor for {} found locations: {}. Selected: {}", new Object[] {entity, locations, lo});
        }
        if (lo.isPresent()) {
            Location l = lo.get();
            Optional<Boolean> locationRunning = Optional.fromNullable(l.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING));
            Optional<Boolean> entityRunning = Optional.fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING));
            Optional<Boolean> locationInstalled = Optional.fromNullable(l.getConfig(BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION));
            Optional<Boolean> entityInstalled = Optional.fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION));
            Optional<Boolean> entityStarted = Optional.fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START));
            boolean skipCheck = locationRunning.or(entityRunning).or(locationInstalled).or(entityInstalled).or(entityStarted).or(false);
            if (l instanceof PortSupplier) {
                int p = ((PortSupplier) l).obtainPort(value);
                if (p != -1) {
                    LOG.debug("{}: choosing port {} for {}", new Object[] { entity, p, getName() });
                    return p;
                }
                // If we are not skipping install or already started, fail now
                if (!skipCheck) {
                    int rangeSize = Iterables.size(value);
                    if (rangeSize == 0) {
                        LOG.warn("{}: no port available for {} (empty range {})", new Object[] { entity, getName(), value });
                    } else if (rangeSize == 1) {
                        Integer pp = value.iterator().next();
                        if (pp > 1024) {
                            LOG.warn("{}: port {} not available for {}", new Object[] { entity, pp, getName() });
                        } else {
                            LOG.warn("{}: port {} not available for {} (root may be required?)", new Object[] { entity, pp, getName() });
                        }
                    } else {
                        LOG.warn("{}: no port available for {} (tried range {})", new Object[] { entity, getName(), value });
                    }
                    return null; // Definitively, no ports available
                }
            }
            // Ports may be available, we just can't tell from the location
            Integer v = (value.isEmpty() ? null : value.iterator().next());
            LOG.debug("{}: choosing port {} (unconfirmed) for {}", new Object[] { entity, v, getName() });
            return v;
        } else {
            LOG.warn("{}: ports not applicable, or not yet applicable, because has multiple locations {}; ignoring ", new Object[] { entity, locations, getName() });
        }
    } else {
        LOG.warn("{}: ports not applicable, or not yet applicable, because has no locations; ignoring {}", entity, getName());
    }
    return null;
}
 
Example 20
Source File: HighAvailabilityManagerInMemoryTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public void testLocationsStillManagedCorrectlyAfterDoublePromotion() throws NoMachinesAvailableException {
    HighAvailabilityManagerImpl ha = (HighAvailabilityManagerImpl) managementContext.getHighAvailabilityManager();
    ha.start(HighAvailabilityMode.MASTER);
    
    TestApplication app = TestApplication.Factory.newManagedInstanceForTests(managementContext);
    
    LocalhostMachineProvisioningLocation l = app.newLocalhostProvisioningLocation();
    l.config().set(TestEntity.CONF_NAME, "sample1");
    Assert.assertEquals(l.getConfig(TestEntity.CONF_NAME), "sample1");
    
    SshMachineLocation l2 = l.obtain();
    Assert.assertEquals(l2.getConfig(TestEntity.CONF_NAME), "sample1");
    Assert.assertNotNull(l2.getParent(), "Parent not set after dodgy promoteToMaster");
    Assert.assertEquals(l2.getParent().getConfig(TestEntity.CONF_NAME), "sample1");

    TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class).location(l).location(l2));
    log.info("Entities managed are: "+managementContext.getEntityManager().getEntities());
    Collection<Location> le = entity.getLocations();
    log.info("Locs at entity are: "+le);
    Collection<Location> lm = managementContext.getLocationManager().getLocations();
    log.info("Locs managed are: "+lm);
    log.info("            objs: "+identities(lm));
    Assert.assertNotNull(entity.getManagementContext());
    Assert.assertNotNull( ((EntityInternal)app.getChildren().iterator().next()).getManagementContext());
    Assert.assertTrue( ((EntityInternal)app.getChildren().iterator().next()).getManagementSupport().isDeployed());
    checkEntitiesHealthy(app, entity);
    
    managementContext.getRebindManager().forcePersistNow(true, null);
    log.info("Test deliberately doing unnecessary extra promoteToMaster");
    ha.promoteToMaster();
    
    log.info("Entities managed are: "+managementContext.getEntityManager().getEntities());
    Collection<Location> lle = entity.getLocations();
    log.info("Locs at entity(old) are: "+lle);
    log.info("                   objs: "+identities(lle));
    // check entities -- the initial-full promotion previously re-created items, 
    // and plugged them in as children, but only managed the roots
    checkEntitiesHealthy(app, entity);
    
    // assert what's in the location manager is accurate
    Collection<Location> llmm = managementContext.getLocationManager().getLocations();
    log.info("Locs managed are: "+llmm);
    log.info("            objs: "+identities(llmm));
    Assert.assertEquals(llmm, lm);
    SshMachineLocation ll2a = Iterables.getOnlyElement(Iterables.filter(llmm, SshMachineLocation.class));
    Assert.assertEquals(ll2a.getConfig(TestEntity.CONF_NAME), "sample1");
    Assert.assertNotNull(ll2a.getParent(), "Parent not set after dodgy promoteToMaster");
    Assert.assertEquals(ll2a.getParent().getConfig(TestEntity.CONF_NAME), "sample1");
    
    // and what's in the location manager is accurate
    Entity ee = (Entity)managementContext.lookup(entity.getId());
    Collection<Location> llee = ee.getLocations();
    log.info("Locs at entity(lookup) are: "+llee);
    log.info("                      objs: "+identities(llee));
    SshMachineLocation ll2b = Iterables.getOnlyElement(Iterables.filter(llee, SshMachineLocation.class));
    Assert.assertEquals(ll2b.getConfig(TestEntity.CONF_NAME), "sample1");
    Assert.assertNotNull(ll2b.getParent(), "Parent not set after dodgy promoteToMaster");
    Assert.assertEquals(ll2b.getParent().getConfig(TestEntity.CONF_NAME), "sample1");
}