Exemple #1
0
 private void cleanModel(final ModelNode attributeValue) {
   if (attributeValue.isDefined()) {
     for (ModelNode node : attributeValue.asList()) {
       node.remove(ANNOTATIONS);
       node.remove(SERVICES);
       node.remove(META_INF);
     }
   }
 }
 private ModelNode trimNonSubsystem(ModelNode definition) {
   ModelNode def = definition.clone();
   for (String key : def.get(CHILDREN).keys()) {
     if (!key.equals(SUBSYSTEM)) {
       def.remove(key);
     }
   }
   return def;
 }
 void updateModel(
     final OperationContext context,
     ModelNode model,
     AttributeDefinition attributeDefinition,
     ModelNode attribute)
     throws OperationFailedException {
   String key = KEY.resolveModelAttribute(context, model).asString();
   attribute.remove(key);
 }
  void execute(OperationContext context, ModelNode operation) throws OperationFailedException {

    ModelNode headers = operation.get(OPERATION_HEADERS);
    headers.remove(EXECUTE_FOR_COORDINATOR);
    final ModelNode missingResources =
        operation
            .get(OPERATION_HEADERS)
            .remove(DomainControllerRuntimeIgnoreTransformationRegistry.MISSING_DOMAIN_RESOURCES);

    if (headers.hasDefined(DomainControllerLockIdUtils.DOMAIN_CONTROLLER_LOCK_ID)) {
      int id = headers.remove(DomainControllerLockIdUtils.DOMAIN_CONTROLLER_LOCK_ID).asInt();
      context.attach(DomainControllerLockIdUtils.DOMAIN_CONTROLLER_LOCK_ID_ATTACHMENT, id);
    }

    final HostControllerExecutionSupport hostControllerExecutionSupport =
        addSteps(context, operation, null, true);

    // Add the missing resources step first
    if (missingResources != null) {
      ModelNode applyMissingResourcesOp =
          ApplyMissingDomainModelResourcesHandler.createPiggyBackedMissingDataOperation(
              missingResources);
      context.addStep(
          applyMissingResourcesOp,
          applyMissingDomainModelResourcesHandler,
          OperationContext.Stage.MODEL,
          true);
    }

    // In case the actual operation fails make sure the result still gets formatted
    context.completeStep(
        new OperationContext.RollbackHandler() {
          @Override
          public void handleRollback(OperationContext context, ModelNode operation) {
            if (hostControllerExecutionSupport.getDomainOperation() != null) {
              final ModelNode domainResult =
                  hostControllerExecutionSupport.getFormattedDomainResult(context.getResult());
              context.getResult().set(domainResult);
            }
          }
        });
  }
  private void addCacheNameToAddress(
      ModelNode cache, PathAddress containerAddress, String cacheType) {

    String name = cache.get(ModelKeys.NAME).asString();
    // setup the cache address
    PathAddress cacheAddress = containerAddress.append(cacheType, name);
    cache.get(ModelDescriptionConstants.OP_ADDR).set(cacheAddress.toModelNode());

    // get rid of NAME now that we are finished with it
    cache.remove(ModelKeys.NAME);
  }
 protected ModelNode createAddOperation(
     final ModelNode address, final ModelNode subModel, final Set<PathElement> children) {
   final ModelNode operation = subModel.clone();
   operation.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
   operation.get(ModelDescriptionConstants.OP_ADDR).set(address);
   if (children != null && !children.isEmpty()) {
     for (final PathElement path : children) {
       if (subModel.hasDefined(path.getKey())) {
         subModel.remove(path.getKey());
       }
     }
   }
   return operation;
 }
  private void parseInvalidationCache(
      XMLExtendedStreamReader reader, ModelNode containerAddress, List<ModelNode> operations)
      throws XMLStreamException {

    // ModelNode for the cache add operation
    ModelNode cache = Util.getEmptyOperation(ModelDescriptionConstants.ADD, null);

    for (int i = 0; i < reader.getAttributeCount(); i++) {
      String value = reader.getAttributeValue(i);
      Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      this.parseClusteredCacheAttribute(reader, i, attribute, value, cache);
    }

    if (!cache.hasDefined(ModelKeys.NAME)) {
      throw ParseUtils.missingRequired(reader, EnumSet.of(Attribute.NAME));
    }
    if (!cache.hasDefined(ModelKeys.MODE)) {
      throw ParseUtils.missingRequired(reader, EnumSet.of(Attribute.MODE));
    }

    while (reader.hasNext() && (reader.nextTag() != XMLStreamConstants.END_ELEMENT)) {
      Element element = Element.forName(reader.getLocalName());
      switch (element) {
        case STATE_TRANSFER:
          {
            this.parseStateTransfer(reader, cache.get(ModelKeys.STATE_TRANSFER).setEmptyObject());
            break;
          }
        default:
          {
            this.parseCacheElement(reader, element, cache);
          }
      }
    }
    String name = cache.get(ModelKeys.NAME).asString();
    // setup the cache address
    ModelNode cacheAddress = containerAddress.clone();
    cacheAddress.add(ModelKeys.INVALIDATION_CACHE, name);
    cacheAddress.protect();
    cache.get(ModelDescriptionConstants.OP_ADDR).set(cacheAddress);

    // get rid of NAME now that we are finished with it
    cache.remove(ModelKeys.NAME);

    operations.add(cache);
  }
  private void removeSubsystems(ModelNode description) {
    // TODO should remove all subsystems since they are tested in unit tests
    // but for now leave threads and remoting in since unit tests could not be created
    // for them due to circular maven dependencies

    ModelNode subsystemDescriptions = description.get(CHILDREN, SUBSYSTEM, MODEL_DESCRIPTION);
    Set<String> removes = new HashSet<String>();
    for (String key : subsystemDescriptions.keys()) {
      if (!key.equals(RemotingExtension.SUBSYSTEM_NAME)
          && !key.equals(ThreadsExtension.SUBSYSTEM_NAME)) {
        removes.add(key);
      }
    }

    for (String remove : removes) {
      subsystemDescriptions.remove(remove);
    }
  }
  private void parseLocalCache(
      XMLExtendedStreamReader reader, ModelNode containerAddress, List<ModelNode> operations)
      throws XMLStreamException {

    // ModelNode for the cache add operation
    ModelNode cache = Util.getEmptyOperation(ModelDescriptionConstants.ADD, null);

    // set the cache mode to local
    // cache.get(ModelKeys.MODE).set(Configuration.CacheMode.LOCAL.name());

    for (int i = 0; i < reader.getAttributeCount(); i++) {
      String value = reader.getAttributeValue(i);
      Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      this.parseCacheAttribute(reader, i, attribute, value, cache);
    }

    if (!cache.hasDefined(ModelKeys.NAME)) {
      throw ParseUtils.missingRequired(reader, EnumSet.of(Attribute.NAME));
    }

    while (reader.hasNext() && (reader.nextTag() != XMLStreamConstants.END_ELEMENT)) {
      Element element = Element.forName(reader.getLocalName());
      this.parseCacheElement(reader, element, cache);
    }

    String name = cache.get(ModelKeys.NAME).asString();
    // setup the cache address
    ModelNode cacheAddress = containerAddress.clone();
    cacheAddress.add(ModelKeys.LOCAL_CACHE, name);
    cacheAddress.protect();
    cache.get(ModelDescriptionConstants.OP_ADDR).set(cacheAddress);

    // get rid of NAME now that we are finished with it
    cache.remove(ModelKeys.NAME);

    operations.add(cache);
  }
 @Override
 public ModelNode fixModel(ModelNode modelNode) {
   modelNode.remove(SOCKET_BINDING_GROUP);
   modelNode.remove(PROFILE);
   return modelNode;
 }
  private void parseDistributedCache(
      XMLExtendedStreamReader reader, ModelNode containerAddress, List<ModelNode> operations)
      throws XMLStreamException {

    // ModelNode for the cache add operation
    ModelNode cache = Util.getEmptyOperation(ModelDescriptionConstants.ADD, null);

    for (int i = 0; i < reader.getAttributeCount(); i++) {
      String value = reader.getAttributeValue(i);
      Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      switch (attribute) {
        case OWNERS:
          {
            cache.get(ModelKeys.OWNERS).set(Integer.parseInt(value));
            break;
          }
        case VIRTUAL_NODES:
          {
            cache.get(ModelKeys.VIRTUAL_NODES).set(Integer.parseInt(value));
            break;
          }
        case L1_LIFESPAN:
          {
            cache.get(ModelKeys.L1_LIFESPAN).set(Long.parseLong(value));
            break;
          }
        default:
          {
            this.parseClusteredCacheAttribute(reader, i, attribute, value, cache);
          }
      }
    }

    if (!cache.hasDefined(ModelKeys.NAME)) {
      throw ParseUtils.missingRequired(reader, EnumSet.of(Attribute.NAME));
    }
    if (!cache.hasDefined(ModelKeys.MODE)) {
      throw ParseUtils.missingRequired(reader, EnumSet.of(Attribute.MODE));
    }

    while (reader.hasNext() && (reader.nextTag() != XMLStreamConstants.END_ELEMENT)) {
      Element element = Element.forName(reader.getLocalName());
      switch (element) {
        case REHASHING:
          {
            this.parseRehashing(reader, cache.get(ModelKeys.REHASHING).setEmptyObject());
            break;
          }
        default:
          {
            this.parseCacheElement(reader, element, cache);
          }
      }
    }

    String name = cache.get(ModelKeys.NAME).asString();
    // setup the cache address
    ModelNode cacheAddress = containerAddress.clone();
    cacheAddress.add(ModelKeys.DISTRIBUTED_CACHE, name);
    cacheAddress.protect();
    cache.get(ModelDescriptionConstants.OP_ADDR).set(cacheAddress);

    // get rid of NAME now that we are finished with it
    cache.remove(ModelKeys.NAME);

    operations.add(cache);
  }
  /** {@inheritDoc} */
  @Override
  public OperationResult execute(
      OperationContext context, ModelNode operation, ResultHandler resultHandler)
      throws OperationFailedException {

    validator.validate(operation);

    String name = operation.require(NAME).asString();
    String runtimeName =
        operation.hasDefined(RUNTIME_NAME) ? operation.get(RUNTIME_NAME).asString() : name;
    byte[] hash;
    if (operation.hasDefined(INPUT_STREAM_INDEX) && operation.hasDefined(HASH)) {
      throw new OperationFailedException(
          new ModelNode().set("Can't pass in both an input-stream-index and a hash"));
    } else if (operation.hasDefined(INPUT_STREAM_INDEX)) {
      InputStream in = getContents(context, operation);
      try {
        hash = deploymentRepository.addDeploymentContent(in);
      } catch (IOException e) {
        throw new OperationFailedException(new ModelNode().set(e.toString()));
      }
    } else if (operation.hasDefined(HASH)) {

      hash = operation.get(HASH).asBytes();
      if (!deploymentRepository.hasDeploymentContent(hash)) {
        throw new OperationFailedException(
            new ModelNode()
                .set(
                    String.format(
                        "No deployment content with hash %s is available in the deployment content repository.",
                        HashUtil.bytesToHexString(hash))));
      }
    } else {
      throw new OperationFailedException(
          new ModelNode().set("Neither an attachment or a hash were passed in"));
    }

    ModelNode rootModel = context.getSubModel();
    ModelNode deployments = rootModel.get(DEPLOYMENT);

    ModelNode replaceNode = deployments.hasDefined(name) ? deployments.get(name) : null;
    if (replaceNode == null) {
      throw new OperationFailedException(
          new ModelNode().set(String.format("No deployment with name %s found", name)));
    }

    boolean start = replaceNode.get(ENABLED).asBoolean();

    ModelNode deployNode = new ModelNode();
    deployNode.get(NAME).set(name);
    deployNode.get(RUNTIME_NAME).set(runtimeName);
    deployNode.get(HASH).set(hash);
    deployNode.get(ENABLED).set(start);

    deployments.get(name).set(deployNode);

    ModelNode compensatingOp = operation.clone();
    compensatingOp.get(RUNTIME_NAME).set(replaceNode.get(RUNTIME_NAME).asString());
    compensatingOp.get(HASH).set(replaceNode.get(HASH).asBytes());
    if (operation.hasDefined(INPUT_STREAM_INDEX)) {
      operation.remove(INPUT_STREAM_INDEX);
    }

    if (start) {
      DeploymentHandlerUtil.replace(deployNode, name, context, resultHandler);
    } else {
      resultHandler.handleResultComplete();
    }

    return new BasicOperationResult(compensatingOp);
  }
  @Override
  public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final FormDataParser parser = formParserFactory.createParser(exchange);
    if (parser == null) {
      Common.UNSUPPORTED_MEDIA_TYPE.handleRequest(exchange);
    }

    // Prevent CSRF which can occur from standard a multipart/form-data submission from a standard
    // HTML form.
    // If the browser sends an Origin header (Chrome / Webkit) then the earlier origin check will
    // have passed
    // to reach this point. If the browser doesn't (FireFox), then  only requests which came from
    // Javascript,
    // which enforces same-origin policy when no Origin header is present, should be allowed. The
    // presence of
    // a custom header indicates usage of XHR since simple forms can not set them.
    HeaderMap headers = exchange.getRequestHeaders();
    if (!headers.contains(Headers.ORIGIN) && !headers.contains(CLIENT_NAME)) {
      ROOT_LOGGER.debug(
          "HTTP Origin or X-Management-Client-Name header is required for all multipart form data posts.");
      Common.UNAUTHORIZED.handleRequest(exchange);
      return;
    }

    // Parse the form data
    final FormData data = parser.parseBlocking();
    final OperationParameter.Builder operationParameterBuilder =
        new OperationParameter.Builder(false);

    // Process the operation
    final FormData.FormValue op = data.getFirst(OPERATION);
    final ModelNode operation;
    try {
      String type = op.getHeaders().getFirst(Headers.CONTENT_TYPE);
      if (Common.APPLICATION_DMR_ENCODED.equals(type)) {
        try (InputStream stream = convertToStream(op)) {
          operation = ModelNode.fromBase64(stream);
        }
        operationParameterBuilder.encode(true);
      } else if (Common.APPLICATION_JSON.equals(stripSuffix(type))) {
        try (InputStream stream = convertToStream(op)) {
          operation = ModelNode.fromJSONStream(stream);
        }
      } else {
        ROOT_LOGGER.debug("Content-type must be application/dmr-encoded or application/json");
        Common.UNAUTHORIZED.handleRequest(exchange);
        return;
      }
    } catch (Exception e) {
      ROOT_LOGGER.errorf("Unable to construct ModelNode '%s'", e.getMessage());
      Common.sendError(exchange, false, e.getLocalizedMessage());
      return;
    }

    // Process the input streams
    final OperationBuilder builder = OperationBuilder.create(operation, true);
    final Iterator<String> i = data.iterator();
    while (i.hasNext()) {
      final String name = i.next();
      final Deque<FormData.FormValue> contents = data.get(name);
      if (contents != null && !contents.isEmpty()) {
        for (final FormData.FormValue value : contents) {
          if (value.isFile()) {
            builder.addFileAsAttachment(value.getPath().toFile());
          }
        }
      }
    }

    operationParameterBuilder.pretty(
        operation.hasDefined("json.pretty") && operation.get("json.pretty").asBoolean());
    // Response callback to handle the :reload operation
    final OperationParameter opParam = operationParameterBuilder.build();
    final ResponseCallback callback =
        new ResponseCallback() {
          @Override
          void doSendResponse(final ModelNode response) {
            if (response.hasDefined(OUTCOME) && FAILED.equals(response.get(OUTCOME).asString())) {
              Common.sendError(exchange, opParam.isEncode(), response);
              return;
            }
            writeResponse(exchange, 200, response, opParam);
          }
        };

    final boolean sendPreparedResponse = sendPreparedResponse(operation);
    final ModelController.OperationTransactionControl control =
        sendPreparedResponse
            ? new ModelController.OperationTransactionControl() {
              @Override
              public void operationPrepared(
                  final ModelController.OperationTransaction transaction, final ModelNode result) {
                transaction.commit();
                // Fix prepared result
                result.get(OUTCOME).set(SUCCESS);
                result.get(RESULT);
                callback.sendResponse(result);
              }
            }
            : ModelController.OperationTransactionControl.COMMIT;

    ModelNode response;
    final Operation builtOp = builder.build();
    try {
      ModelNode opheaders = operation.get(OPERATION_HEADERS);
      opheaders.get(ACCESS_MECHANISM).set(AccessMechanism.HTTP.toString());
      opheaders.get(CALLER_TYPE).set(USER);
      // Don't allow a domain-uuid operation header from a user call
      if (opheaders.hasDefined(DOMAIN_UUID)) {
        opheaders.remove(DOMAIN_UUID);
      }
      response =
          modelController.execute(operation, OperationMessageHandler.DISCARD, control, builtOp);
    } catch (Throwable t) {
      ROOT_LOGGER.modelRequestError(t);
      Common.sendError(exchange, opParam.isEncode(), t.getLocalizedMessage());
      return;
    } finally {
      // Close any input streams that were open
      if (builtOp.isAutoCloseStreams()) {
        for (InputStream in : builtOp.getInputStreams()) {
          IoUtils.safeClose(in);
        }
      }
    }

    callback.sendResponse(response);
  }