Search in sources :

Example 21 with Attribute

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

the class ConfigBeanJMXSupport method descriptor.

public static DescriptorSupport descriptor(final AttributeMethodInfo info) {
    final DescriptorSupport d = new DescriptorSupport();
    final Attribute a = info.attribute();
    d.setField(DESC_KIND, Attribute.class.getName());
    if (!a.defaultValue().equals("\u0000")) {
        d.setField(DESC_DEFAULT_VALUE, a.defaultValue());
    }
    d.setField(DESC_KEY, a.key());
    d.setField(DESC_REQUIRED, a.required());
    d.setField(DESC_REFERENCE, a.reference());
    d.setField(DESC_VARIABLE_EXPANSION, a.variableExpansion());
    d.setField(DESC_DATA_TYPE, info.inferDataType().getName());
    return d;
}
Also used : Attribute(org.jvnet.hk2.config.Attribute) DescriptorSupport(javax.management.modelmbean.DescriptorSupport)

Example 22 with Attribute

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

the class CommandRunnerImpl method doCommand.

/**
 * Called from ExecutionContext.execute.
 */
private void doCommand(ExecutionContext inv, AdminCommand command, final Subject subject, final Job job) {
    boolean fromCheckpoint = job != null && (job.getState() == AdminCommandState.State.REVERTING || job.getState() == AdminCommandState.State.FAILED_RETRYABLE);
    CommandModel model;
    try {
        CommandModelProvider c = CommandModelProvider.class.cast(command);
        model = c.getModel();
    } catch (ClassCastException e) {
        model = new CommandModelImpl(command.getClass());
    }
    UploadedFilesManager ufm = null;
    ActionReport report = inv.report();
    if (!fromCheckpoint) {
        report.setActionDescription(model.getCommandName() + " command");
        report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
    }
    ParameterMap parameters;
    final AdminCommandContext context = new AdminCommandContextImpl(logger, report, inv.inboundPayload(), inv.outboundPayload(), job.getEventBroker(), job.getId());
    context.setSubject(subject);
    List<RuntimeType> runtimeTypes = new ArrayList<RuntimeType>();
    FailurePolicy fp = null;
    Set<CommandTarget> targetTypesAllowed = new HashSet<CommandTarget>();
    ActionReport.ExitCode preSupplementalReturn = ActionReport.ExitCode.SUCCESS;
    ActionReport.ExitCode postSupplementalReturn = ActionReport.ExitCode.SUCCESS;
    CommandRunnerProgressHelper progressHelper = new CommandRunnerProgressHelper(command, model.getCommandName(), job, inv.progressStatusChild);
    // If this glassfish installation does not have stand alone instances / clusters at all, then
    // lets not even look Supplemental command and such. A small optimization
    boolean doReplication = false;
    if ((domain.getServers().getServer().size() > 1) || (!domain.getClusters().getCluster().isEmpty())) {
        doReplication = true;
    } else {
        logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.devmode", "The GlassFish environment does not have any clusters or instances present; Replication is turned off"));
    }
    try {
        // Get list of suplemental commands
        Collection<SupplementalCommand> suplementalCommands = supplementalExecutor.listSuplementalCommands(model.getCommandName());
        try {
            /*
                 * Extract any uploaded files and build a map from parameter names
                 * to the corresponding extracted, uploaded file.
                 */
            ufm = new UploadedFilesManager(inv.report, logger, inv.inboundPayload());
            if (inv.typedParams() != null) {
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.delegatedcommand", "This command is a delegated command. Dynamic reconfiguration will be bypassed"));
                InjectionResolver<Param> injectionTarget = new DelegatedInjectionResolver(model, inv.typedParams(), ufm.optionNameToFileMap());
                if (injectParameters(model, command, injectionTarget, report)) {
                    inv.setReport(doCommand(model, command, context, progressHelper));
                }
                return;
            }
            parameters = inv.parameters();
            if (parameters == null) {
                // no parameters, pass an empty collection
                parameters = new ParameterMap();
            }
            if (isSet(parameters, "help") || isSet(parameters, "Xhelp")) {
                BufferedReader in = getManPage(model.getCommandName(), model);
                String manPage = encodeManPage(in);
                if (manPage != null && isSet(parameters, "help")) {
                    inv.report().getTopMessagePart().addProperty("MANPAGE", manPage);
                } else {
                    report.getTopMessagePart().addProperty(AdminCommandResponse.GENERATED_HELP, "true");
                    getHelp(command, report);
                }
                return;
            }
            try {
                if (!fromCheckpoint && !skipValidation(command)) {
                    validateParameters(model, parameters);
                }
            } catch (MultiException e) {
                // If the cause is UnacceptableValueException -- we want the message
                // from it.  It is wrapped with a less useful Exception.
                Exception exception = e;
                for (Throwable cause : e.getErrors()) {
                    if (cause != null && (cause instanceof UnacceptableValueException)) {
                        // throw away the wrapper.
                        exception = (Exception) cause;
                        break;
                    }
                }
                logger.log(Level.SEVERE, KernelLoggerInfo.invocationException, exception);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                report.setMessage(exception.getMessage());
                report.setFailureCause(exception);
                ActionReport.MessagePart childPart = report.getTopMessagePart().addChild();
                childPart.setMessage(getUsageText(model));
                return;
            }
            // initialize the injector and inject
            MapInjectionResolver injectionMgr = new MapInjectionResolver(model, parameters, ufm.optionNameToFileMap());
            injectionMgr.setContext(context);
            if (!injectParameters(model, command, injectionMgr, report)) {
                return;
            }
            CommandSupport.init(habitat, command, context, job);
            /*
                 * Now that parameters have been injected into the command object,
                 * decide if the current Subject should be permitted to execute
                 * the command.  We need to wait until after injection is done
                 * because the class might implement its own authorization check
                 * and that logic might need the injected values.
                 */
            final Map<String, Object> env = buildEnvMap(parameters);
            try {
                if (!commandSecurityChecker.authorize(context.getSubject(), env, command, context)) {
                    /*
                         * If the command class tried to prepare itself but 
                         * could not then the return is false and the command has
                         * set the action report accordingly.  Don't process
                         * the command further and leave the action report alone.
                         */
                    return;
                }
            } catch (SecurityException ex) {
                report.setFailureCause(ex);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                report.setMessage(adminStrings.getLocalString("commandrunner.noauth", "User is not authorized for this command"));
                return;
            } catch (Exception ex) {
                report.setFailureCause(ex);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                report.setMessage(adminStrings.getLocalString("commandrunner.errAuth", "Error during authorization"));
                return;
            }
            logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.injectiondone", "Parameter mapping, validation, injection completed successfully; Starting paramater injection"));
            // Read cluster annotation attributes
            org.glassfish.api.admin.ExecuteOn clAnnotation = model.getClusteringAttributes();
            if (clAnnotation == null) {
                runtimeTypes.add(RuntimeType.DAS);
                runtimeTypes.add(RuntimeType.INSTANCE);
                fp = FailurePolicy.Error;
            } else {
                if (clAnnotation.value().length == 0) {
                    runtimeTypes.add(RuntimeType.DAS);
                    runtimeTypes.add(RuntimeType.INSTANCE);
                } else {
                    runtimeTypes.addAll(Arrays.asList(clAnnotation.value()));
                }
                if (clAnnotation.ifFailure() == null) {
                    fp = FailurePolicy.Error;
                } else {
                    fp = clAnnotation.ifFailure();
                }
            }
            TargetType tgtTypeAnnotation = command.getClass().getAnnotation(TargetType.class);
            // @TargetType since we do not want to replicate the command
            if (runtimeTypes.contains(RuntimeType.SINGLE_INSTANCE)) {
                if (tgtTypeAnnotation != null) {
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.targettype.unallowed", "Target type is not allowed on single instance command {0}  ,", model.getCommandName()));
                    return;
                }
                // Do not replicate the command when there is
                // @ExecuteOn(RuntimeType.SINGLE_INSTANCE)
                doReplication = false;
            }
            String targetName = parameters.getOne("target");
            if (targetName == null || model.getModelFor("target").getParam().obsolete()) {
                if (command instanceof DeploymentTargetResolver) {
                    targetName = ((DeploymentTargetResolver) command).getTarget(parameters);
                } else {
                    targetName = "server";
                }
            }
            logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.target", "@ExecuteOn parsing and default settings done; Current target is {0}", targetName));
            if (serverEnv.isDas()) {
                if (tgtTypeAnnotation != null) {
                    targetTypesAllowed.addAll(Arrays.asList(tgtTypeAnnotation.value()));
                }
                // If not @TargetType, default it
                if (targetTypesAllowed.isEmpty()) {
                    targetTypesAllowed.add(CommandTarget.DAS);
                    targetTypesAllowed.add(CommandTarget.STANDALONE_INSTANCE);
                    targetTypesAllowed.add(CommandTarget.CLUSTER);
                    targetTypesAllowed.add(CommandTarget.CONFIG);
                }
                // ONLY if the target is "server"
                if (CommandTarget.DAS.isValid(habitat, targetName) && !runtimeTypes.contains(RuntimeType.DAS)) {
                    runtimeTypes.add(RuntimeType.DAS);
                }
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.runtimeTypes", "RuntimeTypes are: {0}", runtimeTypes.toString()));
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration,diagnostics.targetTypes", "TargetTypes are: {0}", targetTypesAllowed.toString()));
                // Is there a server or a cluster or a config with given name ?
                if ((!CommandTarget.DOMAIN.isValid(habitat, targetName)) && (domain.getServerNamed(targetName) == null) && (domain.getClusterNamed(targetName) == null) && (domain.getConfigNamed(targetName) == null) && (domain.getDeploymentGroupNamed(targetName) == null)) {
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.invalidtarget", "Unable to find a valid target with name {0}", targetName));
                    return;
                }
                // Does this command allow this target type
                boolean isTargetValidType = false;
                Iterator<CommandTarget> it = targetTypesAllowed.iterator();
                while (it.hasNext()) {
                    if (it.next().isValid(habitat, targetName)) {
                        isTargetValidType = true;
                        break;
                    }
                }
                if (!isTargetValidType) {
                    StringBuilder validTypes = new StringBuilder();
                    it = targetTypesAllowed.iterator();
                    while (it.hasNext()) {
                        validTypes.append(it.next().getDescription()).append(", ");
                    }
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.invalidtargettype", "Target {0} is not a supported type. Command {1} supports these types of targets only : {2}", targetName, model.getCommandName(), validTypes.toString()));
                    return;
                }
                // instance, return error
                if ((CommandTarget.CLUSTERED_INSTANCE.isValid(habitat, targetName)) && (!targetTypesAllowed.contains(CommandTarget.CLUSTERED_INSTANCE))) {
                    Cluster c = domain.getClusterForInstance(targetName);
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.instanceopnotallowed", "The {0} command is not allowed on instance {1} because it is part of cluster {2}", model.getCommandName(), targetName, c.getName()));
                    return;
                }
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.replicationvalidationdone", "All @ExecuteOn attribute and type validation completed successfully. Starting replication stages"));
            }
            /**
             * We're finally ready to actually execute the command instance.
             * Acquire the appropriate lock.
             */
            Lock lock = null;
            boolean lockTimedOut = false;
            try {
                // XXX: The owner of the lock should not be hardcoded.  The
                // value is not used yet.
                lock = adminLock.getLock(command, "asadmin");
                // Set there progress statuses
                if (!fromCheckpoint) {
                    for (SupplementalCommand supplementalCommand : suplementalCommands) {
                        progressHelper.addProgressStatusToSupplementalCommand(supplementalCommand);
                    }
                }
                // If command is undoable, then invoke prepare method
                if (command instanceof UndoableCommand) {
                    UndoableCommand uCmd = (UndoableCommand) command;
                    logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.prepareunodable", "Command execution stage 1 : Calling prepare for undoable command {0}", inv.name()));
                    if (!uCmd.prepare(context, parameters).equals(ActionReport.ExitCode.SUCCESS)) {
                        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                        report.setMessage(adminStrings.getLocalString("commandrunner.executor.errorinprepare", "The command {0} cannot be completed because the preparation for the command failed " + "indicating potential issues : {1}", model.getCommandName(), report.getMessage()));
                        return;
                    }
                }
                ClusterOperationUtil.clearInstanceList();
                // Run Supplemental commands that have to run before this command on this instance type
                if (!fromCheckpoint) {
                    logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.presupplemental", "Command execution stage 2 : Call pre supplemental commands for {0}", inv.name()));
                    preSupplementalReturn = supplementalExecutor.execute(suplementalCommands, Supplemental.Timing.Before, context, parameters, ufm.optionNameToFileMap());
                    if (preSupplementalReturn.equals(ActionReport.ExitCode.FAILURE)) {
                        report.setActionExitCode(preSupplementalReturn);
                        if (!StringUtils.ok(report.getTopMessagePart().getMessage())) {
                            report.setMessage(adminStrings.getLocalString("commandrunner.executor.supplementalcmdfailed", "A supplemental command failed; cannot proceed further"));
                        }
                        return;
                    }
                }
                // Run main command if it is applicable for this instance type
                if ((runtimeTypes.contains(RuntimeType.ALL)) || (serverEnv.isDas() && (CommandTarget.DOMAIN.isValid(habitat, targetName) || runtimeTypes.contains(RuntimeType.DAS))) || runtimeTypes.contains(RuntimeType.SINGLE_INSTANCE) || (serverEnv.isInstance() && runtimeTypes.contains(RuntimeType.INSTANCE))) {
                    logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.maincommand", "Command execution stage 3 : Calling main command implementation for {0}", inv.name()));
                    report = doCommand(model, command, context, progressHelper);
                    inv.setReport(report);
                }
                if (!FailurePolicy.applyFailurePolicy(fp, report.getActionExitCode()).equals(ActionReport.ExitCode.FAILURE)) {
                    // Run Supplemental commands that have to be run after this command on this instance type
                    logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.postsupplemental", "Command execution stage 4 : Call post supplemental commands for {0}", inv.name()));
                    postSupplementalReturn = supplementalExecutor.execute(suplementalCommands, Supplemental.Timing.After, context, parameters, ufm.optionNameToFileMap());
                    if (postSupplementalReturn.equals(ActionReport.ExitCode.FAILURE)) {
                        report.setActionExitCode(postSupplementalReturn);
                        report.setMessage(adminStrings.getLocalString("commandrunner.executor.supplementalcmdfailed", "A supplemental command failed; cannot proceed further"));
                        return;
                    }
                }
            } catch (AdminCommandLockTimeoutException ex) {
                lockTimedOut = true;
                String lockTime = formatSuspendDate(ex.getTimeOfAcquisition());
                String logMsg = "Command: " + model.getCommandName() + " failed to acquire a command lock.  REASON: time out " + "(current lock acquired on " + lockTime + ")";
                String msg = adminStrings.getLocalString("lock.timeout", "Command timed out.  Unable to acquire a lock to access " + "the domain.  Another command acquired exclusive access " + "to the domain on {0}.  Retry the command at a later " + "time.", lockTime);
                report.setMessage(msg);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            } catch (AdminCommandLockException ex) {
                lockTimedOut = true;
                String lockTime = formatSuspendDate(ex.getTimeOfAcquisition());
                String lockMsg = ex.getMessage();
                String logMsg;
                logMsg = "Command: " + model.getCommandName() + " was blocked.  The domain was suspended by a " + "user on:" + lockTime;
                if (lockMsg != null && !lockMsg.isEmpty()) {
                    logMsg += " Reason: " + lockMsg;
                }
                String msg = adminStrings.getLocalString("lock.notacquired", "The command was blocked.  The domain was suspended by " + "a user on {0}.", lockTime);
                if (lockMsg != null && !lockMsg.isEmpty()) {
                    msg += " " + adminStrings.getLocalString("lock.reason", "Reason:") + " " + lockMsg;
                }
                report.setMessage(msg);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            } finally {
                // command is done, release the lock
                if (lock != null && lockTimedOut == false) {
                    lock.unlock();
                }
            }
        } catch (Exception ex) {
            logger.log(Level.SEVERE, KernelLoggerInfo.invocationException, ex);
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setMessage(ex.getMessage());
            report.setFailureCause(ex);
            ActionReport.MessagePart childPart = report.getTopMessagePart().addChild();
            childPart.setMessage(getUsageText(model));
            return;
        }
        if (processEnv.getProcessType().isEmbedded()) {
            return;
        }
        if (preSupplementalReturn == ActionReport.ExitCode.WARNING || postSupplementalReturn == ActionReport.ExitCode.WARNING) {
            report.setActionExitCode(ActionReport.ExitCode.WARNING);
        }
        if (doReplication && (!FailurePolicy.applyFailurePolicy(fp, report.getActionExitCode()).equals(ActionReport.ExitCode.FAILURE)) && (serverEnv.isDas()) && (runtimeTypes.contains(RuntimeType.INSTANCE) || runtimeTypes.contains(RuntimeType.ALL))) {
            logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.startreplication", "Command execution stages completed on DAS; Starting replication on remote instances"));
            ClusterExecutor executor = null;
            // This try-catch block is a fix for 13838
            try {
                if (model.getClusteringAttributes() != null && model.getClusteringAttributes().executor() != null) {
                    executor = habitat.getService(model.getClusteringAttributes().executor());
                } else {
                    executor = habitat.getService(ClusterExecutor.class, "GlassFishClusterExecutor");
                }
            } catch (UnsatisfiedDependencyException usdepex) {
                logger.log(Level.WARNING, KernelLoggerInfo.cantGetClusterExecutor, usdepex);
            }
            if (executor != null) {
                report.setActionExitCode(executor.execute(model.getCommandName(), command, context, parameters));
                if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.errorwhilereplication", "An error occurred during replication"));
                } else {
                    if (!FailurePolicy.applyFailurePolicy(fp, report.getActionExitCode()).equals(ActionReport.ExitCode.FAILURE)) {
                        logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.afterreplsupplemental", "Command execution stage 5 : Call post-replication supplemental commands for {0}", inv.name()));
                        ActionReport.ExitCode afterReplicationSupplementalReturn = supplementalExecutor.execute(suplementalCommands, Supplemental.Timing.AfterReplication, context, parameters, ufm.optionNameToFileMap());
                        if (afterReplicationSupplementalReturn.equals(ActionReport.ExitCode.FAILURE)) {
                            report.setActionExitCode(afterReplicationSupplementalReturn);
                            report.setMessage(adminStrings.getLocalString("commandrunner.executor.supplementalcmdfailed", "A supplemental command failed; cannot proceed further"));
                            return;
                        }
                    }
                }
            }
        }
        if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
            // If command is undoable, then invoke undo method method
            if (command instanceof UndoableCommand) {
                UndoableCommand uCmd = (UndoableCommand) command;
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.undo", "Command execution failed; calling undo() for command {0}", inv.name()));
                uCmd.undo(context, parameters, ClusterOperationUtil.getCompletedInstances());
            }
        } else {
            // TODO : Is there a better way of doing this ? Got to look into it
            if ("_register-instance".equals(model.getCommandName())) {
                state.addServerToStateService(parameters.getOne("DEFAULT"));
            }
            if ("_unregister-instance".equals(model.getCommandName())) {
                state.removeInstanceFromStateService(parameters.getOne("DEFAULT"));
            }
        }
    } finally {
        if (ufm != null) {
            ufm.close();
        }
    }
}
Also used : DeploymentTargetResolver(org.glassfish.internal.deployment.DeploymentTargetResolver) ActionReport(org.glassfish.api.ActionReport) UnsatisfiedDependencyException(org.jvnet.hk2.config.UnsatisfiedDependencyException) UnacceptableValueException(org.glassfish.common.util.admin.UnacceptableValueException) CommandModelImpl(org.glassfish.common.util.admin.CommandModelImpl) SupplementalCommand(org.glassfish.api.admin.SupplementalCommandExecutor.SupplementalCommand) MultiException(org.glassfish.hk2.api.MultiException) org.glassfish.api.admin(org.glassfish.api.admin) TargetType(org.glassfish.config.support.TargetType) MapInjectionResolver(org.glassfish.common.util.admin.MapInjectionResolver) CommandTarget(org.glassfish.config.support.CommandTarget) Cluster(com.sun.enterprise.config.serverbeans.Cluster) MultiException(org.glassfish.hk2.api.MultiException) UnacceptableValueException(org.glassfish.common.util.admin.UnacceptableValueException) UnsatisfiedDependencyException(org.jvnet.hk2.config.UnsatisfiedDependencyException) Lock(java.util.concurrent.locks.Lock) Param(org.glassfish.api.Param)

Example 23 with Attribute

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

the class CombinedJavaConfigSystemPropertyListener method changed.

/* force serial behavior; don't allow more than one thread to make a mess here */
@Override
public synchronized UnprocessedChangeEvents changed(PropertyChangeEvent[] events) {
    // ignore a REMOVE and an ADD of the same value
    final UnprocessedChangeEvents unp = ConfigSupport.sortAndDispatch(events, new Changed() {

        @Override
        public <T extends ConfigBeanProxy> NotProcessed changed(TYPE type, Class<T> tc, T t) {
            NotProcessed result = null;
            if (tc == Profiler.class) {
                result = new NotProcessed("Creation or changes to a profiler require restart");
            } else if (tc == Property.class && t.getParent().getClass() == JavaConfig.class) {
                result = new NotProcessed("Addition of properties to JavaConfig requires restart");
            } else if (tc == JavaConfig.class && t instanceof JavaConfig) {
                final JavaConfig njc = (JavaConfig) t;
                logFine(type, njc);
                // we must *always* check the jvm options, no way to know except by comparing,
                // plus we should send an appropriate message back for each removed/added item
                final List<String> curProps = new ArrayList<String>(njc.getJvmOptions());
                final boolean jvmOptionsWereChanged = !oldProps.equals(curProps);
                final List<String> reasons = handle(oldProps, curProps);
                oldProps = curProps;
                // something in the JavaConfig itself changed
                // to do this well, we ought to keep a list of attributes, so we can make a good message
                // saying exactly which attribute what changed
                final Map<String, String> curAttrs = collectAttrs(njc);
                reasons.addAll(handleAttrs(oldAttrs, curAttrs));
                oldAttrs = curAttrs;
                result = reasons.isEmpty() ? null : new NotProcessed(CombinedJavaConfigSystemPropertyListener.toString(reasons));
            } else if (tc == SystemProperty.class && t instanceof SystemProperty) {
                final SystemProperty sp = (SystemProperty) t;
                // check to see if this system property is for this instance
                ConfigBeanProxy proxy = sp.getParent();
                ConfigView p = ConfigSupport.getImpl(proxy);
                if (p == ConfigSupport.getImpl(server) || p == ConfigSupport.getImpl(config) || (cluster != null && p == ConfigSupport.getImpl(cluster)) || p == ConfigSupport.getImpl(domain)) {
                    // check to see if this system property is referenced by any of the options
                    String pname = sp.getName();
                    if (referencesProperty(pname, oldProps) || referencesProperty(pname, oldAttrs.values())) {
                        result = new NotProcessed("The system-property, " + pname + ", that is referenced by the Java configuration, was modified");
                    }
                }
                if (type == TYPE.ADD || type == TYPE.CHANGE) {
                    // create-system-properties
                    if (proxy instanceof Domain) {
                        return addToDomain(sp);
                    } else if (proxy instanceof Config && p == ConfigSupport.getImpl(config)) {
                        return addToConfig(sp);
                    } else if (cluster != null && proxy instanceof Cluster && p == ConfigSupport.getImpl(cluster)) {
                        return addToCluster(sp);
                    } else if (proxy instanceof Server && p == ConfigSupport.getImpl(server)) {
                        return addToServer(sp);
                    }
                } else if (type == TYPE.REMOVE) {
                    if (proxy instanceof Domain) {
                        return removeFromDomain(sp);
                    } else if (proxy instanceof Config && p == ConfigSupport.getImpl(config)) {
                        return removeFromConfig(sp);
                    } else if (cluster != null && proxy instanceof Cluster && p == ConfigSupport.getImpl(cluster)) {
                        return removeFromCluster(sp);
                    } else if (proxy instanceof Server && p == ConfigSupport.getImpl(server)) {
                        return removeFromServer(sp);
                    }
                }
            } else {
            // ignore other changes that are reported
            }
            return result;
        }
    }, logger);
    return unp;
}
Also used : UnprocessedChangeEvents(org.jvnet.hk2.config.UnprocessedChangeEvents) Server(com.sun.enterprise.config.serverbeans.Server) TranslatedConfigView(org.glassfish.config.support.TranslatedConfigView) ConfigView(org.jvnet.hk2.config.ConfigView) JavaConfig(com.sun.enterprise.config.serverbeans.JavaConfig) Config(com.sun.enterprise.config.serverbeans.Config) Cluster(com.sun.enterprise.config.serverbeans.Cluster) SystemProperty(com.sun.enterprise.config.serverbeans.SystemProperty) JavaConfig(com.sun.enterprise.config.serverbeans.JavaConfig) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) Profiler(com.sun.enterprise.config.serverbeans.Profiler) Changed(org.jvnet.hk2.config.Changed) NotProcessed(org.jvnet.hk2.config.NotProcessed) ArrayList(java.util.ArrayList) List(java.util.List) Domain(com.sun.enterprise.config.serverbeans.Domain) TYPE(org.jvnet.hk2.config.Changed.TYPE) Property(org.jvnet.hk2.config.types.Property) SystemProperty(com.sun.enterprise.config.serverbeans.SystemProperty) HashMap(java.util.HashMap) Map(java.util.Map)

Example 24 with Attribute

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

the class ApplicationConfigListener method transactionCommited.

public void transactionCommited(final List<PropertyChangeEvent> changes) {
    boolean isUpdatingAttribute = true;
    for (PropertyChangeEvent event : changes) {
        Object oldValue = event.getOldValue();
        Object newValue = event.getNewValue();
        if (event.getSource() instanceof Applications) {
            if (event.getPropertyName().equals(ServerTags.APPLICATION)) {
                if (oldValue == null || newValue == null) {
                    // we are adding/removing application element here
                    // and updating existing attribute
                    isUpdatingAttribute = false;
                    break;
                }
            }
        } else if (event.getSource() instanceof Server || event.getSource() instanceof Cluster) {
            if (event.getPropertyName().equals(ServerTags.APPLICATION_REF)) {
                if (oldValue == null || newValue == null) {
                    // we are adding/removing application-ref element here
                    // and updating existing attribute
                    isUpdatingAttribute = false;
                    break;
                }
            }
        }
    }
    if (!isUpdatingAttribute) {
        // skip the config listener
        return;
    }
    for (PropertyChangeEvent event : changes) {
        if (event.getSource() instanceof Application || event.getSource() instanceof ApplicationRef || event.getSource() instanceof Property) {
            Object oldValue = event.getOldValue();
            Object newValue = event.getNewValue();
            String propertyName = null;
            if (oldValue != null && newValue != null && oldValue instanceof String && newValue instanceof String && !((String) oldValue).equals((String) newValue)) {
                // if it's an attribute change of the application
                // element or application-ref element
                Object parent = event.getSource();
                String appName = null;
                if (parent instanceof Application) {
                    appName = ((Application) parent).getName();
                    propertyName = event.getPropertyName();
                } else if (parent instanceof ApplicationRef) {
                    appName = ((ApplicationRef) parent).getRef();
                    propertyName = event.getPropertyName();
                } else if (parent instanceof Property) {
                    appName = ((Property) parent).getParent(Application.class).getName();
                    propertyName = ((Property) parent).getName();
                }
                // anything
                if (applications.getApplication(appName) == null) {
                    return;
                }
                if (ServerTags.ENABLED.equals(propertyName)) {
                    // enable or disable application accordingly
                    handleAppEnableChange(event.getSource(), appName, Boolean.valueOf((String) newValue));
                } else if (ServerTags.CONTEXT_ROOT.equals(propertyName) || ServerTags.VIRTUAL_SERVERS.equals(propertyName) || ServerTags.AVAILABILITY_ENABLED.equals(propertyName) || ServerTags.CDI_DEV_MODE_ENABLED_PROP.equals(propertyName)) {
                    // for other changes, reload the application
                    handleOtherAppConfigChanges(event.getSource(), appName);
                }
            }
        }
    }
}
Also used : PropertyChangeEvent(java.beans.PropertyChangeEvent) Applications(com.sun.enterprise.config.serverbeans.Applications) Server(com.sun.enterprise.config.serverbeans.Server) Cluster(com.sun.enterprise.config.serverbeans.Cluster) Application(com.sun.enterprise.config.serverbeans.Application) ApplicationRef(com.sun.enterprise.config.serverbeans.ApplicationRef) Property(org.jvnet.hk2.config.types.Property)

Example 25 with Attribute

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

the class ApplicationLifecycle method registerAppInDomainXML.

// register application information in domain.xml
@Override
public void registerAppInDomainXML(final ApplicationInfo applicationInfo, final DeploymentContext context, Transaction t, boolean appRefOnly) throws TransactionFailure {
    final Properties appProps = context.getAppProps();
    final DeployCommandParameters deployParams = context.getCommandParameters(DeployCommandParameters.class);
    if (t != null) {
        try {
            if (!appRefOnly) {
                Application app_w = context.getTransientAppMetaData(ServerTags.APPLICATION, Application.class);
                // adding the application element
                setRestAppAttributes(app_w, appProps);
                Applications apps_w = t.enroll(applications);
                apps_w.getModules().add(app_w);
                if (applicationInfo != null) {
                    applicationInfo.save(app_w);
                }
            }
            List<String> targets = new ArrayList<String>();
            if (!DeploymentUtils.isDomainTarget(deployParams.target)) {
                targets.add(deployParams.target);
            } else {
                List<String> previousTargets = context.getTransientAppMetaData(DeploymentProperties.PREVIOUS_TARGETS, List.class);
                if (previousTargets == null) {
                    previousTargets = domain.getAllReferencedTargetsForApplication(deployParams.name);
                }
                targets = previousTargets;
            }
            String origVS = deployParams.virtualservers;
            Boolean origEnabled = deployParams.enabled;
            Properties previousVirtualServers = context.getTransientAppMetaData(DeploymentProperties.PREVIOUS_VIRTUAL_SERVERS, Properties.class);
            Properties previousEnabledAttributes = context.getTransientAppMetaData(DeploymentProperties.PREVIOUS_ENABLED_ATTRIBUTES, Properties.class);
            for (String target : targets) {
                // first reset the virtualservers, enabled attribute
                deployParams.virtualservers = origVS;
                deployParams.enabled = origEnabled;
                // applicable
                if (DeploymentUtils.isDomainTarget(deployParams.target)) {
                    String vs = previousVirtualServers.getProperty(target);
                    if (vs != null) {
                        deployParams.virtualservers = vs;
                    }
                    String enabledAttr = previousEnabledAttributes.getProperty(target);
                    if (enabledAttr != null) {
                        deployParams.enabled = Boolean.valueOf(enabledAttr);
                    }
                }
                if (deployParams.enabled == null) {
                    deployParams.enabled = Boolean.TRUE;
                }
                Server servr = domain.getServerNamed(target);
                if (servr != null) {
                    ApplicationRef instanceApplicationRef = domain.getApplicationRefInTarget(deployParams.name, servr.getName());
                    if (instanceApplicationRef == null) {
                        // adding the application-ref element to the standalone
                        // server instance
                        ConfigBeanProxy servr_w = t.enroll(servr);
                        // adding the application-ref element to the standalone
                        // server instance
                        ApplicationRef appRef = servr_w.createChild(ApplicationRef.class);
                        setAppRefAttributes(appRef, deployParams);
                        ((Server) servr_w).getApplicationRef().add(appRef);
                    }
                }
                Cluster cluster = domain.getClusterNamed(target);
                if (cluster != null) {
                    // adding the application-ref element to the cluster
                    // and instances
                    ConfigBeanProxy cluster_w = t.enroll(cluster);
                    ApplicationRef appRef = cluster_w.createChild(ApplicationRef.class);
                    setAppRefAttributes(appRef, deployParams);
                    ((Cluster) cluster_w).getApplicationRef().add(appRef);
                    for (Server svr : cluster.getInstances()) {
                        ConfigBeanProxy svr_w = t.enroll(svr);
                        ApplicationRef appRef2 = svr_w.createChild(ApplicationRef.class);
                        setAppRefAttributes(appRef2, deployParams);
                        ((Server) svr_w).getApplicationRef().add(appRef2);
                    }
                }
                DeploymentGroup dg = domain.getDeploymentGroupNamed(target);
                if (dg != null) {
                    ConfigBeanProxy dg_w = t.enroll(dg);
                    ApplicationRef appRef = dg_w.createChild(ApplicationRef.class);
                    setAppRefAttributes(appRef, deployParams);
                    ((DeploymentGroup) dg_w).getApplicationRef().add(appRef);
                    for (Server svr : dg.getInstances()) {
                        ApplicationRef instanceApplicationRef = domain.getApplicationRefInTarget(deployParams.name, svr.getName());
                        if (instanceApplicationRef == null) {
                            ConfigBeanProxy svr_w = t.enroll(svr);
                            ApplicationRef appRef2 = svr_w.createChild(ApplicationRef.class);
                            setAppRefAttributes(appRef2, deployParams);
                            ((Server) svr_w).getApplicationRef().add(appRef2);
                        }
                    }
                }
            }
        } catch (TransactionFailure e) {
            t.rollback();
            throw e;
        } catch (Exception e) {
            t.rollback();
            throw new TransactionFailure(e.getMessage(), e);
        }
        try {
            t.commit();
        } catch (RetryableException e) {
            System.out.println("Retryable...");
            // TODO : do something meaninful here
            t.rollback();
        } catch (TransactionFailure e) {
            t.rollback();
            throw e;
        }
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) PropertyVetoException(java.beans.PropertyVetoException) RetryableException(org.jvnet.hk2.config.RetryableException) MultiException(org.glassfish.hk2.api.MultiException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) IOException(java.io.IOException) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) RetryableException(org.jvnet.hk2.config.RetryableException) DeploymentGroup(fish.payara.enterprise.config.serverbeans.DeploymentGroup)

Aggregations

Attribute (org.jvnet.hk2.config.Attribute)11 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)7 Method (java.lang.reflect.Method)6 ArrayList (java.util.ArrayList)6 PropertyChangeEvent (java.beans.PropertyChangeEvent)5 HashMap (java.util.HashMap)5 MultiException (org.glassfish.hk2.api.MultiException)5 ConfigBeanProxy (org.jvnet.hk2.config.ConfigBeanProxy)5 Map (java.util.Map)4 Dom (org.jvnet.hk2.config.Dom)4 Property (org.jvnet.hk2.config.types.Property)4 Cluster (com.sun.enterprise.config.serverbeans.Cluster)3 SystemProperty (com.sun.enterprise.config.serverbeans.SystemProperty)3 PropertyVetoException (java.beans.PropertyVetoException)3 List (java.util.List)3 Param (org.glassfish.api.Param)3 ParameterMap (org.glassfish.api.admin.ParameterMap)3 Domain (com.sun.enterprise.config.serverbeans.Domain)2 MonitoringService (com.sun.enterprise.config.serverbeans.MonitoringService)2 Server (com.sun.enterprise.config.serverbeans.Server)2