void updatePoolService(final OperationContext context, final ModelNode model)
      throws OperationFailedException {

    final ModelNode poolName = poolAttribute.resolveModelAttribute(context, model);

    final ServiceRegistry serviceRegistry = context.getServiceRegistry(true);
    ServiceController existingDefaultPoolConfigService =
        serviceRegistry.getService(poolConfigServiceName);
    // if a default MDB pool is already installed, then remove it first
    if (existingDefaultPoolConfigService != null) {
      context.removeService(existingDefaultPoolConfigService);
    }

    if (poolName.isDefined()) {
      // now install default pool config service which points to an existing pool config service
      final ValueInjectionService<PoolConfig> newDefaultPoolConfigService =
          new ValueInjectionService<PoolConfig>();
      ServiceController<?> newController =
          context
              .getServiceTarget()
              .addService(poolConfigServiceName, newDefaultPoolConfigService)
              .addDependency(
                  PoolConfigService.EJB_POOL_CONFIG_BASE_SERVICE_NAME.append(poolName.asString()),
                  PoolConfig.class,
                  newDefaultPoolConfigService.getInjector())
              .install();
    }
  }
Пример #2
0
  @Override
  public void execute(OperationContext context, ModelNode operation)
      throws OperationFailedException {
    if (context.isNormalServer()
        && context.getServiceRegistry(false).getService(ModClusterService.NAME) != null) {
      context.addStep(
          new OperationStepHandler() {
            @Override
            public void execute(OperationContext context, ModelNode operation)
                throws OperationFailedException {
              ServiceController<?> controller =
                  context.getServiceRegistry(false).getService(ModClusterService.NAME);
              ModCluster modcluster = (ModCluster) controller.getValue();
              ROOT_LOGGER.debugf("remove-proxy: %s", operation);

              Proxy proxy = new Proxy(operation);
              modcluster.removeProxy(proxy.host, proxy.port);

              context.completeStep();
            }
          },
          OperationContext.Stage.RUNTIME);
    }

    context.completeStep();
  }
  @Override
  public void execute(OperationContext context, ModelNode operation)
      throws OperationFailedException {
    ModelNode newValue = operation.require(CacheContainerResource.PROTO_URL.getName());
    String urlString = newValue.asString();

    final PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
    final String cacheContainerName = address.getElement(address.size() - 1).getValue();
    final ServiceController<?> controller =
        context
            .getServiceRegistry(false)
            .getService(EmbeddedCacheManagerService.getServiceName(cacheContainerName));

    EmbeddedCacheManager cacheManager = (EmbeddedCacheManager) controller.getValue();
    ProtobufMetadataManager protoManager =
        cacheManager.getGlobalComponentRegistry().getComponent(ProtobufMetadataManager.class);
    if (protoManager != null) {
      try {
        URL url = new URL(urlString);
        protoManager.registerProtofile(url.openStream());
      } catch (Exception e) {
        throw new OperationFailedException(
            new ModelNode().set(MESSAGES.failedToInvokeOperation(e.getLocalizedMessage())));
      }
    }
    context.stepCompleted();
  }
Пример #4
0
  @Override
  public void execute(OperationContext context, ModelNode operation)
      throws OperationFailedException {
    if (context.isNormalServer()
        && context.getServiceRegistry(false).getService(ModClusterService.NAME) != null) {
      context.addStep(
          new OperationStepHandler() {
            @Override
            public void execute(OperationContext context, ModelNode operation)
                throws OperationFailedException {
              ServiceController<?> controller =
                  context.getServiceRegistry(false).getService(ModClusterService.NAME);
              ModCluster modcluster = (ModCluster) controller.getValue();
              Map<InetSocketAddress, String> map = modcluster.getProxyInfo();
              ROOT_LOGGER.debugf("Mod_cluster ProxyInfo %s", map);
              if (!map.isEmpty()) {
                final ModelNode result = new ModelNode();
                Object[] addr = map.keySet().toArray();
                for (int i = 0; i < addr.length; i++) {
                  InetSocketAddress address = (InetSocketAddress) addr[i];
                  result.add(address.getHostName() + ":" + address.getPort());
                  result.add(map.get(addr[i]));
                }
                context.getResult().set(result);
              }

              context.stepCompleted();
            }
          },
          OperationContext.Stage.RUNTIME);
    }

    context.stepCompleted();
  }
  @Override
  protected void executeRuntimeStep(OperationContext context, ModelNode operation)
      throws OperationFailedException {
    // Address is of the form:
    // /subsystem=infinispan/cache-container=*/*-cache=*/transaction=TRANSACTION
    PathAddress address = context.getCurrentAddress();
    String containerName = address.getElement(address.size() - 3).getValue();
    String cacheName = address.getElement(address.size() - 2).getValue();
    String name = operation.require(ModelDescriptionConstants.NAME).asString();

    TransactionMetric metric = TransactionMetric.forName(name);

    if (metric == null) {
      context.getFailureDescription().set(InfinispanLogger.ROOT_LOGGER.unknownMetric(name));
    } else {
      Cache<?, ?> cache =
          ServiceContainerHelper.findValue(
              context.getServiceRegistry(false),
              CacheServiceName.CACHE.getServiceName(containerName, cacheName));
      if (cache != null) {
        TxInterceptor interceptor = CacheMetric.findInterceptor(cache, TxInterceptor.class);
        context
            .getResult()
            .set((interceptor != null) ? metric.getValue(interceptor) : new ModelNode(0));
      }
    }
    context.completeStep(OperationContext.ResultHandler.NOOP_RESULT_HANDLER);
  }
Пример #6
0
  @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 (attributeName.equals(TrackerExtension.TICK)) {
      final String suffix =
          PathAddress.pathAddress(operation.get(ModelDescriptionConstants.ADDRESS))
              .getLastElement()
              .getValue();
      TrackerService service =
          (TrackerService)
              context
                  .getServiceRegistry(true)
                  .getRequiredService(TrackerService.createServiceName(suffix))
                  .getValue();
      service.setTick(resolvedValue.asLong());
      context.completeStep();
    }

    return false;
  }
Пример #7
0
  @Override
  protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model)
      throws OperationFailedException {

    ServiceRegistry registry = context.getServiceRegistry(false);
    final ServiceName serviceName =
        MessagingServices.getActiveMQServiceName(
            PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
    ServiceController<?> service = registry.getService(serviceName);
    if (service != null) {
      context.reloadRequired();
    } else {
      final PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
      final String name = address.getLastElement().getValue();

      final ServiceTarget target = context.getServiceTarget();
      if (model.hasDefined(JGROUPS_CHANNEL.getName())) {
        // nothing to do, in that case, the clustering.jgroups subsystem will have setup the stack
      } else if (model.hasDefined(RemoteTransportDefinition.SOCKET_BINDING.getName())) {
        final GroupBindingService bindingService = new GroupBindingService();
        target
            .addService(
                GroupBindingService.getBroadcastBaseServiceName(serviceName).append(name),
                bindingService)
            .addDependency(
                SocketBinding.JBOSS_BINDING_NAME.append(model.get(SOCKET_BINDING).asString()),
                SocketBinding.class,
                bindingService.getBindingRef())
            .install();
      }
    }
  }
Пример #8
0
  @Override
  public void execute(OperationContext context, ModelNode operation)
      throws OperationFailedException {
    if (context.isNormalServer()
        && context.getServiceRegistry(false).getService(ModClusterService.NAME) != null) {
      context.addStep(
          new OperationStepHandler() {
            @Override
            public void execute(OperationContext context, ModelNode operation)
                throws OperationFailedException {
              ServiceController<?> controller =
                  context.getServiceRegistry(false).getService(ModClusterService.NAME);
              ModCluster modcluster = (ModCluster) controller.getValue();
              ROOT_LOGGER.debugf("add-proxy: %s", operation);

              Proxy proxy = new Proxy(operation);
              modcluster.addProxy(proxy.host, proxy.port);

              // TODO AS7-5695 handle rollback
              context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
            }
          },
          OperationContext.Stage.RUNTIME);
    }

    context.stepCompleted();
  }
Пример #9
0
  @Override
  public void execute(OperationContext context, ModelNode operation)
      throws OperationFailedException {
    if (context.isNormalServer()
        && context.getServiceRegistry(false).getService(ModClusterService.NAME) != null) {
      context.addStep(
          new OperationStepHandler() {
            @Override
            public void execute(OperationContext context, ModelNode operation)
                throws OperationFailedException {
              ServiceController<?> controller =
                  context.getServiceRegistry(false).getService(ModClusterService.NAME);
              final ModCluster modcluster = (ModCluster) controller.getValue();
              ROOT_LOGGER.debugf("remove-proxy: %s", operation);

              final Proxy proxy = new Proxy(operation);
              modcluster.removeProxy(proxy.host, proxy.port);

              context.completeStep(
                  new OperationContext.RollbackHandler() {
                    @Override
                    public void handleRollback(OperationContext context, ModelNode operation) {
                      // TODO What if mod_cluster was never aware of this proxy?
                      modcluster.addProxy(proxy.host, proxy.port);
                    }
                  });
            }
          },
          OperationContext.Stage.RUNTIME);
    }

    context.stepCompleted();
  }
  /*    protected int getScaledCount(String attributeName, final ModelNode value) {
          if (!value.hasDefined(COUNT)) {
              throw new IllegalArgumentException("Missing '" + COUNT + "' for '" + attributeName + "'");
          }
          if (!value.hasDefined(PER_CPU)) {
              throw new IllegalArgumentException("Missing '" + PER_CPU + "' for '" + attributeName + "'");
          }

          final BigDecimal count;
          try {
              count = value.get(COUNT).asBigDecimal();
          } catch(NumberFormatException e) {
              throw new IllegalArgumentException("Failed to parse '" + COUNT + "' as java.math.BigDecimal", e);
          }
          final BigDecimal perCpu;
          try {
              perCpu = value.get(PER_CPU).asBigDecimal();
          } catch(NumberFormatException e) {
              throw new IllegalArgumentException("Failed to parse '" + PER_CPU + "' as java.math.BigDecimal", e);
          }

          return new ScaledCount(count, perCpu).getScaledCount();
      }
  */
  @Override
  protected ServiceController<?> getService(
      final OperationContext context, final ModelNode operation) throws OperationFailedException {
    final String name = Util.getNameFromAddress(operation.require(OP_ADDR));
    final ServiceName serviceName = ThreadsServices.executorName(name);
    ServiceController<?> controller = context.getServiceRegistry(true).getService(serviceName);
    if (controller == null) {
      throw new OperationFailedException(
          new ModelNode().set("Service " + serviceName + " not found."));
    }
    return controller;
  }
Пример #11
0
 private AddressControl getAddressControl(
     final OperationContext context, final ModelNode operation) {
   final String addressName =
       PathAddress.pathAddress(operation.require(OP_ADDR)).getLastElement().getValue();
   final ServiceName hqServiceName =
       MessagingServices.getHornetQServiceName(
           PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
   ServiceController<?> hqService = context.getServiceRegistry(false).getService(hqServiceName);
   HornetQServer hqServer = HornetQServer.class.cast(hqService.getValue());
   return AddressControl.class.cast(
       hqServer.getManagementService().getResource(ResourceNames.CORE_ADDRESS + addressName));
 }
Пример #12
0
  @Override
  public void execute(OperationContext context, ModelNode operation)
      throws OperationFailedException {
    if (context.isNormalServer()
        && context.getServiceRegistry(false).getService(ContainerEventHandlerService.SERVICE_NAME)
            != null) {
      context.addStep(
          new OperationStepHandler() {
            @Override
            public void execute(OperationContext context, ModelNode operation)
                throws OperationFailedException {
              ServiceController<?> controller =
                  context
                      .getServiceRegistry(false)
                      .getService(ContainerEventHandlerService.SERVICE_NAME);
              final ModClusterServiceMBean service = (ModClusterServiceMBean) controller.getValue();
              ROOT_LOGGER.debugf("stop-context: %s", operation);
              final ContextHost contexthost = new ContextHost(operation);

              try {
                service.stopContext(
                    contexthost.webhost,
                    contexthost.webcontext,
                    contexthost.waittime,
                    TimeUnit.SECONDS);
              } catch (IllegalArgumentException e) {
                throw new OperationFailedException(
                    new ModelNode()
                        .set(
                            ModClusterLogger.ROOT_LOGGER.ContextOrHostNotFound(
                                contexthost.webhost, contexthost.webcontext)));
              }

              context.completeStep(
                  new OperationContext.RollbackHandler() {
                    @Override
                    public void handleRollback(OperationContext context, ModelNode operation) {
                      // TODO We're assuming that the context was previously enabled, but it could
                      // have been disabled
                      service.enableContext(contexthost.webhost, contexthost.webcontext);
                    }
                  });
            }
          },
          OperationContext.Stage.RUNTIME);
    }

    context.stepCompleted();
  }
Пример #13
0
  void removeRuntimeServices(OperationContext context, ModelNode operation, ModelNode model)
      throws OperationFailedException {

    final PathAddress address = getCacheContainerAddressFromOperation(operation);
    final String containerName = address.getLastElement().getValue();

    // need to remove all container-related services started, in reverse order
    context.removeService(KeyAffinityServiceFactoryService.getServiceName(containerName));

    // remove the BinderService entry
    ModelNode resolvedValue = null;
    final String jndiName =
        (resolvedValue =
                    CacheContainerResourceDefinition.JNDI_NAME.resolveModelAttribute(
                        context, model))
                .isDefined()
            ? resolvedValue.asString()
            : null;
    context.removeService(
        createCacheContainerBinding(jndiName, containerName).getBinderServiceName());

    // remove the cache container
    context.removeService(EmbeddedCacheManagerService.getServiceName(containerName));
    context.removeService(EmbeddedCacheManagerConfigurationService.getServiceName(containerName));
    context.removeService(GlobalComponentRegistryService.getServiceName(containerName));

    // check if a channel was installed
    final ServiceName channelServiceName = ChannelService.getServiceName(containerName);
    final ServiceController<?> channelServiceController =
        context.getServiceRegistry(false).getService(channelServiceName);
    if (channelServiceController != null) {
      for (ChannelServiceProvider provider :
          ServiceLoader.load(
              ChannelServiceProvider.class, ChannelServiceProvider.class.getClassLoader())) {
        for (ServiceName name : provider.getServiceNames(containerName)) {
          context.removeService(name);
        }
      }
      // unregister the protocol metrics by adding a step
      ChannelInstanceResourceDefinition.addChannelProtocolMetricsDeregistrationStep(
          context, containerName);

      context.removeService(createChannelBinding(containerName).getBinderServiceName());
      context.removeService(channelServiceName);
    }
  }
Пример #14
0
 @Override
 protected void performRuntime(
     final OperationContext context,
     final ModelNode operation,
     final ModelNode model,
     final ServiceVerificationHandler verificationHandler,
     final List<ServiceController<?>> newControllers)
     throws OperationFailedException {
   final PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
   final String name = address.getLastElement().getValue();
   final ModelNode level = LEVEL.resolveModelAttribute(context, model);
   final ServiceRegistry serviceRegistry = context.getServiceRegistry(true);
   @SuppressWarnings("unchecked")
   final ServiceController<Logger> controller =
       (ServiceController<Logger>) serviceRegistry.getService(LogServices.loggerName(name));
   if (controller != null && level.isDefined()) {
     controller.getValue().setLevel(ModelParser.parseLevel(level));
   }
 }
Пример #15
0
  @Override
  protected void performRuntime(
      OperationContext context,
      ModelNode operation,
      ModelNode model,
      ServiceVerificationHandler verificationHandler,
      List<ServiceController<?>> newControllers)
      throws OperationFailedException {

    ServiceRegistry registry = context.getServiceRegistry(false);
    final ServiceName hqServiceName =
        MessagingServices.getHornetQServiceName(
            PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
    ServiceController<?> hqService = registry.getService(hqServiceName);
    if (hqService != null) {
      context.reloadRequired();
    }
    // else MessagingSubsystemAdd will add a handler that calls addConnectorServiceConfigs
  }
Пример #16
0
  @Override
  public void execute(OperationContext context, ModelNode operation)
      throws OperationFailedException {
    if (context.isNormalServer()
        && context.getServiceRegistry(false).getService(ModClusterService.NAME) != null) {
      context.addStep(
          new OperationStepHandler() {
            @Override
            public void execute(OperationContext context, ModelNode operation)
                throws OperationFailedException {
              ServiceController<?> controller =
                  context.getServiceRegistry(false).getService(ModClusterService.NAME);
              ModCluster modcluster = (ModCluster) controller.getValue();
              modcluster.disable();
              context.completeStep();
            }
          },
          OperationContext.Stage.RUNTIME);
    }

    context.completeStep();
  }
 @Override
 public void executeRuntimeStep(OperationContext context, ModelNode operation)
     throws OperationFailedException {
   final PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
   final String cacheContainerName = address.getElement(address.size() - 2).getValue();
   final String cacheName = address.getElement(address.size() - 1).getValue();
   final ServiceController<?> controller =
       context
           .getServiceRegistry(false)
           .getService(CacheServiceName.CACHE.getServiceName(cacheContainerName, cacheName));
   if (controller != null) {
     Cache<?, ?> cache = (Cache<?, ?>) controller.getValue();
     if (cache != null) {
       ComponentRegistry registry = SecurityActions.getComponentRegistry(cache.getAdvancedCache());
       LocalTopologyManagerImpl localTopologyManager =
           (LocalTopologyManagerImpl)
               registry.getGlobalComponentRegistry().getComponent(LocalTopologyManager.class);
       if (localTopologyManager != null) {
         try {
           if (operation.hasDefined(VALUE)) {
             ModelNode newValue = operation.get(VALUE);
             localTopologyManager.setCacheAvailability(
                 cacheName, AvailabilityMode.valueOf(newValue.asString()));
           } else {
             context
                 .getResult()
                 .set(
                     new ModelNode()
                         .set(localTopologyManager.getCacheAvailability(cacheName).toString()));
           }
         } catch (Exception e) {
           throw new OperationFailedException(
               new ModelNode().set(MESSAGES.failedToInvokeOperation(e.getLocalizedMessage())));
         }
       }
     }
   }
   context.stepCompleted();
 }
  @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());
    }
  }
Пример #19
0
  @Override
  protected void executeRuntimeStep(OperationContext context, ModelNode operation) {
    // Address is of the form: /subsystem=infinispan/cache-container=*/*-cache=*
    PathAddress address = context.getCurrentAddress();
    String containerName = address.getElement(address.size() - 2).getValue();
    String cacheName = address.getElement(address.size() - 1).getValue();
    String name = Operations.getAttributeName(operation);

    CacheMetric metric = CacheMetric.forName(name);

    if (metric == null) {
      context.getFailureDescription().set(InfinispanLogger.ROOT_LOGGER.unknownMetric(name));
    } else {
      Cache<?, ?> cache =
          ServiceContainerHelper.findValue(
              context.getServiceRegistry(false),
              CacheServiceName.CACHE.getServiceName(containerName, cacheName));
      if (cache != null) {
        context.getResult().set(metric.getValue(cache));
      }
    }
    context.completeStep(OperationContext.ResultHandler.NOOP_RESULT_HANDLER);
  }
    @Override
    public void execute(OperationContext context, ModelNode operation)
        throws OperationFailedException {
      PathAddress address = context.getCurrentAddress();
      String clsName = address.getLastElement().getValue();
      PathAddress parentAddress = address.getParent();
      final ModelNode subModel =
          context
              .readResourceFromRoot(
                  parentAddress
                      .subAddress(0, parentAddress.size() - 1)
                      .append(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME),
                  false)
              .getModel();
      final String host = VIRTUAL_HOST.resolveModelAttribute(context, subModel).asString();
      final String contextPath = CONTEXT_ROOT.resolveModelAttribute(context, subModel).asString();
      final String server = SERVER.resolveModelAttribute(context, subModel).asString();

      final ServiceController<?> controller =
          context
              .getServiceRegistry(false)
              .getService(UndertowService.deploymentServiceName(server, host, contextPath));
      final UndertowDeploymentService deploymentService =
          (UndertowDeploymentService) controller.getService();
      Servlet resteasyServlet = null;
      Handle handle = deploymentService.getDeployment().getThreadSetupAction().setup(null);
      try {
        for (Map.Entry<String, ServletHandler> servletHandler :
            deploymentService.getDeployment().getServlets().getServletHandlers().entrySet()) {
          if (HttpServletDispatcher.class.isAssignableFrom(
              servletHandler.getValue().getManagedServlet().getServletInfo().getServletClass())) {
            resteasyServlet =
                (Servlet) servletHandler.getValue().getManagedServlet().getServlet().getInstance();
            break;
          }
        }
        if (resteasyServlet != null) {
          final Collection<String> servletMappings =
              resteasyServlet
                  .getServletConfig()
                  .getServletContext()
                  .getServletRegistration(resteasyServlet.getServletConfig().getServletName())
                  .getMappings();
          final ResourceMethodRegistry registry =
              (ResourceMethodRegistry)
                  ((HttpServletDispatcher) resteasyServlet).getDispatcher().getRegistry();
          context.addStep(
              new OperationStepHandler() {
                @Override
                public void execute(OperationContext context, ModelNode operation)
                    throws OperationFailedException {
                  final ModelNode response = new ModelNode();
                  List<JaxrsResourceMethodDescription> resMethodInvokers = new ArrayList<>();
                  List<JaxrsResourceLocatorDescription> resLocatorInvokers = new ArrayList<>();
                  for (Map.Entry<String, List<ResourceInvoker>> resource :
                      registry.getBounded().entrySet()) {
                    String mapping = resource.getKey();
                    List<ResourceInvoker> resouceInvokers = resource.getValue();
                    for (ResourceInvoker resourceInvoker : resouceInvokers) {
                      if (ResourceMethodInvoker.class.isAssignableFrom(
                          resourceInvoker.getClass())) {
                        ResourceMethodInvoker methodInvoker =
                            (ResourceMethodInvoker) resourceInvoker;
                        if (methodInvoker.getResourceClass().getCanonicalName().equals(clsName)) {
                          JaxrsResourceMethodDescription resMethodDesc =
                              resMethodDescription(
                                  methodInvoker, contextPath, mapping, servletMappings);
                          resMethodInvokers.add(resMethodDesc);
                        }
                      } else if (ResourceLocatorInvoker.class.isAssignableFrom(
                          resourceInvoker.getClass())) {
                        ResourceLocatorInvoker locatorInvoker =
                            (ResourceLocatorInvoker) resourceInvoker;
                        if (clsName.equals(
                            locatorInvoker.getMethod().getDeclaringClass().getCanonicalName())) {
                          ResourceClass resClass =
                              ResourceBuilder.locatorFromAnnotations(
                                  locatorInvoker.getMethod().getReturnType());
                          JaxrsResourceLocatorDescription resLocatorDesc =
                              resLocatorDescription(
                                  resClass,
                                  contextPath,
                                  mapping,
                                  servletMappings,
                                  new ArrayList<Class<?>>());
                          resLocatorInvokers.add(resLocatorDesc);
                        }
                      }
                    }
                  }
                  Collections.sort(resMethodInvokers);
                  Collections.sort(resLocatorInvokers);
                  handleAttribute(
                      clsName, resMethodInvokers, resLocatorInvokers, servletMappings, response);
                  context.getResult().set(response);
                }
              },
              OperationContext.Stage.RUNTIME);
        }
      } catch (ServletException ex) {
        throw new RuntimeException(ex);
      } finally {
        handle.tearDown();
      }
    }
  static void installHttpManagementConnector(
      final OperationContext context,
      final ModelNode model,
      final ServiceTarget serviceTarget,
      final ServiceVerificationHandler verificationHandler,
      final List<ServiceController<?>> newControllers)
      throws OperationFailedException {

    ServiceName socketBindingServiceName = null;
    ServiceName secureSocketBindingServiceName = null;
    ServiceName interfaceSvcName = null;
    int port = -1;
    int securePort = -1;

    final ModelNode interfaceModelNode = validateResolvedModel(INTERFACE, context, model);
    if (interfaceModelNode.isDefined()) {
      // Legacy config
      String interfaceName = interfaceModelNode.asString();
      interfaceSvcName = NetworkInterfaceService.JBOSS_NETWORK_INTERFACE.append(interfaceName);
      final ModelNode portNode = HTTP_PORT.resolveModelAttribute(context, model);
      port = portNode.isDefined() ? portNode.asInt() : -1;
      final ModelNode securePortNode = HTTPS_PORT.resolveModelAttribute(context, model);
      securePort = securePortNode.isDefined() ? securePortNode.asInt() : -1;

      // Log the config
      if (securePort > -1) {
        if (port > -1) {
          ServerLogger.ROOT_LOGGER.creatingHttpManagementServiceOnPortAndSecurePort(
              interfaceName, port, securePort);
        } else {
          ServerLogger.ROOT_LOGGER.creatingHttpManagementServiceOnSecurePort(
              interfaceName, securePort);
        }
      } else if (port > -1) {
        ServerLogger.ROOT_LOGGER.creatingHttpManagementServiceOnPort(interfaceName, port);
      }
    } else {
      // Socket-binding reference based config
      final ModelNode socketBindingNode = SOCKET_BINDING.resolveModelAttribute(context, model);
      if (socketBindingNode.isDefined()) {
        final String bindingName = socketBindingNode.asString();
        socketBindingServiceName = SocketBinding.JBOSS_BINDING_NAME.append(bindingName);
      }
      final ModelNode secureSocketBindingNode =
          SECURE_SOCKET_BINDING.resolveModelAttribute(context, model);
      if (secureSocketBindingNode.isDefined()) {
        final String bindingName = secureSocketBindingNode.asString();
        secureSocketBindingServiceName = SocketBinding.JBOSS_BINDING_NAME.append(bindingName);
      }

      // Log the config
      if (socketBindingServiceName != null) {
        if (secureSocketBindingServiceName != null) {
          ServerLogger.ROOT_LOGGER.creatingHttpManagementServiceOnSocketAndSecureSocket(
              socketBindingServiceName.getSimpleName(),
              secureSocketBindingServiceName.getSimpleName());
        } else {
          ServerLogger.ROOT_LOGGER.creatingHttpManagementServiceOnSocket(
              socketBindingServiceName.getSimpleName());
        }
      } else if (secureSocketBindingServiceName != null) {
        ServerLogger.ROOT_LOGGER.creatingHttpManagementServiceOnSecureSocket(
            secureSocketBindingServiceName.getSimpleName());
      }
    }

    ServiceName realmSvcName = null;
    final ModelNode realmNode = SECURITY_REALM.resolveModelAttribute(context, model);
    if (realmNode.isDefined()) {
      realmSvcName = SecurityRealmService.BASE_SERVICE_NAME.append(realmNode.asString());
    } else {
      ServerLogger.ROOT_LOGGER.httpManagementInterfaceIsUnsecured();
    }
    boolean consoleEnabled = model.get(ModelDescriptionConstants.CONSOLE_ENABLED).asBoolean(true);
    ConsoleMode consoleMode;
    if (consoleEnabled) {
      consoleMode =
          context.getRunningMode() == RunningMode.ADMIN_ONLY
              ? ConsoleMode.ADMIN_ONLY
              : ConsoleMode.CONSOLE;
    } else {
      consoleMode = ConsoleMode.NO_CONSOLE;
    }

    ServerEnvironment environment =
        (ServerEnvironment)
            context
                .getServiceRegistry(false)
                .getRequiredService(ServerEnvironmentService.SERVICE_NAME)
                .getValue();
    final HttpManagementService service =
        new HttpManagementService(consoleMode, environment.getProductConfig().getConsoleSlot());
    ServiceBuilder<HttpManagement> builder =
        serviceTarget
            .addService(HttpManagementService.SERVICE_NAME, service)
            .addDependency(
                Services.JBOSS_SERVER_CONTROLLER,
                ModelController.class,
                service.getModelControllerInjector())
            .addDependency(
                SocketBindingManagerImpl.SOCKET_BINDING_MANAGER,
                SocketBindingManager.class,
                service.getSocketBindingManagerInjector())
            .addDependency(
                ControlledProcessStateService.SERVICE_NAME,
                ControlledProcessStateService.class,
                service.getControlledProcessStateServiceInjector())
            .addInjection(
                service.getExecutorServiceInjector(),
                Executors.newCachedThreadPool(
                    new JBossThreadFactory(
                        new ThreadGroup("HttpManagementService-threads"),
                        Boolean.FALSE,
                        null,
                        "%G - %t",
                        null,
                        null,
                        AccessController.getContext())));

    if (interfaceSvcName != null) {
      builder
          .addDependency(
              interfaceSvcName, NetworkInterfaceBinding.class, service.getInterfaceInjector())
          .addInjection(service.getPortInjector(), port)
          .addInjection(service.getSecurePortInjector(), securePort);
    } else {
      if (socketBindingServiceName != null) {
        builder.addDependency(
            socketBindingServiceName, SocketBinding.class, service.getSocketBindingInjector());
      }
      if (secureSocketBindingServiceName != null) {
        builder.addDependency(
            secureSocketBindingServiceName,
            SocketBinding.class,
            service.getSecureSocketBindingInjector());
      }
    }

    if (realmSvcName != null) {
      builder.addDependency(
          realmSvcName, SecurityRealmService.class, service.getSecurityRealmInjector());
    }

    if (verificationHandler != null) {
      builder.addListener(verificationHandler);
    }
    ServiceController<?> controller = builder.install();
    if (newControllers != null) {
      newControllers.add(controller);
    }
  }
Пример #22
0
  @Override
  public void executeRuntimeStep(OperationContext context, ModelNode operation)
      throws OperationFailedException {
    if (ignoreOperationIfServerNotActive(context, operation)) {
      return;
    }

    validator.validate(operation);
    final String attributeName = operation.require(ModelDescriptionConstants.NAME).asString();

    PathAddress address =
        PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR));
    String queueName = address.getLastElement().getValue();

    if (forwardToRuntimeQueue(context, operation, RUNTIME_INSTANCE)) {
      return;
    }

    final ServiceName serviceName = MessagingServices.getActiveMQServiceName(address);
    ServiceController<?> service = context.getServiceRegistry(false).getService(serviceName);
    ActiveMQServer server = ActiveMQServer.class.cast(service.getValue());
    QueueControl control =
        QueueControl.class.cast(
            server.getManagementService().getResource(ResourceNames.CORE_QUEUE + queueName));

    if (control == null) {
      throw ControllerLogger.ROOT_LOGGER.managementResourceNotFound(address);
    }

    if (MESSAGE_COUNT.getName().equals(attributeName)) {
      context.getResult().set(control.getMessageCount());
    } else if (SCHEDULED_COUNT.getName().equals(attributeName)) {
      context.getResult().set(control.getScheduledCount());
    } else if (CONSUMER_COUNT.getName().equals(attributeName)) {
      context.getResult().set(control.getConsumerCount());
    } else if (DELIVERING_COUNT.getName().equals(attributeName)) {
      context.getResult().set(control.getDeliveringCount());
    } else if (MESSAGES_ADDED.getName().equals(attributeName)) {
      context.getResult().set(control.getMessagesAdded());
    } else if (ID.getName().equals(attributeName)) {
      context.getResult().set(control.getID());
    } else if (PAUSED.getName().equals(attributeName)) {
      try {
        context.getResult().set(control.isPaused());
      } catch (RuntimeException e) {
        throw e;
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    } else if (TEMPORARY.getName().equals(attributeName)) {
      context.getResult().set(control.isTemporary());
    } else if (EXPIRY_ADDRESS.getName().equals(attributeName)) {
      if (control.getExpiryAddress() != null) {
        context.getResult().set(control.getExpiryAddress());
      }
    } else if (DEAD_LETTER_ADDRESS.getName().equals(attributeName)) {
      if (control.getDeadLetterAddress() != null) {
        context.getResult().set(control.getDeadLetterAddress());
      }
    } else if (readStorageAttributes && getStorageAttributeNames().contains(attributeName)) {
      if (ADDRESS.getName().equals(attributeName)) {
        context.getResult().set(control.getAddress());
      } else if (DURABLE.getName().equals(attributeName)) {
        context.getResult().set(control.isDurable());
      } else if (FILTER.getName().equals(attributeName)) {
        ModelNode result = context.getResult();
        String filter = control.getFilter();
        if (filter != null) {
          result.set(filter);
        }
      }
    } else {
      throw MessagingLogger.ROOT_LOGGER.unsupportedAttribute(attributeName);
    }
  }
    @Override
    protected void executeRuntimeStep(OperationContext context, ModelNode operation)
        throws OperationFailedException {

      final PathAddress address =
          PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR));

      final Resource web =
          context.readResourceFromRoot(address.subAddress(0, address.size()), false);
      final ModelNode subModel = web.getModel();

      final String host = VIRTUAL_HOST.resolveModelAttribute(context, subModel).asString();
      final String path = CONTEXT_ROOT.resolveModelAttribute(context, subModel).asString();
      final String server = SERVER.resolveModelAttribute(context, subModel).asString();

      final ServiceController<?> controller =
          context
              .getServiceRegistry(false)
              .getService(UndertowService.deploymentServiceName(server, host, path));

      SessionStat stat =
          SessionStat.getStat(operation.require(ModelDescriptionConstants.NAME).asString());

      if (stat == null) {
        context
            .getFailureDescription()
            .set(
                UndertowMessages.MESSAGES.unknownMetric(
                    operation.require(ModelDescriptionConstants.NAME).asString()));
      } else {
        context.getResult().set("<not implemented>");
        /*final Context webContext = Context.class.cast(controller.getValue());
        ManagerBase sm = (ManagerBase) webContext.getManager();
        ModelNode result = new ModelNode();
        switch (stat) {
            case ACTIVE_SESSIONS:
                result.set(sm.getActiveSessions());
                break;
            case EXPIRED_SESSIONS:
                result.set(sm.getExpiredSessions());
                break;
            case MAX_ACTIVE_SESSIONS:
                result.set(sm.getMaxActive());
                break;
            case SESSIONS_CREATED:
                result.set(sm.getSessionCounter());
                break;
            case DUPLICATED_SESSION_IDS:
                result.set(sm.getDuplicates());
                break;
            case SESSION_AVG_ALIVE_TIME:
                result.set(sm.getSessionAverageAliveTime());
                break;
            case SESSION_MAX_ALIVE_TIME:
                result.set(sm.getSessionMaxAliveTime());
                break;
            case REJECTED_SESSIONS:
                result.set(sm.getRejectedSessions());
                break;
            default:
                throw new IllegalStateException(WebMessages.MESSAGES.unknownMetric(stat));
        }
        context.getResult().set(result);*/
      }

      context.stepCompleted();
    }
  @Override
  protected void executeRuntimeStep(OperationContext context, ModelNode operation)
      throws OperationFailedException {

    // get the channel name and channel attribute
    PathAddress pathAddress = PathAddress.pathAddress(operation.require(OP_ADDR));
    String channelName = pathAddress.getElement(pathAddress.size() - 1).getValue();
    String attrName = operation.require(NAME).asString();
    ChannelMetrics metric = ChannelMetrics.getStat(attrName);

    // lookup the channel
    ServiceName channelServiceName = ChannelInstanceResource.CHANNEL_PARENT.append(channelName);
    ServiceController<?> controller =
        context.getServiceRegistry(false).getService(channelServiceName);

    // check that the service has been installed and started
    boolean started = controller != null && controller.getValue() != null;
    ModelNode result = new ModelNode();

    if (metric == null) {
      context.getFailureDescription().set(JGroupsMessages.MESSAGES.unknownMetric(attrName));
    } else if (!started) {
      // when the cache service is not available, return a null result
    } else {
      JChannel channel = (JChannel) controller.getValue();
      switch (metric) {
        case ADDRESS:
          result.set(channel.getAddressAsString());
          break;
        case ADDRESS_AS_UUID:
          result.set(channel.getAddressAsUUID());
          break;
        case DISCARD_OWN_MESSAGES:
          result.set(channel.getDiscardOwnMessages());
          break;
        case NUM_TASKS_IN_TIMER:
          result.set(channel.getNumberOfTasksInTimer());
          break;
        case NUM_TIMER_THREADS:
          result.set(channel.getTimerThreads());
          break;
        case RECEIVED_BYTES:
          result.set(channel.getReceivedBytes());
          break;
        case RECEIVED_MESSAGES:
          result.set(channel.getReceivedMessages());
          break;
        case SENT_BYTES:
          result.set(channel.getSentBytes());
          break;
        case SENT_MESSAGES:
          result.set(channel.getSentMessages());
          break;
        case STATE:
          result.set(channel.getState());
          break;
        case STATS_ENABLED:
          result.set(channel.statsEnabled());
          break;
        case VERSION:
          result.set(JChannel.getVersion());
          break;
        case VIEW:
          result.set(channel.getViewAsString());
          break;
      }
      context.getResult().set(result);
    }
    context.completeStep(OperationContext.ResultHandler.NOOP_RESULT_HANDLER);
  }
Пример #25
0
  protected void performRuntime(
      OperationContext context,
      ModelNode operation,
      ModelNode model,
      ServiceVerificationHandler verificationHandler,
      List<ServiceController<?>> newControllers) {

    log.info("Activating Naming Subsystem");

    NamingContext.initializeNamingManager();

    final ServiceBasedNamingStore namingStore =
        new ServiceBasedNamingStore(
            context.getServiceRegistry(false), ContextNames.JAVA_CONTEXT_SERVICE_NAME);

    // Create the Naming Service
    final ServiceTarget target = context.getServiceTarget();
    newControllers.add(
        target
            .addService(NamingService.SERVICE_NAME, new NamingService(namingStore))
            .addAliases(ContextNames.JAVA_CONTEXT_SERVICE_NAME)
            .setInitialMode(ServiceController.Mode.ACTIVE)
            .addListener(verificationHandler)
            .install());

    // Create the java:global namespace
    final ServiceBasedNamingStore globalNamingStore =
        new ServiceBasedNamingStore(
            context.getServiceRegistry(false), ContextNames.GLOBAL_CONTEXT_SERVICE_NAME);
    newControllers.add(
        target
            .addService(
                ContextNames.GLOBAL_CONTEXT_SERVICE_NAME, new NamingStoreService(globalNamingStore))
            .setInitialMode(ServiceController.Mode.ACTIVE)
            .addListener(verificationHandler)
            .install());

    // Create the java:jboss vendor namespace
    final ServiceBasedNamingStore jbossNamingStore =
        new ServiceBasedNamingStore(
            context.getServiceRegistry(false), ContextNames.JBOSS_CONTEXT_SERVICE_NAME);
    newControllers.add(
        target
            .addService(
                ContextNames.JBOSS_CONTEXT_SERVICE_NAME, new NamingStoreService(jbossNamingStore))
            .setInitialMode(ServiceController.Mode.ACTIVE)
            .addListener(verificationHandler)
            .install());

    NamespaceContextSelector.setDefault(
        new NamespaceContextSelector() {
          public Context getContext(String identifier) {
            final NamingStore namingStore;
            if (identifier.equals("global")) {
              namingStore = globalNamingStore;
            } else if (identifier.equals("jboss")) {
              namingStore = jbossNamingStore;
            } else {
              namingStore = null;
            }
            if (namingStore != null) {
              try {
                return (Context) namingStore.lookup(EMPTY_NAME);
              } catch (NamingException e) {
                throw new IllegalStateException(e);
              }
            } else {
              return null;
            }
          }
        });

    // Provide the {@link InitialContext} as OSGi service
    newControllers.add(InitialContextFactoryService.addService(target, verificationHandler));

    newControllers.add(
        target
            .addService(JndiViewExtensionRegistry.SERVICE_NAME, new JndiViewExtensionRegistry())
            .install());

    if (context.isBooting()) {
      context.addStep(
          new AbstractDeploymentChainStep() {
            protected void execute(DeploymentProcessorTarget processorTarget) {
              processorTarget.addDeploymentProcessor(
                  Phase.INSTALL,
                  Phase.INSTALL_JNDI_DEPENDENCY_SETUP,
                  new JndiNamingDependencySetupProcessor());
              processorTarget.addDeploymentProcessor(
                  Phase.INSTALL,
                  Phase.INSTALL_JNDI_DEPENDENCIES,
                  new JndiNamingDependencyProcessor());
            }
          },
          OperationContext.Stage.RUNTIME);
    }
  }