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

The following examples show how to use org.apache.brooklyn.api.entity.Entity#getId() . 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: DynamicClusterImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * @throws StopFailedRuntimeException If stop failed, after successfully starting replacement
 */
protected Entity replaceMember(Entity member, @Nullable Location memberLoc, Map<?, ?> extraFlags) {
    synchronized (mutex) {
        ReferenceWithError<Optional<Entity>> added = addInSingleLocation(memberLoc, extraFlags);

        if (!added.getWithoutError().isPresent()) {
            String msg = String.format("In %s, failed to grow, to replace %s; not removing", this, member);
            if (added.hasError())
                throw new IllegalStateException(msg, added.getError());
            throw new IllegalStateException(msg);
        }

        try {
            stopAndRemoveNode(member);
        } catch (Exception e) {
            Exceptions.propagateIfFatal(e);
            throw new StopFailedRuntimeException("replaceMember failed to stop and remove old member "+member.getId(), e);
        }

        return added.getWithError().get();
    }
}
 
Example 2
Source File: PaasWebAppCloudFoundryDriver.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private void manageService(Entity rawEntity){

        CloudFoundryService cloudFoundryService;
        if (rawEntity instanceof CloudFoundryService){

            cloudFoundryService = (CloudFoundryService) rawEntity;
        
            String serviceName = cloudFoundryService
                    .getConfig(CloudFoundryService.SERVICE_INSTANCE_NAME);


            if (!Strings.isEmpty(serviceName)){

                Entities.waitForServiceUp(cloudFoundryService,
                        cloudFoundryService.getConfig(BrooklynConfigKeys.START_TIMEOUT));

                bindingServiceToEntity(serviceName);
                setCredentialsOnService(cloudFoundryService);
                cloudFoundryService.operation(getEntity());
            } else {
                log.error("Trying to get service instance name from {}, but getting null",
                        cloudFoundryService);
            }
        } else {
            log.error("The service entity {} is not available from the application {}",
                    new Object[]{rawEntity, getEntity()});

            throw new NoSuchElementException("No entity matching id " + rawEntity.getId() +
                    " in Management Context "+getEntity().getManagementContext()+
                    " during entity service binding "+getEntity().getId());
        }
    }
 
Example 3
Source File: DslComponent.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Task<Object> newTask() {
    boolean immediate = false;
    
    Callable<Object> job = new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            Entity targetEntity = component.get();
            
            int indexI = resolveIndex(immediate);
            
            // this is always run in a new dedicated task (possibly a fake task if immediate), so no need to clear
            String tag = "DSL:entity('"+targetEntity.getId()+"').location('"+indexI+"')";
            checkAndTagForRecursiveReference(targetEntity, tag);

            // TODO Try repeatedly if no location(s)?
            Collection<Location> locations = getLocations(targetEntity);
            if (locations.size() < (indexI + 1)) {
                throw new IndexOutOfBoundsException("Target entity ("+component+") has "+locations.size()+" location(s), but requested index "+index);
            }
            Location result = Iterables.get(locations, indexI);
            if (result == null) {
                throw new NullPointerException("Target entity ("+component+") has null location at index "+index);
            }
            return result;
        }
    };
    
    return Tasks.builder()
            .displayName("retrieving locations["+index+"] for "+component)
            .tag(BrooklynTaskTags.TRANSIENT_TASK_TAG)
            .dynamic(false)
            .body(job).build();
}
 
Example 4
Source File: DeployFailureTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void assertEntitiesNotKnown(Iterable<Entity> entities) {
    for (Entity entity : constructedEntities) {
        if (entity.getId() != null) {
            assertFalse(entityManager.isKnownEntityId(entity.getId()), "entity="+entity);
        }
    }
}
 
Example 5
Source File: LocalEntityManager.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Entity toRealEntity(Entity e) {
    checkNotNull(e, "entity");
    
    if (e instanceof AbstractEntity) {
        return e;
    } else {
        Entity result = toRealEntityOrNull(e.getId());
        if (result == null) {
            throw new IllegalStateException("No concrete entity known for entity "+e+" ("+e.getId()+", "+e.getEntityType().getName()+")");
        }
        return result;
    }
}
 
Example 6
Source File: DynamicRegionsFabricImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public String addRegion(String location) {
    Preconditions.checkNotNull(location, "location");
    Location l = getManagementContext().getLocationRegistry().getLocationManaged(location);
    addLocations(Arrays.asList(l));
    
    Entity e = addCluster(l);
    ((EntityInternal)e).addLocations(Arrays.asList(l));
    if (e instanceof Startable) {
        Task<?> task = e.invoke(Startable.START, ImmutableMap.of("locations", ImmutableList.of(l)));
        task.getUnchecked();
    }
    return e.getId();
}
 
Example 7
Source File: EntitiesYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testShellEnvFromYaml() throws Exception {
    String[] yaml = {
            "services:",
            "- type: " + VanillaSoftwareProcess.class.getName(),
            "  id: self",
            "  brooklyn.config:",
            "    map-config:",
            "      key1: val1",
            "      key2: $brooklyn:entity(\"self\")",
            "    list-config:",
            "    - 4.12",
            "    - true",
            "    - $brooklyn:entity(\"self\")",
            "    shell.env:",
            "      MAP_REF: $brooklyn:config(\"map-config\")",
            "      LIST_REF: $brooklyn:config(\"list-config\")",
            "      BEAN:",
            "        $brooklyn:object:",
            "          type: org.apache.brooklyn.entity.software.base.SoftwareProcessShellEnvironmentTest$SimpleBean",
            "          object.fields:",
            "            propString: bean-string",
            "            propInt: -1"
    };
    final EnvRecordingLocation recordingMachine = mgmt().getLocationManager().createLocation(LocationSpec.create(EnvRecordingLocation.class)
            .configure("address", "127.0.0.1"));
    Entity app = createAndStartApplication(joinLines(yaml), ImmutableMap.<String, Object>of("locations", ImmutableList.of(recordingMachine)));
    Entity entity = app.getChildren().iterator().next();
    waitForApplicationTasks(app);

    Map<String, ?> env = recordingMachine.getRecordedEnv().get(1);
    String entityRef = "{\"type\":\"org.apache.brooklyn.api.entity.Entity\",\"id\":\"" + entity.getId() + "\"}";
    assertEquals(env.get("MAP_REF"), "{\"key1\":\"val1\",\"key2\":" + entityRef + "}");
    assertEquals(env.get("LIST_REF"), "[4.12,true," + entityRef + "]");
    assertEquals(env.get("BEAN"), "{\"propString\":\"bean-string\",\"propInt\":-1}");
}
 
Example 8
Source File: ApplicationResource.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/** depth 0 means no detail even at root; negative means infinite; positive means include details for that many levels 
 * (ie 1 means this entity but no details of descendants) */
private EntitySummary fromEntity(Entity entity, boolean includeTags, int detailDepth, List<String> extraSensorGlobs, List<String> extraConfigGlobs) {
    if (detailDepth==0) {
        return new EntitySummary(
            entity.getId(), 
            entity.getDisplayName(),
            entity.getEntityType().getName(),
            entity.getCatalogItemId(),
            MutableMap.of("self", EntityTransformer.entityUri(entity, ui.getBaseUriBuilder())) );
    }

    Boolean serviceUp = entity.getAttribute(Attributes.SERVICE_UP);

    Lifecycle serviceState = entity.getAttribute(Attributes.SERVICE_STATE_ACTUAL);

    String iconUrl = RegisteredTypes.getIconUrl(entity);
    if (iconUrl!=null) {
        if (brooklyn().isUrlServerSideAndSafe(iconUrl))
            // route to server if it is a server-side url
            iconUrl = EntityTransformer.entityUri(entity, ui.getBaseUriBuilder())+"/icon";
    }

    List<EntitySummary> children = Lists.newArrayList();
    if (!entity.getChildren().isEmpty()) {
        for (Entity child : entity.getChildren()) {
            if (Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, child)) {
                children.add(fromEntity(child, includeTags, detailDepth-1, extraSensorGlobs, extraConfigGlobs));
            }
        }
    }

    String parentId = null;
    if (entity.getParent()!= null) {
        parentId = entity.getParent().getId();
    }

    List<String> groupIds = Lists.newArrayList();
    if (!entity.groups().isEmpty()) {
        groupIds.addAll(entitiesIdAsArray(entity.groups()));
    }

    List<Map<String, String>> members = Lists.newArrayList();
    if (entity instanceof Group) {
        // use attribute instead of method in case it is read-only
        Collection<Entity> memberEntities = entity.getAttribute(AbstractGroup.GROUP_MEMBERS);
        if (memberEntities != null && !memberEntities.isEmpty())
            members.addAll(entitiesIdAndNameAsList(memberEntities));
    }

    EntityDetail result = new EntityDetail(
            entity.getApplicationId(),
            entity.getId(),
            parentId,
            entity.getDisplayName(),
            entity.getEntityType().getName(),
            serviceUp,
            serviceState,
            iconUrl,
            entity.getCatalogItemId(),
            children,
            groupIds,
            members,
            MutableMap.of("self", EntityTransformer.entityUri(entity, ui.getBaseUriBuilder())) );
    
    if (includeTags) {
        result.setExtraField("tags", resolving(MutableList.copyOf(entity.tags().getTags())).preferJson(true).resolve() );
    }
    result.setExtraField("creationTimeUtc", entity.getCreationTime());
    addSensorsByGlobs(result, entity, extraSensorGlobs);
    addConfigByGlobs(result, entity, extraConfigGlobs);
    
    return result;
}
 
Example 9
Source File: HaMasterCheckFilterTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private String createApp(ManagementContext mgmt) {
    EntityManager entityMgr = mgmt.getEntityManager();
    Entity app = entityMgr.createEntity(EntitySpec.create(BasicApplication.class));
    return app.getId();
}
 
Example 10
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 11
Source File: EntityTransformer.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static EntitySummary entitySummary(Entity entity, UriBuilder ub) {
        URI applicationUri = serviceUriBuilder(ub, ApplicationApi.class, "get").build(entity.getApplicationId());
        URI entityUri = serviceUriBuilder(ub, EntityApi.class, "get").build(entity.getApplicationId(), entity.getId());
        ImmutableMap.Builder<String, URI> lb = ImmutableMap.<String, URI>builder()
                .put("self", entityUri);
        if (entity.getParent()!=null) {
            URI parentUri = serviceUriBuilder(ub, EntityApi.class, "get").build(entity.getApplicationId(), entity.getParent().getId());
            lb.put("parent", parentUri);
        }

//        UriBuilder urib = serviceUriBuilder(ub, EntityApi.class, "getChildren").build(entity.getApplicationId(), entity.getId());
        // TODO: change all these as well :S
        lb.put("application", applicationUri)
                .put("children", URI.create(entityUri + "/children"))
                .put("config", URI.create(entityUri + "/config"))
                .put("sensors", URI.create(entityUri + "/sensors"))
                .put("effectors", URI.create(entityUri + "/effectors"))
                .put("adjuncts", URI.create(entityUri + "/adjuncts"))
                .put("policies", URI.create(entityUri + "/policies"))
                .put("activities", URI.create(entityUri + "/activities"))
                .put("locations", URI.create(entityUri + "/locations"))
                .put("tags", URI.create(entityUri + "/tags"))
                .put("expunge", URI.create(entityUri + "/expunge"))
                .put("rename", URI.create(entityUri + "/name"))
                .put("spec", URI.create(entityUri + "/spec"))
            ;

        if (RegisteredTypes.getIconUrl(entity)!=null)
            lb.put("iconUrl", URI.create(entityUri + "/icon"));

        if (entity.getCatalogItemId() != null) {
            String versionedId = entity.getCatalogItemId();
            URI catalogUri;
            String symbolicName = CatalogUtils.getSymbolicNameFromVersionedId(versionedId);
            String version = CatalogUtils.getVersionFromVersionedId(versionedId);
            catalogUri = serviceUriBuilder(ub, CatalogApi.class, "getEntity").build(symbolicName, version);
            lb.put("catalog", catalogUri);
        }

        String type = entity.getEntityType().getName();
        return new EntitySummary(entity.getId(), entity.getDisplayName(), type, entity.getCatalogItemId(), lb.build());
    }
 
Example 12
Source File: StubUtils.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static final Predicate<Entity> sameInfrastructure(Entity entity) {
    Preconditions.checkNotNull(entity, "entity");
    return new SameInfrastructurePredicate(entity.getId());
}
 
Example 13
Source File: ServiceStateLogic.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private String nameOfEntity(Entity entity) {
    String name = entity.getDisplayName();
    if (name.contains(entity.getId())) return name;
    else return name + " ("+entity.getId()+")";
}
 
Example 14
Source File: EffectorUtils.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
EffectorCallPropagatedRuntimeException(Entity entity, Effector<?> effector, Throwable throwable) {
    super(makeMessage(entity, effector), throwable);
    this.entityId = entity.getId();
    this.effectorName = effector.getName();
}
 
Example 15
Source File: LocalUsageManager.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected void recordLocationEvent(final Location loc, final Entity caller, final Lifecycle state) {
    log.debug("Storing location lifecycle usage event: location {} in state {}; caller context {}", new Object[] {loc, state, caller});
    ConcurrentMap<String, LocationUsage> eventMap = managementContext.getStorage().<String, LocationUsage>getMap(LOCATION_USAGE_KEY);
    
    String entityTypeName = caller.getEntityType().getName();
    String appId = caller.getApplicationId();

    final LocationUsage.LocationEvent event = new LocationUsage.LocationEvent(state, caller.getId(), entityTypeName, appId, getUser());
    
    
    // Don't call out to alien-code (i.e. loc.toMetadataRecord()) while holding mutex. It might take a while,
    // e.g. ssh'ing to the machine!
    // If we don't have a usage record, then generate one outside of the mutex. But then double-check while
    // holding the mutex to see if another thread has created one. If it has, stick with that rather than 
    // overwriting it.
    LocationUsage usage;
    synchronized (mutex) {
        usage = eventMap.get(loc.getId());
    }
    if (usage == null) {
        usage = new LocationUsage(loc.getId(), ((LocationInternal)loc).toMetadataRecord());
    }
    
    synchronized (mutex) {
        LocationUsage otherUsage = eventMap.get(loc.getId());
        if (otherUsage != null) {
            usage = otherUsage;
        }
        usage.addEvent(event);
        eventMap.put(loc.getId(), usage);
        
        execOnListeners(new Function<UsageListener, Void>() {
                @Override
                public Void apply(UsageListener listener) {
                    listener.onLocationEvent(new LocationMetadataImpl(loc), event);
                    return null;
                }
                @Override
                public String toString() {
                    return "locationEvent("+loc+", "+state+")";
                }});
    }
}
 
Example 16
Source File: LocalEntityManager.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/**
 * Should ensure that the entity is now managed somewhere, and known about in all the lists.
 * Returns true if the entity has now become managed; false if it was already managed (anything else throws exception)
 */
private synchronized boolean manageNonRecursive(Entity e, ManagementTransitionMode mode) {
    Entity old = entitiesById.get(e.getId());
    
    if (old!=null && mode.wasNotLoaded()) {
        if (old == deproxyIfNecessary(e)) {
            log.warn("{} redundant call to start management of entity {}; ignoring", this, e);
        } else {
            throw new IdAlreadyExistsException("call to manage entity "+e+" ("+mode+") but "
                    + "different entity "+old+" already known under that id '"+e.getId()+"' at "+this);
        }
        return false;
    }

    BrooklynLogging.log(log, BrooklynLogging.levelDebugOrTraceIfReadOnly(e),
            "{} starting management of entity {}", this, e);
    Entity realE = toRealEntity(e);
    
    Entity oldProxy = entityProxiesById.get(e.getId());
    Entity proxyE;
    if (oldProxy!=null) {
        if (mode.wasNotLoaded()) {
            throw new IdAlreadyExistsException("call to manage entity "+e+" from unloaded "
                    + "state ("+mode+") but already had proxy "+oldProxy+" already known "
                    + "under that id '"+e.getId()+"' at "+this);
        }
        // make the old proxy point at this new delegate
        // (some other tricks done in the call below)
        ((EntityProxyImpl)(Proxy.getInvocationHandler(oldProxy))).resetDelegate(oldProxy, oldProxy, realE);
        proxyE = oldProxy;
    } else {
        proxyE = toProxyEntityIfAvailable(e);
    }
    entityProxiesById.put(e.getId(), proxyE);
    entityTypes.put(e.getId(), realE.getClass().getName());
    entitiesById.put(e.getId(), realE);
    
    preManagedEntitiesById.remove(e.getId());
    if ((e instanceof Application) && (e.getParent()==null)) {
        applications.add((Application)proxyE);
        applicationIds.add(e.getId());
    }
    if (!entities.contains(proxyE)) 
        entities.add(proxyE);
    
    if (old!=null && old!=e) {
        // passing the transition info will ensure the right shutdown steps invoked for old instance
        unmanage(old, mode, true);
    }
    
    return true;
}
 
Example 17
Source File: DynamicToyMySqlEntityBuilder.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static final String dir(Entity e) {
    return "/tmp/brooklyn-mysql-"+e.getId();
}
 
Example 18
Source File: BrooklynTaskTags.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static EffectorCallTag tagForEffectorCall(Entity entity, String effectorName, ConfigBag parameters) {
    return new EffectorCallTag(entity.getId(), effectorName, parameters);
}
 
Example 19
Source File: BrooklynNodeUpgradeEffectorBody.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private String dryRunUpdate(ConfigBag parameters) {
    // TODO require entity() node state master or hot standby AND require persistence enabled, or a new 'force_attempt_upgrade' parameter to be applied
    // TODO could have a 'skip_dry_run_upgrade' parameter
    // TODO could support 'dry_run_only' parameter, with optional resumption tasks (eg new dynamic effector)

    // 1 add new brooklyn version entity as child (so uses same machine), with same config apart from things in parameters
    final Entity dryRunChild = entity().addChild(createDryRunSpec()
        .displayName("Upgraded Version Dry-Run Node")
        // install dir and label are recomputed because they are not inherited, and download_url will normally be different
        .configure(parameters.getAllConfig()));

    //force this to start as hot-standby
    // TODO alternatively could use REST API as in BrooklynClusterUpgradeEffectorBody
    // TODO Want better way to append to the config (so can do it all in the spec)
    String launchParameters = dryRunChild.getConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS);
    if (Strings.isBlank(launchParameters)) launchParameters = "";
    else launchParameters += " ";
    launchParameters += "--highAvailability "+HighAvailabilityMode.HOT_STANDBY;
    ((EntityInternal)dryRunChild).config().set(BrooklynNode.EXTRA_LAUNCH_PARAMETERS, launchParameters);

    final String dryRunNodeUid = dryRunChild.getId();
    ((EntityInternal)dryRunChild).setDisplayName("Dry-Run Upgraded Brooklyn Node ("+dryRunNodeUid+")");

    DynamicTasks.queue(Effectors.invocation(dryRunChild, BrooklynNode.START, ConfigBag.EMPTY));

    // 2 confirm hot standby status
    DynamicTasks.queue(EntityTasks.requiringAttributeEventually(dryRunChild, BrooklynNode.MANAGEMENT_NODE_STATE, 
        Predicates.equalTo(ManagementNodeState.HOT_STANDBY), Duration.FIVE_MINUTES));

    // 3 stop new version
    DynamicTasks.queue(Tasks.builder().displayName("shutdown transient node")
        .add(Effectors.invocation(dryRunChild, BrooklynNode.STOP_NODE_BUT_LEAVE_APPS, ImmutableMap.of(StopSoftwareParameters.STOP_MACHINE_MODE, StopMode.NEVER)))
        .build());

    DynamicTasks.queue(Tasks.<Void>builder().displayName("remove transient node").body(
        new Runnable() {
            @Override
            public void run() {
                Entities.unmanage(dryRunChild);
            }
        }
    ).build());

    return dryRunChild.getId();
}