public static EffectorSummary effectorSummary(
     final Entity entity, Effector<?> effector, UriBuilder ub) {
   URI applicationUri =
       serviceUriBuilder(ub, ApplicationApi.class, "get").build(entity.getApplicationId());
   URI entityUri =
       serviceUriBuilder(ub, EntityApi.class, "get")
           .build(entity.getApplicationId(), entity.getId());
   URI selfUri =
       serviceUriBuilder(ub, EffectorApi.class, "invoke")
           .build(entity.getApplicationId(), entity.getId(), effector.getName());
   return new EffectorSummary(
       effector.getName(),
       effector.getReturnTypeName(),
       ImmutableSet.copyOf(
           Iterables.transform(
               effector.getParameters(),
               new Function<ParameterType<?>, EffectorSummary.ParameterSummary<?>>() {
                 @Override
                 public EffectorSummary.ParameterSummary<?> apply(
                     @Nullable ParameterType<?> parameterType) {
                   return parameterSummary(entity, parameterType);
                 }
               })),
       effector.getDescription(),
       ImmutableMap.of(
           "self", selfUri,
           "entity", entityUri,
           "application", applicationUri));
 }
  @Test
  public void testAddChild() throws Exception {
    try {
      // to test in GUI:
      // services: [ { type: org.apache.brooklyn.entity.stock.BasicEntity }]
      Response response =
          client()
              .path(entityEndpoint + "/children")
              .query("timeout", "10s")
              .post(
                  javax.ws.rs.client.Entity.entity(
                      "services: [ { type: " + TestEntity.class.getName() + " }]",
                      "application/yaml"));

      HttpAsserts.assertHealthyStatusCode(response.getStatus());
      Assert.assertEquals(entity.getChildren().size(), 1);
      Entity child = Iterables.getOnlyElement(entity.getChildren());
      Assert.assertTrue(Entities.isManaged(child));

      TaskSummary task = response.readEntity(TaskSummary.class);
      Assert.assertEquals(task.getResult(), MutableList.of(child.getId()));

    } finally {
      // restore it for other tests
      Collection<Entity> children = entity.getChildren();
      if (!children.isEmpty()) Entities.unmanage(Iterables.getOnlyElement(children));
    }
  }
示例#3
0
 private void configureEnrichers(Entity entity) {
   for (AttributeSensor sensor :
       Iterables.filter(entity.getEntityType().getSensors(), AttributeSensor.class)) {
     if ((DockerUtils.URL_SENSOR_NAMES.contains(sensor.getName())
             || sensor.getName().endsWith(".url")
             || URI.class.isAssignableFrom(sensor.getType()))
         && !DockerUtils.BLACKLIST_URL_SENSOR_NAMES.contains(sensor.getName())) {
       AttributeSensor<String> target = DockerUtils.<String>mappedSensor(sensor);
       entity.addEnricher(
           dockerHost
               .getSubnetTier()
               .uriTransformingEnricher(EntityAndAttribute.create(entity, sensor), target));
       Set<Hint<?>> hints = RendererHints.getHintsFor(sensor);
       for (Hint<?> hint : hints) {
         RendererHints.register(target, (NamedActionWithUrl) hint);
       }
       if (LOG.isDebugEnabled()) {
         LOG.debug("Mapped URL sensor: origin={}, mapped={}", sensor.getName(), target.getName());
       }
     } else if (PortAttributeSensorAndConfigKey.class.isAssignableFrom(sensor.getClass())) {
       AttributeSensor<String> target =
           DockerUtils.mappedPortSensor((PortAttributeSensorAndConfigKey) sensor);
       entity.addEnricher(
           dockerHost
               .getSubnetTier()
               .hostAndPortTransformingEnricher(
                   EntityAndAttribute.create(entity, sensor), target));
       if (LOG.isDebugEnabled()) {
         LOG.debug("Mapped port sensor: origin={}, mapped={}", sensor.getName(), target.getName());
       }
     }
   }
 }
 public static Map<String, Object> getSensorMap(String sensor, Iterable<Entity> descs) {
   if (Iterables.isEmpty(descs)) return Collections.emptyMap();
   Map<String, Object> result = MutableMap.of();
   Iterator<Entity> di = descs.iterator();
   Sensor<?> s = null;
   while (di.hasNext()) {
     Entity potentialSource = di.next();
     s = potentialSource.getEntityType().getSensor(sensor);
     if (s != null) break;
   }
   if (s == null) s = Sensors.newSensor(Object.class, sensor);
   if (!(s instanceof AttributeSensor<?>)) {
     log.warn("Cannot retrieve non-attribute sensor " + s + " for entities; returning empty map");
     return result;
   }
   for (Entity e : descs) {
     Object v = null;
     try {
       v = e.getAttribute((AttributeSensor<?>) s);
     } catch (Exception exc) {
       Exceptions.propagateIfFatal(exc);
       log.warn("Error retrieving sensor " + s + " for " + e + " (ignoring): " + exc);
     }
     if (v != null) result.put(e.getId(), v);
   }
   return result;
 }
  private void testLocationUnmanagedOnStop(LocationSpec<? extends Location> locationSpec) {
    EntitySpec<BasicApplication> appSpec =
        EntitySpec.create(BasicApplication.class)
            .location(locationSpec)
            .child(
                EntitySpec.create(EmptySoftwareProcess.class)
                    .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, Boolean.TRUE)
                    .configure(EmptySoftwareProcess.USE_SSH_MONITORING, Boolean.FALSE));

    BasicApplication app = mgmt.getEntityManager().createEntity(appSpec);
    Entity child = Iterables.getOnlyElement(app.getChildren());

    Assert.assertEquals(child.getLocations(), ImmutableList.of());

    app.start(ImmutableList.<Location>of());
    Location appLocation = Iterables.getOnlyElement(app.getLocations());
    assertOwned(app, appLocation);
    Location entityLocation = Iterables.getOnlyElement(child.getLocations());
    // No owner tag because it's created by SoftwareProcess, not by Brooklyn internals
    assertNotOwned(entityLocation);
    app.stop();

    Assert.assertEquals(child.getLocations(), ImmutableList.of());

    Assert.assertFalse(mgmt.getEntityManager().isManaged(child));
    Assert.assertFalse(mgmt.getEntityManager().isManaged(app));
    Set<Location> locs = ImmutableSet.copyOf(mgmt.getLocationManager().getLocations());
    Assert.assertFalse(
        locs.contains(entityLocation), locs + " should not contain " + entityLocation);
    Assert.assertFalse(locs.contains(appLocation), locs + " should not contain " + appLocation);
  }
 @Test
 public void testWrapsEntity() throws Exception {
   Entity app = createAndStartApplication("services:", "- type: " + BasicEntity.class.getName());
   assertTrue(app.getConfig(EntityManagementUtils.WRAPPER_APP_MARKER));
   assertTrue(app instanceof BasicApplication);
   assertTrue(Iterables.getOnlyElement(app.getChildren()) instanceof BasicEntity);
 }
  /**
   * Walks the contents of a ManagementContext, to create a corresponding memento.
   *
   * @deprecated since 0.7.0; will be moved to test code; generate each entity/location memento
   *     separately
   */
  @Deprecated
  public static BrooklynMemento newBrooklynMemento(ManagementContext managementContext) {
    BrooklynMementoImpl.Builder builder = BrooklynMementoImpl.builder();

    for (Application app : managementContext.getApplications()) {
      builder.applicationIds.add(app.getId());
    }
    for (Entity entity : managementContext.getEntityManager().getEntities()) {
      builder.entities.put(
          entity.getId(), ((EntityInternal) entity).getRebindSupport().getMemento());

      for (Location location : entity.getLocations()) {
        if (!builder.locations.containsKey(location.getId())) {
          for (Location locationInHierarchy : TreeUtils.findLocationsInHierarchy(location)) {
            if (!builder.locations.containsKey(locationInHierarchy.getId())) {
              builder.locations.put(
                  locationInHierarchy.getId(),
                  ((LocationInternal) locationInHierarchy).getRebindSupport().getMemento());
            }
          }
        }
      }
    }
    for (LocationMemento memento : builder.locations.values()) {
      if (memento.getParent() == null) {
        builder.topLevelLocationIds.add(memento.getId());
      }
    }

    BrooklynMemento result = builder.build();
    MementoValidators.validateMemento(result);
    return result;
  }
 @Test
 public void testDoesNotWrapApp() throws Exception {
   Entity app =
       createAndStartApplication("services:", "- type: " + BasicApplication.class.getName());
   assertNull(app.getConfig(EntityManagementUtils.WRAPPER_APP_MARKER));
   assertTrue(app instanceof BasicApplication);
   assertTrue(app.getChildren().isEmpty());
 }
示例#9
0
 private void insertCallback(Entity entity, ConfigKey<String> commandKey, String callback) {
   String command = entity.config().get(commandKey);
   if (Strings.isNonBlank(command)) {
     command = BashCommands.chain(String.format("( %s )", command), callback);
   } else {
     command = callback;
   }
   entity.config().set(commandKey, command);
 }
 private ArrayNode entitiesIdAsArray(Iterable<? extends Entity> entities) {
   ArrayNode node = mapper().createArrayNode();
   for (Entity entity : entities) {
     if (Entitlements.isEntitled(
         mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
       node.add(entity.getId());
     }
   }
   return node;
 }
 @Test
 public void testDoesNotWrapsEntityIfNoNameOnService() throws Exception {
   Entity app =
       createAndStartApplication(
           "name: topLevel", "services:", "- type: " + BasicApplication.class.getName());
   assertNull(app.getConfig(EntityManagementUtils.WRAPPER_APP_MARKER));
   assertTrue(app instanceof BasicApplication);
   assertTrue(app.getChildren().isEmpty());
   assertEquals(app.getDisplayName(), "topLevel");
 }
 @Override
 public boolean apply(Entity input) {
   switch (input.getAttribute(Attributes.SERVICE_STATE_ACTUAL)) {
     case STOPPED:
     case STOPPING:
     case DESTROYED:
       return false;
   }
   return input.getAttribute(getConfig(HOSTNAME_SENSOR)) != null;
 }
示例#13
0
 @Override
 public InetAddress getNextAgentAddress(String agentId) {
   Entity agent = getManagementContext().getEntityManager().getEntity(agentId);
   String address =
       agent.sensors().get(CalicoNode.DOCKER_HOST).sensors().get(Attributes.SUBNET_ADDRESS);
   try {
     return InetAddress.getByName(address);
   } catch (UnknownHostException uhe) {
     throw Exceptions.propagate(uhe);
   }
 }
 private ArrayNode entitiesIdAndNameAsArray(Collection<? extends Entity> entities) {
   ArrayNode node = mapper().createArrayNode();
   for (Entity entity : entities) {
     if (Entitlements.isEntitled(
         mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
       ObjectNode holder = mapper().createObjectNode();
       holder.put("id", entity.getId());
       holder.put("name", entity.getDisplayName());
       node.add(holder);
     }
   }
   return node;
 }
示例#15
0
 public static HttpClient buildClient(Entity framework) {
   String url = framework.sensors().get(MesosFramework.FRAMEWORK_URL);
   String username = framework.config().get(MesosCluster.MESOS_USERNAME);
   String password = framework.config().get(MesosCluster.MESOS_PASSWORD);
   HttpClientBuilder builder = HttpTool.httpClientBuilder().uri(url);
   if ("true".equals(System.getProperty("jclouds.trust-all-certs"))) {
     builder.trustAll();
   }
   if (username != null && password != null) {
     builder.credentials(new UsernamePasswordCredentials(username, password));
   }
   return builder.build();
 }
 @Test
 public void testWrapsEntityIfDifferentTopLevelName() throws Exception {
   Entity app =
       createAndStartApplication(
           "name: topLevel",
           "services:",
           "- type: " + BasicApplication.class.getName(),
           "  name: bottomLevel");
   assertTrue(app.getConfig(EntityManagementUtils.WRAPPER_APP_MARKER));
   assertTrue(app instanceof BasicApplication);
   assertEquals(app.getDisplayName(), "topLevel");
   assertTrue(Iterables.getOnlyElement(app.getChildren()) instanceof BasicApplication);
   assertTrue(Iterables.getOnlyElement(app.getChildren()).getChildren().isEmpty());
   assertEquals(Iterables.getOnlyElement(app.getChildren()).getDisplayName(), "bottomLevel");
 }
示例#17
0
 public static final Optional<String> httpPost(
     Entity framework, String subUrl, String dataUrl, Map<String, Object> substitutions) {
   String targetUrl =
       Urls.mergePaths(framework.sensors().get(MesosFramework.FRAMEWORK_URL), subUrl);
   String templateContents = ResourceUtils.create().getResourceAsString(dataUrl);
   String processedJson =
       TemplateProcessor.processTemplateContents(templateContents, substitutions);
   LOG.debug("Posting JSON to {}: {}", targetUrl, processedJson);
   URI postUri = URI.create(targetUrl);
   HttpToolResponse response =
       HttpTool.httpPost(
           MesosUtils.buildClient(framework),
           postUri,
           MutableMap.of(
               HttpHeaders.CONTENT_TYPE, "application/json",
               HttpHeaders.ACCEPT, "application/json"),
           processedJson.getBytes());
   LOG.debug("Response: " + response.getContentAsString());
   if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
     LOG.warn(
         "Invalid response code {}: {}", response.getResponseCode(), response.getReasonPhrase());
     return Optional.absent();
   } else {
     LOG.debug("Successfull call to {}: {}", targetUrl);
     return Optional.of(response.getContentAsString());
   }
 }
  /*TODO RENAME Method. It could be represent that the service is bound and the service
  operation is called*/
  private void manageService(Entity rawEntity) {

    CloudFoundryService cloudFoundryService;
    if (rawEntity instanceof CloudFoundryService) {

      cloudFoundryService = (CloudFoundryService) rawEntity;

      String serviceName = cloudFoundryService.getConfig(CloudFoundryService.SERVICE_INSTANCE_NAME);

      if (!Strings.isEmpty(serviceName)) {

        Entities.waitForServiceUp(
            cloudFoundryService, cloudFoundryService.getConfig(BrooklynConfigKeys.START_TIMEOUT));

        bindingServiceToEntity(serviceName);
        setCredentialsOnService(cloudFoundryService);
        cloudFoundryService.operation(getEntity());
      } else {
        log.error(
            "Trying to get service instance name from {}, but getting null", cloudFoundryService);
      }
    } else {
      log.error(
          "The service entity {} is not available from the application {}",
          new Object[] {rawEntity, getEntity()});

      throw new NoSuchElementException(
          "No entity matching id "
              + rawEntity.getId()
              + " in Management Context "
              + getEntity().getManagementContext()
              + " during entity service binding "
              + getEntity().getId());
    }
  }
示例#19
0
 @Override
 protected void onProducerAdded(Entity producer) {
   BrooklynLogging.log(
       LOG,
       BrooklynLogging.levelDebugOrTraceIfReadOnly(producer),
       "{} listening to {}",
       this,
       producer);
   synchronized (values) {
     T vo = values.get(producer);
     if (vo == null) {
       T initialVal;
       if (sourceSensor instanceof AttributeSensor) {
         initialVal = producer.getAttribute((AttributeSensor<T>) sourceSensor);
       } else {
         initialVal = null;
       }
       values.put(producer, initialVal != null ? initialVal : defaultMemberValue);
       // we might skip in onEvent in the short window while !values.containsKey(producer)
       // but that's okay because the put which would have been done there is done here now
     } else {
       // vo will be null unless some weird race with addProducer+removeProducer is occuring
       // (and that's something we can tolerate i think)
       if (LOG.isDebugEnabled())
         LOG.debug(
             "{} already had value ({}) for producer ({}); but that producer has just been added",
             new Object[] {this, vo, producer});
     }
   }
 }
  private JsonNode recursiveTreeFromEntity(Entity entity) {
    ObjectNode aRoot = entityBase(entity);

    if (!entity.getChildren().isEmpty())
      aRoot.put("children", childEntitiesRecursiveAsArray(entity));

    return aRoot;
  }
 @Override
 public String apply(Entity input) {
   String hostname = input.getAttribute(getConfig(HOSTNAME_SENSOR));
   hostname = DOMAIN_NAME_FIRST_CHAR_MATCHER.negate().trimFrom(hostname);
   hostname = DOMAIN_NAME_MATCHER.negate().trimAndCollapseFrom(hostname, '-');
   if (hostname.length() > 63) {
     hostname = hostname.substring(0, 63);
   }
   return hostname;
 }
 @Override
 protected void onEntityAdded(Entity member) {
   if (LOG.isTraceEnabled()) {
     LOG.trace(
         "State of {} on added: {}",
         member,
         member.getAttribute(Attributes.SERVICE_STATE_ACTUAL).name());
   }
   ((BindDnsServerImpl) entity).configureResolver(member);
 }
 @Override
 protected void onEntityChange(Entity member) {
   if (LOG.isTraceEnabled()) {
     LOG.trace(
         "State of {} on change: {}",
         member,
         member.getAttribute(Attributes.SERVICE_STATE_ACTUAL).name());
   }
   ((BindDnsServerImpl) entity).update();
 }
 private ArrayNode childEntitiesRecursiveAsArray(Entity entity) {
   ArrayNode node = mapper().createArrayNode();
   for (Entity e : entity.getChildren()) {
     if (Entitlements.isEntitled(
         mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
       node.add(recursiveTreeFromEntity(e));
     }
   }
   return node;
 }
  @Override
  public String getSeeds() {
    Set<Entity> seeds = getConfig(CassandraNode.INITIAL_SEEDS);
    if (seeds == null) {
      log.warn(
          "No seeds available when requested for " + this,
          new Throwable("source of no Cassandra seeds when requested"));
      return null;
    }
    String snitchName = getConfig(CassandraNode.ENDPOINT_SNITCH_NAME);
    MutableSet<String> seedsHostnames = MutableSet.of();
    for (Entity entity : seeds) {
      // tried removing ourselves if there are other nodes, but that is a BAD idea!
      // blows up with a "java.lang.RuntimeException: No other nodes seen!"

      if (snitchName.equals("Ec2MultiRegionSnitch") || snitchName.contains("MultiCloudSnitch")) {
        // http://www.datastax.com/documentation/cassandra/2.0/mobile/cassandra/architecture/architectureSnitchEC2MultiRegion_c.html
        // says the seeds should be public IPs.
        seedsHostnames.add(entity.getAttribute(CassandraNode.ADDRESS));
      } else {
        String sensorName = getConfig(BROADCAST_ADDRESS_SENSOR);
        if (Strings.isNonBlank(sensorName)) {
          seedsHostnames.add(entity.getAttribute(Sensors.newStringSensor(sensorName)));
        } else {
          Maybe<String> optionalSeedHostname = Machines.findSubnetOrPublicHostname(entity);
          if (optionalSeedHostname.isPresent()) {
            String seedHostname = optionalSeedHostname.get();
            seedsHostnames.add(seedHostname);
          } else {
            log.warn(
                "In node {}, seed hostname missing for {}; not including in seeds list",
                this,
                entity);
          }
        }
      }
    }

    String result = Strings.join(seedsHostnames, ",");
    log.info("Seeds for {}: {}", this, result);
    return result;
  }
示例#26
0
 @Override
 public boolean apply(@Nullable Entity input) {
   // Check if entity is deployed to a MesosLocation
   Optional<Location> lookup =
       Iterables.tryFind(input.getLocations(), Predicates.instanceOf(MesosLocation.class));
   if (lookup.isPresent()) {
     MesosLocation location = (MesosLocation) lookup.get();
     return id.equals(location.getOwner().getId());
   } else {
     return false;
   }
 }
  @Test
  public void testEntityCreatingItsEnricherDoesNotReCreateItUnlessUniqueTagDifferent()
      throws Exception {
    TestEntity e1 =
        origApp.createAndManageChild(
            EntitySpec.create(TestEntity.class, MyTestEntityWithEnricher.class));
    Collection<Enricher> e1e = e1.getEnrichers();
    log.info("enrichers1: " + e1e);
    Entities.dumpInfo(e1);
    assertEquals(e1e.size(), 5);

    newApp = (TestApplication) rebind();
    Entity e2 =
        Iterables.getOnlyElement(
            Entities.descendants(newApp, EntityPredicates.idEqualTo(e1.getId())));
    Collection<Enricher> e2e = e2.getEnrichers();
    log.info("enrichers2: " + e2e);
    Entities.dumpInfo(e2);

    assertEquals(e2e.size(), e1e.size() + 1);
  }
  @Test
  public void testParametersCoercedOnSetAndReferences() throws Exception {
    Integer testValue = Integer.valueOf(55);
    addCatalogItems(
        "brooklyn.catalog:",
        "  id: " + SYMBOLIC_NAME,
        "  version: " + TEST_VERSION,
        "  itemType: entity",
        "  item:",
        "    type: " + BasicApplication.class.getName(),
        "    brooklyn.parameters:",
        "    - name: num",
        "      type: integer",
        "    brooklyn.children:",
        "    - type: " + ConfigEntityForTest.class.getName(),
        "      brooklyn.config:",
        "        refConfig: $brooklyn:scopeRoot().config(\"num\")",
        "    - type: " + ConfigEntityForTest.class.getName(),
        "      brooklyn.config:",
        "        refConfig: $brooklyn:config(\"num\")"); // inherited config

    Entity app =
        createAndStartApplication(
            "services:",
            "- type: " + BasicApplication.class.getName(),
            "  brooklyn.children:",
            "  - type: " + ver(SYMBOLIC_NAME),
            "    brooklyn.config:",
            "      num: \"" + testValue + "\"");

    Entity scopeRoot = Iterables.getOnlyElement(app.getChildren());

    ConfigKey<Object> numKey = ConfigKeys.newConfigKey(Object.class, "num");
    assertEquals(scopeRoot.config().get(numKey), testValue);

    ConfigKey<Object> refConfigKey = ConfigKeys.newConfigKey(Object.class, "refConfig");

    Iterator<Entity> childIter = scopeRoot.getChildren().iterator();
    Entity c1 = childIter.next();
    assertEquals(c1.config().get(refConfigKey), testValue);
    Entity c2 = childIter.next();
    assertEquals(c2.config().get(refConfigKey), testValue);
    assertFalse(childIter.hasNext());
  }
  @Override
  public JsonNode fetch(String entityIds) {
    Map<String, JsonNode> jsonEntitiesById = MutableMap.of();
    for (Application application : mgmt().getApplications())
      jsonEntitiesById.put(application.getId(), fromEntity(application));
    if (entityIds != null) {
      for (String entityId : entityIds.split(",")) {
        Entity entity = mgmt().getEntityManager().getEntity(entityId.trim());
        while (entity != null && entity.getParent() != null) {
          if (Entitlements.isEntitled(
              mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
            jsonEntitiesById.put(entity.getId(), fromEntity(entity));
          }
          entity = entity.getParent();
        }
      }
    }

    ArrayNode result = mapper().createArrayNode();
    for (JsonNode n : jsonEntitiesById.values()) result.add(n);
    return result;
  }
示例#30
0
  private Map<String, Object> getExtraTemplateSubstitutions(String imageName, Entity context) {
    Map<String, Object> templateSubstitutions =
        MutableMap.<String, Object>of("fullyQualifiedImageName", imageName);
    templateSubstitutions.putAll(
        getOwner().config().get(DockerInfrastructure.DOCKERFILE_SUBSTITUTIONS));

    // Add any extra substitutions on the entity (if present)
    if (context != null) {
      templateSubstitutions.putAll(
          context.config().get(DockerInfrastructure.DOCKERFILE_SUBSTITUTIONS));
    }

    return templateSubstitutions;
  }