Search in sources :

Example 1 with PATTERN_SITE

use of org.craftercms.studio.api.v1.constant.StudioConstants.PATTERN_SITE in project studio by craftercms.

the class RepositoryManagementServiceInternalImpl method removeRemote.

@RetryingOperation
@Override
public boolean removeRemote(String siteId, String remoteName) throws CryptoException, RemoteNotRemovableException {
    if (!isRemovableRemote(siteId, remoteName)) {
        throw new RemoteNotRemovableException("Remote repository " + remoteName + " is not removable");
    }
    logger.debug("Remove remote " + remoteName + " from the sandbox repo for the site " + siteId);
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
    Repository repo = helper.getRepository(siteId, SANDBOX);
    String gitLockKey = SITE_SANDBOX_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, siteId);
    generalLockService.lock(gitLockKey);
    try (Git git = new Git(repo)) {
        RemoteRemoveCommand remoteRemoveCommand = git.remoteRemove();
        remoteRemoveCommand.setRemoteName(remoteName);
        retryingRepositoryOperationFacade.call(remoteRemoveCommand);
        List<Ref> resultRemoteBranches = git.branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call();
        List<String> branchesToDelete = new ArrayList<String>();
        for (Ref remoteBranchRef : resultRemoteBranches) {
            if (remoteBranchRef.getName().startsWith(Constants.R_REMOTES + remoteName)) {
                branchesToDelete.add(remoteBranchRef.getName());
            }
        }
        if (CollectionUtils.isNotEmpty(branchesToDelete)) {
            DeleteBranchCommand delBranch = git.branchDelete();
            String[] array = new String[branchesToDelete.size()];
            delBranch.setBranchNames(branchesToDelete.toArray(array));
            delBranch.setForce(true);
            retryingRepositoryOperationFacade.call(delBranch);
        }
    } catch (GitAPIException e) {
        logger.error("Failed to remove remote " + remoteName + " for site " + siteId, e);
        return false;
    } finally {
        generalLockService.unlock(gitLockKey);
    }
    logger.debug("Remove remote record from database for remote " + remoteName + " and site " + siteId);
    Map<String, String> params = new HashMap<String, String>();
    params.put("siteId", siteId);
    params.put("remoteName", remoteName);
    remoteRepositoryDao.deleteRemoteRepository(params);
    return true;
}
Also used : RemoteNotRemovableException(org.craftercms.studio.api.v1.exception.repository.RemoteNotRemovableException) DeleteBranchCommand(org.eclipse.jgit.api.DeleteBranchCommand) HashMap(java.util.HashMap) RemoteRemoveCommand(org.eclipse.jgit.api.RemoteRemoveCommand) ArrayList(java.util.ArrayList) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v1.repository.ContentRepository) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) RetryingOperation(org.craftercms.studio.api.v2.annotation.RetryingOperation)

Example 2 with PATTERN_SITE

use of org.craftercms.studio.api.v1.constant.StudioConstants.PATTERN_SITE in project studio by craftercms.

the class RepositoryManagementServiceInternalImpl method pullFromRemote.

@Override
public boolean pullFromRemote(String siteId, String remoteName, String remoteBranch, String mergeStrategy) throws InvalidRemoteUrlException, ServiceLayerException, CryptoException {
    logger.debug("Get remote data from database for remote " + remoteName + " and site " + siteId);
    String gitLockKey = SITE_SANDBOX_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, siteId);
    RemoteRepository remoteRepository = getRemoteRepository(siteId, remoteName);
    logger.debug("Prepare pull command");
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
    Repository repo = helper.getRepository(siteId, SANDBOX);
    generalLockService.lock(gitLockKey);
    try (Git git = new Git(repo)) {
        PullResult pullResult = null;
        PullCommand pullCommand = git.pull();
        logger.debug("Set remote " + remoteName);
        pullCommand.setRemote(remoteRepository.getRemoteName());
        logger.debug("Set branch to be " + remoteBranch);
        pullCommand.setRemoteBranchName(remoteBranch);
        Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
        pullCommand = helper.setAuthenticationForCommand(pullCommand, remoteRepository.getAuthenticationType(), remoteRepository.getRemoteUsername(), remoteRepository.getRemotePassword(), remoteRepository.getRemoteToken(), remoteRepository.getRemotePrivateKey(), tempKey, true);
        switch(mergeStrategy) {
            case THEIRS:
                pullCommand.setStrategy(MergeStrategy.THEIRS);
                break;
            case OURS:
                pullCommand.setStrategy(MergeStrategy.OURS);
                break;
            default:
                break;
        }
        pullCommand.setFastForward(MergeCommand.FastForwardMode.NO_FF);
        pullResult = retryingRepositoryOperationFacade.call(pullCommand);
        String pullResultMessage = pullResult.toString();
        if (StringUtils.isNotEmpty(pullResultMessage)) {
            logger.info(pullResultMessage);
        }
        Files.delete(tempKey);
        if (!pullResult.isSuccessful() && conflictNotificationEnabled()) {
            List<String> conflictFiles = new ArrayList<String>();
            if (pullResult.getMergeResult() != null) {
                pullResult.getMergeResult().getConflicts().forEach((m, v) -> {
                    conflictFiles.add(m);
                });
            }
            notificationService.notifyRepositoryMergeConflict(siteId, conflictFiles, Locale.ENGLISH);
        }
        if (pullResult.isSuccessful()) {
            String lastCommitId = contentRepository.getRepoLastCommitId(siteId);
            contentRepositoryV2.upsertGitLogList(siteId, Arrays.asList(lastCommitId), false, false);
            List<String> newMergedCommits = extractCommitIdsFromPullResult(siteId, repo, pullResult);
            List<String> commitIds = new ArrayList<String>();
            if (Objects.nonNull(newMergedCommits) && newMergedCommits.size() > 0) {
                logger.debug("Really pulled commits:");
                int cnt = 0;
                for (int i = 0; i < newMergedCommits.size(); i++) {
                    String commitId = newMergedCommits.get(i);
                    logger.debug(commitId);
                    if (!StringUtils.equals(lastCommitId, commitId)) {
                        commitIds.add(commitId);
                        if (cnt++ >= batchSizeGitLog) {
                            contentRepositoryV2.upsertGitLogList(siteId, commitIds, true, true);
                            cnt = 0;
                            commitIds.clear();
                        }
                    }
                }
                if (Objects.nonNull(commitIds) && commitIds.size() > 0) {
                    contentRepositoryV2.upsertGitLogList(siteId, commitIds, true, true);
                }
            }
            siteService.updateLastCommitId(siteId, lastCommitId);
        }
        return pullResult != null && pullResult.isSuccessful();
    } catch (InvalidRemoteException e) {
        logger.error("Remote is invalid " + remoteName, e);
        throw new InvalidRemoteUrlException();
    } catch (GitAPIException e) {
        logger.error("Error while pulling from remote " + remoteName + " branch " + remoteBranch + " for site " + siteId, e);
        throw new ServiceLayerException("Error while pulling from remote " + remoteName + " branch " + remoteBranch + " for site " + siteId, e);
    } catch (CryptoException | IOException e) {
        throw new ServiceLayerException(e);
    } finally {
        generalLockService.unlock(gitLockKey);
    }
}
Also used : Path(java.nio.file.Path) PullCommand(org.eclipse.jgit.api.PullCommand) ArrayList(java.util.ArrayList) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) IOException(java.io.IOException) InvalidRemoteUrlException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException) PullResult(org.eclipse.jgit.api.PullResult) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v1.repository.ContentRepository) Git(org.eclipse.jgit.api.Git) InvalidRemoteException(org.eclipse.jgit.api.errors.InvalidRemoteException) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) CryptoException(org.craftercms.commons.crypto.CryptoException)

Example 3 with PATTERN_SITE

use of org.craftercms.studio.api.v1.constant.StudioConstants.PATTERN_SITE in project studio by craftercms.

the class GitContentRepository method publish.

@RetryingOperation
@Override
public void publish(String site, String sandboxBranch, List<DeploymentItemTO> deploymentItems, String environment, String author, String comment) throws DeploymentException {
    if (CollectionUtils.isEmpty(deploymentItems)) {
        return;
    }
    String commitId = EMPTY;
    String gitLockKey = SITE_PUBLISHED_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, site);
    generalLockService.lock(gitLockKey);
    try {
        GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
        Repository repo = helper.getRepository(site, PUBLISHED);
        boolean repoCreated = false;
        if (Objects.isNull(repo)) {
            helper.createPublishedRepository(site, sandboxBranch);
            repo = helper.getRepository(site, PUBLISHED);
            repoCreated = Objects.nonNull(repo);
        }
        String path = EMPTY;
        String sandboxBranchName = sandboxBranch;
        if (StringUtils.isEmpty(sandboxBranchName)) {
            sandboxBranchName = studioConfiguration.getProperty(REPO_SANDBOX_BRANCH);
        }
        synchronized (repo) {
            try (Git git = new Git(repo)) {
                String inProgressBranchName = environment + IN_PROGRESS_BRANCH_NAME_SUFFIX;
                // fetch "origin/master"
                logger.debug("Fetch from sandbox for site " + site);
                FetchCommand fetchCommand = git.fetch();
                retryingRepositoryOperationFacade.call(fetchCommand);
                // checkout master and pull from sandbox
                logger.debug("Checkout published/master branch for site " + site);
                try {
                    // First delete it in case it already exists (ignored if does not exist)
                    String currentBranch = repo.getBranch();
                    if (currentBranch.endsWith(IN_PROGRESS_BRANCH_NAME_SUFFIX)) {
                        ResetCommand resetCommand = git.reset().setMode(HARD);
                        retryingRepositoryOperationFacade.call(resetCommand);
                    }
                    Ref ref = repo.exactRef(R_HEADS + sandboxBranchName);
                    boolean createBranch = (ref == null);
                    CheckoutCommand checkoutCommand = git.checkout().setName(sandboxBranchName).setCreateBranch(createBranch);
                    retryingRepositoryOperationFacade.call(checkoutCommand);
                    logger.debug("Delete in-progress branch, in case it was not cleaned up for site " + site);
                    DeleteBranchCommand deleteBranchCommand = git.branchDelete().setBranchNames(inProgressBranchName).setForce(true);
                    retryingRepositoryOperationFacade.call(deleteBranchCommand);
                    PullCommand pullCommand = git.pull().setRemote(DEFAULT_REMOTE_NAME).setRemoteBranchName(sandboxBranchName).setStrategy(THEIRS);
                    retryingRepositoryOperationFacade.call(pullCommand);
                } catch (RefNotFoundException e) {
                    logger.error("Failed to checkout published master and to pull content from sandbox for site " + site, e);
                    throw new DeploymentException("Failed to checkout published master and to pull content from " + "sandbox for site " + site);
                }
                // checkout environment branch
                logger.debug("Checkout environment branch " + environment + " for site " + site);
                try {
                    CheckoutCommand checkoutCommand = git.checkout().setName(environment);
                    retryingRepositoryOperationFacade.call(checkoutCommand);
                } catch (RefNotFoundException e) {
                    logger.info("Not able to find branch " + environment + " for site " + site + ". Creating new branch");
                    // create new environment branch
                    // it will start as empty orphan branch
                    CheckoutCommand checkoutCommand = git.checkout().setOrphan(true).setForceRefUpdate(true).setStartPoint(sandboxBranchName).setUpstreamMode(TRACK).setName(environment);
                    retryingRepositoryOperationFacade.call(checkoutCommand);
                    // remove any content to create empty branch
                    RmCommand rmcmd = git.rm();
                    File[] toDelete = repo.getWorkTree().listFiles();
                    for (File toDel : toDelete) {
                        if (!repo.getDirectory().equals(toDel) && !StringUtils.equals(toDel.getName(), DOT_GIT_IGNORE)) {
                            rmcmd.addFilepattern(toDel.getName());
                        }
                    }
                    retryingRepositoryOperationFacade.call(rmcmd);
                    CommitCommand commitCommand = git.commit().setMessage(helper.getCommitMessage(REPO_INITIAL_COMMIT_COMMIT_MESSAGE)).setAllowEmpty(true);
                    retryingRepositoryOperationFacade.call(commitCommand);
                }
                // Create in progress branch
                try {
                    // Create in progress branch
                    logger.debug("Create in-progress branch for site " + site);
                    CheckoutCommand checkoutCommand = git.checkout().setCreateBranch(true).setForceRefUpdate(true).setStartPoint(environment).setUpstreamMode(TRACK).setName(inProgressBranchName);
                    retryingRepositoryOperationFacade.call(checkoutCommand);
                } catch (GitAPIException e) {
                    // TODO: DB: Error ?
                    logger.error("Failed to create in-progress published branch for site " + site);
                }
                Set<String> deployedCommits = new HashSet<String>();
                Set<String> deployedPackages = new HashSet<String>();
                logger.debug("Checkout deployed files started.");
                AddCommand addCommand = git.add();
                for (DeploymentItemTO deploymentItem : deploymentItems) {
                    commitId = deploymentItem.getCommitId();
                    path = helper.getGitPath(deploymentItem.getPath());
                    if (Objects.isNull(commitId) || !commitIdExists(site, PUBLISHED, commitId)) {
                        if (contentExists(site, path)) {
                            if (Objects.isNull(commitId)) {
                                logger.warn("Commit ID is NULL for content " + path + ". Was the git repo reset at some point?");
                            } else {
                                logger.warn("Commit ID " + commitId + " does not exist for content " + path + ". Was the git repo reset at some point?");
                            }
                            logger.info("Publishing content from HEAD for " + path);
                            commitId = getRepoLastCommitId(site);
                        } else {
                            logger.warn("Skipping file " + path + " because commit id is null");
                            continue;
                        }
                    }
                    logger.debug("Checking out file " + path + " from commit id " + commitId + " for site " + site);
                    CheckoutCommand checkout = git.checkout();
                    checkout.setStartPoint(commitId).addPath(path);
                    retryingRepositoryOperationFacade.call(checkout);
                    if (deploymentItem.isMove()) {
                        if (!StringUtils.equals(deploymentItem.getPath(), deploymentItem.getOldPath())) {
                            String oldPath = helper.getGitPath(deploymentItem.getOldPath());
                            RmCommand rmCommand = git.rm().addFilepattern(oldPath).setCached(false);
                            retryingRepositoryOperationFacade.call(rmCommand);
                            cleanUpMoveFolders(git, oldPath);
                        }
                    }
                    if (deploymentItem.isDelete()) {
                        String deletePath = helper.getGitPath(deploymentItem.getPath());
                        boolean isPage = deletePath.endsWith(FILE_SEPARATOR + INDEX_FILE);
                        RmCommand rmCommand = git.rm().addFilepattern(deletePath).setCached(false);
                        retryingRepositoryOperationFacade.call(rmCommand);
                        Path parentToDelete = Paths.get(path).getParent();
                        deleteParentFolder(git, parentToDelete, isPage);
                    }
                    deployedCommits.add(commitId);
                    String packageId = deploymentItem.getPackageId();
                    if (StringUtils.isNotEmpty(packageId)) {
                        deployedPackages.add(deploymentItem.getPackageId());
                    }
                    addCommand.addFilepattern(path);
                    objectMetadataManager.updateLastPublishedDate(site, deploymentItem.getPath(), ZonedDateTime.now(UTC));
                }
                logger.debug("Checkout deployed files completed.");
                // commit all deployed files
                String commitMessage = studioConfiguration.getProperty(REPO_PUBLISHED_COMMIT_MESSAGE);
                logger.debug("Get Author Ident started.");
                User user = userServiceInternal.getUserByIdOrUsername(-1, author);
                PersonIdent authorIdent = helper.getAuthorIdent(user);
                logger.debug("Get Author Ident completed.");
                logger.debug("Git add all published items started.");
                retryingRepositoryOperationFacade.call(addCommand);
                logger.debug("Git add all published items completed.");
                commitMessage = commitMessage.replace("{username}", author);
                commitMessage = commitMessage.replace("{datetime}", ZonedDateTime.now(UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HHmmssSSSX")));
                commitMessage = commitMessage.replace("{source}", "UI");
                commitMessage = commitMessage.replace("{message}", comment);
                StringBuilder sb = new StringBuilder();
                for (String c : deployedCommits) {
                    sb.append(c).append(" ");
                }
                StringBuilder sbPackage = new StringBuilder();
                for (String p : deployedPackages) {
                    sbPackage.append(p).append(" ");
                }
                commitMessage = commitMessage.replace("{commit_id}", sb.toString().trim());
                commitMessage = commitMessage.replace("{package_id}", sbPackage.toString().trim());
                logger.debug("Git commit all published items started.");
                String prologue = studioConfiguration.getProperty(REPO_COMMIT_MESSAGE_PROLOGUE);
                String postscript = studioConfiguration.getProperty(REPO_COMMIT_MESSAGE_POSTSCRIPT);
                StringBuilder sbCommitMessage = new StringBuilder();
                if (StringUtils.isNotEmpty(prologue)) {
                    sbCommitMessage.append(prologue).append("\n\n");
                }
                sbCommitMessage.append(commitMessage);
                if (StringUtils.isNotEmpty(postscript)) {
                    sbCommitMessage.append("\n\n").append(postscript);
                }
                CommitCommand commitCommand = git.commit().setMessage(sbCommitMessage.toString()).setAuthor(authorIdent);
                RevCommit revCommit = retryingRepositoryOperationFacade.call(commitCommand);
                logger.debug("Git commit all published items completed.");
                int commitTime = revCommit.getCommitTime();
                // tag
                ZonedDateTime tagDate2 = Instant.ofEpochSecond(commitTime).atZone(UTC);
                ZonedDateTime publishDate = ZonedDateTime.now(UTC);
                String tagName2 = tagDate2.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HHmmssSSSX")) + "_published_on_" + publishDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HHmmssSSSX"));
                logger.debug("Get Author Ident started.");
                PersonIdent authorIdent2 = helper.getAuthorIdent(user);
                logger.debug("Get Author Ident completed.");
                logger.debug("Git tag started.");
                TagCommand tagCommand = git.tag().setTagger(authorIdent2).setName(tagName2).setMessage(commitMessage);
                retryingRepositoryOperationFacade.call(tagCommand);
                logger.debug("Git tag completed.");
                // checkout environment
                logger.debug("Checkout environment " + environment + " branch for site " + site);
                CheckoutCommand checkoutCommand = git.checkout().setName(environment);
                retryingRepositoryOperationFacade.call(checkoutCommand);
                Ref branchRef = repo.findRef(inProgressBranchName);
                // merge in-progress branch
                logger.debug("Merge in-progress branch into environment " + environment + " for site " + site);
                MergeCommand mergeCommand = git.merge().setCommit(true).include(branchRef);
                retryingRepositoryOperationFacade.call(mergeCommand);
                // clean up
                logger.debug("Delete in-progress branch (clean up) for site " + site);
                DeleteBranchCommand deleteBranchCommand = git.branchDelete().setBranchNames(inProgressBranchName).setForce(true);
                retryingRepositoryOperationFacade.call(deleteBranchCommand);
                git.close();
                if (repoCreated) {
                    siteService.setPublishedRepoCreated(site);
                }
            }
        }
    } catch (Exception e) {
        logger.error("Error when publishing site " + site + " to environment " + environment, e);
        throw new DeploymentException("Error when publishing site " + site + " to environment " + environment + " [commit ID = " + commitId + "]");
    } finally {
        generalLockService.unlock(gitLockKey);
    }
}
Also used : CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) User(org.craftercms.studio.api.v2.dal.User) MergeCommand(org.eclipse.jgit.api.MergeCommand) TagCommand(org.eclipse.jgit.api.TagCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException) ZonedDateTime(java.time.ZonedDateTime) ResetCommand(org.eclipse.jgit.api.ResetCommand) RmCommand(org.eclipse.jgit.api.RmCommand) CommitCommand(org.eclipse.jgit.api.CommitCommand) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) HashSet(java.util.HashSet) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Path(java.nio.file.Path) DeleteBranchCommand(org.eclipse.jgit.api.DeleteBranchCommand) PullCommand(org.eclipse.jgit.api.PullCommand) DeploymentItemTO(org.craftercms.studio.api.v1.to.DeploymentItemTO) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) IOException(java.io.IOException) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException) RemoteRepositoryNotFoundException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotFoundException) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) DeploymentException(org.craftercms.studio.api.v1.service.deployment.DeploymentException) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException) CryptoException(org.craftercms.commons.crypto.CryptoException) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) InvalidRemoteRepositoryCredentialsException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryCredentialsException) InvalidRemoteRepositoryException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v2.repository.ContentRepository) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) FetchCommand(org.eclipse.jgit.api.FetchCommand) PersonIdent(org.eclipse.jgit.lib.PersonIdent) DeploymentException(org.craftercms.studio.api.v1.service.deployment.DeploymentException) File(java.io.File) AddCommand(org.eclipse.jgit.api.AddCommand) RetryingOperation(org.craftercms.studio.api.v2.annotation.RetryingOperation)

Example 4 with PATTERN_SITE

use of org.craftercms.studio.api.v1.constant.StudioConstants.PATTERN_SITE in project studio by craftercms.

the class StudioClusterPublishedRepoSyncTask method updateContent.

protected void updateContent(long sId, String siteId, List<ClusterMember> clusterNodes, List<ClusterSiteRecord> clusterSiteRecords) throws IOException, CryptoException, ServiceLayerException {
    logger.debug("Update published repo for site " + siteId);
    Path siteSandboxPath = buildRepoPath(siteId).resolve(GIT_ROOT);
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repo = builder.setGitDir(siteSandboxPath.toFile()).readEnvironment().findGitDir().build();
    String gitLockKey = SITE_PUBLISHED_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, siteId);
    logger.debug("Git Lock Key: " + gitLockKey);
    try (Git git = new Git(repo)) {
        Set<String> environments = getAllPublishingEnvironments(siteId);
        logger.debug("Update published repo from all active cluster members");
        if (generalLockService.tryLock(gitLockKey)) {
            try {
                for (ClusterMember remoteNode : clusterNodes) {
                    ClusterSiteRecord csr = clusterDao.getClusterSiteRecord(remoteNode.getId(), sId);
                    if (Objects.nonNull(csr) && csr.getPublishedRepoCreated() > 0) {
                        try {
                            logger.debug("Fetch from cluster member " + remoteNode.getLocalAddress());
                            final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
                            FetchCommand fetch = git.fetch().setRemote(remoteNode.getGitRemoteName());
                            fetch = studioClusterUtils.configureAuthenticationForCommand(remoteNode, fetch, tempKey);
                            fetch.call();
                            Files.delete(tempKey);
                        } catch (GitAPIException e) {
                            logger.error("Error while fetching published repo for site " + siteId + " from remote " + remoteNode.getGitRemoteName());
                            logger.error(e.getMessage());
                        }
                    }
                }
                for (String branch : environments) {
                    for (ClusterMember remoteNode : clusterNodes) {
                        ClusterSiteRecord csr = clusterDao.getClusterSiteRecord(remoteNode.getId(), sId);
                        if (Objects.nonNull(csr) && csr.getPublishedRepoCreated() > 0) {
                            try {
                                updatePublishedBranch(siteId, git, remoteNode, branch);
                            } catch (GitAPIException e) {
                                logger.error("Error while updating published repo for site " + siteId + " from remote " + remoteNode.getGitRemoteName() + " environment " + branch);
                                logger.error(e.getMessage());
                            }
                        }
                    }
                }
            } finally {
                generalLockService.unlock(gitLockKey);
            }
        } else {
            logger.debug("Failed to get lock " + gitLockKey);
        }
    }
}
Also used : Path(java.nio.file.Path) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) ContentRepository(org.craftercms.studio.api.v1.repository.ContentRepository) Repository(org.eclipse.jgit.lib.Repository) ClusterMember(org.craftercms.studio.api.v2.dal.ClusterMember) Git(org.eclipse.jgit.api.Git) FetchCommand(org.eclipse.jgit.api.FetchCommand) ClusterSiteRecord(org.craftercms.studio.api.v2.dal.ClusterSiteRecord) FileRepositoryBuilder(org.eclipse.jgit.storage.file.FileRepositoryBuilder)

Example 5 with PATTERN_SITE

use of org.craftercms.studio.api.v1.constant.StudioConstants.PATTERN_SITE in project studio by craftercms.

the class GitContentRepository method createSiteCloneRemote.

@Override
public boolean createSiteCloneRemote(String siteId, String sandboxBranch, String remoteName, String remoteUrl, String remoteBranch, boolean singleBranch, String authenticationType, String remoteUsername, String remotePassword, String remoteToken, String remotePrivateKey, Map<String, String> params, boolean createAsOrphan) throws InvalidRemoteRepositoryException, InvalidRemoteRepositoryCredentialsException, RemoteRepositoryNotFoundException, ServiceLayerException {
    boolean toReturn = false;
    // clone remote git repository for site content
    logger.debug("Creating site " + siteId + " as a clone of remote repository " + remoteName + " (" + remoteUrl + ").");
    String gitLockKey = SITE_SANDBOX_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, siteId);
    generalLockService.lock(gitLockKey);
    try {
        GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
        toReturn = helper.createSiteCloneRemoteGitRepo(siteId, sandboxBranch, remoteName, remoteUrl, remoteBranch, singleBranch, authenticationType, remoteUsername, remotePassword, remoteToken, remotePrivateKey, createAsOrphan);
        if (toReturn) {
            try {
                if (createAsOrphan) {
                    removeRemote(siteId, remoteName);
                } else {
                    insertRemoteToDb(siteId, remoteName, remoteUrl, authenticationType, remoteUsername, remotePassword, remoteToken, remotePrivateKey);
                }
            } catch (CryptoException e) {
                throw new ServiceLayerException(e);
            }
            // update site name variable inside config files
            logger.debug("Update site name configuration variables for site " + siteId);
            toReturn = helper.updateSiteNameConfigVar(siteId);
            if (toReturn) {
                toReturn = helper.replaceParameters(siteId, params);
            }
            if (toReturn) {
                // commit everything so it is visible
                logger.debug("Perform initial commit for site " + siteId);
                toReturn = helper.performInitialCommit(siteId, helper.getCommitMessage(REPO_INITIAL_COMMIT_COMMIT_MESSAGE), sandboxBranch);
            }
        } else {
            logger.error("Error while creating site " + siteId + " by cloning remote repository " + remoteName + " (" + remoteUrl + ").");
        }
    } catch (CryptoException e) {
        logger.error("Error while creating site " + siteId + " by cloning remote repository " + remoteName + " (" + remoteUrl + ").", e);
    } finally {
        generalLockService.unlock(gitLockKey);
    }
    return toReturn;
}
Also used : ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) CryptoException(org.craftercms.commons.crypto.CryptoException)

Aggregations

Repository (org.eclipse.jgit.lib.Repository)25 Git (org.eclipse.jgit.api.Git)23 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)23 ContentRepository (org.craftercms.studio.api.v1.repository.ContentRepository)21 RemoteRepository (org.craftercms.studio.api.v2.dal.RemoteRepository)21 ServiceLayerException (org.craftercms.studio.api.v1.exception.ServiceLayerException)20 GitRepositoryHelper (org.craftercms.studio.api.v2.utils.GitRepositoryHelper)20 IOException (java.io.IOException)17 CryptoException (org.craftercms.commons.crypto.CryptoException)16 Path (java.nio.file.Path)14 UserNotFoundException (org.craftercms.studio.api.v1.exception.security.UserNotFoundException)12 File (java.io.File)7 CommitCommand (org.eclipse.jgit.api.CommitCommand)6 Status (org.eclipse.jgit.api.Status)6 InvalidRemoteUrlException (org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException)5 InvalidRemoteException (org.eclipse.jgit.api.errors.InvalidRemoteException)5 InvalidRemoteRepositoryCredentialsException (org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryCredentialsException)4 InvalidRemoteRepositoryException (org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException)4 RemoteRepositoryNotFoundException (org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotFoundException)4 AddCommand (org.eclipse.jgit.api.AddCommand)4