public ModelController createController(final ModelNode model, final Setup registration)
      throws InterruptedException {
    final ServiceController<?> existingController =
        serviceContainer.getService(ServiceName.of("ModelController"));
    if (existingController != null) {
      final CountDownLatch latch = new CountDownLatch(1);
      existingController.addListener(
          new AbstractServiceListener<Object>() {
            public void listenerAdded(ServiceController<?> serviceController) {
              serviceController.setMode(ServiceController.Mode.REMOVE);
            }

            public void transition(
                ServiceController<?> serviceController, ServiceController.Transition transition) {
              if (transition.equals(ServiceController.Transition.REMOVING_to_REMOVED)) {
                latch.countDown();
              }
            }
          });
      latch.await();
    }

    ServiceTarget target = serviceContainer.subTarget();
    ControlledProcessState processState = new ControlledProcessState(true);
    ModelControllerService svc = new ModelControllerService(processState, registration, model);
    ServiceBuilder<ModelController> builder =
        target.addService(ServiceName.of("ModelController"), svc);
    builder.install();
    svc.latch.await();
    ModelController controller = svc.getValue();
    ModelNode setup = Util.getEmptyOperation("setup", new ModelNode());
    controller.execute(setup, null, null, null);
    processState.setRunning();
    return controller;
  }
Beispiel #2
0
  @Test
  public void test() throws Exception {
    final ModelController controller = getController();

    final ModelNode address = new ModelNode();
    address.add("host", "*");
    address.add("server", "[one,two]");
    address.add("subsystem", "web");
    address.add("connector", "*");

    final ModelNode read = new ModelNode();
    read.get(OP).set("read-resource");
    read.get(OP_ADDR).set(address);

    ModelNode result = controller.execute(read, null, null, null);
    System.out.println(result);
    result = result.get("result");

    Assert.assertEquals(4, result.asInt()); // A,B one,two

    final ModelNode describe = new ModelNode();
    describe.get(OP).set("describe");
    describe.get(OP_ADDR).set(address);

    result = controller.execute(describe, null, null, null).get("result");
  }
  /**
   * Create a new controller with the passed in operations.
   *
   * @param additionalInit Additional initialization that should be done to the parsers, controller
   *     and service container before initializing our extension
   * @param bootOperations the operations
   */
  protected KernelServices installInController(
      AdditionalInitialization additionalInit, List<ModelNode> bootOperations) throws Exception {
    if (additionalInit == null) {
      additionalInit = new AdditionalInitialization();
    }
    ControllerInitializer controllerInitializer = additionalInit.createControllerInitializer();
    additionalInit.setupController(controllerInitializer);

    // Initialize the controller
    ServiceContainer container =
        ServiceContainer.Factory.create("test" + counter.incrementAndGet());
    ServiceTarget target = container.subTarget();
    ControlledProcessState processState = new ControlledProcessState(true);
    List<ModelNode> extraOps = controllerInitializer.initializeBootOperations();
    List<ModelNode> allOps = new ArrayList<ModelNode>();
    if (extraOps != null) {
      allOps.addAll(extraOps);
    }
    allOps.addAll(bootOperations);
    StringConfigurationPersister persister = new StringConfigurationPersister(allOps, testParser);
    ModelControllerService svc =
        new ModelControllerService(
            additionalInit.getType(),
            mainExtension,
            controllerInitializer,
            additionalInit,
            processState,
            persister,
            additionalInit.isValidateOperations());
    ServiceBuilder<ModelController> builder =
        target.addService(ServiceName.of("ModelController"), svc);
    builder.install();

    additionalInit.addExtraServices(target);

    // sharedState = svc.state;
    svc.latch.await();
    ModelController controller = svc.getValue();
    ModelNode setup = Util.getEmptyOperation("setup", new ModelNode());
    controller.execute(setup, null, null, null);
    processState.setRunning();

    KernelServices kernelServices =
        new KernelServices(
            container, controller, persister, new OperationValidator(svc.rootRegistration));
    this.kernelServices.add(kernelServices);
    if (svc.error != null) {
      throw svc.error;
    }

    return kernelServices;
  }
 private synchronized void establishModelControllerClient(ControlledProcessState.State state) {
   ModelControllerClient newClient = null;
   if (state != ControlledProcessState.State.STOPPING && serviceContainer != null) {
     @SuppressWarnings("unchecked")
     final Value<ModelController> controllerService =
         (Value<ModelController>) serviceContainer.getService(Services.JBOSS_SERVER_CONTROLLER);
     if (controllerService != null) {
       final ModelController controller = controllerService.getValue();
       newClient = controller.createClient(executorService);
     } // else TODO use some sort of timeout and poll. A non-stopping server should install a
     // ModelController very quickly
   }
   modelControllerClient = newClient;
   currentProcessState = state;
 }
 private void executeOperations(ModelController controller, List<ModelNode> ops) {
   for (final ModelNode op : ops) {
     op.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false);
     controller.execute(op, null, null, null);
   }
 }
 private ModelNode execute(ModelNode op) {
   return controller.execute(op, null, OperationTransactionControl.COMMIT, null);
 }
 private void executeOperations(ModelController controller, List<ModelNode> ops) {
   for (final ModelNode op : ops) {
     controller.execute(op, null, null, null);
   }
 }
  @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);
  }