org.jboss.as.controller.OperationContext Java Examples

The following examples show how to use org.jboss.as.controller.OperationContext. 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: DeploymentAddHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #2
Source File: AbstractProxyControllerTest.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #3
Source File: SecureOperationReadHandler.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 {

    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 #4
Source File: SecurityRealmAddHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #5
Source File: CustomComponentDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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
Source File: DeploymentUploadUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #7
Source File: SecurityRealmAddHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #8
Source File: PathWriteAttributeHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #9
Source File: StartServersHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #10
Source File: RequestControllerSubsystemAdd.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@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 #11
Source File: AbstractDiscoveryOptionRemoveHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #12
Source File: SocketHandlerResourceDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #13
Source File: SecureDeploymentWriteAttributeHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName,
                                       ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<KeycloakAdapterConfigService> hh) throws OperationFailedException {
    KeycloakAdapterConfigService ckService = KeycloakAdapterConfigService.getInstance();
    hh.setHandback(ckService);
    ckService.updateSecureDeployment(operation, attributeName, resolvedValue);
    return false;
}
 
Example #14
Source File: GlobalOperationHandlers.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
static Locale getLocale(OperationContext context, final ModelNode operation) throws OperationFailedException {
    if (!operation.hasDefined(GlobalOperationAttributes.LOCALE.getName())) {
        return null;
    }
    String unparsed = normalizeLocale(operation.get(GlobalOperationAttributes.LOCALE.getName()).asString());
    try {
        return LocaleResolver.resolveLocale(unparsed);
    } catch (IllegalArgumentException e) {
        reportInvalidLocaleFormat(context, e.getMessage());
        return null;
    }
}
 
Example #15
Source File: RemotingEndpointResource.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 {
    PathAddress parent = context.getCurrentAddress().getParent();
    ModelNode parentOp = operation.clone();
    parentOp.get(OP_ADDR).set(parent.toModelNode());

    OperationStepHandler osh = context.getRootResourceRegistration().getOperationHandler(parent, operation.get(OP).asString());
    context.addStep(parentOp, osh, OperationContext.Stage.MODEL, true);
}
 
Example #16
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 #17
Source File: OperationCancellationTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
@Ignore("MSC-143")
public void testSlaveServerBlockServiceStartCancelMaster() throws Exception {
    long start = System.currentTimeMillis();
    Future<ModelNode> blockFuture = block("slave", "main-three", BlockerExtension.BlockPoint.SERVICE_START);
    String id = findActiveOperation(masterClient, "slave", "main-three", "block", OperationContext.ExecutionStatus.AWAITING_STABILITY, start);
    cancel(masterClient, "master", null, "block", null, start, false);
    ModelNode response = blockFuture.get(GET_TIMEOUT, TimeUnit.MILLISECONDS);
    assertEquals(response.asString(), CANCELLED, response.get(OUTCOME).asString());
    validateNoActiveOperation(masterClient, "slave", "main-three", id, true);
}
 
Example #18
Source File: SyncModelServerStateTestCase.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 ModelNode syncOperation = new ModelNode();
    syncOperation.get(OP).set("calculate-diff-and-sync");
    syncOperation.get(OP_ADDR).setEmptyList();
    syncOperation.get(DOMAIN_MODEL).set(operation.get(DOMAIN_MODEL));

    Resource original = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS);

    final HostControllerRegistrationHandler.OperationExecutor internalExecutor = getControllerService().getInternalExecutor();

    Map<String, ProxyController> serverProxies = new HashMap<>();
    for (Map.Entry<String, MockServerProxy> entry : SyncModelServerStateTestCase.this.serverProxies.entrySet()) {
        serverProxies.put(entry.getKey(), entry.getValue());
    }
    SyncModelParameters parameters =
            new SyncModelParameters(new MockDomainController(), ignoredDomainResourceRegistry,
                    hostControllerEnvironment, extensionRegistry, internalExecutor, true,
                    serverProxies, repository, repository);
    final Resource hostResource =
            context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS).getChildren(HOST).iterator().next();
    final ProductConfig cfg = new ProductConfig("product", "version", "main");
    final HostInfo hostInfo =
            HostInfo.fromModelNode(
                    HostInfo.createLocalHostHostInfo(hostControllerInfo,
                            cfg,
                            ignoredDomainResourceRegistry,
                            hostResource));
    final SyncDomainModelOperationHandler handler =
            new SyncDomainModelOperationHandler(hostInfo, parameters);
    context.addStep(syncOperation, handler, OperationContext.Stage.MODEL, true);
}
 
Example #19
Source File: OperationCoordinatorStepHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void routeToMasterDomainController(OperationContext context, ModelNode operation) {
    // Per discussion on 2011/03/07, routing requests from a slave to the
    // master may overly complicate the security infrastructure. Therefore,
    // the ability to do this is being disabled until it's clear that it's
    // not a problem
    context.getFailureDescription().set(DomainControllerLogger.HOST_CONTROLLER_LOGGER.masterDomainControllerOnlyOperation(operation.get(OP).asString(), PathAddress.pathAddress(operation.get(OP_ADDR))));
}
 
Example #20
Source File: LdapCacheResourceDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected LdapSearcherCache<?, K> lookupService(final OperationContext context, final ModelNode operation) throws OperationFailedException {
    String realmName = null;
    boolean forAuthentication = false;
    boolean forUserSearch = false;

    PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));
    for (PathElement current : address) {
        String key = current.getKey();
        if (SECURITY_REALM.equals(key)) {
            realmName = current.getValue();
        } else if (AUTHENTICATION.equals(key)) {
            forAuthentication = true;
            forUserSearch = true;
        } else if (AUTHORIZATION .equals(key)) {
            forAuthentication = false;
        } else if (USERNAME_TO_DN.equals(key)) {
            forUserSearch = true;
        } else if (GROUP_SEARCH.equals(key)) {
            forUserSearch = false;
        }
    }
    ServiceName serviceName = LdapSearcherCache.ServiceUtil.createServiceName(forAuthentication, forUserSearch, realmName);

    ServiceRegistry registry = context.getServiceRegistry(true);
    ServiceController<LdapSearcherCache<?, K>> service = (ServiceController<LdapSearcherCache<?, K>>) registry.getRequiredService(serviceName);

    try {
        return service.awaitValue();
    } catch (InterruptedException e) {
        throw new OperationFailedException(e);
    }
}
 
Example #21
Source File: OutboundBindAddressAddHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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)
        )
    );
}
 
Example #22
Source File: WorkerResourceDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #23
Source File: RemotingSubsystemAdd.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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 #24
Source File: AccessAuthorizationProviderWriteAttributeHander.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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 #25
Source File: ScheduledThreadPoolRemove.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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 #26
Source File: ReadAttributeGroupTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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 #27
Source File: SaslServerDefinitions.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #28
Source File: ReadResourceHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 #29
Source File: OpTypesExtension.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 {
    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 #30
Source File: ScheduledThreadPoolWriteAttributeHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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);
    }
}