/* * Copyright (C) 2024 johan@nosd.in * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * . */ package in.nosd.redis.functions; import com.google.common.base.Strings; import in.nosd.redis.functions.GenericLookupResult; import in.nosd.redis.functions.LookupTableFunction; import org.graylog.plugins.pipelineprocessor.EvaluationContext; import org.graylog.plugins.pipelineprocessor.ast.functions.FunctionArgs; import org.graylog.plugins.pipelineprocessor.ast.functions.FunctionDescriptor; import org.graylog.plugins.pipelineprocessor.ast.functions.ParameterDescriptor; import org.graylog2.lookup.LookupTableService; import org.graylog2.plugin.lookup.LookupResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; public class RedisLookupPluginFunction extends LookupTableFunction { private static final Logger LOG = LoggerFactory.getLogger(RedisLookupPluginFunction.class); public static final String NAME = "redis_lookup"; private static final String VALUE = "value"; private static final String LOOKUP_TABLE_NAME = "redis-lookup"; private final ParameterDescriptor keyParam = ParameterDescriptor.string(VALUE).description("The key to look up.").build(); private final LookupTableService.Function lookupFunction; @Inject public RedisLookupPluginFunction(final LookupTableService lookupTableService) { this.lookupFunction = lookupTableService.newBuilder().lookupTable(LOOKUP_TABLE_NAME).build(); } @Override public GenericLookupResult evaluate(FunctionArgs args, EvaluationContext context) { String key = keyParam.required(args, context); if (key == null) { LOG.error("NULL parameter passed to Redis lookup."); return null; } LOG.debug("Running Redis lookup for key [{}].", key); final LookupResult lookupResult = this.lookupFunction.lookup(key.trim()); if (lookupResult != null && !lookupResult.isEmpty()) { // If not a String, then fall through to false at the end of the method. final Object value = lookupResult.singleValue(); if (value instanceof String) { return !Strings.isNullOrEmpty((String) value) ? GenericLookupResult.TRUE : GenericLookupResult.FALSE; } } return GenericLookupResult.FALSE; } @Override public FunctionDescriptor descriptor() { return FunctionDescriptor.builder() .name(NAME) .description("Match a key into Redis instance and return value") .params(keyParam) .returnType(GenericLookupResult.class) .build(); } }