Package org.rhq.core.domain.content.transfer

Examples of org.rhq.core.domain.content.transfer.ResourcePackageDetails


        String version = getVersion(sha256);
        String displayVersion = getDisplayVersion(deploymentFile);

        // Package name is the deployment's file name (e.g. foo.ear).
        PackageDetailsKey key = new PackageDetailsKey(fileName, version, PKG_TYPE_FILE, ARCHITECTURE);
        ResourcePackageDetails packageDetails = new ResourcePackageDetails(key);
        packageDetails.setFileName(fileName);
        packageDetails.setLocation(deploymentFile.getPath());
        if (!deploymentFile.isDirectory())
            packageDetails.setFileSize(deploymentFile.length());
        packageDetails.setFileCreatedDate(null); // TODO: get created date via SIGAR
        packageDetails.setSHA256(sha256);
        packageDetails.setInstallationTimestamp(Long.valueOf(System.currentTimeMillis()));
        packageDetails.setDisplayVersion(displayVersion);

        Set<ResourcePackageDetails> packages = new HashSet<ResourcePackageDetails>();
        packages.add(packageDetails);

        return packages;
View Full Code Here


            DeployPackagesResponse response = new DeployPackagesResponse(ContentResponseResult.FAILURE);
            response.setOverallRequestErrorMessage("Only one " + resourceTypeName + " can be updated at a time.");
            return response;
        }

        ResourcePackageDetails packageDetails = packages.iterator().next();

        if (LOG.isDebugEnabled()) {
            LOG.debug("Updating EAR/WAR file '" + deploymentFile + "' using [" + packageDetails + "]...");
        }
        // Find location of existing application.
        if (!deploymentFile.exists()) {
            return failApplicationDeployment("Could not find application to update at location: " + deploymentFile,
                packageDetails);
        }

        LOG.debug("Writing new EAR/WAR bits to temporary file...");
        File tempFile;
        try {
            tempFile = writeNewAppBitsToTempFile(contentServices, packageDetails);
        } catch (Exception e) {
            return failApplicationDeployment("Error writing new application bits to temporary file - cause: " + e,
                packageDetails);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Wrote new EAR/WAR bits to temporary file '" + tempFile + "'.");
        }

        boolean deployExploded = deploymentFile.isDirectory();

        // Backup the original app file/dir.
        File tempDir = getResourceContext().getTemporaryDirectory();
        File backupDir = new File(tempDir, "deployBackup" + UUID.randomUUID().getLeastSignificantBits());
        File backupOfOriginalFile = new File(backupDir, deploymentFile.getName());
        if (LOG.isDebugEnabled()) {
            LOG.debug("Backing up existing EAR/WAR '" + deploymentFile + "' to '" + backupOfOriginalFile + "'...");
        }
        try {
            if (backupOfOriginalFile.exists()) {
                FileUtils.forceDelete(backupOfOriginalFile);
            }
            if (deploymentFile.isDirectory()) {
                FileUtils.copyDirectory(deploymentFile, backupOfOriginalFile, true);
            } else {
                FileUtils.copyFile(deploymentFile, backupOfOriginalFile, true);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to backup existing " + resourceTypeName + "'" + deploymentFile
                + "' to '" + backupOfOriginalFile + "'.");
        }

        ProfileServiceConnection connection = getConnection();
        if (connection == null) {
            DeployPackagesResponse response = new DeployPackagesResponse(ContentResponseResult.FAILURE);
            response.setOverallRequestErrorMessage("No profile service connection available");
            return response;
        }

        DeploymentManager deploymentManager = connection.getDeploymentManager();

        // as crazy as it might sound, there is apparently no way for you to ask the profile service
        // if a deployment was deployed to the farm profile. Thus, we must resort to a poor man's solution:
        // if the deployment name has the "farm/" directory in it, assume it needs to be deployed to the farm
        boolean deployFarmed = getDeploymentKey().contains("/farm/");
        if (deployFarmed) {
            Collection<ProfileKey> profileKeys = deploymentManager.getProfiles();
            boolean farmSupported = false;
            for (ProfileKey profileKey : profileKeys) {
                if (profileKey.getName().equals(FARM_PROFILE_KEY.getName())) {
                    farmSupported = true;
                    break;
                }
            }
            if (!farmSupported) {
                throw new IllegalStateException("This application server instance is not a node in a cluster, "
                    + "so it does not support farmed deployments. Supported deployment profiles are " + profileKeys
                    + ".");
            }
            if (deployExploded) {
                throw new IllegalArgumentException(
                    "Deploying farmed applications in exploded form is not supported by the Profile Service.");
            }
            try {
                deploymentManager.loadProfile(FARM_PROFILE_KEY);
            } catch (Exception e) {
                LOG.info("Failed to switch to farm profile - could not update " + resourceTypeName + " file '"
                    + deploymentFile + "' using [" + packageDetails + "].");
                String errorMessage = ThrowableUtil.getAllMessages(e);
                return failApplicationDeployment(errorMessage, packageDetails);
            }
        }

        String deploymentName = getDeploymentName();
        if (deploymentName == null) {
            DeployPackagesResponse response = new DeployPackagesResponse(ContentResponseResult.FAILURE);
            response.setOverallRequestErrorMessage("Did not find deployment with key [" + getDeploymentKey() + "]");
            return response;
        }

        // Now stop the original app.
        try {
            DeploymentProgress progress = deploymentManager.stop(deploymentName);
            DeploymentUtils.run(progress);
        } catch (Exception e) {
            throw new RuntimeException("Failed to stop deployment [" + deploymentName + "].", e);
        }

        // And then remove it (this will delete the physical file/dir from the deploy dir).
        try {
            DeploymentProgress progress = deploymentManager.remove(deploymentName);
            DeploymentUtils.run(progress);
        } catch (Exception e) {
            throw new RuntimeException("Failed to remove deployment [" + deploymentName + "].", e);
        }

        // Deploy away!
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Deploying '" + tempFile + "'...");
            }
            DeploymentUtils.deployArchive(deploymentManager, tempFile, deployExploded);
        } catch (Exception e) {
            // Deploy failed - rollback to the original app file...
            LOG.debug("Redeploy failed - rolling back to original archive...", e);
            String errorMessage = ThrowableUtil.getAllMessages(e);
            try {
                // Try to delete the new app file, which failed to deploy, if it still exists.
                if (deploymentFile.exists()) {
                    try {
                        FileUtils.forceDelete(deploymentFile);
                    } catch (IOException e1) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Failed to delete application file '" + deploymentFile
                                + "' that failed to deploy.", e1);
                        }
                    }
                }
                // Now redeploy the original file - this generally should succeed.
                DeploymentUtils.deployArchive(deploymentManager, backupOfOriginalFile, deployExploded);
                errorMessage += " ***** ROLLED BACK TO ORIGINAL APPLICATION FILE. *****";

                // If the redeployment of the original backup succeeded then cleanup the backup from disk
                deleteTemporaryFile(backupDir);
                // If the redeployment fails the original backup is preserved on disk until agent restart
            } catch (Exception e1) {
                LOG.debug("Rollback failed!", e1);
                errorMessage += " ***** FAILED TO ROLLBACK TO ORIGINAL APPLICATION FILE. *****: "
                    + ThrowableUtil.getAllMessages(e1);
            }

            //since the deployment failed remove the temp application downloaded for deployment
            deleteTemporaryFile(tempFile);

            LOG.info("Failed to update " + resourceTypeName + " file '" + deploymentFile + "' using [" + packageDetails
                + "].");
            return failApplicationDeployment(errorMessage, packageDetails);
        } finally {
            // Make sure to switch back to the 'applications' profile if we switched to the 'farm' profile above.
            if (deployFarmed) {
                try {
                    deploymentManager.loadProfile(APPLICATIONS_PROFILE_KEY);
                } catch (Exception e) {
                    LOG.debug("Failed to switch back to applications profile from farm profile", e);
                }
            }
        }

        // Store SHA256 in the agent file if deployment was exploded
        if (deploymentFile.isDirectory()) {
            FileContentDelegate fileContentDelegate = new FileContentDelegate();
            fileContentDelegate.saveDeploymentSHA(tempFile, deploymentFile, getResourceContext()
                .getResourceDataDirectory());
        }

        // Remove temporary files created by this deployment.
        deleteTemporaryFile(backupDir);
        deleteTemporaryFile(tempFile.getParentFile());

        DeployPackagesResponse response = new DeployPackagesResponse(ContentResponseResult.SUCCESS);
        DeployIndividualPackageResponse packageResponse = new DeployIndividualPackageResponse(packageDetails.getKey(),
            ContentResponseResult.SUCCESS);
        response.addPackageResponse(packageResponse);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Updated " + resourceTypeName + " file '" + deploymentFile
View Full Code Here

     * @param report Create resource report that tells us what to do
     * @return report that tells us what has been done.
     */
    protected CreateResourceReport deployContent(CreateResourceReport report) {
        ContentContext cctx = context.getContentContext();
        ResourcePackageDetails details = report.getPackageDetails();

        ContentServices contentServices = cctx.getContentServices();
        String resourceTypeName = report.getResourceType().getName();

        ASUploadConnection uploadConnection = new ASUploadConnection(getServerComponent().getASConnection(), details
            .getKey().getName());

        OutputStream out = uploadConnection.getOutputStream();
        if (out == null) {
            report.setStatus(CreateResourceStatus.FAILURE);
            report.setErrorMessage("An error occured while the agent was preparing for content download");
            return report;
        }

        long size;
        try {
            size = contentServices.downloadPackageBitsForChildResource(cctx, resourceTypeName, details.getKey(), out);
        } catch (Exception e) {
            uploadConnection.cancelUpload();
            report.setStatus(CreateResourceStatus.FAILURE);
            LOG.debug("Failed to pull package from server", e);
            report.setErrorMessage("An error occured while the agent was uploading the content for ["
                + details.getKey() + "]");
            return report;
        }

        if (0L == size) {
            uploadConnection.cancelUpload();
            report.setStatus(CreateResourceStatus.FAILURE);
            report.setErrorMessage("An error occured (0 bytes) while the agent was uploading the content for ["
                + details.getKey() + "]");
            return report;

        }

        JsonNode uploadResult = uploadConnection.finishUpload();
        if (verbose) {
            LOG.info(uploadResult);
        }

        if (ASUploadConnection.isErrorReply(uploadResult)) {
            report.setStatus(CreateResourceStatus.FAILURE);
            report.setErrorMessage(ASUploadConnection.getFailureDescription(uploadResult));
            return report;
        }

        // Key is available from UI and CLI
        String fileName = details.getKey().getName();

        String runtimeName = report.getPackageDetails().getDeploymentTimeConfiguration().getSimpleValue("runtimeName");
        if (runtimeName == null || runtimeName.isEmpty()) {
            runtimeName = fileName;
        }
View Full Code Here

                    sha256 = new MessageDigestGenerator(MessageDigestGenerator.SHA_256).calcDigestString(file);
                } catch (Exception e) {
                    // leave as null
                }

                ResourcePackageDetails details = new ResourcePackageDetails(new PackageDetailsKey(file.getName(),
                    getVersion(sha256), getPackageTypeName(), "noarch"));

                packages.add(details);
                details.setFileCreatedDate(file.lastModified()); // Why don't we have a last modified time?
                details.setFileName(file.getName());
                details.setFileSize(file.length());
                details.setClassification(MIME_TYPE_JAR);
                details.setSHA256(sha256);
                details.setDisplayVersion(getDisplayVersion(file));

                details.setExtraProperties(config);
            } catch (IOException e) {
                // If we can't open it, don't worry about it, we just won't know the version
            } finally {
                try {
                    if (jf != null)
View Full Code Here

            response.setOverallRequestResult(ContentResponseResult.FAILURE);
            response.setOverallRequestErrorMessage("Can only deploy one package at a time");
            getLog().warn("deployPackages can only deploy one package at a time");
        }

        ResourcePackageDetails detail = packages.iterator().next();

        ASUploadConnection uploadConnection = new ASUploadConnection(getServerComponent().getASConnection(), detail
            .getKey().getName());
        OutputStream out = uploadConnection.getOutputStream();
        if (out == null) {
            response.setOverallRequestResult(ContentResponseResult.FAILURE);
            response
                .setOverallRequestErrorMessage("An error occured while the agent was preparing for content download");
            return response;
        }
        ResourceType resourceType = context.getResourceType();

        getLog().info("Deploying " + resourceType.getName() + " Resource with key [" + detail.getKey() + "]...");

        try {
            contentServices.downloadPackageBits(context.getContentContext(), detail.getKey(), out, true);
        } catch (Exception e) {
            uploadConnection.cancelUpload();
            response.setOverallRequestResult(ContentResponseResult.FAILURE);
            response.setOverallRequestErrorMessage("An error occured while the agent was downloading the content");
            return response;
        }

        JsonNode uploadResult = uploadConnection.finishUpload();
        if (verbose) {
            getLog().info(uploadResult);
        }

        if (ASUploadConnection.isErrorReply(uploadResult)) {
            response.setOverallRequestResult(ContentResponseResult.FAILURE);
            response.setOverallRequestErrorMessage(ASUploadConnection.getFailureDescription(uploadResult));
            return response;
        }

        JsonNode resultNode = uploadResult.get("result");
        String hash = resultNode.get("BYTES_VALUE").getTextValue();

        try {
            Redeployer redeployer = new Redeployer(detail.getKey().getName(), hash, getASConnection());
            Result result = redeployer.redeployOnServer();
            if (result.isRolledBack()) {
                response.setOverallRequestResult(ContentResponseResult.FAILURE);
                response.setOverallRequestErrorMessage("Rolled Back: " + result.getFailureDescription());
            } else {
                response.setOverallRequestResult(ContentResponseResult.SUCCESS);
                //we just deployed a different file on the AS7 server, so let's refresh ourselves
                deploymentFile = determineDeploymentFile();
                DeployIndividualPackageResponse packageResponse = new DeployIndividualPackageResponse(detail.getKey(),
                    ContentResponseResult.SUCCESS);
                response.addPackageResponse(packageResponse);
            }

        } catch (Exception e) {
            response.setOverallRequestResult(ContentResponseResult.FAILURE);
            response.setOverallRequestErrorMessage(e.getMessage());
        }

        ContentResponseResult result = response.getOverallRequestResult();
        getLog().info(
            "Result of deployment of "
                + resourceType.getName()
                + " Resource with key ["
                + detail.getKey()
                + "]: "
                + ((ContentResponseResult.SUCCESS == result) ? result.name() : (result.name() + ": " + response
                    .getOverallRequestErrorMessage())));

        return response;
View Full Code Here

        String name = getDeploymentName();
        String sha256 = getSHA256(deploymentFile);
        String version = getVersion(sha256);

        PackageDetailsKey key = new PackageDetailsKey(name, version, type.getName(), "noarch");
        ResourcePackageDetails details = new ResourcePackageDetails(key);

        details.setDisplayVersion(getDisplayVersion(deploymentFile));
        details.setFileCreatedDate(null); //TODO figure this out from Sigar somehow?
        details.setFileName(name);
        details.setFileSize(deploymentFile.length());
        details.setInstallationTimestamp(deploymentFile.lastModified());
        details.setLocation(deploymentFile.getAbsolutePath());
        details.setSHA256(sha256);

        return Collections.singleton(details);
    }
View Full Code Here

        }
        return report;
    }

    private void warCreate(CreateResourceReport report) throws Exception {
        ResourcePackageDetails details = report.getPackageDetails();
        PackageDetailsKey key = details.getKey();
        String archiveName = key.getName();

        // Validate file name
        if (!archiveName.toLowerCase().endsWith(".war")) {
            CreateResourceHelper.setErrorOnReport(report, "Deployed file must have a .war extension");
            return;
        }

        // validate explode option
        Configuration deployTimeConfiguration = details.getDeploymentTimeConfiguration();

        if (null == deployTimeConfiguration) {
            CreateResourceHelper.setErrorOnReport(report,
                "Explode On Deploy property is required. Deploy configuration missing.");
            return;
View Full Code Here

    public JBossASServerOperationsDelegate getOperationsDelegate() {
        return operationsDelegate;
    }

    private void earWarCreate(CreateResourceReport report, String resourceTypeName) throws Exception {
        ResourcePackageDetails details = report.getPackageDetails();
        PackageDetailsKey key = details.getKey();
        String archiveName = key.getName();

        // First check to see if the file name has the correct extension. Reject if the user attempts to
        // deploy a WAR file with a bad extension.
        String expectedExtension = resourceTypeName.equals(RESOURCE_TYPE_EAR) ? "ear" : "war";

        int lastPeriod = archiveName.lastIndexOf(".");
        String extension = archiveName.substring(lastPeriod + 1);
        if (lastPeriod == -1 || !expectedExtension.equals(extension)) {
            setErrorOnCreateResourceReport(report, "Incorrect extension specified on filename [" + archiveName
                + "]. Expected [" + expectedExtension + "]");
            return;
        }

        Configuration deployTimeConfiguration = details.getDeploymentTimeConfiguration();
        String deployDirectory = deployTimeConfiguration.getSimple("deployDirectory").getStringValue();
        if (deployDirectory == null) {
            // should not be null, but you never know ..
            setErrorOnCreateResourceReport(report, "Property 'deployDirectory' was unexpectedly null");
            return;
        }

        // Verify the user did not enter a path that represents a security issue:
        // - No absolute directories; must be relative to the configuration path
        // - Cannot contain parent directory references
        File relativeDeployDir = new File(deployDirectory);

        if (relativeDeployDir.isAbsolute()) {
            setErrorOnCreateResourceReport(report, "Path to deploy (deployDirectory) must be a relative path. "
                + "Path specified: " + deployDirectory);
            return;
        }

        if (deployDirectory.contains("..")) {
            setErrorOnCreateResourceReport(report,
                "Path to deploy (deployDirectory) may not reference the parent directory. " + "Path specified: "
                    + deployDirectory);
            return;
        }

        boolean createBackup = false;
        PropertySimple backupProperty = deployTimeConfiguration.getSimple("createBackup");
        if (backupProperty != null && backupProperty.getBooleanValue() != null && backupProperty.getBooleanValue())
            createBackup = true;

        // Perform the deployment
        File deployDir = new File(getConfigurationPath(), deployDirectory);
        FileContentDelegate deployer = new FileContentDelegate(deployDir, "", details.getPackageTypeName());

        File path = deployer.getPath(details);
        if (!createBackup && path.exists()) {
            setErrorOnCreateResourceReport(report, "A " + resourceTypeName + " file named " + path.getName()
                + " is already deployed with path " + path + ".");
View Full Code Here

        Set<ResourcePackageDetails> result = objectUnderTest.discoverDeployedPackages(mockPackageType);

        //verify the results (Assert and mock verification)
        Assert.assertEquals(result.size(), 1);

        ResourcePackageDetails resultPackageDetails = (ResourcePackageDetails) result.toArray()[0];

        Assert.assertEquals(resultPackageDetails.getSHA256(), "abcd1234");
        Assert.assertEquals(resultPackageDetails.getVersion(), "[sha256=abcd1234]");

        verify(mockFileContentDelegate).saveDeploymentSHA(any(File.class), any(File.class), any(File.class));
    }
View Full Code Here

        ResourceContext mockResourceContext = mock(ResourceContext.class);
        when(mockResourceContext.getTemporaryDirectory()).thenReturn(mockResourceTemporaryDir);

        ContentServices mockContentServices = mock(ContentServices.class);
        ResourcePackageDetails mockResourcePackageDetails = mock(ResourcePackageDetails.class);

        File mockTempDir = mock(File.class);
        File mockTempFile = mock(File.class);
        when(mockTempFile.exists()).thenReturn(true);
View Full Code Here

TOP

Related Classes of org.rhq.core.domain.content.transfer.ResourcePackageDetails

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.