Search in sources :

Example 41 with User

use of io.fabric8.openshift.api.model.User in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceImpl method rollback.

@Override
public void rollback(PatchData patchData) {
    Git fork = null;
    try {
        fork = gitPatchRepository.cloneRepository(gitPatchRepository.findOrCreateMainGitRepository(), true);
        Ref installationBranch = null;
        PatchKind kind = patchData.isRollupPatch() ? PatchKind.ROLLUP : PatchKind.NON_ROLLUP;
        switch(kind) {
            case ROLLUP:
                {
                    Activator.log2(LogService.LOG_INFO, String.format("Rolling back rollup patch \"%s\"", patchData.getId()));
                    // rolling back a rollup patch should rebase all user commits on top of current baseline
                    // to previous baseline
                    RevTag currentBaseline = gitPatchRepository.findCurrentBaseline(fork);
                    RevCommit c1 = new RevWalk(fork.getRepository()).parseCommit(fork.getRepository().resolve(currentBaseline.getTagName() + "^{commit}"));
                    // remember the commit to discover P patch tags installed on top of rolledback baseline
                    RevCommit since = c1;
                    RevCommit c2 = new RevWalk(fork.getRepository()).parseCommit(fork.getRepository().resolve("HEAD"));
                    RevCommit to = c2;
                    Iterable<RevCommit> mainChangesSinceRollupPatch = fork.log().addRange(c1, c2).call();
                    List<RevCommit> userChanges = new LinkedList<>();
                    for (RevCommit rc : mainChangesSinceRollupPatch) {
                        if (isUserChangeCommit(rc)) {
                            userChanges.add(rc);
                        }
                    }
                    if (env == EnvType.STANDALONE) {
                        // remove the tag
                        fork.tagDelete().setTags(currentBaseline.getTagName()).call();
                    }
                    // baselines are stacked on each other
                    RevTag previousBaseline = gitPatchRepository.findNthPreviousBaseline(fork, env == EnvType.STANDALONE ? 0 : 1);
                    c1 = new RevWalk(fork.getRepository()).parseCommit(fork.getRepository().resolve(previousBaseline.getTagName() + "^{commit}"));
                    // hard reset of main patch branch - to point to other branch, originating from previous baseline
                    fork.reset().setMode(ResetCommand.ResetType.HARD).setRef(previousBaseline.getTagName() + "^{commit}").call();
                    // reapply those user changes that are not conflicting
                    ListIterator<RevCommit> it = userChanges.listIterator(userChanges.size());
                    Status status = fork.status().call();
                    if (!status.isClean()) {
                        // unstage any garbage
                        fork.reset().setMode(ResetCommand.ResetType.MIXED).call();
                        for (String p : status.getModified()) {
                            gitPatchRepository.checkout(fork).addPath(p).call();
                        }
                    }
                    while (it.hasPrevious()) {
                        RevCommit userChange = it.previous();
                        CherryPickResult cpr = fork.cherryPick().include(userChange.getId()).setNoCommit(true).call();
                        // this time prefer user change on top of previous baseline - this change shouldn't be
                        // conflicting, because when rolling back, patch change was preferred over user change
                        handleCherryPickConflict(patchData.getPatchDirectory(), fork, cpr, userChange, true, PatchKind.ROLLUP, null, false, true);
                        // restore backed up content from the reapplied user change
                        String[] commitMessage = userChange.getFullMessage().split("\n\n");
                        if (commitMessage.length > 1) {
                            // we have original commit (that had conflicts) stored in this commit's full message
                            String ref = commitMessage[commitMessage.length - 1];
                            File backupDir = new File(patchesDir, patchData.getId() + ".backup");
                            if (isStandaloneChild()) {
                                backupDir = new File(patchesDir, patchData.getId() + "." + System.getProperty("karaf.name") + ".backup");
                            }
                            backupDir = new File(backupDir, ref);
                            if (backupDir.exists() && backupDir.isDirectory()) {
                                Activator.log2(LogService.LOG_DEBUG, String.format("Restoring content of %s", backupDir.getCanonicalPath()));
                                copyManagedDirectories(backupDir, karafBase, false, false, false);
                            }
                        }
                        gitPatchRepository.prepareCommit(fork, userChange.getFullMessage()).call();
                    }
                    gitPatchRepository.push(fork);
                    if (env == EnvType.STANDALONE) {
                        // remove remote tag
                        fork.push().setRefSpecs(new RefSpec().setSource(null).setDestination("refs/tags/" + currentBaseline.getTagName())).call();
                    }
                    // remove tags related to non-rollup patches installed between
                    // rolled back baseline and previous HEAD, because rolling back to previous rollup patch
                    // (previous baseline) equal effectively to starting from fresh baseline
                    RevWalk walk = new RevWalk(fork.getRepository());
                    Map<String, RevTag> tags = gitPatchRepository.findTagsBetween(fork, since, to);
                    for (Map.Entry<String, RevTag> entry : tags.entrySet()) {
                        if (entry.getKey().startsWith("patch-")) {
                            fork.tagDelete().setTags(entry.getKey()).call();
                            fork.push().setRefSpecs(new RefSpec().setSource(null).setDestination("refs/tags/" + entry.getKey())).call();
                        }
                    }
                    // HEAD of main patch branch after reset and cherry-picks
                    c2 = new RevWalk(fork.getRepository()).parseCommit(fork.getRepository().resolve("HEAD"));
                    // applyChanges(fork, c1, c2);
                    applyChanges(fork, false);
                    break;
                }
            case NON_ROLLUP:
                {
                    Activator.log2(LogService.LOG_INFO, String.format("Rolling back non-rollup patch \"%s\"", patchData.getId()));
                    // rolling back a non-rollup patch is a revert of the patch commit and removal of patch tag
                    String patchTagName = String.format("patch-%s", env == EnvType.STANDALONE ? patchData.getId() : patchData.getId() + "-" + gitPatchRepository.getStandaloneChildkarafName());
                    ObjectId oid = fork.getRepository().resolve(patchTagName);
                    if (oid == null) {
                        throw new PatchException(String.format("Can't find installed patch (tag %s is missing)", patchTagName));
                    }
                    RevCommit commit = new RevWalk(fork.getRepository()).parseCommit(oid);
                    RevertCommand revertCommand = fork.revert().include(commit);
                    RevCommit reverted = revertCommand.call();
                    if (reverted == null) {
                        List<String> unmerged = revertCommand.getUnmergedPaths();
                        Activator.log2(LogService.LOG_WARNING, "Problem rolling back patch \"" + patchData.getId() + "\". The following files where updated later:");
                        for (String path : unmerged) {
                            Activator.log2(LogService.LOG_WARNING, " - " + path);
                        }
                        RevWalk walk = new RevWalk(fork.getRepository());
                        RevCommit head = walk.parseCommit(fork.getRepository().resolve("HEAD"));
                        Map<String, RevTag> tags = gitPatchRepository.findTagsBetween(fork, commit, head);
                        List<RevTag> laterPatches = new LinkedList<>();
                        if (tags.size() > 0) {
                            for (Map.Entry<String, RevTag> tag : tags.entrySet()) {
                                if (tag.getKey().startsWith("patch-")) {
                                    laterPatches.add(tag.getValue());
                                }
                            }
                            Activator.log2(LogService.LOG_INFO, "The following patches were installed after \"" + patchData.getId() + "\":");
                            for (RevTag t : laterPatches) {
                                String message = " - " + t.getTagName().substring("patch-".length());
                                RevObject object = walk.peel(t);
                                if (object != null) {
                                    RevCommit c = walk.parseCommit(object.getId());
                                    String date = GitPatchRepository.FULL_DATE.format(new Date(c.getCommitTime() * 1000L));
                                    message += " (" + date + ")";
                                }
                                Activator.log2(LogService.LOG_INFO, message);
                            }
                        }
                        return;
                    }
                    // TODO: should we restore the backup possibly created when instalilng P patch?
                    // remove the tag
                    fork.tagDelete().setTags(patchTagName).call();
                    gitPatchRepository.push(fork);
                    // remove remote tag
                    fork.push().setRefSpecs(new RefSpec().setSource(null).setDestination(String.format("refs/tags/%s", patchTagName))).call();
                    // HEAD of main patch branch after reset and cherry-picks
                    RevCommit c = new RevWalk(fork.getRepository()).parseCommit(fork.getRepository().resolve("HEAD"));
                    applyChanges(fork, c.getParent(0), c);
                    break;
                }
        }
    } catch (IOException | GitAPIException e) {
        throw new PatchException(e.getMessage(), e);
    } finally {
        if (fork != null) {
            gitPatchRepository.closeRepository(fork, true);
        }
    }
}
Also used : PatchKind(io.fabric8.patch.management.PatchKind) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) DiffEntry(org.eclipse.jgit.diff.DiffEntry) CherryPickResult(org.eclipse.jgit.api.CherryPickResult) RefSpec(org.eclipse.jgit.transport.RefSpec) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Status(org.eclipse.jgit.api.Status) RevTag(org.eclipse.jgit.revwalk.RevTag) ObjectId(org.eclipse.jgit.lib.ObjectId) RevObject(org.eclipse.jgit.revwalk.RevObject) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ListIterator(java.util.ListIterator) Date(java.util.Date) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) RevertCommand(org.eclipse.jgit.api.RevertCommand) PatchException(io.fabric8.patch.management.PatchException) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) Map(java.util.Map) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap)

Example 42 with User

use of io.fabric8.openshift.api.model.User in project fabric8 by jboss-fuse.

the class ServiceImpl method featureUpdatesInPatch.

/**
 * Returns a list of {@link FeatureUpdate} for single patch, taking into account already discovered updates
 * @param patch
 * @param updatesForFeatureKeys
 * @param kind
 * @return
 */
private List<FeatureUpdate> featureUpdatesInPatch(Patch patch, Map<String, FeatureUpdate> updatesForFeatureKeys, PatchKind kind) throws Exception {
    Set<String> addedRepositoryNames = new HashSet<>();
    HashMap<String, Repository> after = null;
    try {
        List<FeatureUpdate> updatesInThisPatch = new LinkedList<>();
        /*
             * Two pairs of features makes feature names not enough to be a key:
             * <feature name="openjpa" description="Apache OpenJPA 2.2.x persistent engine support" version="2.2.2" resolver="(obr)">
             * <feature name="openjpa" description="Apache OpenJPA 2.3.x persistence engine support" version="2.3.0" resolver="(obr)">
             * and
             * <feature name="activemq-camel" version="5.11.0.redhat-621039" resolver="(obr)" start-level="50">
             * <feature name="activemq-camel" version="1.2.0.redhat-621039" resolver="(obr)">
             */
        // install the new feature repos, tracking the set the were
        // installed before and after
        // (e.g, "karaf-enterprise-2.4.0.redhat-620133" -> Repository)
        Map<String, Repository> before = new HashMap<>(getAvailableFeatureRepositories());
        for (String url : patch.getPatchData().getFeatureFiles()) {
            featuresService.addRepository(new URI(url));
        }
        after = getAvailableFeatureRepositories();
        // track which old repos provide which features to find out if we have new repositories for those features
        // key is name|version (don't expect '|' to be part of name...)
        // assume that [feature-name, feature-version{major,minor,0,0}] is defined only in single repository
        Map<String, String> featuresInOldRepositories = new HashMap<>();
        // key is only name, without version - used when there's single feature in old and in new repositories
        MultiMap<String, String> singleFeaturesInOldRepositories = new MultiMap<>();
        Map<String, Version> actualOldFeatureVersions = new HashMap<>();
        for (Repository existingRepository : before.values()) {
            for (Feature feature : existingRepository.getFeatures()) {
                Version v = Utils.getOsgiVersion(feature.getVersion());
                Version lowestUpdateableVersion = new Version(v.getMajor(), v.getMinor(), 0);
                // assume that we can update feature XXX-2.2.3 to XXX-2.2.142, but not to XXX-2.3.0.alpha-1
                String key = String.format("%s|%s", feature.getName(), lowestUpdateableVersion.toString());
                featuresInOldRepositories.put(key, existingRepository.getURI().toString());
                singleFeaturesInOldRepositories.put(feature.getName(), existingRepository.getURI().toString());
                actualOldFeatureVersions.put(key, v);
            }
        }
        // Use the before and after set to figure out which repos were added.
        addedRepositoryNames = new HashSet<>(after.keySet());
        addedRepositoryNames.removeAll(before.keySet());
        // track the new repositories where we can find old features
        Map<String, String> featuresInNewRepositories = new HashMap<>();
        MultiMap<String, String> singleFeaturesInNewRepositories = new MultiMap<>();
        Map<String, String> actualNewFeatureVersions = new HashMap<>();
        MultiMap<String, String> singleActualNewFeatureVersions = new MultiMap<>();
        // Figure out which old repos were updated:  Do they have feature
        // with the same name as one contained in a repo being added?
        // and do they have update'able version? (just like with bundles)
        Set<String> oldRepositoryNames = new HashSet<String>();
        for (String addedRepositoryName : addedRepositoryNames) {
            Repository added = after.get(addedRepositoryName);
            for (Feature feature : added.getFeatures()) {
                Version v = Utils.getOsgiVersion(feature.getVersion());
                Version lowestUpdateableVersion = new Version(v.getMajor(), v.getMinor(), 0);
                String key = String.format("%s|%s", feature.getName(), lowestUpdateableVersion.toString());
                featuresInNewRepositories.put(key, addedRepositoryName);
                singleFeaturesInNewRepositories.put(feature.getName(), addedRepositoryName);
                actualNewFeatureVersions.put(key, v.toString());
                singleActualNewFeatureVersions.put(feature.getName(), v.toString());
                String oldRepositoryWithUpdateableFeature = featuresInOldRepositories.get(key);
                if (oldRepositoryWithUpdateableFeature == null && singleFeaturesInOldRepositories.get(feature.getName()) != null && singleFeaturesInOldRepositories.get(feature.getName()).size() == 1) {
                    oldRepositoryWithUpdateableFeature = singleFeaturesInOldRepositories.get(feature.getName()).get(0);
                }
                if (oldRepositoryWithUpdateableFeature != null) {
                    // track the old repository to be removed
                    oldRepositoryNames.add(oldRepositoryWithUpdateableFeature);
                }
            }
        }
        // We need to uninstall them. Before we uninstall, track which features were installed.
        for (String oldRepositoryName : oldRepositoryNames) {
            Repository repository = before.get(oldRepositoryName);
            for (Feature feature : repository.getFeatures()) {
                if (featuresService.isInstalled(feature)) {
                    Version v = Utils.getOsgiVersion(feature.getVersion());
                    Version lowestUpdateableVersion = new Version(v.getMajor(), v.getMinor(), 0);
                    String key = String.format("%s|%s", feature.getName(), lowestUpdateableVersion.toString());
                    String newRepositoryName = featuresInNewRepositories.get(key);
                    String newVersion = actualNewFeatureVersions.get(key);
                    if (newRepositoryName == null) {
                        // feature from 1.1.1 to 1.3.0
                        if (singleFeaturesInOldRepositories.get(feature.getName()) != null && singleFeaturesInOldRepositories.get(feature.getName()).size() == 1 && singleFeaturesInNewRepositories.get(feature.getName()) != null && singleFeaturesInNewRepositories.get(feature.getName()).size() == 1) {
                            newRepositoryName = singleFeaturesInNewRepositories.get(feature.getName()).get(0);
                        }
                    }
                    if (newVersion == null) {
                        if (singleActualNewFeatureVersions.get(feature.getName()) != null && singleActualNewFeatureVersions.get(feature.getName()).size() == 1) {
                            newVersion = singleActualNewFeatureVersions.get(feature.getName()).get(0);
                        }
                    }
                    FeatureUpdate featureUpdate = null;
                    if (newVersion != null && newRepositoryName != null) {
                        featureUpdate = new FeatureUpdate(feature.getName(), after.get(oldRepositoryName).getURI().toString(), feature.getVersion(), after.get(newRepositoryName).getURI().toString(), newVersion);
                    } else {
                        // we didn't find an update for installed features among feature repositories from patch
                        // which means we have to preserve both the feature and the repository - this may
                        // be user's feature
                        featureUpdate = new FeatureUpdate(feature.getName(), after.get(oldRepositoryName).getURI().toString(), feature.getVersion(), null, null);
                    }
                    updatesInThisPatch.add(featureUpdate);
                    // Merge result
                    FeatureUpdate oldUpdate = updatesForFeatureKeys.get(key);
                    if (oldUpdate != null) {
                        Version upv = null, newV = null;
                        if (oldUpdate.getNewVersion() != null) {
                            upv = VersionTable.getVersion(oldUpdate.getNewVersion());
                        }
                        if (newVersion != null) {
                            newV = VersionTable.getVersion(newVersion);
                        }
                        if (upv == null && newV == null) {
                        // weird...
                        } else {
                            if (upv == null || (newV != null && upv.compareTo(newV) < 0)) {
                                // other patch contains newer update for the feature
                                updatesForFeatureKeys.put(key, featureUpdate);
                            }
                        }
                    } else {
                        // this is the first update of the bundle
                        updatesForFeatureKeys.put(key, featureUpdate);
                    }
                }
            }
        }
        // now let's see if there are repositories that are NOT updated (either they're not available in patch
        // (like user feature repositories) or simply didn't change (like jclouds 1.8.1 between Fuse 6.2 and 6.2.1)
        Set<String> unchangedRepositoryNames = new HashSet<>(before.keySet());
        unchangedRepositoryNames.removeAll(oldRepositoryNames);
        for (String unchangedRepositoryName : unchangedRepositoryNames) {
            Repository repository = before.get(unchangedRepositoryName);
            boolean hasInstalledFeatures = false;
            for (Feature feature : repository.getFeatures()) {
                if (featuresService.isInstalled(feature)) {
                    FeatureUpdate featureUpdate = new FeatureUpdate(feature.getName(), after.get(unchangedRepositoryName).getURI().toString(), feature.getVersion(), null, null);
                    hasInstalledFeatures = true;
                    // preserve unchanged/user feature - install after restart
                    updatesInThisPatch.add(featureUpdate);
                    // the key doesn't matter
                    updatesForFeatureKeys.put(String.format("%s|%s", feature.getName(), feature.getVersion()), featureUpdate);
                }
            }
            if (!hasInstalledFeatures) {
                // we have to preserve unchanged/user feature repository - even if it had no installed features
                // this featureUpdate means - "restore feature repository only"
                FeatureUpdate featureUpdate = new FeatureUpdate(null, after.get(unchangedRepositoryName).getURI().toString(), null, null, null);
                updatesInThisPatch.add(featureUpdate);
                updatesForFeatureKeys.put(String.format("REPOSITORY_TO_ADD:%s", after.get(unchangedRepositoryName).getURI().toString()), featureUpdate);
            }
        }
        return updatesInThisPatch;
    } catch (Exception e) {
        throw new PatchException(e.getMessage(), e);
    } finally {
        // we'll add new feature repositories again later. here we've added them only to track the updates
        if (after != null) {
            for (String repo : addedRepositoryNames) {
                if (after.get(repo) != null) {
                    featuresService.removeRepository(after.get(repo).getURI(), false);
                }
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) URI(java.net.URI) Feature(org.apache.karaf.features.Feature) LinkedList(java.util.LinkedList) URISyntaxException(java.net.URISyntaxException) PatchException(io.fabric8.patch.management.PatchException) BundleException(org.osgi.framework.BundleException) IOException(java.io.IOException) Repository(org.apache.karaf.features.Repository) Version(org.osgi.framework.Version) PatchException(io.fabric8.patch.management.PatchException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) FeatureUpdate(io.fabric8.patch.management.FeatureUpdate)

Example 43 with User

use of io.fabric8.openshift.api.model.User in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceForStandaloneChildContainersIT method installRollupPatch.

@Test
public void installRollupPatch() throws IOException, GitAPIException {
    initializationPerformedBaselineDistributionFoundInPatches();
    freshKarafStandaloneDistro();
    PatchManagement management = (PatchManagement) pm;
    GitPatchRepository repository = ((GitPatchManagementServiceImpl) pm).getGitPatchRepository();
    Git fork = repository.cloneRepository(repository.findOrCreateMainGitRepository(), true);
    repository.prepareCommit(fork, "artificial change, not treated as user change (could be a patch)").call();
    repository.prepareCommit(fork, "artificial change, not treated as user change").call();
    // no changes, but commit
    ((GitPatchManagementServiceImpl) pm).applyUserChanges(fork);
    FileUtils.write(new File(karafBase, "bin/start"), "echo \"another user change\"\n", true);
    // conflicting change, but commit
    ((GitPatchManagementServiceImpl) pm).applyUserChanges(fork);
    FileUtils.write(new File(karafBase, "bin/test"), "echo \"another user change\"\n");
    // non-conflicting
    ((GitPatchManagementServiceImpl) pm).applyUserChanges(fork);
    repository.closeRepository(fork, true);
    preparePatchZip("src/test/resources/content/patch7", "target/karaf/patches/source/patch-7.zip", false);
    List<PatchData> patches = management.fetchPatches(new File("target/karaf/patches/source/patch-7.zip").toURI().toURL());
    Patch patch = management.trackPatch(patches.get(0));
    String tx = management.beginInstallation(PatchKind.ROLLUP);
    management.install(tx, patch, null);
    @SuppressWarnings("unchecked") Map<String, Git> transactions = (Map<String, Git>) getField(management, "pendingTransactions");
    assertThat(transactions.size(), equalTo(1));
    fork = transactions.values().iterator().next();
    ObjectId since = fork.getRepository().resolve("baseline-child-2.4.0.redhat-620133^{commit}");
    ObjectId to = fork.getRepository().resolve(tx);
    Iterable<RevCommit> commits = fork.log().addRange(since, to).call();
    // only one "user change", because we had two conflicts with new baseline - they were resolved
    // by picking what already comes from rollup patch ("ours"):
    /*
         * Problem with applying the change 657f11c4b65bb7893a2b82f888bb9731a6d5f7d0:
         *  - bin/start: BOTH_MODIFIED
         * Choosing "ours" change
         * Problem with applying the change d9272b97582582f4b056f7170130ec91fc21aeac:
         *  - bin/start: BOTH_MODIFIED
         * Choosing "ours" change
         */
    List<String> commitList = Arrays.asList("[PATCH] Apply user changes", "[PATCH] Apply user changes", "[PATCH] Apply user changes", "[PATCH] Rollup patch patch-7 - resetting etc/overrides.properties", "[PATCH/baseline] Installing baseline-child-2.4.0.redhat-621084");
    int n = 0;
    for (RevCommit c : commits) {
        String msg = c.getShortMessage();
        assertThat(msg, equalTo(commitList.get(n++)));
    }
    assertThat(n, equalTo(commitList.size()));
    assertThat(fork.tagList().call().size(), equalTo(4));
    assertTrue(repository.containsTag(fork, "patch-management"));
    assertTrue(repository.containsTag(fork, "baseline-6.2.0"));
    assertFalse(repository.containsTag(fork, "baseline-6.2.0.redhat-002"));
    assertTrue(repository.containsTag(fork, "baseline-child-2.4.0.redhat-620133"));
    assertTrue(repository.containsTag(fork, "baseline-child-2.4.0.redhat-621084"));
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) GitPatchRepository(io.fabric8.patch.management.impl.GitPatchRepository) GitPatchManagementServiceImpl(io.fabric8.patch.management.impl.GitPatchManagementServiceImpl) Git(org.eclipse.jgit.api.Git) File(java.io.File) Map(java.util.Map) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Test(org.junit.Test)

Example 44 with User

use of io.fabric8.openshift.api.model.User in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceIT method installNonRollupPatchWithUberJars.

@Test
public void installNonRollupPatchWithUberJars() throws IOException, GitAPIException {
    freshKarafStandaloneDistro();
    GitPatchRepository repository = patchManagement("baseline4");
    PatchManagement management = (PatchManagement) pm;
    Git fork = repository.cloneRepository(repository.findOrCreateMainGitRepository(), true);
    // no changes, but commit
    ((GitPatchManagementServiceImpl) pm).applyUserChanges(fork);
    repository.prepareCommit(fork, "artificial change, not treated as user change (could be a patch)").call();
    repository.push(fork);
    repository.closeRepository(fork, true);
    preparePatchZip("src/test/resources/content/patch8", "target/karaf/patches/source/patch-8.zip", false);
    List<PatchData> patches = management.fetchPatches(new File("target/karaf/patches/source/patch-8.zip").toURI().toURL());
    Patch patch = management.trackPatch(patches.get(0));
    String tx = management.beginInstallation(PatchKind.NON_ROLLUP);
    /*
         * bundle.0 = mvn:io.fabric8/pax-romana/1.0.1
         * bundle.1 = mvn:io.fabric8/pax-hellenica/1.0.1/jar
         * # for these two, bundle.getLocation() will return non-matching location
         * bundle.2 = mvn:io.fabric8/pax-bohemia/1.0.1
         * bundle.3 = mvn:io.fabric8/pax-pomerania/1.0.1/jar
         * # for these two, bundle.getLocation() will return matching location
         * bundle.4 = mvn:io.fabric8/pax-avaria/1.0.1/jar/uber
         * bundle.5 = mvn:io.fabric8/pax-mazovia/1.0.1//uber
         * # for these two, bundle.getLocation() will return non-matching location
         * bundle.6 = mvn:io.fabric8/pax-novgorod/1.0.1/jar/uber
         * bundle.7 = mvn:io.fabric8/pax-castile/1.0.1//uber
         */
    LinkedList<BundleUpdate> bundleUpdatesInThisPatch = new LinkedList<>();
    bundleUpdatesInThisPatch.add(new BundleUpdate("pax-romana", "1.0.1", "mvn:io.fabric8/pax-romana/1.0.1", "1.0.0", "mvn:io.fabric8/pax-romana/1.0.0"));
    bundleUpdatesInThisPatch.add(new BundleUpdate("pax-hellenica", "1.0.1", "mvn:io.fabric8/pax-hellenica/1.0.1/jar", "1.0.0", "mvn:io.fabric8/pax-hellenica/1.0.0/jar"));
    bundleUpdatesInThisPatch.add(new BundleUpdate("pax-bohemia", "1.0.1", "mvn:io.fabric8/pax-bohemia/1.0.1", "1.0.0", "mvn:io.fabric8/pax-bohemia/1.0.0/jar"));
    bundleUpdatesInThisPatch.add(new BundleUpdate("pax-pomerania", "1.0.1", "mvn:io.fabric8/pax-pomerania/1.0.1/jar", "1.0.0", "mvn:io.fabric8/pax-pomerania/1.0.0"));
    bundleUpdatesInThisPatch.add(new BundleUpdate("pax-avaria", "1.0.1", "mvn:io.fabric8/pax-avaria/1.0.1/jar/uber", "1.0.0", "mvn:io.fabric8/pax-avaria/1.0.0/jar/uber"));
    bundleUpdatesInThisPatch.add(new BundleUpdate("pax-mazovia", "1.0.1", "mvn:io.fabric8/pax-mazovia/1.0.1//uber", "1.0.0", "mvn:io.fabric8/pax-mazovia/1.0.0//uber"));
    bundleUpdatesInThisPatch.add(new BundleUpdate("pax-novgorod", "1.0.1", "mvn:io.fabric8/pax-novgorod/1.0.1/jar/uber", "1.0.0", "mvn:io.fabric8/pax-novgorod/1.0.0//uber"));
    bundleUpdatesInThisPatch.add(new BundleUpdate("pax-castile", "1.0.1", "mvn:io.fabric8/pax-castile/1.0.1//uber", "1.0.0", "mvn:io.fabric8/pax-castile/1.0.0/jar/uber"));
    management.install(tx, patch, bundleUpdatesInThisPatch);
    @SuppressWarnings("unchecked") Map<String, Git> transactions = (Map<String, Git>) getField(management, "pendingTransactions");
    assertThat(transactions.size(), equalTo(1));
    fork = transactions.values().iterator().next();
    ObjectId since = fork.getRepository().resolve("baseline-6.2.0^{commit}");
    ObjectId to = fork.getRepository().resolve(tx);
    Iterable<RevCommit> commits = fork.log().addRange(since, to).call();
    List<String> commitList = Arrays.asList("[PATCH] Installing patch my-patch-8", "artificial change, not treated as user change (could be a patch)", "[PATCH] Apply user changes");
    int n = 0;
    for (RevCommit c : commits) {
        String msg = c.getShortMessage();
        assertThat(msg, equalTo(commitList.get(n++)));
    }
    assertThat(n, equalTo(commitList.size()));
    assertThat(fork.tagList().call().size(), equalTo(3));
    assertTrue(repository.containsTag(fork, "patch-management"));
    assertTrue(repository.containsTag(fork, "baseline-6.2.0"));
    assertTrue(repository.containsTag(fork, "patch-my-patch-8"));
    Properties startup = new Properties();
    try (FileReader reader = new FileReader(new File(fork.getRepository().getWorkTree(), "etc/startup.properties"))) {
        startup.load(reader);
        assertTrue(startup.containsKey("io/fabric8/pax-romana/1.0.1/pax-romana-1.0.1.jar"));
        assertTrue(startup.containsKey("io/fabric8/pax-hellenica/1.0.1/pax-hellenica-1.0.1.jar"));
        assertTrue(startup.containsKey("io/fabric8/pax-bohemia/1.0.1/pax-bohemia-1.0.1.jar"));
        assertTrue(startup.containsKey("io/fabric8/pax-pomerania/1.0.1/pax-pomerania-1.0.1.jar"));
        assertTrue(startup.containsKey("io/fabric8/pax-avaria/1.0.1/pax-avaria-1.0.1-uber.jar"));
        assertTrue(startup.containsKey("io/fabric8/pax-mazovia/1.0.1/pax-mazovia-1.0.1-uber.jar"));
        assertTrue(startup.containsKey("io/fabric8/pax-novgorod/1.0.1/pax-novgorod-1.0.1-uber.jar"));
        assertTrue(startup.containsKey("io/fabric8/pax-castile/1.0.1/pax-castile-1.0.1-uber.jar"));
        assertFalse(startup.containsKey("io/fabric8/pax-romana/1.0.0/pax-romana-1.0.0.jar"));
        assertFalse(startup.containsKey("io/fabric8/pax-hellenica/1.0.0/pax-hellenica-1.0.0.jar"));
        assertFalse(startup.containsKey("io/fabric8/pax-bohemia/1.0.0/pax-bohemia-1.0.0.jar"));
        assertFalse(startup.containsKey("io/fabric8/pax-pomerania/1.0.0/pax-pomerania-1.0.0.jar"));
        assertFalse(startup.containsKey("io/fabric8/pax-avaria/1.0.0/pax-avaria-1.0.0-uber.jar"));
        assertFalse(startup.containsKey("io/fabric8/pax-mazovia/1.0.0/pax-mazovia-1.0.0-uber.jar"));
        assertFalse(startup.containsKey("io/fabric8/pax-novgorod/1.0.0/pax-novgorod-1.0.0-uber.jar"));
        assertFalse(startup.containsKey("io/fabric8/pax-castile/1.0.0/pax-castile-1.0.0-uber.jar"));
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) GitPatchRepository(io.fabric8.patch.management.impl.GitPatchRepository) Properties(java.util.Properties) LinkedList(java.util.LinkedList) Git(org.eclipse.jgit.api.Git) GitPatchManagementServiceImpl(io.fabric8.patch.management.impl.GitPatchManagementServiceImpl) FileReader(java.io.FileReader) File(java.io.File) Map(java.util.Map) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Test(org.junit.Test)

Example 45 with User

use of io.fabric8.openshift.api.model.User in project fabric8 by jboss-fuse.

the class FabricPatchServiceImpl method install.

@Override
public PatchResult install(final Patch patch, boolean simulation, final String versionId, boolean upload, final String username, final String password, final ProfileUpdateStrategy strategy) throws IOException {
    // we start from the same state as in standalone mode - after successful patch:add
    // we have other things to do in fabric env however:
    // 1. check prerequisites
    // 2. we don't care about current state of framework - it'll be managed by fabric-agent and we don't
    // necessary install a patch for this container we're in
    // 3. we don't do patchManagement.beginInstallation / patchManagement.commitInstallation here
    // this will be done later - after updated fabric-agent is started
    // 4. we don't have to analyze bundles/features/repositories updates - these will be handled simply by
    // updating profiles in specified version
    PatchKind kind = patch.getPatchData().isRollupPatch() ? PatchKind.ROLLUP : PatchKind.NON_ROLLUP;
    if (kind == PatchKind.NON_ROLLUP) {
        throw new UnsupportedOperationException("patch:fabric-install should be used for Rollup patches only");
    }
    String currentContainersVersionId = fabricService.getCurrentContainer().getVersionId();
    if (!simulation && versionId.equals(currentContainersVersionId)) {
        throw new UnsupportedOperationException("Can't install Rollup patch in current version. Please install" + " this patch in new version and then upgrade existing container(s)");
    }
    fabricService.adapt(ProfileService.class).getRequiredVersion(versionId);
    // just a list of new bundle locations - in fabric the updatable version depends on the moment we
    // apply the new version to existing containers.
    List<BundleUpdate> bundleUpdatesInThisPatch = bundleUpdatesInPatch(patch);
    Presentation.displayBundleUpdates(bundleUpdatesInThisPatch, true);
    PatchResult result = new PatchResult(patch.getPatchData(), simulation, System.currentTimeMillis(), bundleUpdatesInThisPatch, null);
    if (!simulation) {
        // update profile definitions stored in Git. We don't update ${karaf.home}/fabric, becuase it is used
        // only once - when importing profiles during fabric:create.
        // when fabric is already available, we have to update (Git) repository information
        GitOperation operation = new GitOperation() {

            @Override
            public Object call(Git git, GitContext context) throws Exception {
                // we can't pass git reference to patch-management
                // because patch-management private-packages git library
                // but we can leverage the write lock we have
                GitHelpers.checkoutBranch(git, versionId);
                // let's get back in history to the point before user changes (profile-edits), but not earlier
                // than last R patch
                String patchBranch = patchManagement.findLatestPatchRevision(git.getRepository().getDirectory(), versionId);
                // now install profiles from patch just like there were no user changes
                patchManagement.installProfiles(git.getRepository().getDirectory(), versionId, patch, strategy);
                // and finally we have to merge user and patch changes to profiles.
                patchManagement.mergeProfileChanges(patch, git.getRepository().getDirectory(), versionId, patchBranch);
                context.commitMessage("Installing rollup patch \"" + patch.getPatchData().getId() + "\"");
                return null;
            }
        };
        gitDataStore.gitOperation(new GitContext().requireCommit().setRequirePush(true), operation, null);
        if (upload) {
            PatchManagement.UploadCallback callback = new PatchManagement.UploadCallback() {

                @Override
                public void doWithUrlConnection(URLConnection connection) throws ProtocolException {
                    if (connection instanceof HttpURLConnection) {
                        ((HttpURLConnection) connection).setRequestMethod("PUT");
                    }
                    if (username != null && password != null) {
                        connection.setRequestProperty("Authorization", "Basic " + Base64Encoder.encode(username + ":" + password));
                    }
                }
            };
            patchManagement.uploadPatchArtifacts(patch.getPatchData(), fabricService.getMavenRepoUploadURI(), callback);
        }
    }
    return result;
}
Also used : PatchKind(io.fabric8.patch.management.PatchKind) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) ProfileService(io.fabric8.api.ProfileService) GitOperation(io.fabric8.git.internal.GitOperation) Git(org.eclipse.jgit.api.Git) HttpURLConnection(java.net.HttpURLConnection) GitContext(io.fabric8.api.GitContext) PatchManagement(io.fabric8.patch.management.PatchManagement) PatchResult(io.fabric8.patch.management.PatchResult) BundleUpdate(io.fabric8.patch.management.BundleUpdate)

Aggregations

Test (org.junit.Test)31 File (java.io.File)19 IOException (java.io.IOException)17 HashMap (java.util.HashMap)16 Git (org.eclipse.jgit.api.Git)12 AuthConfig (io.fabric8.maven.docker.access.AuthConfig)10 Map (java.util.Map)10 LinkedList (java.util.LinkedList)8 RevCommit (org.eclipse.jgit.revwalk.RevCommit)8 ObjectId (org.eclipse.jgit.lib.ObjectId)7 BuildImageConfiguration (io.fabric8.maven.docker.config.BuildImageConfiguration)6 ArrayList (java.util.ArrayList)6 PatchException (io.fabric8.patch.management.PatchException)5 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)5 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)4 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)4 URL (java.net.URL)4 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)4 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)4 IntOrString (io.fabric8.kubernetes.api.model.IntOrString)3