brooklyn-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From s...@apache.org
Subject [3/7] brooklyn-server git commit: [BROOKLYN-183] Initialize brooklyn-core on bundle activation
Date Tue, 08 Mar 2016 15:53:21 GMT
[BROOKLYN-183] Initialize brooklyn-core on bundle activation

Naively initialize brooklyn-core following the call-graph performed by
the non-OSGi launcher, starting from o.a.b.cli.Main down to
o.a.b.launcher.BrooklynLauncher.

Initialization is done via an artifical o.a.b.core.OsgiLauncher bean so
that the initialization sequence could be more easily compared to that
of the cli launcher.

Fix access to ManagementContextInternal from CXF REST resources by
injecting it explicitly. Karaf injects a service proxy instead of wiring
the service implementor, and as a result simply casting the management
context to ManagementContextInternal interface does not work.


Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/cca26a6f
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/cca26a6f
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/cca26a6f

Branch: refs/heads/master
Commit: cca26a6ffbdc8ce1f498e7080d72462d3b28f088
Parents: 972854a
Author: Ciprian Ciubotariu <cheepeero@gmx.net>
Authored: Wed Feb 10 00:04:41 2016 +0200
Committer: Ciprian Ciubotariu <cheepeero@gmx.net>
Committed: Mon Feb 29 20:11:15 2016 +0200

----------------------------------------------------------------------
 .../org/apache/brooklyn/core/OsgiLauncher.java  | 557 +++++++++++++++++++
 .../resources/OSGI-INF/blueprint/blueprint.xml  |  43 +-
 .../etc/org.apache.brooklyn.osgilauncher.cfg    |  59 ++
 .../main/resources/etc/org.apache.cxf.osgi.cfg  |  20 -
 karaf/features/src/main/feature/feature.xml     |   4 +
 .../features/src/main/feature/feature.xml.orig  | 288 ++++++++++
 .../java/org/apache/brooklyn/AssemblyTest.java  |  13 +-
 .../rest/BrooklynRestApiLauncherTest.java       |  98 ++++
 .../resources/AbstractBrooklynRestResource.java |  16 +
 .../brooklyn/rest/resources/AccessResource.java |   5 +-
 .../brooklyn/rest/resources/ServerResource.java |   7 +-
 .../brooklyn/rest/resources/UsageResource.java  |   9 +-
 .../resources/OSGI-INF/blueprint/service.xml    |  20 +
 13 files changed, 1095 insertions(+), 44 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cca26a6f/core/src/main/java/org/apache/brooklyn/core/OsgiLauncher.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/OsgiLauncher.java b/core/src/main/java/org/apache/brooklyn/core/OsgiLauncher.java
new file mode 100644
index 0000000..b7f5bea
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/OsgiLauncher.java
@@ -0,0 +1,557 @@
+/*
+ * Copyright 2016 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.brooklyn.core;
+
+import com.google.common.base.Function;
+import com.google.common.base.Stopwatch;
+import com.google.common.collect.Iterables;
+import groovy.lang.GroovyClassLoader;
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.concurrent.TimeoutException;
+import org.apache.brooklyn.api.catalog.BrooklynCatalog;
+import org.apache.brooklyn.api.catalog.CatalogItem;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityManager;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
+import org.apache.brooklyn.api.mgmt.ha.ManagementPlaneSyncRecordPersister;
+import org.apache.brooklyn.api.mgmt.rebind.PersistenceExceptionHandler;
+import org.apache.brooklyn.api.mgmt.rebind.RebindManager;
+import org.apache.brooklyn.core.catalog.internal.CatalogInitialization;
+import org.apache.brooklyn.core.entity.Entities;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+import org.apache.brooklyn.core.mgmt.ha.HighAvailabilityManagerImpl;
+import org.apache.brooklyn.core.mgmt.ha.ManagementPlaneSyncRecordPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.internal.BrooklynShutdownHooks;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
+import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
+import org.apache.brooklyn.core.mgmt.rebind.PersistenceExceptionHandlerImpl;
+import org.apache.brooklyn.core.mgmt.rebind.RebindManagerImpl;
+import org.apache.brooklyn.core.objs.BrooklynTypes;
+import org.apache.brooklyn.core.server.BrooklynServerConfig;
+import org.apache.brooklyn.core.server.BrooklynServerPaths;
+import org.apache.brooklyn.util.core.ResourceUtils;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.exceptions.FatalConfigurationRuntimeException;
+import org.apache.brooklyn.util.exceptions.FatalRuntimeException;
+import org.apache.brooklyn.util.exceptions.RuntimeInterruptedException;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.io.FileUtil;
+import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.stream.Streams;
+import org.apache.brooklyn.util.text.Strings;
+import org.apache.brooklyn.util.time.Duration;
+import org.apache.brooklyn.util.time.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Initializer for brooklyn-core when running in an OSGi environment.
+ *
+ * Temporarily here; should be totally contained in blueprint beans' init-methods.
+ */
+public class OsgiLauncher {
+
+    private static final Logger log = LoggerFactory.getLogger(OsgiLauncher.class);
+
+    private ManagementContext managementContext;
+
+    private boolean ignoreCatalogErrors = true;
+    private boolean ignorePersistenceErrors = true;
+
+    private HighAvailabilityMode highAvailabilityMode = HighAvailabilityMode.DISABLED;
+
+    private PersistMode persistMode = PersistMode.DISABLED;
+    private String persistenceDir = null;
+    private String persistenceLocation = null;
+    private Duration persistPeriod = Duration.ONE_SECOND;
+
+    public void start() {
+        // Configure launcher
+//        ShutdownHandler shutdownHandler = new AppShutdownHandler();
+        try {
+//            initBrooklynProperties();
+            initCatalog();
+
+            // TODO
+//            launcher.stopWhichAppsOnShutdown(stopWhichAppsOnShutdownMode);
+//            launcher.shutdownHandler(shutdownHandler);
+//
+//            computeAndSetApp(launcher, utils, loader);
+//            customize(launcher);
+//        } catch (FatalConfigurationRuntimeException e) {
+//            throw e;
+//        } catch (Exception e) {
+//            throw new FatalConfigurationRuntimeException("Fatal error configuring Brooklyn launch: " + e.getMessage(), e);
+//        }
+//
+//        try {
+            launcherStart();
+        } catch (FatalRuntimeException e) {
+            // rely on caller logging this propagated exception
+            throw e;
+        } catch (Exception e) {
+            // for other exceptions we log it, possibly redundantly but better too much than too little
+            Exceptions.propagateIfFatal(e);
+            log.error("Error launching brooklyn: " + Exceptions.collapseText(e), e);
+            try {
+                shutdown();
+            } catch (Exception e2) {
+                log.warn("Subsequent error during termination: " + e2);
+                log.debug("Details of subsequent error during termination: " + e2, e2);
+            }
+            Exceptions.propagate(e);
+        }
+
+        // TODO
+//        if (verbose) {
+//            Entities.dumpInfo(launcher.getApplications());
+//        }
+    }
+
+    private void initCatalog() {
+        // TODO
+//            StopWhichAppsOnShutdown stopWhichAppsOnShutdownMode = computeStopWhichAppsOnShutdown();
+//
+//            computeLocations();
+
+//            ResourceUtils utils = ResourceUtils.create(this);
+//            GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader());
+//
+//            // First, run a setup script if the user has provided one
+//            if (script != null) {
+//                execGroovyScript(utils, loader, script);
+//            }
+        // TODO: extract method for catalog initialization
+        CatalogInitialization catInit = new CatalogInitialization();
+        catInit.addPopulationCallback(new Function<CatalogInitialization, Void>() {
+            @Override
+            public Void apply(CatalogInitialization catInit) {
+                try {
+                    populateCatalog(catInit.getManagementContext().getCatalog());
+                } catch (Throwable e) {
+                    catInit.handleException(e, "overridden main class populate catalog");
+                }
+
+                // Force load of catalog
+                confirmCatalog(catInit);
+                return null;
+            }
+        });
+        catInit.setFailOnStartupErrors(!ignoreCatalogErrors);
+//            launcher.catalogInitialization(catInit);
+    }
+
+//    private void initBrooklynProperties() {
+//        BrooklynProperties.Factory.Builder builder = BrooklynProperties.Factory.builderDefault();
+//
+//        if (globalBrooklynPropertiesFile != null) {
+//            File globalProperties = new File(Os.tidyPath(globalBrooklynPropertiesFile));
+//            if (globalProperties.exists()) {
+//                globalProperties = resolveSymbolicLink(globalProperties);
+//                checkFileReadable(globalProperties);
+//                    // brooklyn.properties stores passwords (web-console and cloud credentials),
+//                // so ensure it has sensible permissions
+//                checkFilePermissionsX00(globalProperties);
+//                log.debug("Using global properties file " + globalProperties);
+//            } else {
+//                log.debug("Global properties file " + globalProperties + " does not exist, will ignore");
+//            }
+//            builder.globalPropertiesFile(globalProperties.getAbsolutePath());
+//        } else {
+//            log.debug("Global properties file disabled");
+//            builder.globalPropertiesFile(null);
+//        }
+//
+//        if (localBrooklynPropertiesFile != null) {
+//            File localProperties = new File(Os.tidyPath(localBrooklynPropertiesFile));
+//            localProperties = resolveSymbolicLink(localProperties);
+//            checkFileReadable(localProperties);
+//            checkFilePermissionsX00(localProperties);
+//            builder.localPropertiesFile(localProperties.getAbsolutePath());
+//        }
+//
+//        managementContext = new LocalManagementContext(builder, brooklynAdditionalProperties);
+//
+//        // not needed: called by osgi framework
+////            // We created the management context, so we are responsible for terminating it
+////            BrooklynShutdownHooks.invokeTerminateOnShutdown(managementContext);
+//    }
+//    /**
+//     * @return The canonical path of the argument.
+//     */
+//    private File resolveSymbolicLink(File f) {
+//        File f2 = f;
+//        try {
+//            f2 = f.getCanonicalFile();
+//            if (Files.isSymbolicLink(f.toPath())) {
+//                log.debug("Resolved symbolic link: {} -> {}", f, f2);
+//            }
+//        } catch (IOException e) {
+//            log.warn("Could not determine canonical name of file " + f + "; returning original file", e);
+//        }
+//        return f2;
+//    }
+//
+//    private void checkFileReadable(File f) {
+//        if (!f.exists()) {
+//            throw new FatalRuntimeException("File " + f + " does not exist");
+//        }
+//        if (!f.isFile()) {
+//            throw new FatalRuntimeException(f + " is not a file");
+//        }
+//        if (!f.canRead()) {
+//            throw new FatalRuntimeException(f + " is not readable");
+//        }
+//    }
+//
+//    private void checkFilePermissionsX00(File f) {
+//
+//        Maybe<String> permission = FileUtil.getFilePermissions(f);
+//        if (permission.isAbsent()) {
+//            log.debug("Could not determine permissions of file; assuming ok: " + f);
+//        } else {
+//            if (!permission.get().subSequence(4, 10).equals("------")) {
+//                throw new FatalRuntimeException("Invalid permissions for file " + f + "; expected ?00 but was " + permission.get());
+//            }
+//        }
+//    }
+
+    /* equivalent of launcher.start() in Main.java */
+    private void launcherStart() {
+        // not needed: management context already running (courtesy of blueprint.xml)
+//        // Create the management context
+//        initManagementContext();
+
+        // Inform catalog initialization that it is starting up
+        CatalogInitialization catInit = ((ManagementContextInternal) managementContext).getCatalogInitialization();
+        catInit.setStartingUp(true);
+
+        // not needed: webapps are started as different features (brooklyn-rest-resources-cxf, brooklyn-jsgui etc)
+//        // Start webapps as soon as mgmt context available -- can use them to detect progress of other processes
+//        if (startWebApps) {
+//            try {
+//                startWebApps();
+//            } catch (Exception e) {
+//                handleSubsystemStartupError(ignoreWebErrors, "core web apps", e);
+//            }
+//        }
+        // not needed: camp is a separate karaf feature - let it initialize itself
+//        // Add a CAMP platform
+//        campPlatform = new BrooklynCampPlatformLauncherNoServer()
+//                .useManagementContext(managementContext)
+//                .launch()
+//                .getCampPlatform();
+        try {
+            initPersistence();
+            startPersistence();
+        } catch (Exception e) {
+            handleSubsystemStartupError(ignorePersistenceErrors, "persistence", e);
+        }
+
+        try {
+            // run cat init now if it hasn't yet been run;
+            // will also run if there was an ignored error in catalog above, allowing it to fail startup here if requested
+            if (!catInit.hasRunOfficialInitialization()) {
+                if (persistMode == PersistMode.DISABLED) {
+                    log.debug("Loading catalog as part of launch sequence (it was not loaded as part of any rebind sequence)");
+                    catInit.populateCatalog(ManagementNodeState.MASTER, true, true, null);
+                } else {
+                    // should have loaded during rebind
+                    ManagementNodeState state = managementContext.getHighAvailabilityManager().getNodeState();
+                    log.warn("Loading catalog for " + state + " as part of launch sequence (it was not loaded as part of the rebind sequence)");
+                    catInit.populateCatalog(state, true, true, null);
+                }
+            }
+        } catch (Exception e) {
+            handleSubsystemStartupError(ignoreCatalogErrors, "initial catalog", e);
+        }
+        catInit.setStartingUp(false);
+
+        // no need for command-line locations
+//        // Create the locations. Must happen after persistence is started in case the
+//        // management context's catalog is loaded from persisted state. (Location
+//        // resolution uses the catalog's classpath to scan for resolvers.)
+//        locations.addAll(managementContext.getLocationRegistry().resolve(locationSpecs));
+        // Already rebinded successfully, so previous apps are now available.
+        // Allow the startup to be visible in console for newly created apps.
+        ((LocalManagementContext) managementContext).noteStartupComplete();
+
+//        // TODO create apps only after becoming master, analogously to catalog initialization
+//        try {
+//            createApps();
+//            startApps();
+//        } catch (Exception e) {
+//            handleSubsystemStartupError(ignoreAppErrors, "brooklyn autostart apps", e);
+//        }
+//        if (startBrooklynNode) {
+//            try {
+//                startBrooklynNode();
+//            } catch (Exception e) {
+//                handleSubsystemStartupError(ignoreAppErrors, "brooklyn node / self entity", e);
+//            }
+//        }
+//
+        if (persistMode != PersistMode.DISABLED) {
+            // Make sure the new apps are persisted in case process exits immediately.
+            managementContext.getRebindManager().forcePersistNow(false, null);
+        }
+    }
+
+    public void shutdown() {
+        // not needed: webserver is in other bundles
+//        if (webServer != null) {
+//            try {
+//                webServer.stop();
+//            } catch (Exception e) {
+//                LOG.warn("Error stopping web-server; continuing with termination", e);
+//            }
+//        }
+
+        // TODO Do we want to do this as part of managementContext.terminate, so after other threads are terminated etc?
+        // Otherwise the app can change between this persist and the terminate.
+        if (persistMode != PersistMode.DISABLED) {
+            try {
+                Stopwatch stopwatch = Stopwatch.createStarted();
+                if (managementContext.getHighAvailabilityManager().getPersister() != null) {
+                    managementContext.getHighAvailabilityManager().getPersister().waitForWritesCompleted(Duration.TEN_SECONDS);
+                }
+                managementContext.getRebindManager().waitForPendingComplete(Duration.TEN_SECONDS, true);
+                log.info("Finished waiting for persist; took " + Time.makeTimeStringRounded(stopwatch));
+            } catch (RuntimeInterruptedException e) {
+                Thread.currentThread().interrupt(); // keep going with shutdown
+                log.warn("Persistence interrupted during shutdown: " + e, e);
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt(); // keep going with shutdown
+                log.warn("Persistence interrupted during shutdown: " + e, e);
+            } catch (TimeoutException e) {
+                log.warn("Timeout after 10 seconds waiting for persistence to write all data; continuing");
+            }
+        }
+
+        // not needed; called using blueprint.xml
+//        if (managementContext instanceof ManagementContextInternal) {
+//            ((ManagementContextInternal) managementContext).terminate();
+//        }
+        // TODO
+//        for (Location loc : locations) {
+//            if (loc instanceof Closeable) {
+//                Streams.closeQuietly((Closeable) loc);
+//            }
+//        }
+    }
+
+    /**
+     * method intended for subclassing, to add custom items to the catalog
+     *
+     * @todo Remove ?
+     */
+    protected void populateCatalog(BrooklynCatalog catalog) {
+        // nothing else added here
+    }
+
+    protected void confirmCatalog(CatalogInitialization catInit) {
+        Stopwatch time = Stopwatch.createStarted();
+        BrooklynCatalog catalog = catInit.getManagementContext().getCatalog();
+        Iterable<CatalogItem<Object, Object>> items = catalog.getCatalogItems();
+        for (CatalogItem<Object, Object> item : items) {
+            try {
+                if (item.getCatalogItemType() == CatalogItem.CatalogItemType.TEMPLATE) {
+                    // skip validation of templates, they might contain instructions,
+                    // and additionally they might contain multiple items in which case
+                    // the validation below won't work anyway (you need to go via a deployment plan)
+                } else {
+                    @SuppressWarnings({"unchecked", "rawtypes"})
+                    Object spec = catalog.createSpec((CatalogItem) item);
+                    if (spec instanceof EntitySpec) {
+                        BrooklynTypes.getDefinedEntityType(((EntitySpec<?>) spec).getType());
+                    }
+                    log.debug("Catalog loaded spec " + spec + " for item " + item);
+                }
+            } catch (Throwable throwable) {
+                catInit.handleException(throwable, item);
+            }
+        }
+        log.debug("Catalog (size " + Iterables.size(items) + ") confirmed in " + Duration.of(time));
+    }
+
+    private void handleSubsystemStartupError(boolean ignoreSuchErrors, String system, Exception e) {
+        Exceptions.propagateIfFatal(e);
+        if (ignoreSuchErrors) {
+            log.error("Subsystem for " + system + " had startup error (continuing with startup): " + e, e);
+            if (managementContext != null) {
+                ((ManagementContextInternal) managementContext).errors().add(e);
+            }
+        } else {
+            throw Exceptions.propagate(e);
+        }
+    }
+
+    protected void initPersistence() {
+        // Prepare the rebind directory, and initialise the RebindManager as required
+        final PersistenceObjectStore objectStore;
+        if (persistMode == PersistMode.DISABLED) {
+            log.info("Persistence disabled");
+            objectStore = null;
+
+        } else {
+            try {
+                BrooklynProperties brooklynProperties = ((ManagementContextInternal) managementContext).getBrooklynProperties();
+                if (persistenceLocation == null) {
+                    persistenceLocation = brooklynProperties.getConfig(BrooklynServerConfig.PERSISTENCE_LOCATION_SPEC);
+                }
+                persistenceDir = BrooklynServerPaths.newMainPersistencePathResolver(brooklynProperties).location(persistenceLocation).dir(persistenceDir).resolve();
+                objectStore = BrooklynPersistenceUtils.newPersistenceObjectStore(managementContext, persistenceLocation, persistenceDir,
+                        persistMode, highAvailabilityMode);
+
+                RebindManager rebindManager = managementContext.getRebindManager();
+
+                BrooklynMementoPersisterToObjectStore persister = new BrooklynMementoPersisterToObjectStore(
+                        objectStore,
+                        ((ManagementContextInternal) managementContext).getBrooklynProperties(),
+                        managementContext.getCatalogClassLoader());
+                PersistenceExceptionHandler persistenceExceptionHandler = PersistenceExceptionHandlerImpl.builder().build();
+                ((RebindManagerImpl) rebindManager).setPeriodicPersistPeriod(persistPeriod);
+                rebindManager.setPersister(persister, persistenceExceptionHandler);
+            } catch (FatalConfigurationRuntimeException e) {
+                throw e;
+            } catch (Exception e) {
+                Exceptions.propagateIfFatal(e);
+                log.debug("Error initializing persistence subsystem (rethrowing): " + e, e);
+                throw new FatalRuntimeException("Error initializing persistence subsystem: "
+                        + Exceptions.collapseText(e), e);
+            }
+        }
+
+        // Initialise the HA manager as required
+        if (highAvailabilityMode == HighAvailabilityMode.DISABLED) {
+            log.info("High availability disabled");
+        } else {
+            if (objectStore == null) {
+                throw new FatalConfigurationRuntimeException("Cannot run in HA mode when no persistence configured.");
+            }
+
+            HighAvailabilityManager haManager = managementContext.getHighAvailabilityManager();
+            ManagementPlaneSyncRecordPersister persister
+                    = new ManagementPlaneSyncRecordPersisterToObjectStore(managementContext,
+                            objectStore,
+                            managementContext.getCatalogClassLoader());
+            // not needed: set from config keys
+//            ((HighAvailabilityManagerImpl) haManager).setHeartbeatTimeout(haHeartbeatTimeoutOverride);
+//            ((HighAvailabilityManagerImpl) haManager).setPollPeriod(haHeartbeatPeriodOverride);
+            haManager.setPersister(persister);
+        }
+    }
+
+    protected void startPersistence() {
+        // Now start the HA Manager and the Rebind manager, as required
+        if (highAvailabilityMode == HighAvailabilityMode.DISABLED) {
+            HighAvailabilityManager haManager = managementContext.getHighAvailabilityManager();
+            haManager.disabled();
+
+            if (persistMode != PersistMode.DISABLED) {
+                startPersistenceWithoutHA();
+            }
+
+        } else {
+            // Let the HA manager decide when objectstore.prepare and rebindmgr.rebind need to be called
+            // (based on whether other nodes in plane are already running).
+
+            HighAvailabilityMode startMode = null;
+            switch (highAvailabilityMode) {
+                case AUTO:
+                case MASTER:
+                case STANDBY:
+                case HOT_STANDBY:
+                case HOT_BACKUP:
+                    startMode = highAvailabilityMode;
+                    break;
+                case DISABLED:
+                    throw new IllegalStateException("Unexpected code-branch for high availability mode " + highAvailabilityMode);
+            }
+            if (startMode == null) {
+                throw new IllegalStateException("Unexpected high availability mode " + highAvailabilityMode);
+            }
+
+            log.debug("Management node (with HA) starting");
+            HighAvailabilityManager haManager = managementContext.getHighAvailabilityManager();
+            // prepare after HA mode is known, to prevent backups happening in standby mode
+            haManager.start(startMode);
+        }
+    }
+
+    private void startPersistenceWithoutHA() {
+        RebindManager rebindManager = managementContext.getRebindManager();
+        if (Strings.isNonBlank(persistenceLocation)) {
+            log.info("Management node (no HA) rebinding to entities at " + persistenceLocation + " in " + persistenceDir);
+        } else {
+            log.info("Management node (no HA) rebinding to entities on file system in " + persistenceDir);
+        }
+
+        ClassLoader classLoader = managementContext.getCatalogClassLoader();
+        try {
+            rebindManager.rebind(classLoader, null, ManagementNodeState.MASTER);
+        } catch (Exception e) {
+            Exceptions.propagateIfFatal(e);
+            log.debug("Error rebinding to persisted state (rethrowing): " + e, e);
+            throw new FatalRuntimeException("Error rebinding to persisted state: "
+                    + Exceptions.collapseText(e), e);
+        }
+        rebindManager.startPersistence();
+    }
+
+    public void setHighAvailabilityMode(HighAvailabilityMode highAvailabilityMode) {
+        this.highAvailabilityMode = highAvailabilityMode;
+    }
+
+    public void setIgnoreCatalogErrors(boolean ignoreCatalogErrors) {
+        this.ignoreCatalogErrors = ignoreCatalogErrors;
+    }
+
+    public void setIgnorePersistenceErrors(boolean ignorePersistenceErrors) {
+        this.ignorePersistenceErrors = ignorePersistenceErrors;
+    }
+
+    public void setManagementContext(ManagementContext managementContext) {
+        this.managementContext = managementContext;
+    }
+
+    public void setPersistMode(PersistMode persistMode) {
+        this.persistMode = persistMode;
+    }
+
+    public void setPersistenceDir(String persistenceDir) {
+        this.persistenceDir = persistenceDir;
+    }
+
+    public void setPersistenceLocation(String persistenceLocation) {
+        this.persistenceLocation = persistenceLocation;
+    }
+
+    public void setPersistPeriod(String persistPeriodDescription) {
+        this.persistPeriod = Duration.parse(persistPeriodDescription);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cca26a6f/core/src/main/resources/OSGI-INF/blueprint/blueprint.xml
----------------------------------------------------------------------
diff --git a/core/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/core/src/main/resources/OSGI-INF/blueprint/blueprint.xml
index 08dcbe5..bd0c7eb 100644
--- a/core/src/main/resources/OSGI-INF/blueprint/blueprint.xml
+++ b/core/src/main/resources/OSGI-INF/blueprint/blueprint.xml
@@ -17,25 +17,48 @@ limitations under the License.
 
 <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-           xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
+           xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.2.0"
            xsi:schemaLocation="
              http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
              http://aries.apache.org/schemas/blueprint-cm/blueprint-cm-1.1.0.xsd
              ">
 
-<!--    <cm:property-placeholder persistent-id="org.apache.brooklyn.properties" update-strategy="reload">
+    <cm:property-placeholder persistent-id="org.apache.brooklyn.osgilauncher" update-strategy="reload">
         <cm:default-properties>
-            <cm:property name="some-property" value="${karaf.data}/some-path"/>
+            <cm:property name="ignoreCatalogErrors" value="true" />
+            <cm:property name="ignorePersistenceErrors" value="true" />
+            <cm:property name="highAvailabilityMode" value="DISABLED" />
+            <cm:property name="persistMode" value="DISABLED" />
+            <cm:property name="persistenceDir" value="" />
+            <cm:property name="persistenceLocation" value="" />
+            <cm:property name="persistPeriod" value="1s" />
         </cm:default-properties>
-    </cm:property-placeholder>-->
+    </cm:property-placeholder>
 
     <bean id="localManagementContextService"
-          class="org.apache.brooklyn.core.mgmt.internal.LocalManagementContext" />
+          class="org.apache.brooklyn.core.mgmt.internal.LocalManagementContext" 
+          destroy-method="terminate" />
 
-    <service ref="localManagementContextService"
-             interface="org.apache.brooklyn.api.mgmt.ManagementContext" />
-    
-<!--    <service ref="localManagementContextService"
-             interface="org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal" />-->
+    <service ref="localManagementContextService">
+        <interfaces>
+            <value>org.apache.brooklyn.api.mgmt.ManagementContext</value>
+            <value>org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal</value>
+        </interfaces>
+    </service>
+
+    <bean id="launcher"
+          class="org.apache.brooklyn.core.OsgiLauncher"
+          init-method="start">
+
+        <property name="managementContext" ref="localManagementContextService" />
+
+        <property name="ignoreCatalogErrors" value="${ignoreCatalogErrors}" />
+        <property name="ignorePersistenceErrors" value="${ignorePersistenceErrors}" />
+        <property name="highAvailabilityMode" value="${highAvailabilityMode}" />
+        <property name="persistMode" value="${persistMode}" />
+        <property name="persistenceDir" value="${persistenceDir}" />
+        <property name="persistenceLocation" value="${persistenceLocation}" />
+        <property name="persistPeriod" value="${persistPeriod}" />
+    </bean>
 
 </blueprint>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cca26a6f/karaf/apache-brooklyn/src/main/resources/etc/org.apache.brooklyn.osgilauncher.cfg
----------------------------------------------------------------------
diff --git a/karaf/apache-brooklyn/src/main/resources/etc/org.apache.brooklyn.osgilauncher.cfg b/karaf/apache-brooklyn/src/main/resources/etc/org.apache.brooklyn.osgilauncher.cfg
new file mode 100644
index 0000000..9b70306
--- /dev/null
+++ b/karaf/apache-brooklyn/src/main/resources/etc/org.apache.brooklyn.osgilauncher.cfg
@@ -0,0 +1,59 @@
+################################################################################
+#
+#    Licensed to the Apache Software Foundation (ASF) under one or more
+#    contributor license agreements.  See the NOTICE file distributed with
+#    this work for additional information regarding copyright ownership.
+#    The ASF licenses this file to You under the Apache License, Version 2.0
+#    (the "License"); you may not use this file except in compliance with
+#    the License.  You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+################################################################################
+
+# This file temporarily contains boot settings for brooklyn karaf launcher,
+# matching some of the command-line options of the previous brooklyn-cli launcher
+# (those used during the initialization sequence)
+#
+# Most of these will migrate to a permanent cfg file, once the components themselves get refactored
+# and the configuration options are agreed upon
+
+
+# Ignore catalog subsystem failures during startup (default is to continue, so errors can be viewed via the API)
+#ignoreCatalogErrors=true
+
+# Ignore persistence/HA subsystem failures during startup (default is to continue, so errors can be viewed via the API)
+#ignorePersistenceErrors=true
+
+# The high availability mode. Possible values are:
+# - disabled: management node works in isolation - will not cooperate with any other standby/master nodes in management plane;
+# - auto: will look for other management nodes, and will allocate itself as standby or master based on other nodes' states;
+# - master: will startup as master - if there is already a master then fails immediately;
+# - standby: will start up as lukewarm standby with no state - if there is not already a master then fails immediately,
+#   and if there is a master which subsequently fails, this node can promote itself;
+# - hot_standby: will start up as hot standby in read-only mode - if there is not already a master then fails immediately,
+#   and if there is a master which subseuqently fails, this node can promote itself;
+# - hot_backup: will start up as hot backup in read-only mode - no master is required, and this node will not become a master
+#highAvailabilityMode=disabled
+
+# The persistence mode. Possible values are:
+# - disabled: will not read or persist any state;
+# - auto: will rebind to any existing state, or start up fresh if no state;
+# - rebind: will rebind to the existing state, or fail if no state available;
+# - clean: will start up fresh (removing any existing state)
+#persistMode=disabled
+
+# The directory to read/write persisted state (or container name if using an object store)
+#persistenceDir=
+
+# The location spec for an object store to read/write persisted state
+#persistenceLocation=
+
+# Periodic read-only rebind
+#persistPeriod=1s

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cca26a6f/karaf/apache-brooklyn/src/main/resources/etc/org.apache.cxf.osgi.cfg
----------------------------------------------------------------------
diff --git a/karaf/apache-brooklyn/src/main/resources/etc/org.apache.cxf.osgi.cfg b/karaf/apache-brooklyn/src/main/resources/etc/org.apache.cxf.osgi.cfg
deleted file mode 100644
index e82b1d0..0000000
--- a/karaf/apache-brooklyn/src/main/resources/etc/org.apache.cxf.osgi.cfg
+++ /dev/null
@@ -1,20 +0,0 @@
-################################################################################
-#
-#    Licensed to the Apache Software Foundation (ASF) under one or more
-#    contributor license agreements.  See the NOTICE file distributed with
-#    this work for additional information regarding copyright ownership.
-#    The ASF licenses this file to You under the Apache License, Version 2.0
-#    (the "License"); you may not use this file except in compliance with
-#    the License.  You may obtain a copy of the License at
-#
-#       http://www.apache.org/licenses/LICENSE-2.0
-#
-#    Unless required by applicable law or agreed to in writing, software
-#    distributed under the License is distributed on an "AS IS" BASIS,
-#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-#    See the License for the specific language governing permissions and
-#    limitations under the License.
-#
-################################################################################
-
-org.apache.cxf.servlet.context = /v1

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cca26a6f/karaf/features/src/main/feature/feature.xml
----------------------------------------------------------------------
diff --git a/karaf/features/src/main/feature/feature.xml b/karaf/features/src/main/feature/feature.xml
index c590469..833b318 100644
--- a/karaf/features/src/main/feature/feature.xml
+++ b/karaf/features/src/main/feature/feature.xml
@@ -182,6 +182,10 @@
         <!-- should be deps of jax-rs-2.0 rest-api project -->
         <bundle dependency="true">mvn:javax.servlet/javax.servlet-api/${javax-servlet.version}</bundle>
         <bundle dependency="true">mvn:javax.ws.rs/javax.ws.rs-api/${jax-rs-api.version}</bundle>
+
+        <config name="org.apache.cxf.osgi">
+            org.apache.cxf.servlet.context = /v1
+        </config>
     </feature>
 
     <feature name="brooklyn-jsgui" version="${project.version}" description="Brooklyn REST JavaScript Web GUI">

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cca26a6f/karaf/features/src/main/feature/feature.xml.orig
----------------------------------------------------------------------
diff --git a/karaf/features/src/main/feature/feature.xml.orig b/karaf/features/src/main/feature/feature.xml.orig
new file mode 100644
index 0000000..5a4ac7d
--- /dev/null
+++ b/karaf/features/src/main/feature/feature.xml.orig
@@ -0,0 +1,288 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Licensed to the Apache Software Foundation (ASF) under one or more
+    contributor license agreements.  See the NOTICE file distributed with
+    this work for additional information regarding copyright ownership.
+    The ASF licenses this file to You under the Apache License, Version 2.0
+    (the "License"); you may not use this file except in compliance with
+    the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+-->
+<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="org.apache.brooklyn-${project.version}">
+
+    <repository>mvn:org.apache.karaf.features/standard/${karaf.version}/xml/features</repository>
+    <repository>mvn:org.apache.karaf.features/enterprise/${karaf.version}/xml/features</repository>
+    <repository>mvn:org.apache.karaf.features/spring/${karaf.version}/xml/features</repository>
+
+    <repository>mvn:org.apache.cxf.karaf/apache-cxf/${cxf.version}/xml/features</repository>
+
+    <!-- temporary feature until we migrate to swagger-1.5.4, which is properly bundled -->
+    <feature name="swagger-crippled" version="${swagger.version}" description="Swagger Annotations+Core+JAXRS+Models">
+        <bundle>mvn:io.swagger/swagger-annotations/${swagger.version}</bundle>
+<!--        <bundle>wrap:mvn:io.swagger/swagger-core/${swagger.version}</bundle>
+        <bundle>wrap:mvn:io.swagger/swagger-jaxrs/${swagger.version}</bundle>-->
+        <bundle>mvn:io.swagger/swagger-models/${swagger.version}</bundle>
+
+        <!--<bundle>mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.javassist/${javassist.bundle.version}</bundle>-->
+        <!--<bundle dependency='true'>mvn:com.google.guava/guava/${guava.version}</bundle>-->
+        <bundle dependency='true'>mvn:com.fasterxml.jackson.core/jackson-annotations/${fasterxml.jackson.version}</bundle>
+        <bundle dependency='true'>mvn:com.fasterxml.jackson.core/jackson-core/${fasterxml.jackson.version}</bundle>
+        <bundle dependency='true'>mvn:com.fasterxml.jackson.core/jackson-databind/${fasterxml.jackson.version}</bundle>
+        <bundle dependency='true'>mvn:com.fasterxml.jackson.dataformat/jackson-dataformat-yaml/${fasterxml.jackson.version}</bundle>
+        <bundle dependency='true'>mvn:com.fasterxml.jackson.jaxrs/jackson-jaxrs-base/${fasterxml.jackson.version}</bundle>
+        <bundle dependency='true'>mvn:com.fasterxml.jackson.jaxrs/jackson-jaxrs-json-provider/${fasterxml.jackson.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-utils-common" version="${project.version}" description="Brooklyn Common Utils">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-utils-common/${project.version}</bundle>
+        <bundle>mvn:org.apache.brooklyn/brooklyn-logback-includes/${project.version}</bundle>
+
+        <bundle dependency="true">mvn:com.google.guava/guava/${guava.version}</bundle>
+        <bundle dependency="true">mvn:org.codehaus.groovy/groovy-all/${groovy.version}</bundle>
+        <bundle dependency="true">mvn:commons-io/commons-io/${commons-io.version}</bundle>
+        <bundle dependency="true">mvn:commons-codec/commons-codec/${commons-codec.version}</bundle>
+        <bundle dependency="true">mvn:org.slf4j/jul-to-slf4j/${slf4j.version}</bundle>
+        <bundle dependency="true">mvn:org.yaml/snakeyaml/${snakeyaml.version}</bundle>
+        <bundle dependency="true">mvn:org.apache.httpcomponents/httpcore-osgi/${httpclient.version}</bundle>
+        <bundle dependency="true">mvn:org.apache.httpcomponents/httpclient-osgi/${httpclient.version}</bundle>
+
+        <bundle dependency="true">mvn:ch.qos.logback/logback-classic/${logback.version}</bundle>
+        <bundle dependency="true">mvn:ch.qos.logback/logback-core/${logback.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-utils-groovy" version="${project.version}" description="Brooklyn Groovy Utils">
+        <feature>brooklyn-utils-common</feature>
+        <bundle>mvn:org.apache.brooklyn/brooklyn-utils-common/${project.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-utils-rest-swagger" version="${project.version}" description="Brooklyn REST Swagger Apidoc Utilities">
+        <feature>brooklyn-utils-common</feature>
+        <feature version="${swagger.version}">swagger-crippled</feature>
+
+        <bundle>mvn:org.apache.brooklyn/brooklyn-utils-rest-swagger/${project.version}</bundle>
+
+        <!--<feature>jersey</feature>-->
+        <bundle dependency="true">mvn:com.sun.jersey/jersey-server/${jersey.version}</bundle>
+        <bundle dependency="true">mvn:com.sun.jersey/jersey-core/${jersey.version}</bundle>
+        <bundle dependency="true">mvn:com.sun.jersey/jersey-servlet/${jersey.version}</bundle>
+        <bundle dependency="true">mvn:org.apache.commons/commons-lang3/${commons-lang3.version}</bundle>
+
+        <bundle dependency="true">mvn:javax.servlet/javax.servlet-api/${javax-servlet.version}</bundle>
+        <bundle dependency="true">mvn:javax.ws.rs/javax.ws.rs-api/${jax-rs-api.version}</bundle>
+
+        <!-- TODO: version 1.1.0.Final has OSGi manifest; check if upgrade doesn't get rid of wrap -->
+        <bundle dependency="true">wrap:mvn:javax.validation/validation-api/${validation-api.version}</bundle>
+        <bundle dependency="true">mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.reflections/${reflections.bundle.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-rest-api" version="${project.version}" description="Brooklyn REST API">
+        <feature>brooklyn-utils-rest-swagger</feature>
+        <feature>brooklyn-api</feature>
+
+        <bundle>mvn:org.apache.brooklyn/brooklyn-rest-api/${project.version}</bundle>
+
+        <bundle dependency="true">mvn:com.sun.jersey.contribs/jersey-multipart/${jersey.version}</bundle>
+        <bundle dependency="true">mvn:org.jvnet.mimepull/mimepull/1.9.3</bundle>
+        <bundle dependency="true">mvn:commons-lang/commons-lang/${commons-lang.version}</bundle>
+
+        <!-- TODO: version 1.1.0.Final has OSGi manifest; check if upgrade doesn't get rid of wrap -->
+        <bundle dependency="true">wrap:mvn:javax.validation/validation-api/${validation-api.version}</bundle>
+
+        <!--<feature>jersey</feature>-->
+        <bundle dependency="true">mvn:com.sun.jersey/jersey-servlet/${jersey.version}</bundle>
+        <bundle dependency="true">mvn:org.apache.commons/commons-lang3/${commons-lang3.version}</bundle>
+        <bundle dependency="true">mvn:org.codehaus.jackson/jackson-core-asl/${jackson.version}</bundle>
+        <bundle dependency="true">mvn:org.codehaus.jackson/jackson-mapper-asl/${jackson.version}</bundle>
+
+        <bundle dependency="true">mvn:javax.servlet/javax.servlet-api/${javax-servlet.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-api"  version="${project.version}" description="Brooklyn API">
+        <feature>brooklyn-utils-common</feature>
+        <bundle>mvn:org.apache.brooklyn/brooklyn-api/${project.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-core" version="${project.version}" description="Brooklyn Core">
+        <feature>brooklyn-api</feature>
+
+        <bundle>mvn:org.apache.brooklyn/brooklyn-core/${project.version}</bundle>
+        <bundle>mvn:org.apache.brooklyn/brooklyn-rt-osgi/${project.version}</bundle>
+        <bundle>mvn:org.apache.brooklyn/brooklyn-utils-groovy/${project.version}</bundle>
+    
+        <bundle dependency="true">mvn:com.google.code.gson/gson/${gson.version}</bundle>
+        <bundle dependency="true">mvn:com.jayway.jsonpath/json-path/${jsonPath.version}</bundle>
+        <bundle dependency="true">mvn:com.fasterxml.jackson.core/jackson-core/${fasterxml.jackson.version}</bundle>
+        <bundle dependency="true">mvn:com.fasterxml.jackson.core/jackson-databind/${fasterxml.jackson.version}</bundle>
+        <bundle dependency="true">mvn:com.fasterxml.jackson.core/jackson-annotations/${fasterxml.jackson.version}</bundle>
+        <bundle dependency="true">mvn:net.minidev/json-smart/${jsonSmart.version}</bundle>
+        <bundle dependency="true">mvn:net.minidev/asm/${minidev.asm.version}</bundle>
+        <bundle dependency="true">mvn:com.thoughtworks.xstream/xstream/${xstream.version}</bundle>
+        <bundle dependency="true">mvn:org.freemarker/freemarker/${freemarker.version}</bundle>
+        <bundle dependency="true">mvn:net.schmizz/sshj/${sshj.version}</bundle>
+        <bundle dependency="true">mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.jzlib/1.1.3_2</bundle> <!-- jzlib version is 1.1.3, but bundle is 1.1.3_2 -->
+        <bundle dependency="true">mvn:org.bouncycastle/bcprov-ext-jdk15on/${bouncycastle.version}</bundle>
+        <bundle dependency="true">mvn:org.bouncycastle/bcpkix-jdk15on/${bouncycastle.version}</bundle>
+        <bundle dependency="true">mvn:commons-codec/commons-codec/${commons-codec.version}</bundle>
+        <bundle dependency="true">mvn:org.apache.commons/commons-lang3/${commons-lang3.version}</bundle>
+        <bundle dependency="true">mvn:org.codehaus.jackson/jackson-core-asl/${jackson.version}</bundle>
+        <bundle dependency="true">mvn:org.codehaus.jackson/jackson-mapper-asl/${jackson.version}</bundle>
+        <bundle dependency="true">mvn:org.codehaus.jackson/jackson-jaxrs/${jackson.version}</bundle>
+
+        <!-- TODO: don't use wrap -->
+        <bundle dependency="true">wrap:mvn:com.google.http-client/google-http-client/1.18.0-rc</bundle> <!-- from geoip -->
+        <bundle dependency="true">wrap:mvn:com.maxmind.geoip2/geoip2/${maxmind.version}</bundle> <!-- from geoip2 -->
+        <bundle dependency="true">wrap:mvn:xpp3/xpp3_min/1.1.4c</bundle> <!-- from com.thoughtworks.xstream/xstream -->
+
+        <bundle dependency="true">mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.reflections/${reflections.bundle.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-camp-brooklyn" version="${project.version}" description="Brooklyn CAMP REST API">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-camp/${project.version}</bundle>
+
+        <feature>brooklyn-core</feature>
+        <feature>brooklyn-camp-base</feature>
+        <bundle dependency="true">mvn:commons-beanutils/commons-beanutils/${commons-beanutils.version}</bundle>
+        <bundle dependency="true">mvn:commons-collections/commons-collections/${commons-collections.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-camp-base" version="${project.version}" description="Brooklyn CAMP Base">
+        <bundle>mvn:org.apache.brooklyn.camp/camp-base/${project.version}</bundle>
+
+        <feature>brooklyn-utils-common</feature>
+        <bundle dependency="true">mvn:org.apache.commons/commons-compress/${commons-compress.version}</bundle>
+        <bundle dependency="true">wrap:mvn:org.tukaani/xz/${commons-compress.version}</bundle>
+        <bundle dependency="true">mvn:org.apache.commons/commons-lang3/${commons-lang3.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-camp-server" version="${project.version}" description="Brooklyn CAMP Server">
+        <bundle>mvn:org.apache.brooklyn.camp/camp-server/${project.version}</bundle>
+
+        <feature>brooklyn-camp-base</feature>
+        <feature>brooklyn-utils-rest-swagger</feature>
+        <feature>jetty</feature> <!-- TODO: pax-jetty??? -->
+
+        <bundle dependency="true">mvn:org.codehaus.jackson/jackson-core-asl/${jackson.version}</bundle>
+        
+        <bundle dependency="true">wrap:mvn:javax.validation/validation-api/${validation-api.version}</bundle>
+        <bundle>mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.reflections/${reflections.bundle.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-rest-resources" version="${project.version}" description="Brooklyn REST Resources (CXF)">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-rest-resources/${project.version}</bundle>
+        <feature>brooklyn-core</feature>
+        <feature>brooklyn-rest-api</feature>
+        <feature>brooklyn-camp-brooklyn</feature>
+        <feature>brooklyn-camp-base</feature>
+
+        <feature>cxf-jaxrs</feature>
+
+        <!-- should be deps of jax-rs-2.0 rest-api project -->
+        <bundle dependency="true">mvn:javax.servlet/javax.servlet-api/${javax-servlet.version}</bundle>
+        <bundle dependency="true">mvn:javax.ws.rs/javax.ws.rs-api/${jax-rs-api.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-jsgui" version="${project.version}" description="Brooklyn REST JavaScript Web GUI">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-jsgui/${project.version}/war</bundle>
+        <feature>war</feature>
+    </feature>
+  
+    <feature name="brooklyn-commands"  version="${project.version}"  description="Brooklyn Shell Commands">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-commands/${project.version}</bundle>
+        <!--<feature version="${project.version}">brooklyn-core</feature>-->
+    </feature>
+  
+    <feature name="brooklyn-software-winrm" version="${project.version}" description="Brooklyn WinRM Software Entities">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-software-winrm/${project.version}</bundle>
+        <feature>brooklyn-core</feature>
+        <bundle dependency="true">wrap:mvn:io.cloudsoft.windows/winrm4j/${winrm4j.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-policy"  version="${project.version}" description="Brooklyn Policies">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-policy/${project.version}</bundle>
+        <feature>brooklyn-core</feature>
+    </feature>
+
+    <feature name="brooklyn-software-base"  version="${project.version}"  description="Brooklyn Software Base">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-software-base/${project.version}</bundle>
+        <feature>brooklyn-software-winrm</feature>
+        <feature>brooklyn-policy</feature>
+        <!-- python dependency required but not supported since karaf cannot handle its runtime bindings -->
+    </feature>
+
+    <feature name="brooklyn-jmxmp-agent" version="${project.version}" description="Brooklyn Secure JMXMP Agent">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-jmxmp-agent/${project.version}</bundle>
+        <feature>brooklyn-core</feature>
+        <bundle dependency="true">wrap:mvn:org.glassfish.external/opendmk_jmxremote_optional_jar/${opendmk_jmxremote_optional_jar.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-jmxrmi-agent" version="${project.version}" description="Brooklyn JMX RMI Agent">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-jmxrmi-agent/${project.version}</bundle>
+    </feature>
+
+    <!-- WARNING: feature brooklyn-locations-jclouds cannot really be installed, due to guava 17 issues -->
+    <feature name="brooklyn-locations-jclouds" version="${project.version}" description="Brooklyn Jclouds Location Targets">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-locations-jclouds/${project.version}</bundle>
+        <feature>brooklyn-software-winrm</feature>
+        <bundle dependency="true">mvn:com.google.inject/guice/${guice.version}</bundle>
+        <bundle dependency="true">mvn:${jclouds.groupId}.driver/jclouds-bouncycastle/${jclouds.version}</bundle>
+        <bundle dependency="true">mvn:${jclouds.groupId}/jclouds-core/${jclouds.version}</bundle>
+        <bundle dependency="true">mvn:com.google.guava/guava/${guava.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-software-network" version="${project.version}" description="Brooklyn Network Software Entities">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-software-network/${project.version}</bundle>
+        <feature>brooklyn-software-base</feature>
+    </feature>
+
+    <feature name="brooklyn-software-osgi" version="${project.version}" description="Brooklyn OSGi Software Entities">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-software-osgi/${project.version}</bundle>
+        <feature>brooklyn-core</feature>
+        <feature>brooklyn-api</feature>
+        <feature>brooklyn-software-base</feature>
+        <bundle dependency="true">mvn:com.google.guava/guava/${guava.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-software-database" version="${project.version}" description="Brooklyn Database Software Entities">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-software-database/${project.version}</bundle>
+        <feature>brooklyn-core</feature>
+        <feature>brooklyn-api</feature>
+        <feature>brooklyn-software-base</feature>
+        <bundle dependency="true">mvn:com.google.guava/guava/${guava.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-software-webapp" version="${project.version}" description="Brooklyn Web App Software Entities">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-software-webapp/${project.version}</bundle>
+        <feature>brooklyn-software-base</feature>
+        <bundle dependency="true">wrap:mvn:org.hibernate/jtidy/${jtidy.version}</bundle>
+    </feature>
+
+    <feature name="brooklyn-software-messaging" version="${project.version}" description="Brooklyn Messaging Software Entities">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-software-messaging/${project.version}</bundle>
+        <feature>brooklyn-software-base</feature>
+    </feature>
+
+    <feature name="brooklyn-software-nosql" version="${project.version}" description="Brooklyn NoSQL Data Store Software Entities">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-software-nosql/${project.version}</bundle>
+        <feature>brooklyn-software-base</feature>
+        <feature>brooklyn-software-database</feature>
+        <feature>brooklyn-software-webapp</feature>
+        <bundle dependency="true">mvn:org.mongodb/mongo-java-driver/3.0.3</bundle>
+    </feature>
+
+    <feature name="brooklyn-software-monitoring" version="${project.version}" description="Brooklyn Monitoring Software Entities">
+        <bundle>mvn:org.apache.brooklyn/brooklyn-software-monitoring/${project.version}</bundle>
+        <feature>brooklyn-core</feature>
+        <feature>brooklyn-api</feature>
+        <feature>brooklyn-software-base</feature>
+        <bundle dependency="true">mvn:com.google.guava/guava/${guava.version}</bundle>
+    </feature>
+    
+</features>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cca26a6f/karaf/itest/src/test/java/org/apache/brooklyn/AssemblyTest.java
----------------------------------------------------------------------
diff --git a/karaf/itest/src/test/java/org/apache/brooklyn/AssemblyTest.java b/karaf/itest/src/test/java/org/apache/brooklyn/AssemblyTest.java
index e4ac052..c8389d6 100644
--- a/karaf/itest/src/test/java/org/apache/brooklyn/AssemblyTest.java
+++ b/karaf/itest/src/test/java/org/apache/brooklyn/AssemblyTest.java
@@ -89,7 +89,7 @@ public class AssemblyTest {
                 .groupId("org.apache.brooklyn")
                 .artifactId("apache-brooklyn")
                 .type("zip")
-                .version(asInProject());
+                .versionAsInProject();
     }
 
     public static MavenUrlReference karafStandardFeaturesRepository() {
@@ -98,7 +98,16 @@ public class AssemblyTest {
                 .artifactId("standard")
                 .type("xml")
                 .classifier("features")
-                .version(asInProject());
+                .versionAsInProject();
+    }
+
+    public static MavenUrlReference brooklynFeaturesRepository() {
+        return maven()
+                .groupId("org.apache.brooklyn")
+                .artifactId("brooklyn-features")
+                .type("xml")
+                .classifier("features")
+                .versionAsInProject();
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cca26a6f/karaf/itest/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTest.java
----------------------------------------------------------------------
diff --git a/karaf/itest/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTest.java b/karaf/itest/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTest.java
new file mode 100644
index 0000000..6792ea2
--- /dev/null
+++ b/karaf/itest/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTest.java
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.rest;
+
+import java.io.File;
+import java.util.concurrent.Callable;
+import org.apache.brooklyn.AssemblyTest;
+import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
+
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.http.HttpAsserts;
+import org.apache.brooklyn.util.http.HttpTool;
+import org.apache.http.HttpStatus;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.ops4j.pax.exam.Configuration;
+import static org.ops4j.pax.exam.CoreOptions.junitBundles;
+import org.ops4j.pax.exam.Option;
+import org.ops4j.pax.exam.junit.PaxExam;
+import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.configureConsole;
+import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
+import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.features;
+import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.karafDistributionConfiguration;
+import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.logLevel;
+import org.ops4j.pax.exam.karaf.options.LogLevelOption;
+import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
+import org.ops4j.pax.exam.spi.reactors.PerClass;
+
+@RunWith(PaxExam.class)
+@ExamReactorStrategy(PerClass.class)
+@Ignore // TODO: re-enable after brooklyn is properly initialized within the OSGI environment
+public class BrooklynRestApiLauncherTest {
+
+    private static final String HTTP_PORT = "9998";
+    private static final String ROOT_URL = "http://localhost:" + HTTP_PORT;
+
+    @Configuration
+    public static Option[] configuration() throws Exception {
+        return new Option[]{
+            karafDistributionConfiguration()
+            .frameworkUrl(AssemblyTest.brooklynKarafDist())
+            .unpackDirectory(new File("target/paxexam/unpack/"))
+            .useDeployFolder(false),
+            editConfigurationFilePut("etc/org.ops4j.pax.web.cfg", "org.osgi.service.http.port", HTTP_PORT),
+            configureConsole().ignoreLocalConsole(),
+            logLevel(LogLevelOption.LogLevel.INFO),
+//            features(AssemblyTest.karafStandardFeaturesRepository(), "eventadmin"),
+            features(AssemblyTest.brooklynFeaturesRepository(), "brooklyn-software-base"),
+            junitBundles()
+
+            // for debugging
+//            , keepRuntimeFolder()
+//            , debugConfiguration()
+        };
+    }
+
+    @Test
+    public void testStart() throws Exception {
+        ensureBrooklynStarted();
+
+        final String testUrl = ROOT_URL + "/v1/catalog/entities";
+        int code = Asserts.succeedsEventually(new Callable<Integer>() {
+            @Override
+            public Integer call() throws Exception {
+                int code = HttpTool.getHttpStatusCode(testUrl);
+                if (code == HttpStatus.SC_FORBIDDEN) {
+                    throw new RuntimeException("Retry request");
+                } else {
+                    return code;
+                }
+            }
+        });
+        HttpAsserts.assertHealthyStatusCode(code);
+        HttpAsserts.assertContentContainsText(testUrl, BrooklynNode.class.getSimpleName());
+    }
+
+    private void ensureBrooklynStarted() {
+        final String upUrl = ROOT_URL + "/v1/server/up";
+        HttpAsserts.assertContentEventuallyMatches(upUrl, "true");
+    }
+}

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cca26a6f/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/AbstractBrooklynRestResource.java
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/AbstractBrooklynRestResource.java b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/AbstractBrooklynRestResource.java
index 9882eb3..118c9c7 100644
--- a/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/AbstractBrooklynRestResource.java
+++ b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/AbstractBrooklynRestResource.java
@@ -27,6 +27,7 @@ import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.core.config.render.RendererHints;
 import org.apache.brooklyn.core.mgmt.ManagementContextInjectable;
+import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
 import org.apache.brooklyn.rest.util.BrooklynRestResourceUtils;
 import org.apache.brooklyn.rest.util.OsgiCompat;
 import org.apache.brooklyn.rest.util.WebResourceUtils;
@@ -49,12 +50,18 @@ public abstract class AbstractBrooklynRestResource implements ManagementContextI
 
     
     private ManagementContext managementContext;
+    private ManagementContextInternal managementContextInternal;
+
     private BrooklynRestResourceUtils brooklynRestResourceUtils;
     private ObjectMapper mapper;
 
     public ManagementContext mgmt() {
         return mgmtMaybe().get();
     }
+
+    public ManagementContextInternal mgmtInternal() {
+        return managementContextInternal;
+    }
     
     protected synchronized Maybe<ManagementContext> mgmtMaybe() {
         if (managementContext!=null) return Maybe.of(managementContext);
@@ -71,8 +78,17 @@ public abstract class AbstractBrooklynRestResource implements ManagementContextI
             throw new IllegalStateException("ManagementContext cannot be changed: specified twice for Brooklyn Jersey Resource "+this);
         }
         this.managementContext = managementContext;
+        if (managementContext instanceof ManagementContextInternal) {
+            // when running outside OSGi container
+            this.managementContextInternal = (ManagementContextInternal)managementContext;
+        }
     }
 
+    public void setManagementContextInternal(ManagementContextInternal managementContextInternal) {
+        this.managementContextInternal = managementContextInternal;
+    }
+
+
     public synchronized BrooklynRestResourceUtils brooklyn() {
         if (brooklynRestResourceUtils!=null) return brooklynRestResourceUtils;
         brooklynRestResourceUtils = new BrooklynRestResourceUtils(mgmt());

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cca26a6f/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/AccessResource.java
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/AccessResource.java b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/AccessResource.java
index bb40edf..0aed2c8 100644
--- a/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/AccessResource.java
+++ b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/AccessResource.java
@@ -21,7 +21,6 @@ package org.apache.brooklyn.rest.resources;
 import javax.ws.rs.core.Response;
 
 import org.apache.brooklyn.core.mgmt.internal.AccessManager;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
 import org.apache.brooklyn.rest.api.AccessApi;
 import org.apache.brooklyn.rest.domain.AccessSummary;
 import org.apache.brooklyn.rest.transform.AccessTransformer;
@@ -33,13 +32,13 @@ public class AccessResource extends AbstractBrooklynRestResource implements Acce
 
     @Override
     public AccessSummary get() {
-        AccessManager accessManager = ((ManagementContextInternal) mgmt()).getAccessManager();
+        AccessManager accessManager = mgmtInternal().getAccessManager();
         return AccessTransformer.accessSummary(accessManager, ui.getBaseUriBuilder());
     }
 
     @Override
     public Response locationProvisioningAllowed(boolean allowed) {
-        AccessManager accessManager = ((ManagementContextInternal) mgmt()).getAccessManager();
+        AccessManager accessManager = mgmtInternal().getAccessManager();
         accessManager.setLocationProvisioningAllowed(allowed);
         return Response.status(Response.Status.OK).build();
     }

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cca26a6f/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/ServerResource.java
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/ServerResource.java b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/ServerResource.java
index fe7893b..3f06cc5 100644
--- a/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/ServerResource.java
+++ b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/ServerResource.java
@@ -52,7 +52,6 @@ import org.apache.brooklyn.core.entity.Entities;
 import org.apache.brooklyn.core.entity.StartableApplication;
 import org.apache.brooklyn.core.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.core.mgmt.entitlement.Entitlements;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
 import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils;
 import org.apache.brooklyn.core.mgmt.persist.FileBasedObjectStore;
 import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
@@ -190,7 +189,7 @@ public class ServerResource extends AbstractBrooklynRestResource implements Serv
                     }
 
                     terminateTried = true;
-                    ((ManagementContextInternal)mgmt).terminate(); 
+                    mgmtInternal().terminate(); 
 
                 } catch (Throwable e) {
                     Throwable interesting = Exceptions.getFirstInteresting(e);
@@ -208,7 +207,7 @@ public class ServerResource extends AbstractBrooklynRestResource implements Serv
                     hasAppErrorsOrTimeout.set(true);
                     
                     if (!terminateTried) {
-                        ((ManagementContextInternal)mgmt).terminate(); 
+                        mgmtInternal().terminate(); 
                     }
                 } finally {
 
@@ -356,7 +355,7 @@ public class ServerResource extends AbstractBrooklynRestResource implements Serv
     
     @Override
     public boolean isHealthy() {
-        return isUp() && ((ManagementContextInternal) mgmt()).errors().isEmpty();
+        return isUp() && mgmtInternal().errors().isEmpty();
     }
     
     @Override

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cca26a6f/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/UsageResource.java
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/UsageResource.java b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/UsageResource.java
index ebcd2fa..3c226bd 100644
--- a/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/UsageResource.java
+++ b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/resources/UsageResource.java
@@ -30,7 +30,6 @@ import javax.annotation.Nullable;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.apache.brooklyn.core.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
 import org.apache.brooklyn.core.mgmt.usage.ApplicationUsage;
 import org.apache.brooklyn.core.mgmt.usage.LocationUsage;
 import org.apache.brooklyn.core.mgmt.usage.ApplicationUsage.ApplicationEvent;
@@ -67,7 +66,7 @@ public class UsageResource extends AbstractBrooklynRestResource implements Usage
         
         checkDates(startDate, endDate);
 
-        Set<ApplicationUsage> usages = ((ManagementContextInternal) mgmt()).getUsageManager().getApplicationUsage(Predicates.alwaysTrue());
+        Set<ApplicationUsage> usages = mgmtInternal().getUsageManager().getApplicationUsage(Predicates.alwaysTrue());
 
         for (ApplicationUsage usage : usages) {
             List<UsageStatistic> statistics = retrieveApplicationUsage(usage, startDate, endDate);
@@ -87,7 +86,7 @@ public class UsageResource extends AbstractBrooklynRestResource implements Usage
 
         checkDates(startDate, endDate);
 
-        ApplicationUsage usage = ((ManagementContextInternal) mgmt()).getUsageManager().getApplicationUsage(application);
+        ApplicationUsage usage = mgmtInternal().getUsageManager().getApplicationUsage(application);
         if (usage != null) {
             List<UsageStatistic> statistics = retrieveApplicationUsage(usage, startDate, endDate);
             return new UsageStatistics(statistics, ImmutableMap.<String,URI>of());
@@ -146,7 +145,7 @@ public class UsageResource extends AbstractBrooklynRestResource implements Usage
         checkDates(startDate, endDate);
         
         // Note currently recording ALL metrics for a machine that contains an Event from given Application
-        Set<LocationUsage> matches = ((ManagementContextInternal) mgmt()).getUsageManager().getLocationUsage(new Predicate<LocationUsage>() {
+        Set<LocationUsage> matches = mgmtInternal().getUsageManager().getLocationUsage(new Predicate<LocationUsage>() {
             @Override
             public boolean apply(LocationUsage input) {
                 LocationUsage.LocationEvent first = input.getEvents().get(0);
@@ -189,7 +188,7 @@ public class UsageResource extends AbstractBrooklynRestResource implements Usage
         checkDates(startDate, endDate);
         
         // Note currently recording ALL metrics for a machine that contains an Event from given Application
-        LocationUsage usage = ((ManagementContextInternal) mgmt()).getUsageManager().getLocationUsage(machine);
+        LocationUsage usage = mgmtInternal().getUsageManager().getLocationUsage(machine);
         
         if (usage == null) {
             throw notFound("Machine '%s' not found", machine);

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cca26a6f/rest/rest-resources/src/main/resources/OSGI-INF/blueprint/service.xml
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/main/resources/OSGI-INF/blueprint/service.xml b/rest/rest-resources/src/main/resources/OSGI-INF/blueprint/service.xml
index 1639fef..c1482b7 100644
--- a/rest/rest-resources/src/main/resources/OSGI-INF/blueprint/service.xml
+++ b/rest/rest-resources/src/main/resources/OSGI-INF/blueprint/service.xml
@@ -29,58 +29,78 @@ limitations under the License.
 
     <cxf:bus>
         <cxf:features>
+<!--            <bean class="org.apache.cxf.interceptor.security.JAASAuthenticationFeature">
+                    <property name="reportFault" value="true"/>
+            </bean>-->
             <cxf:logging/>
         </cxf:features>
     </cxf:bus>
 
     <reference id="localManagementContext"
                interface="org.apache.brooklyn.api.mgmt.ManagementContext" />
+    <reference id="localManagementContextInternal"
+               interface="org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal" />
 
     <bean id="accessResourceBean" class="org.apache.brooklyn.rest.resources.AccessResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <bean id="activityResourceBean" class="org.apache.brooklyn.rest.resources.ActivityResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <!--<bean id="apidocResourceBean" class="org.apache.brooklyn.rest.resources.ApidocResource" />-->
     <bean id="applicationResourceBean" class="org.apache.brooklyn.rest.resources.ApplicationResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <bean id="catalogResourceBean" class="org.apache.brooklyn.rest.resources.CatalogResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <bean id="effectorResourceBean" class="org.apache.brooklyn.rest.resources.EffectorResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <bean id="entityConfigResourceBean" class="org.apache.brooklyn.rest.resources.EntityConfigResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <bean id="entityResourceBean" class="org.apache.brooklyn.rest.resources.EntityResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <bean id="locationResourceBean" class="org.apache.brooklyn.rest.resources.LocationResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <bean id="policyConfigResourceBean" class="org.apache.brooklyn.rest.resources.PolicyConfigResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <bean id="policyResourceBean" class="org.apache.brooklyn.rest.resources.PolicyResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <bean id="scriptResourceBean" class="org.apache.brooklyn.rest.resources.ScriptResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <bean id="sensorResourceBean" class="org.apache.brooklyn.rest.resources.SensorResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <bean id="serverResourceBean" class="org.apache.brooklyn.rest.resources.ServerResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <bean id="usageResourceBean" class="org.apache.brooklyn.rest.resources.UsageResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
     <bean id="versionResourceBean" class="org.apache.brooklyn.rest.resources.VersionResource">
         <property name="managementContext" ref="localManagementContext" />
+        <property name="managementContextInternal" ref="localManagementContextInternal" />
     </bean>
 
     <jaxrs:server id="brooklynRestApiV1" address="/">


Mime
View raw message