Skip to content

Commit

Permalink
[Refactor] Use local opensearch.common.SetOnce instead of lucene's ut…
Browse files Browse the repository at this point in the history
…ility class

This copies Apache Lucene's o.a.l.util.SetOnce to o.opensearch.common.SetOnce in
the opensearch-core library and refactors all opensearch classes from the lucene
implementation to the local opensearch implementation. This accomplishes three
objectives: 1. remove the dependency on lucene-core library for classes that
only import this one lucene utility class, 2. shield opensearch core dependency
on this class from any upstream breaking changes, 3. further decouples other
foundation classes from third party libraries so they can be refactored from the
server module into opensearch support libraries.

Signed-off-by: Nicholas Walter Knize <[email protected]>
  • Loading branch information
nknize committed Jan 19, 2023
1 parent 6f2c125 commit fc0fa9d
Show file tree
Hide file tree
Showing 73 changed files with 296 additions and 72 deletions.
104 changes: 104 additions & 0 deletions libs/core/src/main/java/org/opensearch/common/SetOnce.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

/*
* 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.
*/

/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common;

import java.util.concurrent.atomic.AtomicReference;

/**
* A convenient class which offers a semi-immutable object wrapper implementation which allows one
* to set the value of an object exactly once, and retrieve it many times. If {@link #set(Object)}
* is called more than once, {@link AlreadySetException} is thrown and the operation will fail.
*
* This is borrowed from lucene's experimental API. It is not reused to eliminate the dependency
* on lucene core for such a simple (standalone) utility class that may change beyond OpenSearch needs.
*
* @opensearch.internal
*/
public final class SetOnce<T> implements Cloneable {

/** Thrown when {@link SetOnce#set(Object)} is called more than once. */
public static final class AlreadySetException extends IllegalStateException {
public AlreadySetException() {
super("The object cannot be set twice!");
}
}

/** Holding object and marking that it was already set */
private static final class Wrapper<T> {
private T object;

private Wrapper(T object) {
this.object = object;
}
}

private final AtomicReference<Wrapper<T>> set;

/**
* A default constructor which does not set the internal object, and allows setting it by calling
* {@link #set(Object)}.
*/
public SetOnce() {
set = new AtomicReference<>();
}

/**
* Creates a new instance with the internal object set to the given object. Note that any calls to
* {@link #set(Object)} afterwards will result in {@link AlreadySetException}
*
* @throws AlreadySetException if called more than once
* @see #set(Object)
*/
public SetOnce(T obj) {
set = new AtomicReference<>(new Wrapper<>(obj));
}

/** Sets the given object. If the object has already been set, an exception is thrown. */
public final void set(T obj) {
if (!trySet(obj)) {
throw new AlreadySetException();
}
}

/**
* Sets the given object if none was set before.
*
* @return true if object was set successfully, false otherwise
*/
public final boolean trySet(T obj) {
return set.compareAndSet(null, new Wrapper<>(obj));
}

/** Returns the object set by {@link #set(Object)}. */
public final T get() {
Wrapper<T> wrapper = set.get();
return wrapper == null ? null : wrapper.object;
}
}
120 changes: 120 additions & 0 deletions libs/core/src/test/java/org/opensearch/common/SetOnceTests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

/*
* 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.
*/

/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/

package org.opensearch.common;

import org.opensearch.common.SetOnce.AlreadySetException;
import org.opensearch.test.OpenSearchTestCase;

import java.util.Random;

import static org.hamcrest.CoreMatchers.containsString;

public class SetOnceTests extends OpenSearchTestCase {
private static final class SetOnceThread extends Thread {
SetOnce<Integer> set;
boolean success = false;
final Random RAND;

public SetOnceThread(Random random) {
RAND = new Random(random.nextLong());
}

@Override
public void run() {
try {
sleep(RAND.nextInt(10)); // sleep for a short time
set.set(Integer.valueOf(getName().substring(2)));
success = true;
} catch (@SuppressWarnings("unused") InterruptedException e) {
// ignore
} catch (@SuppressWarnings("unused") RuntimeException e) {
// TODO: change exception type
// expected.
success = false;
}
}
}

public void testEmptyCtor() {
SetOnce<Integer> set = new SetOnce<>();
assertNull(set.get());
}

public void testSettingCtor() {
SetOnce<Integer> set = new SetOnce<>(5);
assertEquals(5, set.get().intValue());

AlreadySetException alreadySetException = expectThrows(AlreadySetException.class, () -> set.set(7));
assertThat(alreadySetException.getMessage(), containsString("The object cannot be set twice!"));
}

public void testSetOnce() {
SetOnce<Integer> set = new SetOnce<>();
set.set(5);
assertEquals(5, set.get().intValue());

AlreadySetException alreadySetException = expectThrows(AlreadySetException.class, () -> set.set(7));
assertThat(alreadySetException.getMessage(), containsString("The object cannot be set twice!"));
}

public void testTrySet() {
SetOnce<Integer> set = new SetOnce<>();
assertTrue(set.trySet(5));
assertEquals(5, set.get().intValue());
assertFalse(set.trySet(7));
assertEquals(5, set.get().intValue());
}

public void testSetMultiThreaded() throws Exception {
final SetOnce<Integer> set = new SetOnce<>();
SetOnceThread[] threads = new SetOnceThread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new SetOnceThread(random());
threads[i].setName("t-" + (i + 1));
threads[i].set = set;
}

for (Thread t : threads) {
t.start();
}

for (Thread t : threads) {
t.join();
}

for (SetOnceThread t : threads) {
if (t.success) {
int expectedVal = Integer.parseInt(t.getName().substring(2));
assertEquals("thread " + t.getName(), expectedVal, t.set.get().intValue());
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,11 @@
import org.apache.lucene.analysis.tr.ApostropheFilter;
import org.apache.lucene.analysis.tr.TurkishAnalyzer;
import org.apache.lucene.analysis.util.ElisionFilter;
import org.apache.lucene.util.SetOnce;
import org.opensearch.Version;
import org.opensearch.client.Client;
import org.opensearch.cluster.metadata.IndexNameExpressionResolver;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.SetOnce;
import org.opensearch.common.io.stream.NamedWriteableRegistry;
import org.opensearch.common.logging.DeprecationLogger;
import org.opensearch.common.regex.Regex;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@
import com.maxmind.geoip2.DatabaseReader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.SetOnce;
import org.opensearch.common.CheckedSupplier;
import org.opensearch.common.SetOnce;
import org.opensearch.core.internal.io.IOUtils;

import java.io.Closeable;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@

package org.opensearch.painless;

import org.apache.lucene.util.SetOnce;
import org.opensearch.action.ActionRequest;
import org.opensearch.action.ActionResponse;
import org.opensearch.client.Client;
import org.opensearch.cluster.metadata.IndexNameExpressionResolver;
import org.opensearch.cluster.node.DiscoveryNodes;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.SetOnce;
import org.opensearch.common.io.stream.NamedWriteableRegistry;
import org.opensearch.common.settings.ClusterSettings;
import org.opensearch.common.settings.IndexScopedSettings;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,13 @@
import org.apache.lucene.util.BitDocIdSet;
import org.apache.lucene.util.BitSet;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.SetOnce;
import org.opensearch.OpenSearchException;
import org.opensearch.ResourceNotFoundException;
import org.opensearch.Version;
import org.opensearch.action.ActionListener;
import org.opensearch.action.get.GetRequest;
import org.opensearch.common.ParseField;
import org.opensearch.common.SetOnce;
import org.opensearch.common.bytes.BytesReference;
import org.opensearch.common.io.stream.InputStreamStreamInput;
import org.opensearch.common.io.stream.NamedWriteableAwareStreamInput;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@

package org.opensearch.index.reindex;

import org.apache.lucene.util.SetOnce;
import org.opensearch.OpenSearchSecurityException;
import org.opensearch.OpenSearchStatusException;
import org.opensearch.action.ActionListener;
Expand All @@ -46,6 +45,7 @@
import org.opensearch.client.Client;
import org.opensearch.cluster.metadata.IndexNameExpressionResolver;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.SetOnce;
import org.opensearch.common.bytes.BytesArray;
import org.opensearch.common.io.stream.NamedWriteableRegistry;
import org.opensearch.common.network.NetworkModule;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.SetOnce;
import org.opensearch.client.Client;
import org.opensearch.cluster.metadata.IndexNameExpressionResolver;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.SetOnce;
import org.opensearch.common.io.stream.NamedWriteableRegistry;
import org.opensearch.common.unit.TimeValue;
import org.opensearch.common.xcontent.NamedXContentRegistry;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@

package org.opensearch.transport;

import org.apache.lucene.util.SetOnce;
import org.opensearch.Version;
import org.opensearch.common.SetOnce;
import org.opensearch.common.io.stream.NamedWriteableRegistry;
import org.opensearch.common.network.NetworkModule;
import org.opensearch.common.network.NetworkService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@
import com.google.api.client.util.ClassInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.SetOnce;
import org.opensearch.cloud.gce.GceInstancesService;
import org.opensearch.cloud.gce.GceInstancesServiceImpl;
import org.opensearch.cloud.gce.GceMetadataService;
import org.opensearch.cloud.gce.network.GceNameResolver;
import org.opensearch.cloud.gce.util.Access;
import org.opensearch.common.Booleans;
import org.opensearch.common.SetOnce;
import org.opensearch.common.network.NetworkService;
import org.opensearch.common.settings.Setting;
import org.opensearch.common.settings.Settings;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.lucene.util.SetOnce;
import org.opensearch.ExceptionsHelper;
import org.opensearch.common.Nullable;
import org.opensearch.common.SetOnce;
import org.opensearch.common.Strings;
import org.opensearch.common.blobstore.BlobContainer;
import org.opensearch.common.blobstore.BlobMetadata;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.SetOnce;
import org.opensearch.Version;
import org.opensearch.common.SetOnce;
import org.opensearch.common.io.stream.NamedWriteableRegistry;
import org.opensearch.common.network.NetworkService;
import org.opensearch.common.settings.ClusterSettings;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.lucene.util.SetOnce;
import org.opensearch.action.admin.cluster.node.info.NodeInfo;
import org.opensearch.action.admin.cluster.node.info.NodesInfoResponse;
import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse;
Expand All @@ -48,6 +47,7 @@
import org.opensearch.client.Request;
import org.opensearch.client.Response;
import org.opensearch.client.ResponseListener;
import org.opensearch.common.SetOnce;
import org.opensearch.common.Strings;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.plugins.Plugin;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@

package org.opensearch.action.admin.cluster.node.tasks;

import org.apache.lucene.util.SetOnce;
import org.opensearch.ExceptionsHelper;
import org.opensearch.ResourceNotFoundException;
import org.opensearch.action.ActionFuture;
Expand All @@ -50,6 +49,7 @@
import org.opensearch.action.support.PlainActionFuture;
import org.opensearch.client.node.NodeClient;
import org.opensearch.cluster.node.DiscoveryNode;
import org.opensearch.common.SetOnce;
import org.opensearch.common.inject.Inject;
import org.opensearch.common.io.stream.StreamInput;
import org.opensearch.common.io.stream.StreamOutput;
Expand Down
Loading

0 comments on commit fc0fa9d

Please sign in to comment.