org.apache.brooklyn.entity.software.base.SoftwareProcess Java Examples

The following examples show how to use org.apache.brooklyn.entity.software.base.SoftwareProcess. 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: RedisClusterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
    super.init();

    RedisStore master = addChild(EntitySpec.create(RedisStore.class));
    sensors().set(MASTER, master);

    DynamicCluster slaves = addChild(EntitySpec.create(DynamicCluster.class)
            .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(RedisSlave.class).configure(RedisSlave.MASTER, master)
            .configure(SoftwareProcess.CUSTOMIZE_LATCH, DependentConfiguration.attributeWhenReady(master, Attributes.SERVICE_UP))));
    sensors().set(SLAVES, slaves);

    enrichers().add(Enrichers.builder()
            .propagating(RedisStore.HOSTNAME, RedisStore.ADDRESS, RedisStore.SUBNET_HOSTNAME, RedisStore.SUBNET_ADDRESS, RedisStore.REDIS_PORT)
            .from(master)
            .build());
}
 
Example #2
Source File: AbstractWindowsYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void assertStreams(SoftwareProcess entity, Map<String, List<String>> stdouts) {
    Set<Task<?>> tasks = BrooklynTaskTags.getTasksInEntityContext(mgmt().getExecutionManager(), entity);

    for (Map.Entry<String, List<String>> entry : stdouts.entrySet()) {
        String taskNameRegex = entry.getKey();
        List<String> expectedOuts = entry.getValue();

        Task<?> subTask = findTaskOrSubTask(tasks, TaskPredicates.displayNameSatisfies(StringPredicates.matchesRegex(taskNameRegex))).get();

        String stdin = getStreamOrFail(subTask, BrooklynTaskTags.STREAM_STDIN);
        String stdout = getStreamOrFail(subTask, BrooklynTaskTags.STREAM_STDOUT);
        String stderr = getStreamOrFail(subTask, BrooklynTaskTags.STREAM_STDERR);
        String env = getStream(subTask, BrooklynTaskTags.STREAM_ENV);
        String msg = "stdin="+stdin+"; stdout="+stdout+"; stderr="+stderr+"; env="+env;

        for (String expectedOut : expectedOuts) {
            assertTrue(stdout.contains(expectedOut), msg);
        }
    }
}
 
Example #3
Source File: AbstractWindowsYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void assertSubTaskFailures(SoftwareProcess entity, Map<String, Predicate<CharSequence>> taskErrs) throws Exception {
    Set<Task<?>> tasks = BrooklynTaskTags.getTasksInEntityContext(mgmt().getExecutionManager(), entity);

    for (Map.Entry<String, Predicate<CharSequence>> entry : taskErrs.entrySet()) {
        String taskNameRegex = entry.getKey();
        Predicate<? super String> errChecker = entry.getValue();
        Task<?> subTask = findTaskOrSubTask(tasks, TaskPredicates.displayNameSatisfies(StringPredicates.matchesRegex(taskNameRegex))).get();
        String msg = "regex="+taskNameRegex+"; task="+subTask;
        assertNotNull(subTask, msg);
        assertTrue(subTask.isDone(), msg);
        assertTrue(subTask.isError(), msg);
        try {
            subTask.get();
            fail();
        } catch (Exception e) {
            if (!errChecker.apply(e.toString())) {
                throw e;
            }
        }
    }
}
 
Example #4
Source File: BasicLauncher.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void startBrooklynNode() {
    final String classpath = System.getenv("INITIAL_CLASSPATH");
    if (Strings.isBlank(classpath)) {
        LOG.warn("Cannot find INITIAL_CLASSPATH environment variable, skipping BrooklynNode entity creation");
        return;
    }

    EntitySpec<LocalBrooklynNode> brooklynNodeSpec = EntitySpec.create(LocalBrooklynNode.class)
        .configure(SoftwareProcess.ENTITY_STARTED, true)
        .configure(BrooklynNode.CLASSPATH, Splitter.on(":").splitToList(classpath))
        .displayName("Brooklyn Console");

    brooklynNodeSpec = customizeBrooklynNodeSpec(brooklynNodeSpec);

    if (brooklynNodeSpec != null) {
        EntityManagementUtils.createStarting(managementContext,
                EntitySpec.create(BasicApplication.class)
                    .displayName("Brooklyn")
                    .child(brooklynNodeSpec));
    }
}
 
Example #5
Source File: VanillaSoftwareYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** yaml variant of VanillaSoftwareProcessAndChildrenIntegrationTest */
@Test(groups="Integration")
public void testVanillaSoftwareYamlWithChildStartedAfter() {
    SimpleYamlLauncher l = new SimpleYamlLauncherForTests();
    try {
        Application app = l.launchAppYaml("vanilla-software-with-child-blueprint.yaml");
        log.info("started "+app);

        Entity p1 = Iterables.getOnlyElement( app.getChildren() );
        Long d1 = Long.parseLong( Strings.getFirstWordAfter(new ResourceUtils(this).getResourceAsString(Os.mergePaths(p1.getAttribute(SoftwareProcess.RUN_DIR), "DATE")), "utc") );
        
        Entity p2 = Iterables.getOnlyElement( p1.getChildren() );
        Long d2 = Long.parseLong( Strings.getFirstWordAfter(new ResourceUtils(this).getResourceAsString(Os.mergePaths(p2.getAttribute(SoftwareProcess.RUN_DIR), "DATE")), "utc") );
        Assert.assertTrue( d2-d1 > 2 && d2-d1 < 10, "p2 should have started 3s after parent, but it did not ("+(d2-d1)+"s difference" );
    } finally {
        l.destroyAll();
    }
    log.info("DONE");
}
 
Example #6
Source File: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
private Effector<Void> newStopEffector() {
    return Effectors.effector(Startable.STOP)
            .parameter(SoftwareProcess.StopSoftwareParameters.STOP_PROCESS_MODE)
            .parameter(SoftwareProcess.StopSoftwareParameters.STOP_MACHINE_MODE)
            .impl(new EffectorBody<Void>() {
                @Override
                public Void call(ConfigBag parameters) {
                    LOG.info("Stopping SeaCloudsInitializerPolicy " + "for " + entity.getId());
                    removeSlaAgreement();
                    removeMonitoringRules();
                    removeInfluxDbObservers();
                    removeGrafanaDashboard();

                    // Rewire the original behaviour
                    ((StartableApplication) entity).stop();

                    return null;
                }
            })
            .build();
}
 
Example #7
Source File: TomcatServerDisableRetrieveUsageMetricsIntegrationTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test(groups="Integration")
public void testDisableRetrievalOfUsageMetrics() throws Exception {
    LocalhostMachineProvisioningLocation loc = app.newLocalhostProvisioningLocation();
    final TomcatServer tc1 = app.createAndManageChild(EntitySpec.create(TomcatServer.class)
            .configure(SoftwareProcess.RETRIEVE_USAGE_METRICS, false));
    final TomcatServer tc2 = app.createAndManageChild(EntitySpec.create(TomcatServer.class));
    
    tc1.start(ImmutableList.of(loc));
    tc2.start(ImmutableList.of(loc));

    // tc2 uses defaults, so will include usage metrics
    Asserts.succeedsEventually(new Runnable() {
        @Override
        public void run() {
            assertNotNull(tc2.getAttribute(TomcatServer.CONNECTOR_STATUS));
            assertNotNull(tc2.getAttribute(TomcatServer.ERROR_COUNT));
            assertNotNull(tc2.getAttribute(TomcatServer.REQUEST_COUNT));
            assertNotNull(tc2.getAttribute(TomcatServer.TOTAL_PROCESSING_TIME));
        }});

    // tc1 should have status info, but not usage metrics
    EntityAsserts.assertAttributeEventuallyNonNull(tc1, TomcatServer.CONNECTOR_STATUS);
    EntityAsserts.assertAttributeEqualsContinually(tc1, TomcatServer.ERROR_COUNT, null);
    assertNull(tc1.getAttribute(TomcatServer.REQUEST_COUNT));
    assertNull(tc1.getAttribute(TomcatServer.TOTAL_PROCESSING_TIME));
}
 
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: AbstractWebAppFixtureIntegrationTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test(groups = "Integration", dataProvider = "entitiesWithWarAndURL")
public void initialNamedWarDeployments(final SoftwareProcess entity, final String war, 
        final String urlSubPathToWebApp, final String urlSubPathToPageToQuery) {
    this.entity = entity;
    log.info("test=initialNamedWarDeployments; entity="+entity+"; app="+entity.getApplication());
    
    URL resource = getClass().getClassLoader().getResource(war);
    assertNotNull(resource);
    
    entity.config().set(JavaWebAppService.NAMED_WARS, ImmutableList.of(resource.toString()));
    Entities.start(entity.getApplication(), ImmutableList.of(loc));

    Asserts.succeedsEventually(MutableMap.of("timeout", 60*1000), new Runnable() {
        @Override
        public void run() {
            // TODO get this URL from a WAR file entity
            HttpTestUtils.assertHttpStatusCodeEquals(Urls.mergePaths(entity.getAttribute(WebAppService.ROOT_URL), urlSubPathToWebApp, urlSubPathToPageToQuery), 200);
        }});
}
 
Example #10
Source File: AbstractWebAppFixtureIntegrationTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/**
 * Tests given entity can deploy the given war.  Checks given httpURL to confirm success.
 */
@Test(groups = "Integration", dataProvider = "entitiesWithWarAndURL")
public void initialRootWarDeployments(final SoftwareProcess entity, final String war, 
        final String urlSubPathToWebApp, final String urlSubPathToPageToQuery) {
    this.entity = entity;
    log.info("test=initialRootWarDeployments; entity="+entity+"; app="+entity.getApplication());
    
    URL resource = getClass().getClassLoader().getResource(war);
    assertNotNull(resource);
    
    entity.config().set(JavaWebAppService.ROOT_WAR, resource.toString());
    Entities.start(entity.getApplication(), ImmutableList.of(loc));
    
    //tomcat may need a while to unpack everything
    Asserts.succeedsEventually(MutableMap.of("timeout", 60*1000), new Runnable() {
        @Override
        public void run() {
            // TODO get this URL from a WAR file entity
            HttpTestUtils.assertHttpStatusCodeEquals(Urls.mergePaths(entity.getAttribute(WebAppService.ROOT_URL), urlSubPathToPageToQuery), 200);
            
            assertEquals(entity.getAttribute(JavaWebAppSoftwareProcess.DEPLOYED_WARS), ImmutableSet.of("/"));
        }});
}
 
Example #11
Source File: AbstractWebAppFixtureIntegrationTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that we get consecutive events with zero workrate, and with suitably small timestamps between them.
 */
@Test(groups = "Integration", dataProvider = "basicEntities")
@SuppressWarnings("rawtypes")
public void publishesZeroRequestsPerSecondMetricRepeatedly(final SoftwareProcess entity) {
    this.entity = entity;
    log.info("test=publishesZeroRequestsPerSecondMetricRepeatedly; entity="+entity+"; app="+entity.getApplication());
    
    final int maxIntervalBetweenEvents = 4000; // TomcatServerImpl publishes events every 3000ms so this should be enough overhead
    final int consecutiveEvents = 3;

    Entities.start(entity.getApplication(), ImmutableList.of(loc));
    SubscriptionHandle subscriptionHandle = null;
    final CopyOnWriteArrayList<SensorEvent<Double>> events = new CopyOnWriteArrayList<>();
    try {
        subscriptionHandle = recordEvents(entity, WebAppService.REQUESTS_PER_SECOND_IN_WINDOW, events);
        Asserts.succeedsEventually(assertConsecutiveSensorEventsEqual(
                events, WebAppService.REQUESTS_PER_SECOND_IN_WINDOW, 0.0d, consecutiveEvents, maxIntervalBetweenEvents));
    } finally {
        if (subscriptionHandle != null) entity.subscriptions().unsubscribe(subscriptionHandle);
        entity.stop();
    }
}
 
Example #12
Source File: MachineLifecycleEffectorTasks.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** Dispatches to the appropriate method(s) to start in the given location. */
protected void startInLocation(final Location location) {
    Supplier<MachineLocation> locationS = null;
    if (location instanceof MachineProvisioningLocation) {
        Task<MachineLocation> machineTask = provisionAsync((MachineProvisioningLocation<?>)location);
        locationS = Tasks.supplier(machineTask);
    } else if (location instanceof MachineLocation) {
        locationS = Suppliers.ofInstance((MachineLocation)location);
    }
    Preconditions.checkState(locationS != null, "Unsupported location "+location+", when starting "+entity());

    final Supplier<MachineLocation> locationSF = locationS;

    // Opportunity to block startup until other dependent components are available
    try (CloseableLatch latch = waitForCloseableLatch(entity(), SoftwareProcess.START_LATCH)) {
        preStartAtMachineAsync(locationSF);
        DynamicTasks.queue("start (processes)", new StartProcessesAtMachineTask(locationSF));
        postStartAtMachineAsync();
    }
}
 
Example #13
Source File: EntityLocationUtilsTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testCount() {
    @SuppressWarnings("unused")
    SoftwareProcess r1 = app.createAndManageChild(EntitySpec.create(SoftwareProcess.class, RestMockSimpleEntity.class));
    SoftwareProcess r2 = app.createAndManageChild(EntitySpec.create(SoftwareProcess.class, RestMockSimpleEntity.class));
    Entities.start(app, Arrays.<Location>asList(loc));

    Entities.dumpInfo(app);

    log.info("r2loc: "+r2.getLocations());
    log.info("props: "+((LocationInternal)r2.getLocations().iterator().next()).config().getInternalConfigMap().getAllConfigInheritedRawValuesIgnoringErrors());

    Map<Location, Integer> counts = new EntityLocationUtils(mgmt).countLeafEntitiesByLocatedLocations();
    log.info("count: "+counts);
    assertEquals(ImmutableList.copyOf(counts.values()), ImmutableList.of(2), "counts="+counts);
}
 
Example #14
Source File: NginxIntegrationTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the Nginx proxy starts up and sets SERVICE_UP correctly.
 */
@Test(groups = "Integration")
public void testWhenNoServersReturns404() {
    serverPool = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure("initialSize", 0)
            .configure("memberSpec", EntitySpec.create(TestEntity.class)));
    
    nginx = app.createAndManageChild(EntitySpec.create(NginxController.class)
            .configure("serverPool", serverPool)
            .configure("domain", "localhost"));
    
    app.start(ImmutableList.of(localLoc));

    EntityAsserts.assertAttributeEqualsEventually(nginx, SoftwareProcess.SERVICE_UP, true);
    assertHttpStatusCodeEventuallyEquals(nginx.getAttribute(NginxController.ROOT_URL), 404);
}
 
Example #15
Source File: NginxIntegrationTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test(groups = "Integration")
public void testRestart() {
    serverPool = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure("initialSize", 0)
            .configure("memberSpec", EntitySpec.create(TestEntity.class)));
    
    nginx = app.createAndManageChild(EntitySpec.create(NginxController.class)
            .configure("serverPool", serverPool)
            .configure("domain", "localhost"));
    
    app.start(ImmutableList.of(localLoc));

    nginx.restart();

    EntityAsserts.assertAttributeEqualsEventually(nginx, SoftwareProcess.SERVICE_UP, true);
    assertHttpStatusCodeEventuallyEquals(nginx.getAttribute(NginxController.ROOT_URL), 404);
}
 
Example #16
Source File: CouchbaseClusterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
protected void addServer(Entity serverToAdd) {
    Preconditions.checkNotNull(serverToAdd);
    if (serverToAdd.equals(getPrimaryNode())) {
        // no need to add; but we pass it in anyway because it makes the calling logic easier
        return;
    }
    if (!isMemberInCluster(serverToAdd)) {
        HostAndPort webAdmin = HostAndPort.fromParts(serverToAdd.getAttribute(SoftwareProcess.SUBNET_HOSTNAME),
                serverToAdd.getAttribute(CouchbaseNode.COUCHBASE_WEB_ADMIN_PORT));
        String username = serverToAdd.getConfig(CouchbaseNode.COUCHBASE_ADMIN_USERNAME);
        String password = serverToAdd.getConfig(CouchbaseNode.COUCHBASE_ADMIN_PASSWORD);

        if (isClusterInitialized()) {
            Entities.invokeEffectorWithArgs(this, getPrimaryNode(), CouchbaseNode.SERVER_ADD_AND_REBALANCE, webAdmin.toString(), username, password).getUnchecked();
        } else {
            Entities.invokeEffectorWithArgs(this, getPrimaryNode(), CouchbaseNode.SERVER_ADD, webAdmin.toString(), username, password).getUnchecked();
        }
        //FIXME check feedback of whether the server was added.
        ((EntityInternal) serverToAdd).sensors().set(CouchbaseNode.IS_IN_CLUSTER, true);
    }
}
 
Example #17
Source File: JavaSoftwareProcessSshDriverIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups = "Integration")
public void testJavaStartStopSshDriverStartsAndStopsApp() throws Exception {
    final MyEntity entity = app.createAndManageChild(EntitySpec.create(MyEntity.class));
    app.start(ImmutableList.of(localhost));
    Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
        @Override
        public void run() {
            assertTrue(entity.getAttribute(SoftwareProcess.SERVICE_UP));
        }});

    entity.stop();
    assertFalse(entity.getAttribute(SoftwareProcess.SERVICE_UP));
}
 
Example #18
Source File: MachineLifecycleEffectorTasks.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public String call() {
    if (entity().getAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL) == Lifecycle.STOPPED) {
        log.debug("Skipping stop of entity " + entity() + " when already stopped");
        return "Already stopped";
    }
    ServiceStateLogic.setExpectedState(entity(), Lifecycle.STOPPING);
    entity().sensors().set(SoftwareProcess.SERVICE_UP, false);
    preStopCustom();
    return null;
}
 
Example #19
Source File: MachineLifecycleEffectorTasks.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Suspend the {@link MachineLocation} the entity is provisioned at.
 * <p>
 * Expects the entity's {@link SoftwareProcess#PROVISIONING_LOCATION provisioner} to be capable of
 * {@link SuspendsMachines suspending machines}.
 *
 * @throws java.lang.UnsupportedOperationException if the entity's provisioner cannot suspend machines.
 * @see MachineManagementMixins.SuspendsMachines
 */
protected StopMachineDetails<Integer> suspendAnyProvisionedMachines() {
    @SuppressWarnings("unchecked")
    MachineProvisioningLocation<MachineLocation> provisioner = entity().getAttribute(SoftwareProcess.PROVISIONING_LOCATION);

    if (Iterables.isEmpty(entity().getLocations())) {
        log.debug("No machine decommissioning necessary for " + entity() + " - no locations");
        return new StopMachineDetails<>("No machine suspend necessary - no locations", 0);
    }

    // Only release this machine if we ourselves provisioned it (e.g. it might be running other services)
    if (provisioner == null) {
        log.debug("No machine decommissioning necessary for " + entity() + " - did not provision");
        return new StopMachineDetails<>("No machine suspend necessary - did not provision", 0);
    }

    Location machine = getLocation(null);
    if (!(machine instanceof MachineLocation)) {
        log.debug("No decommissioning necessary for " + entity() + " - not a machine location (" + machine + ")");
        return new StopMachineDetails<>("No machine suspend necessary - not a machine (" + machine + ")", 0);
    }

    if (!(provisioner instanceof SuspendsMachines)) {
        log.debug("Location provisioner ({}) cannot suspend machines", provisioner);
        throw new UnsupportedOperationException("Location provisioner cannot suspend machines: " + provisioner);
    }

    clearEntityLocationAttributes(machine);
    SuspendsMachines.class.cast(provisioner).suspendMachine(MachineLocation.class.cast(machine));

    return new StopMachineDetails<>("Suspended " + machine, 1);
}
 
Example #20
Source File: MachineLifecycleEffectorTasks.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Stop and release the {@link MachineLocation} the entity is provisioned at.
 * <p>
 * Can run synchronously or not, caller will submit/queue as needed, and will block on any submitted tasks.
 */
protected StopMachineDetails<Integer> stopAnyProvisionedMachines() {
    @SuppressWarnings("unchecked")
    MachineProvisioningLocation<MachineLocation> provisioner = entity().getAttribute(SoftwareProcess.PROVISIONING_LOCATION);

    if (Iterables.isEmpty(entity().getLocations())) {
        log.debug("No machine decommissioning necessary for "+entity()+" - no locations");
        return new StopMachineDetails<Integer>("No machine decommissioning necessary - no locations", 0);
    }

    // Only release this machine if we ourselves provisioned it (e.g. it might be running other services)
    if (provisioner==null) {
        log.debug("No machine decommissioning necessary for "+entity()+" - did not provision");
        return new StopMachineDetails<Integer>("No machine decommissioning necessary - did not provision", 0);
    }

    Location machine = getLocation(null);
    if (!(machine instanceof MachineLocation)) {
        log.debug("No decommissioning necessary for "+entity()+" - not a machine location ("+machine+")");
        return new StopMachineDetails<Integer>("No machine decommissioning necessary - not a machine ("+machine+")", 0);
    }

    entity().sensors().set(AttributesInternal.INTERNAL_TERMINATION_TASK_STATE, ProvisioningTaskState.RUNNING);
    try {
        clearEntityLocationAttributes(machine);
        provisioner.release((MachineLocation)machine);
    } finally {
        // TODO On exception, should we add the machine back to the entity (because it might not really be terminated)?
        //      Do we need a better exception hierarchy for that?
        entity().sensors().remove(AttributesInternal.INTERNAL_TERMINATION_TASK_STATE);
    }
    
    return new StopMachineDetails<Integer>("Decommissioned "+machine, 1);
}
 
Example #21
Source File: InitdServiceInstaller.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Task<?> getServiceInstallTask() {
    ResourceUtils resource = new ResourceUtils(this);
    String pidFile = entity.getAttribute(SoftwareProcess.PID_FILE);
    String template = resource.getResourceAsString(enricher.config().get(SERVICE_TEMPLATE));
    String serviceName = getServiceName();
    SshMachineLocation sshMachine = EffectorTasks.getSshMachine(entity);
    Map<String, Object> params = MutableMap.<String, Object>of(
            "service.launch_script", Os.mergePaths(getRunDir(), getStartScriptName()),
            "service.name", serviceName,
            "service.user", sshMachine.getUser(),
            "service.log_path", getLogLocation());
    if (pidFile != null) {
        params.put("service.pid_file", pidFile);
    }
    String service = TemplateProcessor.processTemplateContents(template, (EntityInternal)entity, params);
    String tmpServicePath = Os.mergePaths(getRunDir(), serviceName);
    String servicePath = "/etc/init.d/" + serviceName;
    SshPutTaskWrapper putServiceTask = SshTasks.newSshPutTaskFactory(sshMachine, tmpServicePath)
            .contents(service)
            .newTask();
    ProcessTaskWrapper<Integer> installServiceTask = SshTasks.newSshExecTaskFactory(sshMachine,
            BashCommands.chain(
                BashCommands.sudo("mv " + tmpServicePath + " " + servicePath),
                BashCommands.sudo("chmod 0755 " + servicePath),
                BashCommands.sudo("chkconfig --add " + serviceName),
                BashCommands.sudo("chkconfig " + serviceName + " on")))
        .requiringExitCodeZero()
        .newTask();

    return Tasks.<Void>builder()
        .displayName("install (init.d)")
        .description("Install init.d service")
        .add(putServiceTask)
        .add(installServiceTask)
        .build();
}
 
Example #22
Source File: InitSlaveTaskBody.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
private ProcessTaskFactory<Integer> execSshTask(Entity entity, String cmd, String summary) {
    SshMachineLocation machine = EffectorTasks.getSshMachine(entity);
    return SshTasks.newSshExecTaskFactory(machine, "cd $RUN_DIR\n" + cmd)
        .allowingNonZeroExitCode()
        .environmentVariable("RUN_DIR", entity.getAttribute(SoftwareProcess.RUN_DIR))
        .summary(summary);
}
 
Example #23
Source File: KubernetesLocationYamlLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public KubernetesClient getClient(Entity entity) {
    MachineProvisioningLocation location = entity.sensors().get(SoftwareProcess.PROVISIONING_LOCATION);
    if (location instanceof KubernetesLocation) {
        KubernetesLocation kubernetes = (KubernetesLocation) location;
        ConfigBag config = kubernetes.config().getBag();
        KubernetesClientRegistry registry = kubernetes.config().get(KubernetesLocationConfig.KUBERNETES_CLIENT_REGISTRY);
        KubernetesClient client = registry.getKubernetesClient(config);
        return client;
    }
    throw new IllegalStateException("Cannot find KubernetesLocation on entity: " + Iterables.toString(entity.getLocations()));
}
 
Example #24
Source File: KubernetesLocationYamlLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected <T extends Entity> void checkNginxResource(Entity app, Class<T> type) {
    T entity = Iterables.getOnlyElement(Entities.descendantsAndSelf(app, type));

    Entities.dumpInfo(app);

    assertEntityHealthy(entity);
    assertAttributeEqualsEventually(entity, KubernetesResource.RESOURCE_NAME, "nginx-replication-controller");
    assertAttributeEqualsEventually(entity, KubernetesResource.RESOURCE_TYPE, "ReplicationController");
    assertAttributeEqualsEventually(entity, KubernetesResource.KUBERNETES_NAMESPACE, "default");
    assertAttributeEventually(entity, SoftwareProcess.ADDRESS, and(notNull(), not(equalTo("0.0.0.0"))));
    assertAttributeEventually(entity, SoftwareProcess.SUBNET_ADDRESS, and(notNull(), not(equalTo("0.0.0.0"))));
}
 
Example #25
Source File: AbstractMultiDistroLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void assertExecSsh(SoftwareProcess entity, List<String> commands) {
    SshMachineLocation machine = Machines.findUniqueMachineLocation(entity.getLocations(), SshMachineLocation.class).get();
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    ByteArrayOutputStream errStream = new ByteArrayOutputStream();
    int result = machine.execScript(ImmutableMap.of("out", outStream, "err", errStream), "url-reachable", commands);
    String out = new String(outStream.toByteArray());
    String err = new String(errStream.toByteArray());
    if (result == 0) {
        LOG.debug("Successfully executed: cmds="+commands+"; stderr="+err+"; out="+out);
    } else {
        fail("Failed to execute: result="+result+"; cmds="+commands+"; stderr="+err+"; out="+out);
    }
}
 
Example #26
Source File: MySqlClusterIntegrationTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
private boolean fileExists(MySqlNode node, String binLogName) {
    String dataDir = Strings.nullToEmpty(node.getConfig(MySqlNode.DATA_DIR));
    String path = Os.mergePathsUnix(dataDir, binLogName);
    String cmd = BashCommands.chain(
            "cd $RUN_DIR",
            BashCommands.requireTest(String.format("-f \"%s\"", path), "File " + path + " doesn't exist."));
    String summary = "Check if file " + path + " exists";
    SshMachineLocation machine = EffectorTasks.getSshMachine(node);
    return Entities.submit(node, SshTasks.newSshExecTaskFactory(machine, cmd)
            .allowingNonZeroExitCode()
            .environmentVariable("RUN_DIR", node.getAttribute(SoftwareProcess.RUN_DIR))
            .summary(summary)
            .allowingNonZeroExitCode()).asTask().getUnchecked() == 0;
}
 
Example #27
Source File: SaltEntitySshDriver.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
public void runPostLaunchCommand() {
    super.runPostLaunchCommand();

    final ProcessTaskWrapper<String> retrieveHighstate = SaltSshTasks.retrieveHighstate();
    final ProcessTaskWrapper<String> highstate = DynamicTasks.queue(retrieveHighstate).block();
    String stateDescription = highstate.get();

    SaltHighstate.applyHighstate(stateDescription, getEntity());

    getEntity().sensors().set(SoftwareProcess.SERVICE_UP, true);
}
 
Example #28
Source File: NodeJsTodoApplication.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
public void initApp() {
    RedisStore redis = addChild(EntitySpec.create(RedisStore.class));

    addChild(EntitySpec.create(NodeJsWebAppService.class)
            .configure(NodeJsWebAppService.APP_GIT_REPOSITORY_URL, "https://github.com/grkvlt/nodejs-todo/")
            .configure(NodeJsWebAppService.APP_FILE, "server.js")
            .configure(NodeJsWebAppService.APP_NAME, "nodejs-todo")
            .configure(NodeJsWebAppService.NODE_PACKAGE_LIST, ImmutableList.of("express", "ejs", "jasmine-node", "underscore", "method-override", "cookie-parser", "express-session", "body-parser", "cookie-session", "redis", "redis-url", "connect"))
            .configure(SoftwareProcess.SHELL_ENVIRONMENT, ImmutableMap.<String, Object>of(
                    "REDISTOGO_URL", DependentConfiguration.formatString("redis://%s:%d/",
                            attributeWhenReady(redis, Attributes.HOSTNAME), attributeWhenReady(redis, RedisStore.REDIS_PORT))))
            .configure(SoftwareProcess.LAUNCH_LATCH, attributeWhenReady(redis, Startable.SERVICE_UP)));
}
 
Example #29
Source File: ChefLifecycleEffectorTasks.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
protected void postStartCustom() {
    boolean result = false;
    result |= tryCheckStartPid();
    result |= tryCheckStartService();
    result |= tryCheckStartWindowsService();
    if (!result) {
        log.warn("No way to check whether "+entity()+" is running; assuming yes");
    }
    entity().sensors().set(SoftwareProcess.SERVICE_UP, true);
    super.postStartCustom();
}
 
Example #30
Source File: QpidIntegrationTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
/**
 * Test that the broker starts up and sets SERVICE_UP correctly when plugins are configured.
 * 
 * FIXME the custom plugin was written against qpid 0.14, so that's the version we need to run
 * this test against. However, v0.14 is no longer available from the download site.
 * We should update this plugin so it works with the latest qpid.
 */
@Test(enabled = false, groups = "Integration")
public void canStartupAndShutdownWithPlugin() {
    Map<String,String> qpidRuntimeFiles = MutableMap.<String,String>builder()
            .put("classpath://qpid-test-config.xml", "etc/config.xml")
            .put("http://developers.cloudsoftcorp.com/brooklyn/repository-test/0.7.0/QpidBroker/qpid-test-plugin.jar", "lib/plugins/sample-plugin.jar")
            .build();
    qpid = app.createAndManageChild(EntitySpec.create(QpidBroker.class)
            .configure(SoftwareProcess.RUNTIME_FILES, qpidRuntimeFiles)
            .configure(QpidBroker.SUGGESTED_VERSION, "0.14"));
    qpid.start(ImmutableList.of(testLocation));
    EntityAsserts.assertAttributeEqualsEventually(qpid, Startable.SERVICE_UP, true);
    qpid.stop();
    assertFalse(qpid.getAttribute(Startable.SERVICE_UP));
}