Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Refactor] Use local opensearch.common.SetOnce instead of lucene's utility class #5947

Merged
merged 5 commits into from
Jan 20, 2023
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
- Migrate client transports to Apache HttpClient / Core 5.x ([#4459](https:/opensearch-project/OpenSearch/pull/4459))
- Changed http code on create index API with bad input raising NotXContentException from 500 to 400 ([#4773](https:/opensearch-project/OpenSearch/pull/4773))
- Change http code for DecommissioningFailedException from 500 to 400 ([#5283](https:/opensearch-project/OpenSearch/pull/5283))
- [Refactor] Use local opensearch.common.SetOnce instead of lucene's utility class ([#5947](https:/opensearch-project/OpenSearch/pull/5947))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the compatibility concern with backporting this to 2.x? It looks to me like it would be fine since the existing Lucene class remains available for anything that is using it. (If it is possible to backport this change, then the changelog entry should go in the [Unreleased 2.x] section).

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there are no compatibility concerns for backport: the dependency graph is not changing so the SetOnce is still available at the same place as before (lucene-core).


### Deprecated

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ java.nio.channels.SocketChannel#connect(java.net.SocketAddress)
java.lang.Boolean#getBoolean(java.lang.String)

org.apache.lucene.util.IOUtils @ use @org.opensearch.core.internal.io instead
org.apache.lucene.util.SetOnce @ use @org.opensearch.common.SetOnce instead
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍


@defaultMessage use executors from org.opensearch.common.util.concurrent.OpenSearchExecutors instead which will properly bubble up Errors
java.util.concurrent.AbstractExecutorService#<init>()
Expand Down
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.api
*/
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
Loading