Search in sources :

Example 6 with InvalidRemoteRepositoryException

use of org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException in project studio by craftercms.

the class GitRepositoryHelper method createSiteCloneRemoteGitRepo.

public boolean createSiteCloneRemoteGitRepo(String siteId, String sandboxBranch, String remoteName, String remoteUrl, String remoteBranch, boolean singleBranch, String authenticationType, String remoteUsername, String remotePassword, String remoteToken, String remotePrivateKey, boolean createAsOrphan) throws InvalidRemoteRepositoryException, InvalidRemoteRepositoryCredentialsException, RemoteRepositoryNotFoundException, ServiceLayerException {
    boolean toRet = true;
    // prepare a new folder for the cloned repository
    Path siteSandboxPath = buildRepoPath(SANDBOX, siteId);
    File localPath = siteSandboxPath.toFile();
    localPath.delete();
    logger.debug("Add user credentials if provided");
    // then clone
    logger.debug("Cloning from " + remoteUrl + " to " + localPath);
    CloneCommand cloneCommand = Git.cloneRepository();
    Git cloneResult = null;
    String gitLockKey = SITE_SANDBOX_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, siteId);
    generalLockService.lock(gitLockKey);
    try {
        final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
        switch(authenticationType) {
            case RemoteRepository.AuthenticationType.NONE:
                logger.debug("No authentication");
                break;
            case RemoteRepository.AuthenticationType.BASIC:
                logger.debug("Basic authentication");
                cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(remoteUsername, remotePassword));
                break;
            case RemoteRepository.AuthenticationType.TOKEN:
                logger.debug("Token based authentication");
                cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(remoteToken, StringUtils.EMPTY));
                break;
            case RemoteRepository.AuthenticationType.PRIVATE_KEY:
                logger.debug("Private key authentication");
                tempKey.toFile().deleteOnExit();
                cloneCommand.setTransportConfigCallback(new TransportConfigCallback() {

                    @Override
                    public void configure(Transport transport) {
                        SshTransport sshTransport = (SshTransport) transport;
                        sshTransport.setSshSessionFactory(getSshSessionFactory(remotePrivateKey, tempKey));
                    }
                });
                break;
            default:
                throw new ServiceLayerException("Unsupported authentication type " + authenticationType);
        }
        if (StringUtils.isNotEmpty(remoteBranch)) {
            cloneCommand.setBranch(remoteBranch);
        }
        cloneResult = cloneCommand.setURI(remoteUrl).setDirectory(localPath).setRemote(remoteName).setCloneAllBranches(!singleBranch).call();
        Files.deleteIfExists(tempKey);
        Repository sandboxRepo = checkIfCloneWasOk(cloneResult, remoteName, remoteUrl);
        sandboxRepo = optimizeRepository(sandboxRepo);
        // Make repository orphan if needed
        if (createAsOrphan) {
            makeRepoOrphan(sandboxRepo, siteId);
        }
        sandboxes.put(siteId, sandboxRepo);
    } catch (InvalidRemoteException e) {
        logger.error("Invalid remote repository: " + remoteName + " (" + remoteUrl + ")", e);
        throw new InvalidRemoteRepositoryException("Invalid remote repository: " + remoteName + " (" + remoteUrl + ")");
    } catch (TransportException e) {
        if (StringUtils.endsWithIgnoreCase(e.getMessage(), "not authorized")) {
            logger.error("Bad credentials or read only repository: " + remoteName + " (" + remoteUrl + ")", e);
            throw new InvalidRemoteRepositoryCredentialsException("Bad credentials or read only repository: " + remoteName + " (" + remoteUrl + ") for username " + remoteUsername, e);
        } else {
            logger.error("Remote repository not found: " + remoteName + " (" + remoteUrl + ")", e);
            throw new RemoteRepositoryNotFoundException("Remote repository not found: " + remoteName + " (" + remoteUrl + ")");
        }
    } catch (GitAPIException | IOException | UserNotFoundException e) {
        logger.error("Error while creating repository for site with path" + siteSandboxPath.toString(), e);
        toRet = false;
    } finally {
        generalLockService.unlock(gitLockKey);
        if (cloneResult != null) {
            cloneResult.close();
        }
    }
    return toRet;
}
Also used : Path(java.nio.file.Path) CloneCommand(org.eclipse.jgit.api.CloneCommand) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) InvalidRemoteRepositoryCredentialsException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryCredentialsException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) InvalidRemoteRepositoryException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException) IOException(java.io.IOException) TransportException(org.eclipse.jgit.api.errors.TransportException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) Git(org.eclipse.jgit.api.Git) TransportConfigCallback(org.eclipse.jgit.api.TransportConfigCallback) RemoteRepositoryNotFoundException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotFoundException) InvalidRemoteException(org.eclipse.jgit.api.errors.InvalidRemoteException) SshTransport(org.eclipse.jgit.transport.SshTransport) Transport(org.eclipse.jgit.transport.Transport) File(java.io.File) SshTransport(org.eclipse.jgit.transport.SshTransport)

Example 7 with InvalidRemoteRepositoryException

use of org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException in project studio by craftercms.

the class GitRepositoryHelper method checkIfCloneWasOk.

/**
 * Checks if the clone was executed ok (mostly check for null references and
 * if the clone folder was created as a folder and current user has RW permissions.
 * <b> Never returns null</b>
 * @param cloneResult Clone Result to check.
 * @param remoteName Name of the remote we clone.
 * @param remoteUrl Clone URL
 * @return A {@link Repository} if all checks pass , never returns null.
 * @throws InvalidRemoteRepositoryException If a check does not pass.
 */
private Repository checkIfCloneWasOk(Git cloneResult, String remoteName, String remoteUrl) throws InvalidRemoteRepositoryException {
    // Check if cloneResult is null , if so die.
    if (cloneResult == null) {
        String msg = "Remote Clone Error:: " + remoteName + " (" + remoteUrl + ")  cloneResult object null";
        logger.error(msg);
        throw new InvalidRemoteRepositoryException(msg);
    }
    Repository repository = cloneResult.getRepository();
    // Check if cloneResult is null , if so die.
    if (repository == null) {
        String msg = "Remote Clone Error:: " + remoteName + " (" + remoteUrl + ")  sandboxRepo object null";
        logger.error(msg);
        throw new InvalidRemoteRepositoryException(msg);
    }
    File repoDir = repository.getDirectory();
    // Check if  sandbox repo,: exists, is a dir, we can RW to it.
    if (!repoDir.exists() || !repoDir.isDirectory() || !repoDir.canRead() || !repoDir.canWrite()) {
        String msg = "Remote Clone Error::  " + repository.getDirectory() + " doesn't exist, is not a dir or user" + " don't have RW permissions";
        logger.error(msg);
        throw new InvalidRemoteRepositoryException(msg);
    }
    return repository;
}
Also used : RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) InvalidRemoteRepositoryException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException) File(java.io.File)

Aggregations

ServiceLayerException (org.craftercms.studio.api.v1.exception.ServiceLayerException)5 InvalidRemoteRepositoryException (org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException)5 IOException (java.io.IOException)4 CryptoException (org.craftercms.commons.crypto.CryptoException)4 InvalidRemoteRepositoryCredentialsException (org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryCredentialsException)4 RemoteRepositoryNotFoundException (org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotFoundException)4 EntitlementException (org.craftercms.commons.entitlements.exception.EntitlementException)3 SiteAlreadyExistsException (org.craftercms.studio.api.v1.exception.SiteAlreadyExistsException)3 SiteCreationException (org.craftercms.studio.api.v1.exception.SiteCreationException)3 RemoteRepositoryNotBareException (org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotBareException)3 UserNotFoundException (org.craftercms.studio.api.v1.exception.security.UserNotFoundException)3 RemoteRepository (org.craftercms.studio.api.v2.dal.RemoteRepository)3 Repository (org.eclipse.jgit.lib.Repository)3 File (java.io.File)2 Path (java.nio.file.Path)2 ZonedDateTime (java.time.ZonedDateTime)2 PluginDescriptor (org.craftercms.commons.plugin.model.PluginDescriptor)2 RestServiceException (org.craftercms.commons.rest.RestServiceException)2 SiteFeed (org.craftercms.studio.api.v1.dal.SiteFeed)2 BlueprintNotFoundException (org.craftercms.studio.api.v1.exception.BlueprintNotFoundException)2