Java Code Examples for org.jboss.as.controller.OperationContext#getResult()

The following examples show how to use org.jboss.as.controller.OperationContext#getResult() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ThreadMXBeanFindMonitorDeadlockedThreadsHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {

    try {
        long[] ids = ManagementFactory.getThreadMXBean().findMonitorDeadlockedThreads();
        final ModelNode result = context.getResult();
        if (ids != null) {
            result.setEmptyList();
            for (long id : ids) {
                result.add(id);
            }
        }
    } catch (SecurityException e) {
        throw new OperationFailedException(e.toString());
    }
}
 
Example 2
Source File: SnapshotListHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
    AuthorizationResult authorizationResult = context.authorize(operation);
    if (authorizationResult.getDecision() == AuthorizationResult.Decision.DENY) {
        throw ControllerLogger.ROOT_LOGGER.unauthorized(operation.get(OP).asString(), context.getCurrentAddress(), authorizationResult.getExplanation());
    }

    try {
        SnapshotInfo info = persister.listSnapshots();
        ModelNode result = context.getResult();
        result.get(ModelDescriptionConstants.DIRECTORY).set(info.getSnapshotDirectory());
        result.get(ModelDescriptionConstants.NAMES).setEmptyList();
        for (String name : info.names()) {
            result.get(ModelDescriptionConstants.NAMES).add(name);
        }
    } catch (Exception e) {
        throw new OperationFailedException(e);
    }
    context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
 
Example 3
Source File: GenericSubsystemDescribeHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
    final ModelNode address;
    final PathAddress pa = context.getCurrentAddress();

    AuthorizationResult authResult = context.authorize(operation, DESCRIBE_EFFECTS);
    if (authResult.getDecision() != AuthorizationResult.Decision.PERMIT) {
        throw ControllerLogger.ROOT_LOGGER.unauthorized(operation.require(OP).asString(), pa, authResult.getExplanation());
    }

    if (pa.size() > 0) {
        address = new ModelNode().add(pa.getLastElement().getKey(), pa.getLastElement().getValue());
    } else {
        address = new ModelNode().setEmptyList();
    }
    final Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS);
    final ModelNode result = context.getResult();
    describe(context.getAttachment(OrderedChildTypesAttachment.KEY), resource,
            address, result, context.getResourceRegistration());
}
 
Example 4
Source File: ThreadMXBeanThreadInfoHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {

    validator.validate(operation);
    ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
    try {
        long id = operation.require(PlatformMBeanConstants.ID).asLong();
        ThreadInfo info;
        if (operation.hasDefined(PlatformMBeanConstants.MAX_DEPTH)) {
            info = mbean.getThreadInfo(id, operation.require(PlatformMBeanConstants.MAX_DEPTH).asInt());
        } else {
            info = mbean.getThreadInfo(id);
        }

        final ModelNode result = context.getResult();
        if (info != null) {
            result.set(PlatformMBeanUtil.getDetypedThreadInfo(info, mbean.isThreadCpuTimeSupported()));
        }
    } catch (SecurityException e) {
        throw new OperationFailedException(e.toString());
    }
}
 
Example 5
Source File: HostConnectionResourceDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
    final PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
    final String operationName = operation.require(NAME).asString();
    final String hostName = address.getLastElement().getValue();
    final HostConnectionInfo info = slaveHosts.getHostInfo(hostName);
    if (info != null) {
        final ModelNode result = context.getResult();
        switch (operationName) {
            case HostConnectionInfo.CONNECTED:
                result.set(info.isConnected());
                break;
            case HostConnectionInfo.EVENTS:
                processEvents(info, result.setEmptyList());
                break;
        }
    }
}
 
Example 6
Source File: ThreadMXBeanFindDeadlockedThreadsHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {

    try {
        long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
        final ModelNode result = context.getResult();
        if (ids != null) {
            result.setEmptyList();
            for (long id : ids) {
                result.add(id);
            }
        }
    } catch (SecurityException e) {
        throw new OperationFailedException(e.toString());
    }
}
 
Example 7
Source File: ModifiableRealmDecorator.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException {
    String principalName = IDENTITY.resolveModelAttribute(context, operation).asString();
    ModifiableRealmIdentity realmIdentity = getRealmIdentity(context, principalName);

    try {
        AuthorizationIdentity identity = realmIdentity.getAuthorizationIdentity();
        ModelNode result = context.getResult();

        result.get(ElytronDescriptionConstants.NAME).set(principalName);

        ModelNode attributesNode = result.get(ElytronDescriptionConstants.ATTRIBUTES);
        for (Attributes.Entry entry : identity.getAttributes().entries()) {
            ModelNode entryNode = attributesNode.get(entry.getKey()).setEmptyList();
            for (String s : entry) {
                entryNode.add(s);
            }
        }
    } catch (RealmUnavailableException e) {
        throw ROOT_LOGGER.couldNotReadIdentity(principalName, e);
    }
}
 
Example 8
Source File: ThreadMXBeanThreadInfosHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {

    try {
        final long[] ids = getIds(operation);
        ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
        ThreadInfo[] infos;
        if (operation.hasDefined(PlatformMBeanConstants.LOCKED_MONITORS)) {
            lockedValidator.validate(operation);
            infos = mbean.getThreadInfo(ids,
                    operation.require(PlatformMBeanConstants.LOCKED_MONITORS).asBoolean(),
                    operation.require(PlatformMBeanConstants.LOCKED_SYNCHRONIZERS).asBoolean());
        } else if (operation.hasDefined(PlatformMBeanConstants.MAX_DEPTH)) {
            depthValidator.validate(operation);
            infos = mbean.getThreadInfo(ids, operation.require(PlatformMBeanConstants.MAX_DEPTH).asInt());
        } else {
            infos = mbean.getThreadInfo(ids);
        }

        final ModelNode result = context.getResult();
        if (infos != null) {
            result.setEmptyList();
            for (ThreadInfo info : infos) {
                if (info != null) {
                    result.add(PlatformMBeanUtil.getDetypedThreadInfo(info, mbean.isThreadCpuTimeSupported()));
                } else {
                    // Add an undefined placeholder
                    result.add();
                }
            }
        }
    } catch (SecurityException e) {
        throw new OperationFailedException(e.toString());
    }
}
 
Example 9
Source File: SensitivityResourceDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
    final String attribute = operation.require(NAME).asString();
    final SensitivityClassificationResource resource = (SensitivityClassificationResource)context.readResource(PathAddress.EMPTY_ADDRESS);
    final AbstractSensitivity classification = resource.classification;
    Boolean result;
    if (attribute.equals(DEFAULT_REQUIRES_ADDRESSABLE.getName()) && includeAddressable) {
        result = classification.isDefaultRequiresAccessPermission();
    } else if (attribute.equals(DEFAULT_REQUIRES_READ.getName())) {
        result = classification.isDefaultRequiresReadPermission();
    } else if (attribute.equals(DEFAULT_REQUIRES_WRITE.getName())) {
        result = classification.isDefaultRequiresWritePermission();
    } else if (attribute.equals(CONFIGURED_REQUIRES_ADDRESSABLE.getName()) && includeAddressable) {
        result = classification.getConfiguredRequiresAccessPermission();
    } else if (attribute.equals(CONFIGURED_REQUIRES_READ.getName())) {
        result = classification.getConfiguredRequiresReadPermission();
    } else if (attribute.equals(CONFIGURED_REQUIRES_WRITE.getName())) {
        result = classification.getConfiguredRequiresWritePermission();
    } else {
        throw DomainManagementLogger.ROOT_LOGGER.invalidSensitiveClassificationAttribute(attribute);
    }

    context.getResult();
    if (result != null) {
        context.getResult().set(result);
    }
}
 
Example 10
Source File: AccessConstraintAppliesToResourceDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
void setResult(OperationContext context, AccessConstraintUtilization constraintUtilization) {
    ModelNode result = context.getResult();
    result.setEmptyList();
    for (String attribute : getStringSet(constraintUtilization)) {
        result.add(attribute);
    }
}
 
Example 11
Source File: IsCallerInRoleOperation.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
    String roleName = RoleMappingResourceDefinition.getRoleName(operation);

    if (context.getCurrentStage() == Stage.MODEL) {
        context.addStep(this, Stage.RUNTIME);
    } else {
        ModelNode result = context.getResult();
        Set<String> operationHeaderRoles = RunAsRoleMapper.getOperationHeaderRoles(operation);
        result.set(isCallerInRole(roleName, context.getCaller(), context.getCallEnvironment(), operationHeaderRoles));
    }
}
 
Example 12
Source File: FindNonProgressingOperationHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {

    final long timeout = TimeUnit.SECONDS.toNanos(STABILITY_TIMEOUT.resolveModelAttribute(context, operation).asLong());

    DomainManagementLogger.ROOT_LOGGER.debugf("Identification of operation not progressing after [%d] ns has been requested", timeout);

    String nonProgressing = findNonProgressingOp(context, timeout);
    ModelNode result = context.getResult();
    if (nonProgressing != null) {
        result.set(nonProgressing);
    }
}
 
Example 13
Source File: MemoryManagerMXBeanAttributeHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void executeReadAttribute(OperationContext context, ModelNode operation) throws OperationFailedException {

    final String mmName = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR)).getLastElement().getValue();
    final String name = operation.require(ModelDescriptionConstants.NAME).asString();

    MemoryManagerMXBean memoryManagerMXBean = null;

    for (MemoryManagerMXBean mbean : ManagementFactory.getMemoryManagerMXBeans()) {
        if (mmName.equals(escapeMBeanName(mbean.getName()))) {
            memoryManagerMXBean = mbean;
        }
    }

    if (memoryManagerMXBean == null) {
        throw PlatformMBeanLogger.ROOT_LOGGER.unknownMemoryManager(mmName);
    }

    if (PlatformMBeanConstants.OBJECT_NAME.getName().equals(name)) {
        final String objName = PlatformMBeanUtil.getObjectNameStringWithNameKey(ManagementFactory.MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE, mmName);
        context.getResult().set(objName);
    } else if (ModelDescriptionConstants.NAME.equals(name)) {
        context.getResult().set(escapeMBeanName(memoryManagerMXBean.getName()));
    } else if (PlatformMBeanConstants.VALID.getName().equals(name)) {
        context.getResult().set(memoryManagerMXBean.isValid());
    } else if (PlatformMBeanConstants.MEMORY_POOL_NAMES.equals(name)) {
        final ModelNode result = context.getResult();
        result.setEmptyList();
        for (String pool : memoryManagerMXBean.getMemoryPoolNames()) {
            result.add(escapeMBeanName(pool));
        }
    } else if (MemoryManagerResourceDefinition.MEMORY_MANAGER_READ_ATTRIBUTES.contains(name)) {
        // Bug
        throw PlatformMBeanLogger.ROOT_LOGGER.badReadAttributeImpl(name);
    } else {
        // Shouldn't happen; the global handler should reject
        throw unknownAttribute(operation);
    }

}
 
Example 14
Source File: ModifiableKeyStoreDecorator.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException {
    String alias = ALIAS.resolveModelAttribute(context, operation).asString();
    KeyStore keyStore = getKeyStore(context);

    try {
        ModelNode result = context.getResult();
        if ( ! keyStore.containsAlias(alias)) {
            ROOT_LOGGER.tracef("Alias [%s] does not exists in KeyStore");
            return;
        }

        result.get(ElytronDescriptionConstants.ALIAS).set(alias);
        result.get(ElytronDescriptionConstants.ENTRY_TYPE).set(getEntryType(keyStore, alias));

        Date creationDate = keyStore.getCreationDate(alias);
        if (creationDate != null) {
            SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_FORMAT);
            result.get(ElytronDescriptionConstants.CREATION_DATE).set(sdf.format(creationDate));
        }

        Certificate[] chain = keyStore.getCertificateChain(alias);
        if (chain == null) {
            Certificate cert = keyStore.getCertificate(alias);
            if (cert != null) {
                writeCertificate(result.get(ElytronDescriptionConstants.CERTIFICATE), cert);
            }
        } else {
            writeCertificates(result.get(ElytronDescriptionConstants.CERTIFICATE_CHAIN), chain);
        }
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateEncodingException e) {
        throw new OperationFailedException(e);
    }
}
 
Example 15
Source File: AdvancedModifiableKeyStoreDecorator.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void executeRuntimeStep(final OperationContext context, final ModelNode operation) throws OperationFailedException {
    ModifiableKeyStoreService keyStoreService = getModifiableKeyStoreService(context);
    KeyStore keyStore = keyStoreService.getModifiableValue();

    String alias = ALIAS.resolveModelAttribute(context, operation).asString();
    Long expiration = EXPIRATION.resolveModelAttribute(context, operation).asLong();

    try {
        if (! keyStore.containsAlias(alias)) {
            throw ROOT_LOGGER.keyStoreAliasDoesNotExist(alias);
        }
        X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
        if (certificate == null) {
            throw ROOT_LOGGER.unableToObtainCertificate(alias);
        }
        ZonedDateTime current = ZonedDateTime.now().withZoneSameInstant(ZoneId.of("UTC")).withNano(0);
        ZonedDateTime notAfter = ZonedDateTime.ofInstant(certificate.getNotAfter().toInstant(), ZoneId.of("UTC"));
        long daysToExpiry = ChronoUnit.DAYS.between(current, notAfter);
        ModelNode result = context.getResult();
        if (daysToExpiry <= 0) {
            // already expired
            result.get(ElytronDescriptionConstants.SHOULD_RENEW_CERTIFICATE).set(ModelNode.TRUE);
            daysToExpiry = 0;
        } else {
            if (daysToExpiry <= expiration) {
                result.get(ElytronDescriptionConstants.SHOULD_RENEW_CERTIFICATE).set(ModelNode.TRUE);
            } else {
                result.get(ElytronDescriptionConstants.SHOULD_RENEW_CERTIFICATE).set(ModelNode.FALSE);
            }
        }
        result.get(ElytronDescriptionConstants.DAYS_TO_EXPIRY).set(new ModelNode(daysToExpiry));
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }
}
 
Example 16
Source File: GarbageCollectorMXBeanAttributeHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
protected void executeReadAttribute(OperationContext context, ModelNode operation) throws OperationFailedException {

    final String gcName = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR)).getLastElement().getValue();
    final String name = operation.require(ModelDescriptionConstants.NAME).asString();

    GarbageCollectorMXBean gcMBean = null;

    for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) {
        if (gcName.equals(escapeMBeanName(mbean.getName()))) {
            gcMBean = mbean;
        }
    }

    if (gcMBean == null) {
        throw PlatformMBeanLogger.ROOT_LOGGER.unknownGarbageCollector(gcName);
    }

    if (PlatformMBeanConstants.OBJECT_NAME.getName().equals(name)) {
        final String objName = PlatformMBeanUtil.getObjectNameStringWithNameKey(ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE, gcName);
        context.getResult().set(objName);
    } else if (ModelDescriptionConstants.NAME.equals(name)) {
        context.getResult().set(escapeMBeanName(gcMBean.getName()));
    } else if (PlatformMBeanConstants.VALID.getName().equals(name)) {
        context.getResult().set(gcMBean.isValid());
    } else if (PlatformMBeanConstants.MEMORY_POOL_NAMES.equals(name)) {
        final ModelNode result = context.getResult();
        result.setEmptyList();
        for (String pool : gcMBean.getMemoryPoolNames()) {
            result.add(escapeMBeanName(pool));
        }
    } else if (PlatformMBeanConstants.COLLECTION_COUNT.equals(name)) {
        context.getResult().set(gcMBean.getCollectionCount());
    } else if (PlatformMBeanConstants.COLLECTION_TIME.equals(name)) {
        context.getResult().set(gcMBean.getCollectionTime());
    } else if (GarbageCollectorResourceDefinition.GARBAGE_COLLECTOR_READ_ATTRIBUTES.contains(name)
            || GarbageCollectorResourceDefinition.GARBAGE_COLLECTOR_METRICS.contains(name)) {
        // Bug
        throw PlatformMBeanLogger.ROOT_LOGGER.badReadAttributeImpl(name);
    } else {
        // Shouldn't happen; the global handler should reject
        throw unknownAttribute(operation);
    }

}
 
Example 17
Source File: ServerOperationsResolverHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {

    if (multiPhaseLocalContext.getLocalResponse().has(FAILURE_DESCRIPTION)) {
        // We do not allow failures on the host controllers in a 2-phase op
        context.setRollbackOnly();
    } else {

        // Temporary hack to prevent CompositeOperationHandler throwing away domain failure data
        context.attachIfAbsent(CompositeOperationHandler.DOMAIN_EXECUTION_KEY, Boolean.TRUE);

        // Figure out what server ops are needed to correspond to the domain op we have
        boolean nullDomainOp = hostControllerExecutionSupport.getDomainOperation() == null;
        // Transformed operations might need to simulate certain behavior, so allow read-only operations to be pushed as well
        final boolean pushToServers= operation.hasDefined(OPERATION_HEADERS) && operation.get(OPERATION_HEADERS, DOMAIN_PUSH_TO_SERVERS).asBoolean(false);

        HostControllerExecutionSupport.ServerOperationProvider provider = nullDomainOp
            ? NO_OP_PROVIDER
            : new HostControllerExecutionSupport.ServerOperationProvider() {
                @Override
                public Map<Set<ServerIdentity>, ModelNode> getServerOperations(ModelNode domainOp, PathAddress address) {

                    Map<Set<ServerIdentity>, ModelNode> ops = ServerOperationsResolverHandler.this.getServerOperations(context, domainOp, address, pushToServers);
                    for (Map.Entry<Set<ServerIdentity>, ModelNode> entry : ops.entrySet()) {
                        ModelNode op = entry.getValue();
                        //Remove the caller-type=user header
                        if (op.hasDefined(OPERATION_HEADERS, CALLER_TYPE) && op.get(OPERATION_HEADERS, CALLER_TYPE).asString().equals(USER)) {
                            op.get(OPERATION_HEADERS).remove(CALLER_TYPE);
                        }
                    }

                    HOST_CONTROLLER_LOGGER.tracef("Server ops for %s -- %s", domainOp, ops);
                    return ops;
                }
            };
        Map<ServerIdentity, ModelNode> serverOps = hostControllerExecutionSupport.getServerOps(provider);

        // Format that data and provide it to the coordinator
        ModelNode formattedServerOps = getFormattedServerOps(serverOps);
        if (! serverOps.isEmpty()) {
            final Set<String> serversStarting = new HashSet<>();
            for (Map.Entry<ServerIdentity, ModelNode> serverIdentityModelNodeEntry : serverOps.entrySet()) {
                String serverName = serverIdentityModelNodeEntry.getKey().getServerName();
                ServerStatus serverStatus = serverInventory.determineServerStatus(serverName);
                if (serverStatus == ServerStatus.STARTING) {
                    serversStarting.add(serverName);
                }
            }
            if (! serversStarting.isEmpty()) {
                throw HOST_CONTROLLER_LOGGER.serverManagementUnavailableDuringBoot(serversStarting.toString());
            }
        }

        if (multiPhaseLocalContext.isCoordinator()) {
            // We're the coordinator, so just stash the server ops in the multiphase context
            // for use in the rollout plan
            multiPhaseLocalContext.getLocalServerOps().set(formattedServerOps);
            if (HOST_CONTROLLER_LOGGER.isTraceEnabled()) {
                HOST_CONTROLLER_LOGGER.tracef("%s server ops local response node is %s", getClass().getSimpleName(), formattedServerOps);
            }
        } else {
            // We're not the coordinator, so we need to propagate the server ops
            // to the coordinator via the response we send in the prepare part of Stage.DONE
            // So, change the context result to the special format used for this data
            ModelNode localResult = nullDomainOp ? new ModelNode(IGNORED) : multiPhaseLocalContext.getLocalResponse().get(RESULT);
            ModelNode domainResult = hostControllerExecutionSupport.getFormattedDomainResult(localResult);

            ModelNode contextResult = context.getResult();
            contextResult.setEmptyObject();
            contextResult.get(DOMAIN_RESULTS).set(domainResult);
            contextResult.get(SERVER_OPERATIONS).set(formattedServerOps);


            if (HOST_CONTROLLER_LOGGER.isTraceEnabled()) {
                HOST_CONTROLLER_LOGGER.tracef("%s server ops remote response node is %s", getClass().getSimpleName(), contextResult);
            }

        }

    }
}
 
Example 18
Source File: DomainRolloutStepHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void pushToServers(final OperationContext context, final Map<ServerIdentity, ServerTaskExecutor.ExecutedServerRequest> submittedTasks,
                           final List<ServerTaskExecutor.ServerPreparedResponse> preparedResults, final BlockingTimeout blockingTimeout) throws OperationFailedException {

    final String localHostName = multiphaseContext.getLocalHostInfo().getLocalHostName();
    Map<String, ModelNode> hostResults = new HashMap<String, ModelNode>(multiphaseContext.getHostControllerPreparedResults());
    ModelNode coordinatorOps = multiphaseContext.getLocalContext().getLocalServerOps();
    if (coordinatorOps.isDefined()) {
        // Make a node structure that looks like a response from a remote slave
        ModelNode localNode = new ModelNode();
        localNode.get(RESULT, SERVER_OPERATIONS).set(coordinatorOps);
        hostResults.put(localHostName, localNode);
    }
    Map<String, Map<ServerIdentity, ModelNode>> opsByGroup = getOpsByGroup(hostResults);
    if (opsByGroup.size() > 0) {

        final ModelNode rolloutPlan = getRolloutPlan(this.providedRolloutPlan, opsByGroup);
        if (trace) {
            HOST_CONTROLLER_LOGGER.tracef("Rollout plan is %s", rolloutPlan);
        }

        final Transformers.TransformationInputs transformationInputs = Transformers.TransformationInputs.getOrCreate(context);
        final ServerTaskExecutor taskExecutor = new ServerTaskExecutor(context, submittedTasks, preparedResults) {

            @Override
            protected int execute(TransactionalProtocolClient.TransactionalOperationListener<ServerTaskExecutor.ServerOperation> listener, ServerIdentity server, ModelNode original) throws OperationFailedException {
                final String hostName = server.getHostName();
                ProxyController proxy = hostProxies.get(hostName);
                if (proxy == null) {
                    if (localHostName.equals(hostName)) {
                        // Use our server proxies
                        proxy = serverProxies.get(server.getServerName());
                    }
                    if (proxy == null) {
                        if (trace) {
                            HOST_CONTROLLER_LOGGER.tracef("No proxy for %s", server);
                        }
                        return -1;
                    }
                }
                // Transform the server-results
                final TransformingProxyController remoteProxyController = (TransformingProxyController) proxy;
                final OperationTransformer.TransformedOperation transformed = multiphaseContext.transformServerOperation(hostName, remoteProxyController, transformationInputs, original);
                final ModelNode transformedOperation = transformed.getTransformedOperation();
                final OperationResultTransformer resultTransformer = transformed.getResultTransformer();
                final TransactionalProtocolClient client = remoteProxyController.getProtocolClient();
                if (executeOperation(listener, client, server, transformedOperation, resultTransformer)) {
                    return blockingTimeout.getProxyBlockingTimeout(server.toPathAddress(), remoteProxyController);
                } else {
                    return -1;
                }
            }
        };
        RolloutPlanController rolloutPlanController = new RolloutPlanController(opsByGroup, rolloutPlan,
                multiphaseContext, taskExecutor, executorService, blockingTimeout);
        RolloutPlanController.Result planResult = rolloutPlanController.execute();
        if (trace) {
            HOST_CONTROLLER_LOGGER.tracef("Rollout plan result is %s", planResult);
        }
        if (planResult == RolloutPlanController.Result.FAILED ||
                (planResult == RolloutPlanController.Result.PARTIAL && multiphaseContext.isCompleteRollback())) {
            multiphaseContext.setCompleteRollback(true);
            // AS7-801 -- we need to record a failure description here so the local host change gets aborted
            // Waiting to do it in the DomainFinalResultHandler on the way out is too late
            // Create the result node first so the server results will end up before the failure stuff
            context.getResult();
            context.getFailureDescription().set(DomainControllerLogger.HOST_CONTROLLER_LOGGER.operationFailedOrRolledBack());
            multiphaseContext.setFailureReported(true);
        }
    }
}
 
Example 19
Source File: ReadChildrenNamesHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {

    final PathAddress address = context.getCurrentAddress();
    final String childType = CHILD_TYPE.resolveModelAttribute(context, operation).asString();
    final Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS, false);
    ImmutableManagementResourceRegistration registry = context.getResourceRegistration();
    Map<String, Set<String>> childAddresses = GlobalOperationHandlers.getChildAddresses(context, address, registry, resource, childType);
    Set<String> childNames = childAddresses.get(childType);
    if (childNames == null) {
        throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.unknownChildType(childType));
    }
    final boolean singletons = INCLUDE_SINGLETONS.resolveModelAttribute(context, operation).asBoolean(false);
    if (singletons && isSingletonResource(registry, childType)) {
        Set<PathElement> childTypes = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS);
        for (PathElement child : childTypes) {
            if (childType.equals(child.getKey())) {
                childNames.add(child.getValue());
            }
        }
    }
    // Sort the result
    childNames = new TreeSet<String>(childNames);
    ModelNode result = context.getResult();
    result.setEmptyList();
    PathAddress childAddress = address.append(PathElement.pathElement(childType));
    ModelNode op = Util.createEmptyOperation(READ_RESOURCE_OPERATION, childAddress);
    op.get(OPERATION_HEADERS).set(operation.get(OPERATION_HEADERS));
    ModelNode opAddr = op.get(OP_ADDR);
    ModelNode childProperty = opAddr.require(address.size());
    Set<Action.ActionEffect> actionEffects = EnumSet.of(Action.ActionEffect.ADDRESS);
    FilteredData fd = null;
    for (String childName : childNames) {
        childProperty.set(childType, new ModelNode(childName));
        if (context.authorize(op, actionEffects).getDecision() == AuthorizationResult.Decision.PERMIT) {
            result.add(childName);
        } else {
            if (fd == null) {
                fd = new FilteredData(address);
            }
            fd.addAccessRestrictedResource(childAddress);
        }
    }

    if (fd != null) {
        context.getResponseHeaders().get(ACCESS_CONTROL).set(fd.toModelNode());
    }
}
 
Example 20
Source File: ServerEnvironmentResourceDescription.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
    final ModelNode result = context.getResult();
    final String name = operation.require(NAME).asString();
    if (equals(name, BASE_DIR)) {
        set(result, environment.getServerBaseDir());
    }
    if (equals(name, CONFIG_DIR)) {
        set(result, environment.getServerConfigurationDir());
    }
    if (equals(name, CONFIG_FILE)) {
        set(result, environment.getServerConfigurationFile());
    }
    if (equals(name, DATA_DIR)) {
        set(result, environment.getServerDataDir());
    }
    if (equals(name, CONTENT_DIR)) {
        set(result, environment.getServerContentDir());
    }
    if (equals(name, DEPLOY_DIR)) {
        set(result, environment.getServerContentDir());
    }
    if (equals(name, EXT_DIRS)) {
        set(result, environment.getJavaExtDirs());
    }
    if (equals(name, HOME_DIR)) {
        set(result, environment.getHomeDir());
    }
    if (equals(name, HOST_NAME)) {
        set(result, environment.getHostName());
    }
    if (equals(name, LAUNCH_TYPE)) {
        set(result, environment.getLaunchType().name());
    }
    if (equals(name, INITIAL_RUNNING_MODE)) {
        set(result, environment.getInitialRunningMode().name());
    }
    if (equals(name, LOG_DIR)) {
        set(result, environment.getServerLogDir());
    }
    if (equals(name, MODULES_DIR)) {
        @SuppressWarnings("deprecation")
        File modules = environment.getModulesDir();
        set(result, modules);
    }
    if (equals(name, NODE_NAME)) {
        set(result, environment.getNodeName());
    }
    if (equals(name, QUALIFIED_HOST_NAME)) {
        set(result, environment.getQualifiedHostName());
    }
    if (equals(name, SERVER_NAME)) {
        set(result, environment.getServerName());
    }
    if (equals(name, TEMP_DIR)) {
        set(result, environment.getServerTempDir());
    }
}