Java Code Examples for org.apache.brooklyn.core.location.Locations#getLocationsCheckingAncestors()

The following examples show how to use org.apache.brooklyn.core.location.Locations#getLocationsCheckingAncestors() . 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: MachineLifecycleEffectorTasks.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected Location getLocation(@Nullable Collection<? extends Location> locations) {
    if (locations==null || locations.isEmpty()) locations = entity().getLocations();
    if (locations.isEmpty()) {
        MachineProvisioningLocation<?> provisioner = entity().getAttribute(SoftwareProcess.PROVISIONING_LOCATION);
        if (provisioner!=null) locations = Arrays.<Location>asList(provisioner);
    }
    locations = Locations.getLocationsCheckingAncestors(locations, entity());

    Maybe<MachineLocation> ml = Locations.findUniqueMachineLocation(locations);
    if (ml.isPresent()) return ml.get();

    if (locations.isEmpty())
        throw new IllegalArgumentException("No locations specified when starting "+entity());
    if (locations.size() != 1 || Iterables.getOnlyElement(locations)==null)
        throw new IllegalArgumentException("Ambiguous locations detected when starting "+entity()+": "+locations);
    return Iterables.getOnlyElement(locations);
}
 
Example 2
Source File: SameServerEntityImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Starts the entity and its children in the given locations.
 * <p/>
 * Subclasses should override {@link #doStart} to customise behaviour.
 */
@Override
public final void start(Collection<? extends Location> locsO) {
    addLocations(locsO);
    final Collection<? extends Location> locations = Locations.getLocationsCheckingAncestors(locsO, this);
    
    checkNotNull(locations, "locations");
    if (DynamicTasks.getTaskQueuingContext() != null) {
        doStart(locations);
    } else {
        Task<?> task = Tasks.builder().displayName("start").body(new Runnable() {
            @Override public void run() { doStart(locations); }
        }).build();
        Entities.submit(this, task).getUnchecked();
    }
}
 
Example 3
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 4
Source File: MachineEntityImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Collection<? extends Location> getAllLocations() {
    Collection<? extends Location> locations = getLocations();
    if (locations.isEmpty()) {
        MachineProvisioningLocation<?> provisioner = sensors().get(SoftwareProcess.PROVISIONING_LOCATION);
        if (provisioner!=null) locations = Arrays.<Location>asList(provisioner);
    }
    return Locations.getLocationsCheckingAncestors(locations, this);
}
 
Example 5
Source File: BasicStartableImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Collection<? extends Location> locations) {
    try {
        ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);

        // Opportunity to block startup until other dependent components are available
        Object val = config().get(START_LATCH);
        if (val != null) log.debug("{} finished waiting for start-latch; continuing...", this);

        addLocations(locations);
        locations = Locations.getLocationsCheckingAncestors(locations, this);
        log.info("Starting entity "+this+" at "+locations);

        // essentially does StartableMethods.start(this, locations),
        // but optionally filters locations for each child

        Locations.LocationsFilter filter = getConfig(LOCATIONS_FILTER);
        Iterable<Entity> startables = filterStartableManagedEntities(getChildren());
        if (!Iterables.isEmpty(startables)) {
            List<Task<?>> tasks = Lists.newArrayListWithCapacity(Iterables.size(startables));
            for (final Entity entity : startables) {
                Collection<? extends Location> l2 = locations;
                if (filter != null) {
                    l2 = filter.filterForContext(new ArrayList<Location>(locations), entity);
                    log.debug("Child " + entity + " of " + this + " being started in filtered location list: " + l2);
                }
                tasks.add(Entities.invokeEffectorWithArgs(this, entity, Startable.START, l2));
            }
            for (Task<?> t : tasks) {
                t.getUnchecked();
            }
        }
        sensors().set(Attributes.SERVICE_UP, true);
    } finally {
        ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
    }
}
 
Example 6
Source File: DynamicClusterImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Location getLocation(boolean required) {
    Collection<? extends Location> ll = Locations.getLocationsCheckingAncestors(getLocations(), this);
    if (ll.isEmpty()) {
        if (!required) return null;
        throw new IllegalStateException("No location available for "+this);
    }
    if (ll.size()>1) {
        throw new IllegalStateException("Ambiguous location for "+this+"; expected one but had "+ll);
    }
    return Iterables.getOnlyElement(ll);
}
 
Example 7
Source File: ControlledDynamicWebAppClusterImpl.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Collection<? extends Location> locations) {
    ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);

    try {
        if (isLegacyConstruction()) {
            init();
        }

        locations = Locations.getLocationsCheckingAncestors(locations, this);
        // store inherited locations
        addLocations(locations);

        LoadBalancer loadBalancer = getController();
        loadBalancer.bind(MutableMap.of("serverPool", getControlledGroup()));

        List<Entity> childrenToStart = MutableList.<Entity>of(getCluster());
        // Set controller as child of cluster, if it does not already have a parent
        if (getController().getParent() == null) {
            addChild(getController());
        }

        // And only start controller if we are parent. Favour locations defined on controller, if present
        Task<List<Void>> startControllerTask = null;
        if (this.equals(getController().getParent())) {
            if (getController().getLocations().size() == 0) {
                childrenToStart.add(getController());
            } else {
                 startControllerTask = Entities.invokeEffectorList(this, MutableList.<Entity>of(getController()), Startable.START, ImmutableMap.of("locations", getController().getLocations()));
            }
        }

        // don't propagate start locations
        Entities.invokeEffectorList(this, childrenToStart, Startable.START, ImmutableMap.of("locations", MutableList.of())).get();
        if (startControllerTask != null) {
            startControllerTask.get();
        }

        // wait for everything to start, then update controller, to ensure it is up to date
        // (will happen asynchronously as members come online, but we want to force it to happen)
        getController().update();

        ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
    } catch (Exception e) {
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
        throw Exceptions.propagate(e);
    } finally {
        connectSensors();
    }
}
 
Example 8
Source File: SshCommandMembershipTrackingPolicy.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void execute(Entity target, String command, String type, String memberId, boolean highlight) {
    if (Entities.isNoLongerManaged(target)) return;
    Lifecycle state = target.getAttribute(Attributes.SERVICE_STATE_ACTUAL);
    if (state==Lifecycle.STOPPING || state==Lifecycle.STOPPED) return;
    
    Collection<? extends Location> locations = Locations.getLocationsCheckingAncestors(target.getLocations(), target);
    Maybe<SshMachineLocation> machine = Machines.findUniqueMachineLocation(locations, SshMachineLocation.class);
    if (machine.isAbsentOrNull()) {
        LOG.debug("No machine available to execute command");
        return;
    }

    LOG.info("Executing command on {}: {}", machine.get(), command);
    String executionDir = config().get(EXECUTION_DIR);
    String sshCommand = SshCommandSensor.makeCommandExecutingInDirectory(command, executionDir, target);

    // Set things from the entities defined shell environment, overriding with our config
    Map<String, Object> env = MutableMap.of();
    env.putAll(MutableMap.copyOf(entity.config().get(BrooklynConfigKeys.SHELL_ENVIRONMENT)));
    env.putAll(MutableMap.copyOf(config().get(BrooklynConfigKeys.SHELL_ENVIRONMENT)));

    // Add variables describing this invocation
    env.put(EVENT_TYPE, type);
    env.put(MEMBER_ID, memberId);

    // Try to resolve the configuration in the env Map
    try {
        env = (Map<String, Object>) Tasks.resolveDeepValue(env, Object.class, getExecutionContext());
    } catch (InterruptedException | ExecutionException e) {
        throw Exceptions.propagate(e);
    }

    // Execute the command with the serialized environment strings
    ShellEnvironmentSerializer serializer = new ShellEnvironmentSerializer(getManagementContext());
    SshEffectorTasks.SshEffectorTaskFactory<String> task = SshEffectorTasks.ssh(sshCommand)
            .machine(machine.get())
            .requiringZeroAndReturningStdout()
            .summary("group-" + CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, type))
            .environmentVariables(serializer.serialize(env));

    Task<String> taskI = DynamicTasks.submit(task.newTask(), target);
    if (highlight) {
        highlightAction("Run at "+machine.get().getAddress().getHostAddress(), taskI);
    }
    String output = taskI.getUnchecked();
    LOG.trace("Command returned: {}", output);
}