org.apache.brooklyn.util.core.config.ConfigBag Java Examples

The following examples show how to use org.apache.brooklyn.util.core.config.ConfigBag. 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: SoftwareProcessDriverLifecycleEffectorTasks.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void restart(ConfigBag parameters) {
    RestartMachineMode isRestartMachine = parameters.get(RestartSoftwareParameters.RESTART_MACHINE_TYPED);
    if (isRestartMachine==null) 
        isRestartMachine=RestartMachineMode.AUTO;
    if (isRestartMachine==RestartMachineMode.AUTO) 
        isRestartMachine = getDefaultRestartStopsMachine() ? RestartMachineMode.TRUE : RestartMachineMode.FALSE; 

    if (isRestartMachine==RestartMachineMode.TRUE) {
        log.debug("restart of "+entity()+" requested be applied at machine level");
        super.restart(parameters);
        return;
    }
    
    DynamicTasks.queue("pre-restart", new PreRestartTask());

    log.debug("restart of "+entity()+" appears to have driver and hostname - doing driver-level restart");
    entity().getDriver().restart();
    
    restartChildren(parameters);
    
    DynamicTasks.queue("post-restart", new PostRestartTask());
}
 
Example #2
Source File: JcloudsMachineNamerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateGroupIdInVcloud() {
    ConfigBag cfg = new ConfigBag()
        .configure(JcloudsLocationConfig.CLOUD_PROVIDER, "vcloud")
        .configure(JcloudsLocationConfig.CALLER_CONTEXT, "!mycontext!");
    
    String result = new JcloudsMachineNamer().generateNewGroupId(cfg);
    
    log.info("test mycontext vcloud group id gives: "+result);
    // brooklyn-user-!mycontext!-1234
    // br-<code>-<user>-myco-1234
    Assert.assertTrue(result.length() <= 24-4-1, "result: "+result);
    
    String user = System.getProperty("user.name");
    String userExt = Strings.maxlen(user, 2).toLowerCase();
    
    // Username can be omitted if it is longer than the rules defined in BasicCloudMachineNamer()
    if (user.length() <= 4) { 
        // (length 2 will happen if user is brooklyn, to avoid brooklyn-brooklyn at start!)
        Assert.assertTrue(result.indexOf(userExt) >= 0);
    }
    Assert.assertTrue(result.indexOf("-myc") >= 0);
}
 
Example #3
Source File: Winrm4jTool.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public Winrm4jTool(ConfigBag config) {
    this.bag = checkNotNull(config, "config bag");
    host = getRequiredConfig(config, PROP_HOST);
    port = config.get(PROP_PORT);
    useSecureWinrm = config.get(USE_HTTPS_WINRM);
    authenticationScheme = config.get(USE_NTLM) ? AuthSchemes.NTLM : null;
    computerName = Strings.isNonBlank(config.get(COMPUTER_NAME)) ? config.get(COMPUTER_NAME) : null;
    user = getRequiredConfig(config, PROP_USER);
    password = getRequiredConfig(config, PROP_PASSWORD);
    execTries = getRequiredConfig(config, PROP_EXEC_TRIES);
    execRetryDelay = getRequiredConfig(config, PROP_EXEC_RETRY_DELAY);
    logCredentials = getRequiredConfig(config, LOG_CREDENTIALS);
    operationTimeout = config.get(OPERATION_TIMEOUT);
    retriesOfNetworkFailures = config.get(RETRIES_OF_NETWORK_FAILURES);
    environment = config.get(ENVIRONMENT);
}
 
Example #4
Source File: FunctionSensorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testFunction() throws Exception {
    AtomicReference<String> val = new AtomicReference<String>("first");
    Callable<String> callable = new Callable<String>() {
        @Override public String call() throws Exception {
            return val.get();
        }
    };
    
    FunctionSensor<Integer> initializer = new FunctionSensor<Integer>(ConfigBag.newInstance()
            .configure(FunctionSensor.SENSOR_PERIOD, Duration.millis(10))
            .configure(FunctionSensor.SENSOR_NAME, SENSOR_STRING.getName())
            .configure(FunctionSensor.SENSOR_TYPE, STRING_TARGET_TYPE)
            .configure(FunctionSensor.FUNCTION, callable));
    initializer.apply(entity);
    entity.sensors().set(Attributes.SERVICE_UP, true);
    
    initializer.apply(entity);
    entity.sensors().set(Attributes.SERVICE_UP, true);

    EntityAsserts.assertAttributeEqualsEventually(entity, SENSOR_STRING, "first");
    
    val.set("second");
    EntityAsserts.assertAttributeEqualsEventually(entity, SENSOR_STRING, "second");
}
 
Example #5
Source File: AbstractJcloudsStubYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected Entity createAndStartApplication(Reader input) throws Exception {
    AssemblyTemplate at = platform.pdp().registerDeploymentPlan(input);
    Assembly assembly;
    try {
        assembly = at.getInstantiator().newInstance().instantiate(at, platform);
    } catch (Exception e) {
        LOG.warn("Unable to instantiate " + at + " (rethrowing): " + e);
        throw e;
    }
    LOG.info("Test - created " + assembly);
    final Entity app = mgmt().getEntityManager().getEntity(assembly.getId());
    LOG.info("App - " + app);
    
    // wait for app to have started
    Set<Task<?>> tasks = mgmt().getExecutionManager().getTasksWithAllTags(ImmutableList.of(
            BrooklynTaskTags.EFFECTOR_TAG, 
            BrooklynTaskTags.tagForContextEntity(app), 
            BrooklynTaskTags.tagForEffectorCall(app, "start", ConfigBag.newInstance(ImmutableMap.of("locations", ImmutableMap.of())))));
    Iterables.getOnlyElement(tasks).get();
    
    return app;
}
 
Example #6
Source File: HttpRequestSensorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups="Integration")
@SuppressWarnings("deprecation")
public void testHttpSensorSuppressingDuplicates() throws Exception {
    RecordingSensorEventListener<String> listener = new RecordingSensorEventListener<>();
    entity.subscriptions().subscribe(entity, SENSOR_STRING, listener);
    
    HttpRequestSensor<Integer> sensor = new HttpRequestSensor<Integer>(ConfigBag.newInstance()
            .configure(HttpRequestSensor.SUPPRESS_DUPLICATES, true)
            .configure(HttpRequestSensor.SENSOR_PERIOD, Duration.millis(1))
            .configure(HttpRequestSensor.SENSOR_NAME, SENSOR_STRING.getName())
            .configure(HttpRequestSensor.SENSOR_TYPE, STRING_TARGET_TYPE)
            .configure(HttpRequestSensor.JSON_PATH, "$.myKey")
            .configure(HttpRequestSensor.SENSOR_URI, serverUrl + "/myKey/myValue"));
    sensor.apply((org.apache.brooklyn.api.entity.EntityLocal)entity);
    entity.sensors().set(Attributes.SERVICE_UP, true);

    EntityAsserts.assertAttributeEqualsEventually(entity, SENSOR_STRING, "myValue");
    listener.assertHasEventEventually(Predicates.alwaysTrue());
    
    Asserts.succeedsContinually(new Runnable() {
        @Override public void run() {
            listener.assertEventCount(1);
        }});
}
 
Example #7
Source File: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected ConfigBag extractWinrmConfig(ConfigBag setup, ConfigBag alt) {
    ConfigBag winrmConfig = new ConfigBag();
    
    for (HasConfigKey<?> key : WinRmMachineLocation.ALL_WINRM_CONFIG_KEYS) {
        String keyName = key.getConfigKey().getName();
        if (setup.containsKey(keyName)) {
            winrmConfig.putStringKey(keyName, setup.getStringKey(keyName));
        } else if (alt.containsKey(keyName)) {
            winrmConfig.putStringKey(keyName, setup.getStringKey(keyName));
        }
    }
    
    Map<String, Object> winrmToolClassProperties = Maps.filterKeys(setup.getAllConfig(), StringPredicates.startsWith(WinRmMachineLocation.WINRM_TOOL_CLASS_PROPERTIES_PREFIX));
    winrmConfig.putAll(winrmToolClassProperties);
    
    return winrmConfig;
}
 
Example #8
Source File: CompositeEffectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompositeEffectorWithStopNameAndOverriding() throws InterruptedException {
   server.enqueue(jsonResponse("test.json"));

   HttpCommandEffector httpCommandEffector = new HttpCommandEffector(ConfigBag.newInstance()
           .configure(HttpCommandEffector.EFFECTOR_NAME, EFFECTOR_HTTP_COMMAND.getName())
           .configure(HttpCommandEffector.EFFECTOR_URI, url("/get?login=myLogin"))
           .configure(HttpCommandEffector.EFFECTOR_HTTP_VERB, "GET")
           .configure(HttpCommandEffector.JSON_PATH, "$.args.login")
   );
   assertNotNull(httpCommandEffector);
   compositeEffector = new CompositeEffector(ConfigBag.newInstance()
           .configure(CompositeEffector.EFFECTOR_NAME, "stop")
           .configure(CompositeEffector.OVERRIDE, true)
           .configure(CompositeEffector.EFFECTORS, ImmutableList.of(EFFECTOR_HTTP_COMMAND.getName()))
   );
   assertNotNull(compositeEffector);
   TestEntity testEntity = app.createAndManageChild(buildEntitySpec(httpCommandEffector, compositeEffector));
   List<?> results = testEntity.invoke(Effectors.effector(List.class, "stop").buildAbstract(), ImmutableMap.<String, Object>of()).getUnchecked(Duration.minutes(1));
   Asserts.assertEquals(results.size(), 1);
   assertTrue(results.get(0) instanceof String);
   Asserts.assertEquals(results.get(0), "myLogin");
}
 
Example #9
Source File: CompositeEffectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompositeEffectorWithStopName() throws InterruptedException {
   server.enqueue(jsonResponse("test.json"));

   HttpCommandEffector httpCommandEffector = new HttpCommandEffector(ConfigBag.newInstance()
           .configure(HttpCommandEffector.EFFECTOR_NAME, EFFECTOR_HTTP_COMMAND.getName())
           .configure(HttpCommandEffector.EFFECTOR_URI, url("/get?login=myLogin"))
           .configure(HttpCommandEffector.EFFECTOR_HTTP_VERB, "GET")
           .configure(HttpCommandEffector.JSON_PATH, "$.args.login")
   );
   assertNotNull(httpCommandEffector);
   compositeEffector = new CompositeEffector(ConfigBag.newInstance()
           .configure(CompositeEffector.EFFECTOR_NAME, "stop")
           .configure(CompositeEffector.EFFECTORS, ImmutableList.of(EFFECTOR_HTTP_COMMAND.getName()))
   );
   assertNotNull(compositeEffector);
   TestEntity testEntity = app.createAndManageChild(buildEntitySpec(httpCommandEffector, compositeEffector));
   List<?> results = testEntity.invoke(Effectors.effector(List.class, "stop").buildAbstract(), ImmutableMap.<String, Object>of()).getUnchecked(Duration.minutes(1));
   Asserts.assertEquals(results.size(), 2);
   assertTrue(results.get(0) instanceof String);
   Asserts.assertEquals(results.get(0), "myLogin");
   assertNull(results.get(1));
}
 
Example #10
Source File: NetworkingEffectors.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<SecurityGroup> call(ConfigBag parameters) {
    List<String> rawPortRules = parameters.get(INBOUND_PORTS_LIST);
    IpProtocol ipProtocol = parameters.get(INBOUND_PORTS_LIST_PROTOCOL);
    Preconditions.checkNotNull(ipProtocol, INBOUND_PORTS_LIST_PROTOCOL.getName() + " cannot be null");
    Preconditions.checkNotNull(rawPortRules, INBOUND_PORTS_LIST.getName() + " cannot be null");

    SharedLocationSecurityGroupCustomizer locationSecurityGroupCustomizer = new SharedLocationSecurityGroupCustomizer();
    if (IpProtocol.TCP.equals(ipProtocol)) {
        locationSecurityGroupCustomizer.setTcpPortRanges(rawPortRules);
    } else if (IpProtocol.UDP.equals(ipProtocol)) {
        locationSecurityGroupCustomizer.setUdpPortRanges(rawPortRules);
    } else if (IpProtocol.ICMP.equals(ipProtocol)) {
        locationSecurityGroupCustomizer.setOpenIcmp(true);
    }

    Optional<Location> jcloudsMachineLocationOptional = tryFind(
            (Iterable<Location>) getLocationsCheckingAncestors(null, entity()),
            instanceOf(JcloudsMachineLocation.class));
    if (!jcloudsMachineLocationOptional.isPresent()) {
        throw new IllegalArgumentException("Tried to execute open ports effector on an entity with no JcloudsMachineLocation");
    }
    JcloudsLocation jcloudsLocation = ((JcloudsMachineLocation)jcloudsMachineLocationOptional.get()).getParent();

    return locationSecurityGroupCustomizer.applySecurityGroupCustomizations(jcloudsLocation, jcloudsLocation.getComputeService(),(JcloudsMachineLocation)jcloudsMachineLocationOptional.get());
}
 
Example #11
Source File: SetHostnameCustomizerLiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Live"})
public void testSetFixedHostname() throws Exception {
    SetHostnameCustomizer customizer = new SetHostnameCustomizer(ConfigBag.newInstance()
            .configure(SetHostnameCustomizer.FIXED_HOSTNAME, "myhostname"));
    
    MachineEntity entity = app.createAndManageChild(EntitySpec.create(MachineEntity.class)
            .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true)
            .configure(MachineEntity.PROVISIONING_PROPERTIES.subKey(JcloudsLocation.MACHINE_LOCATION_CUSTOMIZERS.getName()), ImmutableSet.of(customizer))
            .configure(MachineEntity.PROVISIONING_PROPERTIES.subKey(JcloudsLocation.IMAGE_ID.getName()), PROVIDER_IMAGE_ID));


    app.start(ImmutableList.of(loc));
    
    SshMachineLocation machine = Machines.findUniqueMachineLocation(entity.getLocations(), SshMachineLocation.class).get();
    
    assertEquals(getHostname(machine), "myhostname");
}
 
Example #12
Source File: LocationConfigUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")  // requires ~/.ssh/id_rsa
public void testReadsPublicKeyFileWithTildePath() throws Exception {
    ConfigBag config = ConfigBag.newInstance();
    config.put(LocationConfigKeys.PUBLIC_KEY_FILE, SSH_PUBLIC_KEY_FILE_WITH_TILDE);
    
    // don't mind if it has a passphrase
    String data = LocationConfigUtils.getOsCredential(config).doKeyValidation(false).getPublicKeyData();
    assertTrue(data != null && data.length() > 0);
}
 
Example #13
Source File: HttpCommandEffectorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = NullPointerException.class)
public void testMissingURI() {
   httpCommandEffector = new HttpCommandEffector(ConfigBag.newInstance()
           .configure(HttpCommandEffector.EFFECTOR_NAME, EFFECTOR_HTTP_COMMAND.getName())
           .configure(HttpCommandEffector.EFFECTOR_HTTP_VERB, "GET")
   );
}
 
Example #14
Source File: BrooklynClusterUpgradeEffectorBody.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Void call(ConfigBag parameters) {
    if (!upgradeInProgress.compareAndSet(false, true)) {
        throw new IllegalStateException("An upgrade is already in progress.");
    }

    EntitySpec<?> origMemberSpec = entity().getConfig(BrooklynCluster.MEMBER_SPEC);
    Preconditions.checkNotNull(origMemberSpec, BrooklynCluster.MEMBER_SPEC.getName() + " is required for " + UpgradeClusterEffector.class.getName());

    log.debug("Upgrading "+entity()+", changing "+BrooklynCluster.MEMBER_SPEC+" from "+origMemberSpec+" / "+origMemberSpec.getConfig());

    boolean success = false;
    try {
        String newDownloadUrl = parameters.get(DOWNLOAD_URL);
        
        EntitySpec<?> newMemberSpec = EntitySpec.create(origMemberSpec);
        
        ConfigBag newConfig = ConfigBag.newInstance();
        newConfig.putIfNotNull(DOWNLOAD_URL, newDownloadUrl);
        newConfig.put(BrooklynNode.DISTRO_UPLOAD_URL, inferUploadUrl(newDownloadUrl));
        newConfig.putAll(ConfigBag.newInstance(parameters.get(EXTRA_CONFIG)).getAllConfigAsConfigKeyMap());
        newMemberSpec.configure(newConfig.getAllConfigAsConfigKeyMap());
        
        entity().config().set(BrooklynCluster.MEMBER_SPEC, newMemberSpec);
        
        log.debug("Upgrading "+entity()+", new "+BrooklynCluster.MEMBER_SPEC+": "+newMemberSpec+" / "+newMemberSpec.getConfig()+" (adding: "+newConfig+")");
        
        upgrade(parameters);

        success = true;
    } finally {
        if (!success) {
            log.debug("Upgrading "+entity()+" failed, will rethrow after restoring "+BrooklynCluster.MEMBER_SPEC+" to: "+origMemberSpec);
            entity().config().set(BrooklynCluster.MEMBER_SPEC, origMemberSpec);
        }
        
        upgradeInProgress.set(false);
    }
    return null;
}
 
Example #15
Source File: BrooklynImageChooser.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to clone the given item for use with the given {@link ConfigBag}, if
 * the item is {@link ConfigAwareChooser}; otherwise it returns the item unchanged.
 */
@SuppressWarnings("unchecked")
public static <T> T cloneFor(T item, ConfigBag service) {
    if (item instanceof ConfigAwareChooser) {
        return ((ConfigAwareChooser<T>)item).cloneFor(service);
    }
    return item;
}
 
Example #16
Source File: DefaultAzureArmNetworkCreatorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testNetworkInConfig() throws Exception {
    ConfigBag configBag = ConfigBag.newInstance();
    configBag.put(CLOUD_REGION_ID, TEST_LOCATION);
    configBag.put(NETWORK_NAME, TEST_NETWORK_NAME);

    runAssertingNoInteractions(configBag);
}
 
Example #17
Source File: FunctionSensor.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(final EntityLocal entity) {
    super.apply(entity);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Adding HTTP JSON sensor {} to {}", name, entity);
    }

    final ConfigBag allConfig = ConfigBag.newInstanceCopying(this.params).putAll(params);
    
    final Callable<?> function = EntityInitializers.resolve(allConfig, FUNCTION);
    final Boolean suppressDuplicates = EntityInitializers.resolve(allConfig, SUPPRESS_DUPLICATES);
    final Duration logWarningGraceTimeOnStartup = EntityInitializers.resolve(allConfig, LOG_WARNING_GRACE_TIME_ON_STARTUP);
    final Duration logWarningGraceTime = EntityInitializers.resolve(allConfig, LOG_WARNING_GRACE_TIME);

    FunctionPollConfig<?, T> pollConfig = new FunctionPollConfig<Object, T>(sensor)
            .callable(function)
            .onFailureOrException(Functions.constant((T) null))
            .suppressDuplicates(Boolean.TRUE.equals(suppressDuplicates))
            .logWarningGraceTimeOnStartup(logWarningGraceTimeOnStartup)
            .logWarningGraceTime(logWarningGraceTime)
            .period(period);

    FunctionFeed feed = FunctionFeed.builder().entity(entity)
            .poll(pollConfig)
            .build();

    entity.addFeed(feed);
}
 
Example #18
Source File: DefaultConnectivityResolverTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Tests behaviour when no desired addresses are available.
 */
@Test(dataProvider = "fallibleModes", expectedExceptions = IllegalStateException.class)
public void testModeUnavailable(NetworkMode mode, Set<HostAndPort> reachableIps) throws Exception {
    final DefaultConnectivityResolver customizer = new DefaultConnectivityResolver(ImmutableMap.of(
            DefaultConnectivityResolver.NETWORK_MODE, mode,
            DefaultConnectivityResolver.CHECK_CREDENTIALS, false));

    initNodeCreatorAndJcloudsLocation(newNodeCreator(), ImmutableMap.of(
            JcloudsLocationConfig.CONNECTIVITY_RESOLVER, customizer));

    ConnectivityResolverOptions options = newResolveOptionsForIps(reachableIps, Duration.ONE_MILLISECOND).build();
    ConfigBag configBag = jcloudsLocation.config().getBag();
    customizer.resolve(jcloudsLocation, newNodeMetadata(), configBag, options);
}
 
Example #19
Source File: AbstractComputeServiceRegistry.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * returns the jclouds modules user has specified using {@link JcloudsLocationConfig#COMPUTE_SERVICE_MODULES}
 */
protected Iterable<? extends Module> userDefinedModules(ConfigBag conf) {
    Iterable<Module> optionalModules = Collections.EMPTY_SET;
    if (conf.containsKey(JcloudsLocationConfig.COMPUTE_SERVICE_MODULES)) {
        optionalModules = Iterables.concat(optionalModules, conf.get(JcloudsLocationConfig.COMPUTE_SERVICE_MODULES));
    }
    return optionalModules;
}
 
Example #20
Source File: HttpCommandEffectorHttpBinTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpEffectorWithJsonPath() throws Exception {
    new HttpCommandEffector(ConfigBag.newInstance()
            .configure(HttpCommandEffector.EFFECTOR_NAME, "Httpbin")
            .configure(HttpCommandEffector.EFFECTOR_URI, serverUrl + "/get?id=myId")
            .configure(HttpCommandEffector.EFFECTOR_HTTP_VERB, "GET")
            .configure(HttpCommandEffector.JSON_PATH, "$.args.id")
    ).apply(entity);

    String val = entity.invoke(EFFECTOR_HTTPBIN, MutableMap.<String,String>of()).get();
    Assert.assertEquals(val, "myId");
}
 
Example #21
Source File: CloudMachineNamerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateNewMachineUniqueNameFromGroupId() {
    TestApplication app = mgmt.getEntityManager().createEntity(EntitySpec.create(TestApplication.class).displayName("TistApp"));
    TestEntity child = app.createAndManageChild(EntitySpec.create(TestEntity.class).displayName("TestEnt"));

    ConfigBag cfg = new ConfigBag()
        .configure(CloudLocationConfig.CALLER_CONTEXT, child);
    CloudMachineNamer namer = new BasicCloudMachineNamer();
    
    String groupId = namer.generateNewGroupId(cfg);
    String result = namer.generateNewMachineUniqueNameFromGroupId(cfg, groupId);
    Assert.assertTrue(result.startsWith(groupId));
    Assert.assertTrue(result.length() == groupId.length() + 5);
}
 
Example #22
Source File: RebindEntityDynamicTypeInfoTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(enabled=false)
public void testRestoresEffectorAnonymousClass() throws Exception {
    origApp.getMutableEntityType().addEffector(Effectors.effector(String.class, "say_hi")
        .parameter(SayHiBody.NAME_KEY)
        .description("says hello")
        .impl(new EffectorBody<String>() {
            @Override
            public String call(ConfigBag parameters) {
                return "hello "+parameters.get(SayHiBody.NAME_KEY);
            }
        }).build());
    checkEffectorWithRebind();
    
}
 
Example #23
Source File: BrooklynNodeImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Map<String,Object> asMap(ConfigBag parameters, ConfigKey<?> key) {
    Object v = parameters.getStringKey(key.getName());
    if (v==null || (v instanceof String && Strings.isBlank((String)v)))
        return null;
    if (v instanceof Map) 
        return (Map<String, Object>) v;
    
    if (v instanceof String) {
        // TODO ideally, parse YAML 
        return new Gson().fromJson((String)v, Map.class);
    }
    throw new IllegalArgumentException("Invalid "+JavaClassNames.simpleClassName(v)+" value for "+key+": "+v);
}
 
Example #24
Source File: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Map<String,Object> extractSshConfig(ConfigBag setup, NodeMetadata node) {
    ConfigBag nodeConfig = new ConfigBag();
    if (node!=null && node.getCredentials() != null) {
        nodeConfig.putIfNotNull(PASSWORD, node.getCredentials().getOptionalPassword().orNull());
        nodeConfig.putIfNotNull(PRIVATE_KEY_DATA, node.getCredentials().getOptionalPrivateKey().orNull());
    }
    return extractSshConfig(setup, nodeConfig).getAllConfig();
}
 
Example #25
Source File: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * The preferredAddress is returned if it is one of the best choices (e.g. if non-local privateAddresses 
 * contains it, or if privateAddresses.isEmpty but the publicAddresses contains it).
 * 
 * Otherwise, returns the first publicAddress (if any), or failing that the first privateAddress.
 */
private String getPrivateHostnameGeneric(NodeMetadata node, @Nullable ConfigBag setup, Optional<String> preferredAddress) {
    //prefer the private address to the hostname because hostname is sometimes wrong/abbreviated
    //(see that javadoc; also e.g. on rackspace/cloudstack, the hostname is not registered with any DNS).
    //Don't return local-only address (e.g. never 127.0.0.1)
    Iterable<String> privateAddresses = Iterables.filter(node.getPrivateAddresses(), new Predicate<String>() {
        @Override public boolean apply(String input) {
            return input != null && !Networking.isLocalOnly(input);
        }});
    if (!Iterables.isEmpty(privateAddresses)) {
        if (preferredAddress.isPresent() && Iterables.contains(privateAddresses, preferredAddress.get())) {
            return preferredAddress.get();
        }
        return Iterables.get(privateAddresses, 0);
    }
    
    if (groovyTruth(node.getPublicAddresses())) {
        if (preferredAddress.isPresent() && node.getPublicAddresses().contains(preferredAddress.get())) {
            return preferredAddress.get();
        }
        return node.getPublicAddresses().iterator().next();
    } else if (groovyTruth(node.getHostname())) {
        return node.getHostname();
    } else {
        return null;
    }
}
 
Example #26
Source File: LocationConfigUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public void testInfersPublicKeyFileFromPrivateKeyFile() throws Exception {
    ConfigBag config = ConfigBag.newInstance();
    config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE);
    
    String data = LocationConfigUtils.getOsCredential(config).getPublicKeyData();
    assertTrue(data != null && data.length() > 0);
}
 
Example #27
Source File: BrooklynNodeImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected void preStopConfirmCustom() {
    super.preStopConfirmCustom();
    ConfigBag stopParameters = BrooklynTaskTags.getCurrentEffectorParameters();
    if (Boolean.TRUE.equals(getAttribute(BrooklynNode.WEB_CONSOLE_ACCESSIBLE)) &&
            stopParameters != null && !stopParameters.containsKey(ShutdownEffector.STOP_APPS_FIRST)) {
        Preconditions.checkState(getChildren().isEmpty(), "Can't stop instance with running applications.");
    }
}
 
Example #28
Source File: AbstractConfigMapImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** Creates an immutable copy of the config visible at this entity, local and inherited (preferring local), including those that did not match config keys */
@Deprecated
public ConfigBag getAllConfigBag() {
    ConfigBag result = putAllOwnConfigIntoSafely(ConfigBag.newInstance());
    if (getParent()!=null) {
        result.putIfAbsent(
                ((AbstractConfigMapImpl<?>)getParentInternal().config().getInternalConfigMap()).getAllConfigBag() );
    }
    return result.seal();
}
 
Example #29
Source File: DefaultAzureArmNetworkCreatorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void runAssertingNoInteractions(ConfigBag configBag) throws Exception {
    Map<String, Object> configCopy = configBag.getAllConfig();

    DefaultAzureArmNetworkCreator.createDefaultNetworkAndAddToTemplateOptionsIfRequired(computeService, configBag);

    //Ensure nothing changed, and no calls were made to the compute service
    assertEquals(configCopy, configBag.getAllConfig());
    Mockito.verifyZeroInteractions(computeService);
}
 
Example #30
Source File: SshCommandEffectorIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")
public void testSshEffector() throws Exception {
    new SshCommandEffector(ConfigBag.newInstance()
            .configure(SshCommandEffector.EFFECTOR_NAME, "sayHi")
            .configure(SshCommandEffector.EFFECTOR_COMMAND, "echo hi"))
        .apply(entity);
    
    String val = entity.invoke(EFFECTOR_SAY_HI, MutableMap.<String,String>of()).get();
    Assert.assertEquals(val.trim(), "hi", "val="+val);
}