Java Code Examples for org.jboss.as.controller.OperationContext

The following examples show how to use org.jboss.as.controller.OperationContext. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
private void cleanStartServers(final ModelNode servers, final ModelNode domainModel, OperationContext context) throws OperationFailedException {
    Map<String, ProcessInfo> processInfos = serverInventory.determineRunningProcesses();
    for(final Property serverProp : servers.asPropertyList()) {
        String serverName = serverProp.getName();
        if (ServerConfigResourceDefinition.AUTO_START.resolveModelAttribute(context, serverProp.getValue()).asBoolean(true)) {
            ProcessInfo info = processInfos.get(serverInventory.getServerProcessName(serverName));
            if ( info != null ){
                serverInventory.reconnectServer(serverName, domainModel, info.getAuthKey(), info.isRunning(), info.isStopping());
            } else {
                try {
                    serverInventory.startServer(serverName, domainModel, START_BLOCKING, false);
                } catch (Exception e) {
                    ROOT_LOGGER.failedToStartServer(e, serverName);
                }
            }
        }
    }
}
 
Example 2
private void validateRuntimeNames(String deploymentName, OperationContext context) throws OperationFailedException {
    ModelNode deployment = context.readResource(PathAddress.EMPTY_ADDRESS).getModel();

    if (ENABLED.resolveModelAttribute(context, deployment).asBoolean()) {
        String runtimeName = getRuntimeName(deploymentName, deployment);
        Resource root = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS);
        for (Resource.ResourceEntry re : root.getChildren(DEPLOYMENT)) {
            String reName = re.getName();
            if (!deploymentName.equals(reName)) {
                ModelNode otherDepl = re.getModel();
                if (ENABLED.resolveModelAttribute(context, otherDepl).asBoolean()) {
                    String otherRuntimeName = getRuntimeName(reName, otherDepl);
                    if (runtimeName.equals(otherRuntimeName)) {
                        throw ServerLogger.ROOT_LOGGER.runtimeNameMustBeUnique(reName, runtimeName);
                    }
                }
            }
        }
    }
}
 
Example 3
@Override
protected OperationStepHandler additionalModelStep(final LogContextConfiguration logContextConfiguration) {
    return new OperationStepHandler() {
        @Override
        public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
            // If we don't require runtime steps to be executed we need to discard records on the delayed handler
            if (!requiresRuntime(context)) {
                HandlerConfiguration configuration = logContextConfiguration.getHandlerConfiguration(context.getCurrentAddressValue());
                if (configuration != null) {
                    if (!(configuration.getInstance() instanceof DelayedHandler)) {
                        throw LoggingLogger.ROOT_LOGGER.invalidType(DelayedHandler.class, configuration.getInstance().getClass());
                    }
                    final DelayedHandler delayedHandler = (DelayedHandler) configuration.getInstance();
                    // Clear any previous handlers and close them, then add the new handler
                    final Handler[] current = delayedHandler.setHandlers(new Handler[] {new DiscardingHandler()});
                    if (current != null) {
                        for (Handler handler : current) {
                            handler.close();
                        }
                    }
                }
            }
        }
    };
}
 
Example 4
protected void updateOptionsAttribute(OperationContext context, ModelNode operation, String type) {

        final PathAddress operationAddress = PathAddress.pathAddress(operation.get(OP_ADDR));
        final PathAddress discoveryOptionsAddress = operationAddress.subAddress(0, operationAddress.size() - 1);
        final ModelNode discoveryOptions = Resource.Tools.readModel(context.readResourceFromRoot(discoveryOptionsAddress));

        // Get the current list of discovery options and remove the given discovery option
        // from the list to maintain the order
        final ModelNode currentList = discoveryOptions.get(ModelDescriptionConstants.OPTIONS);
        final String name = operationAddress.getLastElement().getValue();

        final ModelNode newList = new ModelNode().setEmptyList();
        for (ModelNode e : currentList.asList()) {
            final Property prop = e.asProperty();
            final String discoveryOptionType = prop.getName();
            final String discoveryOptionName = prop.getValue().get(ModelDescriptionConstants.NAME).asString();
            if (!(discoveryOptionType.equals(type) && discoveryOptionName.equals(name))) {
                newList.add(e);
            }
        }

        final ModelNode writeOp = Util.getWriteAttributeOperation(discoveryOptionsAddress, ModelDescriptionConstants.OPTIONS, newList);
        final OperationStepHandler writeHandler = context.getRootResourceRegistration().getSubModel(discoveryOptionsAddress).getOperationHandler(PathAddress.EMPTY_ADDRESS, WRITE_ATTRIBUTE_OPERATION);
        context.addStep(writeOp, writeHandler, OperationContext.Stage.MODEL);
    }
 
Example 5
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model)
        throws OperationFailedException {
    ServiceTarget serviceTarget = context.getServiceTarget();

    String address = context.getCurrentAddressValue();
    RuntimeCapability<?> primaryCapability = runtimeCapabilities[0];
    ServiceName primaryServiceName = toServiceName(primaryCapability, address);

    final String module = MODULE.resolveModelAttribute(context, model).asStringOrNull();
    final String className = CLASS_NAME.resolveModelAttribute(context, model).asString();

    final Map<String, String> configurationMap;
    configurationMap = CONFIGURATION.unwrap(context, model);

    ServiceBuilder<?> serviceBuilder = serviceTarget.addService(primaryServiceName);
    for (int i = 1; i < runtimeCapabilities.length; i++) {
        serviceBuilder.addAliases(toServiceName(runtimeCapabilities[i], address));
    }

    commonRequirements(serviceBuilder)
        .setInstance(new TrivialService<>(() -> createValue(module, className, configurationMap)))
        .setInitialMode(Mode.ACTIVE)
        .install();
}
 
Example 6
protected void initModel(ManagementModel managementModel, Resource modelControllerResource) {
    ManagementResourceRegistration rootRegistration = managementModel.getRootResourceRegistration();
    GlobalOperationHandlers.registerGlobalOperations(rootRegistration, processType);
    GlobalNotifications.registerGlobalNotifications(rootRegistration, processType);
    rootRegistration.registerOperationHandler(ValidateOperationHandler.DEFINITION, ValidateOperationHandler.INSTANCE);

    rootRegistration.registerOperationHandler(TestUtils.SETUP_OPERATION_DEF, new OperationStepHandler() {
        @Override
        public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
            ModelNode mainModel = new ModelNode();
            mainModel.get(SERVER, "serverA");  //Create an empty node to be got from the proxied model
            mainModel.get("profile", "profileA").get(NAME).set("Profile A");

            AbstractControllerTestBase.createModel(context, mainModel);
        }
    });

    rootRegistration.registerSubModel(ResourceBuilder.Factory.create(PathElement.pathElement("profile", "*"), new NonResolvingResourceDescriptionResolver())
            .addReadOnlyAttribute(TestUtils.createNillableAttribute("name",ModelType.STRING))
            .build());

    PathElement serverAElement = PathElement.pathElement(SERVER, "serverA");
    rootRegistration.registerProxyController(serverAElement, createProxyController(proxy.get(), PathAddress.pathAddress(serverAElement)));
}
 
Example 7
/**
 * {@inheritDoc}
 */
@Override
public void performBoottime(OperationContext context, ModelNode operation, final Resource resource)
        throws OperationFailedException {

    context.addStep(new AbstractDeploymentChainStep() {
        @Override
        protected void execute(DeploymentProcessorTarget processorTarget) {

            processorTarget.addDeploymentProcessor(RequestControllerExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_GLOBAL_REQUEST_CONTROLLER, new RequestControllerDeploymentUnitProcessor());
        }
    }, OperationContext.Stage.RUNTIME);

    int maxRequests = RequestControllerRootDefinition.MAX_REQUESTS.resolveModelAttribute(context, resource.getModel()).asInt();
    boolean trackIndividual = RequestControllerRootDefinition.TRACK_INDIVIDUAL_ENDPOINTS.resolveModelAttribute(context, resource.getModel()).asBoolean();

    RequestController requestController = new RequestController(trackIndividual);

    requestController.setMaxRequestCount(maxRequests);

    context.getServiceTarget().addService(RequestController.SERVICE_NAME, requestController)
            .addDependency(JBOSS_SUSPEND_CONTROLLER, SuspendController.class, requestController.getShutdownControllerInjectedValue())
            .install();

}
 
Example 8
/**
 * Store the deployment contents and attach a "transformed" slave operation to the operation context.
 *
 * @param context the operation context
 * @param operation the original operation
 * @param contentRepository the content repository
 * @return the hash of the uploaded deployment content
 * @throws IOException
 * @throws OperationFailedException
 */
public static byte[] storeContentAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws IOException, OperationFailedException {
    if (!operation.hasDefined(CONTENT)) {
        throw createFailureException(DomainControllerLogger.ROOT_LOGGER.invalidContentDeclaration());
    }
    final ModelNode content = operation.get(CONTENT).get(0);
    if (content.hasDefined(HASH)) {
        // This should be handled as part of the OSH
        throw createFailureException(DomainControllerLogger.ROOT_LOGGER.invalidContentDeclaration());
    }
    final byte[] hash = storeDeploymentContent(context, operation, contentRepository);

    // Clear the contents and update with the hash
    final ModelNode slave = operation.clone();
    slave.get(CONTENT).setEmptyList().add().get(HASH).set(hash);
    // Add the domain op transformer
    List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);
    if (transformers == null) {
        context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());
    }
    transformers.add(new CompositeOperationAwareTransmuter(slave));
    return hash;
}
 
Example 9
private static Map<String, String> resolveProperties( final OperationContext context, final ModelNode model) throws OperationFailedException {
    Map<String, String> configurationProperties;
    if (model.hasDefined(PROPERTY)) {
        List<Property> propertyList = model.require(PROPERTY).asPropertyList();
        configurationProperties = new HashMap<String, String>(propertyList.size());

        for (Property current : propertyList) {
            String propertyName = current.getName();
            ModelNode valueNode = PropertyResourceDefinition.VALUE.resolveModelAttribute(context, current.getValue());
            String value = valueNode.isDefined() ? valueNode.asString() : null;
            configurationProperties.put(propertyName, value);
        }
        configurationProperties = Collections.unmodifiableMap(configurationProperties);
    } else {
        configurationProperties = Collections.emptyMap();
    }
    return configurationProperties;
}
 
Example 10
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {

    ModelNode model = context.readResource(PathAddress.EMPTY_ADDRESS).getModel();
    AuthorizedAddress authorizedAddress = AuthorizedAddress.authorizeAddress(context, operation);

    String attribute = operation.require(ModelDescriptionConstants.NAME).asString();
    if (ActiveOperationResourceDefinition.OPERATION_NAME.getName().equals(attribute)) {
        if (authorizedAddress.isElided()) {
            context.getResult().set(HIDDEN);
        } else {
            context.getResult().set(model.get(attribute));
        }
    } else if (ActiveOperationResourceDefinition.ADDRESS.getName().equals(attribute)) {
        if (authorizedAddress.isElided()) {
            context.getResult().set(authorizedAddress.getAddress());
        } else {
            context.getResult().set(model.get(attribute));
        }
    } else {
        // Programming error
        throw new IllegalStateException();
    }
}
 
Example 11
private Supplier<CallbackHandlerService> addPropertiesAuthenticationService(OperationContext context, ModelNode properties, String realmName,
                                                ServiceTarget serviceTarget, ServiceBuilder<?> realmBuilder) throws OperationFailedException {

    final ServiceName propsServiceName = PropertiesCallbackHandler.ServiceUtil.createServiceName(realmName);
    final String path = PropertiesAuthenticationResourceDefinition.PATH.resolveModelAttribute(context, properties).asString();
    final ModelNode relativeToNode = PropertiesAuthenticationResourceDefinition.RELATIVE_TO.resolveModelAttribute(context, properties);
    final boolean plainText = PropertiesAuthenticationResourceDefinition.PLAIN_TEXT.resolveModelAttribute(context, properties).asBoolean();
    final String relativeTo = relativeToNode.isDefined() ? relativeToNode.asString() : null;

    final ServiceBuilder<?> builder = serviceTarget.addService(propsServiceName);
    final Consumer<CallbackHandlerService> chsConsumer = builder.provides(propsServiceName);
    Supplier<PathManager> pmSupplier = null;
    if (relativeTo != null) {
        pmSupplier = builder.requires(context.getCapabilityServiceName(PATH_MANAGER_CAPABILITY, PathManager.class));
        builder.requires(pathName(relativeTo));
    }
    builder.setInstance(new PropertiesCallbackHandler(chsConsumer, pmSupplier, realmName, path, relativeTo, plainText));
    builder.setInitialMode(ON_DEMAND);
    builder.install();

    return CallbackHandlerService.ServiceUtil.requires(realmBuilder, propsServiceName);
}
 
Example 12
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName,
                                       ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<PathUpdate> handbackHolder) throws OperationFailedException {
    final String pathName = context.getCurrentAddressValue();
    final PathEntry pathEntry = pathManager.getPathEntry(pathName);
    final PathEntry backup = new PathEntry(pathEntry);

    final PathEventContextImpl pathEventContext = pathManager.checkRestartRequired(context, pathName, Event.UPDATED);
    if (pathEventContext.isInstallServices()) {
        if (attributeName.equals(PATH)) {
            String pathVal = resolvedValue.asString();
            pathManager.changePath(pathName, pathVal);
            pathManager.changePathServices(context, pathName, pathVal);
        } else if (attributeName.equals(RELATIVE_TO)) {
            String relToVal = resolvedValue.isDefined() ?  resolvedValue.asString() : null;
            pathManager.changeRelativePath( pathName, relToVal, true);
            pathManager.changeRelativePathServices(context, pathName, relToVal);
        }
    }

    handbackHolder.setHandback(new PathUpdate(backup, pathEventContext));

    return false;
}
 
Example 13
@Override
public void handleResult(OperationContext.ResultAction resultAction, OperationContext context, ModelNode operation) {
    if(fakeOperationResponse != null && fakeOperationResponse.hasDefined(FAILURE_DESCRIPTION)) {
        context.getFailureDescription().set(fakeOperationResponse.get(FAILURE_DESCRIPTION));
        return;
    }
    // Report on filtering
    if (localFilteredData.hasFilteredData()) {
        context.getResponseHeaders().get(ACCESS_CONTROL).set(localFilteredData.toModelNode());
    }

    // Extract any failure info from the individual results and use them
    // to construct an overall failure description if necessary
    if (resultAction == OperationContext.ResultAction.ROLLBACK
            && !context.hasFailureDescription() && result.isDefined()) {
        String op = operation.require(OP).asString();
        Map<PathAddress, ModelNode> failures = new HashMap<PathAddress, ModelNode>();
        for (ModelNode resultItem : result.asList()) {
            if (resultItem.hasDefined(FAILURE_DESCRIPTION)) {
                final PathAddress failedAddress = PathAddress.pathAddress(resultItem.get(ADDRESS));
                ModelNode failedDesc = resultItem.get(FAILURE_DESCRIPTION);
                failures.put(failedAddress, failedDesc);
            }
        }

        if (failures.size() == 1) {
            Map.Entry<PathAddress, ModelNode> entry = failures.entrySet().iterator().next();
            if (entry.getValue().getType() == ModelType.STRING) {
                context.getFailureDescription().set(ControllerLogger.ROOT_LOGGER.wildcardOperationFailedAtSingleAddress(op, entry.getKey(), entry.getValue().asString()));
            } else {
                context.getFailureDescription().set(ControllerLogger.ROOT_LOGGER.wildcardOperationFailedAtSingleAddressWithComplexFailure(op, entry.getKey()));
            }
        } else if (failures.size() > 1) {
            context.getFailureDescription().set(ControllerLogger.ROOT_LOGGER.wildcardOperationFailedAtMultipleAddresses(op, failures.keySet()));
        }
    }
}
 
Example 14
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<Boolean> handbackHolder) throws OperationFailedException {
    final ModelNode model = Resource.Tools.readModel(context.readResource(PathAddress.EMPTY_ADDRESS));
    boolean handback = applyModelToRuntime(context, operation, model);
    handbackHolder.setHandback(handback);
    return handback;

}
 
Example 15
@Override
protected void performBoottime(final OperationContext context, final ModelNode operation, final ModelNode model)
        throws OperationFailedException {

    final Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS);
    final ModelNode node = Resource.Tools.readModel(resource);
    // get the minimum set of deployment permissions.
    final ModelNode deploymentPermissionsModel = node.get(DEPLOYMENT_PERMISSIONS_PATH.getKeyValuePair());
    final ModelNode minimumPermissionsNode = MINIMUM_PERMISSIONS.resolveModelAttribute(context, deploymentPermissionsModel);
    final List<PermissionFactory> minimumSet = this.retrievePermissionSet(context, minimumPermissionsNode);

    // get the maximum set of deployment permissions.
    ModelNode maximumPermissionsNode = MAXIMUM_PERMISSIONS.resolveModelAttribute(context, deploymentPermissionsModel);
    if (!maximumPermissionsNode.isDefined())
        maximumPermissionsNode = DEFAULT_MAXIMUM_SET;
    final List<PermissionFactory> maximumSet = this.retrievePermissionSet(context, maximumPermissionsNode);

    // validate the configured permissions - the minimum set must be implied by the maximum set.
    final FactoryPermissionCollection maxPermissionCollection = new FactoryPermissionCollection(maximumSet.toArray(new PermissionFactory[maximumSet.size()]));
    final StringBuilder failedPermissions = new StringBuilder();
    for (PermissionFactory factory : minimumSet) {
        Permission permission = factory.construct();
        if (!maxPermissionCollection.implies(permission)) {
            failedPermissions.append("\n\t\t").append(permission);
        }
    }
    if (failedPermissions.length() > 0) {
        throw SecurityManagerLogger.ROOT_LOGGER.invalidSubsystemConfiguration(failedPermissions);
    }

    // install the DUPs responsible for parsing and validating security permissions found in META-INF/permissions.xml.
    context.addStep(new AbstractDeploymentChainStep() {
        protected void execute(DeploymentProcessorTarget processorTarget) {
             processorTarget.addDeploymentProcessor(Constants.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_PERMISSIONS,
                     new PermissionsParserProcessor(minimumSet));
             processorTarget.addDeploymentProcessor(Constants.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_PERMISSIONS_VALIDATION,
                     new PermissionsValidationProcessor(maximumSet));
        }
    }, OperationContext.Stage.RUNTIME);
}
 
Example 16
@Override
protected void performRuntime(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
    String osb = ATTRIBUTE.resolveModelAttribute(context, resource.getModel()).asString();
    Service<Void> service = new AbstractService<Void>() {};
    ServiceBuilder sb = context.getServiceTarget().addService(ServiceName.of("wfcore-1106"), service);
    sb.requires(context.getCapabilityServiceName("org.wildfly.network.outbound-socket-binding", osb, OutboundSocketBinding.class));
    sb.install();
}
 
Example 17
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
    operation = operation.clone();
    operation.remove(OP);
    operation.remove(OP_ADDR);

    parameters = new HashMap<>();
    for (String key : operation.keys()) {
        parameters.put(key, operation.get(key));
    }
}
 
Example 18
@Override
protected void recoverServices(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException {
    final ConfigurationPersistence configurationPersistence = getConfigurationPersistence(context);
    if (configurationPersistence != null) {
        configurationPersistence.rollback();
        revertRuntime(context, operation, model, configurationPersistence);
    }
}
 
Example 19
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
    if (context.getProcessType() == ProcessType.SELF_CONTAINED) {
        throw ServerLogger.ROOT_LOGGER.cannotReadContentFromSelfContainedServer();
    }
    final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);
    ModelNode contentItemNode = getContentItem(deploymentResource);
    // Validate this op is available
    if (!isManaged(contentItemNode)) {
        throw ServerLogger.ROOT_LOGGER.cannotReadContentFromUnmanagedDeployment();
    }
    final byte[] deploymentHash = CONTENT_HASH.resolveModelAttribute(context, contentItemNode).asBytes();
    final ModelNode pathNode = DEPLOYMENT_CONTENT_PATH.resolveModelAttribute(context, operation);
    final String path;
    if(pathNode.isDefined()) {
        path = pathNode.asString();
    } else {
        path = "";
    }
    int depth = DEPTH.resolveModelAttribute(context, operation).asInt();
    boolean explodable = ARCHIVE.resolveModelAttribute(context, operation).asBoolean();
    try {
        for (ContentRepositoryElement content : contentRepository.listContent(deploymentHash, path, ContentFilter.Factory.createContentFilter(depth, explodable))) {
            ModelNode contentNode = new ModelNode();
            contentNode.get(PATH).set(content.getPath());
            contentNode.get(DIRECTORY).set(content.isFolder());
            if(!content.isFolder()) {
                contentNode.get(FILE_SIZE).set(content.getSize());
            }
            context.getResult().add(contentNode);
        }
    } catch (ExplodedContentException ex) {
        throw createFailureException(ex.toString());
    }
}
 
Example 20
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {

    // The backup of the original domain model, before we tinker with it
    final Resource original = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS);

    // Execute the delegate
    delegate.execute(context, operation);

    // Just a safety check
    assert context.isBooting() == false;
    if (context.isBooting()) {
        return;
    }

    // Validate references on the new model
    final Resource domain = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS);

    if (syncWithMaster(domain, hostElement)) {
        MasterDomainControllerClient masterDomainControllerClient = null;
        try {
            masterDomainControllerClient = (MasterDomainControllerClient) context.getServiceRegistry(false).getRequiredService(MasterDomainControllerClient.SERVICE_NAME).getValue();
        } catch (ServiceNotFoundException e) {
            // running in admin-only we shouldn't fail if the MDCC isn't available
            if (context.getRunningMode() == RunningMode.ADMIN_ONLY) {
                return;
            }
            throw e;
        }
        // This adds an immediate step to synchronize the model configuration before any other step will be executed
        masterDomainControllerClient.fetchAndSyncMissingConfiguration(context, original);
    }
}
 
Example 21
static boolean isVisible(OperationEntry operationEntry, OperationContext context) {
    Set<OperationEntry.Flag> flags = operationEntry.getFlags();
    return operationEntry.getType() == OperationEntry.EntryType.PUBLIC
            && !flags.contains(OperationEntry.Flag.HIDDEN)
            && (context.getProcessType() != ProcessType.DOMAIN_SERVER || flags.contains(OperationEntry.Flag.RUNTIME_ONLY)
            || flags.contains(OperationEntry.Flag.READ_ONLY));

}
 
Example 22
private void checkNoOtherProtocol(OperationContext context, ModelNode operation) throws OperationFailedException {
    PathAddress opAddr = PathAddress.pathAddress(operation.require(OP_ADDR));
    PathAddress addr = opAddr.subAddress(0, opAddr.size() - 1);
    Resource resource = context.readResourceFromRoot(addr);
    Set<ResourceEntry> existing = resource.getChildren(PROTOCOL);
    if (existing.size() > 1) {
        for (ResourceEntry entry : existing) {
            PathElement mine = addr.getLastElement();
            if (!entry.getPathElement().equals(mine)) {
                throw DomainManagementLogger.ROOT_LOGGER.sysLogProtocolAlreadyConfigured(addr.append(mine));
            }
        }
    }
}
 
Example 23
@Override
protected void setResult(OperationContext context, final String attributeName, final Service<?> service) {
    final EnhancedQueueExecutorService pool = (EnhancedQueueExecutorService) service;
    switch (attributeName) {
        case CommonAttributes.ACTIVE_COUNT:
            context.getResult().set(pool.getActiveCount());
            break;
        case CommonAttributes.COMPLETED_TASK_COUNT:
            context.getResult().set(pool.getCompletedTaskCount());
            break;
        case CommonAttributes.CURRENT_THREAD_COUNT:
            context.getResult().set(pool.getCurrentThreadCount());
            break;
        case CommonAttributes.LARGEST_THREAD_COUNT:
            context.getResult().set(pool.getLargestThreadCount());
            break;
        case CommonAttributes.REJECTED_COUNT:
            context.getResult().set(pool.getRejectedCount());
            break;
        case CommonAttributes.TASK_COUNT:
            context.getResult().set(pool.getTaskCount());
            break;
        case CommonAttributes.QUEUE_SIZE:
            context.getResult().set(pool.getQueueSize());
            break;
        default:
            // Programming bug. Throw a RuntimeException, not OFE, as this is not a client error
            throw ThreadsLogger.ROOT_LOGGER.unsupportedEnhancedQueueExecutorMetric(attributeName);
    }
}
 
Example 24
@Override
protected List<ServiceName> installServices(OperationContext context, NativeInterfaceCommonPolicy commonPolicy, ModelNode model)
        throws OperationFailedException {
    final ServiceTarget serviceTarget = context.getServiceTarget();

    final ServiceName endpointName = ManagementRemotingServices.MANAGEMENT_ENDPOINT;
    final String hostName = WildFlySecurityManager.getPropertyPrivileged(ServerEnvironment.NODE_NAME, null);

    NativeManagementServices.installManagementWorkerService(serviceTarget, context.getServiceRegistry(false));
    NativeManagementServices.installRemotingServicesIfNotInstalled(serviceTarget, hostName, context.getServiceRegistry(false));

    final String bindingName = SOCKET_BINDING.resolveModelAttribute(context, model).asString();
    ServiceName socketBindingServiceName = context.getCapabilityServiceName(SOCKET_BINDING_CAPABILITY_NAME, bindingName, SocketBinding.class);

    String securityRealm = commonPolicy.getSecurityRealm();
    String saslAuthenticationFactory = commonPolicy.getSaslAuthenticationFactory();
    if (saslAuthenticationFactory == null && securityRealm == null) {
        ServerLogger.ROOT_LOGGER.nativeManagementInterfaceIsUnsecured();
    }

    ServiceName securityRealmName = securityRealm != null ? SecurityRealm.ServiceUtil.createServiceName(securityRealm) : null;
    ServiceName saslAuthenticationFactoryName = saslAuthenticationFactory != null ? context.getCapabilityServiceName(
            SASL_AUTHENTICATION_FACTORY_CAPABILITY, saslAuthenticationFactory, SaslAuthenticationFactory.class) : null;
    String sslContext = commonPolicy.getSSLContext();
    ServiceName sslContextName = sslContext != null ? context.getCapabilityServiceName(SSL_CONTEXT_CAPABILITY, sslContext, SSLContext.class) : null;

    final ServiceName sbmName = context.getCapabilityServiceName("org.wildfly.management.socket-binding-manager", SocketBindingManager.class);

    ManagementRemotingServices.installConnectorServicesForSocketBinding(serviceTarget, endpointName,
                ManagementRemotingServices.MANAGEMENT_CONNECTOR,
                socketBindingServiceName, commonPolicy.getConnectorOptions(),
                securityRealmName, saslAuthenticationFactoryName, sslContextName, sbmName);
    return Arrays.asList(REMOTING_BASE.append("server", MANAGEMENT_CONNECTOR), socketBindingServiceName);
}
 
Example 25
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
    super.registerOperations(resourceRegistration);
    resourceRegistration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
    resourceRegistration.registerOperationHandler(TEST_OP, new OperationStepHandler() {
        @Override
        public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
            ServiceController<?> sc = context.getServiceRegistry(false).getService(createServiceName(context.getCurrentAddress()));
            context.getResult().set(sc != null);
        }
    });
}
 
Example 26
@Override
void initializeRemoteDomain(OperationContext context, ModelNode remoteDC) throws OperationFailedException {
    hostControllerInfo.setMasterDomainController(false);
    ModelNode protocolNode = DomainControllerWriteAttributeHandler.PROTOCOL.resolveModelAttribute(context, remoteDC);
    ModelNode hostNode = DomainControllerWriteAttributeHandler.HOST.resolveModelAttribute(context, remoteDC);
    ModelNode portNode = DomainControllerWriteAttributeHandler.PORT.resolveModelAttribute(context, remoteDC);
    if (hostNode.isDefined() && portNode.isDefined()) {
        String host = hostNode.asString();
        int port = portNode.asInt();
        String protocol = protocolNode.asString();
        StaticDiscovery staticDiscoveryOption = new StaticDiscovery(protocol, host, port);
        hostControllerInfo.addRemoteDomainControllerDiscoveryOption(staticDiscoveryOption);
    }
    ModelNode usernameNode = DomainControllerWriteAttributeHandler.USERNAME.resolveModelAttribute(context, remoteDC);
    if (usernameNode.isDefined()) {
        hostControllerInfo.setRemoteDomainControllerUsername(usernameNode.asString());
    }

    ModelNode ignoreUnusedConfiguration = DomainControllerWriteAttributeHandler.IGNORE_UNUSED_CONFIG.resolveModelAttribute(context, remoteDC);

    if (!ignoreUnusedConfiguration.isDefined()) {
        if (hostControllerInfo.isBackupDc()) { // started up with --backup, ignore-unused-configuration not set
            hostControllerInfo.setRemoteDomainControllerIgnoreUnaffectedConfiguration(false);
        } else {
            hostControllerInfo.setRemoteDomainControllerIgnoreUnaffectedConfiguration(true);
        }
    } else {
        hostControllerInfo.setRemoteDomainControllerIgnoreUnaffectedConfiguration(ignoreUnusedConfiguration.asBoolean());
    }
    AdminOnlyDomainConfigPolicy domainConfigPolicy
            = AdminOnlyDomainConfigPolicy.getPolicy(DomainControllerWriteAttributeHandler.ADMIN_ONLY_POLICY.resolveModelAttribute(context, remoteDC).asString());
    hostControllerInfo.setAdminOnlyDomainConfigPolicy(domainConfigPolicy);
    overallConfigPersister.initializeDomainConfigurationPersister(true);

    domainController.initializeSlaveDomainRegistry(rootRegistration, overallConfigPersister.getDomainPersister(), contentRepository, remoteFileRepository,
            hostControllerInfo, extensionRegistry, ignoredDomainResourceRegistry, pathManager);
}
 
Example 27
@Test
public void testSlaveServerBlockRollbackCancelSlave() throws Exception {
    long start = System.currentTimeMillis();
    Future<ModelNode> blockFuture = block("slave", "main-three", BlockerExtension.BlockPoint.ROLLBACK);
    String id = findActiveOperation(masterClient, "slave", "main-three", "block", OperationContext.ExecutionStatus.ROLLING_BACK, start);
    // Here we must pass 'true' to the 'serverOpOnly' param to ensure we cancel the server op, and not the non-blocking HC op
    cancel(masterClient, "slave", null, "block", null, start, true);
    ModelNode response = blockFuture.get(GET_TIMEOUT, TimeUnit.MILLISECONDS);
    // Server can't report it's failure as a prepared message in DONE because it doesn't get there. So master is
    // waiting for the initial report. The slave then cancelling releases the initial report but doesn't change
    // its outcome from FAILED. So master sees failure
    assertEquals(response.asString(), FAILED, response.get(OUTCOME).asString());
    validateNoActiveOperation(masterClient, "slave", "main-three", id, true);
}
 
Example 28
private static ConfigurationPersistence getConfigurationPersistence(final OperationContext context) {
    final PathAddress address = context.getCurrentAddress();
    final LogContext logContext;
    if (LoggingProfileOperations.isLoggingProfileAddress(address)) {
        logContext = LoggingProfileContextSelector.getInstance().get(LoggingProfileOperations.getLoggingProfileName(address));
    } else {
        logContext = LogContext.getLogContext();
    }
    return ConfigurationPersistence.getConfigurationPersistence(logContext);
}
 
Example 29
@Test
public void testSlaveBlockCompletionCancelMaster() throws Exception {
    long start = System.currentTimeMillis();
    Future<ModelNode> blockFuture = block("slave", null, BlockerExtension.BlockPoint.COMMIT);
    String id = findActiveOperation(masterClient, "slave", null, "block", OperationContext.ExecutionStatus.COMPLETING, start);
    cancel(masterClient, "master", null, "block", null, start, false);
    ModelNode response = blockFuture.get(GET_TIMEOUT, TimeUnit.MILLISECONDS);
    // The master may or may not be done with DomainSlaveHandler.execute and DomainRolloutStepHandler.execute
    // when cancelled. If yes, result is SUCCESS, if not result is CANCELLED
    assertSuccessOrCancelled(response);
    validateNoActiveOperation(masterClient, "slave", null, id, true);
}
 
Example 30
static ResourceDefinition getAddSuffixRoleMapperDefinition() {
    AbstractAddStepHandler add = new RoleMapperAddHandler(SUFFIX) {

        @Override
        protected ValueSupplier<RoleMapper> getValueSupplier(OperationContext context, ModelNode model) throws OperationFailedException {
            final String suffix = SUFFIX.resolveModelAttribute(context, model).asString();

            return () -> (Roles r) -> r.addSuffix(suffix);
        }

    };

    return new RoleMapperResourceDefinition(ElytronDescriptionConstants.ADD_SUFFIX_ROLE_MAPPER, add, SUFFIX);
}
 
Example 31
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName,
        ModelNode resolvedValue, ModelNode currentValue,
        org.jboss.as.controller.AbstractWriteAttributeHandler.HandbackHolder<Void> handbackHolder)
        throws OperationFailedException {
    if (!resolvedValue.equals(currentValue)) {
        if (!context.isBooting()) {
            return true;
        }
        updateAuthorizer(resolvedValue, configurableAuthorizer);
    }

    return false;
}
 
Example 32
@Override
protected void applyOperation(final OperationContext context, ModelNode operation, String attributeName,
                              ServiceController<?> service, boolean forRollback) {
    if (!forRollback) {
        // Programming bug. Throw a RuntimeException, not OFE, as this is not a client error
        throw ThreadsLogger.ROOT_LOGGER.unsupportedScheduledThreadPoolAttribute(attributeName);
    }
}
 
Example 33
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
    boolean forMe = context.getProcessType() == ProcessType.DOMAIN_SERVER;
    if (!forMe) {
        String targetHost = TARGET_HOST.resolveModelAttribute(context, operation).asStringOrNull();
        if (targetHost != null) {
            Set<String> hosts = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS, false).getChildrenNames(HOST);
            String name = hosts.size() > 1 ? "master": hosts.iterator().next();
            forMe = targetHost.equals(name);
        }
    }
    if (forMe) {
        context.addStep((ctx, op) -> ctx.getResult().set(true), OperationContext.Stage.RUNTIME);
    }
}
 
Example 34
/**
 * Provides a resource for the current step, either from the context, if the context doesn't have one
 * and {@code registry} is runtime-only, it creates a dummy resource.
 */
private static Resource nullSafeReadResource(final OperationContext context, final ImmutableManagementResourceRegistration registry) {

    Resource result;
    if (registry != null && registry.isRemote()) {
        try {
            // BES 2015/02/12 (WFCORE-539) -- following comment and use of 'true' I can't understand,
            // as the only use of 'resource' is to get the model or the children names,
            // neither of which needs the cloning behavior in OperationContextImpl.readResourceFromRoot

            //TODO check that having changed this from false to true does not break anything
            //If it does, consider adding a Resource.alwaysClone() method that can be used in
            //OperationContextImpl.readResourceFromRoot(final PathAddress address, final boolean recursive)
            //instead of the recursive check
            //result = context.readResource(PathAddress.EMPTY_ADDRESS, true);

            // BES 2015/02/12 -- So, back to 'false'
            result = context.readResource(PathAddress.EMPTY_ADDRESS, false);
        } catch (RuntimeException e) {
            result = PlaceholderResource.INSTANCE;
        }
    } else {
        // BES 2015/02/12 (WFCORE-539) -- following comment and use of 'true' I can't understand,
        // as the only use of 'resource' is to get the model or the children names,
        // neither of which needs the cloning behavior in OperationContextImpl.readResourceFromRoot

        //TODO check that having changed this from false to true does not break anything
        //If it does, consider adding a Resource.alwaysClone() method that can be used in
        //OperationContextImpl.readResourceFromRoot(final PathAddress address, final boolean recursive)
        //instead of the recursive check

        // BES 2015/02/12 -- So, back to 'false'
        result = context.readResource(PathAddress.EMPTY_ADDRESS, false);
    }
    return result;
}
 
Example 35
private static String[] getSaslServerAvailableMechanisms(OperationContext context) {
    RuntimeCapability<Void> runtimeCapability = SASL_SERVER_FACTORY_RUNTIME_CAPABILITY.fromBaseCapability(context.getCurrentAddressValue());
    ServiceName saslServerFactoryName = runtimeCapability.getCapabilityServiceName(SaslServerFactory.class);

    ServiceController<SaslServerFactory> serviceContainer = getRequiredService(context.getServiceRegistry(false), saslServerFactoryName, SaslServerFactory.class);
    if (serviceContainer.getState() != State.UP) {
        return null;
    }
    return serviceContainer.getValue().getMechanismNames(Collections.emptyMap());
}
 
Example 36
@Override
protected void initModel(ManagementModel managementModel) {
    ManagementResourceRegistration registration = managementModel.getRootResourceRegistration();
    GlobalOperationHandlers.registerGlobalOperations(registration, processType);
    GlobalNotifications.registerGlobalNotifications(registration, processType);

    ManagementResourceRegistration basicResourceRegistration = registration.registerSubModel(
            new SimpleResourceDefinition(PathElement.pathElement("subsystem", "basicSubsystem"), new NonResolvingResourceDescriptionResolver()));
    basicResourceRegistration.registerReadOnlyAttribute(TestUtils.createAttribute("first", ModelType.STRING, "group1", false), null);
    basicResourceRegistration.registerReadOnlyAttribute(TestUtils.createAttribute("second", ModelType.STRING, "group1", false), null);
    basicResourceRegistration.registerReadOnlyAttribute(TestUtils.createAttribute("third", ModelType.STRING, "group2", false), null);
    basicResourceRegistration.registerReadOnlyAttribute(TestUtils.createAttribute("fourth", ModelType.STRING, "group2", true), null);
    basicResourceRegistration.registerReadOnlyAttribute(TestUtils.createAttribute("fifth", ModelType.STRING, "group1", true), null);
    basicResourceRegistration.registerReadOnlyAttribute(TestUtils.createAttribute("sixth", ModelType.STRING, "group2", false, false), null);
    basicResourceRegistration.registerReadOnlyAttribute(TestUtils.createAttribute("seventh", ModelType.STRING, "group2", false, true), ShowModelAliasReadHandler.INSTANCE);
    basicResourceRegistration.registerReadOnlyAttribute(TestUtils.createAttribute("eigth", ModelType.STRING, "group1", false, false, true), null);

    registration.registerOperationHandler(TestUtils.SETUP_OPERATION_DEF, new OperationStepHandler() {
        @Override
        public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
            final ModelNode model = new ModelNode();
            //Atttributes
            model.get("subsystem", "basicSubsystem", "first").set("configuration1");
            model.get("subsystem", "basicSubsystem", "second").set(new ValueExpression("${my.value}"));
            model.get("subsystem", "basicSubsystem", "third").set("configuration3");
            model.get("subsystem", "basicSubsystem", "fourth").set("runtime4");
            model.get("subsystem", "basicSubsystem", "fifth").set("runtime5");
            model.get("subsystem", "basicSubsystem", "sixth").set("configuration6");
            model.get("subsystem", "basicSubsystem", "seventh").set("alias7");
            createModel(context, model);
        }
    }
    );
}
 
Example 37
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {

    final ThreadPoolManagementUtils.BaseThreadPoolParameters params =
            ThreadPoolManagementUtils.parseScheduledThreadPoolParameters(context, operation, model);
    ThreadPoolManagementUtils.removeThreadPoolService(params.getName(), addHandler.getCapability(), addHandler.getServiceNameBase(),
            params.getThreadFactory(), addHandler.getThreadFactoryResolver(),
            context);
}
 
Example 38
@Override
protected void performRuntime(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {

    // WFCORE-4510 -- the effective endpoint configuration is from the root subsystem resource,
    // not from the placeholder configuration=endpoint child resource.
    ModelNode endpointModel = resource.getModel();
    String workerName = WORKER.resolveModelAttribute(context, endpointModel).asString();

    final OptionMap map = EndpointConfigFactory.populate(context, endpointModel);

    // create endpoint
    final String nodeName = WildFlySecurityManager.getPropertyPrivileged(RemotingExtension.NODE_NAME_PROPERTY, null);

    // In case of a managed server the subsystem endpoint might already be installed {@see DomainServerCommunicationServices}
    if (context.getProcessType() == ProcessType.DOMAIN_SERVER) {
        final ServiceController<?> controller = context.getServiceRegistry(false).getService(RemotingServices.SUBSYSTEM_ENDPOINT);
        if (controller != null) {
            // if installed, just skip the rest
            return;
        }
    }

    final CapabilityServiceBuilder<?> builder = context.getCapabilityServiceTarget().addCapability(REMOTING_ENDPOINT_CAPABILITY);
    final Consumer<Endpoint> endpointConsumer = builder.provides(REMOTING_ENDPOINT_CAPABILITY);
    final Supplier<XnioWorker> workerSupplier = builder.requiresCapability(IO_WORKER_CAPABILITY_NAME, XnioWorker.class, workerName);
    builder.setInstance(new EndpointService(endpointConsumer, workerSupplier, nodeName, EndpointService.EndpointType.SUBSYSTEM, map));
    builder.install();
}
 
Example 39
static XnioWorker getXnioWorker(OperationContext context) {
    String name = context.getCurrentAddressValue();
    if (!context.getCurrentAddress().getLastElement().getKey().equals(IOExtension.WORKER_PATH.getKey())) { //we are somewhere deeper, lets find worker name
        for (PathElement pe : context.getCurrentAddress()) {
            if (pe.getKey().equals(IOExtension.WORKER_PATH.getKey())) {
                name = pe.getValue();
                break;
            }
        }
    }
    return getXnioWorker(context.getServiceRegistry(false), name);
}
 
Example 40
protected void rollbackRuntime(final OperationContext context, final ModelNode operation, final Resource resource) {
    getWorkerService(context).getBindingsTable().removeExact(
        Inet.parseCidrAddress(operation.require("match").asString()),
        new InetSocketAddress(
            Inet.parseInetAddress(operation.require("bind-address").asString()),
            operation.get("bind-port").asInt(0)
        )
    );
}