You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@brooklyn.apache.org by he...@apache.org on 2017/10/28 10:02:55 UTC
[1/7] brooklyn-server git commit: BROOKLYN-546: fix rebind of system
bundles
Repository: brooklyn-server
Updated Branches:
refs/heads/master 5eb08b262 -> 8d7444aea
BROOKLYN-546: fix rebind of system bundles
Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/bfabe7cc
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/bfabe7cc
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/bfabe7cc
Branch: refs/heads/master
Commit: bfabe7cccc38afccc3dc1e9043fba28d6a6ad8c1
Parents: e73ee29
Author: Aled Sage <al...@gmail.com>
Authored: Mon Oct 23 13:53:10 2017 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Fri Oct 27 12:27:21 2017 +0100
----------------------------------------------------------------------
.../core/mgmt/ha/OsgiArchiveInstaller.java | 79 +++++++++++++-------
1 file changed, 53 insertions(+), 26 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/bfabe7cc/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java
index 0351838..968fbf9 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java
@@ -380,8 +380,15 @@ class OsgiArchiveInstaller {
result.bundle = osgiManager.framework.getBundleContext().getBundle(result.getMetadata().getOsgiUniqueUrl());
if (result.getBundle()==null) {
- log.warn("Brooklyn thought is was already managing bundle "+result.getMetadata().getVersionedName()+" but it's not installed to framework; reinstalling it");
- updating = false;
+ if (hasBundleOnInstall(osgiManager, inferredMetadata, zipFile)) {
+ // e.g. happens if system-bundle is brought under management, and then try to add it again:
+ // if added from "initial catalog" has it, and then added from persisted state as well.
+ result.setIgnoringAlreadyInstalled();
+ return ReferenceWithError.newInstanceWithoutError(result);
+ } else {
+ log.warn("Brooklyn thought is was already managing bundle "+result.getMetadata().getVersionedName()+" but it's not installed to framework; reinstalling it");
+ updating = false;
+ }
} else {
updating = true;
}
@@ -408,30 +415,7 @@ class OsgiArchiveInstaller {
// or if the bundle should be reinstalled/updated
if (!force) {
if (!isBringingExistingOsgiInstalledBundleUnderBrooklynManagement) {
- if (Objects.equal(b.get().getLocation(), inferredMetadata.getUrl())) {
- // installation request was for identical location, so assume we are simply bringing under mgmt
- log.debug("Request to install "+inferredMetadata+" from same location "+b.get().getLocation()+
- " as existing OSGi installed (but not Brooklyn-managed) bundle "+b.get()+", so skipping reinstall");
- isBringingExistingOsgiInstalledBundleUnderBrooklynManagement = true;
- } else {
- // different locations, but see if we can compare input stream contents
- // (prevents needless uninstall/reinstall of already installed bundles)
- try {
- if (Streams.compare(new FileInputStream(zipFile), new URL(b.get().getLocation()).openStream())) {
- log.debug("Request to install "+inferredMetadata+" has same contents"+
- " as existing OSGi installed (but not Brooklyn-managed) bundle "+b.get()+", so skipping reinstall");
- isBringingExistingOsgiInstalledBundleUnderBrooklynManagement = true;
- } else {
- log.debug("Request to install "+inferredMetadata+" has different contents"+
- " as existing OSGi installed (but not Brooklyn-managed) bundle "+b.get()+", so will do reinstall");
- }
- } catch (Exception e) {
- Exceptions.propagateIfFatal(e);
- // probably an invalid URL on installed bundle; that's allowed
- log.debug("Request to install "+inferredMetadata+" could not compare contents"+
- " with existing OSGi installed (but not Brooklyn-managed) bundle "+b.get()+", so will do reinstall (error "+e+" loading from "+b.get().getLocation()+")");
- }
- }
+ isBringingExistingOsgiInstalledBundleUnderBrooklynManagement = hasBundleOnInstall(osgiManager, inferredMetadata, zipFile);
}
} else {
if (isBringingExistingOsgiInstalledBundleUnderBrooklynManagement) {
@@ -648,6 +632,49 @@ class OsgiArchiveInstaller {
}
}
+ private static boolean hasBundleOnInstall(OsgiManager osgiManager, ManagedBundle desired, File zipFile) {
+ // Would be nice to also use `desired.getChecksum()`, but not clear if we can get
+ // MD5 checksum from an installed OSGi bundle.
+
+ Maybe<Bundle> b = Osgis.bundleFinder(osgiManager.framework).symbolicName(desired.getSymbolicName()).version(desired.getOsgiVersionString()).find();
+ if (b.isPresent()) {
+ // bundle already installed to OSGi subsystem (but brooklyn not aware of it as "managed bundle");
+ // this will often happen on a karaf restart where bundle was cached by karaf,
+ // so we need to allow it. can also happen if brooklyn.libraries references an existing bundle.
+
+ // determine if we are simply bringing existing installed under Brooklyn management (because url or binary content identical and not forced)
+ // or if the bundle should be reinstalled/updated
+ if (Objects.equal(b.get().getLocation(), desired.getUrl())) {
+ // installation request was for identical location, so assume we are simply bringing under mgmt
+ log.debug("Request to install "+desired+" from same location "+b.get().getLocation()+
+ " as existing OSGi installed (but not Brooklyn-managed) bundle "+b.get()+", so skipping reinstall");
+ return true;
+ } else {
+ // different locations, but see if we can compare input stream contents
+ // (prevents needless uninstall/reinstall of already installed bundles)
+ try {
+ if (Streams.compare(new FileInputStream(zipFile), new URL(b.get().getLocation()).openStream())) {
+ log.debug("Request to install "+desired+" has same contents"+
+ " as existing OSGi installed (but not Brooklyn-managed) bundle "+b.get()+", so skipping reinstall");
+ return true;
+ } else {
+ log.debug("Request to install "+desired+" has different contents"+
+ " as existing OSGi installed (but not Brooklyn-managed) bundle "+b.get()+", so will do reinstall");
+ return false;
+ }
+ } catch (Exception e) {
+ Exceptions.propagateIfFatal(e);
+ // probably an invalid URL on installed bundle; that's allowed
+ log.debug("Request to install "+desired+" could not compare contents"+
+ " with existing OSGi installed (but not Brooklyn-managed) bundle "+b.get()+", so will do reinstall (error "+e+" loading from "+b.get().getLocation()+")");
+ return false;
+ }
+ }
+ } else {
+ return false;
+ }
+ }
+
private static String getChecksum(ZipFile zf) {
// checksum should ignore time/date stamps on files - just look at entries and contents. also ignore order.
// (tests fail without time/date is one reason, but really if a person rebuilds a ZIP that is the same
[7/7] brooklyn-server git commit: This closes #867
Posted by he...@apache.org.
This closes #867
Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/8d7444ae
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/8d7444ae
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/8d7444ae
Branch: refs/heads/master
Commit: 8d7444aeaf08680b97662e1d016f423085d3b0bf
Parents: 5eb08b2 8a2d51e
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Sat Oct 28 11:02:41 2017 +0100
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Sat Oct 28 11:02:41 2017 +0100
----------------------------------------------------------------------
.../brooklyn/api/mgmt/rebind/RebindManager.java | 9 +-
.../rebind/mementos/ManagedBundleMemento.java | 5 +
.../camp/brooklyn/AbstractYamlTest.java | 2 +-
.../catalog/CatalogOsgiYamlEntityTest.java | 2 +-
.../catalog/CatalogOsgiYamlVersioningTest.java | 2 +-
.../brooklyn/test/lite/CampYamlLiteTest.java | 2 +-
.../catalog/internal/BasicBrooklynCatalog.java | 2 +-
.../catalog/internal/CatalogInitialization.java | 37 +-
.../mgmt/ha/HighAvailabilityManagerImpl.java | 13 +-
.../core/mgmt/ha/OsgiArchiveInstaller.java | 265 ++++++++---
.../brooklyn/core/mgmt/ha/OsgiManager.java | 33 ++
.../NonDeploymentManagementContext.java | 5 +
.../rebind/PeriodicDeltaChangeListener.java | 19 +-
.../core/mgmt/rebind/RebindIteration.java | 2 +-
.../core/mgmt/rebind/RebindManagerImpl.java | 5 +
.../rebind/dto/BasicManagedBundleMemento.java | 20 +-
.../core/server/BrooklynServerConfig.java | 13 +
.../core/typereg/BasicManagedBundle.java | 23 +-
.../core/mgmt/ha/OsgiArchiveInstallerTest.java | 83 ++++
.../core/mgmt/rebind/RebindTestFixture.java | 13 +-
.../AbstractBrooklynLauncherRebindTest.java | 68 ++-
.../BrooklynLauncherRebindCatalogOsgiTest.java | 476 ++++++++++++++++++-
22 files changed, 998 insertions(+), 101 deletions(-)
----------------------------------------------------------------------
[5/7] brooklyn-server git commit: PR #867: bundle persistence
blacklist/whitelist configurable
Posted by he...@apache.org.
PR #867: bundle persistence blacklist/whitelist configurable
Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/03f254fd
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/03f254fd
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/03f254fd
Branch: refs/heads/master
Commit: 03f254fd2812580e343993afaddd69a630841d81
Parents: 5d13ebf
Author: Aled Sage <al...@gmail.com>
Authored: Fri Oct 27 12:09:48 2017 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Fri Oct 27 13:50:15 2017 +0100
----------------------------------------------------------------------
.../core/mgmt/ha/OsgiArchiveInstaller.java | 43 +++++++++-
.../brooklyn/core/mgmt/ha/OsgiManager.java | 4 +
.../core/server/BrooklynServerConfig.java | 13 +++
.../core/mgmt/ha/OsgiArchiveInstallerTest.java | 83 ++++++++++++++++++++
.../core/mgmt/rebind/RebindTestFixture.java | 13 ++-
5 files changed, 150 insertions(+), 6 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/03f254fd/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java
index e3b91fa..e41ec74 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java
@@ -31,15 +31,18 @@ import java.util.Map;
import java.util.TreeMap;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
+import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.brooklyn.api.typereg.ManagedBundle;
import org.apache.brooklyn.api.typereg.RegisteredType;
+import org.apache.brooklyn.config.ConfigKey;
import org.apache.brooklyn.core.BrooklynVersion;
import org.apache.brooklyn.core.catalog.internal.BasicBrooklynCatalog;
import org.apache.brooklyn.core.mgmt.ha.OsgiBundleInstallationResult.ResultCode;
import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.server.BrooklynServerConfig;
import org.apache.brooklyn.core.typereg.BasicBrooklynTypeRegistry;
import org.apache.brooklyn.core.typereg.BasicManagedBundle;
import org.apache.brooklyn.core.typereg.RegisteredTypePredicates;
@@ -64,9 +67,11 @@ import org.osgi.framework.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
+import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
// package-private so we can move this one if/when we move OsgiManager
@@ -74,6 +79,10 @@ class OsgiArchiveInstaller {
private static final Logger log = LoggerFactory.getLogger(OsgiArchiveInstaller.class);
+ public static final ConfigKey<String> PERSIST_MANAGED_BUNDLE_WHITELIST_REGEX = BrooklynServerConfig.PERSIST_MANAGED_BUNDLE_WHITELIST_REGEX;
+
+ public static final ConfigKey<String> PERSIST_MANAGED_BUNDLE_BLACKLIST_REGEX = BrooklynServerConfig.PERSIST_MANAGED_BUNDLE_BLACKLIST_REGEX;
+
final private OsgiManager osgiManager;
private ManagedBundle suppliedKnownBundleMetadata;
private InputStream zipIn;
@@ -93,6 +102,8 @@ class OsgiArchiveInstaller {
private ManagedBundle inferredMetadata;
private final boolean inputStreamSupplied;
+ private volatile Predicate<ManagedBundle> blacklistBundlePersistencePredicate;
+
OsgiArchiveInstaller(OsgiManager osgiManager, ManagedBundle knownBundleMetadata, InputStream zipIn) {
this.osgiManager = osgiManager;
this.suppliedKnownBundleMetadata = knownBundleMetadata;
@@ -121,7 +132,7 @@ class OsgiArchiveInstaller {
}
private ManagementContextInternal mgmt() {
- return (ManagementContextInternal) osgiManager.mgmt;
+ return (ManagementContextInternal) osgiManager.getManagementContext();
}
private synchronized void init() {
@@ -681,15 +692,39 @@ class OsgiArchiveInstaller {
}
}
- private static boolean isBlacklistedForPersistence(ManagedBundle managedBundle) {
- // Specifically, we treat as "managed bundles" (to extract their catalog.bom) the contents of:
+ @VisibleForTesting
+ boolean isBlacklistedForPersistence(ManagedBundle managedBundle) {
+ // We treat as "managed bundles" (to extract their catalog.bom) the contents of:
// - org.apache.brooklyn.core
// - org.apache.brooklyn.policy
// - org.apache.brooklyn.test-framework
// - org.apache.brooklyn.software-*
// - org.apache.brooklyn.library-catalog
// - org.apache.brooklyn.karaf-init (not sure why this one could end up in persisted state!)
- return managedBundle.getSymbolicName().startsWith("org.apache.brooklyn.");
+ // We don't want to persist the entire brooklyn distro! Therefore default is to blacklist those.
+
+ if (blacklistBundlePersistencePredicate == null) {
+ String whitelistRegex = mgmt().getConfig().getConfig(PERSIST_MANAGED_BUNDLE_WHITELIST_REGEX);
+ String blacklistRegex = mgmt().getConfig().getConfig(PERSIST_MANAGED_BUNDLE_BLACKLIST_REGEX);
+
+ final Pattern whitelistPattern = (whitelistRegex != null) ? Pattern.compile(whitelistRegex) : null;
+ final Pattern blacklistPattern = (blacklistRegex != null) ? Pattern.compile(blacklistRegex) : null;
+
+ blacklistBundlePersistencePredicate = new Predicate<ManagedBundle>() {
+ @Override public boolean apply(ManagedBundle input) {
+ String bundleName = input.getSymbolicName();
+ if (whitelistPattern != null && whitelistPattern.matcher(bundleName).matches()) {
+ return false;
+ }
+ if (blacklistPattern != null && blacklistPattern.matcher(bundleName).matches()) {
+ return true;
+ }
+ return false;
+ }
+ };
+ }
+
+ return blacklistBundlePersistencePredicate.apply(managedBundle);
}
private static List<Bundle> findBundlesByVersion(OsgiManager osgiManager, ManagedBundle desired) {
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/03f254fd/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java
index e7bd75e..e3c0e82 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java
@@ -344,6 +344,10 @@ public class OsgiManager {
return Maybe.absent();
}
+ ManagementContext getManagementContext() {
+ return mgmt;
+ }
+
/**
* Clears all record of the managed bundles (use with care!).
*
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/03f254fd/core/src/main/java/org/apache/brooklyn/core/server/BrooklynServerConfig.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/server/BrooklynServerConfig.java b/core/src/main/java/org/apache/brooklyn/core/server/BrooklynServerConfig.java
index 530095d..9bcd409 100644
--- a/core/src/main/java/org/apache/brooklyn/core/server/BrooklynServerConfig.java
+++ b/core/src/main/java/org/apache/brooklyn/core/server/BrooklynServerConfig.java
@@ -131,6 +131,19 @@ public class BrooklynServerConfig {
public static final ConfigKey<Boolean> OSGI_CACHE_CLEAN = ConfigKeys.newBooleanConfigKey("brooklyn.osgi.cache.clean",
"Whether to delete the OSGi directory before and after use; if unset, it will delete if the node ID forms part of the cache dir path (which by default it does) to avoid file leaks");
+ public static final ConfigKey<String> PERSIST_MANAGED_BUNDLE_WHITELIST_REGEX = ConfigKeys.newStringConfigKey(
+ "brooklyn.persistence.bundle.whitelist",
+ "Regex for bundle symbolic names explicitly allowed to be persisted (taking precedence over blacklist); "
+ + "managed bundles will by default be peristed if not blacklisted; "
+ + "they do not need to be explicitly whitelisted.",
+ null);
+
+ public static final ConfigKey<String> PERSIST_MANAGED_BUNDLE_BLACKLIST_REGEX = ConfigKeys.newStringConfigKey(
+ "brooklyn.persistence.bundle.blacklist",
+ "Regex for bundle symbolic names explicitly excluded from persistence (but whitelist takes precedence); "
+ + "if not explicitly blacklisted, managed bundles will by default be peristed",
+ "org\\.apache\\.brooklyn\\..*");
+
/** @see BrooklynServerPaths#getMgmtBaseDir(ManagementContext) */
public static String getMgmtBaseDir(ManagementContext mgmt) {
return BrooklynServerPaths.getMgmtBaseDir(mgmt);
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/03f254fd/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstallerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstallerTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstallerTest.java
new file mode 100644
index 0000000..3a86a3d
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstallerTest.java
@@ -0,0 +1,83 @@
+/*
+ * 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.core.mgmt.ha;
+
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.typereg.ManagedBundle;
+import org.apache.brooklyn.core.server.BrooklynServerConfig;
+import org.apache.brooklyn.core.test.BrooklynMgmtUnitTestSupport;
+import org.apache.brooklyn.util.osgi.VersionedName;
+import org.mockito.Mockito;
+import org.testng.annotations.Test;
+
+public class OsgiArchiveInstallerTest extends BrooklynMgmtUnitTestSupport {
+
+ // The tests here will so far not need an actual OSGi Framework! Therefore we're using the simple
+ // BrooklynMgmtUnitTestSupport, which does not expose `useOsgi` or `osgiReuse`
+
+ @Test
+ public void testBlacklistPersistingOrgApacheBrooklyn() throws Exception {
+ OsgiManager osgiManager = newMockOsgiManager(mgmt);
+ OsgiArchiveInstaller installer = new OsgiArchiveInstaller(osgiManager, Mockito.mock(ManagedBundle.class), new ByteArrayInputStream(new byte[0]));
+
+ assertTrue(installer.isBlacklistedForPersistence(newMockManagedBundle("org.apache.brooklyn.core", "1.0.0")));
+ assertTrue(installer.isBlacklistedForPersistence(newMockManagedBundle("org.apache.brooklyn.mybundle", "1.0.0")));
+ assertFalse(installer.isBlacklistedForPersistence(newMockManagedBundle("org.apache.different", "1.0.0")));
+ }
+
+ @Test
+ public void testWhitelistPersistingBundle() throws Exception {
+ mgmt.getBrooklynProperties().put(BrooklynServerConfig.PERSIST_MANAGED_BUNDLE_WHITELIST_REGEX, "org\\.apache\\.brooklyn\\.mywhitelistedbundle");
+ OsgiManager osgiManager = newMockOsgiManager(mgmt);
+ OsgiArchiveInstaller installer = new OsgiArchiveInstaller(osgiManager, Mockito.mock(ManagedBundle.class), new ByteArrayInputStream(new byte[0]));
+
+ assertTrue(installer.isBlacklistedForPersistence(newMockManagedBundle("org.apache.brooklyn.core", "1.0.0")));
+ assertFalse(installer.isBlacklistedForPersistence(newMockManagedBundle("org.apache.brooklyn.mywhitelistedbundle", "1.0.0")));
+ }
+
+ @Test
+ public void testCustomBlacklistPersistingBundle() throws Exception {
+ mgmt.getBrooklynProperties().put(BrooklynServerConfig.PERSIST_MANAGED_BUNDLE_BLACKLIST_REGEX, "org\\.example\\.myblacklistprefix.*");
+ OsgiManager osgiManager = newMockOsgiManager(mgmt);
+ OsgiArchiveInstaller installer = new OsgiArchiveInstaller(osgiManager, Mockito.mock(ManagedBundle.class), new ByteArrayInputStream(new byte[0]));
+
+ assertTrue(installer.isBlacklistedForPersistence(newMockManagedBundle("org.example.myblacklistprefix.mysuffix", "1.0.0")));
+ assertFalse(installer.isBlacklistedForPersistence(newMockManagedBundle("org.apache.brooklyn.core", "1.0.0")));
+ }
+
+ public OsgiManager newMockOsgiManager(ManagementContext mgmt) throws Exception {
+ OsgiManager result = Mockito.mock(OsgiManager.class);
+ Mockito.when(result.getManagementContext()).thenReturn(mgmt);
+ return result;
+ }
+
+ private ManagedBundle newMockManagedBundle(String symbolicName, String version) {
+ VersionedName versioneName = new VersionedName(symbolicName, version);
+ ManagedBundle result = Mockito.mock(ManagedBundle.class);
+ Mockito.when(result.getSymbolicName()).thenReturn(symbolicName);
+ Mockito.when(result.getOsgiVersionString()).thenReturn(versioneName.getOsgiVersionString());
+ Mockito.when(result.getVersionedName()).thenReturn(versioneName);
+ return result;
+ }
+}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/03f254fd/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestFixture.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestFixture.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestFixture.java
index efe7d28..b80d857 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestFixture.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/rebind/RebindTestFixture.java
@@ -39,8 +39,10 @@ import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
import org.apache.brooklyn.core.mgmt.persist.FileBasedObjectStore;
import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.server.BrooklynServerConfig;
import org.apache.brooklyn.util.core.task.BasicExecutionManager;
import org.apache.brooklyn.util.os.Os;
+import org.apache.brooklyn.util.osgi.OsgiTestResources;
import org.apache.brooklyn.util.repeat.Repeater;
import org.apache.brooklyn.util.text.Identifiers;
import org.apache.brooklyn.util.time.Duration;
@@ -82,11 +84,18 @@ public abstract class RebindTestFixture<T extends StartableApplication> {
}
protected BrooklynProperties createBrooklynProperties() {
+ BrooklynProperties result;
if (useLiveManagementContext()) {
- return BrooklynProperties.Factory.newDefault();
+ result = BrooklynProperties.Factory.newDefault();
} else {
- return BrooklynProperties.Factory.newEmpty();
+ result = BrooklynProperties.Factory.newEmpty();
}
+ // By default, will not persist "org.apache.brooklyn.*" bundles; therefore explicitly whitelist
+ // such things commonly used in tests.
+ String whitelistRegex = OsgiTestResources.BROOKLYN_TEST_MORE_ENTITIES_SYMBOLIC_NAME_FULL
+ + "|" + OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_SYMBOLIC_NAME_FULL;
+ result.put(BrooklynServerConfig.PERSIST_MANAGED_BUNDLE_WHITELIST_REGEX, whitelistRegex);
+ return result;
}
/** @return A started management context */
[4/7] brooklyn-server git commit: PR #867: avoid duplicate bundles in
persistence
Posted by he...@apache.org.
PR #867: avoid duplicate bundles in persistence
Previously, when the “initial catalog” bundles were persisted at
Brooklyn startup, we’d then read the existing persisted state bundles.
The latter would include duplicates of the “initial catalog”. The
persisted state would therefore get duplicates every time Brooklyn
started.
This fixes it by deleted from persisted state any bundles that were
“duplicates” of existing brooklyn-managed-bundles.
Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/5d13ebfb
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/5d13ebfb
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/5d13ebfb
Branch: refs/heads/master
Commit: 5d13ebfb78982f257445d81ec327f225da562e20
Parents: 8519689
Author: Aled Sage <al...@gmail.com>
Authored: Thu Oct 26 23:00:03 2017 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Fri Oct 27 13:50:11 2017 +0100
----------------------------------------------------------------------
.../brooklyn/api/mgmt/rebind/RebindManager.java | 9 +-
.../catalog/internal/CatalogInitialization.java | 37 +++++-
.../mgmt/ha/HighAvailabilityManagerImpl.java | 13 +-
.../brooklyn/core/mgmt/ha/OsgiManager.java | 18 +++
.../NonDeploymentManagementContext.java | 5 +
.../rebind/PeriodicDeltaChangeListener.java | 19 ++-
.../core/mgmt/rebind/RebindManagerImpl.java | 5 +
.../core/typereg/BasicManagedBundle.java | 3 +
.../AbstractBrooklynLauncherRebindTest.java | 28 +++-
.../BrooklynLauncherRebindCatalogOsgiTest.java | 132 +++++++++++++++++++
10 files changed, 259 insertions(+), 10 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/5d13ebfb/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/RebindManager.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/RebindManager.java b/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/RebindManager.java
index e87a577..ecf56c2 100644
--- a/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/RebindManager.java
+++ b/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/RebindManager.java
@@ -89,7 +89,14 @@ public interface RebindManager {
/** Stops the background reading (mirroring) of state.
* Interrupts any current activity and waits for it to cease. */
public void stopReadOnly();
-
+
+ /**
+ * Resets the effects of previously being read-only, ready to be used again (e.g. when promoting to master).
+ * Expected to be called after {@link #stopReadOnly()} (thus long after {@link #setPersister(BrooklynMementoPersister)},
+ * and before {@link #rebind(ClassLoader, RebindExceptionHandler, ManagementNodeState)} followed by {@link #start()}.
+ */
+ public void reset();
+
/** Starts the appropriate background processes, {@link #startPersistence()} if {@link ManagementNodeState#MASTER},
* {@link #startReadOnly()} if {@link ManagementNodeState#HOT_STANDBY} or {@link ManagementNodeState#HOT_BACKUP} */
public void start();
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/5d13ebfb/core/src/main/java/org/apache/brooklyn/core/catalog/internal/CatalogInitialization.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/catalog/internal/CatalogInitialization.java b/core/src/main/java/org/apache/brooklyn/core/catalog/internal/CatalogInitialization.java
index 225e3fd..ff9219a 100644
--- a/core/src/main/java/org/apache/brooklyn/core/catalog/internal/CatalogInitialization.java
+++ b/core/src/main/java/org/apache/brooklyn/core/catalog/internal/CatalogInitialization.java
@@ -199,6 +199,20 @@ public class CatalogInitialization implements ManagementContextInjectable {
}
/**
+ * Clears all record of the brooklyn-managed-bundles (so use with care!).
+ *
+ * Used when promoting from HOT_STANDBY to MASTER. Previous actions performed as HOT_STANDBY
+ * will have been done in read-only mode. When we rebind in anger as master, we want to do this
+ * without a previous cache of managed bundles.
+ */
+ public void clearBrooklynManagedBundles() {
+ Maybe<OsgiManager> osgiManager = managementContext.getOsgiManager();
+ if (osgiManager.isPresent()) {
+ osgiManager.get().clearManagedBundles();
+ }
+ }
+
+ /**
* Adds the given persisted catalog items.
*
* Can be called multiple times, e.g.:
@@ -381,7 +395,7 @@ public class CatalogInitialization implements ManagementContextInjectable {
try {
// Always installing the bundles from persisted state
- installBundles(persistedState.getBundles(), exceptionHandler, rebindLogger);
+ installPersistedBundles(persistedState.getBundles(), exceptionHandler, rebindLogger);
BrooklynCatalog catalog = managementContext.getCatalog();
catalog.addCatalogLegacyItemsOnRebind(persistedState.getLegacyCatalogItems());
@@ -453,8 +467,8 @@ public class CatalogInitialization implements ManagementContextInjectable {
}
}
- private void installBundles(Map<VersionedName, InstallableManagedBundle> bundles, RebindExceptionHandler exceptionHandler, RebindLogger rebindLogger) {
- List<OsgiBundleInstallationResult> installs = MutableList.of();
+ private void installPersistedBundles(Map<VersionedName, InstallableManagedBundle> bundles, RebindExceptionHandler exceptionHandler, RebindLogger rebindLogger) {
+ Map<InstallableManagedBundle, OsgiBundleInstallationResult> installs = MutableMap.of();
// Install the bundles
for (Map.Entry<VersionedName, InstallableManagedBundle> entry : bundles.entrySet()) {
@@ -462,7 +476,7 @@ public class CatalogInitialization implements ManagementContextInjectable {
InstallableManagedBundle installableBundle = entry.getValue();
rebindLogger.debug("RebindManager installing bundle {}", bundleId);
try (InputStream in = installableBundle.getInputStream()) {
- installs.add(installBundle(installableBundle.getManagedBundle(), in));
+ installs.put(installableBundle, installBundle(installableBundle.getManagedBundle(), in));
} catch (Exception e) {
exceptionHandler.onCreateFailed(BrooklynObjectType.MANAGED_BUNDLE, bundleId.toString(), installableBundle.getManagedBundle().getSymbolicName(), e);
}
@@ -470,7 +484,7 @@ public class CatalogInitialization implements ManagementContextInjectable {
// Start the bundles (now that we've installed them all)
Set<RegisteredType> installedTypes = MutableSet.of();
- for (OsgiBundleInstallationResult br: installs) {
+ for (OsgiBundleInstallationResult br : installs.values()) {
try {
startBundle(br);
Iterables.addAll(installedTypes, managementContext.getTypeRegistry().getMatching(
@@ -484,6 +498,19 @@ public class CatalogInitialization implements ManagementContextInjectable {
if (!installedTypes.isEmpty()) {
validateAllTypes(installedTypes, exceptionHandler);
}
+
+ for (Map.Entry<InstallableManagedBundle, OsgiBundleInstallationResult> entry : installs.entrySet()) {
+ ManagedBundle bundle = entry.getKey().getManagedBundle();
+ OsgiBundleInstallationResult result = entry.getValue();
+ if (result.getCode() == OsgiBundleInstallationResult.ResultCode.IGNORING_BUNDLE_AREADY_INSTALLED
+ && !result.getMetadata().getId().equals(bundle.getId())) {
+ // Bundle was already installed as a "Brooklyn managed bundle" (with different id),
+ // and will thus be persisted with that id.
+ // For example, can happen if it is in the "initial catalog" and also in persisted state.
+ // Delete this copy from the persisted state as it is a duplicate.
+ managementContext.getRebindManager().getChangeListener().onUnmanaged(bundle);
+ }
+ }
}
private void validateAllTypes(Set<RegisteredType> installedTypes, RebindExceptionHandler exceptionHandler) {
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/5d13ebfb/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerImpl.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerImpl.java
index cc8b645..dac64a4 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerImpl.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/HighAvailabilityManagerImpl.java
@@ -545,6 +545,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager {
// TODO ideally there'd be an incremental rebind as well as an incremental persist
managementContext.getRebindManager().stopReadOnly();
clearManagedItems(ManagementTransitionMode.transitioning(BrooklynObjectManagementMode.LOADED_READ_ONLY, BrooklynObjectManagementMode.UNMANAGED_PERSISTED));
+ managementContext.getRebindManager().reset();
}
stateListener.onStateChange(getNodeState());
@@ -929,11 +930,19 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager {
managementContext.getRebindManager().stopPersistence();
managementContext.getRebindManager().stopReadOnly();
clearManagedItems(mode);
+ managementContext.getRebindManager().reset();
// tasks are cleared as part of unmanaging entities above
}
- /** clears all managed items from the management context; same items destroyed as in the course of a rebind cycle */
+ /**
+ * Clears all managed items from the management context.
+ *
+ * The same items are destroyed as in the course of a rebind cycle, except for clearBrooklynManagedBundles.
+ * That last operation could be expensive (causing bundles to be installed again). Therefore we only do it
+ * when we stop being a hotProxy or when we are demoted (e.g. during the periodic rebind as hot_stanby
+ * we will not repeatedly clear the brooklyn-managed-bundles).
+ */
protected void clearManagedItems(ManagementTransitionMode mode) {
// start with the root applications
for (Application app: managementContext.getApplications()) {
@@ -957,6 +966,8 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager {
}
((BasicBrooklynCatalog)managementContext.getCatalog()).reset(CatalogDto.newEmptyInstance("<reset-by-ha-status-change>"));
+
+ managementContext.getCatalogInitialization().clearBrooklynManagedBundles();
}
/** Starts hot standby or hot backup, in foreground
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/5d13ebfb/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java
index 9f47a44..e7bd75e 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java
@@ -117,6 +117,13 @@ public class OsgiManager {
private final Map<String, String> managedBundlesUidByUrl = MutableMap.of();
private final Map<VersionedName,ManagedBundle> wrapperBundles = MutableMap.of();
+ synchronized void clear() {
+ managedBundlesByUid.clear();
+ managedBundlesUidByVersionedName.clear();
+ managedBundlesUidByUrl.clear();
+ wrapperBundles.clear();
+ }
+
synchronized Map<String, ManagedBundle> getManagedBundles() {
return ImmutableMap.copyOf(managedBundlesByUid);
}
@@ -337,6 +344,17 @@ public class OsgiManager {
return Maybe.absent();
}
+ /**
+ * Clears all record of the managed bundles (use with care!).
+ *
+ * Used when promoting from HOT_STANDBY to MASTER. Previous actions performed as HOT_STANDBY
+ * will have been done in read-only mode. When we rebind in anger as master, we want to do this
+ * without a previous cache of managed bundles.
+ */
+ public void clearManagedBundles() {
+ managedBundlesRecord.clear();
+ }
+
/** Map of bundles by UID */
public Map<String, ManagedBundle> getManagedBundles() {
return managedBundlesRecord.getManagedBundles();
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/5d13ebfb/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/NonDeploymentManagementContext.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/NonDeploymentManagementContext.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/NonDeploymentManagementContext.java
index a1ab3df..1fc705c 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/NonDeploymentManagementContext.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/internal/NonDeploymentManagementContext.java
@@ -579,6 +579,11 @@ public class NonDeploymentManagementContext implements ManagementContextInternal
}
@Override
+ public void reset() {
+ throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation.");
+ }
+
+ @Override
public void start() {
throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation.");
}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/5d13ebfb/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/PeriodicDeltaChangeListener.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/PeriodicDeltaChangeListener.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/PeriodicDeltaChangeListener.java
index a5af458..e4b2d7d 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/PeriodicDeltaChangeListener.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/PeriodicDeltaChangeListener.java
@@ -283,6 +283,21 @@ public class PeriodicDeltaChangeListener implements ChangeListener {
}
}
+ /**
+ * Resets persistence from STOPPED, back to the initial state of INIT.
+ *
+ * Used when transitioning from HOT_STANDBY to MASTER. On rebinding as MASTER, we want it to
+ * behave in the same way as it would from INIT (e.g. populating the deltaCollector, etc).
+ */
+ void reset() {
+ synchronized (startStopMutex) {
+ if (state != ListenerState.STOPPED) {
+ return;
+ }
+ state = ListenerState.INIT;
+ }
+ }
+
/** Waits for any in-progress writes to be completed then for or any unwritten data to be written. */
@VisibleForTesting
public void waitForPendingComplete(Duration timeout, boolean canTrigger) throws InterruptedException, TimeoutException {
@@ -327,7 +342,7 @@ public class PeriodicDeltaChangeListener implements ChangeListener {
* Indicates whether persistence is active.
* Even when not active, changes will still be tracked unless {@link #isStopped()}.
*/
- private boolean isActive() {
+ boolean isActive() {
return state == ListenerState.RUNNING && persister != null && !isStopped();
}
@@ -336,7 +351,7 @@ public class PeriodicDeltaChangeListener implements ChangeListener {
* in which case will not persist or store anything
* (except for a final internal persistence called while STOPPING.)
*/
- private boolean isStopped() {
+ boolean isStopped() {
return state == ListenerState.STOPPING || state == ListenerState.STOPPED || executionContext.isShutdown();
}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/5d13ebfb/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindManagerImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindManagerImpl.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindManagerImpl.java
index 0830900..8a096d4 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindManagerImpl.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindManagerImpl.java
@@ -364,6 +364,11 @@ public class RebindManagerImpl implements RebindManager {
LOG.debug("Stopped read-only rebinding ("+this+"), mgmt "+managementContext.getManagementNodeId());
}
}
+
+ @Override
+ public void reset() {
+ if (persistenceRealChangeListener != null && !persistenceRealChangeListener.isActive()) persistenceRealChangeListener.reset();
+ }
@Override
public void start() {
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/5d13ebfb/core/src/main/java/org/apache/brooklyn/core/typereg/BasicManagedBundle.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/typereg/BasicManagedBundle.java b/core/src/main/java/org/apache/brooklyn/core/typereg/BasicManagedBundle.java
index 860bf5a..e7489c9 100644
--- a/core/src/main/java/org/apache/brooklyn/core/typereg/BasicManagedBundle.java
+++ b/core/src/main/java/org/apache/brooklyn/core/typereg/BasicManagedBundle.java
@@ -145,6 +145,9 @@ public class BasicManagedBundle extends AbstractBrooklynObject implements Manage
// this makes equality with other OsgiBundleWithUrl items symmetric,
// but for two MB's we look additionally at checksum
if (!Objects.equal(checksum, ((ManagedBundle)other).getChecksum())) return false;
+
+ // only equal if have the same ManagedBundle uid; important for persistence.changeListener().unmanage()
+ if (!Objects.equal(getId(), ((ManagedBundle)other).getId())) return false;
}
return true;
}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/5d13ebfb/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java
index 400e3a8..474c72b 100644
--- a/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java
@@ -70,6 +70,7 @@ import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
@@ -205,10 +206,15 @@ public abstract class AbstractBrooklynLauncherRebindTest {
Assert.assertTrue(compareIterablesWithoutOrderMatters(ids, idsFromItems), String.format("Expected %s, found %s", ids, idsFromItems));
}
- protected void assertManagedBundle(BrooklynLauncher launcher, VersionedName bundleId, Set<VersionedName> expectedCatalogItems) {
+ protected ManagedBundle findManagedBundle(BrooklynLauncher launcher, VersionedName bundleId) {
ManagementContextInternal mgmt = (ManagementContextInternal)launcher.getManagementContext();
ManagedBundle bundle = mgmt.getOsgiManager().get().getManagedBundle(bundleId);
assertNotNull(bundle, bundleId+" not found");
+ return bundle;
+ }
+
+ protected void assertManagedBundle(BrooklynLauncher launcher, VersionedName bundleId, Set<VersionedName> expectedCatalogItems) {
+ assertNotNull(findManagedBundle(launcher, bundleId), bundleId+" not found");
Set<VersionedName> actualCatalogItems = new LinkedHashSet<>();
Iterable<RegisteredType> types = launcher.getManagementContext().getTypeRegistry().getAll();
@@ -225,6 +231,26 @@ public abstract class AbstractBrooklynLauncherRebindTest {
ManagedBundle bundle = mgmt.getOsgiManager().get().getManagedBundle(bundleId);
assertNull(bundle, bundleId+" should not exist");
}
+
+ protected Set<String> getPersistenceListing(BrooklynObjectType type) throws Exception {
+ File persistedSubdir = getPersistanceSubdirectory(type);
+ return ImmutableSet.copyOf(persistedSubdir.list((dir,name) -> !name.endsWith(".jar")));
+ }
+
+ private File getPersistanceSubdirectory(BrooklynObjectType type) {
+ String dir;
+ switch (type) {
+ case ENTITY: dir = "entities"; break;
+ case LOCATION: dir = "locations"; break;
+ case POLICY: dir = "policies"; break;
+ case ENRICHER: dir = "enrichers"; break;
+ case FEED: dir = "feeds"; break;
+ case CATALOG_ITEM: dir = "catalog"; break;
+ case MANAGED_BUNDLE: dir = "bundles"; break;
+ default: throw new UnsupportedOperationException("type="+type);
+ }
+ return new File(persistenceDir, dir);
+ }
private static <T> boolean compareIterablesWithoutOrderMatters(Iterable<T> a, Iterable<T> b) {
List<T> aList = Lists.newArrayList(a);
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/5d13ebfb/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
index 8985147..e953c8d 100644
--- a/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
@@ -29,11 +29,17 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Set;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
+import org.apache.brooklyn.api.objs.BrooklynObjectType;
import org.apache.brooklyn.core.catalog.internal.BasicBrooklynCatalog;
import org.apache.brooklyn.core.catalog.internal.CatalogInitialization;
import org.apache.brooklyn.core.mgmt.ha.OsgiBundleInstallationResult;
import org.apache.brooklyn.core.mgmt.ha.OsgiManager;
import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.test.Asserts;
import org.apache.brooklyn.test.support.TestResourceUnavailableException;
import org.apache.brooklyn.util.core.osgi.Osgis;
import org.apache.brooklyn.util.exceptions.ReferenceWithError;
@@ -427,6 +433,132 @@ public class BrooklynLauncherRebindCatalogOsgiTest extends AbstractBrooklynLaunc
assertManagedBundle(newLauncher, COM_EXAMPLE_BUNDLE_ID, COM_EXAMPLE_BUNDLE_CATALOG_IDS);
}
+ @Test
+ public void testPersistsSingleCopyOfInitialCatalog() throws Exception {
+ Set<VersionedName> bundleItems = ImmutableSet.of(VersionedName.fromString("one:1.0.0"));
+ String bundleBom = createCatalogYaml(ImmutableList.of(), bundleItems);
+ VersionedName bundleName = new VersionedName("org.example.testRebindGetsInitialOsgiCatalog"+Identifiers.makeRandomId(4), "1.0.0");
+ File bundleFile = newTmpBundle(ImmutableMap.of(BasicBrooklynCatalog.CATALOG_BOM, bundleBom.getBytes(StandardCharsets.UTF_8)), bundleName);
+ File initialBomFile = newTmpFile(createCatalogYaml(ImmutableList.of(bundleFile.toURI()), ImmutableList.of()));
+
+ // First launcher should persist the bundle
+ BrooklynLauncher launcher = newLauncherForTests(initialBomFile.getAbsolutePath());
+ launcher.start();
+ String bundlePersistenceId = findManagedBundle(launcher, bundleName).getId();
+ launcher.terminate();
+ assertEquals(getPersistenceListing(BrooklynObjectType.MANAGED_BUNDLE), ImmutableSet.of(bundlePersistenceId));
+
+ // Second launcher should read from initial catalog and persisted state. Both those bundles have different ids.
+ // Should only end up with one of them in persisted state.
+ // (Current impl is that it will be the "initial catalog" version, discarding the previously persisted bundle).
+ BrooklynLauncher launcher2 = newLauncherForTests(initialBomFile.getAbsolutePath());
+ launcher2.start();
+ String bundlePersistenceId2 = findManagedBundle(launcher2, bundleName).getId();
+ launcher2.terminate();
+ assertEquals(getPersistenceListing(BrooklynObjectType.MANAGED_BUNDLE), ImmutableSet.of(bundlePersistenceId2));
+ }
+
+ /**
+ * It is vital that the brooklyn-managed-bundle ids match those in persisted state. If they do not,
+ * then deletion of a brooklyn-managed-bundle will not actually delete it from persisted state.
+ *
+ * Under the covers, the scenario of HOT_STANDBY promoted to MASTER is very different from when
+ * it starts as master:
+ * <ol>
+ * <li> We become hot-standby; we call RebindManager.startReaOnly (so PeriodicDeltaChangeListener
+ * discards changes).
+ * <li>We repeatedly call rebindManager.rebind():
+ * <ol>
+ * <li>Each time, we populate the catalog from the initial and persisted state
+ * <li>The OsgiManager.ManagedBundleRecords is populated the first time; subsequent times we see it is
+ * already a managed bundle so do nothing.
+ * <li>The first time, it calls to the PeriodicDeltaChangeListener about the managed bundle, but the
+ * change is discarded (because we are read-only, and PeriodicDeltaChangeListener is 'STOPPED').
+ * </ol>
+ * <li>On HighAvailabilityManagerImpl promoting us from HOT_STANDBY to MASTER:
+ * <ol>
+ * <li>Calls rebindManager.stopReadOnly; this resets the PeriodicDeltaChangeListener
+ * (so that it's in the INIT state, ready for recording whatever happens while we're promoting to MASTER)
+ * <li>Clears our cache of brooklyn-managed-bundles. This is important so that we record
+ * (and thus update persistence) for the "initial catalog" bundles being managed.
+ * <li>Calls rebindManager.rebind(); we are in a good state to do this, having cleared out whatever
+ * was done previously while we were hot-standby.
+ * <ol>
+ * <li>The new ManagedBundle instances from the "initial catalog" are recorded in the
+ * PeriodicDeltaChangeListener.
+ * <li>For persisted bundles, if they were duplicates of existing brooklyn-managed-bundles then they
+ * are recorded as deleted (in PeriodicDeltaChangeListener).
+ * </ol>
+ * <li>HighAvailabilityManagerImpl.promoteToMaster() then calls rebindManager.start(), which switches us
+ * into writable mode. The changes recorded in PeriodicDeltaChangeListener are applied to the
+ * persisted state.
+ * </ol>
+ * </ol>
+ *
+ * In contrast, when we start as MASTER:
+ * <ol>
+ * <li>We call rebindManager.setPersister(); the PeriodicDeltaChangeListener is in 'INIT' state
+ * so will record any changes.
+ * <li>We call rebindManager.rebind(); it populates the catalog from the initial and persisted state;
+ * <ol>
+ * <li>The new ManagedBundle instances from the "initial catalog" are recorded in the PeriodicDeltaChangeListener.
+ * <li>For persisted bundles, if they were duplicates of existing brooklyn-managed-bundles then they
+ * are recorded as deleted (in PeriodicDeltaChangeListener).
+ * </ol>
+ * <li>We call rebindManager.startPersistence(); this enables write-access to the persistence store,
+ * and starts the PeriodicDeltaChangeListener (so all recorded changes are applied).
+ * </ol>
+ */
+ @Test
+ public void testPersistsSingleCopyOfInitialCatalogOnHotStandbyPromotion() throws Exception {
+ Set<VersionedName> bundleItems = ImmutableSet.of(VersionedName.fromString("one:1.0.0"));
+ String bundleBom = createCatalogYaml(ImmutableList.of(), bundleItems);
+ VersionedName bundleName = new VersionedName("org.example.testRebindGetsInitialOsgiCatalog"+Identifiers.makeRandomId(4), "1.0.0");
+ File bundleFile = newTmpBundle(ImmutableMap.of(BasicBrooklynCatalog.CATALOG_BOM, bundleBom.getBytes(StandardCharsets.UTF_8)), bundleName);
+ File initialBomFile = newTmpFile(createCatalogYaml(ImmutableList.of(bundleFile.toURI()), ImmutableList.of()));
+
+ // First launcher should persist the bundle
+ BrooklynLauncher launcher = newLauncherForTests(initialBomFile.getAbsolutePath())
+ .highAvailabilityMode(HighAvailabilityMode.MASTER);
+ launcher.start();
+ String bundlePersistenceId = findManagedBundle(launcher, bundleName).getId();
+ RebindTestUtils.waitForPersisted(launcher.getManagementContext());
+ assertEquals(getPersistenceListing(BrooklynObjectType.MANAGED_BUNDLE), ImmutableSet.of(bundlePersistenceId));
+
+ // Second launcher goes into hot-standby, and will thus rebind periodically.
+ // When we terminate the first launcher, it will be promoted to master automatically.
+ BrooklynLauncher launcher2 = newLauncherForTests(initialBomFile.getAbsolutePath())
+ .highAvailabilityMode(HighAvailabilityMode.HOT_STANDBY);
+ launcher2.start();
+ assertHotStandbyEventually(launcher2);
+
+ launcher.terminate();
+ assertMasterEventually(launcher2);
+ String bundlePersistenceId2 = findManagedBundle(launcher2, bundleName).getId();
+ launcher2.terminate();
+ assertEquals(getPersistenceListing(BrooklynObjectType.MANAGED_BUNDLE), ImmutableSet.of(bundlePersistenceId2));
+ }
+
+ private void assertHotStandbyEventually(BrooklynLauncher launcher) {
+ ManagementContext mgmt = launcher.getManagementContext();
+ Asserts.succeedsEventually(new Runnable() {
+ public void run() {
+ assertTrue(mgmt.isStartupComplete());
+ assertTrue(mgmt.isRunning());
+ assertEquals(mgmt.getHighAvailabilityManager().getNodeState(), ManagementNodeState.HOT_STANDBY);
+ }});
+ }
+
+ private void assertMasterEventually(BrooklynLauncher launcher) {
+ ManagementContext mgmt = launcher.getManagementContext();
+ Asserts.succeedsEventually(new Runnable() {
+ public void run() {
+ assertTrue(mgmt.isStartupComplete());
+ assertTrue(mgmt.isRunning());
+ assertEquals(mgmt.getHighAvailabilityManager().getNodeState(), ManagementNodeState.MASTER);
+ }});
+ }
+
private Bundle installBundle(Framework framework, File bundle) throws Exception {
try (FileInputStream stream = new FileInputStream(bundle)) {
return framework.getBundleContext().installBundle(bundle.toURI().toString(), stream);
[2/7] brooklyn-server git commit: BROOKLYN-546: add unit test
Posted by he...@apache.org.
BROOKLYN-546: add unit test
Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/2a539c0d
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/2a539c0d
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/2a539c0d
Branch: refs/heads/master
Commit: 2a539c0dc181c7b82e0e8e8c1b2345b464325d10
Parents: bfabe7c
Author: Aled Sage <al...@gmail.com>
Authored: Mon Oct 23 17:37:05 2017 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Fri Oct 27 12:31:20 2017 +0100
----------------------------------------------------------------------
.../brooklyn/core/mgmt/ha/OsgiManager.java | 11 ++
.../AbstractBrooklynLauncherRebindTest.java | 10 +-
.../BrooklynLauncherRebindCatalogOsgiTest.java | 100 ++++++++++++++++++-
3 files changed, 119 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/2a539c0d/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java
index 995f7ed..9f47a44 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiManager.java
@@ -76,6 +76,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.Beta;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@@ -326,6 +327,16 @@ public class OsgiManager {
brooklynBundlesCacheDir = null;
}
+ @VisibleForTesting
+ public static Maybe<Framework> tryPeekFrameworkForReuse() {
+ synchronized (OSGI_FRAMEWORK_CONTAINERS_FOR_REUSE) {
+ if (!OSGI_FRAMEWORK_CONTAINERS_FOR_REUSE.isEmpty()) {
+ return Maybe.of(OSGI_FRAMEWORK_CONTAINERS_FOR_REUSE.get(0));
+ }
+ }
+ return Maybe.absent();
+ }
+
/** Map of bundles by UID */
public Map<String, ManagedBundle> getManagedBundles() {
return managedBundlesRecord.getManagedBundles();
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/2a539c0d/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java
index 0369862..89bcae0 100644
--- a/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java
@@ -25,6 +25,7 @@ import static org.testng.Assert.assertNull;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
+import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
@@ -138,7 +139,14 @@ public abstract class AbstractBrooklynLauncherRebindTest {
Files.write(contents, file, Charsets.UTF_8);
return file;
}
-
+
+ protected File newTmpCopy(File orig) throws Exception {
+ File file = java.nio.file.Files.createTempFile("brooklynLauncherRebindTest-"+Identifiers.makeRandomId(4), "txt").toFile();
+ tmpFiles.add(file);
+ Streams.copyClose(new FileInputStream(orig), new FileOutputStream(file));
+ return file;
+ }
+
protected File newTmpBundle(Map<String, byte[]> files, VersionedName bundleName) {
return newTmpBundle(files, bundleName, ImmutableMap.of());
}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/2a539c0d/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
index 2e9c78e..d4e8c75 100644
--- a/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
@@ -18,15 +18,30 @@
*/
package org.apache.brooklyn.launcher;
+import static org.testng.Assert.assertEquals;
+
import java.io.File;
import java.nio.charset.StandardCharsets;
+import java.io.FileInputStream;
+import java.net.URI;
+import java.util.LinkedHashSet;
+import java.util.List;
import java.util.Set;
+import org.apache.brooklyn.api.typereg.ManagedBundle;
+import org.apache.brooklyn.api.typereg.RegisteredType;
import org.apache.brooklyn.core.catalog.internal.BasicBrooklynCatalog;
import org.apache.brooklyn.core.catalog.internal.CatalogInitialization;
+import org.apache.brooklyn.core.mgmt.ha.OsgiManager;
+import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.entity.stock.BasicEntity;
import org.apache.brooklyn.test.support.TestResourceUnavailableException;
+import org.apache.brooklyn.util.core.osgi.Osgis;
+import org.apache.brooklyn.util.os.Os;
import org.apache.brooklyn.util.osgi.OsgiTestResources;
import org.apache.brooklyn.util.osgi.VersionedName;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.launch.Framework;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -38,6 +53,8 @@ import com.google.common.collect.Iterables;
public class BrooklynLauncherRebindCatalogOsgiTest extends AbstractBrooklynLauncherRebindTest {
+ private static final String CATALOG_EMPTY_INITIAL = "classpath://rebind-test-empty-catalog.bom";
+
private static final VersionedName COM_EXAMPLE_BUNDLE_ID = new VersionedName(
OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_SYMBOLIC_NAME_FULL,
OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_VERSION);
@@ -45,6 +62,8 @@ public class BrooklynLauncherRebindCatalogOsgiTest extends AbstractBrooklynLaunc
private static final Set<VersionedName> COM_EXAMPLE_BUNDLE_CATALOG_IDS = ImmutableSet.of(
new VersionedName("com.example.simpleTest", "0.0.0-SNAPSHOT"));
+ private boolean reuseOsgi = false;
+
@BeforeMethod(alwaysRun=true)
@Override
public void setUp() throws Exception {
@@ -58,7 +77,7 @@ public class BrooklynLauncherRebindCatalogOsgiTest extends AbstractBrooklynLaunc
@Override
protected boolean reuseOsgi() {
- return false;
+ return reuseOsgi;
}
private BrooklynLauncher newLauncherForTests(String catalogInitial) {
@@ -88,6 +107,79 @@ public class BrooklynLauncherRebindCatalogOsgiTest extends AbstractBrooklynLaunc
assertManagedBundle(newLauncher, bundleName, bundleItems);
}
+ /**
+ * See https://issues.apache.org/jira/browse/BROOKLYN-546.
+ *
+ * We built up to launcher3, which will have three things:
+ * 1. a pre-installed "system bundle"
+ * 2. an initial catalog that references this same system bundle (hence the bundle will be "managed")
+ * 3. persisted state that references this same system bundle.
+ *
+ * At the end of this, we want only one version of that "system bundle" to be installed, but also for
+ * it to be a "brooklyn managed bundle".
+ *
+ * This scenario isn't quite the same as BROOKLYN-546. To make it fail, we'd need to have bundle URLs like:
+ * "mvn:org.apache.brooklyn/brooklyn-software-cm-ansible/1.0.0-SNAPSHOT"
+ * (as is used in brooklyn-library/karaf/catalog/target/classes/catalog.bom).
+ *
+ * When that is used, the "osgi unique url" is the same as for the system library, so when it tries
+ * to replace the library by calling "installBundle" then it fails.
+ *
+ * We ensure this isn't happening by asserting that our manually installed "system bundle" is still the same.
+ */
+ @Test
+ public void testRebindWithSystemBundleInCatalog() throws Exception {
+ Set<VersionedName> bundleItems = ImmutableSet.of(VersionedName.fromString("one:1.0.0-SNAPSHOT"));
+ String bundleBom = createCatalogYaml(ImmutableList.of(), bundleItems);
+ VersionedName bundleName = new VersionedName("org.example.testRebindWithSystemBundleInCatalog", "1.0.0.SNAPSHOT");
+ File bundleFile = newTmpBundle(ImmutableMap.of(BasicBrooklynCatalog.CATALOG_BOM, bundleBom.getBytes(StandardCharsets.UTF_8)), bundleName);
+ File bundleFileCopy = newTmpCopy(bundleFile);
+
+ File initialBomFile = newTmpFile(createCatalogYaml(ImmutableList.of(bundleFile.toURI()), ImmutableList.of()));
+
+ Framework reusedFamework = null;
+ Bundle pseudoSystemBundle = null;
+ try {
+ reuseOsgi = true;
+
+ // Launch and terminate brooklyn to ensure there is a reusable OSGi Framework
+ BrooklynLauncher launcher = newLauncherForTests(CATALOG_EMPTY_INITIAL);
+ launcher.start();
+ launcher.terminate();
+ Os.deleteRecursively(persistenceDir);
+
+ // Add our bundle, so it feels for all intents and purposes like a "system bundle"
+ reusedFamework = OsgiManager.tryPeekFrameworkForReuse().get();
+ pseudoSystemBundle = installBundle(reusedFamework, bundleFileCopy);
+
+ // Launch brooklyn, where initial catalog includes a duplicate of the system bundle
+ BrooklynLauncher launcher2 = newLauncherForTests(initialBomFile.getAbsolutePath());
+ launcher2.start();
+ assertCatalogConsistsOfIds(launcher2, bundleItems);
+ assertManagedBundle(launcher2, bundleName, bundleItems);
+ launcher2.terminate();
+
+ // Launch brooklyn, where persisted state now includes the initial catalog's bundle
+ BrooklynLauncher launcher3 = newLauncherForTests(initialBomFile.getAbsolutePath());
+ launcher3.start();
+ assertCatalogConsistsOfIds(launcher3, bundleItems);
+ assertManagedBundle(launcher3, bundleName, bundleItems);
+
+ // Should not have replaced the original "system bundle"
+ reusedFamework.getBundleContext().getBundles();
+ List<Bundle> matchingBundles = Osgis.bundleFinder(reusedFamework).symbolicName(bundleName.getSymbolicName()).version(bundleName.getOsgiVersionString()).findAll();
+ assertEquals(matchingBundles, ImmutableList.of(pseudoSystemBundle));
+
+ launcher3.terminate();
+
+ } finally {
+ reuseOsgi = false;
+ if (pseudoSystemBundle != null && pseudoSystemBundle.getState() != Bundle.UNINSTALLED) {
+ pseudoSystemBundle.uninstall();
+ }
+ }
+ }
+
@Test
public void testRebindUpgradesBundleWithSameItems() throws Exception {
Set<VersionedName> bundleItems = ImmutableSet.of(VersionedName.fromString("one:1.0.0"));
@@ -169,4 +261,10 @@ public class BrooklynLauncherRebindCatalogOsgiTest extends AbstractBrooklynLaunc
assertCatalogConsistsOfIds(newLauncher, COM_EXAMPLE_BUNDLE_CATALOG_IDS);
assertManagedBundle(newLauncher, COM_EXAMPLE_BUNDLE_ID, COM_EXAMPLE_BUNDLE_CATALOG_IDS);
}
+
+ private Bundle installBundle(Framework framework, File bundle) throws Exception {
+ try (FileInputStream stream = new FileInputStream(bundle)) {
+ return framework.getBundleContext().installBundle(bundle.toURI().toString(), stream);
+ }
+ }
}
[6/7] brooklyn-server git commit: Make
testPersistsSingleCopyOfInitialCatalogOnHotStandbyPromotion more robust
Posted by he...@apache.org.
Make testPersistsSingleCopyOfInitialCatalogOnHotStandbyPromotion more robust
Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/8a2d51ea
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/8a2d51ea
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/8a2d51ea
Branch: refs/heads/master
Commit: 8a2d51eadac445d24e4b3b05b55b6c0478d0a058
Parents: 03f254f
Author: Aled Sage <al...@gmail.com>
Authored: Fri Oct 27 16:54:45 2017 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Fri Oct 27 20:44:54 2017 +0100
----------------------------------------------------------------------
.../BrooklynLauncherRebindCatalogOsgiTest.java | 25 ++++++++++++++++++--
1 file changed, 23 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/8a2d51ea/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
index e953c8d..e9c7a07 100644
--- a/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
@@ -26,6 +26,7 @@ import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@@ -33,6 +34,7 @@ import org.apache.brooklyn.api.mgmt.ManagementContext;
import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
import org.apache.brooklyn.api.objs.BrooklynObjectType;
+import org.apache.brooklyn.api.typereg.ManagedBundle;
import org.apache.brooklyn.core.catalog.internal.BasicBrooklynCatalog;
import org.apache.brooklyn.core.catalog.internal.CatalogInitialization;
import org.apache.brooklyn.core.mgmt.ha.OsgiBundleInstallationResult;
@@ -42,6 +44,7 @@ import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
import org.apache.brooklyn.test.Asserts;
import org.apache.brooklyn.test.support.TestResourceUnavailableException;
import org.apache.brooklyn.util.core.osgi.Osgis;
+import org.apache.brooklyn.util.exceptions.Exceptions;
import org.apache.brooklyn.util.exceptions.ReferenceWithError;
import org.apache.brooklyn.util.os.Os;
import org.apache.brooklyn.util.osgi.OsgiTestResources;
@@ -527,6 +530,8 @@ public class BrooklynLauncherRebindCatalogOsgiTest extends AbstractBrooklynLaunc
// Second launcher goes into hot-standby, and will thus rebind periodically.
// When we terminate the first launcher, it will be promoted to master automatically.
+ // However, we'll say state="master" before we've fully initialised, so need to use
+ // assert-eventually.
BrooklynLauncher launcher2 = newLauncherForTests(initialBomFile.getAbsolutePath())
.highAvailabilityMode(HighAvailabilityMode.HOT_STANDBY);
launcher2.start();
@@ -534,9 +539,25 @@ public class BrooklynLauncherRebindCatalogOsgiTest extends AbstractBrooklynLaunc
launcher.terminate();
assertMasterEventually(launcher2);
- String bundlePersistenceId2 = findManagedBundle(launcher2, bundleName).getId();
+ assertPersistedBundleListingEqualsEventually(launcher2, ImmutableSet.of(bundleName));
launcher2.terminate();
- assertEquals(getPersistenceListing(BrooklynObjectType.MANAGED_BUNDLE), ImmutableSet.of(bundlePersistenceId2));
+ }
+
+ private void assertPersistedBundleListingEqualsEventually(BrooklynLauncher launcher, Set<VersionedName> bundles) {
+ Asserts.succeedsEventually(new Runnable() {
+ @Override public void run() {
+ try {
+ Set<String> expected = new LinkedHashSet<>();
+ for (VersionedName bundle : bundles) {
+ String bundleUid = findManagedBundle(launcher, bundle).getId();
+ expected.add(bundleUid);
+ }
+ Set<String> persisted = getPersistenceListing(BrooklynObjectType.MANAGED_BUNDLE);
+ assertEquals(persisted, expected);
+ } catch (Exception e) {
+ throw Exceptions.propagate(e);
+ }
+ }});
}
private void assertHotStandbyEventually(BrooklynLauncher launcher) {
[3/7] brooklyn-server git commit: PR #867: incorporate review comments
Posted by he...@apache.org.
PR #867: incorporate review comments
And better handle pre-existing bundles.
Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/85196899
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/85196899
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/85196899
Branch: refs/heads/master
Commit: 85196899f1a7b151767623f3f735c6d155dd5e28
Parents: 2a539c0
Author: Aled Sage <al...@gmail.com>
Authored: Tue Oct 24 13:50:01 2017 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Fri Oct 27 13:49:55 2017 +0100
----------------------------------------------------------------------
.../rebind/mementos/ManagedBundleMemento.java | 5 +
.../camp/brooklyn/AbstractYamlTest.java | 2 +-
.../catalog/CatalogOsgiYamlEntityTest.java | 2 +-
.../catalog/CatalogOsgiYamlVersioningTest.java | 2 +-
.../brooklyn/test/lite/CampYamlLiteTest.java | 2 +-
.../catalog/internal/BasicBrooklynCatalog.java | 2 +-
.../core/mgmt/ha/OsgiArchiveInstaller.java | 241 +++++++++-----
.../core/mgmt/rebind/RebindIteration.java | 2 +-
.../rebind/dto/BasicManagedBundleMemento.java | 20 +-
.../core/typereg/BasicManagedBundle.java | 20 +-
.../AbstractBrooklynLauncherRebindTest.java | 30 +-
.../BrooklynLauncherRebindCatalogOsgiTest.java | 321 ++++++++++++++++---
12 files changed, 494 insertions(+), 155 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/85196899/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/mementos/ManagedBundleMemento.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/mementos/ManagedBundleMemento.java b/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/mementos/ManagedBundleMemento.java
index 7e487ff..ffcd783 100644
--- a/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/mementos/ManagedBundleMemento.java
+++ b/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/mementos/ManagedBundleMemento.java
@@ -18,6 +18,8 @@
*/
package org.apache.brooklyn.api.mgmt.rebind.mementos;
+import javax.annotation.Nullable;
+
import com.google.common.io.ByteSource;
public interface ManagedBundleMemento extends Memento {
@@ -27,6 +29,9 @@ public interface ManagedBundleMemento extends Memento {
String getUrl();
+ @Nullable
+ String getChecksum();
+
ByteSource getJarContent();
void setJarContent(ByteSource byteSource);
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/85196899/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/AbstractYamlTest.java
----------------------------------------------------------------------
diff --git a/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/AbstractYamlTest.java b/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/AbstractYamlTest.java
index 3d4bbd2..091598f 100644
--- a/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/AbstractYamlTest.java
+++ b/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/AbstractYamlTest.java
@@ -263,7 +263,7 @@ public abstract class AbstractYamlTest {
File bf = bundleMaker.createTempZip("test", MutableMap.of(
new ZipEntry(BasicBrooklynCatalog.CATALOG_BOM), new ByteArrayInputStream(catalogYaml.getBytes())));
ReferenceWithError<OsgiBundleInstallationResult> b = ((ManagementContextInternal)mgmt).getOsgiManager().get().installDeferredStart(
- new BasicManagedBundle(bundleName.getSymbolicName(), bundleName.getVersionString(), null),
+ new BasicManagedBundle(bundleName.getSymbolicName(), bundleName.getVersionString(), null, null),
new FileInputStream(bf),
false);
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/85196899/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogOsgiYamlEntityTest.java
----------------------------------------------------------------------
diff --git a/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogOsgiYamlEntityTest.java b/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogOsgiYamlEntityTest.java
index 6d7df19..ae0df91 100644
--- a/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogOsgiYamlEntityTest.java
+++ b/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogOsgiYamlEntityTest.java
@@ -333,7 +333,7 @@ public class CatalogOsgiYamlEntityTest extends AbstractYamlTest {
addCatalogOSGiEntity(id, SIMPLE_ENTITY_TYPE, true);
Asserts.shouldHaveFailedPreviously();
} catch (Exception e) {
- Asserts.expectedFailureContainsIgnoreCase(e, id, "already installed", "cannot install a different bundle at a same non-snapshot version");
+ Asserts.expectedFailureContainsIgnoreCase(e, id, "already installed", "cannot install a different bundle with the same non-snapshot version");
}
}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/85196899/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogOsgiYamlVersioningTest.java
----------------------------------------------------------------------
diff --git a/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogOsgiYamlVersioningTest.java b/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogOsgiYamlVersioningTest.java
index 672c722..9042663 100644
--- a/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogOsgiYamlVersioningTest.java
+++ b/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogOsgiYamlVersioningTest.java
@@ -74,7 +74,7 @@ public class CatalogOsgiYamlVersioningTest extends CatalogYamlVersioningTest {
@Override
protected void checkAddSameVersionFailsWhenIconIsDifferent(Exception e) {
Asserts.expectedFailureContainsIgnoreCase(e,
- "cannot install a different bundle at a same non-snapshot version");
+ "cannot install a different bundle with the same non-snapshot version");
assertExpectedFailureIncludesSampleId(e);
}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/85196899/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/test/lite/CampYamlLiteTest.java
----------------------------------------------------------------------
diff --git a/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/test/lite/CampYamlLiteTest.java b/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/test/lite/CampYamlLiteTest.java
index 92b053e..d4b67c5 100644
--- a/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/test/lite/CampYamlLiteTest.java
+++ b/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/test/lite/CampYamlLiteTest.java
@@ -213,7 +213,7 @@ public class CampYamlLiteTest {
// install bundle for class access but without loading its catalog.bom,
// since we only have mock matchers here
// (if we don't do this, the default routines install it and try to process the catalog.bom, failing)
- ((ManagementContextInternal)mgmt).getOsgiManager().get().installDeferredStart(new BasicManagedBundle(null, null, bundleUrl), null, false).get();
+ ((ManagementContextInternal)mgmt).getOsgiManager().get().installDeferredStart(new BasicManagedBundle(null, null, bundleUrl, null), null, false).get();
}
private void assertMgmtHasSampleMyCatalogApp(String symbolicName, String bundleUrl) {
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/85196899/core/src/main/java/org/apache/brooklyn/core/catalog/internal/BasicBrooklynCatalog.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/catalog/internal/BasicBrooklynCatalog.java b/core/src/main/java/org/apache/brooklyn/core/catalog/internal/BasicBrooklynCatalog.java
index 810ffc1..c1c893c 100644
--- a/core/src/main/java/org/apache/brooklyn/core/catalog/internal/BasicBrooklynCatalog.java
+++ b/core/src/main/java/org/apache/brooklyn/core/catalog/internal/BasicBrooklynCatalog.java
@@ -1503,7 +1503,7 @@ public class BasicBrooklynCatalog implements BrooklynCatalog {
OsgiBundleInstallationResult result = null;
try {
- result = osgiManager.install(new BasicManagedBundle(vn.getSymbolicName(), vn.getVersionString(), null), new FileInputStream(bf), true, true, forceUpdate).get();
+ result = osgiManager.install(new BasicManagedBundle(vn.getSymbolicName(), vn.getVersionString(), null, null), new FileInputStream(bf), true, true, forceUpdate).get();
} catch (FileNotFoundException e) {
throw Exceptions.propagate(e);
} finally {
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/85196899/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java
index 968fbf9..e3b91fa 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/ha/OsgiArchiveInstaller.java
@@ -26,6 +26,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collections;
+import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.jar.Attributes;
@@ -362,6 +363,7 @@ class OsgiArchiveInstaller {
final boolean updating;
result.metadata = osgiManager.getManagedBundle(inferredMetadata.getVersionedName());
if (result.getMetadata()!=null) {
+
// already have a managed bundle - check if this is using a new/different URL
if (suppliedKnownBundleMetadata!=null && suppliedKnownBundleMetadata.getUrl()!=null) {
String knownIdForThisUrl = osgiManager.managedBundlesRecord.getManagedBundleIdFromUrl(suppliedKnownBundleMetadata.getUrl());
@@ -376,68 +378,106 @@ class OsgiArchiveInstaller {
osgiManager.managedBundlesRecord.setManagedBundleUrl(suppliedKnownBundleMetadata.getUrl(), result.getMetadata().getId());
}
}
+
+ result.bundle = osgiManager.framework.getBundleContext().getBundle(result.getMetadata().getOsgiUniqueUrl());
+
+ // Check if exactly this bundle is already installed
+ if (result.bundle != null && checksumsMatch(result.getMetadata(), inferredMetadata)) {
+ // e.g. repeatedly installing the same bundle
+ log.trace("Bundle "+inferredMetadata+" matches already installed managed bundle "+result.getMetadata()
+ +"; install is no-op");
+ result.setIgnoringAlreadyInstalled();
+ return ReferenceWithError.newInstanceWithoutError(result);
+ } else if (isEquivalentBundleAlreadyOsgiInstalled(osgiManager, inferredMetadata, zipFile)) {
+ // e.g. happens if pre-installed bundle is brought under management, and then add it again via a mvn-style url.
+ // We wouldn't know the checksum from the pre-installed bundle.
+ log.trace("Bundle "+inferredMetadata+" matches metadata of managed bundle "+result.getMetadata()
+ +" (but not OSGi bundle location "+result.getMetadata().getOsgiUniqueUrl()+"), "
+ + "and matches already installed OSGi bundle; ; install is no-op");
+ result.setIgnoringAlreadyInstalled();
+ return ReferenceWithError.newInstanceWithoutError(result);
+ }
+
if (canUpdate()) {
-
- result.bundle = osgiManager.framework.getBundleContext().getBundle(result.getMetadata().getOsgiUniqueUrl());
- if (result.getBundle()==null) {
- if (hasBundleOnInstall(osgiManager, inferredMetadata, zipFile)) {
- // e.g. happens if system-bundle is brought under management, and then try to add it again:
- // if added from "initial catalog" has it, and then added from persisted state as well.
- result.setIgnoringAlreadyInstalled();
- return ReferenceWithError.newInstanceWithoutError(result);
- } else {
- log.warn("Brooklyn thought is was already managing bundle "+result.getMetadata().getVersionedName()+" but it's not installed to framework; reinstalling it");
- updating = false;
- }
+ if (result.getBundle() == null) {
+ log.warn("Brooklyn thought is was already managing bundle "+result.getMetadata().getVersionedName()
+ +" but it's not installed to framework at location "+result.getMetadata().getOsgiUniqueUrl()+"; reinstalling it");
+ updating = false;
} else {
+ log.trace("Updating existing brooklyn-managed bundle "+result);
updating = true;
}
} else {
- if (result.getMetadata().getChecksum()==null || inferredMetadata.getChecksum()==null) {
- log.warn("Missing bundle checksum data for "+result+"; assuming bundle replacement is permitted");
- } else if (!Objects.equal(result.getMetadata().getChecksum(), inferredMetadata.getChecksum())) {
+ List<Bundle> existingBundles = findBundlesByVersion(osgiManager, inferredMetadata);
+ if (existingBundles.size() > 0 && (result.getMetadata().getChecksum()==null || inferredMetadata.getChecksum()==null)) {
+ // e.g. Checksum would be missing if we brought under management a pre-installed bundle with an unusable url.
+ log.info("Missing bundle checksum data for "+result+"; assuming bundle matches existing brooklyn-managed bundle (not re-installing)");
+ result.setIgnoringAlreadyInstalled();
+ return ReferenceWithError.newInstanceWithoutError(result);
+ } else if (result.bundle != null || existingBundles.size() > 0) {
throw new IllegalArgumentException("Bundle "+result.getMetadata().getVersionedName()+" already installed; "
- + "cannot install a different bundle at a same non-snapshot version");
+ + "cannot install a different bundle with the same non-snapshot version");
+ } else {
+ throw new IllegalArgumentException("Bundle "+result.getMetadata().getVersionedName()+" already a brooklyn-managed bundle, but not found in OSGi framework; "
+ + "will not re-install without use of 'force'");
}
- result.setIgnoringAlreadyInstalled();
- return ReferenceWithError.newInstanceWithoutError(result);
}
} else {
+ // No such Brooklyn-managed bundle.
+
+ // Check if likely-looking bundle already installed to OSGi subsystem, but brooklyn not aware of it.
+ // This will often happen on a karaf restart where bundle was cached by karaf, so we need to allow it;
+ // can also happen if brooklyn.libraries references an existing bundle.
+ //
+ // If we're not certain that the bundle is identical
+
+
result.metadata = inferredMetadata;
- // no such Brooklyn-managed bundle
- Maybe<Bundle> b = Osgis.bundleFinder(osgiManager.framework).symbolicName(result.getMetadata().getSymbolicName()).version(result.getMetadata().getSuppliedVersionString()).find();
- if (b.isPresent()) {
- // bundle already installed to OSGi subsystem but brooklyn not aware of it;
- // this will often happen on a karaf restart where bundle was cached by karaf,
- // so we need to allow it. can also happen if brooklyn.libraries references an existing bundle.
+
+ // search for already-installed bundles.
+ List<Bundle> existingBundles = findBundlesByVersion(osgiManager, inferredMetadata);
+ Maybe<Bundle> existingEquivalentBundle = tryFindEquivalentBundle(existingBundles, inferredMetadata, zipFile);
+
+ if (existingEquivalentBundle.isPresent()) {
+ // Identical bundle (by osgi location or binary content) already installed; just bring that under management.
+ // This will often happen on a karaf restart: bundles from persisted state match those cached by karaf,
+ isBringingExistingOsgiInstalledBundleUnderBrooklynManagement = true;
+ result.bundle = existingEquivalentBundle.get();
- // determine if we are simply bringing existing installed under Brooklyn management (because url or binary content identical and not forced)
- // or if the bundle should be reinstalled/updated
- if (!force) {
- if (!isBringingExistingOsgiInstalledBundleUnderBrooklynManagement) {
- isBringingExistingOsgiInstalledBundleUnderBrooklynManagement = hasBundleOnInstall(osgiManager, inferredMetadata, zipFile);
- }
- } else {
+ } else if (existingBundles.size() > 0) {
+ Bundle existingBundle = existingBundles.get(0);
+
+ if (force) {
if (isBringingExistingOsgiInstalledBundleUnderBrooklynManagement) {
log.debug("Request to install "+inferredMetadata+" was forced, so forcing reinstallation "
- + "of existing OSGi installed (but not Brooklyn-managed) bundle "+b.get());
+ + "of existing OSGi installed (but not Brooklyn-managed) bundle "+existingBundle);
isBringingExistingOsgiInstalledBundleUnderBrooklynManagement = false;
}
}
if (isBringingExistingOsgiInstalledBundleUnderBrooklynManagement) {
- result.bundle = b.get();
-
+ // We were explicitly asked to bring an existing OSGi bundle under management;
+ // no equivalence check required
+ result.bundle = existingBundle;
} else {
- // needs reinstallation
- // we could update instead of uninstall/reinstall
- // note however either way we won't be able to rollback if there is a failure
+ // Uninstall and re-install the bundle.
+ // This is a good idea for brooklyn managed bundles that were in the karaf cache (when we can't
+ // determine that they are definitely identical).
+ // It's less good for pre-installed bundles, but if the user has said to deploy it or has
+ // referenced it in `brooklyn.libraries` then we'll go for it anyway! Let's hope they didn't
+ // reference `org.apache.brooklyn.core` or some such.
+ //
+ // We are this extreme because we want rebind to always work! If a user did a `force` install
+ // of a bundle, then we want to do the same on rebind (rather than risk failing).
+ //
+ // Instead of uninstall, we could update the bundle.
+ // Note however either way we won't be able to rollback if there is a failure
log.debug("Brooklyn install of "+result.getMetadata().getVersionedName()+" detected already loaded in OSGi; uninstalling that to reinstall as Brooklyn-managed");
- b.get().uninstall();
+ existingBundle.uninstall();
result.bundle = null;
}
}
- // normal install
+
updating = false;
}
@@ -449,6 +489,7 @@ class OsgiArchiveInstaller {
log.debug("Brooklyn install of "+result.getMetadata().getVersionedName()+" detected already loaded "+result.getBundle()+" in OSGi can be re-used, skipping OSGi install");
} else {
assert result.getBundle()==null;
+ log.debug("Installing bundle "+result.getMetadata().getVersionedName()+", using OSGi location "+result.getMetadata().getOsgiUniqueUrl());
result.bundle = osgiManager.framework.getBundleContext().installBundle(result.getMetadata().getOsgiUniqueUrl(), fin);
}
} else {
@@ -464,14 +505,18 @@ class OsgiArchiveInstaller {
osgiManager.managedBundlesRecord.addManagedBundle(result, zipFile);
result.code = OsgiBundleInstallationResult.ResultCode.INSTALLED_NEW_BUNDLE;
result.message = "Installed Brooklyn catalog bundle "+result.getMetadata().getVersionedName()+" with ID "+result.getMetadata().getId()+" ["+result.bundle.getBundleId()+"]";
- ((BasicManagedBundle)result.getMetadata()).setPersistenceNeeded(true);
- mgmt().getRebindManager().getChangeListener().onManaged(result.getMetadata());
+ if (!isBlacklistedForPersistence(result.getMetadata())) {
+ ((BasicManagedBundle)result.getMetadata()).setPersistenceNeeded(true);
+ mgmt().getRebindManager().getChangeListener().onManaged(result.getMetadata());
+ }
} else {
oldZipFile = osgiManager.managedBundlesRecord.updateManagedBundleFile(result, zipFile);
result.code = OsgiBundleInstallationResult.ResultCode.UPDATED_EXISTING_BUNDLE;
result.message = "Updated Brooklyn catalog bundle "+result.getMetadata().getVersionedName()+" as existing ID "+result.getMetadata().getId()+" ["+result.bundle.getBundleId()+"]";
- ((BasicManagedBundle)result.getMetadata()).setPersistenceNeeded(true);
- mgmt().getRebindManager().getChangeListener().onChanged(result.getMetadata());
+ if (!isBlacklistedForPersistence(result.getMetadata())) {
+ ((BasicManagedBundle)result.getMetadata()).setPersistenceNeeded(true);
+ mgmt().getRebindManager().getChangeListener().onChanged(result.getMetadata());
+ }
}
log.debug(result.message + " (partial): OSGi bundle installed, with bundle start and Brooklyn management to follow");
// can now delete and close (copy has been made and is available from OsgiManager)
@@ -505,8 +550,10 @@ class OsgiArchiveInstaller {
+ "installation will likely be corrupted and correct version should be manually installed.", e);
}
- ((BasicManagedBundle)result.getMetadata()).setPersistenceNeeded(true);
- mgmt().getRebindManager().getChangeListener().onChanged(result.getMetadata());
+ if (!isBlacklistedForPersistence(result.getMetadata())) {
+ ((BasicManagedBundle)result.getMetadata()).setPersistenceNeeded(true);
+ mgmt().getRebindManager().getChangeListener().onChanged(result.getMetadata());
+ }
} else {
if (isBringingExistingOsgiInstalledBundleUnderBrooklynManagement) {
log.debug("Uninstalling bundle "+result.getVersionedName()+" from Brooklyn management only (rollback needed but it was already installed to OSGi)");
@@ -514,8 +561,10 @@ class OsgiArchiveInstaller {
log.debug("Uninstalling bundle "+result.getVersionedName()+" (roll back of failed fresh install, no previous version to revert to)");
}
osgiManager.uninstallUploadedBundle(result.getMetadata(), false, isBringingExistingOsgiInstalledBundleUnderBrooklynManagement);
- ((BasicManagedBundle)result.getMetadata()).setPersistenceNeeded(true);
- mgmt().getRebindManager().getChangeListener().onUnmanaged(result.getMetadata());
+ if (!isBlacklistedForPersistence(result.getMetadata())) {
+ ((BasicManagedBundle)result.getMetadata()).setPersistenceNeeded(true);
+ mgmt().getRebindManager().getChangeListener().onUnmanaged(result.getMetadata());
+ }
}
}
public void run() {
@@ -631,47 +680,75 @@ class OsgiArchiveInstaller {
close();
}
}
-
- private static boolean hasBundleOnInstall(OsgiManager osgiManager, ManagedBundle desired, File zipFile) {
+
+ private static boolean isBlacklistedForPersistence(ManagedBundle managedBundle) {
+ // Specifically, we treat as "managed bundles" (to extract their catalog.bom) the contents of:
+ // - org.apache.brooklyn.core
+ // - org.apache.brooklyn.policy
+ // - org.apache.brooklyn.test-framework
+ // - org.apache.brooklyn.software-*
+ // - org.apache.brooklyn.library-catalog
+ // - org.apache.brooklyn.karaf-init (not sure why this one could end up in persisted state!)
+ return managedBundle.getSymbolicName().startsWith("org.apache.brooklyn.");
+ }
+
+ private static List<Bundle> findBundlesByVersion(OsgiManager osgiManager, ManagedBundle desired) {
+ return Osgis.bundleFinder(osgiManager.framework).symbolicName(desired.getSymbolicName()).version(desired.getOsgiVersionString()).findAll();
+ }
+
+ private static boolean checksumsMatch(ManagedBundle actual, ManagedBundle desired) {
+ return actual.getChecksum() != null && Objects.equal(actual.getChecksum(), desired.getChecksum());
+ }
+
+ private static boolean isEquivalentBundleAlreadyOsgiInstalled(OsgiManager osgiManager, ManagedBundle desired, File zipFile) {
+ for (Bundle bundle : findBundlesByVersion(osgiManager, desired)) {
+ if (isEquivalentBundle(bundle, desired, zipFile)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static Maybe<Bundle> tryFindEquivalentBundle(Iterable<? extends Bundle> bundles, ManagedBundle desired, File zipFile) {
+ for (Bundle bundle : bundles) {
+ if (isEquivalentBundle(bundle, desired, zipFile)) {
+ return Maybe.of(bundle);
+ }
+ }
+
+ return Maybe.absent();
+ }
+
+ private static boolean isEquivalentBundle(Bundle bundle, ManagedBundle desired, File zipFile) {
// Would be nice to also use `desired.getChecksum()`, but not clear if we can get
// MD5 checksum from an installed OSGi bundle.
- Maybe<Bundle> b = Osgis.bundleFinder(osgiManager.framework).symbolicName(desired.getSymbolicName()).version(desired.getOsgiVersionString()).find();
- if (b.isPresent()) {
- // bundle already installed to OSGi subsystem (but brooklyn not aware of it as "managed bundle");
- // this will often happen on a karaf restart where bundle was cached by karaf,
- // so we need to allow it. can also happen if brooklyn.libraries references an existing bundle.
-
- // determine if we are simply bringing existing installed under Brooklyn management (because url or binary content identical and not forced)
- // or if the bundle should be reinstalled/updated
- if (Objects.equal(b.get().getLocation(), desired.getUrl())) {
- // installation request was for identical location, so assume we are simply bringing under mgmt
- log.debug("Request to install "+desired+" from same location "+b.get().getLocation()+
- " as existing OSGi installed (but not Brooklyn-managed) bundle "+b.get()+", so skipping reinstall");
- return true;
- } else {
- // different locations, but see if we can compare input stream contents
- // (prevents needless uninstall/reinstall of already installed bundles)
- try {
- if (Streams.compare(new FileInputStream(zipFile), new URL(b.get().getLocation()).openStream())) {
- log.debug("Request to install "+desired+" has same contents"+
- " as existing OSGi installed (but not Brooklyn-managed) bundle "+b.get()+", so skipping reinstall");
- return true;
- } else {
- log.debug("Request to install "+desired+" has different contents"+
- " as existing OSGi installed (but not Brooklyn-managed) bundle "+b.get()+", so will do reinstall");
- return false;
- }
- } catch (Exception e) {
- Exceptions.propagateIfFatal(e);
- // probably an invalid URL on installed bundle; that's allowed
- log.debug("Request to install "+desired+" could not compare contents"+
- " with existing OSGi installed (but not Brooklyn-managed) bundle "+b.get()+", so will do reinstall (error "+e+" loading from "+b.get().getLocation()+")");
+ if (Objects.equal(bundle.getLocation(), desired.getUrl())) {
+ // installation request was for identical location, so assume we are simply bringing under mgmt
+ log.debug("Request to install "+desired+" from same location "+bundle.getLocation()+
+ " as existing OSGi installed (but not Brooklyn-managed) bundle "+bundle+", so skipping reinstall");
+ return true;
+ } else {
+ // different locations, but see if we can compare input stream contents
+ // (prevents needless uninstall/reinstall of already installed bundles)
+ try {
+ if (Streams.compare(new FileInputStream(zipFile), new URL(bundle.getLocation()).openStream())) {
+ log.debug("Request to install "+desired+" has same contents"+
+ " as existing OSGi installed (but not Brooklyn-managed) bundle "+bundle+", so skipping reinstall");
+ return true;
+ } else {
+ log.debug("Request to install "+desired+" has different contents"+
+ " as existing OSGi installed (but not Brooklyn-managed) bundle "+bundle+", so will do reinstall (if no other equivalents found)");
return false;
}
+ } catch (Exception e) {
+ Exceptions.propagateIfFatal(e);
+ // probably an invalid URL on installed bundle; that's allowed
+ log.debug("Request to install "+desired+" could not compare contents"+
+ " with existing OSGi installed (but not Brooklyn-managed) bundle "+bundle+", so will do reinstall if not other equivalents found (error "+e+" loading from "+bundle.getLocation()+")");
+ return false;
}
- } else {
- return false;
}
}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/85196899/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindIteration.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindIteration.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindIteration.java
index 755107a..8a667eb 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindIteration.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/RebindIteration.java
@@ -1233,7 +1233,7 @@ public abstract class RebindIteration {
}
protected ManagedBundle newManagedBundle(ManagedBundleMemento memento) {
- ManagedBundle result = new BasicManagedBundle(memento.getSymbolicName(), memento.getVersion(), memento.getUrl());
+ ManagedBundle result = new BasicManagedBundle(memento.getSymbolicName(), memento.getVersion(), memento.getUrl(), memento.getChecksum());
FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", memento.getId()), result);
return result;
}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/85196899/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/dto/BasicManagedBundleMemento.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/dto/BasicManagedBundleMemento.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/dto/BasicManagedBundleMemento.java
index 505e7c8..37afb58 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/dto/BasicManagedBundleMemento.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/dto/BasicManagedBundleMemento.java
@@ -42,7 +42,8 @@ public class BasicManagedBundleMemento extends AbstractMemento implements Manage
protected String symbolicName;
protected String version;
protected String url;
-
+ protected String checksum;
+
public Builder symbolicName(String symbolicName) {
this.symbolicName = symbolicName;
return self();
@@ -58,11 +59,17 @@ public class BasicManagedBundleMemento extends AbstractMemento implements Manage
return self();
}
+ public Builder checksum(String checksum) {
+ this.checksum = checksum;
+ return self();
+ }
+
public Builder from(ManagedBundleMemento other) {
super.from(other);
symbolicName = other.getSymbolicName();
version = other.getVersion();
url = other.getUrl();
+ checksum = other.getChecksum();
return self();
}
@@ -74,6 +81,7 @@ public class BasicManagedBundleMemento extends AbstractMemento implements Manage
private String symbolicName;
private String version;
private String url;
+ private String checksum;
transient private ByteSource jarContent;
@SuppressWarnings("unused") // For deserialisation
@@ -84,6 +92,7 @@ public class BasicManagedBundleMemento extends AbstractMemento implements Manage
this.symbolicName = builder.symbolicName;
this.version = builder.version;
this.url = builder.url;
+ this.checksum = builder.checksum;
}
@Override
@@ -102,6 +111,11 @@ public class BasicManagedBundleMemento extends AbstractMemento implements Manage
}
@Override
+ public String getChecksum() {
+ return checksum;
+ }
+
+ @Override
public ByteSource getJarContent() {
return jarContent;
}
@@ -129,7 +143,7 @@ public class BasicManagedBundleMemento extends AbstractMemento implements Manage
return super.newVerboseStringHelper()
.add("symbolicName", getSymbolicName())
.add("version", getVersion())
- .add("url", getUrl());
+ .add("url", getUrl())
+ .add("checksum", getChecksum());
}
-
}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/85196899/core/src/main/java/org/apache/brooklyn/core/typereg/BasicManagedBundle.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/typereg/BasicManagedBundle.java b/core/src/main/java/org/apache/brooklyn/core/typereg/BasicManagedBundle.java
index 8372b99..860bf5a 100644
--- a/core/src/main/java/org/apache/brooklyn/core/typereg/BasicManagedBundle.java
+++ b/core/src/main/java/org/apache/brooklyn/core/typereg/BasicManagedBundle.java
@@ -20,6 +20,8 @@ package org.apache.brooklyn.core.typereg;
import java.util.Map;
+import javax.annotation.Nullable;
+
import org.apache.brooklyn.api.catalog.CatalogItem.CatalogBundle;
import org.apache.brooklyn.api.mgmt.rebind.RebindSupport;
import org.apache.brooklyn.api.typereg.ManagedBundle;
@@ -46,7 +48,7 @@ public class BasicManagedBundle extends AbstractBrooklynObject implements Manage
/** Creates an empty one, with an ID, expecting other fields will be populated. */
public BasicManagedBundle() {}
- public BasicManagedBundle(String name, String version, String url) {
+ public BasicManagedBundle(String name, String version, String url, @Nullable String checksum) {
if (name == null && version == null) {
Preconditions.checkNotNull(url, "Either a URL or both name and version are required");
} else {
@@ -56,6 +58,7 @@ public class BasicManagedBundle extends AbstractBrooklynObject implements Manage
this.symbolicName = name;
this.version = version;
this.url = url;
+ this.checksum = checksum;
}
@Override
@@ -101,9 +104,16 @@ public class BasicManagedBundle extends AbstractBrooklynObject implements Manage
this.url = url;
}
+ /**
+ * Gets the (internal) value to be used as the location in bundleContext.install(location).
+ * It thus allows us to tell if a cached OSGi bundle is the same as a bundle we are about to
+ * install (e.g. one we get from persisted state), or have retrieved from the initial catalog.
+ *
+ * Care should be taken to set the checksum <em>before</em> using the OSGi unique url.
+ */
@Override
public String getOsgiUniqueUrl() {
- return "brooklyn:"+getId();
+ return "brooklyn:" + (checksum != null ? checksum : getId());
}
@Override
@@ -175,6 +185,7 @@ public class BasicManagedBundle extends AbstractBrooklynObject implements Manage
public String getChecksum() {
return checksum;
}
+
public void setChecksum(String md5Checksum) {
this.checksum = md5Checksum;
}
@@ -184,8 +195,9 @@ public class BasicManagedBundle extends AbstractBrooklynObject implements Manage
throw new UnsupportedOperationException();
}
- public static ManagedBundle of(CatalogBundle bundleUrl) {
- return new BasicManagedBundle(bundleUrl.getSymbolicName(), bundleUrl.getSuppliedVersionString(), bundleUrl.getUrl());
+ public static ManagedBundle of(CatalogBundle bundle) {
+ String checksum = (bundle instanceof ManagedBundle) ? ((ManagedBundle)bundle).getChecksum() : null;
+ return new BasicManagedBundle(bundle.getSymbolicName(), bundle.getSuppliedVersionString(), bundle.getUrl(), checksum);
}
public void setPersistenceNeeded(boolean val) {
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/85196899/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java
index 89bcae0..400e3a8 100644
--- a/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTest.java
@@ -267,19 +267,32 @@ public abstract class AbstractBrooklynLauncherRebindTest {
}
protected String createCatalogYaml(Iterable<URI> libraries, Iterable<VersionedName> entities) {
- if (Iterables.isEmpty(libraries) && Iterables.isEmpty(entities)) {
- return "brooklyn.catalog: {}\n";
- }
-
+ return createCatalogYaml(libraries, ImmutableList.of(), entities, null);
+ }
+
+ protected String createCatalogYaml(Iterable<URI> libraryUris, Iterable<VersionedName> libraryNames, Iterable<VersionedName> entities) {
+ return createCatalogYaml(libraryUris, libraryNames, entities, null);
+ }
+
+ protected String createCatalogYaml(Iterable<URI> libraryUris, Iterable<VersionedName> libraryNames, Iterable<VersionedName> entities, String randomNoise) {
StringBuilder result = new StringBuilder();
result.append("brooklyn.catalog:\n");
- if (!Iterables.isEmpty(libraries)) {
+ if (randomNoise != null) {
+ result.append(" description: "+randomNoise+"\n");
+ }
+ if (!(Iterables.isEmpty(libraryUris) && Iterables.isEmpty(libraryNames))) {
result.append(" brooklyn.libraries:\n");
}
- for (URI library : libraries) {
+ for (URI library : libraryUris) {
result.append(" - " + library+"\n");
}
- if (!Iterables.isEmpty(entities)) {
+ for (VersionedName library : libraryNames) {
+ result.append(" - name: "+library.getSymbolicName()+"\n");
+ result.append(" version: \""+library.getVersionString()+"\"\n");
+ }
+ if (Iterables.isEmpty(entities)) {
+ result.append(" items: []\n");
+ } else {
result.append(" items:\n");
}
for (VersionedName entity : entities) {
@@ -292,6 +305,9 @@ public abstract class AbstractBrooklynLauncherRebindTest {
return result.toString();
}
+
+
+
public PersistedStateInitializer newPersistedStateInitializer() {
return new PersistedStateInitializer();
}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/85196899/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
index d4e8c75..8985147 100644
--- a/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindCatalogOsgiTest.java
@@ -19,30 +19,31 @@
package org.apache.brooklyn.launcher;
import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
import java.io.File;
-import java.nio.charset.StandardCharsets;
import java.io.FileInputStream;
-import java.net.URI;
-import java.util.LinkedHashSet;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
import java.util.List;
import java.util.Set;
-import org.apache.brooklyn.api.typereg.ManagedBundle;
-import org.apache.brooklyn.api.typereg.RegisteredType;
import org.apache.brooklyn.core.catalog.internal.BasicBrooklynCatalog;
import org.apache.brooklyn.core.catalog.internal.CatalogInitialization;
+import org.apache.brooklyn.core.mgmt.ha.OsgiBundleInstallationResult;
import org.apache.brooklyn.core.mgmt.ha.OsgiManager;
import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.entity.stock.BasicEntity;
import org.apache.brooklyn.test.support.TestResourceUnavailableException;
import org.apache.brooklyn.util.core.osgi.Osgis;
+import org.apache.brooklyn.util.exceptions.ReferenceWithError;
import org.apache.brooklyn.util.os.Os;
import org.apache.brooklyn.util.osgi.OsgiTestResources;
import org.apache.brooklyn.util.osgi.VersionedName;
+import org.apache.brooklyn.util.text.Identifiers;
import org.osgi.framework.Bundle;
import org.osgi.framework.launch.Framework;
-import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import com.google.common.base.Joiner;
@@ -62,12 +63,29 @@ public class BrooklynLauncherRebindCatalogOsgiTest extends AbstractBrooklynLaunc
private static final Set<VersionedName> COM_EXAMPLE_BUNDLE_CATALOG_IDS = ImmutableSet.of(
new VersionedName("com.example.simpleTest", "0.0.0-SNAPSHOT"));
+ /**
+ * Whether we reuse OSGi Framework depends if we want it to feel like rebinding on a new machine
+ * (so no cached bundles), or a local restart. We can also use {@code reuseOsgi = true} to emulate
+ * system bundles (by pre-installing them into the reused framework at the start of the test).
+ */
private boolean reuseOsgi = false;
- @BeforeMethod(alwaysRun=true)
+ private List<Bundle> reusedBundles = new ArrayList<>();
+
+ @AfterMethod(alwaysRun=true)
@Override
- public void setUp() throws Exception {
- super.setUp();
+ public void tearDown() throws Exception {
+ try {
+ reuseOsgi = false;
+ for (Bundle bundle : reusedBundles) {
+ if (bundle != null && bundle.getState() != Bundle.UNINSTALLED) {
+ bundle.uninstall();
+ }
+ }
+ reusedBundles.clear();
+ } finally {
+ super.tearDown();
+ }
}
@Override
@@ -110,7 +128,7 @@ public class BrooklynLauncherRebindCatalogOsgiTest extends AbstractBrooklynLaunc
/**
* See https://issues.apache.org/jira/browse/BROOKLYN-546.
*
- * We built up to launcher3, which will have three things:
+ * We built up to launcher2, which will have three things:
* 1. a pre-installed "system bundle"
* 2. an initial catalog that references this same system bundle (hence the bundle will be "managed")
* 3. persisted state that references this same system bundle.
@@ -130,54 +148,201 @@ public class BrooklynLauncherRebindCatalogOsgiTest extends AbstractBrooklynLaunc
@Test
public void testRebindWithSystemBundleInCatalog() throws Exception {
Set<VersionedName> bundleItems = ImmutableSet.of(VersionedName.fromString("one:1.0.0-SNAPSHOT"));
- String bundleBom = createCatalogYaml(ImmutableList.of(), bundleItems);
- VersionedName bundleName = new VersionedName("org.example.testRebindWithSystemBundleInCatalog", "1.0.0.SNAPSHOT");
- File bundleFile = newTmpBundle(ImmutableMap.of(BasicBrooklynCatalog.CATALOG_BOM, bundleBom.getBytes(StandardCharsets.UTF_8)), bundleName);
+ VersionedName bundleName = new VersionedName("org.example.brooklynLauncherRebindCatalogOsgiTest."+Identifiers.makeRandomId(4), "1.0.0.SNAPSHOT");
+ File bundleFile = newTmpBundle(bundleItems, bundleName);
File bundleFileCopy = newTmpCopy(bundleFile);
File initialBomFile = newTmpFile(createCatalogYaml(ImmutableList.of(bundleFile.toURI()), ImmutableList.of()));
- Framework reusedFamework = null;
- Bundle pseudoSystemBundle = null;
- try {
- reuseOsgi = true;
-
- // Launch and terminate brooklyn to ensure there is a reusable OSGi Framework
- BrooklynLauncher launcher = newLauncherForTests(CATALOG_EMPTY_INITIAL);
- launcher.start();
- launcher.terminate();
- Os.deleteRecursively(persistenceDir);
-
- // Add our bundle, so it feels for all intents and purposes like a "system bundle"
- reusedFamework = OsgiManager.tryPeekFrameworkForReuse().get();
- pseudoSystemBundle = installBundle(reusedFamework, bundleFileCopy);
-
- // Launch brooklyn, where initial catalog includes a duplicate of the system bundle
- BrooklynLauncher launcher2 = newLauncherForTests(initialBomFile.getAbsolutePath());
- launcher2.start();
- assertCatalogConsistsOfIds(launcher2, bundleItems);
- assertManagedBundle(launcher2, bundleName, bundleItems);
- launcher2.terminate();
-
- // Launch brooklyn, where persisted state now includes the initial catalog's bundle
- BrooklynLauncher launcher3 = newLauncherForTests(initialBomFile.getAbsolutePath());
- launcher3.start();
- assertCatalogConsistsOfIds(launcher3, bundleItems);
- assertManagedBundle(launcher3, bundleName, bundleItems);
-
- // Should not have replaced the original "system bundle"
- reusedFamework.getBundleContext().getBundles();
- List<Bundle> matchingBundles = Osgis.bundleFinder(reusedFamework).symbolicName(bundleName.getSymbolicName()).version(bundleName.getOsgiVersionString()).findAll();
- assertEquals(matchingBundles, ImmutableList.of(pseudoSystemBundle));
-
- launcher3.terminate();
+ reuseOsgi = true;
+
+ // Add our bundle, so it feels for all intents and purposes like a "system bundle"
+ Framework reusedFramework = initReusableOsgiFramework();
+ Bundle pseudoSystemBundle = installBundle(reusedFramework, bundleFileCopy);
+ reusedBundles.add(pseudoSystemBundle);
+
+ // Launch brooklyn, where initial catalog includes a duplicate of the system bundle
+ BrooklynLauncher launcher = newLauncherForTests(initialBomFile.getAbsolutePath());
+ launcher.start();
+ assertCatalogConsistsOfIds(launcher, bundleItems);
+ assertManagedBundle(launcher, bundleName, bundleItems);
+ launcher.terminate();
- } finally {
- reuseOsgi = false;
- if (pseudoSystemBundle != null && pseudoSystemBundle.getState() != Bundle.UNINSTALLED) {
- pseudoSystemBundle.uninstall();
- }
+ // Launch brooklyn, where persisted state now includes the initial catalog's bundle
+ BrooklynLauncher launcher2 = newLauncherForTests(initialBomFile.getAbsolutePath());
+ launcher2.start();
+ assertCatalogConsistsOfIds(launcher2, bundleItems);
+ assertManagedBundle(launcher2, bundleName, bundleItems);
+
+ // Should not have replaced the original "system bundle"
+ assertOnlyBundle(reusedFramework, bundleName, pseudoSystemBundle);
+
+ launcher2.terminate();
+ }
+
+ @Test
+ public void testInstallPreexistingBundle() throws Exception {
+ Set<VersionedName> bundleItems = ImmutableSet.of(VersionedName.fromString("one:1.0.0-SNAPSHOT"));
+ VersionedName bundleName = new VersionedName("org.example.brooklynLauncherRebindCatalogOsgiTest."+Identifiers.makeRandomId(4), "1.0.0.SNAPSHOT");
+ File bundleFile = newTmpBundle(bundleItems, bundleName);
+ File bundleFileCopy = newTmpCopy(bundleFile);
+
+ reuseOsgi = true;
+
+ // Add our bundle, so it feels for all intents and purposes like a "system bundle"
+ Framework reusedFramework = initReusableOsgiFramework();
+ Bundle pseudoSystemBundle = installBundle(reusedFramework, bundleFileCopy);
+ reusedBundles.add(pseudoSystemBundle);
+
+ // Launch brooklyn, and explicitly install pre-existing bundle.
+ // Should bring it under brooklyn-management (should not re-install it).
+ BrooklynLauncher launcher = newLauncherForTests(CATALOG_EMPTY_INITIAL);
+ launcher.start();
+ installBrooklynBundle(launcher, bundleFile, false).getWithError();
+
+ assertOnlyBundle(launcher, bundleName, pseudoSystemBundle);
+ assertCatalogConsistsOfIds(launcher, bundleItems);
+ assertManagedBundle(launcher, bundleName, bundleItems);
+ launcher.terminate();
+
+ // Launch brooklyn again (because will have persisted the pre-installed bundle)
+ BrooklynLauncher launcher2 = newLauncherForTests(CATALOG_EMPTY_INITIAL);
+ launcher2.start();
+ assertOnlyBundle(reusedFramework, bundleName, pseudoSystemBundle);
+ assertCatalogConsistsOfIds(launcher2, bundleItems);
+ assertManagedBundle(launcher2, bundleName, bundleItems);
+ launcher2.terminate();
+ }
+
+ @Test
+ public void testInstallPreexistingBundleViaIndirectBrooklynLibrariesReference() throws Exception {
+ Set<VersionedName> bundleItems = ImmutableSet.of(VersionedName.fromString("one:1.0.0-SNAPSHOT"));
+ VersionedName systemBundleName = new VersionedName("org.example.brooklynLauncherRebindCatalogOsgiTest.system"+Identifiers.makeRandomId(4), "1.0.0.SNAPSHOT");
+ File systemBundleFile = newTmpBundle(bundleItems, systemBundleName);
+
+ String bundleBom = createCatalogYaml(ImmutableList.of(), ImmutableList.of(systemBundleName), ImmutableList.of());
+ VersionedName bundleName = new VersionedName("org.example.brooklynLauncherRebindCatalogOsgiTest.initial"+Identifiers.makeRandomId(4), "1.0.0.SNAPSHOT");
+ File bundleFile = newTmpBundle(ImmutableMap.of(BasicBrooklynCatalog.CATALOG_BOM, bundleBom.getBytes(StandardCharsets.UTF_8)), bundleName);
+
+ File initialBomFile = newTmpFile(createCatalogYaml(ImmutableList.of(bundleFile.toURI()), ImmutableList.of()));
+
+ reuseOsgi = true;
+
+ // Add our bundle, so it feels for all intents and purposes like a "system bundle"
+ Framework reusedFramework = initReusableOsgiFramework();
+ Bundle pseudoSystemBundle = installBundle(reusedFramework, systemBundleFile);
+ reusedBundles.add(pseudoSystemBundle);
+
+ // Launch brooklyn, with initial catalog pointing at bundle that points at system bundle.
+ // Should bring it under brooklyn-management (without re-installing it).
+ BrooklynLauncher launcher = newLauncherForTests(initialBomFile.getAbsolutePath());
+ launcher.start();
+ assertOnlyBundle(launcher, systemBundleName, pseudoSystemBundle);
+ assertCatalogConsistsOfIds(launcher, bundleItems);
+ assertManagedBundle(launcher, systemBundleName, bundleItems);
+ assertManagedBundle(launcher, bundleName, ImmutableSet.of());
+ launcher.terminate();
+
+ // Launch brooklyn again (because will have persisted both those bundles)
+ BrooklynLauncher launcher2 = newLauncherForTests(CATALOG_EMPTY_INITIAL);
+ launcher2.start();
+ assertOnlyBundle(launcher2, systemBundleName, pseudoSystemBundle);
+ assertCatalogConsistsOfIds(launcher2, bundleItems);
+ assertManagedBundle(launcher2, systemBundleName, bundleItems);
+ assertManagedBundle(launcher2, bundleName, ImmutableSet.of());
+ launcher2.terminate();
+ }
+
+ @Test
+ public void testInstallPreexistingBundleViaInitialBomBrooklynLibrariesReference() throws Exception {
+ runInstallPreexistingBundleViaInitialBomBrooklynLibrariesReference(false);
+ }
+
+ // Aled thought we supported version ranges in 'brooklyn.libraries', but doesn't work here.
+ @Test(groups="Broken")
+ public void testInstallPreexistingBundleViaInitialBomBrooklynLibrariesReferenceWithVersionRange() throws Exception {
+ runInstallPreexistingBundleViaInitialBomBrooklynLibrariesReference(true);
+ }
+
+ protected void runInstallPreexistingBundleViaInitialBomBrooklynLibrariesReference(boolean useVersionRange) throws Exception {
+ Set<VersionedName> bundleItems = ImmutableSet.of(VersionedName.fromString("one:1.0.0"));
+ VersionedName systemBundleName = new VersionedName("org.example.brooklynLauncherRebindCatalogOsgiTest.system"+Identifiers.makeRandomId(4), "1.0.0");
+ File systemBundleFile = newTmpBundle(bundleItems, systemBundleName);
+
+ VersionedName systemBundleNameRef;
+ if (useVersionRange) {
+ systemBundleNameRef = new VersionedName(systemBundleName.getSymbolicName(), "[1,2)");
+ } else {
+ systemBundleNameRef = systemBundleName;
}
+ File initialBomFile = newTmpFile(createCatalogYaml(ImmutableList.of(), ImmutableList.of(systemBundleNameRef), ImmutableList.of()));
+
+ reuseOsgi = true;
+
+ // Add our bundle, so it feels for all intents and purposes like a "system bundle"
+ Framework reusedFramework = initReusableOsgiFramework();
+ Bundle pseudoSystemBundle = installBundle(reusedFramework, systemBundleFile);
+ reusedBundles.add(pseudoSystemBundle);
+
+ // Launch brooklyn, with initial catalog pointing at system bundle.
+ // Should bring it under brooklyn-management (without re-installing it).
+ BrooklynLauncher launcher = newLauncherForTests(initialBomFile.getAbsolutePath());
+ launcher.start();
+ assertOnlyBundle(launcher, systemBundleName, pseudoSystemBundle);
+ assertCatalogConsistsOfIds(launcher, bundleItems);
+ assertManagedBundle(launcher, systemBundleName, bundleItems);
+ launcher.terminate();
+
+ // Launch brooklyn again (because will have persisted both those bundles)
+ BrooklynLauncher launcher2 = newLauncherForTests(CATALOG_EMPTY_INITIAL);
+ launcher2.start();
+ assertOnlyBundle(launcher2, systemBundleName, pseudoSystemBundle);
+ assertCatalogConsistsOfIds(launcher2, bundleItems);
+ assertManagedBundle(launcher2, systemBundleName, bundleItems);
+ launcher2.terminate();
+ }
+
+ @Test
+ public void testInstallReplacesPreexistingBundleWithoutForce() throws Exception {
+ runInstallReplacesPreexistingBundle(false);
+ }
+
+ @Test
+ public void testInstallReplacesPreexistingBundleWithForce() throws Exception {
+ runInstallReplacesPreexistingBundle(true);
+ }
+
+ protected void runInstallReplacesPreexistingBundle(boolean force) throws Exception {
+ Set<VersionedName> bundleItems = ImmutableSet.of(VersionedName.fromString("one:1.0.0-SNAPSHOT"));
+ VersionedName bundleName = new VersionedName("org.example.brooklynLauncherRebindCatalogOsgiTest."+Identifiers.makeRandomId(4), "1.0.0.SNAPSHOT");
+ File systemBundleFile = newTmpBundle(bundleItems, bundleName);
+ File replacementBundleFile = newTmpBundle(bundleItems, bundleName, "randomDifference"+Identifiers.makeRandomId(4));
+
+ reuseOsgi = true;
+
+ // Add our bundle, so it feels for all intents and purposes like a "system bundle"
+ Framework reusedFramework = initReusableOsgiFramework();
+ Bundle pseudoSystemBundle = installBundle(reusedFramework, systemBundleFile);
+ reusedBundles.add(pseudoSystemBundle);
+
+ // Launch brooklyn, and explicitly install pre-existing bundle.
+ // Should bring it under brooklyn-management (should not re-install it).
+ BrooklynLauncher launcher = newLauncherForTests(CATALOG_EMPTY_INITIAL);
+ launcher.start();
+ installBrooklynBundle(launcher, replacementBundleFile, force).getWithError();
+
+ assertOnlyBundleReplaced(launcher, bundleName, pseudoSystemBundle);
+ assertCatalogConsistsOfIds(launcher, bundleItems);
+ assertManagedBundle(launcher, bundleName, bundleItems);
+ launcher.terminate();
+
+ // Launch brooklyn again (because will have persisted the pre-installed bundle)
+ BrooklynLauncher launcher2 = newLauncherForTests(CATALOG_EMPTY_INITIAL);
+ launcher2.start();
+ assertOnlyBundleReplaced(reusedFramework, bundleName, pseudoSystemBundle);
+ assertCatalogConsistsOfIds(launcher2, bundleItems);
+ assertManagedBundle(launcher2, bundleName, bundleItems);
+ launcher2.terminate();
}
@Test
@@ -267,4 +432,54 @@ public class BrooklynLauncherRebindCatalogOsgiTest extends AbstractBrooklynLaunc
return framework.getBundleContext().installBundle(bundle.toURI().toString(), stream);
}
}
+
+ private ReferenceWithError<OsgiBundleInstallationResult> installBrooklynBundle(BrooklynLauncher launcher, File bundleFile, boolean force) throws Exception {
+ OsgiManager osgiManager = ((ManagementContextInternal)launcher.getManagementContext()).getOsgiManager().get();
+ try (FileInputStream bundleStream = new FileInputStream(bundleFile)) {
+ return osgiManager.install(null, bundleStream, true, true, force);
+ }
+ }
+
+ private void assertOnlyBundle(BrooklynLauncher launcher, VersionedName bundleName, Bundle expectedBundle) {
+ Framework framework = ((ManagementContextInternal)launcher.getManagementContext()).getOsgiManager().get().getFramework();
+ assertOnlyBundle(framework, bundleName, expectedBundle);
+ }
+
+ private void assertOnlyBundleReplaced(BrooklynLauncher launcher, VersionedName bundleName, Bundle expectedBundle) {
+ Framework framework = ((ManagementContextInternal)launcher.getManagementContext()).getOsgiManager().get().getFramework();
+ assertOnlyBundleReplaced(framework, bundleName, expectedBundle);
+ }
+
+ private void assertOnlyBundle(Framework framework, VersionedName bundleName, Bundle expectedBundle) {
+ List<Bundle> matchingBundles = Osgis.bundleFinder(framework).symbolicName(bundleName.getSymbolicName()).version(bundleName.getOsgiVersionString()).findAll();
+ assertTrue(matchingBundles.contains(expectedBundle), "Bundle missing; matching="+matchingBundles);
+ assertEquals(matchingBundles.size(), 1, "Extra bundles; matching="+matchingBundles);
+ }
+
+ private void assertOnlyBundleReplaced(Framework framework, VersionedName bundleName, Bundle expectedBundle) {
+ List<Bundle> matchingBundles = Osgis.bundleFinder(framework).symbolicName(bundleName.getSymbolicName()).version(bundleName.getOsgiVersionString()).findAll();
+ assertFalse(matchingBundles.contains(expectedBundle), "Bundle still present; matching="+matchingBundles);
+ assertEquals(matchingBundles.size(), 1, "Extra bundles; matching="+matchingBundles);
+ }
+
+ private Framework initReusableOsgiFramework() {
+ if (!reuseOsgi) throw new IllegalStateException("Must first set reuseOsgi");
+
+ if (OsgiManager.tryPeekFrameworkForReuse().isAbsent()) {
+ BrooklynLauncher launcher = newLauncherForTests(CATALOG_EMPTY_INITIAL);
+ launcher.start();
+ launcher.terminate();
+ Os.deleteRecursively(persistenceDir);
+ }
+ return OsgiManager.tryPeekFrameworkForReuse().get();
+ }
+
+ private File newTmpBundle(Set<VersionedName> catalogItems, VersionedName bundleName) {
+ return newTmpBundle(catalogItems, bundleName, null);
+ }
+
+ private File newTmpBundle(Set<VersionedName> catalogItems, VersionedName bundleName, String randomNoise) {
+ String bundleBom = createCatalogYaml(ImmutableList.of(), ImmutableList.of(), catalogItems, randomNoise);
+ return newTmpBundle(ImmutableMap.of(BasicBrooklynCatalog.CATALOG_BOM, bundleBom.getBytes(StandardCharsets.UTF_8)), bundleName);
+ }
}