public Task<?> expunge(final Entity entity, final boolean release) { if (mgmt.getEntitlementManager() .isEntitled( Entitlements.getEntitlementContext(), Entitlements.INVOKE_EFFECTOR, Entitlements.EntityAndItem.of(entity, "expunge"))) { return mgmt.getExecutionManager() .submit( MutableMap.of( "displayName", "expunging " + entity, "description", "REST call to expunge entity " + entity.getDisplayName() + " (" + entity + ")"), new Runnable() { @Override public void run() { if (release) Entities.destroyCatching(entity); else mgmt.getEntityManager().unmanage(entity); } }); } throw WebResourceUtils.unauthorized( "User '%s' is not authorized to expunge entity %s", Entitlements.getEntitlementContext().user(), entity); }
public static File getBrooklynWebTmpDir(ManagementContext mgmt) { String brooklynMgmtBaseDir = getMgmtBaseDir(mgmt); File webappTempDir = new File( Os.mergePaths( brooklynMgmtBaseDir, "planes", mgmt.getManagementPlaneId(), mgmt.getManagementNodeId(), "jetty")); try { FileUtils.forceMkdir(webappTempDir); Os.deleteOnExitRecursivelyAndEmptyParentsUpTo(webappTempDir, new File(brooklynMgmtBaseDir)); return webappTempDir; } catch (Exception e) { Exceptions.propagateIfFatal(e); IllegalStateException e2 = new IllegalStateException( "Cannot create working directory " + webappTempDir + " for embedded jetty server: " + e, e); log.warn(e2.getMessage() + " (rethrowing)"); throw e2; } }
/** * finds the entity indicated by the given ID or name * * <p>prefers ID based lookup in which case appId is optional, and if supplied will be enforced. * optionally the name can be supplied, for cases when paths should work across versions, in which * case names will be searched recursively (and the application is required). * * @throws 404 or 412 (unless input is null in which case output is null) */ public EntityLocal getEntity(String application, String entity) { if (entity == null) return null; Application app = application != null ? getApplication(application) : null; EntityLocal e = (EntityLocal) mgmt.getEntityManager().getEntity(entity); if (e != null) { if (!Entitlements.isEntitled(mgmt.getEntitlementManager(), Entitlements.SEE_ENTITY, e)) { throw WebResourceUtils.notFound( "Cannot find entity '%s': no known ID and application not supplied for searching", entity); } if (app == null || app.equals(findTopLevelApplication(e))) return e; throw WebResourceUtils.preconditionFailed( "Application '%s' specified does not match application '%s' to which entity '%s' (%s) is associated", application, e.getApplication().getId(), entity, e); } if (application == null) throw WebResourceUtils.notFound( "Cannot find entity '%s': no known ID and application not supplied for searching", entity); assert app != null : "null app should not be returned from getApplication"; e = searchForEntityNamed(app, entity); if (e != null) return e; throw WebResourceUtils.notFound( "Cannot find entity '%s' in application '%s' (%s)", entity, application, app); }
/** Walks the contents of a ManagementContext, to create a corresponding memento. */ 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 testReloadBrooklynPropertiesNonDeploy() { CampPlatform platform = brooklynMgmt.getConfig().getConfig(BrooklynCampConstants.CAMP_PLATFORM); Assert.assertNotNull(platform); brooklynMgmt.reloadBrooklynProperties(); CampPlatform reloadedPlatform = brooklynMgmt.getConfig().getConfig(BrooklynCampConstants.CAMP_PLATFORM); Assert.assertEquals(reloadedPlatform, platform); }
/** * looks for the given application instance, first by ID then by name * * @throws 404 if not found, or not entitled */ public Application getApplication(String application) { Entity e = mgmt.getEntityManager().getEntity(application); if (!Entitlements.isEntitled(mgmt.getEntitlementManager(), Entitlements.SEE_ENTITY, e)) { throw notFound("Application '%s' not found", application); } if (e != null && e instanceof Application) return (Application) e; for (Application app : mgmt.getApplications()) { if (app.getId().equals(application)) return app; if (application.equalsIgnoreCase(app.getDisplayName())) return app; } throw notFound("Application '%s' not found", application); }
public static boolean isEnabled(ManagementContext mgmt, String prefix) { ConfigKey<Boolean> key = ConfigKeys.newConfigKeyWithPrefix(prefix + ".", LocationConfigKeys.ENABLED); Boolean enabled = mgmt.getConfig().getConfig(key); if (enabled != null) return enabled.booleanValue(); return true; }
public void addChild(Location child) { // Previously, setParent delegated to addChildLocation and we sometimes ended up with // duplicate entries here. Instead this now uses a similar scheme to // AbstractLocation.setParent/addChild (with any weaknesses for distribution that such a // scheme might have...). // // We continue to use a list to allow identical-looking locations, but they must be different // instances. synchronized (children) { for (Location contender : children) { if (contender == child) { // don't re-add; no-op return; } } children.add(child); } if (isManaged()) { Locations.manage(child, managementContext); } else if (managementContext != null) { if (((LocalLocationManager) managementContext.getLocationManager()) .getLocationEvenIfPreManaged(child.getId()) == null) { ((ManagementContextInternal) managementContext).prePreManage(child); } } children.add(child); child.setParent(this); }
@Test public void testCreateAndManageChild() { TestEntity result = entity.createAndManageChild(TestEntity.Spec.newInstance()); assertIsProxy(result); assertIsProxy(Iterables.get(entity.getChildren(), 0)); assertIsProxy(result.getParent()); assertIsProxy(managementContext.getEntityManager().getEntity(result.getId())); }
protected Map<?, ?> getRenderingConfigurationFor(String catalogId) { MutableMap<Object, Object> result = MutableMap.of(); CatalogItem<?> item = mgmt.getCatalog().getCatalogItem(catalogId); if (item == null) return result; result.addIfNotNull("iconUrl", item.getIconUrl()); return result; }
protected void assertNotYetManaged() { if (!inConstruction && (managementContext != null && managementContext.getLocationManager().isManaged(this))) { LOG.warn( "Configuration being made to {} after deployment; may not be supported in future versions", this); } // throw new IllegalStateException("Cannot set configuration "+key+" on active location "+this) }
@Test public void testInvokeTerminateManagementContextOnShutdown() throws Exception { BrooklynShutdownHooks.invokeTerminateOnShutdown(managementContext); BrooklynShutdownHooks.BrooklynShutdownHookJob job = BrooklynShutdownHookJob.newInstanceForTesting(); job.run(); assertFalse(managementContext.isRunning()); }
@BeforeMethod(alwaysRun = true) public void setup() throws Exception { mgmt = new LocalManagementContext(); LocalhostMachineProvisioningLocation lhc = mgmt.getLocationManager() .createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)); host = lhc.obtain(); clearExpectedFailure(); tempDir = Os.newTempDir(getClass()); }
// Should first stop entities, then terminate management contexts @Test public void testInvokeStopEntityAndTerminateManagementContextOnShutdown() throws Exception { BrooklynShutdownHooks.invokeTerminateOnShutdown(managementContext); BrooklynShutdownHooks.invokeStopOnShutdown(entity); BrooklynShutdownHooks.BrooklynShutdownHookJob job = BrooklynShutdownHookJob.newInstanceForTesting(); job.run(); assertTrue(entity.getCallHistory().contains("stop")); assertFalse(managementContext.isRunning()); }
@BeforeMethod(alwaysRun = true) public void setUp() throws Exception { localManagementContext = newPersistingManagementContext(); if (persister == null) { persister = localManagementContext.getRebindManager().getPersister(); } if (objectStore == null && persister instanceof BrooklynMementoPersisterToObjectStore) { objectStore = ((BrooklynMementoPersisterToObjectStore) persister).getObjectStore(); } app = ApplicationBuilder.newManagedApp( EntitySpec.create(TestApplication.class), localManagementContext); location = localManagementContext .getLocationManager() .createLocation( LocationSpec.create(SshMachineLocation.class).configure("address", "localhost")); entity = app.createAndManageChild(EntitySpec.create(TestEntity.class).location(location)); enricher = app.addEnricher(Enrichers.builder().propagatingAll().from(entity).build()); app.addPolicy(policy = new TestPolicy()); }
@SuppressWarnings("unchecked") public static <T> Maybe<Class<T>> tryLoadFromClasspath(String typeName, ManagementContext mgmt) { Class<T> clazz; try { clazz = (Class<T>) mgmt.getCatalog().getRootClassLoader().loadClass(typeName); } catch (ClassNotFoundException e) { LOG.debug("Class {} not found on classpath", typeName); return Maybe.absent(new Throwable("Could not find " + typeName + " on classpath")); } return Maybe.<Class<T>>of(clazz); }
public void onManagementStopped() { this.managed = false; if (managementContext.isRunning()) { BrooklynStorage storage = ((ManagementContextInternal) managementContext).getStorage(); storage.remove(id + "-parent"); storage.remove(id + "-children"); storage.remove(id + "-creationTime"); storage.remove(id + "-hostGeoInfo"); storage.remove(id + "-displayName"); storage.remove(id + "-config"); } }
@Test public void testEffectorOnProxyIsRecorded() { Object result = entity.identityEffector("abc"); assertEquals(result, "abc"); Set<Task<?>> tasks = managementContext .getExecutionManager() .getTasksWithAllTags(ImmutableList.of(ManagementContextInternal.EFFECTOR_TAG, entity)); Task<?> task = Iterables.get(tasks, 0); assertEquals(tasks.size(), 1, "tasks=" + tasks); assertTrue(task.getDescription().contains("identityEffector")); }
@SuppressWarnings("unchecked") public static <T extends Entity> Maybe<Class<T>> tryLoadEntityFromCatalogue( String entityTypeName, ManagementContext mgmt) { try { return (Maybe<Class<T>>) (Maybe<?>) Maybe.<Class<? extends Entity>>of( mgmt.getCatalog().loadClassByType(entityTypeName, Entity.class)); } catch (NoSuchElementException e) { LOG.debug("Class {} not found in catalogue classpath", entityTypeName); return Maybe.absent(); } }
@Test(groups = "Integration") public void testSshFetch() throws IOException { String fn = Urls.mergePaths(tempDir.getPath(), "f2"); FileUtils.write(new File(fn), "hello fetched world"); SshFetchTaskFactory tf = SshTasks.newSshFetchTaskFactory(host, fn); SshFetchTaskWrapper t = tf.newTask(); mgmt.getExecutionManager().submit(t); t.block(); Assert.assertTrue(t.isDone()); Assert.assertEquals(t.get(), "hello fetched world"); Assert.assertEquals(t.getBytes(), "hello fetched world".getBytes()); }
@Test public void testReloadBrooklynPropertiesDeploy() { brooklynMgmt.reloadBrooklynProperties(); CampPlatform reloadedPlatform = brooklynMgmt.getConfig().getConfig(BrooklynCampConstants.CAMP_PLATFORM); Assert.assertNotNull(reloadedPlatform); Reader input = Streams.reader( new ResourceUtils(this).getResourceFromUrl("test-entity-basic-template.yaml")); AssemblyTemplate template = reloadedPlatform.pdp().registerDeploymentPlan(input); try { Assembly assembly = template.getInstantiator().newInstance().instantiate(template, reloadedPlatform); LOG.info("Test - created " + assembly); final Entity app = brooklynMgmt.getEntityManager().getEntity(assembly.getId()); LOG.info("App - " + app); Assert.assertEquals(app.getDisplayName(), "test-entity-basic-template"); EntityTestUtils.assertAttributeEqualsEventually(app, Startable.SERVICE_UP, true); } catch (Exception e) { LOG.warn("Unable to instantiate " + template + " (rethrowing): " + e); throw Exceptions.propagate(e); } }
@Test public void testEntityManagerQueriesGiveProxies() { EntityManager entityManager = managementContext.getEntityManager(); Application retrievedApp = (Application) entityManager.getEntity(app.getId()); TestEntity retrievedEntity = (TestEntity) entityManager.getEntity(entity.getId()); assertIsProxy(retrievedApp); assertIsProxy(retrievedEntity); Collection<Entity> entities = entityManager.getEntities(); for (Entity e : entities) { assertIsProxy(e); } assertEquals(ImmutableSet.copyOf(entities), ImmutableSet.of(app, entity)); }
protected boolean removeChild(Location child) { boolean removed; synchronized (children) { removed = children.remove(child); } if (removed) { if (child instanceof Closeable) { Streams.closeQuietly((Closeable) child); } child.setParent(null); if (isManaged()) { managementContext.getLocationManager().unmanage(child); } } return removed; }
public Task<?> destroy(final Application application) { return mgmt.getExecutionManager() .submit( MutableMap.of( "displayName", "destroying " + application, "description", "REST call to destroy application " + application.getDisplayName() + " (" + application + ")"), new Runnable() { @Override public void run() { ((EntityInternal) application).destroy(); mgmt.getEntityManager().unmanage(application); } }); }
protected <T> ProcessTaskWrapper<T> submit(final ProcessTaskFactory<T> tf) { tf.machine(host); ProcessTaskWrapper<T> t = tf.newTask(); mgmt.getExecutionManager().submit(t); return t; }
protected SshPutTaskWrapper submit(final SshPutTaskFactory tf) { SshPutTaskWrapper t = tf.newTask(); mgmt.getExecutionManager().submit(t); return t; }
protected <T extends Location> T addChild(LocationSpec<T> spec) { T child = managementContext.getLocationManager().createLocation(spec); addChild(child); return child; }
public void reloadBrooklynProperties() { mgmt.reloadBrooklynProperties(); }
public BrooklynCatalog getCatalog() { return mgmt.getCatalog(); }
public LocationRegistry getLocationRegistry() { return mgmt.getLocationRegistry(); }