org.apache.brooklyn.api.effector.Effector Java Examples

The following examples show how to use org.apache.brooklyn.api.effector.Effector. 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: TestSensorAndEffectorInitializer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(@SuppressWarnings("deprecation") org.apache.brooklyn.api.entity.EntityLocal entity) {
    Effector<String> eff = Effectors.effector(String.class, EFFECTOR_SAY_HELLO).parameter(String.class, "name").impl(
        new EffectorBody<String>() {
            @Override
            public String call(ConfigBag parameters) {
                Object name = parameters.getStringKey("name");
                entity().sensors().set(Sensors.newStringSensor(SENSOR_LAST_HELLO), Strings.toString(name));
                return helloWord()+" "+name;
            }
        }).build();
    ((EntityInternal)entity).getMutableEntityType().addEffector(eff);
    
    ((EntityInternal)entity).getMutableEntityType().addSensor(Sensors.newStringSensor(SENSOR_HELLO_DEFINED));
    
    AttributeSensor<String> emitted = Sensors.newStringSensor(SENSOR_HELLO_DEFINED_EMITTED);
    ((EntityInternal)entity).getMutableEntityType().addSensor(emitted);
    entity.sensors().set(emitted, "1");
}
 
Example #2
Source File: EffectorUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Invokes a method effector so that its progress is tracked. For internal use only, when we know the effector is backed by a method which is local.
 */
public static <T> T invokeMethodEffector(Entity entity, Effector<T> eff, Map<String,?> args) {
    Object[] parametersArray = EffectorUtils.prepareArgsForEffector(eff, args);
    String name = eff.getName();

    try {
        if (log.isDebugEnabled()) log.debug("Invoking effector {} on {}", new Object[] {name, entity});
        if (log.isTraceEnabled()) log.trace("Invoking effector {} on {} with args {}", new Object[] {name, entity, Sanitizer.sanitize(args)});
        EntityManagementSupport mgmtSupport = ((EntityInternal)entity).getManagementSupport();
        if (!mgmtSupport.isDeployed()) {
            mgmtSupport.attemptLegacyAutodeployment(name);
        }
        ManagementContextInternal mgmtContext = (ManagementContextInternal) ((EntityInternal) entity).getManagementContext();

        mgmtSupport.getEntityChangeListener().onEffectorStarting(eff, parametersArray);
        try {
            return mgmtContext.invokeEffectorMethodSync(entity, eff, args);
        } finally {
            mgmtSupport.getEntityChangeListener().onEffectorCompleted(eff);
        }
    } catch (Exception e) {
        throw handleEffectorException(entity, eff, e);
    }
}
 
Example #3
Source File: ElectPrimaryEffector.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Object call() throws Exception {
    String promoteEffectorName = params.get(PROMOTE_EFFECTOR_NAME);
    Effector<?> eff = entity().getEffector(promoteEffectorName);
    if (eff!=null) {
        return DynamicTasks.queue( Effectors.invocation(entity(), eff, params) ).asTask().getUnchecked();
    }
    EntityInternal newPrimary = (EntityInternal)params.getStringKey("newPrimary");
    if (newPrimary==null) {
        return "Nothing to promote; no new primary";
    }
    eff = newPrimary.getEffector(promoteEffectorName);
    if (eff!=null) {
        return DynamicTasks.queue( Effectors.invocation(newPrimary, eff, params) ).asTask().getUnchecked();
    }
    if (params.containsKey(PROMOTE_EFFECTOR_NAME)) {
        throw new IllegalStateException("Key "+PROMOTE_EFFECTOR_NAME.getName()+" set as "+promoteEffectorName+
            " but that effector isn't available on this entity or new primary "+newPrimary);
    }
    return "No promotion effector '"+promoteEffectorName+"'; nothing to do";
}
 
Example #4
Source File: AddChildrenEffector.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public Body(Effector<?> eff, ConfigBag params) {
    this.effector = eff;
    String newBlueprint = null;
    Object yaml = params.get(BLUEPRINT_YAML);
    if (yaml instanceof Map) {
        newBlueprint = toJson((Map<?,?>)yaml);
    } else if (yaml instanceof String) {
        newBlueprint = (String) yaml;
    } else if (yaml!=null) {
        throw new IllegalArgumentException(this+" requires map or string in "+BLUEPRINT_YAML+"; not "+yaml.getClass()+" ("+yaml+")");
    }
    String blueprintType = params.get(BLUEPRINT_TYPE);
    if (blueprintType!=null) {
        if (newBlueprint!=null) {
            throw new IllegalArgumentException(this+" cannot take both "+BLUEPRINT_TYPE+" and "+BLUEPRINT_YAML);
        }
        newBlueprint = "services: [ { type: "+blueprintType+" } ]";
    }
    if (newBlueprint==null) {
        throw new IllegalArgumentException(this+" requires either "+BLUEPRINT_TYPE+" or "+BLUEPRINT_YAML);
    }
    blueprintBase = newBlueprint;
    autostart = params.get(AUTO_START);
}
 
Example #5
Source File: ProxyEffectorYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testThrowsIfTargetDoesNotResolve() throws Exception {
    final String effectorName = "proxy-effector";
    Entity app = createAndStartApplication(
            "location: localhost",
            "services:",
            "- type: " + BasicEntity.class.getName(),
            "  brooklyn.initializers:",
            "  - type: org.apache.brooklyn.core.effector.ProxyEffector",
            "    brooklyn.config:",
            "      name: " + effectorName,
            "      targetEntity: $brooklyn:entity(\"skhbfskdbf\")",
            "      targetEffector: identityEffector"
    );
    waitForApplicationTasks(app);
    Entity basicEntity = app.getChildren().iterator().next();
    Effector<?> effector = basicEntity.getEntityType().getEffectorByName(effectorName).get();
    try {
        basicEntity.invoke(effector, ImmutableMap.<String, Object>of()).get();
        Asserts.shouldHaveFailedPreviously("expected exception when invoking effector that does not exist");
    } catch (Exception e) {
        Asserts.expectedFailure(e);
    }
}
 
Example #6
Source File: AbstractManagementContext.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> T invokeEffectorMethodLocal(Entity entity, Effector<T> eff, Map<String, ?> args) {
    assert isManagedLocally(entity) : "cannot invoke effector method at "+this+" because it is not managed here";
    totalEffectorInvocationCount.incrementAndGet();
    Object[] transformedArgs = EffectorUtils.prepareArgsForEffector(eff, args);
    
    try {
        Maybe<Object> result = Reflections.invokeMethodFromArgs(entity, eff.getName(), Arrays.asList(transformedArgs));
        if (result.isPresent()) {
            return (T) result.get();
        } else {
            throw new IllegalStateException("Unable to invoke entity effector method "+eff.getName()+" on "+entity+" - not found matching args");
        }
        
    } catch (IllegalAccessException | InvocationTargetException e) {
        // Note that if we do any "nicer" error, such as:
        //     throw Exceptions.propagate("Unable to invoke entity effector method "+eff.getName()+" on "+entity, e)
        // then EffectorBasicTest.testInvokeEffectorErrorCollapsedNicely fails because its call to:
        //     Exceptions.collapseTextInContext
        // does not unwrap this text.
        throw Exceptions.propagate(e);
    }
}
 
Example #7
Source File: InvokeEffectorOnCollectionSensorChange.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void onEvent(String effectorName, Object parameter) {
    Maybe<Effector<?>> effector = getEffector(effectorName);
    if (effector.isPresentAndNonNull()) {
        final Map<String, Object> parameters;
        if (parameter instanceof Map) {
            Map<?, ?> param = (Map) parameter;
            parameters = MutableMap.of();
            for (Map.Entry<?, ?> entry : param.entrySet()) {
                String key = TypeCoercions.coerce(entry.getKey(), String.class);
                parameters.put(key, entry.getValue());
            }
        } else {
            parameters = MutableMap.of(getConfig(PARAMETER_NAME), parameter);
        }

        LOG.debug("{} invoking {} on {} with parameters {}", new Object[]{this, effector, entity, parameters});
        invoke(effector.get(), parameters);
    }
}
 
Example #8
Source File: AbstractEffector.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** not meant for overriding; subclasses should override the abstract {@link #call(Entity, Map)} method in this class */
@Override
public final EffectorTaskFactory<T> getBody() {
    return new EffectorTaskFactory<T>() {
        @Override
        public Task<T> newTask(final Entity entity, final Effector<T> effector, final ConfigBag parameters) {
            return new DynamicSequentialTask<T>(
                    getFlagsForTaskInvocationAt(entity, AbstractEffector.this, parameters),
                    new Callable<T>() {
                        @Override public T call() {
                            return AbstractEffector.this.call(parameters.getAllConfig(), entity);
                        }
                    });
        }
    };
}
 
Example #9
Source File: BrooklynTaskTags.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * finds the task up the {@code child} hierarchy handling the {@code effector} call,
 * returns null if one doesn't exist. 
 */
@Beta
public static Task<?> getClosestEffectorTask(Task<?> child, Effector<?> effector) {
    Task<?> t = child;
    while (t != null) {
        Set<Object> tags = t.getTags();
        if (tags.contains(EFFECTOR_TAG)) {
            for (Object tag: tags) {
                if (tag instanceof EffectorCallTag) {
                    EffectorCallTag et = (EffectorCallTag) tag;
                    if (effector != null && !et.getEffectorName().equals(effector.getName()))
                        continue;
                    return t;
                }
            }
        }
        t = t.getSubmittedByTask();
    }
    return null;
}
 
Example #10
Source File: CompositeEffectorYamlRebindTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void runRebindWhenIsUp(String catalogYaml, String appId) throws Exception {
   addCatalogItems(catalogYaml);

   String appYaml = Joiner.on("\n").join(
           "services: ",
           "- type: " + appId);
   Entity app = createStartWaitAndLogApplication(appYaml);
   TestEntity entity = (TestEntity) Iterables.find(app.getChildren(), EntityPredicates.displayNameEqualTo("targetEntity"));
   
   // start was overridden, so java method not called; but composite will have called "testEntity.myEffector"
   assertEquals(entity.getCallHistory(), ImmutableList.of("myEffector"));
   entity.clearCallHistory();
   
   // Rebind
   StartableApplication newApp = rebind();
   TestEntity newEntity = (TestEntity) Iterables.find(newApp.getChildren(), EntityPredicates.displayNameEqualTo("targetEntity"));
   Effector<?> effector = assertHasInitializers(newEntity, "start");

   // Confirm HttpCommandEffector still functions
   Object results = newEntity.invoke(effector, ImmutableMap.<String, Object>of()).get();
   assertEquals(results, MutableList.of("myId", null));
   
   assertEquals(newEntity.getCallHistory(), ImmutableList.of("myEffector"));
}
 
Example #11
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 #12
Source File: Entities.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Invokes an {@link Effector} on multiple entities, with the named arguments from the parameters {@link Map}
 * using the context of the provided {@link Entity}.
 * <p>
 * Intended for use only from the callingEntity.
 * <p>
 * Returns a {@link ParallelTask} containing the results from each tasks invocation. Calling
 * {@link java.util.concurrent.Future#get() get()} on this will block until all tasks are complete,
 * and will throw an exception if any task resulted in an error.
 *
 * @return {@link ParallelTask} containing results from each invocation
 */
public static <T> Task<List<T>> invokeEffectorList(Entity callingEntity, Iterable<? extends Entity> entitiesToCall,
        final Effector<T> effector, final Map<String,?> parameters) {
    // formulation is complicated, but it is building up a list of tasks, without blocking on them initially,
    // but ensuring that when the parallel task is gotten it does block on all of them

    if (entitiesToCall == null){
        entitiesToCall = ImmutableList.of();
    }

    List<TaskAdaptable<T>> tasks = Lists.newArrayList();

    for (final Entity entity : entitiesToCall) {
        tasks.add( Effectors.invocation(entity, effector, parameters) );
    }
    ParallelTask<T> invoke = new ParallelTask<T>(
            MutableMap.of(
                    "displayName", effector.getName()+" (parallel)",
                    "description", "Invoking effector \""+effector.getName()+"\" on "+tasks.size()+(tasks.size() == 1 ? " entity" : " entities"),
                    "tag", BrooklynTaskTags.tagForCallerEntity(callingEntity)),
            tasks);
    TaskTags.markInessential(invoke);
    return DynamicTasks.queueIfPossible(invoke).orSubmitAsync(callingEntity).asTask();
}
 
Example #13
Source File: Effectors.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** returns an unsubmitted task which will invoke the given effector on the given entities in parallel;
 * return type is Task<List<T>> (but haven't put in the blood sweat toil and tears to make the generics work) */
public static TaskAdaptable<List<?>> invocationParallel(Effector<?> eff, Map<?,?> params, Iterable<? extends Entity> entities) {
    List<TaskAdaptable<?>> tasks = new ArrayList<TaskAdaptable<?>>();
    for (Entity e: entities) tasks.add(invocation(e, eff, params));
    return Tasks.parallel(
            "invoking " + eff + " on " + tasks.size() + " node" + (Strings.s(tasks.size())),
            tasks.toArray(new TaskAdaptable[tasks.size()]));
}
 
Example #14
Source File: RebindEntityDynamicTypeInfoTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void checkEffectorWithRebind() throws InterruptedException, ExecutionException,
    Exception {
    Effector<?> eff = origApp.getEntityType().getEffectorByName("say_hi").get();
    assertEquals(origApp.invoke(eff, ConfigBag.newInstance().configure(SayHiBody.NAME_KEY, "bob").getAllConfig()).get(), "hello bob");
    
    newApp = rebind();
    log.info("Effectors on new app: "+newApp.getEntityType().getEffectors());
    assertNotSame(newApp, origApp);
    assertEquals(newApp.getId(), origApp.getId());
    
    assertEquals(newApp.invoke(eff, ConfigBag.newInstance().configure(SayHiBody.NAME_KEY, "bob").getAllConfig()).get(), "hello bob");
    eff = newApp.getEntityType().getEffectorByName("say_hi").get();
    assertEquals(newApp.invoke(eff, ConfigBag.newInstance().configure(SayHiBody.NAME_KEY, "bob").getAllConfig()).get(), "hello bob");
}
 
Example #15
Source File: EffectorMetadataTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testEffectorMetaDataFromAnnotationsWithoutConstant() {
    Effector<?> effector = EffectorUtils.findEffectorDeclared(e1, "effWithAnnotationButNoConstant").get();
    assertEquals(effector.getName(), "effWithAnnotationButNoConstant");
    assertEquals(effector.getDescription(), "my effector description");
    assertEquals(effector.getReturnType(), String.class);
    assertParametersEqual(
            effector.getParameters(), 
            ImmutableList.<ParameterType<?>>of(
                    new BasicParameterType<String>("param1", String.class, "my param description", "my default val")));
}
 
Example #16
Source File: EntityProxyImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Effector<?> findEffector(Method m, Object[] args) {
    String name = m.getName();
    Set<Effector<?>> effectors = delegate.getEntityType().getEffectors();
    for (Effector<?> contender : effectors) {
        if (name.equals(contender.getName())) {
            return contender;
        }
    }
    return null;
}
 
Example #17
Source File: AbstractSoftwareProcessRestartIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void runStopProcessAndRestart(Effector<?> restartEffector, Map<String, ?> args) throws Exception {
    LocalhostMachineProvisioningLocation loc = app.newLocalhostProvisioningLocation();
    SoftwareProcess entity = app.createAndManageChild(newEntitySpec());
    
    // Start the app
    app.start(ImmutableList.of(loc));
    EntityAsserts.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_UP, true);
    EntityAsserts.assertAttributeEqualsEventually(app, SoftwareProcess.SERVICE_UP, true);

    // Stop the process
    Entities.invokeEffector(app, entity, SoftwareProcess.STOP, ImmutableMap.of(
            StopSoftwareParameters.STOP_MACHINE_MODE.getName(), StopSoftwareParameters.StopMode.NEVER))
            .get();
    EntityAsserts.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_UP, false);
    EntityAsserts.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
    EntityAsserts.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, false);
    EntityAsserts.assertAttributeEventually(entity, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, CollectionFunctionals.<String>mapSizeEquals(1));
    
    // Restart the process
    Entities.invokeEffector(app, entity, restartEffector, args).get();
    EntityAsserts.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_UP, true);
    EntityAsserts.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
    EntityAsserts.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, true);
    EntityAsserts.assertAttributeEqualsEventually(entity, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, ImmutableMap.<String, Object>of());

    EntityAsserts.assertAttributeEqualsEventually(app, SoftwareProcess.SERVICE_UP, true);
    EntityAsserts.assertAttributeEqualsEventually(app, SoftwareProcess.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
}
 
Example #18
Source File: BrooklynNodeIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void createNodeAndExecStopEffector(Effector<?> eff) throws Exception {
        BrooklynNode brooklynNode = setUpBrooklynNodeWithApp();
        File pidFile = new File(getDriver(brooklynNode).getPidFile());
        assertTrue(isPidRunning(pidFile));
        
        brooklynNode.invoke(eff, Collections.<String, Object>emptyMap()).getUnchecked();

        // Note can't use driver.isRunning to check shutdown; can't invoke scripts on an unmanaged entity
        EntityAsserts.assertAttributeEquals(brooklynNode, BrooklynNode.SERVICE_UP, false);
        
        // unmanaged if the machine is destroyed - ie false on localhost (this test by default), but true in the cloud 
//        assertFalse(Entities.isManaged(brooklynNode));
        
        assertFalse(isPidRunning(pidFile), "pid in "+pidFile+" still running");
    }
 
Example #19
Source File: CatalogOsgiVersionMoreEntityRebindTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testEffectorInBundleReferencedByStockCatalogItem() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_PATH);
    
    String effectorType = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_EFFECTOR;
    
    addCatalogItems(
            "brooklyn.catalog:",
            "  id: wrapped-entity",
            "  version: 1.0",
            "  item:",
            "    services:",
            "    - type: " + TestEntity.class.getName());

    addCatalogItems(
            "brooklyn.catalog:",
            "  id: with-effector-from-library",
            "  version: 1.0",
            "  brooklyn.libraries:",
            "  - classpath:" + OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_PATH,
            "  item:",
            "    services:",
            "    - type: " + BasicApplication.class.getName(),
            "      brooklyn.children:",
            "      - type: wrapped-entity:1.0",
            "        brooklyn.initializers:",
            "        - type: " + effectorType);

    Entity app = createAndStartApplication("services: [ { type: 'with-effector-from-library:1.0' } ]");
    Entity entity = Iterables.getOnlyElement(app.getChildren());
    Effector<?> effector = entity.getEntityType().getEffectorByName("myEffector").get();
    entity.invoke(effector, ImmutableMap.<String, Object>of()).get();
    
    StartableApplication newApp = rebind();
    Entity newEntity = Iterables.getOnlyElement(newApp.getChildren());
    Effector<?> newEffector = newEntity.getEntityType().getEffectorByName("myEffector").get();
    newEntity.invoke(newEffector, ImmutableMap.<String, Object>of()).get();
}
 
Example #20
Source File: CompositeEffector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Object invokeEffectorNamed(String effectorName, ConfigBag params) {
    LOG.info("{} invoking effector on {}, effector={}, parameters={}",
            new Object[]{this, entity(), effectorName, params});
    Maybe<Effector<?>> effector = entity().getEntityType().getEffectorByName(effectorName);
    if (effector.isAbsent()) {
        throw new IllegalStateException("Cannot find effector " + effectorName);
    }
    return entity().invoke(effector.get(), params.getAllConfig()).getUnchecked();
}
 
Example #21
Source File: AddEffector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** returns a ConfigBag containing the merger of the supplied parameters with default values on the effector-defined parameters */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static ConfigBag getMergedParams(Effector<?> eff, ConfigBag params) {
    ConfigBag result = ConfigBag.newInstanceCopying(params);
    for (ParameterType<?> param: eff.getParameters()) {
        ConfigKey key = Effectors.asConfigKey(param);
        if (!result.containsKey(key))
            result.configure(key, params.get(key));
    }
    return result;
}
 
Example #22
Source File: SshCommandEffector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public Body(Effector<?> eff, ConfigBag params) {
    this.effector = eff;
    this.command = Preconditions.checkNotNull(params.get(EFFECTOR_COMMAND), "SSH command must be supplied when defining this effector");
    this.shellEnv = params.get(EFFECTOR_SHELL_ENVIRONMENT);
    this.executionDir = params.get(EFFECTOR_EXECUTION_DIR);
    this.executionTarget = params.get(EXECUTION_TARGET);
}
 
Example #23
Source File: EffectorTransformer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static EffectorSummary effectorSummaryForCatalog(Effector<?> effector) {
    Set<EffectorSummary.ParameterSummary<?>> parameters = ImmutableSet.copyOf(Iterables.transform(effector.getParameters(),
            new Function<ParameterType<?>, EffectorSummary.ParameterSummary<?>>() {
                @Override
                public EffectorSummary.ParameterSummary<?> apply(ParameterType<?> parameterType) {
                    return parameterSummary(null, parameterType);
                }
            }));
    return new EffectorSummary(effector.getName(),
            effector.getReturnTypeName(), parameters, effector.getDescription(), null);
}
 
Example #24
Source File: Effectors.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** as {@link #invocationParallel(Effector, Map, Iterable)} but executing sequentially */
public static TaskAdaptable<List<?>> invocationSequential(Effector<?> eff, Map<?,?> params, Iterable<? extends Entity> entities) {
    List<TaskAdaptable<?>> tasks = new ArrayList<TaskAdaptable<?>>();
    for (Entity e: entities) tasks.add(invocation(e, eff, params));
    return Tasks.sequential(
            "invoking " + eff + " on " + tasks.size() + " node" + (Strings.s(tasks.size())),
            tasks.toArray(new TaskAdaptable[tasks.size()]));
}
 
Example #25
Source File: EffectorTasks.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static <T> EffectorTaskFactory<T> of(final Task<T> task) {
    return new EffectorTaskFactory<T>() {
        @Override
        public Task<T> newTask(Entity entity, Effector<T> effector, ConfigBag parameters) {
            return task;
        }
    };
}
 
Example #26
Source File: DynamicClusterImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Creates tasks that obtain permits from {@link #childTaskSemaphore} before invoking <code>effector</code>
 * on <code>target</code>. Permits are released in a {@link ListenableFuture#addListener listener}. No
 * permits are obtained if {@link #childTaskSemaphore} is <code>null</code>.
 * @param target Entity to invoke effector on
 * @param effector Effector to invoke on target
 * @param arguments Effector arguments
 * @param isPrivileged If true the method obtains a permit from {@link #childTaskSemaphore}
 *                     immediately and returns the effector invocation task, otherwise it
 *                     returns a task that sequentially obtains a permit then runs the effector.
 * @return An unsubmitted task.
 */
protected <T> Task<?> newThrottledEffectorTask(Entity target, Effector<T> effector, Map<?, ?> arguments, boolean isPrivileged) {
    final Task<?> toSubmit;
    final Task<T> effectorTask = Effectors.invocation(target, effector, arguments).asTask();
    if (getChildTaskSemaphore() != null) {
        // permitObtained communicates to the release task whether the permit should really be released
        // or not. ObtainPermit sets it to true when a permit is acquired.
        final AtomicBoolean permitObtained = new AtomicBoolean();
        final String description = "Waiting for permit to run " + effector.getName() + " on " + target;
        final Runnable obtain = new ObtainPermit(getChildTaskSemaphore(), description, permitObtained);
        // Acquire the permit now for the privileged task and just queue the effector invocation.
        // If it's unprivileged then queue a task to obtain a permit first.
        if (isPrivileged) {
            obtain.run();
            toSubmit = effectorTask;
        } else {
            Task<?> obtainMutex = Tasks.builder()
                    .description(description)
                    .body(new ObtainPermit(getChildTaskSemaphore(), description, permitObtained))
                    .build();
            toSubmit = Tasks.sequential(
                    "Waiting for permit then running " + effector.getName() + " on " + target,
                    obtainMutex, effectorTask);
        }
        toSubmit.addListener(new ReleasePermit(getChildTaskSemaphore(), permitObtained), MoreExecutors.sameThreadExecutor());
    } else {
        toSubmit = effectorTask;
    }
    return toSubmit;
}
 
Example #27
Source File: AbstractInvokeEffectorPolicy.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Invoke effector with parameters on the entity that the policy is attached to.
 */
protected <T> Task<T> invoke(Effector<T> effector, Map<String, ?> parameters) {
    if (isBusySensorEnabled()) {
        getTaskCounter().incrementAndGet();
        publishIsBusy();
    }
    Task<T> task = entity.invoke(effector, parameters);
    if (isBusySensorEnabled()) {
        task.addListener(new EffectorListener(), MoreExecutors.sameThreadExecutor());
    }
    return task;
}
 
Example #28
Source File: InvokeEffectorOnSensorChange.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(SensorEvent<Object> event) {
    final Effector<?> eff = getEffectorNamed(getConfig(EFFECTOR)).get();
    if (isBusySensorEnabled()) {
        final Object currentSensorValue = entity.sensors().get(sensor);
        setMoreUpdatesComing(event.getTimestamp(), event.getValue(), currentSensorValue);
    }
    invoke(eff, MutableMap.<String, Object>of());
}
 
Example #29
Source File: EffectorUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** method used for calls such as   entity.effector(arg1, arg2)
 * get routed here from AbstractEntity.invokeMethod */
private static Object[] prepareArgsForEffectorFromArray(Effector<?> eff, Object args[]) {
    int newArgsNeeded = eff.getParameters().size();
    if (args.length==1 && args[0] instanceof Map) {
        if (newArgsNeeded!=1 || !eff.getParameters().get(0).getParameterClass().isAssignableFrom(args[0].getClass())) {
            // treat a map in an array as a map passed directly (unless the method takes a single-arg map)
            // this is to support   effector(param1: val1)
            return prepareArgsForEffectorFromMap(eff, (Map) args[0]);
        }
    }
    return prepareArgsForEffectorAsMapFromArray(eff, args).values().toArray(new Object[0]);
}
 
Example #30
Source File: Entities.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Task<List<T>> invokeEffectorListWithArgs(Entity callingEntity, Iterable<? extends Entity> entitiesToCall,
        final Effector<T> effector, Object ...args) {
    return invokeEffectorListWithMap(callingEntity, entitiesToCall, effector,
            // putting into a map, unnecessarily, as it ends up being the array again...
            EffectorUtils.prepareArgsForEffectorAsMapFromArray(effector, args));
}