Search in sources :

Example 31 with Element

use of org.jvnet.hk2.config.Element in project Payara by payara.

the class InstanceDeployCommand method execute.

@Override
public void execute(AdminCommandContext ctxt) {
    long operationStartTime = Calendar.getInstance().getTimeInMillis();
    final ActionReport report = ctxt.getActionReport();
    final Logger logger = ctxt.getLogger();
    ReadableArchive archive = null;
    this.origin = Origin.deploy_instance;
    this.command = Command._deploy;
    this.previousContextRoot = preservedcontextroot;
    if (previousVirtualServers != null) {
        String vs = previousVirtualServers.getProperty(target);
        if (vs != null) {
            this.virtualservers = vs;
        }
    }
    if (previousEnabledAttributes != null) {
        String enabledAttr = previousEnabledAttributes.getProperty(target);
        if (enabledAttr != null) {
            String enabledAttrForApp = previousEnabledAttributes.getProperty(DeploymentUtils.DOMAIN_TARGET_NAME);
            this.enabled = Boolean.valueOf(enabledAttr) && Boolean.valueOf(enabledAttrForApp);
        }
    }
    try {
        if (!path.exists()) {
            report.setMessage(localStrings.getLocalString("fnf", "File not found", path.getAbsolutePath()));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
        if (snifferManager.hasNoSniffers()) {
            String msg = localStrings.getLocalString("nocontainer", "No container services registered, done...");
            report.failure(logger, msg);
            return;
        }
        archive = archiveFactory.openArchive(path, this);
        ArchiveHandler archiveHandler = deployment.getArchiveHandler(archive, type);
        if (archiveHandler == null) {
            report.failure(logger, localStrings.getLocalString("deploy.unknownarchivetype", "Archive type of {0} was not recognized", path.getName()));
            return;
        }
        // wait until all applications are loaded as we may have dependency on these, or the previous app is still
        // starting
        startupProvider.get();
        // clean up any left over repository files
        if (!keepreposdir.booleanValue()) {
            FileUtils.whack(new File(env.getApplicationRepositoryPath(), VersioningUtils.getRepositoryName(name)));
        }
        ExtendedDeploymentContext deploymentContext = deployment.getBuilder(logger, this, report).source(archive).build();
        // clean up any remaining generated files
        deploymentContext.clean();
        deploymentContext.getAppProps().putAll(appprops);
        processGeneratedContent(generatedcontent, deploymentContext, logger);
        Transaction t = null;
        Application application = applications.getApplication(name);
        if (application != null) {
            // application element already been synchronized over
            t = new Transaction();
        } else {
            t = deployment.prepareAppConfigChanges(deploymentContext);
        }
        ApplicationInfo appInfo;
        appInfo = deployment.deploy(deploymentContext);
        if (report.getActionExitCode() == ActionReport.ExitCode.SUCCESS) {
            try {
                moveAltDDFilesToPermanentLocation(deploymentContext, logger);
                // register application information in domain.xml
                if (application != null) {
                    // application element already synchronized over
                    // just write application-ref
                    deployment.registerAppInDomainXML(appInfo, deploymentContext, t, true);
                } else {
                    // write both application and application-ref
                    deployment.registerAppInDomainXML(appInfo, deploymentContext, t);
                }
            } catch (Exception e) {
                // roll back the deployment and re-throw the exception
                deployment.undeploy(name, deploymentContext);
                deploymentContext.clean();
                throw e;
            }
        }
    } catch (Throwable e) {
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage(e.getMessage());
        report.setFailureCause(e);
    } finally {
        try {
            if (archive != null) {
                archive.close();
            }
        } catch (IOException e) {
            logger.log(Level.INFO, localStrings.getLocalString("errClosingArtifact", "Error while closing deployable artifact : ", path.getAbsolutePath()), e);
        }
        if (report.getActionExitCode().equals(ActionReport.ExitCode.SUCCESS)) {
            logger.info(localStrings.getLocalString("deploy.done", "Deployment of {0} done is {1} ms", name, (Calendar.getInstance().getTimeInMillis() - operationStartTime)));
        } else if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
            String errorMessage = report.getMessage();
            Throwable cause = report.getFailureCause();
            if (cause != null) {
                String causeMessage = cause.getMessage();
                if (causeMessage != null && !causeMessage.equals(errorMessage)) {
                    errorMessage = errorMessage + " : " + cause.getMessage();
                }
                logger.log(Level.SEVERE, errorMessage, cause.getCause());
            }
            report.setMessage(localStrings.getLocalString("failToLoadOnInstance", "Failed to load the application on instance {0} : {1}", server.getName(), errorMessage));
            // reset the failure cause so command framework will not try
            // to print the same message again
            report.setFailureCause(null);
        }
    }
}
Also used : ArchiveHandler(org.glassfish.api.deployment.archive.ArchiveHandler) ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) IOException(java.io.IOException) ActionReport(org.glassfish.api.ActionReport) Logger(java.util.logging.Logger) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) IOException(java.io.IOException) Transaction(org.jvnet.hk2.config.Transaction) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) ZipFile(java.util.zip.ZipFile) File(java.io.File) Application(com.sun.enterprise.config.serverbeans.Application)

Example 32 with Element

use of org.jvnet.hk2.config.Element in project Payara by payara.

the class InstanceLifecycleModuleCommand method execute.

@Override
public void execute(AdminCommandContext context) {
    final ActionReport report = context.getActionReport();
    final Logger logger = context.getLogger();
    try {
        Application application = applications.getApplication(name);
        Transaction t = new Transaction();
        // create a dummy context to hold params and props
        DeployCommandParameters commandParams = new DeployCommandParameters();
        commandParams.name = name;
        commandParams.target = target;
        commandParams.enabled = enabled;
        commandParams.virtualservers = virtualservers;
        ExtendedDeploymentContext lifecycleContext = new DeploymentContextImpl(report, null, commandParams, null);
        lifecycleContext.getAppProps().putAll(appprops);
        if (application != null) {
            // application element already been synchronized over
            // just write application-ref
            deployment.registerAppInDomainXML(null, lifecycleContext, t, true);
        } else {
            // write both
            t = deployment.prepareAppConfigChanges(lifecycleContext);
            deployment.registerAppInDomainXML(null, lifecycleContext, t);
        }
    } catch (Exception e) {
        report.failure(logger, e.getMessage());
    }
}
Also used : DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) Transaction(org.jvnet.hk2.config.Transaction) ActionReport(org.glassfish.api.ActionReport) Logger(java.util.logging.Logger) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) Application(com.sun.enterprise.config.serverbeans.Application) DeploymentContextImpl(org.glassfish.deployment.common.DeploymentContextImpl)

Example 33 with Element

use of org.jvnet.hk2.config.Element in project Payara by payara.

the class UndeployCommand method execute.

@Override
public void execute(AdminCommandContext context) {
    // for each matched version
    for (String appName : matchedVersions) {
        if (target == null) {
            target = deployment.getDefaultTarget(appName, origin, _classicstyle);
        }
        ApplicationInfo info = deployment.get(appName);
        Application application = apps.getModule(Application.class, appName);
        if (application == null) {
            report.setMessage(localStrings.getLocalString("application.notreg", "Application {0} not registered", appName));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
        deployment.validateUndeploymentTarget(target, appName);
        if (!DeploymentUtils.isDomainTarget(target)) {
            ApplicationRef ref = domain.getApplicationRefInTarget(appName, target);
            if (ref == null) {
                report.setMessage(localStrings.getLocalString("ref.not.referenced.target", "Application {0} is not referenced by target {1}", appName, target));
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                return;
            }
        }
        ReadableArchive source = null;
        if (info == null) {
            // disabled application or application failed to be
            // loaded for some reason
            URI uri = null;
            try {
                uri = new URI(application.getLocation());
            } catch (URISyntaxException e) {
                logger.severe("Cannot determine original location for application : " + e.getMessage());
            }
            if (uri != null) {
                File location = new File(uri);
                if (location.exists()) {
                    try {
                        source = archiveFactory.openArchive(location);
                    } catch (IOException e) {
                        logger.log(Level.INFO, e.getMessage(), e);
                    }
                } else {
                    logger.warning("Originally deployed application at " + location + " not found");
                }
            }
        } else {
            source = info.getSource();
        }
        if (source == null) {
            logger.fine("Cannot get source archive for undeployment");
            // server is in a consistent state after restart
            try {
                deployment.unregisterAppFromDomainXML(appName, target);
            } catch (TransactionFailure e) {
                logger.warning("Module " + appName + " not found in configuration");
            }
            // also remove application from runtime registry
            if (info != null) {
                appRegistry.remove(appName);
            }
            return;
        }
        File sourceFile = new File(source.getURI());
        if (!source.exists()) {
            logger.log(Level.WARNING, "Cannot find application bits at " + sourceFile.getPath() + ". Please restart server to ensure server is in a consistent state before redeploy the application.");
            // server is in a consistent state after restart
            try {
                deployment.unregisterAppFromDomainXML(appName, target);
            } catch (TransactionFailure e) {
                logger.warning("Module " + appName + " not found in configuration");
            }
            // also remove application from runtime registry
            if (info != null) {
                appRegistry.remove(appName);
            }
            return;
        }
        // now start the normal undeploying
        this.name = appName;
        this._type = application.archiveType();
        ExtendedDeploymentContext deploymentContext = null;
        try {
            deploymentContext = deployment.getBuilder(logger, this, report).source(source).build();
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Cannot create context for undeployment ", e);
            report.setMessage(localStrings.getLocalString("undeploy.contextcreation.failed", "Cannot create context for undeployment : {0} ", e.getMessage()));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
        final InterceptorNotifier notifier = new InterceptorNotifier(habitat, deploymentContext);
        final DeployCommandSupplementalInfo suppInfo = new DeployCommandSupplementalInfo();
        suppInfo.setDeploymentContext(deploymentContext);
        report.setResultType(DeployCommandSupplementalInfo.class, suppInfo);
        final Properties appProps = deploymentContext.getAppProps();
        appProps.putAll(application.getDeployProperties());
        if (properties != null) {
            appProps.putAll(properties);
        }
        deploymentContext.setModulePropsMap(application.getModulePropertiesMap());
        events.send(new Event<DeploymentContext>(Deployment.UNDEPLOYMENT_VALIDATION, deploymentContext), false);
        if (report.getActionExitCode() == ActionReport.ExitCode.FAILURE) {
            // status as failure, return
            return;
        }
        // disable the application first for non-DAS target
        if (env.isDas() && !DeploymentUtils.isDASTarget(target)) {
            ActionReport subReport = report.addSubActionsReport();
            CommandRunner.CommandInvocation inv = commandRunner.getCommandInvocation("disable", subReport, context.getSubject());
            try {
                final ParameterMapExtractor extractor = new ParameterMapExtractor(this);
                final ParameterMap parameters = extractor.extract(Collections.EMPTY_LIST);
                parameters.set("DEFAULT", appName);
                parameters.add(DeploymentProperties.IS_UNDEPLOY, Boolean.TRUE.toString());
                inv.parameters(parameters).execute();
                if (subReport.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
                    // if disable application failed
                    // we should just return
                    report.setMessage(localStrings.getLocalString("disable.command.failed", "{0} disabled failed", appName));
                    return;
                }
                if (DeploymentUtils.isDomainTarget(target)) {
                    List<String> targets = domain.getAllReferencedTargetsForApplication(appName);
                    // replicate command to all referenced targets
                    parameters.remove("isUndeploy");
                    notifier.ensureBeforeReported(ExtendedDeploymentContext.Phase.REPLICATION);
                    ClusterOperationUtil.replicateCommand("undeploy", FailurePolicy.Error, FailurePolicy.Warn, FailurePolicy.Ignore, targets, context, parameters, habitat);
                }
            } catch (Exception e) {
                report.failure(logger, e.getMessage());
                return;
            }
        }
        /*
             * Extract the generated artifacts from the application's properties
             * and record them in the DC.  This will be useful, for example,
             * during Deployer.clean.
             */
        final Artifacts generatedArtifacts = DeploymentUtils.generatedArtifacts(application);
        generatedArtifacts.record(deploymentContext);
        if (info != null) {
            deployment.undeploy(appName, deploymentContext);
        }
        // check if it's directory deployment
        boolean isDirectoryDeployed = Boolean.valueOf(application.getDirectoryDeployed());
        // and warning case
        if (!report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
            // so far I am doing this after the unload, maybe this should be moved before...
            try {
                // remove the "application" element
                deployment.unregisterAppFromDomainXML(appName, target);
            } catch (TransactionFailure e) {
                logger.warning("Module " + appName + " not found in configuration");
            }
            // remove context from generated
            deploymentContext.clean();
            // free file descriptors
            try {
                Class clazz = Class.forName("sun.net.www.protocol.jar.JarFileFactory", true, URL.class.getClassLoader());
                Field[] fields = clazz.getDeclaredFields();
                for (Field field : fields) {
                    if ("fileCache".equals(field.getName())) {
                        field.setAccessible(true);
                        HashMap<String, JarFile> files = (HashMap<String, JarFile>) field.get(null);
                        Set<JarFile> jars = new HashSet<>();
                        jars.addAll(files.values());
                        for (JarFile file : jars) {
                            file.close();
                        }
                    }
                }
            } catch (ClassNotFoundException | IllegalAccessException | SecurityException | IllegalArgumentException ex) {
                logger.log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
            }
            // perform full GC after cleaning to ensure full clean up
            System.gc();
            // if directory deployment then do not remove the directory
            if ((!keepreposdir) && !isDirectoryDeployed && source.exists()) {
                /*
                     * Delete the repository directory as an archive so
                     * any special handling (such as stale file handling)
                     * known to the archive can run.
                     */
                source.delete();
            }
        }
    // else a message should have been provided.
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) HashMap(java.util.HashMap) ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) URISyntaxException(java.net.URISyntaxException) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) DeploymentProperties(org.glassfish.deployment.common.DeploymentProperties) Properties(java.util.Properties) ActionReport(org.glassfish.api.ActionReport) URI(java.net.URI) URL(java.net.URL) Field(java.lang.reflect.Field) ParameterMapExtractor(org.glassfish.common.util.admin.ParameterMapExtractor) CommandRunner(org.glassfish.api.admin.CommandRunner) HashSet(java.util.HashSet) ParameterMap(org.glassfish.api.admin.ParameterMap) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) URISyntaxException(java.net.URISyntaxException) VersioningException(org.glassfish.deployment.versioning.VersioningException) IOException(java.io.IOException) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) Artifacts(org.glassfish.deployment.common.Artifacts) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 34 with Element

use of org.jvnet.hk2.config.Element in project Payara by payara.

the class SecurityConfigUpgradeService method postConstruct.

@Override
public void postConstruct() {
    if (domain.getExtensionByType(SecurityConfigurations.class) != null) {
        /*
             * The domain already contains a security-configurations setting,
             * so for now that's sufficient to conclude we don't need to upgrade.
             */
        logger.log(Level.INFO, "SecurityConfigUpgradeService bypassing - security-configurations already present");
        return;
    }
    Transaction t = null;
    try {
        t = new Transaction();
        final Domain domain_w = t.enroll(domain);
        /*
             * Create the security configurations element and add it to the domain.
             */
        final SecurityConfigurations sc_w = domain_w.createChild(SecurityConfigurations.class);
        domain_w.getExtensions().add(sc_w);
        /*
             * Create and add the authentication service.
             */
        final AuthenticationService as_w = addAuthenticationService(sc_w);
        /*
             * Next, add the two providers and their children.
             */
        addAdmRealmProvider(as_w);
        addFileRealmProvider(as_w);
        /**
         * Next add the authorization service
         */
        final AuthorizationService authorizationService = addAuthorizationService(sc_w);
        /**
         * Next add the authorization service provider
         */
        addSimpleAuthorizationProvider(authorizationService);
        t.commit();
        logger.log(Level.INFO, "SecurityConfigUpgradeService successfully completed the upgrade");
    } catch (Exception ex) {
        if (t != null) {
            t.rollback();
        }
        logger.log(Level.SEVERE, null, ex);
    }
}
Also used : Transaction(org.jvnet.hk2.config.Transaction) Domain(com.sun.enterprise.config.serverbeans.Domain) PropertyVetoException(java.beans.PropertyVetoException)

Example 35 with Element

use of org.jvnet.hk2.config.Element in project Payara by payara.

the class WriteableView method commit.

/**
 * Commit this Transaction.
 *
 * @param t the transaction commiting.
 * @throws TransactionFailure
 *          if the transaction commit failed
 */
public synchronized List<PropertyChangeEvent> commit(Transaction t) throws TransactionFailure {
    if (currentTx == t) {
        currentTx = null;
    }
    // a key attribute must be non-null and have length >= 1
    final ConfigBean master = getMasterView();
    final String keyStr = master.model.key;
    if (keyStr != null) {
        final String key = stripMarkers(keyStr);
        final String value = getPropertyValue(key);
        if (value == null) {
            throw new TransactionFailure("Key value cannot be null: " + key);
        }
        if (value.length() == 0) {
            throw new TransactionFailure("Key value cannot be empty string: " + key);
        }
    }
    try {
        List<PropertyChangeEvent> appliedChanges = new ArrayList<PropertyChangeEvent>();
        for (PropertyChangeEvent event : changedAttributes.values()) {
            ConfigModel.Property property = bean.model.findIgnoreCase(event.getPropertyName());
            ConfigBeanInterceptor interceptor = bean.getOptionalFeature(ConfigBeanInterceptor.class);
            try {
                if (interceptor != null) {
                    interceptor.beforeChange(event);
                }
            } catch (PropertyVetoException e) {
                throw new TransactionFailure(e.getMessage(), e);
            }
            property.set(bean, event.getNewValue());
            if (interceptor != null) {
                interceptor.afterChange(event, System.currentTimeMillis());
            }
            appliedChanges.add(event);
        }
        for (ProtectedList entry : changedCollections.values()) {
            List<Object> originalList = entry.readOnly;
            for (PropertyChangeEvent event : entry.changeEvents) {
                if (event.getOldValue() == null) {
                    originalList.add(event.getNewValue());
                } else {
                    final Object toBeRemovedObj = event.getOldValue();
                    if (toBeRemovedObj instanceof ConfigBeanProxy) {
                        final Dom toBeRemoved = Dom.unwrap((ConfigBeanProxy) toBeRemovedObj);
                        for (int index = 0; index < originalList.size(); index++) {
                            Object element = originalList.get(index);
                            Dom dom = Dom.unwrap((ConfigBeanProxy) element);
                            if (dom == toBeRemoved) {
                                Object newValue = event.getNewValue();
                                if (newValue == null) {
                                    originalList.remove(index);
                                } else {
                                    originalList.set(index, newValue);
                                }
                            }
                        }
                    } else if (toBeRemovedObj instanceof String) {
                        final String toBeRemoved = (String) toBeRemovedObj;
                        for (int index = 0; index < originalList.size(); index++) {
                            final String item = (String) originalList.get(index);
                            if (item.equals(toBeRemoved)) {
                                originalList.remove(index);
                            }
                        }
                    } else {
                        throw new IllegalArgumentException();
                    }
                }
                appliedChanges.add(event);
            }
        }
        changedAttributes.clear();
        changedCollections.clear();
        return appliedChanges;
    } catch (TransactionFailure e) {
        throw e;
    } catch (Exception e) {
        throw new TransactionFailure(e.getMessage(), e);
    } finally {
        bean.getLock().unlock();
    }
}
Also used : PropertyChangeEvent(java.beans.PropertyChangeEvent) PropertyVetoException(java.beans.PropertyVetoException) PropertyVetoException(java.beans.PropertyVetoException) Property(org.jvnet.hk2.config.ConfigModel.Property)

Aggregations

Property (org.jvnet.hk2.config.types.Property)14 PropertyVetoException (java.beans.PropertyVetoException)13 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)13 IOException (java.io.IOException)8 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)4 List (java.util.List)4 TreeMap (java.util.TreeMap)4 ActionReport (org.glassfish.api.ActionReport)4 MultiException (org.glassfish.hk2.api.MultiException)4 ExtendedDeploymentContext (org.glassfish.internal.deployment.ExtendedDeploymentContext)4 ConfigModel (org.jvnet.hk2.config.ConfigModel)4 Dom (org.jvnet.hk2.config.Dom)4 Application (com.sun.enterprise.config.serverbeans.Application)3 Domain (com.sun.enterprise.config.serverbeans.Domain)3 Server (com.sun.enterprise.config.serverbeans.Server)3 SystemProperty (com.sun.enterprise.config.serverbeans.SystemProperty)3 File (java.io.File)3 HashSet (java.util.HashSet)3 Iterator (java.util.Iterator)3