Beispiel #1
0
  @Override
  public CreateResourceReport createResource(CreateResourceReport report) {

    if (report.getPackageDetails() != null) { // Content deployment
      return deployContent(report);
    } else {
      report.setStatus(CreateResourceStatus.INVALID_CONFIGURATION);
      Address createAddress = new Address(address);
      createAddress.add(
          report.getPluginConfiguration().getSimpleValue("path", ""),
          report.getUserSpecifiedResourceName());
      Operation op = new Operation("add", createAddress);
      for (Property prop : report.getResourceConfiguration().getProperties()) {
        if (prop instanceof PropertySimple) {
          PropertySimple ps = (PropertySimple) prop;
          String value = ps.getStringValue();
          op.addAdditionalProperty(prop.getName(), value);
        }
        // TODO more types
      }
      Result result = getASConnection().execute(op);
      if (result.isSuccess()) {
        report.setStatus(CreateResourceStatus.SUCCESS);
        report.setResourceKey(address.getPath());
        report.setResourceName(report.getUserSpecifiedResourceName());
      } else {
        report.setStatus(CreateResourceStatus.FAILURE);
        report.setErrorMessage(result.getFailureDescription());
      }
    }
    return report;
  }
  @Override
  protected void getValues(
      ManagedComponent managedComponent,
      MeasurementReport report,
      Set<MeasurementScheduleRequest> metrics)
      throws Exception {
    Set<MeasurementScheduleRequest> uncollectedMetrics = new HashSet<MeasurementScheduleRequest>();
    for (MeasurementScheduleRequest request : metrics) {
      String metricName = request.getName();
      if (metricName.equals("custom.connectionAvailable")) {
        try {
          Configuration parameters = new Configuration();
          OperationResult result = invokeOperation(managedComponent, "testConnection", parameters);
          PropertySimple resultProp = result.getComplexResults().getSimple("result");
          boolean connectionAvailable = resultProp.getBooleanValue();
          MeasurementDataTrait trait =
              new MeasurementDataTrait(request, connectionAvailable ? "yes" : "no");
          report.addData(trait);
        } catch (Exception e) {
          log.error("Failed to collect trait [" + metricName + "].", e);
        }
      } else {
        uncollectedMetrics.add(request);
      }
    }

    super.getValues(managedComponent, report, uncollectedMetrics);
  }
  @NotNull
  public List<Pattern> getExcludes() {
    List<Pattern> excludes = new ArrayList<Pattern>();
    PropertySimple excludesProp =
        this.pluginConfig.getSimple(RESPONSE_TIME_URL_EXCLUDES_CONFIG_PROP);
    if ((excludesProp != null) && (excludesProp.getStringValue() != null)) {
      StringTokenizer tokenizer = new StringTokenizer(excludesProp.getStringValue(), " ");
      while (tokenizer.hasMoreTokens()) {
        String regEx = tokenizer.nextToken();
        try {
          Pattern exclude = Pattern.compile(regEx);
          excludes.add(exclude);
        } catch (PatternSyntaxException e) {
          throw new InvalidPluginConfigurationException(
              "'"
                  + RESPONSE_TIME_URL_EXCLUDES_CONFIG_PROP
                  + "' connection property contains an invalid exclude expression: "
                  + regEx,
              e);
        }
      }
    }

    return excludes;
  }
  @NotNull
  public List<RegexSubstitution> getTransforms() {
    List<RegexSubstitution> transforms = new ArrayList<RegexSubstitution>();
    PropertySimple transformsProp =
        this.pluginConfig.getSimple(RESPONSE_TIME_URL_TRANSFORMS_CONFIG_PROP);
    if ((transformsProp != null) && (transformsProp.getStringValue() != null)) {
      StringTokenizer tokenizer = new StringTokenizer(transformsProp.getStringValue(), " ");
      while (tokenizer.hasMoreTokens()) {
        String value = tokenizer.nextToken();
        String delimiter = value.substring(0, 1); // first character is the delimiter (sed-style)
        String lastChar = value.substring(value.length() - 1);
        if (value.length() < 3 || !lastChar.equals(delimiter)) {
          throw new InvalidPluginConfigurationException(
              "'"
                  + RESPONSE_TIME_URL_TRANSFORMS_CONFIG_PROP
                  + "' connection property contains an invalid transform expression ["
                  + value
                  + "]. "
                  + "A transform expressions should contain exactly three delimiters (the first character "
                  + "of the expression is the delimiter) and should also end with a delimiter. For example, "
                  + "|foo|bar|\" replaces \"foo\" with \"bar\".");
        }
        String[] tokens =
            value.substring(1, value.length() - 1).split(Pattern.quote(delimiter), -1);
        if (tokens.length != 2) {
          throw new InvalidPluginConfigurationException(
              "'"
                  + RESPONSE_TIME_URL_TRANSFORMS_CONFIG_PROP
                  + "' connection property contains an invalid transform expression ["
                  + value
                  + "]. "
                  + "A transform expressions should contain exactly three delimiters (the first character "
                  + "of the expression is the delimiter). For example, \"|foo|bar|\" replaces \"foo\" with \"bar\".");
        }
        String regEx = tokens[0];
        String replacement = tokens[1];
        try {
          Pattern pattern = Pattern.compile(regEx);
          RegexSubstitution transform = new RegexSubstitution(pattern, replacement);
          transforms.add(transform);
        } catch (PatternSyntaxException e) {
          throw new InvalidPluginConfigurationException(
              "'"
                  + RESPONSE_TIME_URL_TRANSFORMS_CONFIG_PROP
                  + "' connection property contains an invalid transform expression ["
                  + value
                  + "]. "
                  + "Specifically, the regular expression portion ["
                  + regEx
                  + "] is not a valid regular expression.",
              e);
        }
      }
    }

    return transforms;
  }
 public static List<String> getGlobList(PropertySimple list) {
   if (list != null) {
     return Arrays.asList(list.getStringValue().split("\\s*\\|\\s*"));
   } else {
     return Collections.emptyList();
   }
 }
  private void updateCassandraJvmProps(Configuration newConfig) throws IOException {
    PropertiesFileUpdate propertiesUpdater =
        new PropertiesFileUpdate(jvmOptsFile.getAbsolutePath());
    Properties properties = propertiesUpdater.loadExistingProperties();

    String jmxPort = newConfig.getSimpleValue("jmxPort");
    if (!StringUtil.isEmpty(jmxPort)) {
      validateIntegerArg("jmx_port", jmxPort);
      properties.setProperty("jmx_port", jmxPort);
    }

    String maxHeapSize = newConfig.getSimpleValue("maxHeapSize");
    if (!StringUtil.isEmpty(maxHeapSize)) {
      validateHeapArg("maxHeapSize", maxHeapSize);
      // We want min and max heap to be the same
      properties.setProperty("heap_min", "-Xms" + maxHeapSize);
      properties.setProperty("heap_max", "-Xmx" + maxHeapSize);
    }

    String heapNewSize = newConfig.getSimpleValue("heapNewSize");
    if (!StringUtil.isEmpty(heapNewSize)) {
      validateHeapArg("heapNewSize", heapNewSize);
      properties.setProperty("heap_new", "-Xmn" + heapNewSize);
    }

    String threadStackSize = newConfig.getSimpleValue("threadStackSize");
    if (!StringUtil.isEmpty(threadStackSize)) {
      validateIntegerArg("threadStackSize", threadStackSize);
      properties.setProperty("thread_stack_size", "-Xss" + threadStackSize + "k");
    }

    PropertySimple heapDumpOnOMMError = newConfig.getSimple("heapDumpOnOOMError");
    if (heapDumpOnOMMError != null) {
      if (heapDumpOnOMMError.getBooleanValue()) {
        properties.setProperty("heap_dump_on_OOMError", "-XX:+HeapDumpOnOutOfMemoryError");
      } else {
        properties.setProperty("heap_dump_on_OOMError", "");
      }
    }

    String heapDumpDir = useForwardSlash(newConfig.getSimpleValue("heapDumpDir"));
    if (!StringUtil.isEmpty(heapDumpDir)) {
      properties.setProperty("heap_dump_dir", heapDumpDir);
    }

    propertiesUpdater.update(properties);
  }
  private String composeResourceKey(Configuration pluginConfiguration) {
    PropertySimple includeGlobsProp =
        pluginConfiguration.getSimple(AugeasConfigurationComponent.INCLUDE_GLOBS_PROP);
    PropertySimple excludeGlobsProp =
        pluginConfiguration.getSimple(AugeasConfigurationComponent.EXCLUDE_GLOBS_PROP);

    StringBuilder bld = new StringBuilder();

    bld.append(includeGlobsProp.getStringValue());

    if (excludeGlobsProp != null && excludeGlobsProp.getStringValue().length() > 0) {
      bld.append("---");
      bld.append(excludeGlobsProp.getStringValue());
    }

    return bld.toString();
  }
  private void updateCassandraYaml(Configuration newConfig) {
    ConfigEditor editor = new ConfigEditor(cassandraYamlFile);
    try {
      editor.load();

      PropertySimple cqlPortProperty = newConfig.getSimple("cqlPort");
      if (cqlPortProperty != null) {
        editor.setNativeTransportPort(cqlPortProperty.getIntegerValue());
      }

      PropertySimple gossipPortProperty = newConfig.getSimple("gossipPort");
      if (gossipPortProperty != null) {
        editor.setStoragePort(gossipPortProperty.getIntegerValue());
      }

      editor.save();
    } catch (ConfigEditorException e) {
      if (e.getCause() instanceof YAMLException) {
        log.error("Failed to update " + cassandraYamlFile);
        log.info("Attempting to restore " + cassandraYamlFile);
        try {
          editor.restore();
          throw e;
        } catch (ConfigEditorException e1) {
          log.error(
              "Failed to restore "
                  + cassandraYamlFile
                  + ". A copy of the file prior to any "
                  + "modifications can be found at "
                  + editor.getBackupFile());
          throw new ConfigEditorException(
              "There was an error updating "
                  + cassandraYamlFile
                  + " and "
                  + "undoing the changes failed. A copy of the file can be found at "
                  + editor.getBackupFile()
                  + ". See the agent logs for more details.",
              e);
        }
      } else {
        log.error(
            "No updates were made to " + cassandraYamlFile + " due to an unexpected error", e);
        throw e;
      }
    }
  }
Beispiel #9
0
 private static String getResourceName(Configuration pluginConfig, Configuration resourceConfig) {
   PropertySimple resourceNameProp =
       pluginConfig.getSimple(TranslatorComponent.Config.RESOURCE_NAME);
   if (resourceNameProp == null || resourceNameProp.getStringValue() == null)
     throw new IllegalStateException(
         "Property [" //$NON-NLS-1$
             + TranslatorComponent.Config.RESOURCE_NAME
             + "] is not defined in the default plugin configuration."); //$NON-NLS-1$
   String resourceNamePropName = resourceNameProp.getStringValue();
   PropertySimple propToUseAsResourceName = resourceConfig.getSimple(resourceNamePropName);
   if (propToUseAsResourceName == null)
     throw new IllegalStateException(
         "Property ["
             + resourceNamePropName //$NON-NLS-1$
             + "] is not defined in initial Resource configuration."); //$NON-NLS-1$
   return propToUseAsResourceName.getStringValue();
 }
Beispiel #10
0
  private String replacePropertyPatterns(String envVars) {
    Pattern pattern = Pattern.compile("(%([^%]*)%)");
    Matcher matcher = pattern.matcher(envVars);
    Configuration parentPluginConfig =
        this.resourceContext.getParentResourceComponent().getPluginConfiguration();
    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
      String propName = matcher.group(2);
      PropertySimple prop = parentPluginConfig.getSimple(propName);
      String propPattern = matcher.group(1);
      String replacement = (prop != null) ? prop.getStringValue() : propPattern;
      matcher.appendReplacement(buffer, Matcher.quoteReplacement(replacement));
    }

    matcher.appendTail(buffer);
    return buffer.toString();
  }
  /**
   * Invoke operations on the Cache MBean instance
   *
   * @param fullOpName Name of the operation
   * @param parameters Parameters of the Operation
   * @return OperationResult object if successful
   * @throws Exception If operation was not successful
   */
  @Override
  public OperationResult invokeOperation(String fullOpName, Configuration parameters)
      throws Exception {
    boolean trace = log.isTraceEnabled();
    EmsBean bean = queryComponentBean(fullOpName);
    String opName = fullOpName.substring(fullOpName.indexOf(".") + 1);
    EmsOperation ops = bean.getOperation(opName);
    Collection<PropertySimple> simples = parameters.getSimpleProperties().values();
    if (trace) log.trace("Parameters, as simple properties, are " + simples);
    Object[] realParams = new Object[simples.size()];
    int i = 0;
    for (PropertySimple property : simples) {
      // Since parameters are typed in UI, passing them as Strings is the only reasonable way of
      // dealing with this
      realParams[i++] = property.getStringValue();
    }

    if (ops == null) throw new Exception("Operation " + fullOpName + " can't be found");

    Object result = ops.invoke(realParams);
    if (trace) log.trace("Returning operation result containing " + result.toString());
    return new OperationResult(result.toString());
  }
Beispiel #12
0
  Object getObjectForProperty(PropertySimple prop, PropertyDefinitionSimple propDef) {

    PropertySimpleType type = propDef.getType();
    switch (type) {
      case STRING:
        return prop.getStringValue();
      case INTEGER:
        return prop.getIntegerValue();
      case BOOLEAN:
        return prop.getBooleanValue();
      case LONG:
        return prop.getLongValue();
      case FLOAT:
        return prop.getFloatValue();
      case DOUBLE:
        return prop.getDoubleValue();
      default:
        return prop.getStringValue();
    }
  }
Beispiel #13
0
  @Override
  public OperationResult invokeOperation(String name, Configuration parameters)
      throws InterruptedException, Exception {

    if (!name.contains(":")) {
      OperationResult badName = new OperationResult("Operation name did not contain a ':'");
      badName.setErrorMessage("Operation name did not contain a ':'");
      return badName;
    }

    int colonPos = name.indexOf(':');
    String what = name.substring(0, colonPos);
    String op = name.substring(colonPos + 1);
    Operation operation = null;

    Address theAddress = new Address();

    if (what.equals("server-group")) {
      String groupName = parameters.getSimpleValue("name", "");
      String profile = parameters.getSimpleValue("profile", "default");

      theAddress.add("server-group", groupName);

      operation = new Operation(op, theAddress);
      operation.addAdditionalProperty("profile", profile);
    } else if (what.equals("server")) {
      if (context.getResourceType().getName().equals("JBossAS-Managed")) {
        String host = pluginConfiguration.getSimpleValue("domainHost", "local");
        theAddress.add("host", host);
        theAddress.add("server-config", myServerName);
        operation = new Operation(op, theAddress);
      } else if (context.getResourceType().getName().equals("Host")) {
        theAddress.add(address);
        String serverName = parameters.getSimpleValue("name", null);
        theAddress.add("server-config", serverName);
        Map<String, Object> props = new HashMap<String, Object>();
        String serverGroup = parameters.getSimpleValue("group", null);
        props.put("group", serverGroup);
        if (op.equals("add")) {
          props.put("name", serverName);
          boolean autoStart = parameters.getSimple("auto-start").getBooleanValue();
          props.put("auto-start", autoStart);
          // TODO put more properties in
        }

        operation = new Operation(op, theAddress, props);
      } else {
        operation = new Operation(op, theAddress);
      }
    } else if (what.equals("destination")) {
      theAddress.add(address);
      String newName = parameters.getSimpleValue("name", "");
      String type = parameters.getSimpleValue("type", "jms-queue").toLowerCase();
      theAddress.add(type, newName);
      PropertyList jndiNamesProp = parameters.getList("entries");
      if (jndiNamesProp == null || jndiNamesProp.getList().isEmpty()) {
        OperationResult fail = new OperationResult();
        fail.setErrorMessage("No jndi bindings given");
        return fail;
      }
      List<String> jndiNames = new ArrayList<String>();
      for (Property p : jndiNamesProp.getList()) {
        PropertySimple ps = (PropertySimple) p;
        jndiNames.add(ps.getStringValue());
      }

      operation = new Operation(op, theAddress);
      operation.addAdditionalProperty("entries", jndiNames);
      if (type.equals("jms-queue")) {
        PropertySimple ps = (PropertySimple) parameters.get("durable");
        if (ps != null) {
          boolean durable = ps.getBooleanValue();
          operation.addAdditionalProperty("durable", durable);
        }
        String selector = parameters.getSimpleValue("selector", "");
        if (!selector.isEmpty()) operation.addAdditionalProperty("selector", selector);
      }

    } else if (what.equals("managed-server")) {
      String chost = parameters.getSimpleValue("hostname", "");
      String serverName = parameters.getSimpleValue("servername", "");
      String serverGroup = parameters.getSimpleValue("server-group", "");
      String socketBindings = parameters.getSimpleValue("socket-bindings", "");
      String portS = parameters.getSimpleValue("port-offset", "0");
      int port = Integer.parseInt(portS);
      String autostartS = parameters.getSimpleValue("auto-start", "false");
      boolean autoStart = Boolean.getBoolean(autostartS);

      theAddress.add("host", chost);
      theAddress.add("server-config", serverName);
      Map<String, Object> props = new HashMap<String, Object>();
      props.put("name", serverName);
      props.put("group", serverGroup);
      props.put("socket-binding-group", socketBindings);
      props.put("socket-binding-port-offset", port);
      props.put("auto-start", autoStart);

      operation = new Operation(op, theAddress, props);
    } else if (what.equals("domain")) {
      operation = new Operation(op, new Address());
    } else if (what.equals("domain-deployment")) {
      if (op.equals("promote")) {
        String serverGroup = parameters.getSimpleValue("server-group", "-not set-");
        List<String> serverGroups = new ArrayList<String>();
        if (serverGroup.equals("__all")) {
          serverGroups.addAll(getServerGroups());
        } else {
          serverGroups.add(serverGroup);
        }
        String resourceKey = context.getResourceKey();
        resourceKey = resourceKey.substring(resourceKey.indexOf("=") + 1);

        log.info(
            "Promoting ["
                + resourceKey
                + "] to server group(s) ["
                + Arrays.asList(serverGroups)
                + "]");

        PropertySimple simple = parameters.getSimple("enabled");
        Boolean enabled = false;
        if (simple != null && simple.getBooleanValue() != null) enabled = simple.getBooleanValue();

        operation = new CompositeOperation();
        for (String theGroup : serverGroups) {
          theAddress = new Address();
          theAddress.add("server-group", theGroup);

          theAddress.add("deployment", resourceKey);
          Operation step = new Operation("add", theAddress);
          step.addAdditionalProperty("enabled", enabled);
          ((CompositeOperation) operation).addStep(step);
        }
      }
    } else if (what.equals("naming")) {
      if (op.equals("jndi-view")) {
        theAddress.add(address);
        operation = new Operation("jndi-view", theAddress);
      }
    }

    OperationResult operationResult = new OperationResult();
    if (operation != null) {
      Result result = connection.execute(operation);

      if (!result.isSuccess()) {
        operationResult.setErrorMessage(result.getFailureDescription());
      } else {
        String tmp;
        if (result.getResult() == null) tmp = "-none provided by the server-";
        else tmp = result.getResult().toString();
        operationResult.setSimpleResult(tmp);
      }
    } else {
      operationResult.setErrorMessage("No valid operation was given for input [" + name + "]");
    }
    return operationResult;
  }
  public CreateResourceReport createResource(CreateResourceReport report) {

    JBossASServerComponent parentResourceComponent =
        getResourceContext().getParentResourceComponent();

    String resourceTypeName = report.getResourceType().getName();

    String objectNamePreString;
    boolean isTopic = false;
    if (resourceTypeName.contains("Topic")) {
      objectNamePreString = TOPIC_MBEAN_NAME;
      isTopic = true;
    } else {
      objectNamePreString = QUEUE_MBEAN_NAME;
    }

    Configuration config = report.getResourceConfiguration();

    String name = config.getSimple("MBeanName").getStringValue();
    PropertySimple nameTemplateProp = report.getPluginConfiguration().getSimple("nameTemplate");
    String rName = nameTemplateProp.getStringValue();
    //noinspection ConstantConditions
    rName = rName.replace("{name}", name);

    EmsConnection connection = parentResourceComponent.getEmsConnection();

    if (DeploymentUtility.isDuplicateJndiName(connection, objectNamePreString, name)) {
      report.setStatus(CreateResourceStatus.FAILURE);
      report.setErrorMessage("Duplicate JNDI Name, a resource with that name already exists");
      return report;
    }
    PropertySimple pluginNameProperty = new PropertySimple("name", rName);
    getResourceContext().getPluginConfiguration().put(pluginNameProperty);

    File deployDir = new File(parentResourceComponent.getConfigurationPath() + "/deploy");
    File deploymentFile =
        new File(deployDir, FileNameUtility.formatFileName(name) + "-destination-service.xml");

    xmlEditor = new JBossMessagingConfigurationEditor(resourceTypeName);
    xmlEditor.updateConfiguration(deploymentFile, name, report);
    try {
      parentResourceComponent.deployFile(deploymentFile);
    } catch (Exception e) {
      JBossASServerComponent.setErrorOnCreateResourceReport(report, e.getLocalizedMessage(), e);
      return report;
    }

    // This key needs to be the same as the object name string used in discovery, defined in the
    // plugin descriptor
    //   jboss.messaging.destination:service=<Queue|Topic>,name=%name%
    String serviceString = (isTopic ? "Topic" : "Queue");

    String objectName = "jboss.messaging.destination:name=" + name + ",service=" + serviceString;
    try {
      // IMPORTANT: The object name must be canonicalized so it matches the resource key that
      //            MBeanResourceDiscoveryComponent uses, which is the canonical object name.
      objectName = getCanonicalName(objectName);
      report.setResourceKey(objectName);
    } catch (MalformedObjectNameException e) {
      log.warn("Invalid key [" + objectName + "]: " + e.getMessage());
      return report;
    }
    report.setResourceName(rName);

    try {
      Thread.sleep(5000L);
    } catch (InterruptedException e) {
      log.info("Sleep after datasource create interrupted", e);
      Thread.currentThread().interrupt();
    }

    return report;
  }
  @Override
  protected AlertCriteria getFetchCriteria(DSRequest request) {
    AlertCriteria criteria = new AlertCriteria();

    // retrieve previous settings from portlet config
    if ((portlet != null) && (this.portlet instanceof DashboardPortlet)) {
      Configuration portletConfig = configuration;
      // filter priority, if null or empty then no priority filtering
      String currentSetting =
          portletConfig.getSimpleValue(Constant.ALERT_PRIORITY, Constant.ALERT_PRIORITY_DEFAULT);
      if (!currentSetting.trim().isEmpty()) {
        String[] parsedValues = currentSetting.trim().split(",");

        if (parsedValues.length < AlertPriority.values().length) {
          AlertPriority[] filterPriorities = new AlertPriority[parsedValues.length];
          int indx = 0;
          for (String priority : parsedValues) {
            AlertPriority p = AlertPriority.valueOf(priority);
            filterPriorities[indx++] = p;
          }
          criteria.addFilterPriorities(filterPriorities);
        }
      }

      PageControl pc = new PageControl();
      // result sort order
      currentSetting =
          portletConfig.getSimpleValue(
              Constant.RESULT_SORT_ORDER, Constant.RESULT_SORT_ORDER_DEFAULT);
      if (currentSetting.trim().isEmpty()) {
        pc.setPrimarySortOrder(PageOrdering.valueOf(Constant.RESULT_SORT_ORDER_DEFAULT));
      } else {
        pc.setPrimarySortOrder(PageOrdering.valueOf(currentSetting));
      }

      // result timeframe if enabled
      PropertySimple property = portletConfig.getSimple(Constant.METRIC_RANGE_ENABLE);
      if (null != property && Boolean.valueOf(property.getBooleanValue())) { // then proceed setting

        boolean isAdvanced =
            Boolean.valueOf(
                portletConfig.getSimpleValue(
                    Constant.METRIC_RANGE_BEGIN_END_FLAG,
                    Constant.METRIC_RANGE_BEGIN_END_FLAG_DEFAULT));
        if (isAdvanced) {
          // Advanced time settings
          currentSetting =
              portletConfig.getSimpleValue(Constant.METRIC_RANGE, Constant.METRIC_RANGE_DEFAULT);
          String[] range = currentSetting.split(",");
          if (range.length == 2) {
            criteria.addFilterStartTime(Long.valueOf(range[0]));
            criteria.addFilterEndTime(Long.valueOf(range[1]));
          }
        } else {
          // Simple time settings
          property = portletConfig.getSimple(Constant.METRIC_RANGE_LASTN);
          if (property != null) {
            Integer lastN =
                Integer.valueOf(
                    portletConfig.getSimpleValue(
                        Constant.METRIC_RANGE_LASTN, Constant.METRIC_RANGE_LASTN_DEFAULT));
            Integer units =
                Integer.valueOf(
                    portletConfig.getSimpleValue(
                        Constant.METRIC_RANGE_UNIT, Constant.METRIC_RANGE_UNIT_DEFAULT));
            ArrayList<Long> beginEnd = MeasurementUtility.calculateTimeFrame(lastN, units);
            criteria.addFilterStartTime(Long.valueOf(beginEnd.get(0)));
            criteria.addFilterEndTime(Long.valueOf(beginEnd.get(1)));
          }
        }
      }

      // result count
      currentSetting =
          portletConfig.getSimpleValue(Constant.RESULT_COUNT, Constant.RESULT_COUNT_DEFAULT);
      if (currentSetting.trim().isEmpty()) {
        pc.setPageSize(Integer.valueOf(Constant.RESULT_COUNT_DEFAULT));
      } else {
        pc.setPageSize(Integer.valueOf(currentSetting));
      }

      criteria.setPageControl(pc);

      if (groupId != null) {
        criteria.addFilterResourceGroupIds(groupId);
      }
      if ((resourceIds != null) && (resourceIds.length > 0)) {
        criteria.addFilterResourceIds(resourceIds);
      }
    }
    criteria.fetchAlertDefinition(true);
    criteria.fetchRecoveryAlertDefinition(true);
    criteria.fetchConditionLogs(true);
    return criteria;
  }
Beispiel #16
0
  @Override
  public CreateResourceReport createResource(CreateResourceReport report) {
    report.setStatus(CreateResourceStatus.INVALID_CONFIGURATION);
    Address createAddress = new Address(this.address);

    String path = report.getPluginConfiguration().getSimpleValue("path", "");
    String resourceName;
    if (!path.contains("=")) {
      // this is not a singleton subsystem
      // resources like  example=test1 and example=test2 can be created
      resourceName = report.getUserSpecifiedResourceName();
    } else {
      // this is a request to create a true singleton subsystem
      // both the path and the name are set at resource level configuration
      resourceName = path.substring(path.indexOf('=') + 1);
      path = path.substring(0, path.indexOf('='));
    }

    createAddress.add(path, resourceName);

    Operation op = new Operation("add", createAddress);
    for (Property prop : report.getResourceConfiguration().getProperties()) {
      SimpleEntry<String, ?> entry = null;

      boolean isEntryEligible = true;
      if (prop instanceof PropertySimple) {
        PropertySimple propertySimple = (PropertySimple) prop;
        PropertyDefinitionSimple propertyDefinition =
            this.configurationDefinition.getPropertyDefinitionSimple(propertySimple.getName());

        if (propertyDefinition == null
            || (!propertyDefinition.isRequired() && propertySimple.getStringValue() == null)) {
          isEntryEligible = false;
        } else {
          entry = preparePropertySimple(propertySimple, propertyDefinition);
        }
      } else if (prop instanceof PropertyList) {
        PropertyList propertyList = (PropertyList) prop;
        PropertyDefinitionList propertyDefinition =
            this.configurationDefinition.getPropertyDefinitionList(propertyList.getName());

        if (!propertyDefinition.isRequired() && propertyList.getList().size() == 0) {
          isEntryEligible = false;
        } else {
          entry = preparePropertyList(propertyList, propertyDefinition);
        }
      } else if (prop instanceof PropertyMap) {
        PropertyMap propertyMap = (PropertyMap) prop;
        PropertyDefinitionMap propertyDefinition =
            this.configurationDefinition.getPropertyDefinitionMap(propertyMap.getName());

        if (!propertyDefinition.isRequired() && propertyMap.getMap().size() == 0) {
          isEntryEligible = false;
        } else {
          entry = preparePropertyMap(propertyMap, propertyDefinition);
        }
      }

      if (isEntryEligible) {
        op.addAdditionalProperty(entry.getKey(), entry.getValue());
      }
    }

    Result result = this.connection.execute(op);
    if (result.isSuccess()) {
      report.setStatus(CreateResourceStatus.SUCCESS);
      report.setResourceKey(createAddress.getPath());
      report.setResourceName(report.getUserSpecifiedResourceName());
    } else {
      report.setStatus(CreateResourceStatus.FAILURE);
      report.setErrorMessage(result.getFailureDescription());
    }

    return report;
  }
Beispiel #17
0
 public void print(PropertySimple p, int depth) {
   out.println(indent(depth) + p.getName() + " = " + p.getStringValue());
 }
Beispiel #18
0
  @Override
  public void updateResourceConfiguration(
      final ConfigurationUpdateReport configurationUpdateReport) {
    ResourceType resourceType = context.getResourceType();
    ConfigurationDefinition configDef = resourceType.getResourceConfigurationDefinition();
    Configuration newConfig = configurationUpdateReport.getConfiguration();

    // remove special property being possibly sent from server in case EAP requires reload/restart
    newConfig.remove("__OOB");

    // 1. First of all, read the current configuration
    ConfigurationLoadDelegate readDelegate =
        new ConfigurationLoadDelegate(configDef, getASConnection(), address, includeRuntime);
    Configuration currentConfig;
    try {
      currentConfig = readDelegate.loadResourceConfiguration();
    } catch (Exception e) {
      getLog().error("Could not read current configuration before update", e);
      configurationUpdateReport.setStatus(FAILURE);
      configurationUpdateReport.setErrorMessage(
          "Could not read current configuration before update: " + ThrowableUtil.getRootMessage(e));
      return;
    }

    // 2. We will wrap all property-simple and connection properties changes in a composite
    // operation
    CompositeOperation updateOperation = new CompositeOperation();

    // 3. Capture property-simple changes
    Map<String, PropertySimple> newConfigSimpleProperties = newConfig.getSimpleProperties();
    Map<String, PropertySimple> currentConfigSimpleProperties = currentConfig.getSimpleProperties();

    Set<String> allSimplePropertyNames =
        new HashSet<String>(
            newConfigSimpleProperties.size() + currentConfigSimpleProperties.size());
    allSimplePropertyNames.addAll(newConfigSimpleProperties.keySet());
    allSimplePropertyNames.addAll(currentConfigSimpleProperties.keySet());
    // Read-only
    allSimplePropertyNames.remove(ENABLED_ATTRIBUTE);

    for (String simplePropertyName : allSimplePropertyNames) {
      PropertySimple newConfigPropertySimple = newConfigSimpleProperties.get(simplePropertyName);
      String newConfigPropertySimpleValue =
          newConfigPropertySimple == null ? null : newConfigPropertySimple.getStringValue();
      PropertySimple currentConfigPropertySimple =
          currentConfigSimpleProperties.get(simplePropertyName);
      String currentConfigPropertySimpleValue =
          currentConfigPropertySimple == null ? null : currentConfigPropertySimple.getStringValue();
      boolean canUnset = !UNSET_FORBIDDEN_ATTRIBUTES.contains(simplePropertyName);

      if (newConfigPropertySimpleValue == null) {
        if (currentConfigPropertySimpleValue != null) {
          String val;
          if (canUnset) {
            val = null;
          } else {
            val = configDef.getPropertyDefinitionSimple(simplePropertyName).getDefaultValue();
          }
          updateOperation.addStep(new WriteAttribute(getAddress(), simplePropertyName, val));
        }
      } else if (!newConfigPropertySimpleValue.equals(currentConfigPropertySimpleValue)) {
        updateOperation.addStep(
            new WriteAttribute(getAddress(), simplePropertyName, newConfigPropertySimpleValue));
      }
    }

    // 4. Capture connection property changes
    String connPropAttributeNameOnServer, connPropPluginConfigPropertyName, keyName;
    if (isXADatasourceResource(resourceType)) {
      connPropAttributeNameOnServer = "xa-datasource-properties";
      connPropPluginConfigPropertyName = XA_DATASOURCE_PROPERTIES_ATTRIBUTE;
      keyName = "key";
    } else {
      connPropAttributeNameOnServer = "connection-properties";
      connPropPluginConfigPropertyName = CONNECTION_PROPERTIES_ATTRIBUTE;
      keyName = "pname";
    }

    Map<String, String> newConfigConnectionProperties =
        getConnectionPropertiesAsMap(newConfig.getList(connPropPluginConfigPropertyName), keyName);
    Map<String, String> currentConfigConnectionProperties =
        getConnectionPropertiesAsMap(
            currentConfig.getList(connPropPluginConfigPropertyName), keyName);
    Set<String> allConnectionPropertyNames =
        new HashSet<String>(
            newConfigConnectionProperties.size() + currentConfigConnectionProperties.size());
    allConnectionPropertyNames.addAll(newConfigConnectionProperties.keySet());
    allConnectionPropertyNames.addAll(currentConfigConnectionProperties.keySet());

    for (String connectionPropertyName : allConnectionPropertyNames) {
      Address propertyAddress = new Address(getAddress());
      propertyAddress.add(connPropAttributeNameOnServer, connectionPropertyName);

      String newConfigConnectionPropertyValue =
          newConfigConnectionProperties.get(connectionPropertyName);
      String currentConfigConnectionPropertyValue =
          currentConfigConnectionProperties.get(connectionPropertyName);

      if (newConfigConnectionPropertyValue == null) {
        updateOperation.addStep(new Operation("remove", propertyAddress));
      } else if (currentConfigConnectionPropertyValue == null) {
        Operation addOperation = new Operation("add", propertyAddress);
        addOperation.addAdditionalProperty("value", newConfigConnectionPropertyValue);
        updateOperation.addStep(addOperation);
      } else if (!newConfigConnectionPropertyValue.equals(currentConfigConnectionPropertyValue)) {
        updateOperation.addStep(new Operation("remove", propertyAddress));
        Operation addOperation = new Operation("add", propertyAddress);
        addOperation.addAdditionalProperty("value", newConfigConnectionPropertyValue);
        updateOperation.addStep(addOperation);
      }
    }

    // 5. Update config if needed
    if (updateOperation.numberOfSteps() > 0) {
      Result res = getASConnection().execute(updateOperation);
      if (res.isSuccess()) {
        configurationUpdateReport.setStatus(SUCCESS);
      } else {
        configurationUpdateReport.setStatus(FAILURE);
        configurationUpdateReport.setErrorMessage(res.getFailureDescription());
      }
    } else {
      configurationUpdateReport.setStatus(NOCHANGE);
    }
  }
Beispiel #19
0
  private CreateResourceReport createConfigurationBasedResource(
      CreateResourceReport createResourceReport) {
    ResourceType resourceType = createResourceReport.getResourceType();
    Configuration defaultPluginConfig = getDefaultPluginConfiguration(resourceType);
    Configuration resourceConfig = createResourceReport.getResourceConfiguration();
    String resourceName = getResourceName(defaultPluginConfig, resourceConfig);
    ComponentType componentType = ProfileServiceUtil.getComponentType(resourceType);
    ManagementView managementView = null;
    ;
    managementView = getConnection().getManagementView();

    if (ProfileServiceUtil.isManagedComponent(getConnection(), resourceName, componentType)) {
      createResourceReport.setStatus(CreateResourceStatus.FAILURE);
      createResourceReport.setErrorMessage(
          "A "
              + resourceType.getName() // $NON-NLS-1$
              + " named '"
              + resourceName
              + "' already exists."); //$NON-NLS-1$ //$NON-NLS-2$
      return createResourceReport;
    }

    createResourceReport.setResourceName(resourceName);
    String resourceKey = getResourceKey(resourceType, resourceName);
    createResourceReport.setResourceKey(resourceKey);

    PropertySimple templateNameProperty =
        resourceConfig.getSimple(TranslatorComponent.Config.TEMPLATE_NAME);
    String templateName = templateNameProperty.getStringValue();

    DeploymentTemplateInfo template;
    try {
      template = managementView.getTemplate(templateName);
      Map<String, ManagedProperty> managedProperties = template.getProperties();

      ProfileServiceUtil.convertConfigurationToManagedProperties(
          managedProperties, resourceConfig, resourceType, null);

      LOG.debug(
          "Applying template ["
              + templateName //$NON-NLS-1$
              + "] to create ManagedComponent of type ["
              + componentType //$NON-NLS-1$
              + "]..."); //$NON-NLS-1$
      try {
        managementView.applyTemplate(resourceName, template);
        managementView.process();
        createResourceReport.setStatus(CreateResourceStatus.SUCCESS);
      } catch (Exception e) {
        LOG.error(
            "Unable to apply template ["
                + templateName //$NON-NLS-1$
                + "] to create ManagedComponent of type " //$NON-NLS-1$
                + componentType
                + ".",
            e); //$NON-NLS-1$
        createResourceReport.setStatus(CreateResourceStatus.FAILURE);
        createResourceReport.setException(e);
      }
    } catch (NoSuchDeploymentException e) {
      LOG.error("Unable to find template [" + templateName + "].", e); // $NON-NLS-1$ //$NON-NLS-2$
      createResourceReport.setStatus(CreateResourceStatus.FAILURE);
      createResourceReport.setException(e);
    } catch (Exception e) {
      LOG.error("Unable to process create request", e); // $NON-NLS-1$
      createResourceReport.setStatus(CreateResourceStatus.FAILURE);
      createResourceReport.setException(e);
    }
    return createResourceReport;
  }
  private void updateTemplate(ConfigurationTemplate existingDT, ConfigurationTemplate newDT) {

    try {
      Configuration existConf = existingDT.getConfiguration();
      Configuration newConf = newDT.getConfiguration();
      Collection<String> exNames = existConf.getNames();
      Collection<String> newNames = newConf.getNames();
      List<String> toRemove = new ArrayList<String>();
      for (String name : exNames) {
        Property prop = newConf.get(name);
        if (prop instanceof PropertySimple) {
          PropertySimple ps = newConf.getSimple(name);
          if (ps != null) {
            Property eprop = existConf.get(name);
            if (eprop instanceof PropertySimple) {
              PropertySimple exps = existConf.getSimple(name);
              if (ps.getStringValue() != null) {
                exps.setStringValue(ps.getStringValue());
                //                                System.out.println("  updated " + name + " to
                // value " + ps.getStringValue());
              }
            } else {
              if (eprop != null) {
                //                                System.out.println("Can't yet handle target prop:
                // " + eprop);
              }
            }
          } else { // property not in new template -> deleted
            toRemove.add(name);
          }
        } else {
          if (prop != null) {
            //                        System.out.println("Can't yet handle source prop: " + prop);
          }
        }
      }
      for (String name : toRemove) existConf.remove(name);

      // now check for new names and add them
      for (String name : newNames) {
        if (!exNames.contains(name)) {
          Property prop = newConf.get(name);
          if (prop instanceof PropertySimple) {
            PropertySimple ps = newConf.getSimple(name);
            if (ps.getStringValue() != null) {
              // TODO add a new property
              //                            Collection<Property> properties =
              // existConf.getProperties();
              //                            properties = new ArrayList<Property>(properties);
              //                            properties.add(ps);
              //                            existConf.setProperties(properties);
              Property property = ps.deepCopy(false);
              existConf.put(property);
            }
          }
        }
      }

      entityManager.flush();
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }
Beispiel #21
0
  private void save() {
    if (editor.validate()) {
      Map<String, PropertySimple> simpleProperties =
          editor.getConfiguration().getSimpleProperties();
      HashMap<String, String> props = new HashMap<String, String>();
      for (PropertySimple simple : simpleProperties.values()) {
        String value = (simple.getStringValue() != null) ? simple.getStringValue() : "";

        // some of our properties actually need different values on the server than how they were
        // visualized in the UI.
        // -- JAASProvider is a boolean in the UI but must be "LDAP" if it was true and "JDBC" if it
        // was false
        // -- LDAPProtocol is a boolean in the UI but must be "ssl" if true and "" if it was false
        // -- some other numerical values need to be converted to milliseconds
        if (Constant.JAASProvider.equals(simple.getName())) {
          if (Boolean.parseBoolean(value)) {
            value = Constant.LDAPJAASProvider;
          } else {
            value = Constant.JDBCJAASProvider;
          }
        } else if (Constant.LDAPProtocol.equals(simple.getName())) {
          if (Boolean.parseBoolean(value)) {
            value = "ssl";
          } else {
            value = "";
          }
        } else if (Constant.AgentMaxQuietTimeAllowed.equals(simple.getName())) {
          value = convertMinutesToMillis(value);
        } else if (Constant.DataMaintenance.equals(simple.getName())) {
          value = convertHoursToMillis(value);
        } else if (Constant.AvailabilityPurge.equals(simple.getName())
            || Constant.AlertPurge.equals(simple.getName())
            || Constant.TraitPurge.equals(simple.getName())
            || Constant.RtDataPurge.equals(simple.getName())
            || Constant.EventPurge.equals(simple.getName())
            || Constant.DriftFilePurge.equals(simple.getName())
            || Constant.BaselineFrequency.equals(simple.getName())
            || Constant.BaselineDataSet.equals(simple.getName())) {
          value = convertDaysToMillis(value);
        }

        props.put(simple.getName(), value);
      }

      GWTServiceLookup.getSystemService()
          .setSystemConfiguration(
              props,
              false,
              new AsyncCallback<Void>() {
                @Override
                public void onSuccess(Void result) {
                  CoreGUI.getMessageCenter()
                      .notify(
                          new Message(
                              MSG.view_admin_systemSettings_savedSettings(),
                              Message.Severity.Info));
                }

                @Override
                public void onFailure(Throwable caught) {
                  CoreGUI.getErrorHandler()
                      .handleError(MSG.view_admin_systemSettings_saveFailure(), caught);
                }
              });
    } else {
      CoreGUI.getMessageCenter()
          .notify(
              new Message(
                  MSG.view_admin_systemSettings_fixBeforeSaving(),
                  Severity.Warning,
                  EnumSet.of(Message.Option.Transient)));
    }
  }