Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.stormcrawler.opensearch;

import com.fasterxml.jackson.databind.JsonNode;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.stormcrawler.JSONResource;
import org.opensearch.action.get.GetRequest;
import org.opensearch.action.get.GetResponse;
import org.opensearch.client.RequestOptions;
import org.opensearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Loads a delegate class that implements both a required base type and {@link JSONResource}, then
* periodically refreshes its configuration from OpenSearch. Used by {@link
* org.apache.stormcrawler.opensearch.filtering.JSONURLFilterWrapper} and {@link
* org.apache.stormcrawler.opensearch.parse.filter.JSONResourceWrapper} to eliminate duplicated
* setup/refresh/cleanup logic.
*
* @param <T> the base type that the delegate must extend (e.g. URLFilter or ParseFilter)
*/
public class DelegateRefresher<T> {

private static final Logger LOG = LoggerFactory.getLogger(DelegateRefresher.class);

private final T delegate;
private Timer refreshTimer;
private RestHighLevelClient osClient;

/**
* Creates a refresher by loading the delegate class from the JSON configuration.
*
* @param baseType the required base class (e.g. URLFilter.class or ParseFilter.class)
* @param stormConf the Storm configuration map
* @param filterParams the JSON params node containing "delegate" and optional "refresh"
* @param configurer callback to configure the delegate after instantiation
*/
public DelegateRefresher(
Class<T> baseType,
Map<String, Object> stormConf,
JsonNode filterParams,
DelegateConfigure<T> configurer) {

JsonNode delegateNode = filterParams.get("delegate");
if (delegateNode == null) {
throw new RuntimeException("delegateNode undefined!");
}

String delegateClassName = null;
JsonNode node = delegateNode.get("class");
if (node != null && node.isTextual()) {
delegateClassName = node.asText();
}
if (delegateClassName == null) {
throw new RuntimeException(baseType.getSimpleName() + " delegate class undefined!");
}

try {
Class<?> filterClass = Class.forName(delegateClassName);

if (!baseType.isAssignableFrom(filterClass)) {
throw new RuntimeException(
"Filter " + delegateClassName + " does not extend " + baseType.getName());
}

@SuppressWarnings("unchecked")
T instance = (T) filterClass.getDeclaredConstructor().newInstance();

if (!(instance instanceof JSONResource)) {
throw new RuntimeException(
"Filter " + delegateClassName + " does not implement JSONResource");
}

this.delegate = instance;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
LOG.error("Can't setup {}: {}", delegateClassName, e);
throw new RuntimeException("Can't setup " + delegateClassName, e);
}

// configure the delegate
JsonNode paramsNode = delegateNode.get("params");
configurer.configure(delegate, stormConf, paramsNode);

// set up periodic refresh from OpenSearch
int refreshRate = 600;
node = filterParams.get("refresh");
if (node != null && (node.isInt() || node.isTextual())) {
refreshRate = node.asInt(refreshRate);
}

final JSONResource resource = (JSONResource) delegate;

refreshTimer = new Timer();
refreshTimer.schedule(
new TimerTask() {
public void run() {
if (osClient == null) {
try {
osClient = OpenSearchConnection.getClient(stormConf, "config");
} catch (Exception e) {
LOG.error("Exception while creating OpenSearch connection", e);
}
}
if (osClient != null) {
LOG.info("Reloading json resources from OpenSearch");
try {
GetResponse response =
osClient.get(
new GetRequest(
"config", resource.getResourceFile()),
RequestOptions.DEFAULT);
resource.loadJSONResources(
new ByteArrayInputStream(response.getSourceAsBytes()));
} catch (Exception e) {
LOG.error("Can't load config from OpenSearch", e);
}
}
}
},
refreshRate * 1000L,
refreshRate * 1000L);
}

/** Returns the delegate instance. */
public T getDelegate() {
return delegate;
}

/** Cancels the refresh timer and closes the OpenSearch client. */
public void cleanup() {
if (refreshTimer != null) {
refreshTimer.cancel();
}
if (osClient != null) {
try {
osClient.close();
} catch (IOException e) {
LOG.error("Exception when closing OpenSearch client", e);
}
osClient = null;
}
}

/** Callback interface for configuring the delegate after instantiation. */
@FunctionalInterface
public interface DelegateConfigure<T> {
void configure(T delegate, Map<String, Object> stormConf, JsonNode params);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,13 @@
package org.apache.stormcrawler.opensearch.filtering;

import com.fasterxml.jackson.databind.JsonNode;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.stormcrawler.JSONResource;
import org.apache.stormcrawler.Metadata;
import org.apache.stormcrawler.filtering.URLFilter;
import org.apache.stormcrawler.opensearch.OpenSearchConnection;
import org.apache.stormcrawler.opensearch.DelegateRefresher;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.opensearch.action.get.GetRequest;
import org.opensearch.action.get.GetResponse;
import org.opensearch.client.RequestOptions;
import org.opensearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Wraps a URLFilter whose resources are in a JSON file that can be stored in OpenSearch. The
Expand All @@ -47,8 +36,8 @@
*
* <pre>
* {
* "class": "org.apache.stormcrawler.elasticsearch.filtering.JSONURLFilterWrapper",
* "name": "ESFastURLFilter",
* "class": "org.apache.stormcrawler.opensearch.filtering.JSONURLFilterWrapper",
* "name": "OSFastURLFilter",
* "params": {
* "refresh": "60",
* "delegate": {
Expand All @@ -69,117 +58,27 @@
*/
public class JSONURLFilterWrapper extends URLFilter {

private static final Logger LOG = LoggerFactory.getLogger(JSONURLFilterWrapper.class);

private URLFilter delegatedURLFilter;
private Timer refreshTimer;
private RestHighLevelClient osClient;
private DelegateRefresher<URLFilter> refresher;

public void configure(@NotNull Map<String, Object> stormConf, @NotNull JsonNode filterParams) {

String urlfilterclass = null;

JsonNode delegateNode = filterParams.get("delegate");
if (delegateNode == null) {
throw new RuntimeException("delegateNode undefined!");
}

JsonNode node = delegateNode.get("class");
if (node != null && node.isTextual()) {
urlfilterclass = node.asText();
}

if (urlfilterclass == null) {
throw new RuntimeException("urlfilter.class undefined!");
}

// load an instance of the delegated parsefilter
try {
Class<?> filterClass = Class.forName(urlfilterclass);

boolean subClassOK = URLFilter.class.isAssignableFrom(filterClass);
if (!subClassOK) {
throw new RuntimeException(
"Filter " + urlfilterclass + " does not extend URLFilter");
}

delegatedURLFilter = (URLFilter) filterClass.getDeclaredConstructor().newInstance();

// check that it implements JSONResource
if (!JSONResource.class.isInstance(delegatedURLFilter)) {
throw new RuntimeException(
"Filter " + urlfilterclass + " does not implement JSONResource");
}

} catch (Exception e) {
LOG.error("Can't setup {}: {}", urlfilterclass, e);
throw new RuntimeException("Can't setup " + urlfilterclass, e);
}

// configure it
node = delegateNode.get("params");

delegatedURLFilter.configure(stormConf, node);

int refreshRate = 600;

node = filterParams.get("refresh");
if (node != null && node.isInt()) {
refreshRate = node.asInt(refreshRate);
}

final JSONResource resource = (JSONResource) delegatedURLFilter;

refreshTimer = new Timer();
refreshTimer.schedule(
new TimerTask() {
public void run() {
if (osClient == null) {
try {
osClient = OpenSearchConnection.getClient(stormConf, "config");
} catch (Exception e) {
LOG.error("Exception while creating OpenSearch connection", e);
}
}
if (osClient != null) {
LOG.info("Reloading json resources from OpenSearch");
try {
GetResponse response =
osClient.get(
new GetRequest(
"config", resource.getResourceFile()),
RequestOptions.DEFAULT);
resource.loadJSONResources(
new ByteArrayInputStream(response.getSourceAsBytes()));
} catch (Exception e) {
LOG.error("Can't load config from OpenSearch", e);
}
}
}
},
0,
refreshRate * 1000);
refresher =
new DelegateRefresher<>(
URLFilter.class,
stormConf,
filterParams,
(delegate, conf, params) -> delegate.configure(conf, params));
}

@Override
public @Nullable String filter(
@Nullable URL sourceUrl,
@Nullable Metadata sourceMetadata,
@NotNull String urlToFilter) {
return delegatedURLFilter.filter(sourceUrl, sourceMetadata, urlToFilter);
return refresher.getDelegate().filter(sourceUrl, sourceMetadata, urlToFilter);
}

@Override
public void cleanup() {
if (refreshTimer != null) {
refreshTimer.cancel();
}
if (osClient != null) {
try {
osClient.close();
} catch (IOException e) {
LOG.error("Exception when closing OpenSearch client", e);
}
}
refresher.cleanup();
}
}
Loading