public static AlarmCallbackHistory create(
     String id,
     AlarmCallbackConfiguration alarmCallbackConfiguration,
     Alert alert,
     AlertCondition alertCondition,
     AlarmCallbackResult result) {
   return create(id, alarmCallbackConfiguration, alert, alertCondition, result, Tools.nowUTC());
 }
  @Test
  public void runCodegen() throws IOException {
    final Rule rule = parser.parseRule(ruleForTest(), true).withId("1");

    final String sourceCode = CodeGenerator.sourceCodeForRule(rule);
    Files.write(sourceCode, OUTFILE.toFile(), StandardCharsets.UTF_8);

    log.info("Code:\n{}", sourceCode);

    try {

      ClassLoader ruleClassloader = new ClassLoader() {};
      //noinspection unchecked
      Class<GeneratedRule> rule$1 =
          (Class<GeneratedRule>)
              JCC.loadFromJava(
                  ruleClassloader,
                  "org.graylog.plugins.pipelineprocessor.$dynamic.rules.rule$1",
                  sourceCode);

      //noinspection unchecked
      final Set<Constructor> constructors =
          ReflectionUtils.getConstructors(rule$1, input -> input.getParameterCount() == 1);
      final Constructor onlyElement = Iterables.getOnlyElement(constructors);
      final GeneratedRule generatedRule = (GeneratedRule) onlyElement.newInstance(functionRegistry);

      final Message message = new Message("hello", "jenkins.torch.sh", Tools.nowUTC());
      message.addField("message", "#1234");
      message.addField("something_that_doesnt_exist", "foo");
      final EvaluationContext context = new EvaluationContext(message);

      final boolean when = generatedRule.when(context);
      if (when) {
        generatedRule.then(context);
      }
      log.info("created dynamic rule {} matches: {}", generatedRule.name(), when);

      assertThat(context.currentMessage().hasField("some_identifier")).isTrue();

    } catch (InvocationTargetException
        | ClassNotFoundException
        | InstantiationException
        | IllegalAccessException e) {
      log.error("Cannot load dynamically created class!", e);
    }
  }
  @Test
  @UsingDataSet(loadStrategy = LoadStrategyEnum.DELETE_ALL)
  public void testCreate() throws Exception {
    final String title = "Dashboard Title";
    final String description = "This is the dashboard description";
    final String creatorUserId = "foobar";
    final DateTime createdAt = Tools.nowUTC();

    final Dashboard dashboard =
        dashboardService.create(title, description, creatorUserId, createdAt);

    assertNotNull(dashboard);
    assertEquals(title, dashboard.getTitle());
    assertEquals(description, dashboard.getDescription());
    assertNotNull(dashboard.getId());
    assertEquals(0, dashboardService.count());
  }
 protected FieldValueAlertCondition getFieldValueAlertCondition(Map<String, Object> parameters) {
   return new FieldValueAlertCondition(
       searches, stream, CONDITION_ID, Tools.nowUTC(), STREAM_CREATOR, parameters);
 }
Ejemplo n.º 5
0
  public Map<String, Object> toElasticSearchObject(@Nonnull final Meter invalidTimestampMeter) {
    final Map<String, Object> obj =
        Maps.newHashMapWithExpectedSize(REQUIRED_FIELDS.size() + fields.size());

    for (Map.Entry<String, Object> entry : fields.entrySet()) {
      final String key = entry.getKey();

      // Elasticsearch does not allow "." characters in keys since version 2.0.
      // See:
      // https://www.elastic.co/guide/en/elasticsearch/reference/2.0/breaking_20_mapping_changes.html#_field_names_may_not_contain_dots
      if (key != null && key.contains(".")) {
        final String newKey = key.replace('.', KEY_REPLACEMENT_CHAR);

        // If the message already contains the transformed key, we skip the field and emit a
        // warning.
        // This is still not optimal but better than implementing expensive logic with multiple
        // replacement
        // character options. Conflicts should be rare...
        if (!obj.containsKey(newKey)) {
          obj.put(newKey, entry.getValue());
        } else {
          LOG.warn(
              "Keys must not contain a \".\" character! Ignoring field \"{}\"=\"{}\" in message [{}] - Unable to replace \".\" with a \"{}\" because of key conflict: \"{}\"=\"{}\"",
              key,
              entry.getValue(),
              getId(),
              KEY_REPLACEMENT_CHAR,
              newKey,
              obj.get(newKey));
          LOG.debug("Full message with \".\" in message key: {}", this);
        }
      } else {
        if (key != null && obj.containsKey(key)) {
          final String newKey = key.replace(KEY_REPLACEMENT_CHAR, '.');
          // Deliberate warning duplicates because the key with the "." might be transformed before
          // reaching
          // the duplicate original key with a "_". Otherwise we would silently overwrite the
          // transformed key.
          LOG.warn(
              "Keys must not contain a \".\" character! Ignoring field \"{}\"=\"{}\" in message [{}] - Unable to replace \".\" with a \"{}\" because of key conflict: \"{}\"=\"{}\"",
              newKey,
              fields.get(newKey),
              getId(),
              KEY_REPLACEMENT_CHAR,
              key,
              entry.getValue());
          LOG.debug("Full message with \".\" in message key: {}", this);
        }
        obj.put(key, entry.getValue());
      }
    }

    obj.put(FIELD_MESSAGE, getMessage());
    obj.put(FIELD_SOURCE, getSource());

    final Object timestampValue = getField(FIELD_TIMESTAMP);
    DateTime dateTime;
    if (timestampValue instanceof Date) {
      dateTime = new DateTime(timestampValue);
    } else if (timestampValue instanceof DateTime) {
      dateTime = (DateTime) timestampValue;
    } else if (timestampValue instanceof String) {
      // if the timestamp value is a string, we try to parse it in the correct format.
      // we fall back to "now", this avoids losing messages which happen to have the wrong timestamp
      // format
      try {
        dateTime = ES_DATE_FORMAT_FORMATTER.parseDateTime((String) timestampValue);
      } catch (IllegalArgumentException e) {
        LOG.trace(
            "Invalid format for field timestamp '{}' in message {}, forcing to current time.",
            timestampValue,
            getId());
        invalidTimestampMeter.mark();
        dateTime = Tools.nowUTC();
      }
    } else {
      // don't allow any other types for timestamp, force to "now"
      LOG.trace(
          "Invalid type for field timestamp '{}' in message {}, forcing to current time.",
          timestampValue.getClass().getSimpleName(),
          getId());
      invalidTimestampMeter.mark();
      dateTime = Tools.nowUTC();
    }
    if (dateTime != null) {
      obj.put(FIELD_TIMESTAMP, buildElasticSearchTimeFormat(dateTime.withZone(UTC)));
    }

    // Manually converting stream ID to string - caused strange problems without it.
    if (getStreams().isEmpty()) {
      obj.put(FIELD_STREAMS, Collections.emptyList());
    } else {
      final List<String> streamIds = Lists.newArrayListWithCapacity(streams.size());
      for (Stream stream : streams) {
        streamIds.add(stream.getId());
      }
      obj.put(FIELD_STREAMS, streamIds);
    }

    return obj;
  }