org.apache.brooklyn.util.collections.MutableList Java Examples

The following examples show how to use org.apache.brooklyn.util.collections.MutableList. 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: Strings.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** Returns canonicalized string from the given object, made "unique" by:
 * <li> putting sets into the toString order
 * <li> appending a hash code if it's longer than the max (and the max is bigger than 0) */
public static String toUniqueString(Object x, int optionalMax) {
    if (x instanceof Iterable && !(x instanceof List)) {
        // unsorted collections should have a canonical order imposed
        MutableList<String> result = MutableList.of();
        for (Object xi: (Iterable<?>)x) {
            result.add(toUniqueString(xi, optionalMax));
        }
        Collections.sort(result);
        x = result.toString();
    }
    if (x==null) return "{null}";
    String xs = x.toString();
    if (xs.length()<=optionalMax || optionalMax<=0) return xs;
    return maxlenWithEllipsis(xs, optionalMax-8)+"/"+Integer.toHexString(xs.hashCode());
}
 
Example #2
Source File: CatalogInitialization.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void populateInitialFromUri(BasicBrooklynCatalog catalog, String catalogUrl) {
    log.debug("Loading initial catalog from {}", catalogUrl);

    try {
        String contents = new ResourceUtils(this).getResourceAsString(catalogUrl);

        catalog.reset(MutableList.<CatalogItem<?,?>>of());
        Object result = catalog.addItems(contents);
        
        log.debug("Loaded initial catalog from {}: {}", catalogUrl, result);
        
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        if (isRebindReadOnlyShuttingDown(getManagementContext())) {
            throw Exceptions.propagate(e);
        }

        log.warn("Error importing catalog from " + catalogUrl + ": " + e, e);
    }
}
 
Example #3
Source File: BasicBrooklynCatalog.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * @deprecated since 1.0.0; Catalog annotation is deprecated.
 */
@Deprecated
private Collection<CatalogItemDtoAbstract<?, ?>> scanAnnotationsLegacyInListOfLibraries(ManagementContext mgmt, Collection<? extends OsgiBundleWithUrl> libraries, Map<?, ?> catalogMetadata, ManagedBundle containingBundle) {
    CatalogDto dto = CatalogDto.newNamedInstance("Bundles Scanned Catalog", "All annotated Brooklyn entities detected in bundles", "scanning-bundles-classpath-"+libraries.hashCode());
    List<String> urls = MutableList.of();
    for (OsgiBundleWithUrl b: libraries) {
        // does not support pre-installed bundles identified by name:version 
        // (ie where URL not supplied)
        if (Strings.isNonBlank(b.getUrl())) {
            urls.add(b.getUrl());
        } else {
            log.warn("scanJavaAnnotations does not apply to pre-installed bundles; skipping "+b);
        }
    }
    
    if (urls.isEmpty()) {
        log.warn("No bundles to scan: scanJavaAnnotations currently only applies to OSGi bundles provided by URL"); 
        return MutableList.of();
    }
    
    CatalogDo subCatalog = new CatalogDo(dto);
    subCatalog.addToClasspath(urls.toArray(new String[0]));
    return scanAnnotationsInternal(mgmt, subCatalog, catalogMetadata, containingBundle);
}
 
Example #4
Source File: AbstractEntity.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void removeLocations(Collection<? extends Location> removedLocations) {
    synchronized (locations) {
        List<Location> oldLocations = locations.get();
        Set<Location> trulyRemovedLocations = Sets.intersection(ImmutableSet.copyOf(removedLocations), ImmutableSet.copyOf(oldLocations));
        locations.set(MutableList.<Location>builder().addAll(oldLocations).removeAll(removedLocations).buildImmutable());
        
        for (Location loc : trulyRemovedLocations) {
            sensors().emit(AbstractEntity.LOCATION_REMOVED, loc);
        }
    }
    
    // TODO Not calling `Entities.unmanage(removedLocation)` because this location might be shared with other entities.
    // Relying on abstractLocation.removeChildLocation unmanaging it, but not ideal as top-level locations will stick
    // around forever, even if not referenced.
    // Same goes for AbstractEntity#clearLocations().
    
    getManagementSupport().getEntityChangeListener().onLocationsChanged();
}
 
Example #5
Source File: DynamicSequentialTaskTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testChildrenRunConcurrentlyWithPrimary() {
    Task<String> t = Tasks.<String>builder().dynamic(true)
        .body(monitorableJob("main"))
        .add(monitorableTask("1")).add(monitorableTask("2")).build();
    ec.submit(t);
    releaseAndWaitForMonitorableJob("1");
    releaseAndWaitForMonitorableJob("main");
    Assert.assertFalse(t.blockUntilEnded(TINY_TIME));
    releaseMonitorableJob("2");
    
    Assert.assertTrue(t.blockUntilEnded(TIMEOUT));
    Assert.assertEquals(messages, MutableList.of("1", "main", "2"));
    Assert.assertTrue(stopwatch.elapsed(TimeUnit.MILLISECONDS) < TIMEOUT.toMilliseconds(), "took too long: "+stopwatch);
    Assert.assertFalse(t.isError());
}
 
Example #6
Source File: StartStopSshDriverTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private List<ThreadInfo> getThreadsCalling(Class<?> clazz) {
    String clazzName = clazz.getCanonicalName();
    List<ThreadInfo> result = MutableList.of();
    ThreadMXBean threadMxbean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threads = threadMxbean.dumpAllThreads(false, false);
    
    for (ThreadInfo thread : threads) {
        StackTraceElement[] stackTrace = thread.getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            if (clazzName == stackTraceElement.getClassName()) {
                result.add(thread);
                break;
            }
        }
    }
    return result;
}
 
Example #7
Source File: TaskTransformer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static List<TaskSummary> fromTasks(List<Task<?>> tasksToScan, int limit, Boolean recurse, Entity entity, UriInfo ui) {
    int sizeRemaining = limit;
    if (limit>0) {
        tasksToScan = MutableList.copyOf(Ordering.from(new InterestingTasksFirstComparator(entity)).leastOf(tasksToScan, limit));
    }
    Map<String,Task<?>> tasksLoaded = MutableMap.of();
    
    while (!tasksToScan.isEmpty()) {
        Task<?> t = tasksToScan.remove(0);
        if (tasksLoaded.put(t.getId(), t)==null) {
            if (--sizeRemaining==0) {
                break;
            }
            if (Boolean.TRUE.equals(recurse)) {
                if (t instanceof HasTaskChildren) {
                    Iterables.addAll(tasksToScan, ((HasTaskChildren) t).getChildren() );
                }
            }
        }
    }
    return new LinkedList<TaskSummary>(Collections2.transform(tasksLoaded.values(), 
        TaskTransformer.fromTask(ui.getBaseUriBuilder())));
}
 
Example #8
Source File: JcloudsBlobStoreBasedObjectStoreTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void doTestWithStore(PersistenceObjectStore objectStore) {
    log.info("testing against "+objectStore.getSummaryName());
    
    objectStore.createSubPath("foo");
    StoreObjectAccessor f = objectStore.newAccessor("foo/file1.txt");
    Assert.assertFalse(f.exists());

    Stopwatch timer = Stopwatch.createStarted();
    f.append("Hello world");
    log.info("created in "+Duration.of(timer));
    timer.reset();
    Assert.assertEquals(f.get(), "Hello world");
    log.info("retrieved in "+Duration.of(timer));
    Assert.assertTrue(f.exists());
    
    timer.reset();
    List<String> files = objectStore.listContentsWithSubPath("foo");
    log.info("list retrieved in "+Duration.of(timer)+"; is: "+files);
    Assert.assertEquals(files, MutableList.of("foo/file1.txt"));
    
    f.delete();
}
 
Example #9
Source File: MapConfigKeyAndFriendsMoreTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public void testListCollectionUsage() throws Exception {
    // passing a collection to the RHS of setConfig can be ambiguous,
    // esp if there are already values set, but attempt to act sensibly
    // (logging warnings if the set is not empty)
    entity.config().set(TestEntity.CONF_LIST_OBJ_THING, ListModifications.addItem("w"));
    entity.config().set(TestEntity.CONF_LIST_OBJ_THING, MutableList.of("x"));
    entity.config().set(TestEntity.CONF_LIST_OBJ_THING, MutableList.of("y"));
    entity.config().set(TestEntity.CONF_LIST_OBJ_THING, MutableList.of("a", "b"));
    entity.config().set(TestEntity.CONF_LIST_OBJ_THING, ListModifications.addItem("z"));
    entity.config().set(TestEntity.CONF_LIST_OBJ_THING, ListModifications.addItem(MutableList.of("c", "d")));
    entity.config().set(TestEntity.CONF_LIST_OBJ_THING, MutableList.of(MutableList.of("e", "f")));
    log.info("List-Coll: "+MutableMap.copyOf(entity.config().getLocalBag().getAllConfig()));
    List<? extends Object> list = entity.getConfig(TestEntity.CONF_LIST_OBJ_THING);
    Assert.assertEquals(list.size(), 8, "list is: "+list);
    // "a", "b", "w", "x", "y", "z", ImmutableList.of("c", "d"), ImmutableList.of("e", "f"))
}
 
Example #10
Source File: BasicBrooklynCatalog.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override @Beta
public Map<RegisteredType,Collection<Throwable>> validateTypes(Iterable<RegisteredType> typesToValidate) {
    List<RegisteredType> typesRemainingToValidate = MutableList.copyOf(typesToValidate);
    while (true) {
        log.debug("Catalog load, starting validation cycle, "+typesRemainingToValidate.size()+" to validate");
        Map<RegisteredType,Collection<Throwable>> result = MutableMap.of();
        for (RegisteredType t: typesRemainingToValidate) {
            Collection<Throwable> tr = validateType(t, null);
            if (!tr.isEmpty()) {
                result.put(t, tr);
            }
        }
        log.debug("Catalog load, finished validation cycle, "+typesRemainingToValidate.size()+" unvalidated");
        if (result.isEmpty() || result.size()==typesRemainingToValidate.size()) {
            return result;
        }
        // recurse wherever there were problems so long as we are reducing the number of problem types
        // (this lets us solve complex reference problems without needing a complex dependency tree,
        // in max O(N^2) time)
        typesRemainingToValidate = MutableList.copyOf(result.keySet());
    }
}
 
Example #11
Source File: ShellAbstractTool.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** builds the command to run the given script;
 * note that some modes require \$RESULT passed in order to access a variable, whereas most just need $ */
protected List<String> buildRunScriptCommand() {
    String scriptInvocationCmd;
    if (runAsRoot) {
        if (authSudo) {
            scriptInvocationCmd = BashCommands.authSudo(scriptPath, password);
        } else {
            scriptInvocationCmd = BashCommands.sudo(scriptPath) + " < /dev/null";
        }
    } else {
        scriptInvocationCmd = scriptPath + " < /dev/null";
    }
    
    MutableList.Builder<String> cmds = MutableList.<String>builder()
            .add(scriptInvocationCmd)
            .add("RESULT=$?");
    if (!noExtraOutput)
        cmds.add("echo Executed "+scriptPath+", result $RESULT"); 
    if (!noDeleteAfterExec) {
        // use "-f" because some systems have "rm" aliased to "rm -i"
        // use "< /dev/null" to guarantee doesn't hang
        cmds.add("rm -f "+scriptPath+" < /dev/null");
    }
    cmds.add("exit $RESULT");
    return cmds.build();
}
 
Example #12
Source File: DependentConfigurationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testListAttributeWhenReadyFromMultipleEntitiesWithGlobalPostProcessor() throws Exception {
    final Task<String> t = submit(DependentConfiguration.builder()
            .attributeWhenReadyFromMultiple(ImmutableList.of(entity, entity2), TestEntity.SEQUENCE)
            .postProcessFromMultiple(new Function<List<Integer>, String>() {
                    @Override public String apply(List<Integer> input) {
                        if (input == null) {
                            return null;
                        } else {
                            MutableList<Integer> inputCopy = MutableList.copyOf(input);
                            Collections.sort(inputCopy);
                            return Joiner.on(",").join(inputCopy);
                        }
                    }})
            .build());
    
    entity.sensors().set(TestEntity.SEQUENCE, 1);
    entity2.sensors().set(TestEntity.SEQUENCE, 2);
    assertEquals(assertDoneEventually(t), "1,2");
}
 
Example #13
Source File: AbstractMemento.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public B from(Memento other) {
    brooklynVersion = other.getBrooklynVersion();
    id = other.getId();
    type = other.getType();
    typeClass = other.getTypeClass();
    displayName = other.getDisplayName();
    catalogItemId = other.getCatalogItemId();
    searchPath = isEmpty(other.getCatalogItemIdSearchPath()) ?
        MutableList.<String>of() : MutableList.copyOf(other.getCatalogItemIdSearchPath());
    customFields.putAll(other.getCustomFields());
    tags.addAll(other.getTags());
    relations.putAll(other.getRelations());
    uniqueTag = other.getUniqueTag();
    return self();
}
 
Example #14
Source File: RebindClassInitializationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testRestoresSimpleApp() throws Exception {
    messages.clear();
    messages.add("creating");
    origApp.createAndManageChild(EntitySpec.create(Entity.class, MyEntityForClassInitializationTesting.class));
    messages.add("created");
    messages.add("rebinding");
    newApp = rebind();
    messages.add("rebinded");
    
    log.debug("Create and rebind message sequence is:\n- "+Strings.join(messages, "\n- "));
    Assert.assertEquals(messages, MutableList.of(
        "creating", "ME.static_initializer", "ME.initializer", 
        "WIM.static_initializer", "WIM.initializer", "WIM.constructor", 
        "ME.constructor", "created", 
        "rebinding", "ME.initializer", "WIM.initializer", "WIM.constructor", 
        "ME.constructor", "rebinded"));
}
 
Example #15
Source File: BasicMasterChooser.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
     * Filters the {@link ManagementPlaneSyncRecord#getManagementNodes()} to only those in an appropriate state, 
     * and with heartbeats that have not timed out.
     */
    protected List<ScoredRecord<?>> filterHealthy(ManagementPlaneSyncRecord memento, Duration heartbeatTimeout, long nowIsh) {
        long oldestAcceptableTimestamp = nowIsh - heartbeatTimeout.toMilliseconds();
        List<ScoredRecord<?>> contenders = MutableList.of();
        for (ManagementNodeSyncRecord contender : memento.getManagementNodes().values()) {
            boolean statusOk = (contender.getStatus() == ManagementNodeState.STANDBY || contender.getStatus() == ManagementNodeState.HOT_STANDBY || contender.getStatus() == ManagementNodeState.MASTER);
            Long remoteTimestamp = contender.getRemoteTimestamp();
            boolean heartbeatOk;
            if (remoteTimestamp==null) {
                throw new IllegalStateException("Missing remote timestamp when performing master election: "+this+" / "+contender);
                // if the above exception happens in some contexts we could either fallback to local, or fail:
//                remoteTimestamp = contender.getLocalTimestamp();
                // or
//                heartbeatOk=false;
            } else {
                heartbeatOk = remoteTimestamp >= oldestAcceptableTimestamp;
            }
            if (statusOk && heartbeatOk) {
                contenders.add(newScoredRecord(contender));
            }
            if (LOG.isTraceEnabled()) LOG.trace("Filtering choices of new master: contender="+contender+"; statusOk="+statusOk+"; heartbeatOk="+heartbeatOk);
        }
        return contenders;
    }
 
Example #16
Source File: Reflections.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** Lists all fields declared on the class, with those lowest in the hierarchy first,
 *  filtered and ordered as requested. 
 *  <p>
 *  See {@link ReflectionPredicates} and {@link FieldOrderings} for conveniences.
 *  <p>
 *  Default is no filter and {@link FieldOrderings#SUB_BEST_FIELD_LAST_THEN_ALPHABETICAL}
 *  */
public static List<Field> findFields(final Class<?> clazz, Predicate<Field> filter, Comparator<Field> fieldOrdering) {
    checkNotNull(clazz, "clazz");
    MutableList.Builder<Field> result = MutableList.<Field>builder();
    Stack<Class<?>> tovisit = new Stack<Class<?>>();
    Set<Class<?>> visited = Sets.newLinkedHashSet();
    tovisit.push(clazz);
    
    while (!tovisit.isEmpty()) {
        Class<?> nextclazz = tovisit.pop();
        if (!visited.add(nextclazz)) {
            continue; // already visited
        }
        if (nextclazz.getSuperclass() != null) tovisit.add(nextclazz.getSuperclass());
        tovisit.addAll(Arrays.asList(nextclazz.getInterfaces()));
        
        result.addAll(Iterables.filter(Arrays.asList(nextclazz.getDeclaredFields()), 
            filter!=null ? filter : Predicates.<Field>alwaysTrue()));
    }
    
    List<Field> resultList = result.build();
    Collections.sort(resultList, fieldOrdering != null ? fieldOrdering : FieldOrderings.SUB_BEST_FIELD_LAST_THEN_ALPHABETICAL);
    
    return resultList;
}
 
Example #17
Source File: BasicStartableTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups={"Broken"})
public void testTransitionsThroughLifecycles() throws Exception {
    BasicStartable startable = app.addChild(EntitySpec.create(BasicStartable.class));
    EntityAsserts.assertAttributeEqualsEventually(app, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
    
    final RecordingSensorEventListener<Lifecycle> listener = new RecordingSensorEventListener<Lifecycle>(true);
    mgmt.getSubscriptionContext(startable)
            .subscribe(startable, Attributes.SERVICE_STATE_ACTUAL, listener);

    app.start(ImmutableList.of(loc1));
    app.config().set(StartableApplication.DESTROY_ON_STOP, false);
    app.stop();

    Iterable<Lifecycle> expected = Lists.newArrayList(
            Lifecycle.STARTING,
            Lifecycle.RUNNING,
            Lifecycle.STOPPING,
            Lifecycle.STOPPED);
    Asserts.eventually(new Supplier<Iterable<Lifecycle>>() {
        @Override
        public Iterable<Lifecycle> get() {
            return MutableList.copyOf(listener.getEventValuesSortedByTimestamp());
        }
    }, Predicates.equalTo(expected));
}
 
Example #18
Source File: Histogram.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    if (counts.isEmpty()) return "<empty>";
    
    StringBuilder result = new StringBuilder("{");
    List<Integer> sortedPows = MutableList.copyOf(counts.keySet());
    Collections.sort(sortedPows);
    int minPow = sortedPows.get(0);
    int maxPow = sortedPows.get(sortedPows.size()-1);
    for (int i = minPow; i <= maxPow; i++) {
        if (i != minPow) result.append(", ");
        long lower = i == 0 ? 0 : (long) Math.pow(2, i-1);
        long upper = (long) Math.pow(2, i);
        Integer count = counts.get(i);
        result.append(Time.makeTimeStringRounded(lower, TimeUnit.NANOSECONDS) 
                + "-" + Time.makeTimeStringRounded(upper, TimeUnit.NANOSECONDS) 
                + ": " + (count == null ? 0 : count));
    }
    result.append("}");
    return result.toString();
}
 
Example #19
Source File: WebAppConcurrentDeployTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test(groups = "Live", dataProvider="basicEntities")
public void testConcurrentDeploys(EntitySpec<? extends JavaWebAppSoftwareProcess> webServerSpec) throws Exception {
    JavaWebAppSoftwareProcess server = app.createAndManageChild(webServerSpec);
    app.start(ImmutableList.of(loc));
    EntityAsserts.assertAttributeEqualsEventually(server, Attributes.SERVICE_UP, Boolean.TRUE);
    Collection<Task<Void>> deploys = MutableList.of();
    for (int i = 0; i < 5; i++) {
        deploys.add(server.invoke(TomcatServer.DEPLOY, MutableMap.of("url", getTestWar(), "targetName", "/")));
    }
    for(Task<Void> t : deploys) {
        t.getUnchecked();
    }

    final HttpClient client = HttpTool.httpClientBuilder().build();
    final URI warUrl = URI.create(server.getAttribute(JavaWebAppSoftwareProcess.ROOT_URL));
    Asserts.succeedsEventually(new Runnable() {
        @Override
        public void run() {
            HttpToolResponse resp = HttpTool.httpGet(client, warUrl, ImmutableMap.<String,String>of());
            assertEquals(resp.getResponseCode(), 200);
        }
    });
}
 
Example #20
Source File: ShellAbstractTool.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the command to retrieve the exit status of the command, written to stdout.
 */
protected List<String> buildRetrieveStatusCommand() {
    // Retrieve exit status from file (writtent to stdout), if populated;
    // if not found and pid still running, then return empty string; else exit code 1.
    List<String> cmdParts = ImmutableList.of(
            "# Retrieve status", // comment is to aid testing - see SshjToolAsyncStubIntegrationTest
            "if test -s "+exitStatusPath+"; then",
            "    cat "+exitStatusPath,
            "elif test -s "+pidPath+"; then",
            "    pid=`cat "+pidPath+"`",
            "    if ! ps -p $pid > /dev/null < /dev/null; then",
            "        # no exit status, and not executing; give a few seconds grace in case just about to write exit status",
            "        sleep 3",
            "        if test -s "+exitStatusPath+"; then",
            "            cat "+exitStatusPath+"",
            "        else",
            "            echo \"No exit status in "+exitStatusPath+", and pid in "+pidPath+" ($pid) not executing\"",
            "            exit 1",
            "        fi",
            "    fi",
            "else",
            "    echo \"No exit status in "+exitStatusPath+", and "+pidPath+" is empty\"",
            "    exit 1",
            "fi"+"\n");
    String cmd = Joiner.on("\n").join(cmdParts);

    MutableList.Builder<String> cmds = MutableList.<String>builder()
            .add((runAsRoot ? BashCommands.sudo(cmd) : cmd))
            .add("RESULT=$?");
    cmds.add("exit $RESULT");
    return cmds.build();
}
 
Example #21
Source File: TestWinrmCommandImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private List<Map<String, Object>> exitCodeAssertions() {

        List<Map<String, Object>> assertStatus = getAssertions(this, ASSERT_STATUS);
        List<Map<String, Object>> assertOut = getAssertions(this, ASSERT_OUT);
        List<Map<String, Object>> assertErr = getAssertions(this, ASSERT_ERR);

        List<Map<String, Object>> result;
        if (assertStatus.isEmpty() && assertOut.isEmpty() && assertErr.isEmpty()) {
            Map<String, Object> shouldSucceed = DEFAULT_ASSERTION;
            result = MutableList.of(shouldSucceed);
        } else {
            result = assertStatus;
        }
        return result;
    }
 
Example #22
Source File: RiakNodeImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
private void configureInternalNetworking() {
    Location location = getDriver().getLocation();
    if (!(location instanceof JcloudsSshMachineLocation)) {
        LOG.info("Not running in a JcloudsSshMachineLocation, not adding IP permissions to {}", this);
        return;
    }
    JcloudsMachineLocation machine = (JcloudsMachineLocation) location;
    JcloudsLocationSecurityGroupCustomizer customizer = JcloudsLocationSecurityGroupCustomizer.getInstance(getApplicationId());

    String cidr = Cidr.UNIVERSAL.toString(); // TODO configure with a more restrictive CIDR
    Collection<IpPermission> permissions = MutableList.<IpPermission>builder()
            .add(IpPermission.builder()
                    .ipProtocol(IpProtocol.TCP)
                    .fromPort(sensors().get(ERLANG_PORT_RANGE_START))
                    .toPort(sensors().get(ERLANG_PORT_RANGE_END))
                    .cidrBlock(cidr)
                    .build())
            .add(IpPermission.builder()
                    .ipProtocol(IpProtocol.TCP)
                    .fromPort(config().get(HANDOFF_LISTENER_PORT))
                    .toPort(config().get(HANDOFF_LISTENER_PORT))
                    .cidrBlock(cidr)
                    .build())
            .add(IpPermission.builder()
                    .ipProtocol(IpProtocol.TCP)
                    .fromPort(config().get(EPMD_LISTENER_PORT))
                    .toPort(config().get(EPMD_LISTENER_PORT))
                    .cidrBlock(cidr)
                    .build())
             .build();
    LOG.debug("Applying custom security groups to {}: {}", machine, permissions);
    customizer.addPermissionsToLocation(machine, permissions);
}
 
Example #23
Source File: BrooklynYamlLocationResolver.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public List<LocationSpec<?>> resolveLocations(Iterable<Object> locations) {
    List<LocationSpec<?>> result = MutableList.of();
    for (Object l: locations) {
        LocationSpec<?> ll = resolveLocation(l);
        if (ll!=null) result.add(ll);
    }
    return result;
}
 
Example #24
Source File: InMemoryObjectStore.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> listContentsWithSubPath(final String parentSubPath) {
    if (!prepared) throw new IllegalStateException("prepare method not yet invoked: "+this);
    synchronized (filesByName) {
        List<String> result = MutableList.of();
        for (String file: filesByName.keySet())
            if (file.startsWith(parentSubPath))
                result.add(file);
        return result;
    }
}
 
Example #25
Source File: ConstraintSerializationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testNestedAndIsSimplified() {
    Predicate<String> p = Predicates.<String>and(
            ConfigConstraints.required(), 
            Predicates.and(Predicates.alwaysTrue()),
            Predicates.<String>and(StringPredicates.matchesRegex(".*")));
    Assert.assertEquals(ConstraintSerialization.INSTANCE.toJsonList(p), 
            MutableList.of("required", MutableMap.of("regex", ".*")));
}
 
Example #26
Source File: MemoryUsageTrackerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")
public void testSoftUsageAndClearance() {
    MemoryUsageSummary initialMemory = new MemoryUsageSummary();
    LOG.info("Memory usage at start of test: "+initialMemory);
    
    MemoryUsageSummary beforeCollectedMemory = null;
    
    List<Maybe<?>> dump = MutableList.of();
    for (int i=0; i<1000*1000; i++) {
        beforeCollectedMemory = new MemoryUsageSummary();
        
        dump.add(Maybe.soft(new byte[1000*1000]));
        if (containsAbsent(dump)) break;
    }
    int cleared = countAbsents(dump);
    assertTrue(cleared > 0, "No soft references cleared after trying to allocate all available memory");
    LOG.info("First soft reference cleared after "+dump.size()+" 1M blocks created; "+cleared+" of them cleared; memory just before collected is "+beforeCollectedMemory);
    
    // Expect the soft references to only have been collected when most of the JVM's memory 
    // was being used. However, it's not necessarily "almost all" (e.g. I've seen on my 
    // laptop the above log message show usedFraction=0.8749949398012845).
    // For more details of when this would be triggered, see:
    //     http://jeremymanson.blogspot.co.uk/2009/07/how-hotspot-decides-to-clear_07.html
    // And note that we set `-XX:SoftRefLRUPolicyMSPerMB=1` to avoid:
    //     https://issues.apache.org/jira/browse/BROOKLYN-375
    assertUsedMemoryFractionWithinRange(beforeCollectedMemory, Range.closed(0.7, 1.0));
    
    String clearanceResult = MemoryUsageTracker.forceClearSoftReferences(100*1000, 10*1000*1000);
    LOG.info("Forcing memory eviction: " + clearanceResult);
    
    System.gc(); System.gc();
    MemoryUsageSummary afterClearedMemory = new MemoryUsageSummary();
    double initialUsedFraction = 1.0*initialMemory.used / afterClearedMemory.total; // re-calculate; might have grown past -Xms during test.
    assertUsedMemoryFractionWithinRange(afterClearedMemory, Range.closed(0.0, initialUsedFraction + 0.1));
    LOG.info("Final memory usage (after forcing clear, and GC): "+afterClearedMemory);
}
 
Example #27
Source File: ServiceStateLogic.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Object computeServiceProblems() {
    Map<Entity, Lifecycle> values = getValues(SERVICE_STATE_ACTUAL);
    int numRunning=0;
    List<Entity> onesNotHealthy=MutableList.of();
    Set<Lifecycle> ignoreStates = getConfig(IGNORE_ENTITIES_WITH_THESE_SERVICE_STATES);
    for (Map.Entry<Entity,Lifecycle> state: values.entrySet()) {
        if (state.getValue()==Lifecycle.RUNNING) numRunning++;
        else if (!ignoreStates.contains(state.getValue()))
            onesNotHealthy.add(state.getKey());
    }

    QuorumCheck qc = getConfig(RUNNING_QUORUM_CHECK);
    if (qc!=null) {
        if (qc.isQuorate(numRunning, onesNotHealthy.size()+numRunning))
            // quorate
            return null;

        if (onesNotHealthy.isEmpty())
            return "Not enough entities running to be quorate";
    } else {
        if (onesNotHealthy.isEmpty())
            return null;
    }

    return "Required entit"+Strings.ies(onesNotHealthy.size())+" not healthy: "+
        (onesNotHealthy.size()>3 ? nameOfEntity(onesNotHealthy.get(0))+" and "+(onesNotHealthy.size()-1)+" others"
            : Strings.join(nameOfEntity(onesNotHealthy), ", "));
}
 
Example #28
Source File: BundleUpgradeParser.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static Multimap<VersionedName, VersionRangedName> parseUpgradeForTypesHeader(String input, Bundle bundle, Supplier<? extends Iterable<? extends RegisteredType>> typeSupplier, Multimap<VersionedName, VersionRangedName> upgradesForBundles) {
    List<String> sourceVersions = null;
    if (upgradesForBundles!=null) {
        Collection<VersionRangedName> acceptableRanges = upgradesForBundles.get(new VersionedName(bundle));
        if (acceptableRanges!=null && !acceptableRanges.isEmpty()) {
            for (VersionRangedName n: acceptableRanges) {
                if (n.getSymbolicName().equals(bundle.getSymbolicName())) {
                    if (sourceVersions==null) {
                        sourceVersions = MutableList.of();
                    }
                    sourceVersions.add(n.getOsgiVersionRange().toString());
                }
            }
        }
    }
    Set<VersionedName> typeSupplierNames = MutableList.copyOf(typeSupplier.get()).stream().map(
        (t) -> VersionedName.toOsgiVersionedName(t.getVersionedName())).collect(Collectors.toSet());
    if (input==null && sourceVersions!=null && !sourceVersions.isEmpty()) {
        input = "*";
    }
    return parseVersionRangedNameEqualsVersionedNameList(input, false,
        // wildcard means all types, all versions of this bundle this bundle replaces
        getTypeNamesInBundle(typeSupplier), sourceVersions,
        // default target is same type at version of this bundle
        (i) -> { 
            VersionedName targetTypeAtBundleVersion = new VersionedName(i.getSymbolicName(), bundle.getVersion());
            if (!typeSupplierNames.contains(VersionedName.toOsgiVersionedName(targetTypeAtBundleVersion))) {
                throw new IllegalStateException("Bundle manifest declares it upgrades "+i+" "
                    + "but does not declare an explicit target and does not contain inferred target "+targetTypeAtBundleVersion);
            }
            return targetTypeAtBundleVersion; 
        });
}
 
Example #29
Source File: Reflections.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** As {@link #invokeConstructorFromArgs(Class, Object...)} but allowing more configurable input;
 * in particular setAccessible allows private constructors to be used (not the default) */
@SuppressWarnings("unchecked")
public static <T> Maybe<T> invokeConstructorFromArgs(Reflections reflections, Class<? extends T> clazz, Object[] argsArray, boolean setAccessible) {
    for (Constructor<?> constructor : MutableList.<Constructor<?>>of().appendAll(Arrays.asList(clazz.getConstructors())).appendAll(Arrays.asList(clazz.getDeclaredConstructors()))) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        if (constructor.isVarArgs()) {
            if (typesMatchUpTo(argsArray, parameterTypes, parameterTypes.length-1)) {
                Class<?> varargType = parameterTypes[parameterTypes.length-1].getComponentType();
                boolean varargsMatch = true;
                for (int i=parameterTypes.length-1; i<argsArray.length; i++) {
                    if (!Boxing.boxedType(varargType).isInstance(argsArray[i]) ||
                                            (varargType.isPrimitive() && argsArray[i]==null)) {
                        varargsMatch = false;
                        break;
                    }
                }
                if (varargsMatch) {
                    Object varargs = Array.newInstance(varargType, argsArray.length+1 - parameterTypes.length);
                    for (int i=parameterTypes.length-1; i<argsArray.length; i++) {
                        Boxing.setInArray(varargs, i+1-parameterTypes.length, argsArray[i], varargType);
                    }
                    Object[] newArgsArray = new Object[parameterTypes.length];
                    System.arraycopy(argsArray, 0, newArgsArray, 0, parameterTypes.length-1);
                    newArgsArray[parameterTypes.length-1] = varargs;
                    if (setAccessible) constructor.setAccessible(true);
                    return Maybe.of((T)reflections.loadInstance(constructor, newArgsArray));
                }
            }
        }
        if (typesMatch(argsArray, parameterTypes)) {
            if (setAccessible) constructor.setAccessible(true);
            return Maybe.of((T) reflections.loadInstance(constructor, argsArray));
        }
    }
    return Maybe.absent("Constructor not found");
}
 
Example #30
Source File: BasicBrooklynTypeRegistryTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testAlias() {
    add(SAMPLE_TYPE);
    add(SAMPLE_TYPE2);
    
    RegisteredType sampleType15WithAliases = RegisteredTypes.addAliases(
        beanWithSuper("item.A", "1.1", new BasicTypeImplementationPlan("ignore", null), String.class),
        MutableList.of("my_a", "the_a"));
    add(sampleType15WithAliases);
    Assert.assertEquals(sampleType15WithAliases.getAliases(), MutableSet.of("my_a", "the_a"));
    
    Assert.assertEquals( Iterables.size(registry().getMatching(
        RegisteredTypePredicates.symbolicName(SAMPLE_TYPE.getSymbolicName()))), 3);
    
    Assert.assertEquals( registry().get("my_a"), sampleType15WithAliases );
    Assert.assertEquals( registry().get("the_a"), sampleType15WithAliases );
    Assert.assertEquals( registry().get(sampleType15WithAliases.getId()), sampleType15WithAliases );
    
    // but unadorned type still returns v2
    Assert.assertEquals( registry().get(sampleType15WithAliases.getSymbolicName()), SAMPLE_TYPE2 );
    
    // and filters work
    Assert.assertEquals( registry().getMatching(RegisteredTypePredicates.alias("the_a")),
        MutableList.of(sampleType15WithAliases) );
    Assert.assertEquals( registry().get("my_a",  
        RegisteredTypeLoadingContexts.bean(String.class)), sampleType15WithAliases );
    Assert.assertEquals( registry().get("my_a",  
        RegisteredTypeLoadingContexts.bean(Integer.class)), null );
}