Java Code Examples for org.apache.brooklyn.util.text.Strings#isBlank()

The following examples show how to use org.apache.brooklyn.util.text.Strings#isBlank() . 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: CatalogUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static BrooklynClassLoadingContext getClassLoadingContext(Entity entity) {
    ManagementContext mgmt = ((EntityInternal)entity).getManagementContext();
    String catId = entity.getCatalogItemId();
    if (Strings.isBlank(catId)) return JavaBrooklynClassLoadingContext.create(mgmt);
    Maybe<RegisteredType> cat = RegisteredTypes.tryValidate(mgmt.getTypeRegistry().get(catId), RegisteredTypeLoadingContexts.spec(Entity.class));
    if (cat.isNull()) {
        log.warn("Cannot load "+catId+" to get classloader for "+entity+"; will try with standard loader, but might fail subsequently");
        return JavaBrooklynClassLoadingContext.create(mgmt);
    }
    return newClassLoadingContext(mgmt, cat.get(), JavaBrooklynClassLoadingContext.create(mgmt));
}
 
Example 2
Source File: BundleUpgradeParser.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static VersionRangedName fromString(String val, boolean singleVersionIsOsgiRange) {
    if (Strings.isBlank(val)) {
        throw new IllegalArgumentException("Must not be blank");
    }
    String[] parts = val.split(":");
    if (parts.length > 2) {
        throw new IllegalArgumentException("Identifier '"+val+"' has too many parts; max one ':' symbol");
    }
    if (parts.length == 1 || Strings.isBlank(parts[1])) {
        throw new IllegalArgumentException("Identifier '"+val+"' must be of 'name:versionRange' syntax");
    }
    return new VersionRangedName(parts[0], parts[1], singleVersionIsOsgiRange);
}
 
Example 3
Source File: MySqlNodeImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public String getPassword() {
    String result = getAttribute(MySqlNode.PASSWORD);
    if (Strings.isBlank(result)) {
        result = Identifiers.makeRandomId(12);
        sensors().set(MySqlNode.PASSWORD, result);
    }
    return result;
}
 
Example 4
Source File: MySqlClusterImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Nullable private static String getDatabaseCreationScriptAsString(Entity entity) {
    String url = entity.getConfig(MySqlMaster.MASTER_CREATION_SCRIPT_URL);
    if (!Strings.isBlank(url))
        return new ResourceUtils(entity).getResourceAsString(url);
    String contents = entity.getConfig(MySqlMaster.MASTER_CREATION_SCRIPT_CONTENTS);
    if (!Strings.isBlank(contents))
        return contents;
    return null;
}
 
Example 5
Source File: ConfigInheritance.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** @deprecated since 0.10.0 see fromString in selected subclasses of {@link ConfigInheritance} eg BasicConfigInheritance */
public static ConfigInheritance fromString(String val) {
    if (Strings.isBlank(val)) return null;
    switch (val.toLowerCase().trim()) {
    case "none":
        return NONE;
    case "always": 
        return ALWAYS;
    case "deepmerge" :
    case "deep_merge" :
        return DEEP_MERGE;
    default:
        throw new IllegalArgumentException("Invalid config-inheritance '"+val+"' (legal values are none, always or merge)");
    }
}
 
Example 6
Source File: KubernetesClientRegistryImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected String getRelativeFile(String file, Path folder) {
    if (Strings.isBlank(file)) {
        return null;
    }
    Path path = Paths.get(file);
    if (!Files.exists(path)) {
        path = folder.resolve(file);
    }
    return path.toString();
}
 
Example 7
Source File: AsyncApplicationImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void init() {
    // Code below copied from BasicAppliationImpl.
    // Set the default name *before* calling super.init(), and only do so if we don't have an 
    // explicit default. This is a belt-and-braces fix: before we overwrote the defaultDisplayName
    // that was inferred from the catalog item name.
    if (Strings.isBlank(getConfig(DEFAULT_DISPLAY_NAME))) {
        setDefaultDisplayName("Application ("+getId()+")");
    }
    super.init();
}
 
Example 8
Source File: CouchbaseNodeImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
public void bucketCreate(String bucketName, String bucketType, Integer bucketPort, Integer bucketRamSize, Integer bucketReplica) {
    if (Strings.isBlank(bucketType)) bucketType = "couchbase";
    if (bucketRamSize==null || bucketRamSize<=0) bucketRamSize = 200;
    if (bucketReplica==null || bucketReplica<0) bucketReplica = 1;

    getDriver().bucketCreate(bucketName, bucketType, bucketPort, bucketRamSize, bucketReplica);
}
 
Example 9
Source File: AbstractOnNetworkEnricher.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void checkConfig() {
    Collection<? extends AttributeSensor<?>> sensors = getConfig(SENSORS);
    Maybe<Object> rawMapMatching = config().getRaw(MAP_MATCHING);
    String mapMatching = config().get(MAP_MATCHING);
    
    if (sensors == null || sensors.isEmpty()) {
        if (Strings.isBlank(mapMatching)) {
            throw new IllegalStateException(this+" requires 'sensors' config (when 'mapMatching' is explicitly blank)");
        }
    } else if (rawMapMatching.isPresent()) {
        throw new IllegalStateException(this+" must not have explicit 'mapMatching' and 'sensors' config");
    }
}
 
Example 10
Source File: JcloudsSshMachineLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public String getSubnetHostname() {
    if (privateHostname == null) {
        Optional<NodeMetadata> node = getOptionalNode();
        if (node.isPresent()) {
            // Prefer jcloudsLocation.getPrivateHostname(): it handles AWS hostname in a special way, 
            // by querying AWS for the hostname that resolves both inside and outside of the region.
            // If we can't get the node (i.e. the cloud provider doesn't know that id, because it has
            // been terminated), then we don't care as much about getting the right id!
            HostAndPort sshHostAndPort = getSshHostAndPort();
            Supplier<LoginCredentials> creds = getLoginCredentialsSupplier();
            privateHostname = jcloudsParent.getPrivateHostname(node.get(), Optional.of(sshHostAndPort), creds, config().getBag());

        } else {
            // Fallback: impl taken from jcloudsParent.getPrivateHostnameGeneric(NodeMetadata, ConfigBag).
            // But we won't have a node object (e.g. after rebind, and VM has been terminated).
            //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)
            for (String p : getPrivateAddresses()) {
                if (Networking.isLocalOnly(p)) continue;
                privateHostname = p;
                break;
            }
            if (Strings.isBlank(privateHostname) && groovyTruth(getPublicAddresses())) {
                privateHostname = getPublicAddresses().iterator().next();
            } else if (Strings.isBlank(privateHostname)) {
                privateHostname = getHostname();
            }
        }
        requestPersist();
        LOG.debug("Resolved subnet hostname {} for {}", privateHostname, this);
    }
    
    return privateHostname;
}
 
Example 11
Source File: BrooklynEntityMatcher.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public boolean apply(Object deploymentPlanItem, AssemblyTemplateConstructor atc) {
    if (!(deploymentPlanItem instanceof Service)) return false;
    
    String type = lookupType(deploymentPlanItem);
    if (type==null) return false;

    log.trace("Item {} being instantiated with {}", deploymentPlanItem, type);

    Object old = atc.getInstantiator();
    if (old!=null && !old.equals(BrooklynAssemblyTemplateInstantiator.class)) {
        log.warn("Can't mix Brooklyn entities with non-Brooklyn entities (at present): "+old);
        return false;
    }

    // TODO should we build up a new type, BrooklynEntityComponentTemplate here
    // complete w EntitySpec -- ie merge w BrooklynComponentTemplateResolver ?
    
    Builder<? extends PlatformComponentTemplate> builder = PlatformComponentTemplate.builder();
    builder.type( type.indexOf(':')==-1 ? "brooklyn:"+type : type );
    
    // currently instantiator must be brooklyn at the ATC level
    // optionally would be nice to support multiple/mixed instantiators, 
    // ie at the component level, perhaps with the first one responsible for building the app
    atc.instantiator(BrooklynAssemblyTemplateInstantiator.class);

    String name = ((Service)deploymentPlanItem).getName();
    if (!Strings.isBlank(name)) builder.name(name);
    
    // configuration
    Map<String, Object> attrs = MutableMap.copyOf( ((Service)deploymentPlanItem).getCustomAttributes() );

    if (attrs.containsKey("id"))
        builder.customAttribute("planId", attrs.remove("id"));

    Object location = attrs.remove("location");
    if (location!=null)
        builder.customAttribute("location", location);
    Object locations = attrs.remove("locations");
    if (locations!=null)
        builder.customAttribute("locations", locations);
    Object iconUrl = attrs.remove(BrooklynConfigKeys.ICON_URL.getName());
    if (iconUrl!=null)
        builder.customAttribute(BrooklynConfigKeys.ICON_URL.getName(), iconUrl);

    MutableMap<Object, Object> brooklynFlags = MutableMap.of();
    Object origBrooklynFlags = attrs.remove(BrooklynCampReservedKeys.BROOKLYN_FLAGS);
    if (origBrooklynFlags!=null) {
        if (!(origBrooklynFlags instanceof Map))
            throw new IllegalArgumentException("brooklyn.flags must be a map of brooklyn flags");
        brooklynFlags.putAll((Map<?,?>)origBrooklynFlags);
    }

    addCustomMapAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_CONFIG);
    addCustomListAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_POLICIES);
    addCustomListAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_ENRICHERS);
    addCustomListAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_INITIALIZERS);
    addCustomListAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_CHILDREN);
    addCustomListAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_PARAMETERS);
    addCustomMapAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_CATALOG);
    addCustomListAttributeIfNonNull(builder, attrs, BrooklynCampReservedKeys.BROOKLYN_TAGS);

    brooklynFlags.putAll(attrs);
    if (!brooklynFlags.isEmpty()) {
        builder.customAttribute(BrooklynCampReservedKeys.BROOKLYN_FLAGS, brooklynFlags);
    }

    atc.add(builder.build());

    return true;
}
 
Example 12
Source File: BrooklynComponentTemplateResolver.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends Entity> void populateSpec(EntitySpec<T> spec, Set<String> encounteredRegisteredTypeIds) {
    String name, source=null, templateId=null, planId=null;
    if (template.isPresent()) {
        name = template.get().getName();
        templateId = template.get().getId();
        source = template.get().getSourceCode();
    } else {
        name = (String)attrs.getStringKey("name");
    }
    planId = (String)attrs.getStringKey("id");
    if (planId==null)
        planId = (String) attrs.getStringKey(BrooklynCampConstants.PLAN_ID_FLAG);

    Object childrenObj = attrs.getStringKey(BrooklynCampReservedKeys.BROOKLYN_CHILDREN);
    if (childrenObj != null) {
        Iterable<Map<String,?>> children = (Iterable<Map<String,?>>)childrenObj;
        for (Map<String,?> childAttrs : children) {
            BrooklynComponentTemplateResolver entityResolver = BrooklynComponentTemplateResolver.Factory.newInstance(loader, childAttrs);
            // encounteredRegisteredTypeIds must contain the items currently being loaded (the dependency chain),
            // but not parent items in this type already resolved (this is because an item's definition should
            // not include itself here, as a defined child, as that would create an endless loop; 
            // use in a member spec is fine)
            EntitySpec<? extends Entity> childSpec = entityResolver.resolveSpec(encounteredRegisteredTypeIds);
            spec.child(EntityManagementUtils.unwrapEntity(childSpec));
        }
    }

    if (source!=null) {
        spec.tag(BrooklynTags.newYamlSpecTag(source));
    }

    if (!Strings.isBlank(name))
        spec.displayName(name);
    if (templateId != null)
        spec.configure(BrooklynCampConstants.TEMPLATE_ID, templateId);
    if (planId != null)
        spec.configure(BrooklynCampConstants.PLAN_ID, planId);

    List<LocationSpec<?>> locations = new BrooklynYamlLocationResolver(mgmt).resolveLocations(attrs.getAllConfig(), true);
    if (locations != null) {
        // override locations defined in the type if locations are specified here
        // empty list can be used by caller to clear, so they are inherited
        spec.clearLocations();
        spec.locationSpecs(locations);
    }

    decorateSpec(spec, encounteredRegisteredTypeIds);
}
 
Example 13
Source File: BrooklynNodeUpgradeEffectorBody.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private String dryRunUpdate(ConfigBag parameters) {
    // TODO require entity() node state master or hot standby AND require persistence enabled, or a new 'force_attempt_upgrade' parameter to be applied
    // TODO could have a 'skip_dry_run_upgrade' parameter
    // TODO could support 'dry_run_only' parameter, with optional resumption tasks (eg new dynamic effector)

    // 1 add new brooklyn version entity as child (so uses same machine), with same config apart from things in parameters
    final Entity dryRunChild = entity().addChild(createDryRunSpec()
        .displayName("Upgraded Version Dry-Run Node")
        // install dir and label are recomputed because they are not inherited, and download_url will normally be different
        .configure(parameters.getAllConfig()));

    //force this to start as hot-standby
    // TODO alternatively could use REST API as in BrooklynClusterUpgradeEffectorBody
    // TODO Want better way to append to the config (so can do it all in the spec)
    String launchParameters = dryRunChild.getConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS);
    if (Strings.isBlank(launchParameters)) launchParameters = "";
    else launchParameters += " ";
    launchParameters += "--highAvailability "+HighAvailabilityMode.HOT_STANDBY;
    ((EntityInternal)dryRunChild).config().set(BrooklynNode.EXTRA_LAUNCH_PARAMETERS, launchParameters);

    final String dryRunNodeUid = dryRunChild.getId();
    ((EntityInternal)dryRunChild).setDisplayName("Dry-Run Upgraded Brooklyn Node ("+dryRunNodeUid+")");

    DynamicTasks.queue(Effectors.invocation(dryRunChild, BrooklynNode.START, ConfigBag.EMPTY));

    // 2 confirm hot standby status
    DynamicTasks.queue(EntityTasks.requiringAttributeEventually(dryRunChild, BrooklynNode.MANAGEMENT_NODE_STATE, 
        Predicates.equalTo(ManagementNodeState.HOT_STANDBY), Duration.FIVE_MINUTES));

    // 3 stop new version
    DynamicTasks.queue(Tasks.builder().displayName("shutdown transient node")
        .add(Effectors.invocation(dryRunChild, BrooklynNode.STOP_NODE_BUT_LEAVE_APPS, ImmutableMap.of(StopSoftwareParameters.STOP_MACHINE_MODE, StopMode.NEVER)))
        .build());

    DynamicTasks.queue(Tasks.<Void>builder().displayName("remove transient node").body(
        new Runnable() {
            @Override
            public void run() {
                Entities.unmanage(dryRunChild);
            }
        }
    ).build());

    return dryRunChild.getId();
}
 
Example 14
Source File: MaxMind2HostGeoLookup.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public HostGeoInfo getHostGeoInfo(InetAddress address) throws MalformedURLException, IOException {
    if (lookupFailed) return null;
    
    DatabaseReader ll = getDatabaseReader();
    if (ll==null) return null;
    
    InetAddress extAddress = address;
    if (Networking.isPrivateSubnet(extAddress)) extAddress = InetAddress.getByName(LocalhostExternalIpLoader.getLocalhostIpQuicklyOrDefault());
    
    try {
        CityResponse l = ll.city(extAddress);
        if (l==null) {
            if (log.isDebugEnabled()) log.debug("Geo info failed to find location for address {}, using {}", extAddress, ll);
            return null;
        }
        
        StringBuilder name = new StringBuilder();
        
        if (l.getCity()!=null && l.getCity().getName()!=null) name.append(l.getCity().getName());
        
        if (l.getSubdivisions()!=null) {
            for (Subdivision subd: Lists.reverse(l.getSubdivisions())) {
                if (name.length()>0) name.append(", ");
                // prefer e.g. USA state codes over state names
                if (!Strings.isBlank(subd.getIsoCode())) 
                    name.append(subd.getIsoCode());
                else
                    name.append(subd.getName());
            }
        }
        
        if (l.getCountry()!=null) {
            if (name.length()==0) {
                name.append(l.getCountry().getName());
            } else {
                name.append(" ("); name.append(l.getCountry().getIsoCode()); name.append(")");
            }
        }

        
        HostGeoInfo geo = new HostGeoInfo(address.getHostName(), name.toString(), l.getLocation().getLatitude(), l.getLocation().getLongitude());
        log.debug("Geo info lookup (MaxMind DB) for "+address+" returned: "+geo);
        return geo;
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Geo info lookup failed: "+e);
        throw Throwables.propagate(e);
    }
}
 
Example 15
Source File: BasicDownloadsManager.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private DownloadResolver newDownloader(DownloadRequirement req) {
    // Infer filename
    String filename = null;
    for (Function<? super DownloadRequirement, String> filenameProducer : filenameProducers) {
        filename = filenameProducer.apply(req);
        if (!Strings.isBlank(filename)) break;
    }
    
    // If a filename-producer has given us the filename, then augment the DownloadRequirement with that
    // (so that local-repo substitutions etc can use that explicit filename)
    DownloadRequirement wrappedReq;
    if (filename == null) {
        wrappedReq = req;
    } else {
        wrappedReq = BasicDownloadRequirement.copy(req, ImmutableMap.of("filename", filename));
    }
    
    // Get ordered download targets to be tried
    List<String> primaries = Lists.newArrayList();
    List<String> fallbacks = Lists.newArrayList();
    for (Function<? super DownloadRequirement, ? extends DownloadTargets> producer : producers) {
        DownloadTargets vals = producer.apply(wrappedReq);
        primaries.addAll(vals.getPrimaryLocations());
        fallbacks.addAll(vals.getFallbackLocations());
        if (!vals.canContinueResolving()) {
            break;
        }
    }

    Set<String> result = Sets.newLinkedHashSet();
    result.addAll(primaries);
    result.addAll(fallbacks);

    if (result.isEmpty()) {
        throw new IllegalArgumentException("No downloads matched for "+req);
    }
    
    // If filename-producers didn't give any explicit filename, then infer from download results
    if (filename == null) {
        for (String target : result) {
            filename = FilenameProducers.inferFilename(target);
            if (!Strings.isBlank(filename)) break;
        }
    }
    if (Strings.isBlank(filename)) {
        throw new IllegalArgumentException("No filenames matched for "+req+" (targets "+result+")");
    }
    
    // And return the result
    return new BasicDownloadResolver(result, filename);
}
 
Example 16
Source File: BrooklynYamlLocationResolver.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/** resolves the location from the given spec string, either "Named Location", or "named:Named Location" format;
 * returns null if input is blank (or null); otherwise guaranteed to resolve or throw error */
public LocationSpec<?> resolveLocationFromString(String location) {
    if (Strings.isBlank(location)) return null;
    return resolveLocation(location, MutableMap.of());
}
 
Example 17
Source File: LocationsYamlTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static void assertUserAddress(MachineLocation l, String user, String address) {
    Assert.assertEquals(l.getAddress().getHostAddress(), address);
    if (!Strings.isBlank(user)) Assert.assertEquals(((SshMachineLocation)l).getUser(), user);        
}
 
Example 18
Source File: ServerPoolLocationResolver.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public LocationSpec newLocationSpecFromString(String spec, Map locationFlags, LocationRegistry registry) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Resolving location '" + spec + "' with flags " + Joiner.on(",").withKeyValueSeparator("=").join(locationFlags));
    }

    Matcher matcher = PATTERN.matcher(spec);
    if (!matcher.matches()) {
        String m = String.format("Invalid location '%s'; must specify either %s:entityId or %s:entityId:(key=argument)",
                spec, PREFIX, PREFIX);
        throw new IllegalArgumentException(m);
    }

    // TODO Could validate that the namePart matches the existing poolLoc
    String argsPart = matcher.group(4);
    Map<String, String> argsMap = (argsPart != null) ? KeyValueParser.parseMap(argsPart) : Collections.<String,String>emptyMap();
    @SuppressWarnings("unused")
    String namePart = argsMap.get("name");

    if (!ACCEPTABLE_ARGS.containsAll(argsMap.keySet())) {
        Set<String> illegalArgs = Sets.difference(argsMap.keySet(), ACCEPTABLE_ARGS);
        throw new IllegalArgumentException("Invalid location '"+spec+"'; illegal args "+illegalArgs+"; acceptable args are "+ACCEPTABLE_ARGS);
    }

    String poolLocId = matcher.group(2);
    if (Strings.isBlank(poolLocId)) {
        throw new IllegalArgumentException("Invalid location '"+spec+"'; pool's location id must be non-empty");
    }

    Location poolLoc = managementContext.getLocationManager().getLocation(poolLocId);
    if (poolLoc == null) {
        throw new IllegalArgumentException("Unknown ServerPool location id "+poolLocId+", spec "+spec);
    } else if (!(poolLoc instanceof ServerPoolLocation)) {
        throw new IllegalArgumentException("Invalid location id for ServerPool, spec "+spec+"; instead matches "+poolLoc);
    }

    return LocationSpec.create(ServerPoolLocation.class)
            .configure(LocationConstructor.LOCATION, poolLoc)
            .configure(Config.SPECIAL_CONSTRUCTOR, LocationConstructor.class);
}
 
Example 19
Source File: ExecWithLoggingHelpers.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public int execWithLogging(Map<String,?> props, final String summaryForLogging, final List<String> commands,
        final Map<String,?> env, String expectedCommandHeaders, final ExecRunner execCommand) {
    if (commandLogger!=null && commandLogger.isDebugEnabled()) {
        String allcmds = (Strings.isBlank(expectedCommandHeaders) ? "" : expectedCommandHeaders + " ; ") + Strings.join(commands, " ; ");
        commandLogger.debug("{}, initiating "+shortName.toLowerCase()+" on machine {}{}: {}",
                new Object[] {summaryForLogging, getTargetName(),
                env!=null && !env.isEmpty() ? " (env "+Sanitizer.sanitize(env)+")": "", allcmds});
    }

    if (commands.isEmpty()) {
        if (commandLogger!=null && commandLogger.isDebugEnabled())
            commandLogger.debug("{}, on machine {}, ending: no commands to run", summaryForLogging, getTargetName());
        return 0;
    }

    final ConfigBag execFlags = new ConfigBag().putAll(props);
    // some props get overridden in execFlags, so remove them from the tool flags
    final ConfigBag toolFlags = new ConfigBag().putAll(props).removeAll(
            LOG_PREFIX, STDOUT, STDERR, ShellTool.PROP_NO_EXTRA_OUTPUT);

    execFlags.configure(ShellTool.PROP_SUMMARY, summaryForLogging);
    
    preExecChecks();
    
    String logPrefix = execFlags.get(LOG_PREFIX);
    if (logPrefix==null) logPrefix = constructDefaultLoggingPrefix(execFlags);

    if (!execFlags.get(NO_STDOUT_LOGGING)) {
        String stdoutLogPrefix = "["+(logPrefix != null ? logPrefix+":stdout" : "stdout")+"] ";
        OutputStream outO = LoggingOutputStream.builder()
                .outputStream(execFlags.get(STDOUT))
                .logger(commandLogger)
                .logPrefix(stdoutLogPrefix)
                .build();

        execFlags.put(STDOUT, outO);
    }

    if (!execFlags.get(NO_STDERR_LOGGING)) {
        String stderrLogPrefix = "["+(logPrefix != null ? logPrefix+":stderr" : "stderr")+"] ";
        OutputStream outE = LoggingOutputStream.builder()
                .outputStream(execFlags.get(STDERR))
                .logger(commandLogger)
                .logPrefix(stderrLogPrefix)
                .build();
        execFlags.put(STDERR, outE);
    }

    Tasks.setBlockingDetails(shortName+" executing, "+summaryForLogging);
    try {
        return execWithTool(MutableMap.copyOf(toolFlags.getAllConfig()), new Function<ShellTool, Integer>() {
            @Override
            public Integer apply(ShellTool tool) {
                int result = execCommand.exec(tool, MutableMap.copyOf(execFlags.getAllConfig()), commands, env);
                if (commandLogger!=null && commandLogger.isDebugEnabled()) 
                    commandLogger.debug("{}, on machine {}, completed: return status {}",
                            new Object[] {summaryForLogging, getTargetName(), result});
                return result;
            }});

    } finally {
        Tasks.setBlockingDetails(null);
    }
}
 
Example 20
Source File: DockerJcloudsLocation.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public Template buildTemplate(ComputeService computeService, ConfigBag config, Collection<JcloudsLocationCustomizer> customizers) {
    String loginUser = config.get(JcloudsLocation.LOGIN_USER);
    String loginPassword = config.get(JcloudsLocation.LOGIN_USER_PASSWORD);
    String loginKeyFile = config.get(JcloudsLocation.LOGIN_USER_PRIVATE_KEY_FILE);
    String loginKeyData = config.get(JcloudsLocation.LOGIN_USER_PRIVATE_KEY_DATA);

    Template template = super.buildTemplate(computeService, config, customizers);
    DockerTemplateOptions templateOptions = (DockerTemplateOptions) template.getOptions();
    Image image = template.getImage();
    List<String> env = MutableList.copyOf(templateOptions.getEnv());

    // Inject login credentials, if required
    Boolean injectLoginCredentials = config.get(INJECT_LOGIN_CREDENTIAL);
    if (injectLoginCredentials == null) {
        String imageDescription = image.getDescription();
        for (String regex : IMAGE_DESCRIPTION_REGEXES_REQUIRING_INJECTED_LOGIN_CREDS) {
            if (imageDescription != null && imageDescription.matches(regex)) {
                injectLoginCredentials = true;
                break;
            }
        }
    }
    if (Strings.isBlank(loginUser) && Strings.isBlank(loginPassword) && Strings.isBlank(loginKeyFile) && Strings.isBlank(loginKeyData)) {
        if (Boolean.TRUE.equals(injectLoginCredentials)) {
            loginUser = "root";
            loginPassword = Identifiers.makeRandomPassword(12);
            templateOptions.overrideLoginUser(loginUser);
            templateOptions.overrideLoginPassword(loginPassword);

            env.add("BROOKLYN_ROOT_PASSWORD=" + loginPassword);
        }
    }

    Entity context = validateCallerContext(config);
    Map<String, Object> containerEnv = MutableMap.copyOf(context.config().get(DockerContainer.CONTAINER_ENVIRONMENT));
    for (Map.Entry<String, String> entry : Maps.transformValues(containerEnv, Functions.toStringFunction()).entrySet()) {
        env.add(String.format("%s=%s", entry.getKey(), entry.getValue()));
    }
    templateOptions.env(env);

    return template;
}