Search in sources :

Example 21 with SiteFeed

use of org.craftercms.studio.api.v1.dal.SiteFeed in project studio by craftercms.

the class SiteServiceImpl method getAllAvailableSites.

@Override
public Set<String> getAllAvailableSites() {
    List<SiteFeed> sites = siteFeedMapper.getSites();
    Set<String> toRet = new HashSet<>();
    for (SiteFeed site : sites) {
        toRet.add(site.getSiteId());
    }
    return toRet;
}
Also used : SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) HashSet(java.util.HashSet)

Example 22 with SiteFeed

use of org.craftercms.studio.api.v1.dal.SiteFeed in project studio by craftercms.

the class SiteServiceImpl method setSiteState.

@Override
public void setSiteState(String siteId, String state) {
    siteFeedMapper.setSiteState(siteId, state);
    try {
        ClusterMember clusterMember = clusterDao.getMemberByLocalAddress(studioClusterUtils.getClusterNodeLocalAddress());
        if (Objects.nonNull(clusterMember)) {
            SiteFeed siteFeed = getSite(siteId);
            clusterDao.setSiteState(clusterMember.getId(), siteFeed.getId(), state);
        }
    } catch (SiteNotFoundException e) {
        logger.error("Site not found " + siteId);
    }
}
Also used : ClusterMember(org.craftercms.studio.api.v2.dal.ClusterMember) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException)

Example 23 with SiteFeed

use of org.craftercms.studio.api.v1.dal.SiteFeed in project studio by craftercms.

the class SiteServiceImpl method createSitePushToRemote.

private void createSitePushToRemote(String siteId, String sandboxBranch, String description, String blueprintId, String remoteName, String remoteUrl, String remoteBranch, String authenticationType, String remoteUsername, String remotePassword, String remoteToken, String remotePrivateKey, Map<String, String> params, boolean createAsOrphan) throws ServiceLayerException {
    if (exists(siteId)) {
        throw new SiteAlreadyExistsException();
    }
    logger.debug("Get blueprint descriptor for " + blueprintId);
    PluginDescriptor descriptor = sitesServiceInternal.getBlueprintDescriptor(blueprintId);
    if (Objects.isNull(descriptor)) {
        throw new BlueprintNotFoundException();
    }
    logger.debug("Validate blueprint parameters");
    sitesServiceInternal.validateBlueprintParameters(descriptor, params);
    String blueprintLocation = sitesServiceInternal.getBlueprintLocation(blueprintId);
    String searchEngine = descriptor.getPlugin().getSearchEngine();
    boolean success = true;
    // We must fail site creation if any of the site creations steps fail and rollback
    // For example: Create site => create Deployer Target (fail) = fail
    // and rollback the whole thing.
    // What we need to do for site creation and the order of execution:
    // 1) deployer target, 2) git repo, 3) database, 4) kick deployer
    String siteUuid = UUID.randomUUID().toString();
    logger.info("Starting site creation process for site " + siteId + " from " + blueprintId + " blueprint.");
    // Create the site in the preview deployer
    try {
        logger.info("Creating Deployer targets for site " + siteId);
        deployer.createTargets(siteId, searchEngine);
    } catch (RestServiceException e) {
        String msg = "Error while creating site: " + siteId + " ID: " + siteId + " from blueprint: " + blueprintId + ". The required Deployer targets couldn't be created";
        logger.error(msg, e);
        throw new DeployerTargetException(msg, e);
    }
    if (success) {
        try {
            logger.info("Creating site " + siteId + " from blueprint " + blueprintId);
            success = createSiteFromBlueprintGit(blueprintLocation, siteId, siteId, sandboxBranch, description, params);
            addSiteUuidFile(siteId, siteUuid);
            // insert database records
            logger.info("Adding site record to database for site " + siteId);
            SiteFeed siteFeed = new SiteFeed();
            siteFeed.setName(siteId);
            siteFeed.setSiteId(siteId);
            siteFeed.setSiteUuid(siteUuid);
            siteFeed.setDescription(description);
            siteFeed.setPublishingStatus(READY);
            siteFeed.setPublishingStatusMessage(studioConfiguration.getProperty(JOB_DEPLOY_CONTENT_TO_ENVIRONMENT_STATUS_MESSAGE_DEFAULT));
            siteFeed.setSandboxBranch(sandboxBranch);
            siteFeed.setSearchEngine(searchEngine);
            siteFeedMapper.createSite(siteFeed);
            logger.info("Upgrading site");
            upgradeManager.upgradeSite(siteId);
        } catch (Exception e) {
            success = false;
            logger.error("Error while creating site: " + siteId + " ID: " + siteId + " from blueprint: " + blueprintId + ". Rolling back...", e);
            contentRepository.deleteSite(siteId);
            try {
                deployer.deleteTargets(siteId);
            } catch (Exception ex) {
                logger.error("Error while rolling back/deleting site: " + siteId + " ID: " + siteId + " from blueprint: " + blueprintId + ". This means the site's Deployer " + "targets are still present, but the site was not successfully created", e);
            }
            throw new SiteCreationException("Error while creating site: " + siteId + " ID: " + siteId + " from blueprint: " + blueprintId, e);
        }
        if (success) {
            ZonedDateTime now = ZonedDateTime.now();
            String creator = securityService.getCurrentUser();
            try {
                logger.info("Pushing site " + siteId + " to remote repository " + remoteName + " (" + remoteUrl + ")");
                contentRepository.addRemote(siteId, remoteName, remoteUrl, authenticationType, remoteUsername, remotePassword, remoteToken, remotePrivateKey);
                contentRepository.createSitePushToRemote(siteId, remoteName, remoteUrl, authenticationType, remoteUsername, remotePassword, remoteToken, remotePrivateKey, createAsOrphan);
            } catch (RemoteRepositoryNotFoundException | InvalidRemoteRepositoryException | InvalidRemoteRepositoryCredentialsException | RemoteRepositoryNotBareException | InvalidRemoteUrlException | ServiceLayerException e) {
                logger.error("Error while pushing site: " + siteId + " ID: " + siteId + " to remote repository " + remoteName + " (" + remoteUrl + ")", e);
                contentRepositoryV2.removeRemote(siteId, remoteName);
            }
            try {
                // Add default groups
                logger.info("Adding default groups for site " + siteId);
                addDefaultGroupsForNewSite(siteId);
                logger.debug("Adding audit logs.");
                String lastCommitId = contentRepositoryV2.getRepoLastCommitId(siteId);
                Map<String, String> createdFiles = contentRepositoryV2.getChangeSetPathsFromDelta(siteId, null, lastCommitId);
                insertCreateSiteAuditLog(siteId, siteId, createdFiles);
                insertAddRemoteAuditLog(siteId, remoteName);
                processCreatedFiles(siteId, createdFiles, creator, now, lastCommitId);
                contentRepositoryV2.insertGitLog(siteId, lastCommitId, 1, 1);
                updateLastCommitId(siteId, lastCommitId);
                updateLastVerifiedGitlogCommitId(siteId, lastCommitId);
                updateLastSyncedGitlogCommitId(siteId, lastCommitId);
                logger.info("Loading configuration for site " + siteId);
                reloadSiteConfiguration(siteId);
            } catch (Exception e) {
                success = false;
                logger.error("Error while creating site: " + siteId + " ID: " + siteId + " from blueprint: " + blueprintId + ". Rolling back.", e);
                deleteSite(siteId);
                throw new SiteCreationException("Error while creating site: " + siteId + " ID: " + siteId + " from blueprint: " + blueprintId + ". Rolling back.");
            }
        }
    }
    if (success) {
        // Now that everything is created, we can sync the preview deployer with the new content
        logger.info("Sync all content to preview for site " + siteId);
        try {
            deploymentService.syncAllContentToPreview(siteId, true);
        } catch (ServiceLayerException e) {
            logger.error("Error while syncing site: " + siteId + " ID: " + siteId + " to preview. Site was " + "successfully created otherwise. Ignoring.", e);
            throw new SiteCreationException("Error while syncing site: " + siteId + " ID: " + siteId + " to preview. Site was successfully created, but it won't be preview-able until the " + "Preview Deployer is reachable.");
        }
        setSiteState(siteId, STATE_CREATED);
    } else {
        throw new SiteCreationException("Error while creating site: " + siteId + " ID: " + siteId + ".");
    }
    logger.info("Finished creating site " + siteId);
}
Also used : BlueprintNotFoundException(org.craftercms.studio.api.v1.exception.BlueprintNotFoundException) InvalidRemoteRepositoryCredentialsException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryCredentialsException) DeployerTargetException(org.craftercms.studio.api.v1.exception.DeployerTargetException) SiteAlreadyExistsException(org.craftercms.studio.api.v1.exception.SiteAlreadyExistsException) InvalidRemoteRepositoryException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) InvalidRemoteUrlException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException) SiteConfigNotFoundException(org.craftercms.studio.api.v1.service.site.SiteConfigNotFoundException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) SiteCreationException(org.craftercms.studio.api.v1.exception.SiteCreationException) MissingPluginParameterException(org.craftercms.studio.api.v2.exception.MissingPluginParameterException) IOException(java.io.IOException) RemoteRepositoryNotFoundException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotFoundException) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) InvalidRemoteUrlException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException) DeployerTargetException(org.craftercms.studio.api.v1.exception.DeployerTargetException) RestServiceException(org.craftercms.commons.rest.RestServiceException) SiteAlreadyExistsException(org.craftercms.studio.api.v1.exception.SiteAlreadyExistsException) GroupAlreadyExistsException(org.craftercms.studio.api.v1.exception.security.GroupAlreadyExistsException) DocumentException(org.dom4j.DocumentException) EntitlementException(org.craftercms.commons.entitlements.exception.EntitlementException) BlueprintNotFoundException(org.craftercms.studio.api.v1.exception.BlueprintNotFoundException) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException) CryptoException(org.craftercms.commons.crypto.CryptoException) RemoteRepositoryNotBareException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotBareException) InvalidRemoteRepositoryCredentialsException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryCredentialsException) InvalidRemoteRepositoryException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException) RestServiceException(org.craftercms.commons.rest.RestServiceException) PluginDescriptor(org.craftercms.commons.plugin.model.PluginDescriptor) ZonedDateTime(java.time.ZonedDateTime) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) RemoteRepositoryNotFoundException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotFoundException) SiteCreationException(org.craftercms.studio.api.v1.exception.SiteCreationException) RemoteRepositoryNotBareException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotBareException)

Example 24 with SiteFeed

use of org.craftercms.studio.api.v1.dal.SiteFeed in project studio by craftercms.

the class DeploymentServiceImpl method enablePublishing.

@Override
@ValidateParams
public boolean enablePublishing(@ValidateStringParam(name = "site") String site, boolean enabled) throws SiteNotFoundException, AuthenticationException {
    if (!siteService.exists(site)) {
        throw new SiteNotFoundException();
    }
    if (!securityService.isSiteAdmin(securityService.getCurrentUser(), site)) {
        throw new AuthenticationException();
    }
    boolean toRet = siteService.enablePublishing(site, enabled);
    String message;
    String status;
    if (enabled) {
        logger.info("Publishing started for site {0}", site);
        if (publishingManager.isPublishingQueueEmpty(site)) {
            message = studioConfiguration.getProperty(JOB_DEPLOY_CONTENT_TO_ENVIRONMENT_STATUS_MESSAGE_DEFAULT);
            status = READY;
        } else {
            message = studioConfiguration.getProperty(JOB_DEPLOY_CONTENT_TO_ENVIRONMENT_STATUS_MESSAGE_QUEUED);
            status = QUEUED;
        }
    } else {
        logger.info("Publishing stopped for site {0}", site);
        message = studioConfiguration.getProperty(JOB_DEPLOY_CONTENT_TO_ENVIRONMENT_STATUS_MESSAGE_STOPPED);
        message = message.replace("{username}", securityService.getCurrentUser()).replace("{datetime}", ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern(DATE_PATTERN_WORKFLOW_WITH_TZ)));
        status = STOPPED;
    }
    siteService.updatePublishingStatusMessage(site, status, message);
    SiteFeed siteFeed = siteService.getSite(site);
    AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
    auditLog.setSiteId(siteFeed.getId());
    if (enabled) {
        auditLog.setOperation(OPERATION_START_PUBLISHER);
    } else {
        auditLog.setOperation(OPERATION_STOP_PUBLISHER);
    }
    auditLog.setActorId(securityService.getCurrentUser());
    auditLog.setPrimaryTargetId(siteFeed.getSiteId());
    auditLog.setPrimaryTargetType(TARGET_TYPE_SITE);
    auditLog.setPrimaryTargetValue(siteFeed.getName());
    auditServiceInternal.insertAuditLog(auditLog);
    return toRet;
}
Also used : AuthenticationException(org.craftercms.studio.api.v1.exception.security.AuthenticationException) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) ValidateParams(org.craftercms.commons.validation.annotations.param.ValidateParams)

Example 25 with SiteFeed

use of org.craftercms.studio.api.v1.dal.SiteFeed in project studio by craftercms.

the class WorkflowServiceImpl method reject.

@Override
@SuppressWarnings("unchecked")
@ValidateParams
public ResultTO reject(@ValidateStringParam(name = "site") String site, String request) throws ServiceLayerException {
    ResultTO result = new ResultTO();
    try {
        String approver = securityService.getCurrentUser();
        JSONObject requestObject = JSONObject.fromObject(request);
        String reason = (requestObject.containsKey(JSON_KEY_REASON)) ? requestObject.getString(JSON_KEY_REASON) : "";
        JSONArray items = requestObject.getJSONArray(JSON_KEY_ITEMS);
        String scheduledDate = null;
        if (requestObject.containsKey(JSON_KEY_SCHEDULED_DATE)) {
            scheduledDate = requestObject.getString(JSON_KEY_SCHEDULED_DATE);
        }
        int length = items.size();
        if (length > 0) {
            SimpleDateFormat format = new SimpleDateFormat(StudioConstants.DATE_PATTERN_WORKFLOW_WITH_TZ);
            List<DmDependencyTO> submittedItems = new ArrayList<DmDependencyTO>();
            for (int index = 0; index < length; index++) {
                String stringItem = items.optString(index);
                // JSONObject item = items.getJSONObject(index);
                // getSubmittedItem(site, item, format, scheduledDate);
                DmDependencyTO submittedItem = null;
                submittedItem = getSubmittedItem(site, stringItem, format, scheduledDate, null);
                submittedItems.add(submittedItem);
            }
            List<String> paths = new ArrayList<String>();
            List<AuditLogParameter> auditLogParameters = new ArrayList<AuditLogParameter>();
            for (DmDependencyTO goLiveItem : submittedItems) {
                if (contentService.contentExists(site, goLiveItem.getUri())) {
                    paths.add(goLiveItem.getUri());
                }
                AuditLogParameter auditLogParameter = new AuditLogParameter();
                auditLogParameter.setTargetId(site + ":" + goLiveItem.getUri());
                auditLogParameter.setTargetType(TARGET_TYPE_CONTENT_ITEM);
                auditLogParameter.setTargetValue(goLiveItem.getUri());
                auditLogParameters.add(auditLogParameter);
            }
            objectStateService.setSystemProcessingBulk(site, paths, true);
            Set<String> cancelPaths = new HashSet<String>();
            cancelPaths.addAll(paths);
            deploymentService.cancelWorkflowBulk(site, cancelPaths);
            reject(site, submittedItems, reason, approver);
            SiteFeed siteFeed = siteService.getSite(site);
            AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
            auditLog.setOperation(OPERATION_REJECT);
            auditLog.setActorId(approver);
            auditLog.setSiteId(siteFeed.getId());
            auditLog.setPrimaryTargetId(site);
            auditLog.setPrimaryTargetType(TARGET_TYPE_SITE);
            auditLog.setPrimaryTargetValue(site);
            auditLog.setParameters(auditLogParameters);
            auditServiceInternal.insertAuditLog(auditLog);
            objectStateService.setSystemProcessingBulk(site, paths, false);
            result.setSuccess(true);
            result.setStatus(200);
            result.setMessage(notificationService.getNotificationMessage(site, NotificationMessageType.CompleteMessages, NotificationService.COMPLETE_REJECT, Locale.ENGLISH));
        } else {
            result.setSuccess(false);
            result.setMessage("No items provided for preparation.");
        }
    } catch (JSONException | DeploymentException e) {
        result.setSuccess(false);
        result.setMessage(e.getMessage());
    }
    return result;
}
Also used : JSONArray(net.sf.json.JSONArray) ArrayList(java.util.ArrayList) JSONException(net.sf.json.JSONException) DmDependencyTO(org.craftercms.studio.api.v1.to.DmDependencyTO) ResultTO(org.craftercms.studio.api.v1.to.ResultTO) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) JSONObject(net.sf.json.JSONObject) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) DeploymentException(org.craftercms.studio.api.v1.service.deployment.DeploymentException) AuditLogParameter(org.craftercms.studio.api.v2.dal.AuditLogParameter) SimpleDateFormat(java.text.SimpleDateFormat) HashSet(java.util.HashSet) ValidateParams(org.craftercms.commons.validation.annotations.param.ValidateParams)

Aggregations

SiteFeed (org.craftercms.studio.api.v1.dal.SiteFeed)58 AuditLog (org.craftercms.studio.api.v2.dal.AuditLog)39 ServiceLayerException (org.craftercms.studio.api.v1.exception.ServiceLayerException)21 SiteNotFoundException (org.craftercms.studio.api.v1.exception.SiteNotFoundException)18 ArrayList (java.util.ArrayList)16 HashMap (java.util.HashMap)15 AuditLogParameter (org.craftercms.studio.api.v2.dal.AuditLogParameter)12 Group (org.craftercms.studio.api.v2.dal.Group)12 HasPermission (org.craftercms.commons.security.permissions.annotations.HasPermission)11 UserNotFoundException (org.craftercms.studio.api.v1.exception.security.UserNotFoundException)11 User (org.craftercms.studio.api.v2.dal.User)10 IOException (java.io.IOException)9 ClusterMember (org.craftercms.studio.api.v2.dal.ClusterMember)9 CryptoException (org.craftercms.commons.crypto.CryptoException)8 ValidateParams (org.craftercms.commons.validation.annotations.param.ValidateParams)8 EntitlementException (org.craftercms.commons.entitlements.exception.EntitlementException)6 ZonedDateTime (java.time.ZonedDateTime)5 AuthenticationSystemException (org.craftercms.studio.api.v1.exception.security.AuthenticationSystemException)5 UserAlreadyExistsException (org.craftercms.studio.api.v1.exception.security.UserAlreadyExistsException)5 SiteService (org.craftercms.studio.api.v1.service.site.SiteService)5