Example #1
0
 public static ModelNode parseBoundedIntegerAttribute(
     final XMLExtendedStreamReader reader,
     final int index,
     final int minInclusive,
     final int maxInclusive,
     boolean allowExpression)
     throws XMLStreamException {
   final String stringValue = reader.getAttributeValue(index);
   if (allowExpression) {
     ModelNode expression = parsePossibleExpression(stringValue);
     if (expression.getType() == ModelType.EXPRESSION) {
       return expression;
     }
   }
   try {
     final int value = Integer.parseInt(stringValue);
     if (value < minInclusive || value > maxInclusive) {
       throw ControllerLogger.ROOT_LOGGER.invalidAttributeValue(
           value,
           reader.getAttributeName(index),
           minInclusive,
           maxInclusive,
           reader.getLocation());
     }
     return new ModelNode().set(value);
   } catch (NumberFormatException nfe) {
     throw ControllerLogger.ROOT_LOGGER.invalidAttributeValueInt(
         nfe, stringValue, reader.getAttributeName(index), reader.getLocation());
   }
 }
  @Override
  public ManagementResourceRegistration registerOverrideModel(
      String name, OverrideDescriptionProvider descriptionProvider) {
    Assert.checkNotNullParam("name", name);
    Assert.checkNotNullParam("descriptionProvider", descriptionProvider);

    if (parent == null) {
      throw ControllerLogger.ROOT_LOGGER.cannotOverrideRootRegistration();
    }

    if (!PathElement.WILDCARD_VALUE.equals(valueString)) {
      throw ControllerLogger.ROOT_LOGGER.cannotOverrideNonWildCardRegistration(valueString);
    }
    PathElement pe = PathElement.pathElement(parent.getKeyName(), name);

    final SimpleResourceDefinition rd =
        new SimpleResourceDefinition(
            pe,
            new OverrideDescriptionCombiner(
                getModelDescription(PathAddress.EMPTY_ADDRESS), descriptionProvider)) {

          @Override
          public List<AccessConstraintDefinition> getAccessConstraints() {
            return AbstractResourceRegistration.this.getAccessConstraints();
          }
        };
    return parent.getParent().registerSubModel(rd);
  }
 @Override
 public void unregisterOverrideModel(String name) {
   Assert.checkNotNullParam("name", name);
   if (PathElement.WILDCARD_VALUE.equals(name)) {
     throw ControllerLogger.ROOT_LOGGER.wildcardRegistrationIsNotAnOverride();
   }
   if (parent == null) {
     throw ControllerLogger.ROOT_LOGGER.rootRegistrationIsNotOverridable();
   }
   PathElement pe = PathElement.pathElement(parent.getKeyName(), name);
   parent.getParent().unregisterSubModel(pe);
 }
  @Override
  public void execute(OperationContext context, ModelNode operation)
      throws OperationFailedException {

    String operationName = NAME.resolveModelAttribute(context, operation).asString();
    boolean accessControl = ACCESS_CONTROL.resolveModelAttribute(context, operation).asBoolean();

    final DescribedOp describedOp =
        getDescribedOp(context, operationName, operation, !accessControl);
    if (describedOp == null
        || (context.getProcessType() == ProcessType.DOMAIN_SERVER
            && !describedOp.flags.contains(OperationEntry.Flag.RUNTIME_ONLY))) {
      throw new OperationFailedException(
          ControllerLogger.ROOT_LOGGER.operationNotRegistered(
              operationName, context.getCurrentAddress()));
    } else {
      ModelNode result = describedOp.getDescription();

      if (accessControl) {
        final PathAddress address = context.getCurrentAddress();
        ModelNode operationToCheck = Util.createOperation(operationName, address);
        operationToCheck.get(OPERATION_HEADERS).set(operation.get(OPERATION_HEADERS));
        AuthorizationResult authorizationResult = context.authorizeOperation(operationToCheck);
        result
            .get(ACCESS_CONTROL.getName(), EXECUTE)
            .set(authorizationResult.getDecision() == Decision.PERMIT);
      }

      context.getResult().set(result);
    }
  }
Example #5
0
 /**
  * Get an exception reporting a missing, required XML attribute.
  *
  * @param reader the stream reader
  * @param supportedElement the element that is to be used in place of the unsupported one.
  * @return the exception
  */
 public static XMLStreamException unsupportedElement(
     final XMLExtendedStreamReader reader, String supportedElement) {
   return ControllerLogger.ROOT_LOGGER.unsupportedElement(
       new QName(reader.getNamespaceURI(), reader.getLocalName(), reader.getPrefix()),
       reader.getLocation(),
       supportedElement);
 }
 /**
  * Sets the validator to use for validating list elements.
  *
  * @param elementValidator the validator
  * @return a builder that can be used to continue building the attribute definition
  * @throws java.lang.IllegalArgumentException if {@code elementValidator} is {@code null}
  */
 @SuppressWarnings("unchecked")
 public final BUILDER setElementValidator(ParameterValidator elementValidator) {
   if (elementValidator == null) {
     throw ControllerLogger.ROOT_LOGGER.nullVar("elementValidator");
   }
   this.elementValidator = elementValidator;
   // Setting an element validator invalidates any existing overall attribute validator
   this.validator = null;
   return (BUILDER) this;
 }
 protected void performRemove(
     OperationContext context, final ModelNode operation, final ModelNode model)
     throws OperationFailedException {
   final Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS);
   if (!requireNoChildResources() || resource.getChildTypes().isEmpty()) {
     context.removeResource(PathAddress.EMPTY_ADDRESS);
   } else {
     List<PathElement> children = getChildren(resource);
     throw ControllerLogger.ROOT_LOGGER.cannotRemoveResourceWithChildren(children);
   }
 }
 @Override
 public void registerProxyController(final PathElement address, final ProxyController controller)
     throws IllegalArgumentException {
   final AbstractResourceRegistration existing =
       getSubRegistration(PathAddress.pathAddress(address));
   if (existing != null && existing.getValueString().equals(address.getValue())) {
     throw ControllerLogger.ROOT_LOGGER.nodeAlreadyRegistered(existing.getLocationString());
   }
   getOrCreateSubregistry(address.getKey())
       .registerProxyController(address.getValue(), controller);
 }
Example #9
0
 /**
  * Get an exception reporting a missing, required XML attribute.
  *
  * @param reader the stream reader
  * @param required a set of enums whose toString method returns the attribute name
  * @return the exception
  */
 public static XMLStreamException missingRequired(
     final XMLExtendedStreamReader reader, final String... required) {
   final StringBuilder b = new StringBuilder();
   for (int i = 0; i < required.length; i++) {
     final String o = required[i];
     b.append(o);
     if (required.length > i + 1) {
       b.append(", ");
     }
   }
   return ControllerLogger.ROOT_LOGGER.missingRequiredAttributes(b, reader.getLocation());
 }
  /** {@inheritDoc} */
  @Override
  public final ManagementResourceRegistration getOverrideModel(String name) {

    Assert.checkNotNullParam("name", name);

    if (parent == null) {
      throw ControllerLogger.ROOT_LOGGER.cannotOverrideRootRegistration();
    }

    if (!PathElement.WILDCARD_VALUE.equals(valueString)) {
      throw ControllerLogger.ROOT_LOGGER.cannotOverrideNonWildCardRegistration(valueString);
    }
    PathElement pe = PathElement.pathElement(parent.getKeyName(), name);

    // TODO https://issues.jboss.org/browse/WFLY-2883
    //        ManagementResourceRegistration candidate =
    // parent.getParent().getSubModel(PathAddress.pathAddress(pe));
    //        // We may have gotten back the wildcard reg; detect this by checking for allowing
    // override
    //        return candidate.isAllowsOverride() ? null : candidate;
    return parent.getParent().getSubModel(PathAddress.pathAddress(pe));
  }
Example #11
0
 /**
  * Get an exception reporting a missing, required XML child element.
  *
  * @param reader the stream reader
  * @param required a set of enums whose toString method returns the attribute name
  * @return the exception
  */
 public static XMLStreamException missingOneOf(
     final XMLExtendedStreamReader reader, final Set<?> required) {
   final StringBuilder b = new StringBuilder();
   Iterator<?> iterator = required.iterator();
   while (iterator.hasNext()) {
     final Object o = iterator.next();
     b.append(o.toString());
     if (iterator.hasNext()) {
       b.append(", ");
     }
   }
   return ControllerLogger.ROOT_LOGGER.missingOneOf(b, reader.getLocation());
 }
Example #12
0
 @Override
 public void acquireControllerLock() {
   if (lockStep == null) {
     try {
       controller.acquireWriteLock(operationId, true);
       lockStep = activeStep;
     } catch (InterruptedException e) {
       cancelled = true;
       Thread.currentThread().interrupt();
       throw ControllerLogger.ROOT_LOGGER.operationCancelledAsynchronously();
     }
   }
 }
 private static void warnMultipleValidInterfaces(
     String interfaceName,
     Map<NetworkInterface, Set<InetAddress>> acceptable,
     NetworkInterface selectedInterface,
     InetAddress selectedAddress) {
   Set<String> nis = new HashSet<String>();
   Set<InetAddress> addresses = new HashSet<InetAddress>();
   for (Map.Entry<NetworkInterface, Set<InetAddress>> entry : acceptable.entrySet()) {
     nis.add(entry.getKey().getName());
     addresses.addAll(entry.getValue());
   }
   ControllerLogger.ROOT_LOGGER.multipleMatchingAddresses(
       interfaceName, addresses, nis, selectedAddress, selectedInterface.getName());
 }
  private AuthorizationResult authorize(
      PermissionCollection userPermissions, PermissionCollection requiredPermissions) {

    final Enumeration<Permission> enumeration = requiredPermissions.elements();
    while (enumeration.hasMoreElements()) {
      Permission requiredPermission = enumeration.nextElement();
      if (!userPermissions.implies(requiredPermission)) {
        return new AuthorizationResult(
            AuthorizationResult.Decision.DENY,
            new ModelNode(ControllerLogger.ROOT_LOGGER.permissionDenied()));
      }
    }
    return AuthorizationResult.PERMITTED;
  }
 @Override
 public ManagementResourceRegistration registerSubModel(
     final ResourceDefinition resourceDefinition) {
   if (resourceDefinition == null) {
     throw ControllerLogger.ROOT_LOGGER.nullVar("resourceDefinition");
   }
   final PathElement address = resourceDefinition.getPathElement();
   if (address == null) {
     throw ControllerLogger.ROOT_LOGGER.cannotRegisterSubmodelWithNullPath();
   }
   if (isRuntimeOnly()) {
     throw ControllerLogger.ROOT_LOGGER.cannotRegisterSubmodel();
   }
   final AbstractResourceRegistration existing =
       getSubRegistration(PathAddress.pathAddress(address));
   if (existing != null && existing.getValueString().equals(address.getValue())) {
     throw ControllerLogger.ROOT_LOGGER.nodeAlreadyRegistered(existing.getLocationString());
   }
   final String key = address.getKey();
   final NodeSubregistry child = getOrCreateSubregistry(key);
   final ManagementResourceRegistration resourceRegistration =
       child.register(address.getValue(), resourceDefinition, false);
   resourceDefinition.registerAttributes(resourceRegistration);
   resourceDefinition.registerOperations(resourceRegistration);
   resourceDefinition.registerChildren(resourceRegistration);
   if (constraintUtilizationRegistry != null
       && resourceDefinition instanceof ConstrainedResourceDefinition) {
     PathAddress childAddress = getPathAddress().append(address);
     List<AccessConstraintDefinition> constraintDefinitions =
         ((ConstrainedResourceDefinition) resourceDefinition).getAccessConstraints();
     for (AccessConstraintDefinition acd : constraintDefinitions) {
       constraintUtilizationRegistry.registerAccessConstraintResourceUtilization(
           acd.getKey(), childAddress);
     }
   }
   return resourceRegistration;
 }
  @Override
  public void registerAlias(PathElement address, AliasEntry alias) {
    RootInvocation rootInvocation = parent == null ? null : getRootInvocation();
    AbstractResourceRegistration root = rootInvocation == null ? this : rootInvocation.root;
    PathAddress myaddr =
        rootInvocation == null ? PathAddress.EMPTY_ADDRESS : rootInvocation.pathAddress;

    PathAddress targetAddress = alias.getTarget().getPathAddress();
    alias.setAddresses(targetAddress, myaddr.append(address));
    AbstractResourceRegistration target =
        (AbstractResourceRegistration) root.getSubModel(alias.getTargetAddress());
    if (target == null) {
      throw ControllerLogger.ROOT_LOGGER.aliasTargetResourceRegistrationNotFound(
          alias.getTargetAddress());
    }

    registerAlias(address, alias, target);
  }
  private void handleReadAttribute(OperationContext context, ModelNode operation) {

    if (ignoreOperationIfServerNotActive(context, operation)) {
      return;
    }

    final AddressControl addressControl = getAddressControl(context, operation);
    if (addressControl == null) {
      PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
      throw ControllerLogger.ROOT_LOGGER.managementResourceNotFound(address);
    }

    final String name = operation.require(ModelDescriptionConstants.NAME).asString();

    try {
      if (ROLES_ATTR_NAME.equals(name)) {
        String json = addressControl.getRolesAsJSON();
        reportRoles(context, json);
      } else if (QUEUE_NAMES.equals(name)) {
        String[] queues = addressControl.getQueueNames();
        reportListOfStrings(context, queues);
      } else if (NUMBER_OF_BYTES_PER_PAGE.equals(name)) {
        long l = addressControl.getNumberOfBytesPerPage();
        context.getResult().set(l);
      } else if (NUMBER_OF_PAGES.equals(name)) {
        int i = addressControl.getNumberOfPages();
        context.getResult().set(i);
      } else if (BINDING_NAMES.equals(name)) {
        String[] bindings = addressControl.getBindingNames();
        reportListOfStrings(context, bindings);
      } else {
        // Bug
        throw MessagingLogger.ROOT_LOGGER.unsupportedAttribute(name);
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      context.getFailureDescription().set(e.getLocalizedMessage());
    }

    context.stepCompleted();
  }
  @Override
  public boolean canRunAs(Set<String> mappedRoles, String runAsRole) {
    if (runAsRole == null) {
      return false;
    }

    boolean hasRole = authorizerConfiguration.hasRole(runAsRole);
    boolean isSuperUser = mappedRoles.contains(StandardRole.SUPERUSER.toString());

    /*
     * We only allow users to specify roles to run as if they are SuperUser, if the user is not SuperUser we need to be
     * careful to not provide a way for the user to test which roles actually exist.
     */

    if (isSuperUser && hasRole == false) {
      throw ControllerLogger.ROOT_LOGGER.unknownRole(runAsRole);
    }

    return hasRole && isSuperUser;
  }
 private void emitAttributeValueWrittenNotification(
     OperationContext context,
     PathAddress address,
     String attributeName,
     ModelNode oldValue,
     ModelNode newValue) {
   // only emit a notification if the value has been successfully changed
   if (oldValue.equals(newValue)) {
     return;
   }
   ModelNode data = new ModelNode();
   data.get(NAME.getName()).set(attributeName);
   data.get(GlobalNotifications.OLD_VALUE).set(oldValue);
   data.get(GlobalNotifications.NEW_VALUE).set(newValue);
   Notification notification =
       new Notification(
           ATTRIBUTE_VALUE_WRITTEN_NOTIFICATION,
           address,
           ControllerLogger.ROOT_LOGGER.attributeValueWritten(attributeName, oldValue, newValue),
           data);
   context.emit(notification);
 }
  @Override
  public void executeRuntimeStep(OperationContext context, ModelNode operation)
      throws OperationFailedException {
    final String attributeName = operation.require(ModelDescriptionConstants.NAME).asString();

    PathAddress pathAddress =
        PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR));
    String addressName = pathAddress.getElement(pathAddress.size() - 2).getValue();
    String roleName = pathAddress.getLastElement().getValue();

    final ServiceName serviceName =
        MessagingServices.getActiveMQServiceName(
            PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
    ServiceController<?> service = context.getServiceRegistry(false).getService(serviceName);
    ActiveMQServer server = ActiveMQServer.class.cast(service.getValue());
    AddressControl control =
        AddressControl.class.cast(
            server.getManagementService().getResource(ResourceNames.CORE_ADDRESS + addressName));

    if (control == null) {
      PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
      throw ControllerLogger.ROOT_LOGGER.managementResourceNotFound(address);
    }

    try {
      String rolesAsJSON = control.getRolesAsJSON();
      ModelNode res = ModelNode.fromJSONString(rolesAsJSON);
      ModelNode roles = ManagementUtil.convertSecurityRole(res);
      ModelNode matchedRole = findRole(roleName, roles);
      if (matchedRole == null || !matchedRole.hasDefined(attributeName)) {
        throw MessagingLogger.ROOT_LOGGER.unsupportedAttribute(attributeName);
      }
      boolean value = matchedRole.get(attributeName).asBoolean();
      context.getResult().set(value);
    } catch (Exception e) {
      context.getFailureDescription().set(e.getLocalizedMessage());
    }
  }
  @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);
  }
 @Override
 public AliasEntry getAliasEntry() {
   // Overridden by AliasResourceRegistration
   throw ControllerLogger.ROOT_LOGGER.resourceRegistrationIsNotAnAlias();
 }
  @Override
  public void execute(OperationContext context, ModelNode operation)
      throws OperationFailedException {
    NAME.validateOperation(operation);
    final ModelNode nameModel =
        GlobalOperationAttributes.NAME.resolveModelAttribute(context, operation);
    final PathAddress address = context.getCurrentAddress();
    final ImmutableManagementResourceRegistration registry = context.getResourceRegistration();
    if (registry == null) {
      throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.noSuchResourceType(address));
    }
    final boolean useEnhancedSyntax = containsEnhancedSyntax(nameModel.asString(), registry);
    final String attributeName;
    final String attributeExpression;
    if (useEnhancedSyntax) {
      attributeExpression = nameModel.asString();
      attributeName = extractAttributeName(nameModel.asString());
    } else {
      attributeName = nameModel.asString();
      attributeExpression = attributeName;
    }

    final AttributeAccess attributeAccess =
        registry.getAttributeAccess(PathAddress.EMPTY_ADDRESS, attributeName);
    if (attributeAccess == null) {
      throw new OperationFailedException(
          ControllerLogger.ROOT_LOGGER.unknownAttribute(attributeName));
    } else if (attributeAccess.getAccessType() != AttributeAccess.AccessType.READ_WRITE) {
      throw new OperationFailedException(
          ControllerLogger.ROOT_LOGGER.attributeNotWritable(attributeName));
    } else {

      // Authorize
      ModelNode currentValue;
      if (attributeAccess.getStorageType() == AttributeAccess.Storage.CONFIGURATION) {
        ModelNode model = context.readResourceForUpdate(PathAddress.EMPTY_ADDRESS).getModel();
        currentValue = model.has(attributeName) ? model.get(attributeName) : new ModelNode();
      } else {
        currentValue = new ModelNode();
      }
      AuthorizationResult authorizationResult =
          context.authorize(operation, attributeName, currentValue);
      if (authorizationResult.getDecision() == AuthorizationResult.Decision.DENY) {
        throw ControllerLogger.ROOT_LOGGER.unauthorized(
            operation.require(OP).asString(), address, authorizationResult.getExplanation());
      }

      if (attributeAccess.getStorageType() == AttributeAccess.Storage.CONFIGURATION
          && !registry.isRuntimeOnly()) {
        // if the attribute is stored in the configuration, we can read its
        // old and new value from the resource's model before and after executing its write handler
        final ModelNode oldValue = currentValue.clone();
        doExecuteInternal(
            context,
            operation,
            attributeAccess,
            attributeName,
            currentValue,
            useEnhancedSyntax,
            attributeExpression);
        ModelNode model = context.readResource(PathAddress.EMPTY_ADDRESS).getModel();
        ModelNode newValue = model.has(attributeName) ? model.get(attributeName) : new ModelNode();
        emitAttributeValueWrittenNotification(context, address, attributeName, oldValue, newValue);

      } else {
        assert attributeAccess.getStorageType() == AttributeAccess.Storage.RUNTIME;

        // if the attribute is a runtime attribute, its old and new values must
        // be read using the attribute's read handler and the write operation
        // must be sandwiched between the 2 calls to the read handler.
        // Each call to the read handlers will have their own results while
        // the call to the write handler will use this OSH context result.

        OperationContext.Stage currentStage = context.getCurrentStage();

        final ModelNode readAttributeOperation =
            Util.createOperation(READ_ATTRIBUTE_OPERATION, address);
        readAttributeOperation.get(NAME.getName()).set(attributeName);
        ReadAttributeHandler readAttributeHandler = new ReadAttributeHandler(null, null, false);

        // create 2 model nodes to store the result of the read-attribute operations
        // before and after writing the value
        final ModelNode oldValue = new ModelNode();
        final ModelNode newValue = new ModelNode();

        // We're going to add a bunch of steps, but we want them to execute right away
        // so we use the 'addFirst=true' param to addStep. That means we add them
        // in reverse order of how they will execute

        // 4th OSH is to emit the notification
        context.addStep(
            new OperationStepHandler() {
              @Override
              public void execute(OperationContext context, ModelNode operation)
                  throws OperationFailedException {
                // aggregate data from the 2 read-attribute operations
                emitAttributeValueWrittenNotification(
                    context, address, attributeName, oldValue.get(RESULT), newValue.get(RESULT));
              }
            },
            currentStage,
            true);

        // 3rd OSH is to read the new value
        context.addStep(newValue, readAttributeOperation, readAttributeHandler, currentStage, true);

        // 2nd OSH is to write the value
        context.addStep(
            new OperationStepHandler() {
              @Override
              public void execute(OperationContext context, ModelNode operation)
                  throws OperationFailedException {
                doExecuteInternal(
                    context,
                    operation,
                    attributeAccess,
                    attributeName,
                    oldValue.get(RESULT),
                    useEnhancedSyntax,
                    attributeExpression);
              }
            },
            currentStage,
            true);

        // 1st OSH is to read the old value
        context.addStep(oldValue, readAttributeOperation, readAttributeHandler, currentStage, true);
      }
    }
  }
Example #24
0
 IllegalStateException readOnlyContext() {
   return ControllerLogger.ROOT_LOGGER.readOnlyContext();
 }
Example #25
0
  @Override
  public void execute(OperationContext context, ModelNode operation)
      throws OperationFailedException {

    final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));
    final String childType = CHILD_TYPE.resolveModelAttribute(context, operation).asString();

    // Build up the op we're going to repeatedly execute
    final ModelNode readOp = new ModelNode();
    readOp.get(OP).set(READ_RESOURCE_OPERATION);
    INCLUDE_RUNTIME.validateAndSet(operation, readOp);
    RECURSIVE.validateAndSet(operation, readOp);
    RECURSIVE_DEPTH.validateAndSet(operation, readOp);
    PROXIES.validateAndSet(operation, readOp);
    INCLUDE_DEFAULTS.validateAndSet(operation, readOp);

    final Map<PathElement, ModelNode> resources = new HashMap<PathElement, ModelNode>();

    final Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS, false);
    final 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(
          new ModelNode().set(ControllerLogger.ROOT_LOGGER.unknownChildType(childType)));
    }

    // Track any excluded items
    FilteredData filteredData = new FilteredData(address);

    // We're going to add a bunch of steps that should immediately follow this one. We are going to
    // add them
    // in reverse order of how they should execute, building up a stack.

    // Last to execute is the handler that assembles the overall response from the pieces created by
    // all the other steps
    final ReadChildrenResourcesAssemblyHandler assemblyHandler =
        new ReadChildrenResourcesAssemblyHandler(resources, filteredData, address, childType);
    context.addStep(assemblyHandler, OperationContext.Stage.MODEL, true);

    for (final String key : childNames) {
      final PathElement childPath = PathElement.pathElement(childType, key);
      final PathAddress childAddress =
          PathAddress.EMPTY_ADDRESS.append(PathElement.pathElement(childType, key));

      final ModelNode readResOp = readOp.clone();
      readResOp.get(OP_ADDR).set(PathAddress.pathAddress(address, childPath).toModelNode());

      // See if there was an override registered for the standard :read-resource handling
      // (unlikely!!!)
      OperationStepHandler overrideHandler =
          context
              .getResourceRegistration()
              .getOperationHandler(childAddress, READ_RESOURCE_OPERATION);
      if (overrideHandler == null) {
        throw new OperationFailedException(
            new ModelNode().set(ControllerLogger.ROOT_LOGGER.noOperationHandler()));
      } else if (overrideHandler.getClass() == ReadResourceHandler.class) {
        // not an override
        overrideHandler = null;
      }
      OperationStepHandler rrHandler =
          new ReadResourceHandler(filteredData, overrideHandler, false);
      final ModelNode rrRsp = new ModelNode();
      resources.put(childPath, rrRsp);
      context.addStep(rrRsp, readResOp, rrHandler, OperationContext.Stage.MODEL, true);
    }

    context.stepCompleted();
  }
Example #26
0
 /**
  * Get an exception reporting an unexpected XML element.
  *
  * @param reader the stream reader
  * @return the exception
  */
 public static XMLStreamException unexpectedElement(
     final XMLExtendedStreamReader reader, Set<String> possible) {
   return ControllerLogger.ROOT_LOGGER.unexpectedElement(
       reader.getName(), asStringList(possible), reader.getLocation());
 }
  @Override
  public void execute(OperationContext context, ModelNode operation)
      throws OperationFailedException {
    ModelNode operationModel = new ModelNode();
    populateModel(operation, operationModel);
    String attributeName = NAME.resolveModelAttribute(context, operationModel).asString();
    final ImmutableManagementResourceRegistration registry = context.getResourceRegistration();
    final boolean useEnhancedSyntax = containsEnhancedSyntax(attributeName, registry);
    String attributeExpression = attributeName;
    if (useEnhancedSyntax) {
      attributeName = extractAttributeName(attributeName);
    }
    final AttributeAccess attributeAccess =
        context
            .getResourceRegistration()
            .getAttributeAccess(PathAddress.EMPTY_ADDRESS, attributeName);
    if (attributeAccess == null) {
      throw new OperationFailedException(
          ControllerLogger.ROOT_LOGGER.unknownAttribute(attributeName));
    }
    final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));

    final ModelNode readResponse = new ModelNode();

    // prepare write operation
    ModelNode writeOperation = Util.createOperation(WriteAttributeHandler.DEFINITION, address);
    writeOperation.get(NAME.getName()).set(useEnhancedSyntax ? attributeExpression : attributeName);
    ModelNode writeOperationValue =
        writeOperation.get(
            ModelDescriptionConstants.VALUE); // value will be set in modification step

    if (attributeAccess.getStorageType() == AttributeAccess.Storage.CONFIGURATION) {

      // Steps need to be performed before any other steps, so they are added in opposite order
      // with addFirst=true parameter.

      // 2. modify value and register writing step
      context.addStep(
          (context1, operation1) -> {
            updateModel(
                context,
                operationModel,
                attributeAccess.getAttributeDefinition(),
                readResponse.get(RESULT));

            // add write step
            if (requiredReadWriteAccess) {
              writeOperationValue.set(readResponse.get(RESULT));
              context.addStep(
                  writeOperation,
                  WriteAttributeHandler.INSTANCE,
                  OperationContext.Stage.MODEL,
                  true);
            }
          },
          OperationContext.Stage.MODEL,
          true);

      // 1. read current attribute value
      ModelNode readAttributeOperation =
          Util.getReadAttributeOperation(
              address, useEnhancedSyntax ? attributeExpression : attributeName);
      context.addStep(
          readResponse,
          readAttributeOperation,
          ReadAttributeHandler.INSTANCE,
          OperationContext.Stage.MODEL,
          true);
    } else {
      assert attributeAccess.getStorageType() == AttributeAccess.Storage.RUNTIME;

      // For Storage.RUNTIME attributes, attributes need to be registered with reader and writer
      // step handlers,
      // which must postpone reading / writing to RUNTIME stage (by registering new RUNTIME steps
      // which will
      // perform actual reading / writing).

      // Steps need to be performed before any other steps, so they are added in opposite order
      // with addFirst=true parameter.

      // 3. write modified value
      if (requiredReadWriteAccess) {
        context.addStep(
            readResponse,
            writeOperation,
            WriteAttributeHandler.INSTANCE,
            OperationContext.Stage.MODEL,
            true);
      }

      // 2. modify value
      context.addStep(
          (context1, operation1) -> {
            context.addStep(
                (context2, operation2) -> {
                  updateModel(
                      context2,
                      operationModel,
                      attributeAccess.getAttributeDefinition(),
                      readResponse.get(RESULT));
                  writeOperationValue.set(readResponse.get(RESULT));
                },
                OperationContext.Stage.RUNTIME);
          },
          OperationContext.Stage.MODEL,
          true);

      // 1. read current attribute value
      ModelNode readAttributeOperation =
          Util.getReadAttributeOperation(
              address, useEnhancedSyntax ? attributeExpression : attributeName);
      context.addStep(
          readResponse,
          readAttributeOperation,
          ReadAttributeHandler.INSTANCE,
          OperationContext.Stage.MODEL,
          true);
    }
  }
 private IllegalArgumentException operationNotRegisteredException(String op, PathElement address) {
   return ControllerLogger.ROOT_LOGGER.operationNotRegisteredException(
       op, PathAddress.pathAddress(address));
 }
 private IllegalArgumentException alreadyRegistered(final String type, final String name) {
   return ControllerLogger.ROOT_LOGGER.alreadyRegistered(type, name, getLocationString());
 }
Example #30
0
  private void parseSocketBindingGroup(
      final XMLExtendedStreamReader reader,
      final Set<String> interfaces,
      final ModelNode address,
      final Namespace expectedNs,
      final List<ModelNode> updates)
      throws XMLStreamException {

    // unique names for both socket-binding and outbound-socket-binding(s)
    final Set<String> uniqueBindingNames = new HashSet<String>();

    ModelNode op = Util.getEmptyOperation(ADD, null);
    // Handle attributes
    String socketBindingGroupName = null;

    final EnumSet<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.DEFAULT_INTERFACE);
    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
      final String value = reader.getAttributeValue(i);
      if (!isNoNamespaceAttribute(reader, i)) {
        throw unexpectedAttribute(reader, i);
      }
      final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      switch (attribute) {
        case NAME:
          {
            socketBindingGroupName = value;
            required.remove(attribute);
            break;
          }
        case DEFAULT_INTERFACE:
          {
            SocketBindingGroupResourceDefinition.DEFAULT_INTERFACE.parseAndSetParameter(
                value, op, reader);
            required.remove(attribute);
            break;
          }
        case PORT_OFFSET:
          {
            SocketBindingGroupResourceDefinition.PORT_OFFSET.parseAndSetParameter(
                value, op, reader);
            break;
          }
        default:
          throw ParseUtils.unexpectedAttribute(reader, i);
      }
    }

    if (!required.isEmpty()) {
      throw missingRequired(reader, required);
    }

    ModelNode groupAddress = address.clone().add(SOCKET_BINDING_GROUP, socketBindingGroupName);
    op.get(OP_ADDR).set(groupAddress);

    updates.add(op);

    // Handle elements
    while (reader.nextTag() != END_ELEMENT) {
      requireNamespace(reader, expectedNs);
      final Element element = Element.forName(reader.getLocalName());
      switch (element) {
        case SOCKET_BINDING:
          {
            // FIXME JBAS-8825
            final String bindingName =
                parseSocketBinding(reader, interfaces, groupAddress, updates);
            if (!uniqueBindingNames.add(bindingName)) {
              throw ControllerLogger.ROOT_LOGGER.alreadyDeclared(
                  Element.SOCKET_BINDING.getLocalName(),
                  Element.OUTBOUND_SOCKET_BINDING.getLocalName(),
                  bindingName,
                  Element.SOCKET_BINDING_GROUP.getLocalName(),
                  socketBindingGroupName,
                  reader.getLocation());
            }
            break;
          }
        case OUTBOUND_SOCKET_BINDING:
          {
            final String bindingName =
                parseOutboundSocketBinding(reader, interfaces, groupAddress, updates);
            if (!uniqueBindingNames.add(bindingName)) {
              throw ControllerLogger.ROOT_LOGGER.alreadyDeclared(
                  Element.SOCKET_BINDING.getLocalName(),
                  Element.OUTBOUND_SOCKET_BINDING.getLocalName(),
                  bindingName,
                  Element.SOCKET_BINDING_GROUP.getLocalName(),
                  socketBindingGroupName,
                  reader.getLocation());
            }
            break;
          }
        default:
          throw unexpectedElement(reader);
      }
    }
  }