org.apache.brooklyn.core.location.Locations Java Examples

The following examples show how to use org.apache.brooklyn.core.location.Locations. 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: MachineDetailsEc2LiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected void doTest(Location loc) throws Exception {
    Entity testEntity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class));
    app.start(ImmutableList.of(loc));
    EntityAsserts.assertAttributeEqualsEventually(MutableMap.of("timeout", TIMEOUT_MS),
            testEntity, Startable.SERVICE_UP, true);

    SshMachineLocation sshLoc = Locations.findUniqueSshMachineLocation(testEntity.getLocations()).get();
    MachineDetails machine = app.getExecutionContext()
            .submit(BasicMachineDetails.taskForSshMachineLocation(sshLoc))
            .getUnchecked();
    LOG.info("Found the following at {}: {}", loc, machine);
    assertNotNull(machine);
    OsDetails details = machine.getOsDetails();
    assertNotNull(details);
    assertNotNull(details.getArch());
    assertNotNull(details.getName());
    assertNotNull(details.getVersion());
    assertFalse(details.getArch().startsWith("architecture:"));
    assertFalse(details.getName().startsWith("name:"));
    assertFalse(details.getVersion().startsWith("version:"));
}
 
Example #2
Source File: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
private Effector<Void> newStartEffector() {
    return Effectors.effector(Startable.START)
            .impl(new EffectorBody<Void>() {
                @Override
                public Void call(ConfigBag parameters) {
                    LOG.info("Starting SeaCloudsInitializerPolicy " + "for " + entity.getId());
                    installSLA();
                    installMonitoringRules();
                    notifyRulesReady();
                    installInfluxDbObservers();
                    installGrafanaDashboards();

                    // Rewire the original behaviour
                    Collection<? extends Location> locations = null;
                    Object locationRaw = parameters.getStringKey(EffectorStartableImpl.StartParameters.LOCATIONS.getName());
                    locations = Locations.coerceToCollectionOfLocationsManaged(getManagementContext(), locationRaw);
                    ((StartableApplication) entity).start(locations);

                    return null;
                }
            })
            .build();
}
 
Example #3
Source File: RebindPolicyTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testExpungesOnEntityUnmanaged() throws Exception {
    Location loc = origManagementContext.getLocationRegistry().getLocationManaged("localhost");
    TestEntity entity = origApp.createAndManageChild(EntitySpec.create(TestEntity.class));
    MyPolicy policy = entity.policies().add(PolicySpec.create(MyPolicy.class));
    MyEnricher enricher = entity.enrichers().add(EnricherSpec.create(MyEnricher.class));

    RebindTestUtils.waitForPersisted(origApp);

    Entities.unmanage(entity);
    Locations.unmanage(loc);
    RebindTestUtils.stopPersistence(origApp);
    
    BrooklynMementoManifest manifest = loadMementoManifest();
    assertFalse(manifest.getEntityIdToManifest().containsKey(entity.getId()));
    assertFalse(manifest.getPolicyIdToType().containsKey(policy.getId()));
    assertFalse(manifest.getEnricherIdToType().containsKey(enricher.getId()));
    assertFalse(manifest.getLocationIdToType().containsKey(loc.getId()));
}
 
Example #4
Source File: SshCommandEffector.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public String callMany(Collection<Entity> targets, ConfigBag params) {
    TaskBuilder<Object> ptb = Tasks.builder().parallel(true).displayName("effector "+effector.getName()+" ssh to targets");
    for (Entity target: targets) {
        if (Entities.isNoLongerManaged(target)) continue;
        
        Lifecycle state = target.getAttribute(Attributes.SERVICE_STATE_ACTUAL);
        if (state==Lifecycle.STOPPING || state==Lifecycle.STOPPED) continue;

        Maybe<SshMachineLocation> machine = Locations.findUniqueSshMachineLocation(target.getLocations());
        if (machine.isAbsent()) continue;
        
        SshEffectorTaskFactory<String> t = makePartialTaskFactory(params, target);
        t.summary("effector "+effector.getName()+" at "+target); 
        t.machine( machine.get() );
        
        ptb.add(t.newTask());
    }
    queue(ptb.build()).getUnchecked();
    return null;
}
 
Example #5
Source File: StubHostLocation.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void release(StubContainerLocation machine) {
    DynamicCluster cluster = dockerHost.getDockerContainerCluster();
    StubContainer container = machine.getOwner();
    if (cluster.removeMember(container)) {
        LOG.info("Docker Host {}: member {} released", dockerHost, machine);
    } else {
        LOG.warn("Docker Host {}: member {} not found for release", dockerHost, machine);
    }

    // Now close and unmange the container
    try {
        container.stop();
        machine.close();
    } catch (Exception e) {
        LOG.warn("Error stopping container: " + container, e);
        Exceptions.propagateIfFatal(e);
    } finally {
        Entities.unmanage(container);
        Locations.unmanage(machine);
    }
}
 
Example #6
Source File: MachineDetailsGoogleComputeLiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected void doTest(Location loc) throws Exception {
    Entity testEntity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class));
    app.start(ImmutableList.of(loc));
    EntityAsserts.assertAttributeEqualsEventually(testEntity, Startable.SERVICE_UP, true);

    SshMachineLocation sshLoc = Locations.findUniqueSshMachineLocation(testEntity.getLocations()).get();
    MachineDetails machine = app.getExecutionContext()
            .submit(BasicMachineDetails.taskForSshMachineLocation(sshLoc))
            .getUnchecked();
    LOG.info("Found the following at {}: {}", loc, machine);
    assertNotNull(machine);
    OsDetails details = machine.getOsDetails();
    assertNotNull(details);
    assertNotNull(details.getArch());
    assertNotNull(details.getName());
    assertNotNull(details.getVersion());
    assertFalse(details.getArch().startsWith("architecture:"));
    assertFalse(details.getName().startsWith("name:"));
    assertFalse(details.getVersion().startsWith("version:"));
}
 
Example #7
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 #8
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 #9
Source File: MachineLifecycleEffectorTasks.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@link EffectorBody} which supplies the implementation for the start effector.
 * <p>
 * Calls {@link #start(Collection)} in this class.
 */
public EffectorBody<Void> newStartEffectorTask() {
    // TODO included anonymous inner class for backwards compatibility with persisted state.
    new EffectorBody<Void>() {
        @Override
        public Void call(ConfigBag parameters) {
            Collection<? extends Location> locations  = null;

            Object locationsRaw = parameters.getStringKey(LOCATIONS.getName());
            locations = Locations.coerceToCollectionOfLocationsManaged(entity().getManagementContext(), locationsRaw);

            if (locations==null) {
                // null/empty will mean to inherit from parent
                locations = Collections.emptyList();
            }

            start(locations);
            return null;
        }
    };
    return new StartEffectorBody();
}
 
Example #10
Source File: EmptySoftwareProcessYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testProvisioningProperties() throws Exception {
    Entity app = createAndStartApplication(
        "location:",
        "  localhost:",
        "    sshToolClass: "+RecordingSshTool.class.getName(),
        "    myLocConfig: myval",
        "services:",
        "- type: "+EmptySoftwareProcess.class.getName(),
        "  brooklyn.config:",
        "    provisioning.properties:",
        "      minRam: 16384");
    waitForApplicationTasks(app);

    log.info("App started:");
    Dumper.dumpInfo(app);
    
    EmptySoftwareProcess entity = (EmptySoftwareProcess) app.getChildren().iterator().next();
    Map<String, Object> pp = entity.getConfig(EmptySoftwareProcess.PROVISIONING_PROPERTIES);
    assertEquals(pp.get("minRam"), 16384);
    
    MachineLocation machine = Locations.findUniqueMachineLocation(entity.getLocations()).get();
    assertEquals(machine.config().get(ConfigKeys.newConfigKey(Object.class, "myLocConfig")), "myval");
    assertEquals(machine.config().get(ConfigKeys.newConfigKey(Object.class, "minRam")), 16384);
}
 
Example #11
Source File: PostgreSqlNodeChefImplFromScratch.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
protected void connectSensors() {
    sensors().set(DATASTORE_URL, String.format("postgresql://%s:%s/", getAttribute(HOSTNAME), getAttribute(POSTGRESQL_PORT)));

    Maybe<SshMachineLocation> machine = Locations.findUniqueSshMachineLocation(getLocations());

    if (machine.isPresent()) {
        feed = SshFeed.builder()
                .entity(this)
                .machine(machine.get())
                .poll(new SshPollConfig<Boolean>(SERVICE_UP)
                        .command("ps -ef | grep [p]ostgres")
                        .setOnSuccess(true)
                        .setOnFailureOrException(false))
                .build();
    } else {
        LOG.warn("Location(s) {} not an ssh-machine location, so not polling for status; setting serviceUp immediately", getLocations());
    }
}
 
Example #12
Source File: KafkaClusterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Collection<? extends Location> locations) {
    if (isLegacyConstruction()) {
        // TODO should no longer be needed?
        init();
    }

    locations = MutableList.copyOf(Locations.getLocationsCheckingAncestors(locations, this));

    Iterables.getOnlyElement(locations); // Assert just one
    // set it; here we don't allow changing locations
    addLocations(locations);

    List<Entity> childrenToStart = MutableList.<Entity>of(getCluster());
    // Set the KafkaZookeeper entity as child of cluster, if it does not already have a parent
    if (getZooKeeper().getParent() == null) {
        addChild(getZooKeeper());
    } // And only start zookeeper if we are parent
    if (Objects.equal(this, getZooKeeper().getParent())) childrenToStart.add(getZooKeeper());
    Entities.invokeEffector(this, childrenToStart, Startable.START, ImmutableMap.of("locations", locations)).getUnchecked();
}
 
Example #13
Source File: AnsibleEntityImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
protected void connectSensors() {
    super.connectSensors();

    Maybe<SshMachineLocation> machine = Locations.findUniqueSshMachineLocation(getLocations());

    if (machine.isPresent()) {
        String cmd = getDriver().getStatusCmd();
        feed = SshFeed.builder()
                .entity(this)
                .period(config().get(SERVICE_PROCESS_IS_RUNNING_POLL_PERIOD))
                .machine(machine.get())
                .poll(new SshPollConfig<Boolean>(SERVICE_UP)
                        .command(cmd)
                        .setOnSuccess(true)
                        .setOnFailureOrException(false))
                .build();
    } else {
        LOG.warn("Location(s) {} not an ssh-machine location, so not polling for status; setting serviceUp immediately", getLocations());
        sensors().set(SERVICE_UP, true);
    }
}
 
Example #14
Source File: StubHostImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteLocation() {
    StubHostLocation loc = (StubHostLocation) sensors().get(DYNAMIC_LOCATION);
    if (loc != null) {
        loc.deregister();
        Locations.unmanage(loc);
    }
    sensors().set(DYNAMIC_LOCATION, null);
    sensors().set(LOCATION_NAME, null);
}
 
Example #15
Source File: SshCommandEffectorIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    app = TestApplication.Factory.newManagedInstanceForTests();
    entity = app.createAndManageChild(EntitySpec.create(TestEntity.class).location(TestApplication.LOCALHOST_MACHINE_SPEC));
    machine = Locations.findUniqueSshMachineLocation(entity.getLocations()).get();
    app.start(ImmutableList.<Location>of());
}
 
Example #16
Source File: SshCommandSensorIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    app = TestApplication.Factory.newManagedInstanceForTests();
    entity = app.createAndManageChild(EntitySpec.create(TestEntity.class).location(TestApplication.LOCALHOST_MACHINE_SPEC));
    machine = Locations.findUniqueSshMachineLocation(entity.getLocations()).get();
    app.start(ImmutableList.<Location>of());
    tempFile = File.createTempFile("testSshCommand", ".txt");
}
 
Example #17
Source File: LocationPredicatesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testManaged() throws Exception {
    // TODO get exception in LocalhostMachineProvisioningLocation.removeChild because childLoc is "in use";
    // this happens from the call to unmanage(loc), which first unmanaged the children.
    loc.release(childLoc);
    
    assertTrue(LocationPredicates.managed().apply(loc));
    Locations.unmanage(loc);
    assertFalse(LocationPredicates.managed().apply(loc));
}
 
Example #18
Source File: DynamicClusterWithAvailabilityZonesRebindTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testRebindWithDefaultZoneFailureDetector() throws Exception {
    // Start and then unmanage a cluster (so it's detector was populated).
    // Do this in case the ZoneFailureDetector is shared!
    SimulatedLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SimulatedLocationWithZoneExtension.class)
            .configure(SimulatedLocationWithZoneExtension.ZONE_NAMES, ImmutableList.of("zone1", "zone2"))
            .configure(SimulatedLocationWithZoneExtension.ZONE_FAIL_CONDITIONS, ImmutableMap.of("zone1", Predicates.alwaysTrue())));

    DynamicCluster cluster = app().addChild(EntitySpec.create(DynamicCluster.class)
            .configure(DynamicCluster.ENABLE_AVAILABILITY_ZONES, true)
            .configure(DynamicCluster.INITIAL_SIZE, 2)
            .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
    
    cluster.start(ImmutableList.of(loc));
    
    Entities.unmanage(cluster);
    Locations.unmanage(loc);

    // Start a second cluster
    SimulatedLocation locUnrelated = mgmt().getLocationManager().createLocation(LocationSpec.create(SimulatedLocationWithZoneExtension.class)
            .configure(SimulatedLocationWithZoneExtension.ZONE_NAMES, ImmutableList.of("zone3", "zone4"))
            .configure(SimulatedLocationWithZoneExtension.ZONE_FAIL_CONDITIONS, ImmutableMap.of("zone3", Predicates.alwaysTrue())));
    
    DynamicCluster clusterUnrelated = app().addChild(EntitySpec.create(DynamicCluster.class)
            .configure(DynamicCluster.ENABLE_AVAILABILITY_ZONES, true)
            .configure(DynamicCluster.INITIAL_SIZE, 2)
            .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
    clusterUnrelated.start(ImmutableList.of(locUnrelated));
    
    rebind();
    
    // Confirm that cluster is usable
    DynamicCluster newClusterUnrelated = (DynamicCluster) mgmt().getEntityManager().getEntity(clusterUnrelated.getId());
    newClusterUnrelated.resize(4);
}
 
Example #19
Source File: MariaDbNodeImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
protected void connectSensors() {
    super.connectSensors();
    sensors().set(DATASTORE_URL, String.format("mysql://%s:%s/", getAttribute(HOSTNAME), getAttribute(MARIADB_PORT)));

    /*        
     * TODO status gives us things like:
     *   Uptime: 2427  Threads: 1  Questions: 581  Slow queries: 0  Opens: 53  Flush tables: 1  Open tables: 35  Queries per second avg: 0.239
     * So can extract lots of sensors from that.
     */
    Maybe<SshMachineLocation> machine = Locations.findUniqueSshMachineLocation(getLocations());

    if (machine.isPresent()) {
        String cmd = getDriver().getStatusCmd();
        feed = SshFeed.builder()
                .entity(this)
                .period(config().get(SERVICE_PROCESS_IS_RUNNING_POLL_PERIOD))
                .machine(machine.get())
                .poll(new SshPollConfig<Boolean>(SERVICE_UP)
                        .command(cmd)
                        .setOnSuccess(true)
                        .setOnFailureOrException(false))
                .poll(new SshPollConfig<Double>(QUERIES_PER_SECOND_FROM_MARIADB)
                        .command(cmd)
                        .onSuccess(new Function<SshPollValue, Double>() {
                            @Override
                            public Double apply(SshPollValue input) {
                                String q = Strings.getFirstWordAfter(input.getStdout(), "Queries per second avg:");
                                return (q == null) ? null : Double.parseDouble(q);
                            }})
                        .setOnFailureOrException(null) )
                .build();
    } else {
        LOG.warn("Location(s) {} not an ssh-machine location, so not polling for status; setting serviceUp immediately", getLocations());
        sensors().set(SERVICE_UP, true);
    }
}
 
Example #20
Source File: AbstractCommandFeed.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected MachineLocation getMachine() {
    Supplier<MachineLocation> supplier = config().get(MACHINE);
    if (supplier != null) {
        return supplier.get();
    } else {
        return Locations.findUniqueMachineLocation(entity.getLocations()).get();
    }
}
 
Example #21
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 #22
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 #23
Source File: ClockerDynamicLocationPatternTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testThroughLocationRegistry() throws Exception {
    StubInfrastructure infra = mgmt.getEntityManager().createEntity(EntitySpec.create(StubInfrastructure.class)
            .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, shouldSkipOnBoxBaseDirResolution()));
    infra.start(ImmutableList.of(loc));
    
    String infraLocSpec = infra.sensors().get(StubInfrastructure.LOCATION_SPEC);
    String infraLocName = infra.sensors().get(StubInfrastructure.LOCATION_NAME);
    StubInfrastructureLocation infraLoc = (StubInfrastructureLocation) mgmt.getLocationRegistry().getLocationManaged(infraLocSpec);
    StubInfrastructureLocation infraLoc2 = (StubInfrastructureLocation) mgmt.getLocationRegistry().getLocationManaged(infraLocName);
    assertSame(infraLoc, infraLoc2);
    assertHasLocation(mgmt.getLocationRegistry().getDefinedLocations().values(), infraLocName);


    MachineLocation machine = infraLoc.obtain(ImmutableMap.of());
    
    StubHost host = (StubHost) Iterables.getOnlyElement(infra.getStubHostCluster().getMembers());
    String hostLocSpec = host.sensors().get(StubHost.LOCATION_SPEC);
    String hostLocName = host.sensors().get(StubHost.LOCATION_NAME);
    StubHostLocation hostLoc = (StubHostLocation) mgmt.getLocationRegistry().getLocationManaged(hostLocSpec);
    StubHostLocation hostLoc2 = (StubHostLocation) mgmt.getLocationRegistry().getLocationManaged(hostLocName);
    assertSame(hostLoc, hostLoc2);
    assertHasLocation(mgmt.getLocationRegistry().getDefinedLocations().values(), hostLocName);

    StubContainer container = (StubContainer) Iterables.getOnlyElement(host.getDockerContainerCluster().getMembers());
    StubContainerLocation containerLoc = container.getDynamicLocation();
    assertEquals(containerLoc, machine);
    assertEquals(Iterables.getOnlyElement(hostLoc.getChildren()), machine);
    
    infraLoc.release(machine);
    assertFalse(Entities.isManaged(container));
    assertFalse(Locations.isManaged(containerLoc));
}
 
Example #24
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 #25
Source File: StubInfrastructureImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteLocation() {
    StubInfrastructureLocation location = getDynamicLocation();

    if (location != null) {
        location.deregister();
        Locations.unmanage(location);
    }

    sensors().set(LocationOwner.DYNAMIC_LOCATION, null);
    sensors().set(LocationOwner.LOCATION_NAME, null);
}
 
Example #26
Source File: SecurityGroupLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@BeforeMethod(alwaysRun=true)
@Override
public void setUp() throws Exception {
    // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
    brooklynProperties = BrooklynProperties.Factory.newDefault();
    brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-description-regex");
    brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-name-regex");
    brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-id");
    brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".inboundPorts");
    brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".hardware-id");

    // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty")
    brooklynProperties.remove("brooklyn.ssh.config.scriptHeader");

    mgmt = new LocalManagementContextForTests(brooklynProperties);

    super.setUp();

    Map<String,?> allFlags = MutableMap.<String,Object>builder()
        .put("tags", ImmutableList.of(getClass().getName()))
        .putAll(ImmutableMap.of("imageId", UBUNTU_12, "loginUser", "ubuntu", "hardwareId", "m1.small"))
        .build();
    loc = mgmt.getLocationRegistry().getLocationManaged(LOCATION_SPEC, allFlags);
    testEntity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class));
    app.start(ImmutableList.of(loc));
    EntityAsserts.assertAttributeEqualsEventually(MutableMap.of("timeout", TIMEOUT_MS),
        testEntity, Startable.SERVICE_UP, true);
    SshMachineLocation sshLoc = Locations.findUniqueSshMachineLocation(testEntity.getLocations()).get();
    jcloudsMachineLocation = (JcloudsMachineLocation)sshLoc;
    computeService = jcloudsMachineLocation.getParent().getComputeService();

}
 
Example #27
Source File: CleanOrphanedLocationsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandlesDanglingReference() throws Exception {
    SshMachineLocation todelete = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
    SshMachineLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
    origApp.addLocations(ImmutableList.of(todelete));
    origApp.sensors().set(Sensors.newSensor(Object.class, "mysensor"), loc);
    origApp.config().set(ConfigKeys.newConfigKey(Object.class, "myconfig"), loc);
    origApp.tags().addTag(loc);
    loc.config().set(ConfigKeys.newConfigKey(Object.class, "myconfig"), todelete);
    
    Locations.unmanage(todelete);
    assertFalse(getRawData().getLocations().containsKey(todelete.getId()));

    assertTransformIsNoop();
}
 
Example #28
Source File: CleanOrphanedLocationsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandlesDanglingReferencesInLocationListSurroundingValidReference() throws Exception {
    SshMachineLocation todelete = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
    SshMachineLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
    SshMachineLocation todelete2 = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
    origApp.addLocations(ImmutableList.of(todelete, loc, todelete2));
    Locations.unmanage(todelete);

    assertTransformIsNoop();
}
 
Example #29
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 #30
Source File: AbstractJcloudsStubbedLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected JcloudsLocation replaceJcloudsLocation(String locationSpec) {
    if (machines != null && machines.size() > 0) {
        throw new IllegalStateException("Cannot replace jcloudsLocation after provisioning machine with old one");
    }
    if (jcloudsLocation != null) {
        Locations.unmanage(jcloudsLocation);
    }
    jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().getLocationManaged(
            locationSpec,
            jcloudsLocationConfig(ImmutableMap.<Object, Object>of(
                    JcloudsLocationConfig.COMPUTE_SERVICE_REGISTRY, computeServiceRegistry,
                    JcloudsLocationConfig.WAIT_FOR_SSHABLE, "false",
                    JcloudsLocationConfig.POLL_FOR_FIRST_REACHABLE_ADDRESS, "false")));
    return jcloudsLocation;
}