Search in sources :

Example 86 with Entry

use of io.fabric8.maven.docker.config.CopyConfiguration.Entry in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceImpl method updateReferences.

/**
 * Changes prefixed references (to artifacts in <code>${karaf.default.repository}</code>) according to
 * a list of bundle updates.
 * @param fork
 * @param file
 * @param prefix
 * @param locationUpdates
 * @param useBackSlash
 */
protected void updateReferences(Git fork, String file, String prefix, Map<String, String> locationUpdates, boolean useBackSlash) {
    File updatedFile = new File(fork.getRepository().getWorkTree(), file);
    if (!updatedFile.isFile()) {
        return;
    }
    BufferedReader reader = null;
    StringWriter sw = new StringWriter();
    try {
        Activator.log2(LogService.LOG_INFO, "Updating \"" + file + "\"");
        reader = new BufferedReader(new FileReader(updatedFile));
        String line = null;
        while ((line = reader.readLine()) != null) {
            for (Map.Entry<String, String> entry : locationUpdates.entrySet()) {
                String pattern = prefix + entry.getKey();
                String replacement = prefix + entry.getValue();
                if (useBackSlash) {
                    pattern = pattern.replaceAll("/", "\\\\");
                    replacement = replacement.replaceAll("/", "\\\\");
                }
                if (line.contains(pattern)) {
                    line = line.replace(pattern, replacement);
                }
            }
            sw.append(line);
            if (useBackSlash) {
                // Assume it's .bat file
                sw.append("\r");
            }
            sw.append("\n");
        }
        IOUtils.closeQuietly(reader);
        FileUtils.write(updatedFile, sw.toString());
    } catch (Exception e) {
        Activator.log(LogService.LOG_ERROR, null, e.getMessage(), e, true);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}
Also used : StringWriter(java.io.StringWriter) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) Map(java.util.Map) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) PatchException(io.fabric8.patch.management.PatchException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 87 with Entry

use of io.fabric8.maven.docker.config.CopyConfiguration.Entry in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceImpl method install.

@Override
public void install(String transaction, Patch patch, List<BundleUpdate> bundleUpdatesInThisPatch) {
    transactionIsValid(transaction, patch);
    Git fork = pendingTransactions.get(transaction);
    try {
        switch(pendingTransactionsTypes.get(transaction)) {
            case ROLLUP:
                {
                    Activator.log2(LogService.LOG_INFO, String.format("Installing rollup patch \"%s\"", patch.getPatchData().getId()));
                    // we can install only one rollup patch within single transaction
                    // and it is equal to cherry-picking all user changes on top of transaction branch
                    // after cherry-picking the commit from the rollup patch branch
                    // rollup patches do their own update to startup.properties
                    // we're operating on patch branch, HEAD of the patch branch points to the baseline
                    ObjectId since = fork.getRepository().resolve("HEAD^{commit}");
                    // we'll pick all user changes between baseline and main patch branch without P installations
                    ObjectId to = fork.getRepository().resolve(gitPatchRepository.getMainBranchName() + "^{commit}");
                    Iterable<RevCommit> mainChanges = fork.log().addRange(since, to).call();
                    List<RevCommit> userChanges = new LinkedList<>();
                    // gather lines of HF patches - patches that have *only* bundle updates
                    // if any of HF patches provide newer version of artifact than currently installed R patch,
                    // we will leave the relevant line in etc/overrides.properties
                    List<String> hfChanges = new LinkedList<>();
                    for (RevCommit rc : mainChanges) {
                        if (isUserChangeCommit(rc)) {
                            userChanges.add(rc);
                        } else {
                            String hfPatchId = isHfChangeCommit(rc);
                            if (hfPatchId != null) {
                                hfChanges.addAll(gatherOverrides(hfPatchId, patch));
                            }
                        }
                    }
                    String patchRef = patch.getManagedPatch().getCommitId();
                    if (env == EnvType.STANDALONE_CHILD) {
                        // we're in a slightly different situation:
                        // - patch was patch:added in root container
                        // - its main commit should be used when patching full Fuse/AMQ container
                        // - it created "side" commits (with tags) for this case of patching admin:create based containers
                        // - those tags are stored in special patch-info.txt file within patch' commit
                        String patchInfo = gitPatchRepository.getFileContent(fork, patchRef, "patch-info.txt");
                        if (patchInfo != null) {
                            BufferedReader reader = new BufferedReader(new StringReader(patchInfo));
                            String line = null;
                            while ((line = reader.readLine()) != null) {
                                if (line.startsWith("#")) {
                                    continue;
                                }
                                Pattern p = Pattern.compile(env.getBaselineTagFormat().replace("%s", "(.*)"));
                                if (p.matcher(line).matches()) {
                                    // this means we have another commit/tag that we should chery-pick as a patch
                                    // for this standalone child container
                                    patchRef = line.trim();
                                }
                            }
                        } else {
                            // hmm, we actually can't patch standalone child container then...
                            Activator.log2(LogService.LOG_WARNING, String.format("Can't install rollup patch \"%s\" in admin container - no information about admin container patch", patch.getPatchData().getId()));
                            return;
                        }
                    }
                    if (env == EnvType.STANDALONE) {
                        // pick the rollup patch
                        fork.cherryPick().include(fork.getRepository().resolve(patchRef)).setNoCommit(true).call();
                        gitPatchRepository.prepareCommit(fork, String.format(MARKER_R_PATCH_INSTALLATION_PATTERN, patch.getPatchData().getId())).call();
                    } else if (env == EnvType.STANDALONE_CHILD) {
                        // rebase on top of rollup patch
                        fork.reset().setMode(ResetCommand.ResetType.HARD).setRef("refs/tags/" + patchRef + "^{commit}").call();
                    }
                    // next commit - reset overrides.properties - this is 2nd step of installing rollup patch
                    // we are doing it even if the commit is going to be empty - this is the same step as after
                    // creating initial baseline
                    resetOverrides(fork.getRepository().getWorkTree(), hfChanges);
                    fork.add().addFilepattern("etc/overrides.properties").call();
                    RevCommit c = gitPatchRepository.prepareCommit(fork, String.format(MARKER_R_PATCH_RESET_OVERRIDES_PATTERN, patch.getPatchData().getId())).call();
                    if (env == EnvType.STANDALONE) {
                        // tag the new rollup patch as new baseline
                        String newFuseVersion = determineVersion(fork.getRepository().getWorkTree(), "fuse");
                        fork.tag().setName(String.format(EnvType.STANDALONE.getBaselineTagFormat(), newFuseVersion)).setObjectId(c).call();
                    }
                    // reapply those user changes that are not conflicting
                    // for each conflicting cherry-pick we do a backup of user files, to be able to restore them
                    // when rollup patch is rolled back
                    ListIterator<RevCommit> it = userChanges.listIterator(userChanges.size());
                    int prefixSize = Integer.toString(userChanges.size()).length();
                    int count = 1;
                    while (it.hasPrevious()) {
                        RevCommit userChange = it.previous();
                        String prefix = String.format("%0" + prefixSize + "d-%s", count++, userChange.getName());
                        CherryPickResult result = fork.cherryPick().include(userChange).setNoCommit(true).call();
                        // ENTESB-5492: remove etc/overrides.properties if there is such file left from old patch
                        // mechanism
                        File overrides = new File(fork.getRepository().getWorkTree(), "etc/overrides.properties");
                        if (overrides.isFile()) {
                            // version of some bundles, overrides.properties should be kept
                            if (!(hfChanges.size() > 0 && overrides.length() > 0)) {
                                overrides.delete();
                                fork.rm().addFilepattern("etc/overrides.properties").call();
                            }
                        }
                        // if there's conflict here, prefer patch version (which is "ours" (first) in this case)
                        handleCherryPickConflict(patch.getPatchData().getPatchDirectory(), fork, result, userChange, false, PatchKind.ROLLUP, prefix, true, false);
                        // always commit even empty changes - to be able to restore user changes when rolling back
                        // rollup patch.
                        // commit has the original commit id appended to the message.
                        // when we rebase on OLDER baseline (rollback) we restore backed up files based on this
                        // commit id (from patches/patch-id.backup/number-commit directory)
                        String newMessage = userChange.getFullMessage() + "\n\n";
                        newMessage += prefix;
                        gitPatchRepository.prepareCommit(fork, newMessage).call();
                        // we may have unadded changes - when file mode is changed
                        fork.reset().setMode(ResetCommand.ResetType.HARD).call();
                    }
                    // finally - let's get rid of all the tags related to non-rollup patches installed between
                    // previous baseline and previous HEAD, because installing rollup patch makes all previous P
                    // patches obsolete
                    RevWalk walk = new RevWalk(fork.getRepository());
                    RevCommit c1 = walk.parseCommit(since);
                    RevCommit c2 = walk.parseCommit(to);
                    Map<String, RevTag> tags = gitPatchRepository.findTagsBetween(fork, c1, c2);
                    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();
                        }
                    }
                    break;
                }
            case NON_ROLLUP:
                {
                    Activator.log2(LogService.LOG_INFO, String.format("Installing non-rollup patch \"%s\"", patch.getPatchData().getId()));
                    // simply cherry-pick patch commit to transaction branch
                    // non-rollup patches require manual change to artifact references in all files
                    // pick the non-rollup patch
                    RevCommit commit = new RevWalk(fork.getRepository()).parseCommit(fork.getRepository().resolve(patch.getManagedPatch().getCommitId()));
                    CherryPickResult result = fork.cherryPick().include(commit).setNoCommit(true).call();
                    handleCherryPickConflict(patch.getPatchData().getPatchDirectory(), fork, result, commit, true, PatchKind.NON_ROLLUP, null, true, false);
                    // there are several files in ${karaf.home} that need to be changed together with patch
                    // commit, to make them reference updated bundles (paths, locations, ...)
                    updateFileReferences(fork, patch.getPatchData(), bundleUpdatesInThisPatch);
                    updateOverrides(fork.getRepository().getWorkTree(), patch.getPatchData());
                    fork.add().addFilepattern(".").call();
                    // always commit non-rollup patch
                    RevCommit c = gitPatchRepository.prepareCommit(fork, String.format(MARKER_P_PATCH_INSTALLATION_PATTERN, patch.getPatchData().getId())).call();
                    // we may have unadded changes - when file mode is changed
                    fork.reset().setMode(ResetCommand.ResetType.HARD).call();
                    // tag the installed patch (to easily rollback and to prevent another installation)
                    String tagName = String.format("patch-%s", patch.getPatchData().getId().replace(' ', '-'));
                    if (env == EnvType.STANDALONE_CHILD) {
                        tagName += "-" + gitPatchRepository.getStandaloneChildkarafName();
                    }
                    fork.tag().setName(tagName).setObjectId(c).call();
                    break;
                }
        }
    } catch (IOException | GitAPIException e) {
        throw new PatchException(e.getMessage(), e);
    }
}
Also used : Pattern(java.util.regex.Pattern) ObjectId(org.eclipse.jgit.lib.ObjectId) IOException(java.io.IOException) ListIterator(java.util.ListIterator) RevWalk(org.eclipse.jgit.revwalk.RevWalk) 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) Git(org.eclipse.jgit.api.Git) CherryPickResult(org.eclipse.jgit.api.CherryPickResult) RefSpec(org.eclipse.jgit.transport.RefSpec) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) 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) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 88 with Entry

use of io.fabric8.maven.docker.config.CopyConfiguration.Entry in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceImpl method trackBaselinesForRootContainer.

/**
 * These baselines are created from org.jboss.fuse:jboss-fuse-karaf or org.jboss.amq:jboss-a-mq baseline distros.
 * @param fork
 */
private void trackBaselinesForRootContainer(Git fork) throws IOException, GitAPIException {
    // two separate branches for two kinds of baselines for root containers
    if (fork.getRepository().getRef("refs/heads/" + gitPatchRepository.getFuseRootContainerPatchBranchName()) == null) {
        String startPoint = "patch-management^{commit}";
        if (fork.getRepository().getRef("refs/remotes/origin/" + gitPatchRepository.getFuseRootContainerPatchBranchName()) != null) {
            startPoint = "refs/remotes/origin/" + gitPatchRepository.getFuseRootContainerPatchBranchName();
        }
        gitPatchRepository.checkout(fork).setName(gitPatchRepository.getFuseRootContainerPatchBranchName()).setStartPoint(startPoint).setCreateBranch(true).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
    }
    if (fork.getRepository().getRef("refs/heads/" + gitPatchRepository.getAmqRootContainerPatchBranchName()) == null) {
        String startPoint = "patch-management^{commit}";
        if (fork.getRepository().getRef("refs/remotes/origin/" + gitPatchRepository.getAmqRootContainerPatchBranchName()) != null) {
            startPoint = "refs/remotes/origin/" + gitPatchRepository.getAmqRootContainerPatchBranchName();
        }
        gitPatchRepository.checkout(fork).setName(gitPatchRepository.getAmqRootContainerPatchBranchName()).setStartPoint(startPoint).setCreateBranch(true).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
    }
    File systemRepo = getSystemRepository(karafHome, systemContext);
    String currentFuseVersion = determineVersion(karafHome, "fuse");
    String currentFabricVersion = determineVersion(karafHome, "fabric");
    // Fuse distros first
    File[] versionDirs = new File(systemRepo, "org/jboss/fuse/jboss-fuse-karaf").listFiles();
    Map<Version, File> versions = new TreeMap<>();
    gitPatchRepository.checkout(fork).setName(gitPatchRepository.getFuseRootContainerPatchBranchName()).call();
    // we'll look for Fuse/AMQ baseline in /patches dir too - it doesn't have to be present
    versions.put(Utils.getOsgiVersion(currentFuseVersion), patchesDir);
    if (versionDirs != null) {
        for (File version : versionDirs) {
            if (version.isDirectory()) {
                versions.put(Utils.getOsgiVersion(version.getName()), version);
            }
        }
    }
    for (Map.Entry<Version, File> entry : versions.entrySet()) {
        String version = entry.getKey().toString();
        if (gitPatchRepository.containsTag(fork, String.format(EnvType.FABRIC_FUSE.getBaselineTagFormat(), version))) {
            continue;
        }
        File baselineDistribution = null;
        File location = new File(entry.getValue(), String.format("jboss-fuse-karaf-%1$s-baseline.zip", version));
        if (location.isFile()) {
            baselineDistribution = location;
            Activator.log(LogService.LOG_INFO, "Found Fuse baseline distribution: " + baselineDistribution.getCanonicalPath());
        }
        if (baselineDistribution != null) {
            RevCommit commit = trackBaselineRepository(fork, baselineDistribution, version);
            fork.tag().setName(String.format(EnvType.FABRIC_FUSE.getBaselineTagFormat(), version)).setObjectId(commit).call();
        }
    }
    // Now AMQ distros
    versionDirs = new File(systemRepo, "org/jboss/amq/jboss-a-mq").listFiles();
    versions.clear();
    gitPatchRepository.checkout(fork).setName(gitPatchRepository.getAmqRootContainerPatchBranchName()).call();
    // we'll look for Fuse/AMQ baseline in /patches dir too - it doesn't have to be present
    versions.put(Utils.getOsgiVersion(currentFuseVersion), patchesDir);
    if (versionDirs != null) {
        for (File version : versionDirs) {
            if (version.isDirectory()) {
                versions.put(Utils.getOsgiVersion(version.getName()), version);
            }
        }
    }
    for (Map.Entry<Version, File> entry : versions.entrySet()) {
        String version = entry.getKey().toString();
        if (gitPatchRepository.containsTag(fork, String.format(EnvType.FABRIC_AMQ.getBaselineTagFormat(), version))) {
            continue;
        }
        File baselineDistribution = null;
        File location = new File(entry.getValue(), String.format("jboss-a-mq-%1$s-baseline.zip", version));
        if (location.isFile()) {
            baselineDistribution = location;
            Activator.log(LogService.LOG_INFO, "Found AMQ baseline distribution: " + baselineDistribution.getCanonicalPath());
        }
        if (baselineDistribution != null) {
            RevCommit commit = trackBaselineRepository(fork, baselineDistribution, version);
            fork.tag().setName(String.format(EnvType.FABRIC_AMQ.getBaselineTagFormat(), version)).setObjectId(commit).call();
        }
    }
    gitPatchRepository.push(fork, gitPatchRepository.getFuseRootContainerPatchBranchName());
    gitPatchRepository.push(fork, gitPatchRepository.getAmqRootContainerPatchBranchName());
}
Also used : Version(org.osgi.framework.Version) Artifact.isSameButVersion(io.fabric8.patch.management.Artifact.isSameButVersion) TreeMap(java.util.TreeMap) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) Map(java.util.Map) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 89 with Entry

use of io.fabric8.maven.docker.config.CopyConfiguration.Entry 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 90 with Entry

use of io.fabric8.maven.docker.config.CopyConfiguration.Entry in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceImpl method unzipFabric8Distro.

/**
 * Unzips <code>bin</code> and <code>etc</code> everything we need from org.apache.karaf.admin.core.
 * @param rootDir
 * @param artifact
 * @param version
 * @param fork
 * @return branch name where the distro should be tracked, or <code>null</code> if it's already tracked
 * @throws IOException
 */
private String unzipFabric8Distro(String rootDir, File artifact, String version, Git fork) throws IOException, GitAPIException {
    ZipFile zf = new ZipFile(artifact);
    try {
        // first pass - what's this distro?
        boolean officialFabric8 = true;
        for (Enumeration<ZipArchiveEntry> e = zf.getEntries(); e.hasMoreElements(); ) {
            ZipArchiveEntry entry = e.nextElement();
            String name = entry.getName();
            if (name.startsWith(rootDir + "/")) {
                name = name.substring(rootDir.length() + 1);
            }
            if ("etc/startup.properties".equals(name)) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOUtils.copyLarge(zf.getInputStream(entry), baos);
                Properties props = new Properties();
                props.load(new ByteArrayInputStream(baos.toByteArray()));
                for (String p : props.stringPropertyNames()) {
                    if (p.startsWith("org/jboss/fuse/shared-commands/")) {
                        // we have Fuse!
                        officialFabric8 = false;
                        break;
                    }
                }
            }
        }
        // checkout correct branch
        if (officialFabric8) {
            if (gitPatchRepository.containsTag(fork, String.format("baseline-ssh-fabric8-%s", version))) {
                return null;
            }
            gitPatchRepository.checkout(fork).setName(gitPatchRepository.getFabric8SSHContainerPatchBranchName()).call();
        } else {
            if (gitPatchRepository.containsTag(fork, String.format("baseline-ssh-fuse-%s", version))) {
                return null;
            }
            gitPatchRepository.checkout(fork).setName(gitPatchRepository.getFuseSSHContainerPatchBranchName()).call();
        }
        for (String managedDirectory : MANAGED_DIRECTORIES) {
            FileUtils.deleteDirectory(new File(fork.getRepository().getWorkTree(), managedDirectory));
        }
        // second pass - unzip what we need
        for (Enumeration<ZipArchiveEntry> e = zf.getEntries(); e.hasMoreElements(); ) {
            ZipArchiveEntry entry = e.nextElement();
            String name = entry.getName();
            if (name.startsWith(rootDir + "/")) {
                name = name.substring(rootDir.length() + 1);
            }
            if (!(name.startsWith("bin") || name.startsWith("etc") || name.startsWith("fabric") || name.startsWith("lib") || name.startsWith("licenses") || name.startsWith("metatype"))) {
                continue;
            }
            if (!entry.isDirectory() && !entry.isUnixSymlink()) {
                File file = new File(fork.getRepository().getWorkTree(), name);
                file.getParentFile().mkdirs();
                FileOutputStream output = new EOLFixingFileOutputStream(fork.getRepository().getWorkTree(), file);
                IOUtils.copyLarge(zf.getInputStream(entry), output);
                IOUtils.closeQuietly(output);
                if (Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class) != null) {
                    if (name.startsWith("bin/") && !name.endsWith(".bat")) {
                        Files.setPosixFilePermissions(file.toPath(), getPermissionsFromUnixMode(file, 0775));
                    }
                }
            }
        }
        return officialFabric8 ? gitPatchRepository.getFabric8SSHContainerPatchBranchName() : gitPatchRepository.getFuseSSHContainerPatchBranchName();
    } finally {
        if (zf != null) {
            zf.close();
        }
    }
}
Also used : ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) ByteArrayInputStream(java.io.ByteArrayInputStream) EOLFixingFileOutputStream(io.fabric8.patch.management.io.EOLFixingFileOutputStream) FileOutputStream(java.io.FileOutputStream) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) EOLFixingFileOutputStream(io.fabric8.patch.management.io.EOLFixingFileOutputStream) Properties(java.util.Properties) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) PosixFileAttributeView(java.nio.file.attribute.PosixFileAttributeView)

Aggregations

Map (java.util.Map)89 HashMap (java.util.HashMap)57 IOException (java.io.IOException)31 File (java.io.File)30 ArrayList (java.util.ArrayList)26 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)16 List (java.util.List)14 Properties (java.util.Properties)14 HashSet (java.util.HashSet)10 Entry (io.fabric8.maven.docker.config.CopyConfiguration.Entry)9 ZipFile (org.apache.commons.compress.archivers.zip.ZipFile)9 Test (org.junit.Test)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)8 LinkedHashMap (java.util.LinkedHashMap)8 TreeMap (java.util.TreeMap)8 Resource (io.fabric8.kubernetes.client.dsl.Resource)7 FileInputStream (java.io.FileInputStream)7 Set (java.util.Set)7 Profile (io.fabric8.api.Profile)6 ProfileService (io.fabric8.api.ProfileService)5