org.apache.brooklyn.core.entity.Entities Java Examples

The following examples show how to use org.apache.brooklyn.core.entity.Entities. 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: ChildEntityCustomizer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void customize(JcloudsLocation location, ComputeService computeService, JcloudsMachineLocation machine) {
    EntitySpec<?> spec = config().get(CHILD_ENTITY_SPEC);
    Boolean create = config().get(CREATE_CHILD_ENTITY);
    Duration timeout = config().get(BrooklynConfigKeys.START_TIMEOUT);
    Entity parent = getCallerContext(machine);

    if (Boolean.TRUE.equals(create) && spec != null) {
        LOG.info("Creating child entity for {} in {}", parent, machine);
        Entity child = getBrooklynManagementContext().getEntityManager().createEntity(spec);
        child.setParent(parent);
        Task<Void> start = Entities.invokeEffectorWithArgs(parent, child, Startable.START, ImmutableList.of(machine));
        if (!start.blockUntilEnded(timeout)) {
            throw new IllegalStateException(String.format("Timed out while starting child entity for %s", parent));
        }
    }
}
 
Example #2
Source File: CliTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testStopAllApplications() throws Exception {
    LaunchCommand launchCommand = new Main.LaunchCommand();
    ManagementContext mgmt = LocalManagementContextForTests.newInstance();
    
    try {
        StartableApplication app = mgmt.getEntityManager().createEntity(EntitySpec.create(StartableApplication.class).impl(ExampleApp.class));
        ExampleApp appImpl = (ExampleApp) Entities.deproxy(app);
        SimulatedLocation loc = mgmt.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class));
        app.start(ImmutableList.of(loc));
        assertTrue(appImpl.running);
        
        launchCommand.stopAllApps(ImmutableList.of(app));
        assertFalse(appImpl.running);
    } finally {
        // Stopping the app will make app.getManagementContext return the "NonDeploymentManagementContext";
        if (mgmt != null) Entities.destroyAll(mgmt);
    }
}
 
Example #3
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 #4
Source File: CustomAggregatingEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAggregatesChildrenOfProducer() {
    TestEntity p1 = entity.createAndManageChild(EntitySpec.create(TestEntity.class));
    TestEntity p2 = entity.createAndManageChild(EntitySpec.create(TestEntity.class));
    p1.sensors().set(intSensor, 1);
    
    app.enrichers().add(Enrichers.builder()
            .aggregating(intSensor)
            .publishing(target)
            .computingSum()
            .from(entity)
            .fromChildren()
            .build());

    EntityAsserts.assertAttributeEqualsEventually(app, target, 1);

    p2.sensors().set(intSensor, 2);
    EntityAsserts.assertAttributeEqualsEventually(app, target, 3);
    
    Entities.unmanage(p2);
    EntityAsserts.assertAttributeEqualsEventually(app, target, 1);
}
 
Example #5
Source File: NodeJsWebAppFixtureIntegrationTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Integration","Broken"})
public void testInitialNamedDeployments() {
    final String urlSubPathToWebApp = APP_NAME;
    final String urlSubPathToPageToQuery = "";
    LOG.info("test=testInitialNamedDeployments; entity="+entity+"; app="+entity.getApplication());
    
    Entities.start(entity.getApplication(), ImmutableList.of(loc));

    Asserts.succeedsEventually(MutableMap.of("timeout", Duration.minutes(1)), new Runnable() {
        @Override
        public void run() {
            // TODO get this URL from a web-app entity of some kind?
            String url = Urls.mergePaths(entity.getAttribute(WebAppService.ROOT_URL), urlSubPathToWebApp, urlSubPathToPageToQuery);
            HttpTestUtils.assertHttpStatusCodeEquals(url, 200);
        }});
}
 
Example #6
Source File: KarafContainerTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Integration", "WIP"})
public void canStartupAndShutdown() throws Exception {
    karaf = app.createAndManageChild(EntitySpec.create(KarafContainer.class)
            .configure("name", Identifiers.makeRandomId(8))
            .configure("displayName", "Karaf Test"));
    
    app.start(ImmutableList.of(localhost));
    EntityAsserts.assertAttributeEqualsEventually(karaf, Attributes.SERVICE_UP, true);
    
    Entities.dumpInfo(karaf);
    final int pid = karaf.getAttribute(KarafContainer.KARAF_PID);
    Entities.submit(app, SshEffectorTasks.requirePidRunning(pid).machine(localhost.obtain())).get();
    
    karaf.stop();
    EntityAsserts.assertAttributeEqualsEventually(karaf, Attributes.SERVICE_UP, false);
    
    Asserts.succeedsEventually(new Runnable() {
        @Override
        public void run() {
            try {
                Assert.assertFalse(Entities.submit(app, SshEffectorTasks.isPidRunning(pid).machine(localhost.obtain())).get());
            } catch (NoMachinesAvailableException e) {
                throw Exceptions.propagate(e);
            }
        }});
}
 
Example #7
Source File: KubernetesLocationYamlLiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Live"})
public void testLoginPasswordOverride() throws Exception {
    String customPassword = "myDifferentPassword";

    String yaml = Joiner.on("\n").join(
            locationYaml,
            "services:",
            "  - type: " + EmptySoftwareProcess.class.getName(),
            "    brooklyn.config:",
            "      provisioning.properties:",
            "        " + KubernetesLocationConfig.LOGIN_USER_PASSWORD.getName() + ": " + customPassword);

    Entity app = createStartWaitAndLogApplication(yaml);
    EmptySoftwareProcess entity = Iterables.getOnlyElement(Entities.descendantsAndSelf(app, EmptySoftwareProcess.class));

    SshMachineLocation machine = Machines.findUniqueMachineLocation(entity.getLocations(), SshMachineLocation.class).get();
    assertEquals(machine.config().get(SshMachineLocation.PASSWORD), customPassword);
    assertTrue(machine.isSshable());
}
 
Example #8
Source File: UpdatingMap.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Called whenever the values for the set of producers changes (e.g. on an event, or on a member added/removed).
 */
@SuppressWarnings("unchecked")
protected void onUpdated() {
    try {
        Object v = computing.apply(producer.getAttribute(sourceSensor));
        if (v == null && Boolean.TRUE.equals(removingIfResultIsNull)) {
            v = Entities.REMOVE;
        }
        if (v == Entities.UNCHANGED) {
            // nothing
        } else {
            TKey key = this.key;
            if (key==null) key = (TKey) sourceSensor.getName();

            ServiceStateLogic.updateMapSensorEntry(entity, targetSensor, key, (TVal) v);
        }
    } catch (Throwable t) {
        LOG.warn("Error calculating map update for enricher "+this, t);
        throw Exceptions.propagate(t);
    }
}
 
Example #9
Source File: DynamicClusterTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testWaitForServiceUpDefaultsToNotChecking() throws Exception {
    DynamicCluster cluster = app.addChild(EntitySpec.create(DynamicCluster.class)
            .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
            .configure("initialSize", 1));

    // Indicate that the cluster is not healthy 
    ServiceStateLogic.updateMapSensorEntry(cluster, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, "simulateNotUpKey", "myVal");

    // Start - expect it to complete promptly
    Stopwatch stopwatch = Stopwatch.createStarted();
    app.start(ImmutableList.of());
    Duration startTime = Duration.of(stopwatch);
    LOG.info("start-time "+startTime);
    assertTrue(startTime.isShorterThan(Asserts.DEFAULT_LONG_TIMEOUT), "startTime="+startTime);

    // Should be on-fire
    EntityAsserts.assertAttributeEqualsEventually(cluster, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
    EntityAsserts.assertAttributeEqualsEventually(cluster, Attributes.SERVICE_UP, false);

    // Clearing the notUp indicator should allow it to recover
    ServiceStateLogic.updateMapSensorEntry(cluster, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, "simulateNotUpKey", Entities.REMOVE);
    EntityAsserts.assertAttributeEqualsEventually(cluster, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
    EntityAsserts.assertAttributeEqualsEventually(cluster, Attributes.SERVICE_UP, true);
}
 
Example #10
Source File: CustomAggregatingEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAggregatesExistingChildren() {
    TestEntity p1 = entity.createAndManageChild(EntitySpec.create(TestEntity.class));
    TestEntity p2 = entity.createAndManageChild(EntitySpec.create(TestEntity.class));
    p1.sensors().set(intSensor, 1);
    
    entity.enrichers().add(Enrichers.builder()
            .aggregating(intSensor)
            .publishing(target)
            .computingSum()
            .fromChildren()
            .build());


    EntityAsserts.assertAttributeEqualsEventually(entity, target, 1);

    p2.sensors().set(intSensor, 2);
    EntityAsserts.assertAttributeEqualsEventually(entity, target, 3);
    
    Entities.unmanage(p2);
    EntityAsserts.assertAttributeEqualsEventually(entity, target, 1);
}
 
Example #11
Source File: JcloudsRebindStubTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
@AfterMethod(alwaysRun=true)
public void tearDown() throws Exception {
    List<Exception> exceptions = Lists.newArrayList();
    for (ManagementContext mgmt : mgmts) {
        try {
            if (mgmt.isRunning()) Entities.destroyAll(mgmt);
        } catch (Exception e) {
            LOG.warn("Error destroying management context", e);
            exceptions.add(e);
        }
    }
    mgmts.clear();
    origManagementContext = null;
    newManagementContext = null;
    origApp = null;
    newApp = null;
    
    super.tearDown();
    
    if (exceptions.size() > 0) {
        throw new CompoundRuntimeException("Error in tearDown of "+getClass(), exceptions);
    }
}
 
Example #12
Source File: BasicExecutionManager.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected boolean deleteTaskNonRecursive(Task<?> task) {
    Set<?> tags = TaskTags.getTagsFast(checkNotNull(task, "task"));
    for (Object tag : tags) {
        synchronized (tasksByTag) {
            Set<Task<?>> tasks = tasksWithTagLiveOrNull(tag);
            if (tasks != null) {
                tasks.remove(task);
                if (tasks.isEmpty()) {
                    tasksByTag.remove(tag);
                }
            }
        }
    }
    Task<?> removed = tasksById.remove(task.getId());
    incompleteTaskIds.remove(task.getId());
    if (removed!=null && removed.isSubmitted() && !removed.isDone(true)) {
        Entity context = BrooklynTaskTags.getContextEntity(removed);
        if (context!=null && !Entities.isManaged(context)) {
            log.debug("Forgetting about active task on unmanagement of "+context+": "+removed);
        } else {
            log.warn("Deleting submitted task before completion: "+removed+"; this task will continue to run in the background outwith "+this+", but perhaps it should have been cancelled?");
        }
    }
    return removed != null;
}
 
Example #13
Source File: ActivePartialRebindTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testRebindParentSimple() throws Exception {
    TestEntity c1 = origApp.addChild(EntitySpec.create(TestEntity.class));
    
    AbstractEntity origAppr = Entities.deproxy(origApp);
    
    doPartialRebindOfIds(origApp.getId());
    
    BrooklynObject app2 = origManagementContext.lookup(origApp.getId());
    AbstractEntity app2r = Entities.deproxy((Entity)app2);
    
    Assert.assertTrue(app2 == origApp, "Proxy instance should be the same: "+app2+" / "+origApp);
    Assert.assertFalse(app2r == origAppr, "Real instance should NOT be the same: "+app2r+" / "+origAppr);
    
    Assert.assertTrue(c1.getManagementSupport().isDeployed());
    
    // check that child of parent is not a new unmanaged entity
    Entity c1b = origApp.getChildren().iterator().next();
    Assert.assertTrue(c1.getManagementSupport().isDeployed());
    Assert.assertTrue( ((EntityInternal)c1b).getManagementSupport().isDeployed(), "Not deployed: "+c1b );
}
 
Example #14
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 #15
Source File: WinRmMachineLocationLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@AfterClass(alwaysRun=true)
public void tearDownClass() throws Exception {
    try {
        if (executor != null) executor.shutdownNow();
        if (machine != null) loc.release(machine);
        if (mgmt != null) Entities.destroyAll(mgmt);
    } catch (Throwable t) {
        LOG.error("Caught exception in tearDown method", t);
    } finally {
        executor = null;
        mgmt = null;
    }
}
 
Example #16
Source File: SameServerEntityImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Stops the entity and its children.
 * <p/>
 * Subclasses should override {@link #doStop} to customise behaviour.
 */
@Override
public final void stop() {
    if (DynamicTasks.getTaskQueuingContext() != null) {
        doStop();
    } else {
        Task<?> task = Tasks.builder().displayName("stop").body(new Runnable() {
            @Override public void run() { doStop(); }
        }).build();
        Entities.submit(this, task).getUnchecked();
    }
}
 
Example #17
Source File: EnrichersYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithEntityEnricherAndParameters() throws Exception {
    Entity app = createAndStartApplication(loadYaml("test-entity-basic-template.yaml",
                "  id: parentId",
                "  brooklyn.parameters:",
                "    - name: test.fqdn",
                "      type: string",
                "      default: \"www.example.org\"",
                "  brooklyn.enrichers:",
                "    - enricherType: org.apache.brooklyn.enricher.stock.Transformer",
                "      brooklyn.config:",
                "        enricher.triggerSensors:",
                "          - $brooklyn:sensor(\"test.sequence\")",
                "        enricher.targetSensor: $brooklyn:sensor(\"main.uri\")",
                "        enricher.targetValue:",
                "          $brooklyn:formatString:",
                "            - \"http://%s:%d/\"",
                "            - $brooklyn:config(\"test.fqdn\")",
                "            - $brooklyn:attributeWhenReady(\"test.sequence\")"));
    waitForApplicationTasks(app);
    
    log.info("App started:");
    final Entity parentEntity = app.getChildren().iterator().next();
    Dumper.dumpInfo(app);
    Assert.assertTrue(parentEntity instanceof TestEntity, "Expected parent entity to be TestEntity, found:" + parentEntity);
    parentEntity.sensors().set(TestEntity.SEQUENCE, 1234);
    Asserts.eventually(Entities.attributeSupplier(parentEntity, Sensors.newStringSensor("main.uri")), Predicates.<String>equalTo("http://www.example.org:1234/"));
}
 
Example #18
Source File: QuarantineGroupTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpungeMembersWithStop() throws Exception {
    group.addMember(e1);
    group.addMember(e2);
    group.expungeMembers(true);
    
    assertFalse(Entities.isManaged(e1));
    assertFalse(Entities.isManaged(e2));
    assertEquals(e1.getCallHistory(), ImmutableList.of("stop"));
    assertEquals(e2.getCallHistory(), ImmutableList.of("stop"));
}
 
Example #19
Source File: AbstractCloudFoundryPaasLocationLiveTest.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
@AfterMethod
public void tearDown() throws Exception {
    if (app != null) {
        Entities.destroyAllCatching(app.getManagementContext());
    }
    if (managementContext != null){
        Entities.destroyAll(managementContext);
    }
}
 
Example #20
Source File: DynamicClusterImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void stopAndRemoveNode(Entity member) {
    removeMember(member);
    try {
        if (member instanceof Startable) {
            Task<?> task = newThrottledEffectorTask(member, Startable.STOP, Collections.<String, Object>emptyMap());
            DynamicTasks.get(task);
        }
    } finally {
        Entities.unmanage(member);
    }
}
 
Example #21
Source File: GeoDnsServiceYamlTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Test
public void testTargetGroupCanBeSetInYaml() throws Exception {
    final String resourceName = "classpath:/" + getClass().getPackage().getName().replace('.', '/') + "/geodns.yaml";
    final String blueprint = loadYaml(resourceName);
    Application app = EntityManagementUtils.createUnstarted(mgmt(), blueprint);
    GeoscalingDnsService geodns = Iterables.getOnlyElement(Entities.descendantsAndSelf(app, GeoscalingDnsService.class));
    DynamicFabric fabric = Iterables.getOnlyElement(Entities.descendantsAndSelf(app, DynamicFabric.class));
    assertEquals(geodns.config().get(AbstractGeoDnsService.ENTITY_PROVIDER), fabric);
}
 
Example #22
Source File: EffectorTaskTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Void call(ConfigBag parameters) {
    Entity child = Iterables.getOnlyElement(entity().getChildren());
    AtomicBoolean lock = new AtomicBoolean();
    Task<Void> dummyTask = null;

    try {
        // Queue a (DST secondary) task which waits until notified, so that tasks queued later will get blocked
        queue(Effectors.invocation(entity(), STALL, ImmutableMap.of("lock", lock)));
    
        // Start a new task - submitted directly to child's ExecutionContext, as well as added as a
        // DST secondary of the current effector.
        dummyTask = child.invoke(DUMMY, ImmutableMap.<String, Object>of());
        dummyTask.getUnchecked();

        // Execution completed in the child's ExecutionContext, but still queued as a secondary.
        // Destroy the child entity so that no subsequent tasks can be executed in its context.
        Entities.destroy(child);
    } finally {
        // Let STALL complete
        synchronized(lock) {
            lock.set(true);
            lock.notifyAll();
        }
        // At this point DUMMY will be unblocked and the DST will try to execute it as a secondary.
        // Submission will be ignored because DUMMY already executed.
        // If it's not ignored then submission will fail because entity is already unmanaged.
    }
    return null;
}
 
Example #23
Source File: AbstractWebAppFixtureIntegrationTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
/**
 * Checks an entity can start, set SERVICE_UP to true and shutdown again.
 */
@Test(groups = "Integration", dataProvider = "basicEntities")
public void canStartAndStop(final SoftwareProcess entity) {
    this.entity = entity;
    log.info("test=canStartAndStop; entity="+entity+"; app="+entity.getApplication());
    
    Entities.start(entity.getApplication(), ImmutableList.of(loc));
    EntityAsserts.assertAttributeEqualsEventually(
            MutableMap.of("timeout", 120*1000), entity, Startable.SERVICE_UP, Boolean.TRUE);
    entity.stop();
    assertFalse(entity.getAttribute(Startable.SERVICE_UP));
}
 
Example #24
Source File: XmlMementoSerializerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testFieldReffingEntity() throws Exception {
    final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
    ReffingEntity reffer = new ReffingEntity(app);
    ManagementContext managementContext = app.getManagementContext();
    try {
        serializer.setLookupContext(newEmptyLookupManagementContext(managementContext, true).add(app));
        ReffingEntity reffer2 = assertSerializeAndDeserialize(reffer);
        assertEquals(reffer2.entity, app);
    } finally {
        Entities.destroyAll(managementContext);
    }
}
 
Example #25
Source File: ConfigInheritanceYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigOnRuntimeParentUsesConfigKeyDeclaredOnParent() throws Exception {
    addCatalogItems(
            "brooklyn.catalog:",
            "  version: 1.0.0",
            "  itemType: entity",
            "  items:",
            "  - id: test-entity",
            "    item:",
            "      type: "+MyTestEntity.class.getName(), 
            "  - id: test-app",
            "    item:",
            "      type: " + BasicApplication.class.getName(),
            "      brooklyn.parameters:",
            "      - name: myParam",
            "        type: String",
            "        default: myVal",
            "      brooklyn.config:",
            "        test.confName: $brooklyn:scopeRoot().config(\"myParam\")",
            "      brooklyn.children:",
            "      - type: test-entity"
            );

    Entity app = createStartWaitAndLogApplication(Joiner.on("\n").join(
            "services:",
            "- type: "+BasicApplication.class.getName(),
            "  brooklyn.children:",
            "  - type: test-app"));
    
    MyTestEntity testEntity = (MyTestEntity) Iterables.find(Entities.descendantsAndSelf(app), Predicates.instanceOf(MyTestEntity.class));
    assertEquals(testEntity.config().get(MyTestEntity.CONF_NAME), "myVal");
    assertEquals(testEntity.sensors().get(MyTestEntity.MY_SENSOR), "myVal");
}
 
Example #26
Source File: InPlaceExternalConfigSupplierTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@AfterMethod(alwaysRun=true)
public void tearDown() throws Exception {
    try {
        if (mgmt != null) Entities.destroyAll(mgmt);
    } finally {
        mgmt = null;
    }
}
 
Example #27
Source File: AutoScalerPolicyPoolSizeTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testResizeUp() throws Exception {
    EntityAsserts.assertAttributeEqualsEventually(cluster, TestCluster.GROUP_SIZE, CLUSTER_INIITIAL_SIZE);
    // Simulate user expunging the entities manually
    for (int i = 0; i < CLUSTER_MAX_SIZE - CLUSTER_MIN_SIZE; i++) {
        Entities.destroyCatching(cluster.getMembers().iterator().next());
    }
    EntityAsserts.assertAttributeEqualsEventually(cluster, TestSizeRecordingCluster.SIZE_HISTORY_RECORD_COUNT, 2);
    Assert.assertEquals((int)cluster.getSizeHistory().get(0), CLUSTER_INIITIAL_SIZE);
    Assert.assertEquals((int)cluster.getSizeHistory().get(1), CLUSTER_MIN_SIZE);
}
 
Example #28
Source File: SoftwareProcessEntityTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void testBasicSoftwareProcessStopModes(StopMode stopProcessMode, StopMode stopMachineMode, boolean isEntityStopped) throws Exception {
    FixedListMachineProvisioningLocation<SshMachineLocation> l = getLocation();
    MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
    entity.start(ImmutableList.of(l));
    SimulatedDriver d = (SimulatedDriver) entity.getDriver();
    Location machine = Iterables.getOnlyElement(entity.getLocations());
    d.events.clear();

    if (isEntityStopped) {
        ((EntityInternal)entity).sensors().set(ServiceStateLogic.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
    }

    TaskAdaptable<Void> t1 = Entities.submit(entity, Effectors.invocation(entity, Startable.STOP,
            ConfigBag.newInstance()
                .configure(StopSoftwareParameters.STOP_PROCESS_MODE, stopProcessMode)
                .configure(StopSoftwareParameters.STOP_MACHINE_MODE, stopMachineMode)));
    t1.asTask().get(10, TimeUnit.SECONDS);

    if (MachineLifecycleEffectorTasksTest.canStop(app, stopProcessMode, isEntityStopped)) {
        assertEquals(d.events, ImmutableList.of("stop"));
    } else {
        assertTrue(d.events.isEmpty());
    }
    if (MachineLifecycleEffectorTasksTest.canStop(app, stopMachineMode, machine == null)) {
        assertTrue(entity.getLocations().isEmpty());
        assertTrue(l.getAvailable().contains(machine));
    } else {
        assertEquals(ImmutableList.copyOf(entity.getLocations()), ImmutableList.of(machine));
        assertFalse(l.getAvailable().contains(machine));
    }
}
 
Example #29
Source File: StormSshDriver.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public String getNimbusHostname() {
    String result = entity.getConfig(Storm.NIMBUS_HOSTNAME);
    if (result != null) return result;

    Entity nimbus = entity.getConfig(Storm.NIMBUS_ENTITY);
    if (nimbus == null) {
        log.warn("No nimbus hostname available; using 'localhost'");
        return "localhost";
    }
    return Entities.submit(entity, DependentConfiguration.attributeWhenReady(nimbus, Attributes.HOSTNAME)).getUnchecked();
}
 
Example #30
Source File: KubernetesLocationYamlLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Assumes that the container entity uses port 8080.
 */
protected <T extends Entity> T runTomcat(String yaml, Class<T> type) throws Exception {
    Entity app = createStartWaitAndLogApplication(yaml);
    T entity = Iterables.getOnlyElement(Entities.descendantsAndSelf(app, type));

    Entities.dumpInfo(app);
    String publicMapped = assertAttributeEventuallyNonNull(entity, Sensors.newStringSensor("docker.port.8080.mapped.public"));
    HostAndPort publicPort = HostAndPort.fromString(publicMapped);

    assertReachableEventually(publicPort);
    assertHttpStatusCodeEventuallyEquals("http://" + publicPort.getHostText() + ":" + publicPort.getPort(), 200);

    return entity;
}