proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
crate_crate
crate/server/src/main/java/org/elasticsearch/common/settings/Settings.java
FilteredMap
entrySet
class FilteredMap extends AbstractMap<String, Object> { private final Map<String, Object> delegate; private final Predicate<String> filter; private final String prefix; // we cache that size since we have to iterate the entire set // this is safe to do since this map is only used with unmodifiable maps private int size = -1; @Override public Set<Entry<String, Object>> entrySet() {<FILL_FUNCTION_BODY>} private FilteredMap(Map<String, Object> delegate, Predicate<String> filter, String prefix) { this.delegate = delegate; this.filter = filter; this.prefix = prefix; } @Override public Object get(Object key) { if (key instanceof String str) { final String theKey = prefix == null ? str : prefix + str; if (filter.test(theKey)) { return delegate.get(theKey); } } return null; } @Override public boolean containsKey(Object key) { if (key instanceof String str) { final String theKey = prefix == null ? str : prefix + str; if (filter.test(theKey)) { return delegate.containsKey(theKey); } } return false; } @Override public int size() { if (size == -1) { size = Math.toIntExact(delegate.keySet().stream().filter(filter).count()); } return size; } }
Set<Entry<String, Object>> delegateSet = delegate.entrySet(); return new AbstractSet<>() { @Override public Iterator<Entry<String, Object>> iterator() { Iterator<Entry<String, Object>> iter = delegateSet.iterator(); return new Iterator<Entry<String, Object>>() { private int numIterated; private Entry<String, Object> currentElement; @Override public boolean hasNext() { if (currentElement != null) { return true; // protect against calling hasNext twice } else { if (numIterated == size) { // early terminate assert size != -1 : "size was never set: " + numIterated + " vs. " + size; return false; } while (iter.hasNext()) { if (filter.test((currentElement = iter.next()).getKey())) { numIterated++; return true; } } // we didn't find anything currentElement = null; return false; } } @Override public Entry<String, Object> next() { if (currentElement == null && hasNext() == false) { // protect against no #hasNext call or not respecting it throw new NoSuchElementException("make sure to call hasNext first"); } final Entry<String, Object> current = this.currentElement; this.currentElement = null; if (prefix == null) { return current; } return new Entry<String, Object>() { @Override public String getKey() { return current.getKey().substring(prefix.length()); } @Override public Object getValue() { return current.getValue(); } @Override public Object setValue(Object value) { throw new UnsupportedOperationException(); } }; } }; } @Override public int size() { return FilteredMap.this.size(); } };
396
516
912
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/common/time/JavaDateFormatter.java
JavaDateFormatter
equals
class JavaDateFormatter implements DateFormatter { private final String format; private final DateTimeFormatter printer; private final DateTimeFormatter[] parsers; JavaDateFormatter(String format, DateTimeFormatter printer, DateTimeFormatter... parsers) { if (printer == null) { throw new IllegalArgumentException("printer may not be null"); } long distinctZones = Arrays.stream(parsers).map(DateTimeFormatter::getZone).distinct().count(); if (distinctZones > 1) { throw new IllegalArgumentException("formatters must have the same time zone"); } long distinctLocales = Arrays.stream(parsers).map(DateTimeFormatter::getLocale).distinct().count(); if (distinctLocales > 1) { throw new IllegalArgumentException("formatters must have the same locale"); } if (parsers.length == 0) { this.parsers = new DateTimeFormatter[]{printer}; } else { this.parsers = parsers; } this.format = format; this.printer = printer; } @Override public TemporalAccessor parse(String input) { DateTimeParseException failure = null; for (int i = 0; i < parsers.length; i++) { try { return parsers[i].parse(input); } catch (DateTimeParseException e) { if (failure == null) { failure = e; } else { failure.addSuppressed(e); } } } // ensure that all parsers exceptions are returned instead of only the last one throw failure; } @Override public DateFormatter withZone(ZoneId zoneId) { // shortcurt to not create new objects unnecessarily if (zoneId.equals(parsers[0].getZone())) { return this; } final DateTimeFormatter[] parsersWithZone = new DateTimeFormatter[parsers.length]; for (int i = 0; i < parsers.length; i++) { parsersWithZone[i] = parsers[i].withZone(zoneId); } return new JavaDateFormatter(format, printer.withZone(zoneId), parsersWithZone); } @Override public DateFormatter withLocale(Locale locale) { // shortcurt to not create new objects unnecessarily if (locale.equals(parsers[0].getLocale())) { return this; } final DateTimeFormatter[] parsersWithZone = new DateTimeFormatter[parsers.length]; for (int i = 0; i < parsers.length; i++) { parsersWithZone[i] = parsers[i].withLocale(locale); } return new JavaDateFormatter(format, printer.withLocale(locale), parsersWithZone); } @Override public String format(TemporalAccessor accessor) { return printer.format(accessor); } @Override public String pattern() { return format; } @Override public DateFormatter parseDefaulting(Map<TemporalField, Long> fields) { final DateTimeFormatterBuilder parseDefaultingBuilder = new DateTimeFormatterBuilder().append(printer); fields.forEach(parseDefaultingBuilder::parseDefaulting); if (parsers.length == 1 && parsers[0].equals(printer)) { return new JavaDateFormatter(format, parseDefaultingBuilder.toFormatter(Locale.ROOT)); } else { final DateTimeFormatter[] parsersWithDefaulting = new DateTimeFormatter[parsers.length]; for (int i = 0; i < parsers.length; i++) { DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder().append(parsers[i]); fields.forEach(builder::parseDefaulting); parsersWithDefaulting[i] = builder.toFormatter(Locale.ROOT); } return new JavaDateFormatter(format, parseDefaultingBuilder.toFormatter(Locale.ROOT), parsersWithDefaulting); } } @Override public Locale getLocale() { return this.printer.getLocale(); } @Override public ZoneId getZone() { return this.printer.getZone(); } @Override public int hashCode() { return Objects.hash(getLocale(), printer.getZone(), format); } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public String toString() { return String.format(Locale.ROOT, "format[%s] locale[%s]", format, getLocale()); } }
if (obj.getClass().equals(this.getClass()) == false) { return false; } JavaDateFormatter other = (JavaDateFormatter) obj; return Objects.equals(format, other.format) && Objects.equals(getLocale(), other.getLocale()) && Objects.equals(this.printer.getZone(), other.printer.getZone());
1,239
104
1,343
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/common/transport/PortsRange.java
PortsRange
iterate
class PortsRange { private final String portRange; public PortsRange(String portRange) { this.portRange = portRange; } public String getPortRangeString() { return portRange; } public int[] ports() throws NumberFormatException { final IntArrayList ports = new IntArrayList(); iterate(new PortCallback() { @Override public boolean onPortNumber(int portNumber) { ports.add(portNumber); return false; } }); return ports.toArray(); } public boolean iterate(PortCallback callback) throws NumberFormatException {<FILL_FUNCTION_BODY>} public interface PortCallback { boolean onPortNumber(int portNumber); } @Override public String toString() { return "PortsRange{" + "portRange='" + portRange + '\'' + '}'; } }
StringTokenizer st = new StringTokenizer(portRange, ","); boolean success = false; while (st.hasMoreTokens() && !success) { String portToken = st.nextToken().trim(); int index = portToken.indexOf('-'); if (index == -1) { int portNumber = Integer.parseInt(portToken.trim()); success = callback.onPortNumber(portNumber); if (success) { break; } } else { int startPort = Integer.parseInt(portToken.substring(0, index).trim()); int endPort = Integer.parseInt(portToken.substring(index + 1).trim()); if (endPort < startPort) { throw new IllegalArgumentException("Start port [" + startPort + "] must be greater than end port [" + endPort + "]"); } for (int i = startPort; i <= endPort; i++) { success = callback.onPortNumber(i); if (success) { break; } } } } return success;
240
276
516
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/common/unit/Fuzziness.java
Fuzziness
parseCustomAuto
class Fuzziness { public static final Fuzziness ZERO = new Fuzziness(0); public static final Fuzziness ONE = new Fuzziness(1); public static final Fuzziness TWO = new Fuzziness(2); public static final Fuzziness AUTO = new Fuzziness("AUTO"); private static final int DEFAULT_LOW_DISTANCE = 3; private static final int DEFAULT_HIGH_DISTANCE = 6; private final String fuzziness; private int lowDistance = DEFAULT_LOW_DISTANCE; private int highDistance = DEFAULT_HIGH_DISTANCE; private Fuzziness(int fuzziness) { if (fuzziness != 0 && fuzziness != 1 && fuzziness != 2) { throw new IllegalArgumentException("Valid edit distances are [0, 1, 2] but was [" + fuzziness + "]"); } this.fuzziness = Integer.toString(fuzziness); } private Fuzziness(String fuzziness) { if (fuzziness == null || fuzziness.isEmpty()) { throw new IllegalArgumentException("fuzziness can't be null!"); } this.fuzziness = fuzziness.toUpperCase(Locale.ROOT); } private Fuzziness(String fuzziness, int lowDistance, int highDistance) { this(fuzziness); if (lowDistance < 0 || highDistance < 0 || lowDistance > highDistance) { throw new IllegalArgumentException("fuzziness wrongly configured, must be: lowDistance > 0, highDistance" + " > 0 and lowDistance <= highDistance "); } this.lowDistance = lowDistance; this.highDistance = highDistance; } public static Fuzziness build(Object fuzziness) { if (fuzziness instanceof Fuzziness) { return (Fuzziness) fuzziness; } String string = fuzziness.toString(); if (AUTO.asString().equalsIgnoreCase(string)) { return AUTO; } else if (string.toUpperCase(Locale.ROOT).startsWith(AUTO.asString() + ":")) { return parseCustomAuto(string); } return new Fuzziness(string); } private static Fuzziness parseCustomAuto(final String string) {<FILL_FUNCTION_BODY>} public static Fuzziness parse(XContentParser parser) throws IOException { XContentParser.Token token = parser.currentToken(); switch (token) { case VALUE_STRING: case VALUE_NUMBER: final String fuzziness = parser.text(); if (AUTO.asString().equalsIgnoreCase(fuzziness)) { return AUTO; } else if (fuzziness.toUpperCase(Locale.ROOT).startsWith(AUTO.asString() + ":")) { return parseCustomAuto(fuzziness); } try { final int minimumSimilarity = Integer.parseInt(fuzziness); switch (minimumSimilarity) { case 0: return ZERO; case 1: return ONE; case 2: return TWO; default: return build(fuzziness); } } catch (NumberFormatException ex) { return build(fuzziness); } default: throw new IllegalArgumentException("Can't parse fuzziness on token: [" + token + "]"); } } public int asDistance(String text) { if (this.equals(AUTO)) { //AUTO final int len = termLen(text); if (len < lowDistance) { return 0; } else if (len < highDistance) { return 1; } else { return 2; } } return Math.min(2, (int) asFloat()); } public float asFloat() { if (this.equals(AUTO) || isAutoWithCustomValues()) { return 1f; } return Float.parseFloat(fuzziness.toString()); } private int termLen(String text) { return text == null ? 5 : text.codePointCount(0, text.length()); // 5 avg term length in english } public String asString() { if (isAutoWithCustomValues()) { return fuzziness.toString() + ":" + lowDistance + "," + highDistance; } return fuzziness.toString(); } private boolean isAutoWithCustomValues() { return fuzziness.startsWith("AUTO") && (lowDistance != DEFAULT_LOW_DISTANCE || highDistance != DEFAULT_HIGH_DISTANCE); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Fuzziness other = (Fuzziness) obj; return Objects.equals(fuzziness, other.fuzziness); } @Override public int hashCode() { return fuzziness.hashCode(); } }
assert string.toUpperCase(Locale.ROOT).startsWith(AUTO.asString() + ":"); String[] fuzzinessLimit = string.substring(AUTO.asString().length() + 1).split(","); if (fuzzinessLimit.length == 2) { try { int lowerLimit = Integer.parseInt(fuzzinessLimit[0]); int highLimit = Integer.parseInt(fuzzinessLimit[1]); return new Fuzziness("AUTO", lowerLimit, highLimit); } catch (NumberFormatException e) { throw new ElasticsearchParseException("failed to parse [{}] as a \"auto:int,int\"", e, string); } } else { throw new ElasticsearchParseException("failed to find low and high distance values"); }
1,337
206
1,543
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/common/unit/SizeValue.java
SizeValue
toString
class SizeValue implements Writeable, Comparable<SizeValue> { private final long size; private final SizeUnit sizeUnit; public SizeValue(long singles) { this(singles, SizeUnit.SINGLE); } public SizeValue(long size, SizeUnit sizeUnit) { if (size < 0) { throw new IllegalArgumentException("size in SizeValue may not be negative"); } this.size = size; this.sizeUnit = sizeUnit; } public SizeValue(StreamInput in) throws IOException { size = in.readVLong(); sizeUnit = SizeUnit.SINGLE; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVLong(singles()); } public long singles() { return sizeUnit.toSingles(size); } public long getSingles() { return singles(); } public long kilo() { return sizeUnit.toKilo(size); } public long getKilo() { return kilo(); } public long mega() { return sizeUnit.toMega(size); } public long getMega() { return mega(); } public long giga() { return sizeUnit.toGiga(size); } public long getGiga() { return giga(); } public long tera() { return sizeUnit.toTera(size); } public long getTera() { return tera(); } public long peta() { return sizeUnit.toPeta(size); } public long getPeta() { return peta(); } public double kiloFrac() { return ((double) singles()) / SizeUnit.C1; } public double getKiloFrac() { return kiloFrac(); } public double megaFrac() { return ((double) singles()) / SizeUnit.C2; } public double getMegaFrac() { return megaFrac(); } public double gigaFrac() { return ((double) singles()) / SizeUnit.C3; } public double getGigaFrac() { return gigaFrac(); } public double teraFrac() { return ((double) singles()) / SizeUnit.C4; } public double getTeraFrac() { return teraFrac(); } public double petaFrac() { return ((double) singles()) / SizeUnit.C5; } public double getPetaFrac() { return petaFrac(); } @Override public String toString() {<FILL_FUNCTION_BODY>} public static SizeValue parseSizeValue(String sValue) throws ElasticsearchParseException { return parseSizeValue(sValue, null); } public static SizeValue parseSizeValue(String sValue, SizeValue defaultValue) throws ElasticsearchParseException { if (sValue == null) { return defaultValue; } long singles; try { if (sValue.endsWith("k") || sValue.endsWith("K")) { singles = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * SizeUnit.C1); } else if (sValue.endsWith("m") || sValue.endsWith("M")) { singles = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * SizeUnit.C2); } else if (sValue.endsWith("g") || sValue.endsWith("G")) { singles = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * SizeUnit.C3); } else if (sValue.endsWith("t") || sValue.endsWith("T")) { singles = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * SizeUnit.C4); } else if (sValue.endsWith("p") || sValue.endsWith("P")) { singles = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * SizeUnit.C5); } else { singles = Long.parseLong(sValue); } } catch (NumberFormatException e) { throw new ElasticsearchParseException("failed to parse [{}]", e, sValue); } return new SizeValue(singles, SizeUnit.SINGLE); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return compareTo((SizeValue) o) == 0; } @Override public int hashCode() { return Double.hashCode(((double) size) * sizeUnit.toSingles(1)); } @Override public int compareTo(SizeValue other) { double thisValue = ((double) size) * sizeUnit.toSingles(1); double otherValue = ((double) other.size) * other.sizeUnit.toSingles(1); return Double.compare(thisValue, otherValue); } }
long singles = singles(); double value = singles; String suffix = ""; if (singles >= SizeUnit.C5) { value = petaFrac(); suffix = "p"; } else if (singles >= SizeUnit.C4) { value = teraFrac(); suffix = "t"; } else if (singles >= SizeUnit.C3) { value = gigaFrac(); suffix = "g"; } else if (singles >= SizeUnit.C2) { value = megaFrac(); suffix = "m"; } else if (singles >= SizeUnit.C1) { value = kiloFrac(); suffix = "k"; } return Strings.format1Decimals(value, suffix);
1,395
201
1,596
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/common/util/BigByteArray.java
BigByteArray
set
class BigByteArray extends AbstractBigArray implements ByteArray { private static final BigByteArray ESTIMATOR = new BigByteArray(0, BigArrays.NON_RECYCLING_INSTANCE, false); private byte[][] pages; /** Constructor. */ BigByteArray(long size, BigArrays bigArrays, boolean clearOnResize) { super(BYTE_PAGE_SIZE, bigArrays, clearOnResize); this.size = size; pages = new byte[numPages(size)][]; for (int i = 0; i < pages.length; ++i) { pages[i] = newBytePage(i); } } @Override public byte get(long index) { final int pageIndex = pageIndex(index); final int indexInPage = indexInPage(index); return pages[pageIndex][indexInPage]; } @Override public byte set(long index, byte value) { final int pageIndex = pageIndex(index); final int indexInPage = indexInPage(index); final byte[] page = pages[pageIndex]; final byte ret = page[indexInPage]; page[indexInPage] = value; return ret; } @Override public boolean get(long index, int len, BytesRef ref) { assert index + len <= size(); int pageIndex = pageIndex(index); final int indexInPage = indexInPage(index); if (indexInPage + len <= pageSize()) { ref.bytes = pages[pageIndex]; ref.offset = indexInPage; ref.length = len; return false; } else { ref.bytes = new byte[len]; ref.offset = 0; ref.length = pageSize() - indexInPage; System.arraycopy(pages[pageIndex], indexInPage, ref.bytes, 0, ref.length); do { ++pageIndex; final int copyLength = Math.min(pageSize(), len - ref.length); System.arraycopy(pages[pageIndex], 0, ref.bytes, ref.length, copyLength); ref.length += copyLength; } while (ref.length < len); return true; } } @Override public void set(long index, byte[] buf, int offset, int len) {<FILL_FUNCTION_BODY>} @Override public void fill(long fromIndex, long toIndex, byte value) { if (fromIndex > toIndex) { throw new IllegalArgumentException(); } final int fromPage = pageIndex(fromIndex); final int toPage = pageIndex(toIndex - 1); if (fromPage == toPage) { Arrays.fill(pages[fromPage], indexInPage(fromIndex), indexInPage(toIndex - 1) + 1, value); } else { Arrays.fill(pages[fromPage], indexInPage(fromIndex), pages[fromPage].length, value); for (int i = fromPage + 1; i < toPage; ++i) { Arrays.fill(pages[i], value); } Arrays.fill(pages[toPage], 0, indexInPage(toIndex - 1) + 1, value); } } @Override public boolean hasArray() { return false; } @Override public byte[] array() { assert false; throw new UnsupportedOperationException(); } @Override protected int numBytesPerElement() { return 1; } /** Change the size of this array. Content between indexes <code>0</code> and <code>min(size(), newSize)</code> will be preserved. */ @Override public void resize(long newSize) { final int numPages = numPages(newSize); if (numPages > pages.length) { pages = Arrays.copyOf(pages, ArrayUtil.oversize(numPages, RamUsageEstimator.NUM_BYTES_OBJECT_REF)); } for (int i = numPages - 1; i >= 0 && pages[i] == null; --i) { pages[i] = newBytePage(i); } for (int i = numPages; i < pages.length && pages[i] != null; ++i) { pages[i] = null; releasePage(i); } this.size = newSize; } /** Estimates the number of bytes that would be consumed by an array of the given size. */ public static long estimateRamBytes(final long size) { return ESTIMATOR.ramBytesEstimated(size); } }
assert index + len <= size(); int pageIndex = pageIndex(index); final int indexInPage = indexInPage(index); if (indexInPage + len <= pageSize()) { System.arraycopy(buf, offset, pages[pageIndex], indexInPage, len); } else { int copyLen = pageSize() - indexInPage; System.arraycopy(buf, offset, pages[pageIndex], indexInPage, copyLen); do { ++pageIndex; offset += copyLen; len -= copyLen; copyLen = Math.min(len, pageSize()); System.arraycopy(buf, offset, pages[pageIndex], 0, copyLen); } while (len > copyLen); }
1,195
189
1,384
<methods>public final long ramBytesEstimated(long) ,public final long ramBytesUsed() ,public abstract void resize(long) ,public final long size() <variables>private V<?>[] cache,private final non-sealed int pageMask,private final non-sealed int pageShift,private final non-sealed org.elasticsearch.common.util.PageCacheRecycler recycler,protected long size
crate_crate
crate/server/src/main/java/org/elasticsearch/common/util/BigObjectArray.java
BigObjectArray
resize
class BigObjectArray<T> extends AbstractBigArray implements ObjectArray<T> { @SuppressWarnings("rawtypes") private static final BigObjectArray ESTIMATOR = new BigObjectArray(0, BigArrays.NON_RECYCLING_INSTANCE); private Object[][] pages; /** Constructor. */ BigObjectArray(long size, BigArrays bigArrays) { super(OBJECT_PAGE_SIZE, bigArrays, true); this.size = size; pages = new Object[numPages(size)][]; for (int i = 0; i < pages.length; ++i) { pages[i] = newObjectPage(i); } } @SuppressWarnings("unchecked") @Override public T get(long index) { final int pageIndex = pageIndex(index); final int indexInPage = indexInPage(index); return (T) pages[pageIndex][indexInPage]; } @Override public T set(long index, T value) { final int pageIndex = pageIndex(index); final int indexInPage = indexInPage(index); final Object[] page = pages[pageIndex]; @SuppressWarnings("unchecked") final T ret = (T) page[indexInPage]; page[indexInPage] = value; return ret; } @Override protected int numBytesPerElement() { return Integer.BYTES; } /** Change the size of this array. Content between indexes <code>0</code> and <code>min(size(), newSize)</code> will be preserved. */ @Override public void resize(long newSize) {<FILL_FUNCTION_BODY>} /** Estimates the number of bytes that would be consumed by an array of the given size. */ public static long estimateRamBytes(final long size) { return ESTIMATOR.ramBytesEstimated(size); } }
final int numPages = numPages(newSize); if (numPages > pages.length) { pages = Arrays.copyOf(pages, ArrayUtil.oversize(numPages, RamUsageEstimator.NUM_BYTES_OBJECT_REF)); } for (int i = numPages - 1; i >= 0 && pages[i] == null; --i) { pages[i] = newObjectPage(i); } for (int i = numPages; i < pages.length && pages[i] != null; ++i) { pages[i] = null; releasePage(i); } this.size = newSize;
509
169
678
<methods>public final long ramBytesEstimated(long) ,public final long ramBytesUsed() ,public abstract void resize(long) ,public final long size() <variables>private V<?>[] cache,private final non-sealed int pageMask,private final non-sealed int pageShift,private final non-sealed org.elasticsearch.common.util.PageCacheRecycler recycler,protected long size
crate_crate
crate/server/src/main/java/org/elasticsearch/common/util/CancellableThreads.java
CancellableThreads
add
class CancellableThreads { private final Set<Thread> threads = new HashSet<>(); // needs to be volatile as it is also read outside of synchronized blocks. private volatile boolean cancelled = false; private final SetOnce<OnCancel> onCancel = new SetOnce<>(); private String reason; public synchronized boolean isCancelled() { return cancelled; } public void checkForCancel() { checkForCancel(null); } private void checkForCancel(Exception beforeCancelException) { if (isCancelled()) { final String reason; final OnCancel onCancel; synchronized (this) { reason = this.reason; onCancel = this.onCancel.get(); } if (onCancel != null) { onCancel.onCancel(reason, beforeCancelException); } // fallback to the default exception final RuntimeException cancelExp = new ExecutionCancelledException("operation was cancelled reason [" + reason + "]"); if (beforeCancelException != null) { cancelExp.addSuppressed(beforeCancelException); } throw cancelExp; } } private synchronized boolean add() {<FILL_FUNCTION_BODY>} /** * run the Interruptable, capturing the executing thread. Concurrent calls * to {@link #cancel(String)} will interrupt this thread causing the call * to prematurely return. * * @param interruptable code to run */ public void execute(Interruptable interruptable) { boolean wasInterrupted = add(); boolean cancelledByExternalInterrupt = false; RuntimeException runtimeException = null; try { interruptable.run(); } catch (InterruptedException | ThreadInterruptedException e) { // ignore, this interrupt has been triggered by us in #cancel()... assert cancelled : "Interruption via Thread#interrupt() is unsupported. Use CancellableThreads#cancel() instead"; // we can only reach here if assertions are disabled. If we reach this code and cancelled is false, this means that we've // been interrupted externally (which we don't support). cancelledByExternalInterrupt = !cancelled; } catch (RuntimeException t) { runtimeException = t; } finally { remove(); } // we are now out of threads collection so we can't be interrupted any more by this class // restore old flag and see if we need to fail if (wasInterrupted) { Thread.currentThread().interrupt(); } else { // clear the flag interrupted flag as we are checking for failure.. Thread.interrupted(); } checkForCancel(runtimeException); if (runtimeException != null) { // if we're not canceling, we throw the original exception throw runtimeException; } if (cancelledByExternalInterrupt) { // restore interrupt flag to at least adhere to expected behavior Thread.currentThread().interrupt(); throw new RuntimeException("Interruption via Thread#interrupt() is unsupported. Use CancellableThreads#cancel() instead"); } } private synchronized void remove() { threads.remove(Thread.currentThread()); } /** cancel all current running operations. Future calls to {@link #checkForCancel()} will be failed with the given reason */ public synchronized void cancel(String reason) { if (cancelled) { // we were already cancelled, make sure we don't interrupt threads twice // this is important in order to make sure that we don't mark // Thread.interrupted without handling it return; } cancelled = true; this.reason = reason; for (Thread thread : threads) { thread.interrupt(); } threads.clear(); } public interface Interruptable extends IOInterruptable { void run() throws InterruptedException; } public interface IOInterruptable { void run() throws IOException, InterruptedException; } public static class ExecutionCancelledException extends ElasticsearchException { public ExecutionCancelledException(String msg) { super(msg); } public ExecutionCancelledException(StreamInput in) throws IOException { super(in); } } /** * Registers a callback that will be invoked when some running operations are cancelled or {@link #checkForCancel()} is called. */ public synchronized void setOnCancel(OnCancel onCancel) { this.onCancel.set(onCancel); } @FunctionalInterface public interface OnCancel { /** * Called when some running operations are cancelled or {@link #checkForCancel()} is explicitly called. * If this method throws an exception, cancelling tasks will fail with that exception; otherwise they * will fail with the default exception {@link ExecutionCancelledException}. * * @param reason the reason of the cancellation * @param beforeCancelException any error that was encountered during the execution before the operations were cancelled. * @see #checkForCancel() * @see #setOnCancel(OnCancel) */ void onCancel(String reason, @Nullable Exception beforeCancelException); } }
checkForCancel(); threads.add(Thread.currentThread()); // capture and clean the interrupted thread before we start, so we can identify // our own interrupt. we do so under lock so we know we don't clear our own. return Thread.interrupted();
1,328
68
1,396
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/common/util/concurrent/AbstractAsyncTask.java
AbstractAsyncTask
run
class AbstractAsyncTask implements Runnable, Closeable { private final Logger logger; private final ThreadPool threadPool; private final AtomicBoolean closed = new AtomicBoolean(false); private final boolean autoReschedule; private volatile Scheduler.Cancellable cancellable; private volatile boolean isScheduledOrRunning; private volatile Exception lastThrownException; private volatile TimeValue interval; protected AbstractAsyncTask(Logger logger, ThreadPool threadPool, TimeValue interval, boolean autoReschedule) { this.logger = logger; this.threadPool = threadPool; this.interval = interval; this.autoReschedule = autoReschedule; } /** * Change the interval between runs. * If a future run is scheduled then this will reschedule it. * @param interval The new interval between runs. */ public synchronized void setInterval(TimeValue interval) { this.interval = interval; if (cancellable != null) { rescheduleIfNecessary(); } } public TimeValue getInterval() { return interval; } /** * Test any external conditions that determine whether the task * should be scheduled. This method does *not* need to test if * the task is closed, as being closed automatically prevents * scheduling. * @return Should the task be scheduled to run? */ protected abstract boolean mustReschedule(); /** * Schedule the task to run after the configured interval if it * is not closed and any further conditions imposed by derived * classes are met. Any previously scheduled invocation is * cancelled. */ public synchronized void rescheduleIfNecessary() { if (isClosed()) { return; } if (cancellable != null) { cancellable.cancel(); } if (interval.millis() > 0 && mustReschedule()) { if (logger.isTraceEnabled()) { logger.trace("scheduling {} every {}", toString(), interval); } cancellable = threadPool.schedule(threadPool.preserveContext(this), interval, getThreadPool()); isScheduledOrRunning = true; } else { logger.trace("scheduled {} disabled", toString()); cancellable = null; isScheduledOrRunning = false; } } public boolean isScheduled() { // Currently running counts as scheduled to avoid an oscillating return value // from this method when a task is repeatedly running and rescheduling itself. return isScheduledOrRunning; } /** * Cancel any scheduled run, but do not prevent subsequent restarts. */ public synchronized void cancel() { if (cancellable != null) { cancellable.cancel(); cancellable = null; } isScheduledOrRunning = false; } /** * Cancel any scheduled run */ @Override public synchronized void close() { if (closed.compareAndSet(false, true)) { cancel(); } } public boolean isClosed() { return this.closed.get(); } @Override public final void run() {<FILL_FUNCTION_BODY>} private static boolean sameException(Exception left, Exception right) { if (left.getClass() == right.getClass()) { if (Objects.equals(left.getMessage(), right.getMessage())) { StackTraceElement[] stackTraceLeft = left.getStackTrace(); StackTraceElement[] stackTraceRight = right.getStackTrace(); if (stackTraceLeft.length == stackTraceRight.length) { for (int i = 0; i < stackTraceLeft.length; i++) { if (stackTraceLeft[i].equals(stackTraceRight[i]) == false) { return false; } } return true; } } } return false; } protected abstract void runInternal(); /** * Use the same threadpool by default. * Derived classes can change this if required. */ protected String getThreadPool() { return ThreadPool.Names.SAME; } }
synchronized (this) { cancellable = null; isScheduledOrRunning = autoReschedule; } try { runInternal(); } catch (Exception ex) { if (lastThrownException == null || sameException(lastThrownException, ex) == false) { // prevent the annoying fact of logging the same stuff all the time with an interval of 1 sec will spam all your logs logger.warn( () -> new ParameterizedMessage( "failed to run task {} - suppressing re-occurring exceptions unless the exception changes", toString()), ex); lastThrownException = ex; } } finally { if (autoReschedule) { rescheduleIfNecessary(); } }
1,070
198
1,268
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/common/util/concurrent/AbstractLifecycleRunnable.java
AbstractLifecycleRunnable
doRun
class AbstractLifecycleRunnable extends AbstractRunnable { /** * The monitored lifecycle for the associated service. */ private final Lifecycle lifecycle; /** * The service's logger (note: this is passed in!). */ private final Logger logger; /** * {@link AbstractLifecycleRunnable} must be aware of the actual {@code lifecycle} to react properly. * * @param lifecycle The lifecycle to react too * @param logger The logger to use when logging * @throws NullPointerException if any parameter is {@code null} */ public AbstractLifecycleRunnable(Lifecycle lifecycle, Logger logger) { this.lifecycle = Objects.requireNonNull(lifecycle, "lifecycle must not be null"); this.logger = Objects.requireNonNull(logger, "logger must not be null"); } /** * {@inheritDoc} * <p> * This invokes {@link #doRunInLifecycle()} <em>only</em> if the {@link #lifecycle} is not stopped or closed. Otherwise it exits * immediately. */ @Override protected final void doRun() throws Exception {<FILL_FUNCTION_BODY>} /** * Perform runnable logic, but only if the {@link #lifecycle} is <em>not</em> stopped or closed. * * @throws InterruptedException if the run method throws an {@link InterruptedException} */ protected abstract void doRunInLifecycle() throws Exception; /** * {@inheritDoc} * <p> * This overrides the default behavior of {@code onAfter} to add the caveat that it only runs if the {@link #lifecycle} is <em>not</em> * stopped or closed. * <p> * Note: this does not guarantee that it won't be stopped concurrently as it invokes {@link #onAfterInLifecycle()}, * but it's a solid attempt at preventing it. For those that use this for rescheduling purposes, the next invocation would be * effectively cancelled immediately if that's the case. * * @see #onAfterInLifecycle() */ @Override public final void onAfter() { if (lifecycle.stoppedOrClosed() == false) { onAfterInLifecycle(); } } /** * This method is invoked in the finally block of the run method, but it is only executed if the {@link #lifecycle} is <em>not</em> * stopped or closed. * <p> * This method is most useful for rescheduling the next iteration of the current runnable. */ protected void onAfterInLifecycle() { // nothing by default } }
// prevent execution if the service is stopped if (lifecycle.stoppedOrClosed()) { logger.trace("lifecycle is stopping. exiting"); return; } doRunInLifecycle();
750
63
813
<methods>public non-sealed void <init>() ,public boolean isForceExecution() ,public void onAfter() ,public abstract void onFailure(java.lang.Exception) ,public void onRejection(java.lang.Exception) ,public final void run() <variables>
crate_crate
crate/server/src/main/java/org/elasticsearch/common/util/concurrent/AbstractRefCounted.java
AbstractRefCounted
tryIncRef
class AbstractRefCounted implements RefCounted { private final AtomicInteger refCount = new AtomicInteger(1); private final String name; public AbstractRefCounted(String name) { this.name = name; } @Override public final void incRef() { if (tryIncRef() == false) { alreadyClosed(); } } @Override public final boolean tryIncRef() {<FILL_FUNCTION_BODY>} @Override public final void decRef() { int i = refCount.decrementAndGet(); assert i >= 0; if (i == 0) { closeInternal(); } } protected void alreadyClosed() { throw new AlreadyClosedException(name + " is already closed can't increment refCount current count [" + refCount.get() + "]"); } /** * Returns the current reference count. */ public int refCount() { return this.refCount.get(); } /** gets the name of this instance */ public String getName() { return name; } protected abstract void closeInternal(); }
do { int i = refCount.get(); if (i > 0) { if (refCount.compareAndSet(i, i + 1)) { return true; } } else { return false; } } while (true);
306
72
378
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/common/util/concurrent/EsAbortPolicy.java
EsAbortPolicy
rejectedExecution
class EsAbortPolicy implements XRejectedExecutionHandler { private final CounterMetric rejected = new CounterMetric(); @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {<FILL_FUNCTION_BODY>} @Override public long rejected() { return rejected.count(); } }
if (r instanceof AbstractRunnable) { if (((AbstractRunnable) r).isForceExecution()) { BlockingQueue<Runnable> queue = executor.getQueue(); if (!(queue instanceof SizeBlockingQueue)) { throw new IllegalStateException("forced execution, but expected a size queue"); } try { ((SizeBlockingQueue) queue).forcePut(r); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("forced execution, but got interrupted", e); } return; } } rejected.inc(); throw new EsRejectedExecutionException("rejected execution of " + r + " on " + executor, executor.isShutdown());
89
191
280
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/common/util/concurrent/FutureUtils.java
FutureUtils
cancel
class FutureUtils { /** * Cancel execution of this future without interrupting a running thread. See {@link Future#cancel(boolean)} for details. * * @param toCancel the future to cancel * @return false if the future could not be cancelled, otherwise true */ @SuppressForbidden(reason = "Future#cancel()") public static boolean cancel(@Nullable final Future<?> toCancel) {<FILL_FUNCTION_BODY>} /** * Calls {@link Future#get()} without the checked exceptions. * * @param future to dereference * @param <T> the type returned * @return the value of the future */ public static <T> T get(Future<T> future) { try { return future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Future got interrupted", e); } catch (ExecutionException e) { throw rethrowExecutionException(e); } } /** * Calls {@link #get(Future, long, TimeUnit)} */ public static <T> T get(Future<T> future, TimeValue timeValue) { return get(future, timeValue.millis(), TimeUnit.MILLISECONDS); } /** * Calls {@link Future#get(long, TimeUnit)} without the checked exceptions. * * @param future to dereference * @param timeout to wait * @param unit for timeout * @param <T> the type returned * @return the value of the future */ public static <T> T get(Future<T> future, long timeout, TimeUnit unit) { try { return future.get(timeout, unit); } catch (TimeoutException e) { throw new ElasticsearchTimeoutException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Future got interrupted", e); } catch (ExecutionException e) { throw FutureUtils.rethrowExecutionException(e); } } public static RuntimeException rethrowExecutionException(ExecutionException e) { return Exceptions.toRuntimeException(SQLExceptions.unwrap(e)); } }
if (toCancel != null) { return toCancel.cancel(false); // this method is a forbidden API since it interrupts threads } return false;
578
46
624
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/common/util/concurrent/ReleasableLock.java
ReleasableLock
removeCurrentThread
class ReleasableLock implements Releasable { private final Lock lock; // a per-thread count indicating how many times the thread has entered the lock; only works if assertions are enabled private final ThreadLocal<Integer> holdingThreads; public ReleasableLock(Lock lock) { this.lock = lock; if (Assertions.ENABLED) { holdingThreads = new ThreadLocal<>(); } else { holdingThreads = null; } } @Override public void close() { lock.unlock(); assert removeCurrentThread(); } public ReleasableLock acquire() throws EngineException { lock.lock(); assert addCurrentThread(); return this; } /** * Try acquiring lock, returning null if unable. */ public ReleasableLock tryAcquire() { boolean locked = lock.tryLock(); if (locked) { assert addCurrentThread(); return this; } else { return null; } } private boolean addCurrentThread() { final Integer current = holdingThreads.get(); holdingThreads.set(current == null ? 1 : current + 1); return true; } private boolean removeCurrentThread() {<FILL_FUNCTION_BODY>} public boolean isHeldByCurrentThread() { if (holdingThreads == null) { throw new UnsupportedOperationException("asserts must be enabled"); } final Integer count = holdingThreads.get(); return count != null && count > 0; } }
final Integer count = holdingThreads.get(); assert count != null && count > 0; if (count == 1) { holdingThreads.remove(); } else { holdingThreads.set(count - 1); } return true;
411
70
481
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/common/util/concurrent/SizeBlockingQueue.java
SizeBlockingQueue
poll
class SizeBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E> { private final BlockingQueue<E> queue; private final int capacity; private final AtomicInteger size = new AtomicInteger(); public SizeBlockingQueue(BlockingQueue<E> queue, int capacity) { assert capacity >= 0; this.queue = queue; this.capacity = capacity; } @Override public int size() { return size.get(); } public int capacity() { return this.capacity; } @Override public Iterator<E> iterator() { final Iterator<E> it = queue.iterator(); return new Iterator<E>() { E current; @Override public boolean hasNext() { return it.hasNext(); } @Override public E next() { current = it.next(); return current; } @Override public void remove() { // note, we can't call #remove on the iterator because we need to know // if it was removed or not if (queue.remove(current)) { size.decrementAndGet(); } } }; } @Override public E peek() { return queue.peek(); } @Override public E poll() { E e = queue.poll(); if (e != null) { size.decrementAndGet(); } return e; } @Override public E poll(long timeout, TimeUnit unit) throws InterruptedException {<FILL_FUNCTION_BODY>} @Override public boolean remove(Object o) { boolean v = queue.remove(o); if (v) { size.decrementAndGet(); } return v; } /** * Forces adding an element to the queue, without doing size checks. */ public void forcePut(E e) throws InterruptedException { size.incrementAndGet(); try { queue.put(e); } catch (InterruptedException ie) { size.decrementAndGet(); throw ie; } } @Override public boolean offer(E e) { while (true) { final int current = size.get(); if (current >= capacity()) { return false; } if (size.compareAndSet(current, 1 + current)) { break; } } boolean offered = queue.offer(e); if (!offered) { size.decrementAndGet(); } return offered; } @Override public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { // note, not used in ThreadPoolExecutor throw new IllegalStateException("offer with timeout not allowed on size queue"); } @Override public void put(E e) throws InterruptedException { // note, not used in ThreadPoolExecutor throw new IllegalStateException("put not allowed on size queue"); } @Override public E take() throws InterruptedException { E e; try { e = queue.take(); size.decrementAndGet(); } catch (InterruptedException ie) { throw ie; } return e; } @Override public int remainingCapacity() { return capacity() - size.get(); } @Override public int drainTo(Collection<? super E> c) { int v = queue.drainTo(c); size.addAndGet(-v); return v; } @Override public int drainTo(Collection<? super E> c, int maxElements) { int v = queue.drainTo(c, maxElements); size.addAndGet(-v); return v; } @Override public Object[] toArray() { return queue.toArray(); } @Override public <T> T[] toArray(T[] a) { return (T[]) queue.toArray(a); } @Override public boolean contains(Object o) { return queue.contains(o); } @Override public boolean containsAll(Collection<?> c) { return queue.containsAll(c); } }
E e = queue.poll(timeout, unit); if (e != null) { size.decrementAndGet(); } return e;
1,140
45
1,185
<methods>public boolean add(E) ,public boolean addAll(Collection<? extends E>) ,public void clear() ,public E element() ,public E remove() <variables>
crate_crate
crate/server/src/main/java/org/elasticsearch/discovery/DiscoveryStats.java
DiscoveryStats
toXContent
class DiscoveryStats implements Writeable, ToXContentFragment { private final PendingClusterStateStats queueStats; private final PublishClusterStateStats publishStats; public DiscoveryStats(PendingClusterStateStats queueStats, PublishClusterStateStats publishStats) { this.queueStats = queueStats; this.publishStats = publishStats; } public DiscoveryStats(StreamInput in) throws IOException { queueStats = in.readOptionalWriteable(PendingClusterStateStats::new); publishStats = in.readOptionalWriteable(PublishClusterStateStats::new); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalWriteable(queueStats); out.writeOptionalWriteable(publishStats); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {<FILL_FUNCTION_BODY>} static final class Fields { static final String DISCOVERY = "discovery"; } public PendingClusterStateStats getQueueStats() { return queueStats; } public PublishClusterStateStats getPublishStats() { return publishStats; } }
builder.startObject(Fields.DISCOVERY); if (queueStats != null) { queueStats.toXContent(builder, params); } if (publishStats != null) { publishStats.toXContent(builder, params); } builder.endObject(); return builder;
307
84
391
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/discovery/HandshakingTransportAddressConnector.java
HandshakingTransportAddressConnector
onResponse
class HandshakingTransportAddressConnector implements TransportAddressConnector { private static final Logger LOGGER = LogManager.getLogger(HandshakingTransportAddressConnector.class); // connection timeout for probes public static final Setting<TimeValue> PROBE_CONNECT_TIMEOUT_SETTING = Setting.timeSetting("discovery.probe.connect_timeout", TimeValue.timeValueMillis(3000), TimeValue.timeValueMillis(1), Setting.Property.NodeScope); // handshake timeout for probes public static final Setting<TimeValue> PROBE_HANDSHAKE_TIMEOUT_SETTING = Setting.timeSetting("discovery.probe.handshake_timeout", TimeValue.timeValueMillis(1000), TimeValue.timeValueMillis(1), Setting.Property.NodeScope); private final TransportService transportService; private final TimeValue probeConnectTimeout; private final TimeValue probeHandshakeTimeout; public HandshakingTransportAddressConnector(Settings settings, TransportService transportService) { this.transportService = transportService; probeConnectTimeout = PROBE_CONNECT_TIMEOUT_SETTING.get(settings); probeHandshakeTimeout = PROBE_HANDSHAKE_TIMEOUT_SETTING.get(settings); } @Override public void connectToRemoteMasterNode(TransportAddress transportAddress, ActionListener<DiscoveryNode> listener) { transportService.getThreadPool().generic().execute(new AbstractRunnable() { private final AbstractRunnable thisConnectionAttempt = this; @Override protected void doRun() { // We could skip this if the transportService were already connected to the given address, but the savings would be minimal // so we open a new connection anyway. final DiscoveryNode targetNode = new DiscoveryNode("", transportAddress.toString(), UUIDs.randomBase64UUID(Randomness.get()), // generated deterministically for reproducible tests transportAddress.address().getHostString(), transportAddress.getAddress(), transportAddress, emptyMap(), emptySet(), Version.CURRENT.minimumCompatibilityVersion()); LOGGER.trace("[{}] opening probe connection", thisConnectionAttempt); transportService.openConnection( targetNode, ConnectionProfile.buildSingleChannelProfile( Type.REG, probeConnectTimeout, probeHandshakeTimeout, TimeValue.MINUS_ONE, null ), new ActionListener<>() { @Override public void onResponse(Connection connection) {<FILL_FUNCTION_BODY>} @Override public void onFailure(Exception e) { listener.onFailure(e); } } ); } @Override public void onFailure(Exception e) { listener.onFailure(e); } @Override public String toString() { return "connectToRemoteMasterNode[" + transportAddress + "]"; } }); } }
LOGGER.trace("[{}] opened probe connection", thisConnectionAttempt); // use NotifyOnceListener to make sure the following line does not result in onFailure being called when // the connection is closed in the onResponse handler transportService.handshake(connection, probeHandshakeTimeout.millis(), new NotifyOnceListener<DiscoveryNode>() { @Override protected void innerOnResponse(DiscoveryNode remoteNode) { try { // success means (amongst other things) that the cluster names match LOGGER.trace("[{}] handshake successful: {}", thisConnectionAttempt, remoteNode); IOUtils.closeWhileHandlingException(connection); if (remoteNode.equals(transportService.getLocalNode())) { listener.onFailure(new ConnectTransportException(remoteNode, "local node found")); } else if (remoteNode.isMasterEligibleNode() == false) { listener.onFailure(new ConnectTransportException(remoteNode, "non-master-eligible node found")); } else { transportService.connectToNode(remoteNode, new ActionListener<Void>() { @Override public void onResponse(Void ignored) { LOGGER.trace("[{}] full connection successful: {}", thisConnectionAttempt, remoteNode); listener.onResponse(remoteNode); } @Override public void onFailure(Exception e) { // we opened a connection and successfully performed a handshake, so we're definitely // talking to a master-eligible node with a matching cluster name and a good version, // but the attempt to open a full connection to its publish address failed; a common // reason is that the remote node is listening on 0.0.0.0 but has made an inappropriate // choice for its publish address. LOGGER.warn(new ParameterizedMessage( "[{}] completed handshake with [{}] but followup connection failed", thisConnectionAttempt, remoteNode), e); listener.onFailure(e); } }); } } catch (Exception e) { listener.onFailure(e); } } @Override protected void innerOnFailure(Exception e) { // we opened a connection and successfully performed a low-level handshake, so we were definitely // talking to an Elasticsearch node, but the high-level handshake failed indicating some kind of // mismatched configurations (e.g. cluster name) that the user should address boolean nodeClosed = e instanceof AlreadyClosedException || (e instanceof SendRequestTransportException transportException && transportException.getCause() instanceof NodeClosedException); if (!nodeClosed) { LOGGER.warn(new ParameterizedMessage("handshake failed for [{}]", thisConnectionAttempt), e); } IOUtils.closeWhileHandlingException(connection); listener.onFailure(e); } });
747
734
1,481
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/env/ESFileStore.java
ESFileStore
getTotalSpace
class ESFileStore extends FileStore { /** Underlying filestore */ final FileStore in; private int majorDeviceNumber; private int minorDeviceNumber; @SuppressForbidden(reason = "tries to determine if disk is spinning") // TODO: move PathUtils to be package-private here instead of // public+forbidden api! ESFileStore(final FileStore in) { this.in = in; if (Constants.LINUX) { try { final List<String> lines = Files.readAllLines(PathUtils.get("/proc/self/mountinfo")); for (final String line : lines) { final String[] fields = line.trim().split("\\s+"); final String mountPoint = fields[4]; if (mountPoint.equals(getMountPointLinux(in))) { final String[] deviceNumbers = fields[2].split(":"); majorDeviceNumber = Integer.parseInt(deviceNumbers[0]); minorDeviceNumber = Integer.parseInt(deviceNumbers[1]); break; } } } catch (final Exception e) { majorDeviceNumber = -1; minorDeviceNumber = -1; } } else { majorDeviceNumber = -1; minorDeviceNumber = -1; } } // these are hacks that are not guaranteed private static String getMountPointLinux(final FileStore store) { String desc = store.toString(); int index = desc.lastIndexOf(" ("); if (index != -1) { return desc.substring(0, index); } else { return desc; } } @Override public String name() { return in.name(); } @Override public String type() { return in.type(); } @Override public boolean isReadOnly() { return in.isReadOnly(); } @Override public long getTotalSpace() throws IOException {<FILL_FUNCTION_BODY>} @Override public long getUsableSpace() throws IOException { long result = in.getUsableSpace(); if (result < 0) { // see https://bugs.openjdk.java.net/browse/JDK-8162520: result = Long.MAX_VALUE; } return result; } @Override public long getUnallocatedSpace() throws IOException { long result = in.getUnallocatedSpace(); if (result < 0) { // see https://bugs.openjdk.java.net/browse/JDK-8162520: result = Long.MAX_VALUE; } return result; } @Override public boolean supportsFileAttributeView(Class<? extends FileAttributeView> type) { return in.supportsFileAttributeView(type); } @Override public boolean supportsFileAttributeView(String name) { if ("lucene".equals(name)) { return true; } else { return in.supportsFileAttributeView(name); } } @Override public <V extends FileStoreAttributeView> V getFileStoreAttributeView(Class<V> type) { return in.getFileStoreAttributeView(type); } @Override public Object getAttribute(String attribute) throws IOException { switch (attribute) { // for the partition case "lucene:major_device_number": return majorDeviceNumber; case "lucene:minor_device_number": return minorDeviceNumber; default: return in.getAttribute(attribute); } } @Override public String toString() { return in.toString(); } }
long result = in.getTotalSpace(); if (result < 0) { // see https://bugs.openjdk.java.net/browse/JDK-8162520: result = Long.MAX_VALUE; } return result;
958
71
1,029
<methods>public abstract java.lang.Object getAttribute(java.lang.String) throws java.io.IOException,public long getBlockSize() throws java.io.IOException,public abstract V getFileStoreAttributeView(Class<V>) ,public abstract long getTotalSpace() throws java.io.IOException,public abstract long getUnallocatedSpace() throws java.io.IOException,public abstract long getUsableSpace() throws java.io.IOException,public abstract boolean isReadOnly() ,public abstract java.lang.String name() ,public abstract boolean supportsFileAttributeView(Class<? extends java.nio.file.attribute.FileAttributeView>) ,public abstract boolean supportsFileAttributeView(java.lang.String) ,public abstract java.lang.String type() <variables>
crate_crate
crate/server/src/main/java/org/elasticsearch/gateway/GatewayAllocator.java
InternalPrimaryShardAllocator
fetchData
class InternalPrimaryShardAllocator extends PrimaryShardAllocator { private final NodeClient client; InternalPrimaryShardAllocator(NodeClient client) { this.client = client; } @Override protected AsyncShardFetch.FetchResult<NodeGatewayStartedShards> fetchData(ShardRouting shard, RoutingAllocation allocation) {<FILL_FUNCTION_BODY>} private void listStartedShards(ShardId shardId, String customDataPath, DiscoveryNode[] nodes, ActionListener<BaseNodesResponse<NodeGatewayStartedShards>> listener) { var request = new TransportNodesListGatewayStartedShards.Request(shardId, customDataPath, nodes); client.execute(TransportNodesListGatewayStartedShards.TYPE, request).whenComplete(listener); } }
// explicitely type lister, some IDEs (Eclipse) are not able to correctly infer the function type Lister<BaseNodesResponse<NodeGatewayStartedShards>, NodeGatewayStartedShards> lister = this::listStartedShards; AsyncShardFetch<NodeGatewayStartedShards> fetch = asyncFetchStarted.computeIfAbsent( shard.shardId(), shardId -> new InternalAsyncFetch<>( logger, "shard_started", shardId, IndexMetadata.INDEX_DATA_PATH_SETTING.get(allocation.metadata().index(shard.index()).getSettings()), lister ) ); AsyncShardFetch.FetchResult<NodeGatewayStartedShards> shardState = fetch.fetchData(allocation.nodes(), allocation.getIgnoreNodes(shard.shardId())); if (shardState.hasData()) { shardState.processAllocation(allocation); } return shardState;
219
265
484
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/gateway/TransportNodesListGatewayMetaState.java
NodeGatewayMetaState
writeTo
class NodeGatewayMetaState extends BaseNodeResponse { @Nullable private final Metadata metadata; public NodeGatewayMetaState(DiscoveryNode node, Metadata metadata) { super(node); this.metadata = metadata; } public NodeGatewayMetaState(StreamInput in) throws IOException { super(in); if (in.readBoolean()) { metadata = Metadata.readFrom(in); } else { metadata = null; } } @Override public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>} @Nullable public Metadata metadata() { return metadata; } }
super.writeTo(out); if (metadata == null) { out.writeBoolean(false); } else { out.writeBoolean(true); metadata.writeTo(out); }
182
56
238
<methods><variables>protected final non-sealed org.elasticsearch.cluster.service.ClusterService clusterService,protected final non-sealed Class<org.elasticsearch.gateway.TransportNodesListGatewayMetaState.NodeGatewayMetaState> nodeResponseClass,protected final non-sealed org.elasticsearch.threadpool.ThreadPool threadPool,final non-sealed java.lang.String transportNodeAction,protected final non-sealed org.elasticsearch.transport.TransportService transportService
crate_crate
crate/server/src/main/java/org/elasticsearch/gateway/WriteStateException.java
WriteStateException
rethrowAsErrorOrUncheckedException
class WriteStateException extends IOException { private final boolean dirty; WriteStateException(boolean dirty, String message, Exception cause) { super(message, cause); this.dirty = dirty; } /** * If this method returns false, state is guaranteed to be not written to disk. * If this method returns true, we don't know if state is written to disk. */ public boolean isDirty() { return dirty; } /** * Rethrows this {@link WriteStateException} as {@link IOError} if dirty flag is set, which will lead to JVM shutdown. * If dirty flag is not set, this exception is wrapped into {@link UncheckedIOException}. */ public void rethrowAsErrorOrUncheckedException() {<FILL_FUNCTION_BODY>} }
if (isDirty()) { throw new IOError(this); } else { throw new UncheckedIOException(this); }
207
40
247
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
crate_crate
crate/server/src/main/java/org/elasticsearch/index/analysis/CustomNormalizerProvider.java
CustomNormalizerProvider
build
class CustomNormalizerProvider extends AbstractIndexAnalyzerProvider<CustomAnalyzer> { private final Settings analyzerSettings; private CustomAnalyzer customAnalyzer; public CustomNormalizerProvider(IndexSettings indexSettings, String name, Settings settings) { super(indexSettings, name, settings); this.analyzerSettings = settings; } public void build(final String tokenizerName, final TokenizerFactory tokenizerFactory, final Map<String, CharFilterFactory> charFilters, final Map<String, TokenFilterFactory> tokenFilters) {<FILL_FUNCTION_BODY>} @Override public CustomAnalyzer get() { return this.customAnalyzer; } }
if (analyzerSettings.get("tokenizer") != null) { throw new IllegalArgumentException("Custom normalizer [" + name() + "] cannot configure a tokenizer"); } List<String> charFilterNames = analyzerSettings.getAsList("char_filter"); List<CharFilterFactory> charFiltersList = new ArrayList<>(charFilterNames.size()); for (String charFilterName : charFilterNames) { CharFilterFactory charFilter = charFilters.get(charFilterName); if (charFilter == null) { throw new IllegalArgumentException("Custom normalizer [" + name() + "] failed to find char_filter under name [" + charFilterName + "]"); } if (charFilter instanceof MultiTermAwareComponent == false) { throw new IllegalArgumentException("Custom normalizer [" + name() + "] may not use char filter [" + charFilterName + "]"); } charFilter = (CharFilterFactory) ((MultiTermAwareComponent) charFilter).getMultiTermComponent(); charFiltersList.add(charFilter); } List<String> tokenFilterNames = analyzerSettings.getAsList("filter"); List<TokenFilterFactory> tokenFilterList = new ArrayList<>(tokenFilterNames.size()); for (String tokenFilterName : tokenFilterNames) { TokenFilterFactory tokenFilter = tokenFilters.get(tokenFilterName); if (tokenFilter == null) { throw new IllegalArgumentException("Custom Analyzer [" + name() + "] failed to find filter under name [" + tokenFilterName + "]"); } if (tokenFilter instanceof MultiTermAwareComponent == false) { throw new IllegalArgumentException("Custom normalizer [" + name() + "] may not use filter [" + tokenFilterName + "]"); } tokenFilter = (TokenFilterFactory) ((MultiTermAwareComponent) tokenFilter).getMultiTermComponent(); tokenFilterList.add(tokenFilter); } this.customAnalyzer = new CustomAnalyzer( tokenizerName, tokenizerFactory, charFiltersList.toArray(new CharFilterFactory[charFiltersList.size()]), tokenFilterList.toArray(new TokenFilterFactory[tokenFilterList.size()]) );
178
552
730
<methods>public void <init>(org.elasticsearch.index.IndexSettings, java.lang.String, org.elasticsearch.common.settings.Settings) ,public final java.lang.String name() ,public final org.elasticsearch.index.analysis.AnalyzerScope scope() <variables>private final non-sealed java.lang.String name,protected final non-sealed Version version
crate_crate
crate/server/src/main/java/org/elasticsearch/index/analysis/IndexAnalyzers.java
IndexAnalyzers
close
class IndexAnalyzers extends AbstractIndexComponent implements Closeable { private final NamedAnalyzer defaultIndexAnalyzer; private final NamedAnalyzer defaultSearchAnalyzer; private final NamedAnalyzer defaultSearchQuoteAnalyzer; private final Map<String, NamedAnalyzer> analyzers; private final Map<String, NamedAnalyzer> normalizers; private final Map<String, NamedAnalyzer> whitespaceNormalizers; public IndexAnalyzers(IndexSettings indexSettings, NamedAnalyzer defaultIndexAnalyzer, NamedAnalyzer defaultSearchAnalyzer, NamedAnalyzer defaultSearchQuoteAnalyzer, Map<String, NamedAnalyzer> analyzers, Map<String, NamedAnalyzer> normalizers, Map<String, NamedAnalyzer> whitespaceNormalizers) { super(indexSettings); this.defaultIndexAnalyzer = defaultIndexAnalyzer; this.defaultSearchAnalyzer = defaultSearchAnalyzer; this.defaultSearchQuoteAnalyzer = defaultSearchQuoteAnalyzer; this.analyzers = unmodifiableMap(analyzers); this.normalizers = unmodifiableMap(normalizers); this.whitespaceNormalizers = unmodifiableMap(whitespaceNormalizers); } /** * Returns an analyzer mapped to the given name or <code>null</code> if not present */ public NamedAnalyzer get(String name) { return analyzers.get(name); } /** * Returns a normalizer mapped to the given name or <code>null</code> if not present */ public NamedAnalyzer getNormalizer(String name) { return normalizers.get(name); } /** * Returns a normalizer that splits on whitespace mapped to the given name or <code>null</code> if not present */ public NamedAnalyzer getWhitespaceNormalizer(String name) { return whitespaceNormalizers.get(name); } /** * Returns the default index analyzer for this index */ public NamedAnalyzer getDefaultIndexAnalyzer() { return defaultIndexAnalyzer; } /** * Returns the default search analyzer for this index */ public NamedAnalyzer getDefaultSearchAnalyzer() { return defaultSearchAnalyzer; } /** * Returns the default search quote analyzer for this index */ public NamedAnalyzer getDefaultSearchQuoteAnalyzer() { return defaultSearchQuoteAnalyzer; } @Override public void close() throws IOException {<FILL_FUNCTION_BODY>} }
IOUtils.close(() -> Stream.concat(analyzers.values().stream(), normalizers.values().stream()) .filter(a -> a.scope() == AnalyzerScope.INDEX).iterator());
654
52
706
<methods>public org.elasticsearch.index.IndexSettings getIndexSettings() ,public org.elasticsearch.index.Index index() <variables>protected final non-sealed org.elasticsearch.common.logging.DeprecationLogger deprecationLogger,protected final non-sealed org.elasticsearch.index.IndexSettings indexSettings,protected final non-sealed Logger logger
crate_crate
crate/server/src/main/java/org/elasticsearch/index/analysis/PreConfiguredAnalysisComponent.java
PreConfiguredAnalysisComponent
get
class PreConfiguredAnalysisComponent<T> implements AnalysisModule.AnalysisProvider<T> { private final String name; protected final PreBuiltCacheFactory.PreBuiltCache<T> cache; protected PreConfiguredAnalysisComponent(String name, PreBuiltCacheFactory.CachingStrategy cache) { this.name = name; this.cache = PreBuiltCacheFactory.getCache(cache); } protected PreConfiguredAnalysisComponent(String name, PreBuiltCacheFactory.PreBuiltCache<T> cache) { this.name = name; this.cache = cache; } @Override public T get(IndexSettings indexSettings, Environment environment, String name, Settings settings) throws IOException {<FILL_FUNCTION_BODY>} /** * The name of the analysis component in the API. */ public String getName() { return name; } protected abstract T create(Version version); }
Version versionCreated = Version.indexCreated(settings); synchronized (this) { T factory = cache.get(versionCreated); if (factory == null) { factory = create(versionCreated); cache.put(versionCreated, factory); } return factory; }
239
76
315
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/analysis/PreConfiguredCharFilter.java
PreConfiguredCharFilter
create
class PreConfiguredCharFilter extends PreConfiguredAnalysisComponent<CharFilterFactory> { /** * Create a pre-configured char filter that may not vary at all. */ public static PreConfiguredCharFilter singleton(String name, boolean useFilterForMultitermQueries, UnaryOperator<Reader> create) { return new PreConfiguredCharFilter( name, CachingStrategy.ONE, useFilterForMultitermQueries, (reader, version) -> create.apply(reader) ); } /** * Create a pre-configured char filter that may not vary at all, provide access to the elasticsearch version */ public static PreConfiguredCharFilter singletonWithVersion(String name, boolean useFilterForMultitermQueries, BiFunction<Reader, org.elasticsearch.Version, Reader> create) { return new PreConfiguredCharFilter( name, CachingStrategy.ONE, useFilterForMultitermQueries, (reader, version) -> create.apply(reader, version) ); } /** * Create a pre-configured token filter that may vary based on the Lucene version. */ public static PreConfiguredCharFilter luceneVersion(String name, boolean useFilterForMultitermQueries, BiFunction<Reader, org.apache.lucene.util.Version, Reader> create) { return new PreConfiguredCharFilter( name, CachingStrategy.LUCENE, useFilterForMultitermQueries, (reader, version) -> create.apply(reader, version.luceneVersion) ); } /** * Create a pre-configured token filter that may vary based on the Elasticsearch version. */ public static PreConfiguredCharFilter elasticsearchVersion(String name, boolean useFilterForMultitermQueries, BiFunction<Reader, org.elasticsearch.Version, Reader> create) { return new PreConfiguredCharFilter(name, CachingStrategy.ELASTICSEARCH, useFilterForMultitermQueries, create); } private final boolean useFilterForMultitermQueries; private final BiFunction<Reader, Version, Reader> create; protected PreConfiguredCharFilter(String name, CachingStrategy cache, boolean useFilterForMultitermQueries, BiFunction<Reader, org.elasticsearch.Version, Reader> create) { super(name, cache); this.useFilterForMultitermQueries = useFilterForMultitermQueries; this.create = create; } /** * Can this {@link TokenFilter} be used in multi-term queries? */ public boolean shouldUseFilterForMultitermQueries() { return useFilterForMultitermQueries; } private interface MultiTermAwareCharFilterFactory extends CharFilterFactory, MultiTermAwareComponent {} @Override protected CharFilterFactory create(Version version) {<FILL_FUNCTION_BODY>} }
if (useFilterForMultitermQueries) { return new MultiTermAwareCharFilterFactory() { @Override public String name() { return getName(); } @Override public Reader create(Reader reader) { return create.apply(reader, version); } @Override public Object getMultiTermComponent() { return this; } }; } return new CharFilterFactory() { @Override public Reader create(Reader reader) { return create.apply(reader, version); } @Override public String name() { return getName(); } };
757
169
926
<methods>public org.elasticsearch.index.analysis.CharFilterFactory get(org.elasticsearch.index.IndexSettings, org.elasticsearch.env.Environment, java.lang.String, org.elasticsearch.common.settings.Settings) throws java.io.IOException,public java.lang.String getName() <variables>protected final non-sealed PreBuiltCache<org.elasticsearch.index.analysis.CharFilterFactory> cache,private final non-sealed java.lang.String name
crate_crate
crate/server/src/main/java/org/elasticsearch/index/analysis/ShingleTokenFilterFactory.java
Factory
create
class Factory implements TokenFilterFactory { private final int maxShingleSize; private final boolean outputUnigrams; private final boolean outputUnigramsIfNoShingles; private final String tokenSeparator; private final String fillerToken; private int minShingleSize; private final String name; public Factory(String name) { this(name, ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE, true, false, ShingleFilter.DEFAULT_TOKEN_SEPARATOR, ShingleFilter.DEFAULT_FILLER_TOKEN); } Factory(String name, int minShingleSize, int maxShingleSize, boolean outputUnigrams, boolean outputUnigramsIfNoShingles, String tokenSeparator, String fillerToken) { this.maxShingleSize = maxShingleSize; this.outputUnigrams = outputUnigrams; this.outputUnigramsIfNoShingles = outputUnigramsIfNoShingles; this.tokenSeparator = tokenSeparator; this.minShingleSize = minShingleSize; this.fillerToken = fillerToken; this.name = name; } @Override public TokenStream create(TokenStream tokenStream) {<FILL_FUNCTION_BODY>} public int getMaxShingleSize() { return maxShingleSize; } public int getMinShingleSize() { return minShingleSize; } public boolean getOutputUnigrams() { return outputUnigrams; } public boolean getOutputUnigramsIfNoShingles() { return outputUnigramsIfNoShingles; } @Override public String name() { return name; } }
ShingleFilter filter = new ShingleFilter(tokenStream, minShingleSize, maxShingleSize); filter.setOutputUnigrams(outputUnigrams); filter.setOutputUnigramsIfNoShingles(outputUnigramsIfNoShingles); filter.setTokenSeparator(tokenSeparator); filter.setFillerToken(fillerToken); if (outputUnigrams || (minShingleSize != maxShingleSize)) { /** * We disable the graph analysis on this token stream * because it produces shingles of different size. * Graph analysis on such token stream is useless and dangerous as it may create too many paths * since shingles of different size are not aligned in terms of positions. */ filter.addAttribute(DisableGraphAttribute.class); } return filter;
483
213
696
<methods>public void <init>(org.elasticsearch.index.IndexSettings, java.lang.String, org.elasticsearch.common.settings.Settings) ,public java.lang.String name() ,public final Version version() <variables>private final non-sealed java.lang.String name,protected final non-sealed Version version
crate_crate
crate/server/src/main/java/org/elasticsearch/index/engine/CombinedDocValues.java
CombinedDocValues
docVersion
class CombinedDocValues { private final NumericDocValues versionDV; private final NumericDocValues seqNoDV; private final NumericDocValues primaryTermDV; private final NumericDocValues tombstoneDV; private final NumericDocValues recoverySource; CombinedDocValues(LeafReader leafReader) throws IOException { this.versionDV = Objects.requireNonNull(leafReader.getNumericDocValues(DocSysColumns.VERSION.name()), "VersionDV is missing"); this.seqNoDV = Objects.requireNonNull(leafReader.getNumericDocValues(DocSysColumns.Names.SEQ_NO), "SeqNoDV is missing"); this.primaryTermDV = Objects.requireNonNull( leafReader.getNumericDocValues(DocSysColumns.Names.PRIMARY_TERM), "PrimaryTermDV is missing"); this.tombstoneDV = leafReader.getNumericDocValues(DocSysColumns.Names.TOMBSTONE); this.recoverySource = leafReader.getNumericDocValues(SourceFieldMapper.RECOVERY_SOURCE_NAME); } long docVersion(int segmentDocId) throws IOException {<FILL_FUNCTION_BODY>} long docSeqNo(int segmentDocId) throws IOException { assert seqNoDV.docID() < segmentDocId; if (seqNoDV.advanceExact(segmentDocId) == false) { assert false : "DocValues for field [" + DocSysColumns.Names.SEQ_NO + "] is not found"; throw new IllegalStateException("DocValues for field [" + DocSysColumns.Names.SEQ_NO + "] is not found"); } return seqNoDV.longValue(); } long docPrimaryTerm(int segmentDocId) throws IOException { // We exclude non-root nested documents when querying changes, every returned document must have primary term. assert primaryTermDV.docID() < segmentDocId; if (primaryTermDV.advanceExact(segmentDocId) == false) { assert false : "DocValues for field [" + DocSysColumns.Names.PRIMARY_TERM + "] is not found"; throw new IllegalStateException("DocValues for field [" + DocSysColumns.Names.PRIMARY_TERM + "] is not found"); } return primaryTermDV.longValue(); } boolean isTombstone(int segmentDocId) throws IOException { if (tombstoneDV == null) { return false; } assert tombstoneDV.docID() < segmentDocId; return tombstoneDV.advanceExact(segmentDocId) && tombstoneDV.longValue() > 0; } boolean hasRecoverySource(int segmentDocId) throws IOException { if (recoverySource == null) { return false; } assert recoverySource.docID() < segmentDocId; return recoverySource.advanceExact(segmentDocId); } }
assert versionDV.docID() < segmentDocId; if (versionDV.advanceExact(segmentDocId) == false) { assert false : "DocValues for field [" + DocSysColumns.VERSION.name() + "] is not found"; throw new IllegalStateException("DocValues for field [" + DocSysColumns.VERSION.name() + "] is not found"); } return versionDV.longValue();
773
111
884
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/engine/CommitStats.java
CommitStats
writeTo
class CommitStats implements Writeable { private final Map<String, String> userData; private final long generation; private final String id; // lucene commit id in base 64; private final int numDocs; public CommitStats(SegmentInfos segmentInfos) { // clone the map to protect against concurrent changes userData = Map.copyOf(segmentInfos.getUserData()); // lucene calls the current generation, last generation. generation = segmentInfos.getLastGeneration(); id = Base64.getEncoder().encodeToString(segmentInfos.getId()); numDocs = Lucene.getNumDocs(segmentInfos); } public CommitStats(StreamInput in) throws IOException { HashMap<String, String> builder = new HashMap<>(); for (int i = in.readVInt(); i > 0; i--) { builder.put(in.readString(), in.readString()); } userData = Map.copyOf(builder); generation = in.readLong(); id = in.readOptionalString(); numDocs = in.readInt(); } @Override public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>} public Map<String, String> getUserData() { return userData; } public long getGeneration() { return generation; } /** base64 version of the commit id (see {@link SegmentInfos#getId()} */ public String getId() { return id; } /** * A raw version of the commit id (see {@link SegmentInfos#getId()} */ public Engine.CommitId getRawCommitId() { return new Engine.CommitId(Base64.getDecoder().decode(id)); } /** * The synced-flush id of the commit if existed. */ public String syncId() { return userData.get(InternalEngine.SYNC_COMMIT_ID); } /** * Returns the number of documents in the in this commit */ public int getNumDocs() { return numDocs; } }
out.writeVInt(userData.size()); for (Map.Entry<String, String> entry : userData.entrySet()) { out.writeString(entry.getKey()); out.writeString(entry.getValue()); } out.writeLong(generation); out.writeOptionalString(id); out.writeInt(numDocs);
564
94
658
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/engine/DeleteVersionValue.java
DeleteVersionValue
equals
class DeleteVersionValue extends VersionValue { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(DeleteVersionValue.class); final long time; DeleteVersionValue(long version,long seqNo, long term, long time) { super(version, seqNo, term); this.time = time; } @Override public boolean isDelete() { return true; } @Override public long ramBytesUsed() { return BASE_RAM_BYTES_USED; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (int) (time ^ (time >>> 32)); return result; } @Override public String toString() { return "DeleteVersionValue{" + "version=" + version + ", seqNo=" + seqNo + ", term=" + term + ",time=" + time + '}'; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; DeleteVersionValue that = (DeleteVersionValue) o; return time == that.time;
306
73
379
<methods>public boolean equals(java.lang.Object) ,public Collection<Accountable> getChildResources() ,public org.elasticsearch.index.translog.Translog.Location getLocation() ,public int hashCode() ,public boolean isDelete() ,public long ramBytesUsed() ,public java.lang.String toString() <variables>private static final long BASE_RAM_BYTES_USED,final non-sealed long seqNo,final non-sealed long term,final non-sealed long version
crate_crate
crate/server/src/main/java/org/elasticsearch/index/engine/IndexVersionValue.java
IndexVersionValue
equals
class IndexVersionValue extends VersionValue { private static final long RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(IndexVersionValue.class); private final Translog.Location translogLocation; IndexVersionValue(Translog.Location translogLocation, long version, long seqNo, long term) { super(version, seqNo, term); this.translogLocation = translogLocation; } @Override public long ramBytesUsed() { return RAM_BYTES_USED + RamUsageEstimator.shallowSizeOf(translogLocation); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(super.hashCode(), translogLocation); } @Override public String toString() { return "IndexVersionValue{" + "version=" + version + ", seqNo=" + seqNo + ", term=" + term + ", location=" + translogLocation + '}'; } @Override public Translog.Location getLocation() { return translogLocation; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; IndexVersionValue that = (IndexVersionValue) o; return Objects.equals(translogLocation, that.translogLocation);
314
80
394
<methods>public boolean equals(java.lang.Object) ,public Collection<Accountable> getChildResources() ,public org.elasticsearch.index.translog.Translog.Location getLocation() ,public int hashCode() ,public boolean isDelete() ,public long ramBytesUsed() ,public java.lang.String toString() <variables>private static final long BASE_RAM_BYTES_USED,final non-sealed long seqNo,final non-sealed long term,final non-sealed long version
crate_crate
crate/server/src/main/java/org/elasticsearch/index/engine/TranslogLeafReader.java
TranslogLeafReader
docFromOperation
class TranslogLeafReader extends LeafReader { private final Translog.Index operation; private static final FieldInfo FAKE_SOURCE_FIELD = new FieldInfo(SourceFieldMapper.NAME, 1, false, false, false, IndexOptions.NONE, DocValuesType.NONE, -1, Collections.emptyMap(), 0, 0, 0, 0, VectorEncoding.BYTE, VectorSimilarityFunction.EUCLIDEAN, false, false); private static final FieldInfo FAKE_ID_FIELD = new FieldInfo(IdFieldMapper.NAME, 3, false, false, false, IndexOptions.NONE, DocValuesType.NONE, -1, Collections.emptyMap(), 0, 0, 0, 0, VectorEncoding.BYTE, VectorSimilarityFunction.EUCLIDEAN, false, false); TranslogLeafReader(Translog.Index operation) { this.operation = operation; } @Override public CacheHelper getCoreCacheHelper() { throw new UnsupportedOperationException(); } @Override public Terms terms(String field) { throw new UnsupportedOperationException(); } @Override public NumericDocValues getNumericDocValues(String field) { throw new UnsupportedOperationException(); } @Override public BinaryDocValues getBinaryDocValues(String field) { throw new UnsupportedOperationException(); } @Override public SortedDocValues getSortedDocValues(String field) { throw new UnsupportedOperationException(); } @Override public SortedNumericDocValues getSortedNumericDocValues(String field) { throw new UnsupportedOperationException(); } @Override public SortedSetDocValues getSortedSetDocValues(String field) { throw new UnsupportedOperationException(); } @Override public NumericDocValues getNormValues(String field) { throw new UnsupportedOperationException(); } @Override public FieldInfos getFieldInfos() { throw new UnsupportedOperationException(); } @Override public Bits getLiveDocs() { throw new UnsupportedOperationException(); } @Override public PointValues getPointValues(String field) { throw new UnsupportedOperationException(); } @Override public void checkIntegrity() { } @Override public LeafMetaData getMetaData() { throw new UnsupportedOperationException(); } @Override public Fields getTermVectors(int docID) { throw new UnsupportedOperationException(); } @Override public int numDocs() { return 1; } @Override public int maxDoc() { return 1; } @Override public void document(int docID, StoredFieldVisitor visitor) throws IOException { docFromOperation(docID, visitor, operation); } @Override protected void doClose() { } @Override public CacheHelper getReaderCacheHelper() { throw new UnsupportedOperationException(); } @Override public FloatVectorValues getFloatVectorValues(String field) throws IOException { throw new UnsupportedOperationException(); } @Override public ByteVectorValues getByteVectorValues(String field) throws IOException { throw new UnsupportedOperationException(); } @Override public void searchNearestVectors(String field, float[] target, KnnCollector knnCollector, Bits acceptDocs) throws IOException { throw new UnsupportedOperationException(); } @Override public void searchNearestVectors(String field, byte[] target, KnnCollector knnCollector, Bits acceptDocs) throws IOException { throw new UnsupportedOperationException(); } @Override public TermVectors termVectors() throws IOException { throw new UnsupportedOperationException(); } @Override public StoredFields storedFields() throws IOException { return new StoredFields() { @Override public void document(int docID, StoredFieldVisitor visitor) throws IOException { docFromOperation(docID, visitor, operation); } }; } private static void docFromOperation(int docID, StoredFieldVisitor visitor, Translog.Index operation) throws IOException {<FILL_FUNCTION_BODY>} }
if (docID != 0) { throw new IllegalArgumentException("no such doc ID " + docID); } if (visitor.needsField(FAKE_SOURCE_FIELD) == StoredFieldVisitor.Status.YES) { assert operation.getSource().toBytesRef().offset == 0; assert operation.getSource().toBytesRef().length == operation.getSource().toBytesRef().bytes.length; visitor.binaryField(FAKE_SOURCE_FIELD, operation.getSource().toBytesRef().bytes); } if (visitor.needsField(FAKE_ID_FIELD) == StoredFieldVisitor.Status.YES) { visitor.stringField(FAKE_ID_FIELD, operation.id()); }
1,133
189
1,322
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/engine/VersionValue.java
VersionValue
toString
class VersionValue implements Accountable { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(VersionValue.class); /** the version of the document. used for versioned indexed operations and as a BWC layer, where no seq# are set yet */ final long version; /** the seq number of the operation that last changed the associated uuid */ final long seqNo; /** the term of the operation that last changed the associated uuid */ final long term; VersionValue(long version, long seqNo, long term) { this.version = version; this.seqNo = seqNo; this.term = term; } public boolean isDelete() { return false; } @Override public long ramBytesUsed() { return BASE_RAM_BYTES_USED; } @Override public Collection<Accountable> getChildResources() { return Collections.emptyList(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; VersionValue that = (VersionValue) o; if (version != that.version) return false; if (seqNo != that.seqNo) return false; return term == that.term; } @Override public int hashCode() { int result = (int) (version ^ (version >>> 32)); result = 31 * result + (int) (seqNo ^ (seqNo >>> 32)); result = 31 * result + (int) (term ^ (term >>> 32)); return result; } @Override public String toString() {<FILL_FUNCTION_BODY>} /** * Returns the translog location for this version value or null. This is optional and might not be tracked all the time. */ @Nullable public Translog.Location getLocation() { return null; } }
return "VersionValue{" + "version=" + version + ", seqNo=" + seqNo + ", term=" + term + '}';
538
47
585
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/mapper/ArrayTypeParser.java
ArrayTypeParser
parse
class ArrayTypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {<FILL_FUNCTION_BODY>} }
Object inner = node.remove(ArrayMapper.INNER_TYPE); if (inner == null) { throw new MapperParsingException("property [inner] missing"); } if (!(inner instanceof Map)) { throw new MapperParsingException("property [inner] must be a map"); } @SuppressWarnings("unchecked") Map<String, Object> innerNode = (Map<String, Object>) inner; String typeName = (String) innerNode.get("type"); if (typeName == null && innerNode.containsKey("properties")) { typeName = ObjectMapper.CONTENT_TYPE; } Mapper.TypeParser innerTypeParser = parserContext.typeParser(typeName); Mapper.Builder innerBuilder = innerTypeParser.parse(name, innerNode, parserContext); if (innerBuilder instanceof ObjectMapper.Builder) { return new ObjectArrayMapper.Builder(name, ((ObjectMapper.Builder) innerBuilder)); } return new ArrayMapper.Builder(name, innerBuilder);
65
260
325
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/mapper/FieldNamesFieldMapper.java
FieldNamesFieldType
parseCreateField
class FieldNamesFieldType extends MappedFieldType { private boolean enabled = Defaults.ENABLED; public FieldNamesFieldType() { super(Defaults.NAME, true, false); } @Override public String typeName() { return CONTENT_TYPE; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled; } } private FieldNamesFieldMapper(FieldType fieldType, MappedFieldType mappedFieldType) { super(fieldType, mappedFieldType); } @Override public FieldNamesFieldType fieldType() { return (FieldNamesFieldType) super.fieldType(); } @Override public void preParse(ParseContext context) { } @Override public void postParse(ParseContext context) throws IOException { } @Override public void parse(ParseContext context) throws IOException { // Adding values to the _field_names field is handled by the mappers for each field type } static Iterable<String> extractFieldNames(final String fullPath) { return new Iterable<String>() { @Override public Iterator<String> iterator() { return new Iterator<String>() { int endIndex = nextEndIndex(0); private int nextEndIndex(int index) { while (index < fullPath.length() && fullPath.charAt(index) != '.') { index += 1; } return index; } @Override public boolean hasNext() { return endIndex <= fullPath.length(); } @Override public String next() { final String result = fullPath.substring(0, endIndex); endIndex = nextEndIndex(endIndex + 1); return result; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } @Override protected void parseCreateField(ParseContext context, Consumer<IndexableField> onField) throws IOException {<FILL_FUNCTION_BODY>
if (fieldType().isEnabled() == false) { return; } Document document = context.doc(); final List<String> paths = new ArrayList<>(document.getFields().size()); String previousPath = ""; // used as a sentinel - field names can't be empty for (IndexableField field : document.getFields()) { final String path = field.name(); if (path.equals(previousPath)) { // Sometimes mappers create multiple Lucene fields, eg. one for indexing, // one for doc values and one for storing. Deduplicating is not required // for correctness but this simple check helps save utf-8 conversions and // gives Lucene fewer values to deal with. continue; } paths.add(path); previousPath = path; } for (String path : paths) { for (String fieldName : extractFieldNames(path)) { if (fieldType.indexOptions() != IndexOptions.NONE || fieldType.stored()) { document.add(new Field(fieldType().name(), fieldName, fieldType)); } } }
557
285
842
<methods>public void postParse(org.elasticsearch.index.mapper.ParseContext) throws java.io.IOException,public abstract void preParse(org.elasticsearch.index.mapper.ParseContext) throws java.io.IOException<variables>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/mapper/Mapping.java
Mapping
toXContent
class Mapping implements ToXContentFragment { final Version indexCreated; final RootObjectMapper root; final MetadataFieldMapper[] metadataMappers; final Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> metadataMappersMap; final Map<String, Object> meta; public Mapping(Version indexCreated, RootObjectMapper rootObjectMapper, MetadataFieldMapper[] metadataMappers, Map<String, Object> meta) { this.indexCreated = indexCreated; this.metadataMappers = metadataMappers; Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> metadataMappersMap = new HashMap<>(); for (MetadataFieldMapper metadataMapper : metadataMappers) { metadataMappersMap.put(metadataMapper.getClass(), metadataMapper); } this.root = rootObjectMapper; // keep root mappers sorted for consistent serialization Arrays.sort(metadataMappers, new Comparator<Mapper>() { @Override public int compare(Mapper o1, Mapper o2) { return o1.name().compareTo(o2.name()); } }); this.metadataMappersMap = unmodifiableMap(metadataMappersMap); this.meta = meta; } @NotNull public Set<String> indices() { if (meta == null) { return Set.of(); } Map<String, Object> indicesMap = Maps.getOrDefault(meta, "indices", Map.of()); return indicesMap.keySet(); } /** Return the root object mapper. */ public RootObjectMapper root() { return root; } /** * Generate a mapping update for the given root object mapper. */ public Mapping mappingUpdate(Mapper rootObjectMapper) { return new Mapping(indexCreated, (RootObjectMapper) rootObjectMapper, metadataMappers, meta); } /** Get the root mapper with the given class. */ @SuppressWarnings("unchecked") public <T extends MetadataFieldMapper> T metadataMapper(Class<T> clazz) { return (T) metadataMappersMap.get(clazz); } /** @see DocumentMapper#merge(Mapping, boolean) */ public Mapping merge(Mapping mergeWith) { RootObjectMapper mergedRoot = root.merge(mergeWith.root); Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> mergedMetadataMappers = new HashMap<>(metadataMappersMap); for (MetadataFieldMapper metaMergeWith : mergeWith.metadataMappers) { MetadataFieldMapper mergeInto = mergedMetadataMappers.get(metaMergeWith.getClass()); MetadataFieldMapper merged; if (mergeInto == null) { merged = metaMergeWith; } else { merged = (MetadataFieldMapper) mergeInto.merge(metaMergeWith); } mergedMetadataMappers.put(merged.getClass(), merged); } Map<String, Object> mergedMeta = mergeWith.meta == null ? meta : mergeWith.meta; return new Mapping(indexCreated, mergedRoot, mergedMetadataMappers.values().toArray(new MetadataFieldMapper[0]), mergedMeta); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {<FILL_FUNCTION_BODY>} @Override public String toString() { try { XContentBuilder builder = JsonXContent.builder().startObject(); toXContent(builder, new ToXContent.MapParams(emptyMap())); return Strings.toString(builder.endObject()); } catch (IOException bogus) { throw new UncheckedIOException(bogus); } } }
root.toXContent(builder, params, new ToXContent() { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if (meta != null) { builder.field("_meta", meta); } for (Mapper mapper : metadataMappers) { mapper.toXContent(builder, params); } return builder; } }); return builder;
967
117
1,084
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/mapper/ParseContext.java
InternalParseContext
createCopyToContext
class InternalParseContext extends ParseContext { private final DocumentMapper docMapper; private final DocumentMapperParser docMapperParser; private final ContentPath path; private final XContentParser parser; private final Document document; private final IndexSettings indexSettings; private final SourceToParse sourceToParse; private final List<Mapper> dynamicMappers; public InternalParseContext(IndexSettings indexSettings, DocumentMapperParser docMapperParser, DocumentMapper docMapper, SourceToParse source, XContentParser parser) { this.indexSettings = indexSettings; this.docMapper = docMapper; this.docMapperParser = docMapperParser; this.path = new ContentPath(0); this.parser = parser; this.document = new Document(); this.sourceToParse = source; this.dynamicMappers = new ArrayList<>(); } @Override public DocumentMapperParser docMapperParser() { return this.docMapperParser; } @Override public IndexSettings indexSettings() { return this.indexSettings; } @Override public SourceToParse sourceToParse() { return this.sourceToParse; } @Override public ContentPath path() { return this.path; } @Override public XContentParser parser() { return this.parser; } @Override public Document doc() { return this.document; } @Override public RootObjectMapper root() { return docMapper.root(); } @Override public DocumentMapper docMapper() { return this.docMapper; } @Override public MapperService mapperService() { return docMapperParser.mapperService; } @Override public void addDynamicMapper(Mapper mapper) { dynamicMappers.add(mapper); } @Override public List<Mapper> getDynamicMappers() { return dynamicMappers; } } public abstract DocumentMapperParser docMapperParser(); /** * Return a new context that will be within a copy-to operation. */ public final ParseContext createCopyToContext() {<FILL_FUNCTION_BODY>
return new FilterParseContext(this) { @Override public boolean isWithinCopyTo() { return true; } };
582
40
622
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/mapper/ParsedDocument.java
ParsedDocument
toString
class ParsedDocument { private final Field version; private final String id; private final SequenceIDFields seqID; private final Document document; private final BytesReference source; private final Mapping dynamicMappingsUpdate; public ParsedDocument(Field version, SequenceIDFields seqID, String id, Document document, BytesReference source, Mapping dynamicMappingsUpdate) { this.version = version; this.seqID = seqID; this.id = id; this.document = document; this.source = source; this.dynamicMappingsUpdate = dynamicMappingsUpdate; } public String id() { return this.id; } public Field version() { return version; } public void updateSeqID(long sequenceNumber, long primaryTerm) { this.seqID.seqNo.setLongValue(sequenceNumber); this.seqID.seqNoDocValue.setLongValue(sequenceNumber); this.seqID.primaryTerm.setLongValue(primaryTerm); } /** * Makes the processing document as a tombstone document rather than a regular document. * Tombstone documents are stored in Lucene index to represent delete operations or Noops. */ ParsedDocument toTombstone() { this.seqID.tombstoneField.setLongValue(1); doc().add(this.seqID.tombstoneField); return this; } public Document doc() { return document; } public BytesReference source() { return this.source; } /** * Return dynamic updates to mappings or {@code null} if there were no * updates to the mappings. */ public Mapping dynamicMappingsUpdate() { return dynamicMappingsUpdate; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "Document id[" + id + "] doc [" + document + ']';
503
23
526
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/recovery/RecoveryStats.java
RecoveryStats
toString
class RecoveryStats { private final AtomicInteger currentAsSource = new AtomicInteger(); private final AtomicInteger currentAsTarget = new AtomicInteger(); private final AtomicLong throttleTimeInNanos = new AtomicLong(); public RecoveryStats() { } public void add(RecoveryStats recoveryStats) { if (recoveryStats != null) { this.currentAsSource.addAndGet(recoveryStats.currentAsSource()); this.currentAsTarget.addAndGet(recoveryStats.currentAsTarget()); } addTotals(recoveryStats); } public void addTotals(RecoveryStats recoveryStats) { if (recoveryStats != null) { this.throttleTimeInNanos.addAndGet(recoveryStats.throttleTime().nanos()); } } /** * Number of ongoing recoveries for which a shard serves as a source */ public int currentAsSource() { return currentAsSource.get(); } /** * Number of ongoing recoveries for which a shard serves as a target */ public int currentAsTarget() { return currentAsTarget.get(); } /** * Total time recoveries waited due to throttling */ public TimeValue throttleTime() { return TimeValue.timeValueNanos(throttleTimeInNanos.get()); } public void incCurrentAsTarget() { currentAsTarget.incrementAndGet(); } public void decCurrentAsTarget() { currentAsTarget.decrementAndGet(); } public void incCurrentAsSource() { currentAsSource.incrementAndGet(); } public void decCurrentAsSource() { currentAsSource.decrementAndGet(); } public void addThrottleTime(long nanos) { throttleTimeInNanos.addAndGet(nanos); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "recoveryStats, currentAsSource [" + currentAsSource() + "],currentAsTarget [" + currentAsTarget() + "], throttle [" + throttleTime() + "]";
532
51
583
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/search/MultiMatchQuery.java
CrossFieldsQueryBuilder
blendTerms
class CrossFieldsQueryBuilder extends QueryBuilder { private FieldAndFieldType[] blendedFields; CrossFieldsQueryBuilder(float tiebreaker) { super(tiebreaker); } @Override public List<Query> buildGroupedQueries(MultiMatchQueryType type, Map<String, Float> fieldNames, Object value, String minimumShouldMatch) { Map<Analyzer, List<FieldAndFieldType>> groups = new HashMap<>(); List<Query> queries = new ArrayList<>(); for (Map.Entry<String, Float> entry : fieldNames.entrySet()) { String name = entry.getKey(); MappedFieldType fieldType = context.fieldMapper(name); if (fieldType != null) { Analyzer actualAnalyzer = getAnalyzer(fieldType, type == MultiMatchQueryType.PHRASE); name = fieldType.name(); if (!groups.containsKey(actualAnalyzer)) { groups.put(actualAnalyzer, new ArrayList<>()); } Float boost = entry.getValue(); boost = boost == null ? Float.valueOf(1.0f) : boost; groups.get(actualAnalyzer).add(new FieldAndFieldType(fieldType, boost)); } else { queries.add(new MatchNoDocsQuery("unknown field " + name)); } } for (List<FieldAndFieldType> group : groups.values()) { if (group.size() > 1) { blendedFields = new FieldAndFieldType[group.size()]; int i = 0; for (FieldAndFieldType fieldAndFieldType : group) { blendedFields[i++] = fieldAndFieldType; } } else { blendedFields = null; } /* * We have to pick some field to pass through the superclass so * we just pick the first field. It shouldn't matter because * fields are already grouped by their analyzers/types. */ String representativeField = group.get(0).fieldType.name(); Query q = parseGroup(type.matchQueryType(), representativeField, 1f, value, minimumShouldMatch); if (q != null) { queries.add(q); } } return queries.isEmpty() ? null : queries; } @Override public Query blendTerms(Term[] terms, MappedFieldType fieldType) { if (blendedFields == null || blendedFields.length == 1) { return super.blendTerms(terms, fieldType); } BytesRef[] values = new BytesRef[terms.length]; for (int i = 0; i < terms.length; i++) { values[i] = terms[i].bytes(); } return MultiMatchQuery.blendTerms(context, values, commonTermsCutoff, tieBreaker, blendedFields); } @Override public Query blendTerm(Term term, MappedFieldType fieldType) { if (blendedFields == null) { return super.blendTerm(term, fieldType); } return MultiMatchQuery.blendTerm(context, term.bytes(), commonTermsCutoff, tieBreaker, blendedFields); } @Override public Query termQuery(MappedFieldType fieldType, BytesRef value) { /* * Use the string value of the term because we're reusing the * portion of the query is usually after the analyzer has run on * each term. We just skip that analyzer phase. */ return blendTerm(new Term(fieldType.name(), value.utf8ToString()), fieldType); } @Override public Query blendPhrase(PhraseQuery query, MappedFieldType type) { if (blendedFields == null) { return super.blendPhrase(query, type); } /** * We build phrase queries for multi-word synonyms when {@link QueryBuilder#autoGenerateSynonymsPhraseQuery} is true. */ return MultiMatchQuery.blendPhrase(query, tieBreaker, blendedFields); } } static Query blendTerm(QueryShardContext context, BytesRef value, Float commonTermsCutoff, float tieBreaker, FieldAndFieldType... blendedFields) { return blendTerms(context, new BytesRef[] {value}, commonTermsCutoff, tieBreaker, blendedFields); } static Query blendTerms(QueryShardContext context, BytesRef[] values, Float commonTermsCutoff, float tieBreaker, FieldAndFieldType... blendedFields) {<FILL_FUNCTION_BODY>
List<Query> queries = new ArrayList<>(); Term[] terms = new Term[blendedFields.length * values.length]; float[] blendedBoost = new float[blendedFields.length * values.length]; int i = 0; for (FieldAndFieldType ft : blendedFields) { for (BytesRef term : values) { Query query; try { query = new TermQuery(new Term(ft.fieldType.name(), term)); } catch (IllegalArgumentException e) { // the query expects a certain class of values such as numbers // of ip addresses and the value can't be parsed, so ignore this // field continue; } catch (ElasticsearchParseException parseException) { // date fields throw an ElasticsearchParseException with the // underlying IAE as the cause, ignore this field if that is // the case if (parseException.getCause() instanceof IllegalArgumentException) { continue; } throw parseException; } float boost = ft.boost; while (query instanceof BoostQuery) { BoostQuery bq = (BoostQuery) query; query = bq.getQuery(); boost *= bq.getBoost(); } if (query.getClass() == TermQuery.class) { terms[i] = ((TermQuery) query).getTerm(); blendedBoost[i] = boost; i++; } else { if (boost != 1f && query instanceof MatchNoDocsQuery == false) { query = new BoostQuery(query, boost); } queries.add(query); } } } if (i > 0) { terms = Arrays.copyOf(terms, i); blendedBoost = Arrays.copyOf(blendedBoost, i); if (commonTermsCutoff != null) { queries.add(BlendedTermQuery.commonTermsBlendedQuery(terms, blendedBoost, commonTermsCutoff)); } else { queries.add(BlendedTermQuery.dismaxBlendedQuery(terms, blendedBoost, tieBreaker)); } } if (queries.size() == 1) { return queries.get(0); } else { // best effort: add clauses that are not term queries so that they have an opportunity to match // however their score contribution will be different // TODO: can we improve this? return new DisjunctionMaxQuery(queries, 1.0f); }
1,168
635
1,803
<methods>public void <init>(org.elasticsearch.index.query.QueryShardContext) ,public Query parse(org.elasticsearch.index.search.MatchQuery.Type, java.lang.String, java.lang.Object) ,public void setAnalyzer(java.lang.String) ,public void setAnalyzer(Analyzer) ,public void setAutoGenerateSynonymsPhraseQuery(boolean) ,public void setCommonTermsCutoff(java.lang.Float) ,public void setEnablePositionIncrements(boolean) ,public void setFuzziness(org.elasticsearch.common.unit.Fuzziness) ,public void setFuzzyPrefixLength(int) ,public void setFuzzyRewriteMethod(MultiTermQuery.RewriteMethod) ,public void setLenient(boolean) ,public void setMaxExpansions(int) ,public void setOccur(BooleanClause.Occur) ,public void setPhraseSlop(int) ,public void setTranspositions(boolean) ,public void setZeroTermsQuery(org.elasticsearch.index.search.MatchQuery.ZeroTermsQuery) <variables>static final float DEFAULT_BOOST,public static final boolean DEFAULT_LENIENCY,public static final int DEFAULT_PHRASE_SLOP,public static final org.elasticsearch.index.search.MatchQuery.ZeroTermsQuery DEFAULT_ZERO_TERMS_QUERY,private static final org.elasticsearch.common.logging.DeprecationLogger DEPRECATION_LOGGER,protected Analyzer analyzer,protected boolean autoGenerateSynonymsPhraseQuery,protected java.lang.Float commonTermsCutoff,protected final non-sealed org.elasticsearch.index.query.QueryShardContext context,protected boolean enablePositionIncrements,protected org.elasticsearch.common.unit.Fuzziness fuzziness,protected int fuzzyPrefixLength,protected MultiTermQuery.RewriteMethod fuzzyRewriteMethod,protected boolean lenient,protected int maxExpansions,protected BooleanClause.Occur occur,protected int phraseSlop,protected boolean transpositions,protected org.elasticsearch.index.search.MatchQuery.ZeroTermsQuery zeroTermsQuery
crate_crate
crate/server/src/main/java/org/elasticsearch/index/seqno/SequenceNumbers.java
SequenceNumbers
loadSeqNoInfoFromLuceneCommit
class SequenceNumbers { public static final String LOCAL_CHECKPOINT_KEY = "local_checkpoint"; public static final String MAX_SEQ_NO = "max_seq_no"; /** * Represents an unassigned sequence number (e.g., can be used on primary operations before they are executed). */ public static final long UNASSIGNED_SEQ_NO = -2L; /** * Represents no operations have been performed on the shard. Initial value of a sequence number. */ public static final long NO_OPS_PERFORMED = -1L; public static final long SKIP_ON_REPLICA = -3L; /** * Represents an unassigned primary term (e.g., when a primary shard was not yet allocated) */ public static final long UNASSIGNED_PRIMARY_TERM = 0L; /** * Reads the sequence number stats from the commit data (maximum sequence number and local checkpoint). * * @param commitData the commit data * @return the sequence number stats */ public static CommitInfo loadSeqNoInfoFromLuceneCommit( final Iterable<Map.Entry<String, String>> commitData) {<FILL_FUNCTION_BODY>} /** * Compute the minimum of the given current minimum sequence number and the specified sequence number, accounting for the fact that the * current minimum sequence number could be {@link SequenceNumbers#NO_OPS_PERFORMED} or * {@link SequenceNumbers#UNASSIGNED_SEQ_NO}. When the current minimum sequence number is not * {@link SequenceNumbers#NO_OPS_PERFORMED} nor {@link SequenceNumbers#UNASSIGNED_SEQ_NO}, the specified sequence number * must not be {@link SequenceNumbers#UNASSIGNED_SEQ_NO}. * * @param minSeqNo the current minimum sequence number * @param seqNo the specified sequence number * @return the new minimum sequence number */ public static long min(final long minSeqNo, final long seqNo) { if (minSeqNo == NO_OPS_PERFORMED) { return seqNo; } else if (minSeqNo == UNASSIGNED_SEQ_NO) { return seqNo; } else { if (seqNo == UNASSIGNED_SEQ_NO) { throw new IllegalArgumentException("sequence number must be assigned"); } return Math.min(minSeqNo, seqNo); } } /** * Compute the maximum of the given current maximum sequence number and the specified sequence number, accounting for the fact that the * current maximum sequence number could be {@link SequenceNumbers#NO_OPS_PERFORMED} or * {@link SequenceNumbers#UNASSIGNED_SEQ_NO}. When the current maximum sequence number is not * {@link SequenceNumbers#NO_OPS_PERFORMED} nor {@link SequenceNumbers#UNASSIGNED_SEQ_NO}, the specified sequence number * must not be {@link SequenceNumbers#UNASSIGNED_SEQ_NO}. * * @param maxSeqNo the current maximum sequence number * @param seqNo the specified sequence number * @return the new maximum sequence number */ public static long max(final long maxSeqNo, final long seqNo) { if (maxSeqNo == NO_OPS_PERFORMED) { return seqNo; } else if (maxSeqNo == UNASSIGNED_SEQ_NO) { return seqNo; } else { if (seqNo == UNASSIGNED_SEQ_NO) { throw new IllegalArgumentException("sequence number must be assigned"); } return Math.max(maxSeqNo, seqNo); } } public static final class CommitInfo { public final long maxSeqNo; public final long localCheckpoint; public CommitInfo(long maxSeqNo, long localCheckpoint) { this.maxSeqNo = maxSeqNo; this.localCheckpoint = localCheckpoint; } @Override public String toString() { return "CommitInfo{" + "maxSeqNo=" + maxSeqNo + ", localCheckpoint=" + localCheckpoint + '}'; } } }
long maxSeqNo = NO_OPS_PERFORMED; long localCheckpoint = NO_OPS_PERFORMED; for (final Map.Entry<String, String> entry : commitData) { final String key = entry.getKey(); if (key.equals(SequenceNumbers.LOCAL_CHECKPOINT_KEY)) { assert localCheckpoint == NO_OPS_PERFORMED : localCheckpoint; localCheckpoint = Long.parseLong(entry.getValue()); } else if (key.equals(SequenceNumbers.MAX_SEQ_NO)) { assert maxSeqNo == NO_OPS_PERFORMED : maxSeqNo; maxSeqNo = Long.parseLong(entry.getValue()); } } return new CommitInfo(maxSeqNo, localCheckpoint);
1,117
207
1,324
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/shard/PrimaryReplicaSyncer.java
SnapshotSender
doRun
class SnapshotSender extends AbstractRunnable implements ActionListener<ReplicationResponse> { private final SyncAction syncAction; private final ResyncTask task; // to track progress private final String primaryAllocationId; private final long primaryTerm; private final ShardId shardId; private final Translog.Snapshot snapshot; private final long startingSeqNo; private final long maxSeqNo; private final long maxSeenAutoIdTimestamp; private final int chunkSizeInBytes; private final ActionListener<Void> listener; private final AtomicBoolean firstMessage = new AtomicBoolean(true); private final AtomicInteger totalSentOps = new AtomicInteger(); private final AtomicInteger totalSkippedOps = new AtomicInteger(); private final AtomicBoolean closed = new AtomicBoolean(); SnapshotSender(SyncAction syncAction, ResyncTask task, ShardId shardId, String primaryAllocationId, long primaryTerm, Translog.Snapshot snapshot, int chunkSizeInBytes, long startingSeqNo, long maxSeqNo, long maxSeenAutoIdTimestamp, ActionListener<Void> listener) { this.syncAction = syncAction; this.task = task; this.shardId = shardId; this.primaryAllocationId = primaryAllocationId; this.primaryTerm = primaryTerm; this.snapshot = snapshot; this.chunkSizeInBytes = chunkSizeInBytes; this.startingSeqNo = startingSeqNo; this.maxSeqNo = maxSeqNo; this.maxSeenAutoIdTimestamp = maxSeenAutoIdTimestamp; this.listener = listener; task.setTotalOperations(snapshot.totalOperations()); } @Override public void onResponse(ReplicationResponse response) { run(); } @Override public void onFailure(Exception e) { if (closed.compareAndSet(false, true)) { listener.onFailure(e); } } private static final Translog.Operation[] EMPTY_ARRAY = new Translog.Operation[0]; @Override protected void doRun() throws Exception {<FILL_FUNCTION_BODY>} }
long size = 0; final List<Translog.Operation> operations = new ArrayList<>(); task.setPhase("collecting_ops"); task.setResyncedOperations(totalSentOps.get()); task.setSkippedOperations(totalSkippedOps.get()); Translog.Operation operation; while ((operation = snapshot.next()) != null) { final long seqNo = operation.seqNo(); if (seqNo == SequenceNumbers.UNASSIGNED_SEQ_NO || seqNo < startingSeqNo) { totalSkippedOps.incrementAndGet(); continue; } assert operation.seqNo() >= 0 : "sending operation with unassigned sequence number [" + operation + "]"; operations.add(operation); size += operation.estimateSize(); totalSentOps.incrementAndGet(); // check if this request is past bytes threshold, and if so, send it off if (size >= chunkSizeInBytes) { break; } } final long trimmedAboveSeqNo = firstMessage.get() ? maxSeqNo : SequenceNumbers.UNASSIGNED_SEQ_NO; // have to send sync request even in case of there are no operations to sync - have to sync trimmedAboveSeqNo at least if (!operations.isEmpty() || trimmedAboveSeqNo != SequenceNumbers.UNASSIGNED_SEQ_NO) { task.setPhase("sending_ops"); ResyncReplicationRequest request = new ResyncReplicationRequest(shardId, trimmedAboveSeqNo, maxSeenAutoIdTimestamp, operations.toArray(EMPTY_ARRAY)); LOGGER.trace("{} sending batch of [{}][{}] (total sent: [{}], skipped: [{}])", shardId, operations.size(), new ByteSizeValue(size), totalSentOps.get(), totalSkippedOps.get()); firstMessage.set(false); syncAction.sync(request, primaryAllocationId, primaryTerm, this); } else if (closed.compareAndSet(false, true)) { LOGGER.trace("{} resync completed (total sent: [{}], skipped: [{}])", shardId, totalSentOps.get(), totalSkippedOps.get()); listener.onResponse(null); }
578
594
1,172
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/shard/ReplicationGroup.java
ReplicationGroup
hashCode
class ReplicationGroup { private final IndexShardRoutingTable routingTable; private final Set<String> inSyncAllocationIds; private final Set<String> trackedAllocationIds; private final long version; private final Set<String> unavailableInSyncShards; // derived from the other fields private final List<ShardRouting> replicationTargets; // derived from the other fields private final List<ShardRouting> skippedShards; // derived from the other fields public ReplicationGroup(IndexShardRoutingTable routingTable, Set<String> inSyncAllocationIds, Set<String> trackedAllocationIds, long version) { this.routingTable = routingTable; this.inSyncAllocationIds = inSyncAllocationIds; this.trackedAllocationIds = trackedAllocationIds; this.version = version; this.unavailableInSyncShards = Sets.difference(inSyncAllocationIds, routingTable.getAllAllocationIds()); this.replicationTargets = new ArrayList<>(); this.skippedShards = new ArrayList<>(); for (final ShardRouting shard : routingTable) { if (shard.unassigned()) { assert shard.primary() == false : "primary shard should not be unassigned in a replication group: " + shard; skippedShards.add(shard); } else { if (trackedAllocationIds.contains(shard.allocationId().getId())) { replicationTargets.add(shard); } else { assert inSyncAllocationIds.contains(shard.allocationId().getId()) == false : "in-sync shard copy but not tracked: " + shard; skippedShards.add(shard); } if (shard.relocating()) { ShardRouting relocationTarget = shard.getTargetRelocatingShard(); if (trackedAllocationIds.contains(relocationTarget.allocationId().getId())) { replicationTargets.add(relocationTarget); } else { skippedShards.add(relocationTarget); assert inSyncAllocationIds.contains(relocationTarget.allocationId().getId()) == false : "in-sync shard copy but not tracked: " + shard; } } } } } public long getVersion() { return version; } public IndexShardRoutingTable getRoutingTable() { return routingTable; } public Set<String> getInSyncAllocationIds() { return inSyncAllocationIds; } public Set<String> getTrackedAllocationIds() { return trackedAllocationIds; } /** * Returns the set of shard allocation ids that are in the in-sync set but have no assigned routing entry */ public Set<String> getUnavailableInSyncShards() { return unavailableInSyncShards; } /** * Returns the subset of shards in the routing table that should be replicated to. Includes relocation targets. */ public List<ShardRouting> getReplicationTargets() { return replicationTargets; } /** * Returns the subset of shards in the routing table that are unassigned or initializing and not ready yet to receive operations * (i.e. engine not opened yet). Includes relocation targets. */ public List<ShardRouting> getSkippedShards() { return skippedShards; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ReplicationGroup that = (ReplicationGroup) o; if (!routingTable.equals(that.routingTable)) return false; if (!inSyncAllocationIds.equals(that.inSyncAllocationIds)) return false; return trackedAllocationIds.equals(that.trackedAllocationIds); } @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public String toString() { return "ReplicationGroup{" + "routingTable=" + routingTable + ", inSyncAllocationIds=" + inSyncAllocationIds + ", trackedAllocationIds=" + trackedAllocationIds + '}'; } }
int result = routingTable.hashCode(); result = 31 * result + inSyncAllocationIds.hashCode(); result = 31 * result + trackedAllocationIds.hashCode(); return result;
1,120
55
1,175
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/shard/ShardId.java
ShardId
computeHashCode
class ShardId implements Writeable, Comparable<ShardId> { private final Index index; private final int shardId; private final int hashCode; public ShardId(Index index, int shardId) { this.index = index; this.shardId = shardId; this.hashCode = computeHashCode(); } public ShardId(String index, String indexUUID, int shardId) { this(new Index(index, indexUUID), shardId); } public ShardId(StreamInput in) throws IOException { index = new Index(in); shardId = in.readVInt(); hashCode = computeHashCode(); } @Override public void writeTo(StreamOutput out) throws IOException { index.writeTo(out); out.writeVInt(shardId); } public Index getIndex() { return index; } public String getIndexName() { return index.getName(); } public int id() { return this.shardId; } @Override public String toString() { return "[" + index.getName() + "][" + shardId + "]"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ShardId shardId1 = (ShardId) o; return shardId == shardId1.shardId && index.equals(shardId1.index); } @Override public int hashCode() { return hashCode; } private int computeHashCode() {<FILL_FUNCTION_BODY>} @Override public int compareTo(ShardId o) { if (o.id() == shardId) { int compare = index.getName().compareTo(o.getIndex().getName()); if (compare != 0) { return compare; } return index.getUUID().compareTo(o.getIndex().getUUID()); } return Integer.compare(shardId, o.id()); } }
int result = index != null ? index.hashCode() : 0; result = 31 * result + shardId; return result;
569
40
609
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/shard/ShardUtils.java
ShardUtils
extractShardId
class ShardUtils { private ShardUtils() { } /** * Tries to extract the shard id from a reader if possible, when its not possible, * will return null. */ @Nullable public static ShardId extractShardId(LeafReader reader) { final ElasticsearchLeafReader esReader = ElasticsearchLeafReader.getElasticsearchLeafReader(reader); if (esReader != null) { assert reader.getRefCount() > 0 : "ElasticsearchLeafReader is already closed"; return esReader.shardId(); } return null; } /** * Tries to extract the shard id from a reader if possible, when its not possible, * will return null. */ @Nullable public static ShardId extractShardId(DirectoryReader reader) {<FILL_FUNCTION_BODY>} }
final ElasticsearchDirectoryReader esReader = ElasticsearchDirectoryReader.getElasticsearchDirectoryReader(reader); if (esReader != null) { return esReader.shardId(); } throw new IllegalArgumentException("can't extract shard ID, can't unwrap ElasticsearchDirectoryReader");
234
79
313
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/snapshots/blobstore/RateLimitingInputStream.java
RateLimitingInputStream
read
class RateLimitingInputStream extends FilterInputStream { private final Supplier<RateLimiter> rateLimiterSupplier; private final Listener listener; private long bytesSinceLastRateLimit; public interface Listener { void onPause(long nanos); } public RateLimitingInputStream(InputStream delegate, Supplier<RateLimiter> rateLimiterSupplier, Listener listener) { super(delegate); this.rateLimiterSupplier = rateLimiterSupplier; this.listener = listener; } private void maybePause(int bytes) throws IOException { bytesSinceLastRateLimit += bytes; final RateLimiter rateLimiter = rateLimiterSupplier.get(); if (rateLimiter != null) { if (bytesSinceLastRateLimit >= rateLimiter.getMinPauseCheckBytes()) { long pause = rateLimiter.pause(bytesSinceLastRateLimit); bytesSinceLastRateLimit = 0; if (pause > 0) { listener.onPause(pause); } } } } @Override public int read() throws IOException { int b = super.read(); maybePause(1); return b; } @Override public int read(byte[] b, int off, int len) throws IOException {<FILL_FUNCTION_BODY>} }
int n = super.read(b, off, len); if (n > 0) { maybePause(n); } return n;
365
43
408
<methods>public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException<variables>protected volatile java.io.InputStream in
crate_crate
crate/server/src/main/java/org/elasticsearch/index/snapshots/blobstore/SnapshotFiles.java
SnapshotFiles
findPhysicalIndexFile
class SnapshotFiles { private final String snapshot; private final List<FileInfo> indexFiles; @Nullable private final String shardStateIdentifier; private Map<String, FileInfo> physicalFiles = null; /** * Returns snapshot name * * @return snapshot name */ public String snapshot() { return snapshot; } /** * @param snapshot snapshot name * @param indexFiles index files * @param shardStateIdentifier unique identifier for the state of the shard that this snapshot was taken from */ public SnapshotFiles(String snapshot, List<FileInfo> indexFiles, @Nullable String shardStateIdentifier) { this.snapshot = snapshot; this.indexFiles = indexFiles; this.shardStateIdentifier = shardStateIdentifier; } /** * Returns an identifier for the shard state that can be used to check whether a shard has changed between * snapshots or not. */ @Nullable public String shardStateIdentifier() { return shardStateIdentifier; } /** * Returns a list of file in the snapshot */ public List<FileInfo> indexFiles() { return indexFiles; } /** * Returns true if this snapshot contains a file with a given original name * * @param physicalName original file name * @return true if the file was found, false otherwise */ public boolean containPhysicalIndexFile(String physicalName) { return findPhysicalIndexFile(physicalName) != null; } /** * Returns information about a physical file with the given name * @param physicalName the original file name * @return information about this file */ private FileInfo findPhysicalIndexFile(String physicalName) {<FILL_FUNCTION_BODY>} }
if (physicalFiles == null) { Map<String, FileInfo> files = new HashMap<>(); for (FileInfo fileInfo : indexFiles) { files.put(fileInfo.physicalName(), fileInfo); } this.physicalFiles = files; } return physicalFiles.get(physicalName);
467
83
550
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/store/ByteSizeCachingDirectory.java
SizeAndModCount
wrapIndexOutput
class SizeAndModCount { final long size; final long modCount; final boolean pendingWrite; SizeAndModCount(long length, long modCount, boolean pendingWrite) { this.size = length; this.modCount = modCount; this.pendingWrite = pendingWrite; } } private static long estimateSizeInBytes(Directory directory) throws IOException { long estimatedSize = 0; String[] files = directory.listAll(); for (String file : files) { try { estimatedSize += directory.fileLength(file); } catch (NoSuchFileException | FileNotFoundException | AccessDeniedException e) { // ignore, the file is not there no more; on Windows, if one thread concurrently deletes a file while // calling Files.size, you can also sometimes hit AccessDeniedException } } return estimatedSize; } private final SingleObjectCache<SizeAndModCount> size; // Both these variables need to be accessed under `this` lock. private long modCount = 0; private long numOpenOutputs = 0; ByteSizeCachingDirectory(Directory in, TimeValue refreshInterval) { super(in); size = new SingleObjectCache<SizeAndModCount>(refreshInterval, new SizeAndModCount(0L, -1L, true)) { @Override protected SizeAndModCount refresh() { // It is ok for the size of the directory to be more recent than // the mod count, we would just recompute the size of the // directory on the next call as well. However the opposite // would be bad as we would potentially have a stale cache // entry for a long time. So we fetch the values of modCount and // numOpenOutputs BEFORE computing the size of the directory. final long modCount; final boolean pendingWrite; synchronized (ByteSizeCachingDirectory.this) { modCount = ByteSizeCachingDirectory.this.modCount; pendingWrite = ByteSizeCachingDirectory.this.numOpenOutputs != 0; } final long size; try { // Compute this OUTSIDE of the lock size = estimateSizeInBytes(getDelegate()); } catch (IOException e) { throw new UncheckedIOException(e); } return new SizeAndModCount(size, modCount, pendingWrite); } @Override protected boolean needsRefresh() { if (super.needsRefresh() == false) { // The size was computed recently, don't recompute return false; } SizeAndModCount cached = getNoRefresh(); if (cached.pendingWrite) { // The cached entry was generated while there were pending // writes, so the size might be stale: recompute. return true; } synchronized (ByteSizeCachingDirectory.this) { // If there are pending writes or if new files have been // written/deleted since last time: recompute return numOpenOutputs != 0 || cached.modCount != modCount; } } }; } /** Return the cumulative size of all files in this directory. */ long estimateSizeInBytes() throws IOException { try { return size.getOrRefresh().size; } catch (UncheckedIOException e) { // we wrapped in the cache and unwrap here throw e.getCause(); } } @Override public IndexOutput createOutput(String name, IOContext context) throws IOException { return wrapIndexOutput(super.createOutput(name, context)); } @Override public IndexOutput createTempOutput(String prefix, String suffix, IOContext context) throws IOException { return wrapIndexOutput(super.createTempOutput(prefix, suffix, context)); } private IndexOutput wrapIndexOutput(IndexOutput out) {<FILL_FUNCTION_BODY>
synchronized (this) { numOpenOutputs++; } return new FilterIndexOutput(out.toString(), out) { @Override public void writeBytes(byte[] b, int length) throws IOException { // Don't write to atomicXXX here since it might be called in // tight loops and memory barriers are costly super.writeBytes(b, length); } @Override public void writeByte(byte b) throws IOException { // Don't write to atomicXXX here since it might be called in // tight loops and memory barriers are costly super.writeByte(b); } @Override public void close() throws IOException { // Close might cause some data to be flushed from in-memory buffers, so // increment the modification counter too. try { super.close(); } finally { synchronized (ByteSizeCachingDirectory.this) { numOpenOutputs--; modCount++; } } } };
974
256
1,230
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/store/StoreStats.java
StoreStats
add
class StoreStats implements Writeable, ToXContentFragment { /** * Sentinel value for cases where the shard does not yet know its reserved size so we must fall back to an estimate, for instance * prior to receiving the list of files in a peer recovery. */ public static final long UNKNOWN_RESERVED_BYTES = -1L; public static final Version RESERVED_BYTES_VERSION = Version.V_4_8_0; private long sizeInBytes; private long reservedSize; public StoreStats() { } /** * @param sizeInBytes the size of the store in bytes * @param reservedSize a prediction of how much larger the store is expected to grow, or {@link StoreStats#UNKNOWN_RESERVED_BYTES}. */ public StoreStats(long sizeInBytes, long reservedSize) { assert reservedSize == UNKNOWN_RESERVED_BYTES || reservedSize >= 0 : reservedSize; this.sizeInBytes = sizeInBytes; this.reservedSize = reservedSize; } public StoreStats(StreamInput in) throws IOException { sizeInBytes = in.readVLong(); if (in.getVersion().onOrAfter(RESERVED_BYTES_VERSION)) { reservedSize = in.readZLong(); } else { reservedSize = UNKNOWN_RESERVED_BYTES; } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVLong(sizeInBytes); if (out.getVersion().onOrAfter(RESERVED_BYTES_VERSION)) { out.writeZLong(reservedSize); } } public void add(StoreStats stats) {<FILL_FUNCTION_BODY>} private static long ignoreIfUnknown(long reservedSize) { return reservedSize == UNKNOWN_RESERVED_BYTES ? 0L : reservedSize; } public long sizeInBytes() { return sizeInBytes; } public long getSizeInBytes() { return sizeInBytes; } public ByteSizeValue size() { return new ByteSizeValue(sizeInBytes); } public ByteSizeValue getSize() { return size(); } /** * A prediction of how much larger this store will eventually grow. For instance, if we are currently doing a peer recovery or restoring * a snapshot into this store then we can account for the rest of the recovery using this field. A value of {@code -1B} indicates that * the reserved size is unknown. */ public ByteSizeValue getReservedSize() { return new ByteSizeValue(reservedSize); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(Fields.STORE); builder.humanReadableField(Fields.SIZE_IN_BYTES, Fields.SIZE, size()); builder.humanReadableField(Fields.RESERVED_IN_BYTES, Fields.RESERVED, getReservedSize()); builder.endObject(); return builder; } static final class Fields { static final String STORE = "store"; static final String SIZE = "size"; static final String SIZE_IN_BYTES = "size_in_bytes"; static final String RESERVED = "reserved"; static final String RESERVED_IN_BYTES = "reserved_in_bytes"; } }
if (stats == null) { return; } sizeInBytes += stats.sizeInBytes; reservedSize = ignoreIfUnknown(reservedSize) + ignoreIfUnknown(stats.reservedSize);
913
55
968
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/translog/BufferedChecksumStreamInput.java
BufferedChecksumStreamInput
readShort
class BufferedChecksumStreamInput extends FilterStreamInput { private static final int SKIP_BUFFER_SIZE = 1024; private static final ThreadLocal<byte[]> BUFFER = ThreadLocal.withInitial(() -> new byte[8]); private byte[] skipBuffer; private final Checksum digest; private final String source; public BufferedChecksumStreamInput(StreamInput in, String source, BufferedChecksumStreamInput reuse) { super(in); this.source = source; if (reuse == null) { this.digest = new BufferedChecksum(new CRC32()); } else { this.digest = reuse.digest; digest.reset(); this.skipBuffer = reuse.skipBuffer; } } public BufferedChecksumStreamInput(StreamInput in, String source) { this(in, source, null); } public long getChecksum() { return this.digest.getValue(); } @Override public byte readByte() throws IOException { final byte b = delegate.readByte(); digest.update(b); return b; } @Override public void readBytes(byte[] b, int offset, int len) throws IOException { delegate.readBytes(b, offset, len); digest.update(b, offset, len); } @Override public short readShort() throws IOException {<FILL_FUNCTION_BODY>} @Override public int readInt() throws IOException { final byte[] buf = BUFFER.get(); readBytes(buf, 0, 4); return ((buf[0] & 0xFF) << 24) | ((buf[1] & 0xFF) << 16) | ((buf[2] & 0xFF) << 8) | (buf[3] & 0xFF); } @Override public long readLong() throws IOException { final byte[] buf = BUFFER.get(); readBytes(buf, 0, 8); return (((long) (((buf[0] & 0xFF) << 24) | ((buf[1] & 0xFF) << 16) | ((buf[2] & 0xFF) << 8) | (buf[3] & 0xFF))) << 32) | ((((buf[4] & 0xFF) << 24) | ((buf[5] & 0xFF) << 16) | ((buf[6] & 0xFF) << 8) | (buf[7] & 0xFF)) & 0xFFFFFFFFL); } @Override @SuppressWarnings("sync-override") public void reset() throws IOException { delegate.reset(); digest.reset(); } @Override public int read() throws IOException { return readByte() & 0xFF; } @Override public boolean markSupported() { return delegate.markSupported(); } @Override public long skip(long numBytes) throws IOException { if (numBytes < 0) { throw new IllegalArgumentException("numBytes must be >= 0, got " + numBytes); } if (skipBuffer == null) { skipBuffer = new byte[SKIP_BUFFER_SIZE]; } assert skipBuffer.length == SKIP_BUFFER_SIZE; long skipped = 0; for (; skipped < numBytes; ) { final int step = (int) Math.min(SKIP_BUFFER_SIZE, numBytes - skipped); readBytes(skipBuffer, 0, step); skipped += step; } return skipped; } @Override public synchronized void mark(int readlimit) { delegate.mark(readlimit); } public void resetDigest() { digest.reset(); } public String getSource() { return source; } }
final byte[] buf = BUFFER.get(); readBytes(buf, 0, 2); return (short) (((buf[0] & 0xFF) << 8) | (buf[1] & 0xFF));
1,011
61
1,072
<methods>public int available() throws java.io.IOException,public void close() throws java.io.IOException,public org.elasticsearch.Version getVersion() ,public int read() throws java.io.IOException,public byte readByte() throws java.io.IOException,public void readBytes(byte[], int, int) throws java.io.IOException,public int readInt() throws java.io.IOException,public long readLong() throws java.io.IOException,public short readShort() throws java.io.IOException,public void reset() throws java.io.IOException,public void setVersion(org.elasticsearch.Version) <variables>protected final non-sealed org.elasticsearch.common.io.stream.StreamInput delegate
crate_crate
crate/server/src/main/java/org/elasticsearch/index/translog/MultiSnapshot.java
SeqNoSet
getAndSet
class SeqNoSet { static final short BIT_SET_SIZE = 1024; private final LongObjectHashMap<CountedBitSet> bitSets = new LongObjectHashMap<>(); /** * Marks this sequence number and returns {@code true} if it is seen before. */ boolean getAndSet(long value) {<FILL_FUNCTION_BODY>} }
assert value >= 0; final long key = value / BIT_SET_SIZE; CountedBitSet bitset = bitSets.get(key); if (bitset == null) { bitset = new CountedBitSet(BIT_SET_SIZE); bitSets.put(key, bitset); } final int index = Math.toIntExact(value % BIT_SET_SIZE); final boolean wasOn = bitset.get(index); bitset.set(index); return wasOn;
102
136
238
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/index/translog/TranslogCorruptedException.java
TranslogCorruptedException
corruptedMessage
class TranslogCorruptedException extends ElasticsearchException { public TranslogCorruptedException(String source, String details) { super(corruptedMessage(source, details)); } public TranslogCorruptedException(String source, Throwable cause) { this(source, null, cause); } public TranslogCorruptedException(String source, String details, Throwable cause) { super(corruptedMessage(source, details), cause); } private static String corruptedMessage(String source, String details) {<FILL_FUNCTION_BODY>} public TranslogCorruptedException(StreamInput in) throws IOException { super(in); } }
String msg = "translog from source [" + source + "] is corrupted"; if (details != null) { msg += ", " + details; } return msg;
172
50
222
<methods>public void <init>(java.lang.Throwable) ,public transient void <init>(java.lang.String, java.lang.Object[]) ,public transient void <init>(java.lang.String, java.lang.Throwable, java.lang.Object[]) ,public void <init>(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public void addHeader(java.lang.String, List<java.lang.String>) ,public transient void addMetadata(java.lang.String, java.lang.String[]) ,public void addMetadata(java.lang.String, List<java.lang.String>) ,public static org.elasticsearch.ElasticsearchException fromXContent(org.elasticsearch.common.xcontent.XContentParser) throws java.io.IOException,public static void generateThrowableXContent(org.elasticsearch.common.xcontent.XContentBuilder, org.elasticsearch.common.xcontent.ToXContent.Params, java.lang.Throwable) throws java.io.IOException,public java.lang.String getDetailedMessage() ,public static java.lang.String getExceptionName(java.lang.Throwable) ,public List<java.lang.String> getHeader(java.lang.String) ,public Set<java.lang.String> getHeaderKeys() ,public static int getId(Class<? extends org.elasticsearch.ElasticsearchException>) ,public org.elasticsearch.index.Index getIndex() ,public List<java.lang.String> getMetadata(java.lang.String) ,public Set<java.lang.String> getMetadataKeys() ,public java.lang.Throwable getRootCause() ,public org.elasticsearch.index.shard.ShardId getShardId() ,public io.crate.rest.action.HttpErrorStatus httpErrorStatus() ,public static org.elasticsearch.ElasticsearchException innerFromXContent(org.elasticsearch.common.xcontent.XContentParser, boolean) throws java.io.IOException,public static boolean isRegistered(Class<? extends java.lang.Throwable>, org.elasticsearch.Version) ,public io.crate.protocols.postgres.PGErrorStatus pgErrorStatus() ,public static org.elasticsearch.ElasticsearchException readException(org.elasticsearch.common.io.stream.StreamInput, int) throws java.io.IOException,public static T readStackTrace(T, org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public void setIndex(org.elasticsearch.index.Index) ,public void setIndex(java.lang.String) ,public transient void setResources(java.lang.String, java.lang.String[]) ,public void setShard(org.elasticsearch.index.shard.ShardId) ,public org.elasticsearch.rest.RestStatus status() ,public java.lang.String toString() ,public org.elasticsearch.common.xcontent.XContentBuilder toXContent(org.elasticsearch.common.xcontent.XContentBuilder, org.elasticsearch.common.xcontent.ToXContent.Params) throws java.io.IOException,public java.lang.Throwable unwrapCause() ,public static T writeStackTraces(T, org.elasticsearch.common.io.stream.StreamOutput, Writer<java.lang.Throwable>) throws java.io.IOException,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>private static final java.lang.String CAUSED_BY,private static final non-sealed Map<Class<? extends org.elasticsearch.ElasticsearchException>,org.elasticsearch.ElasticsearchException.ElasticsearchExceptionHandle> CLASS_TO_ELASTICSEARCH_EXCEPTION_HANDLE,private static final java.lang.String HEADER,private static final non-sealed Map<java.lang.Integer,CheckedFunction<org.elasticsearch.common.io.stream.StreamInput,? extends org.elasticsearch.ElasticsearchException,java.io.IOException>> ID_TO_SUPPLIER,private static final java.lang.String INDEX_METADATA_KEY,private static final java.lang.String INDEX_METADATA_KEY_UUID,private static final java.lang.String REASON,private static final java.lang.String RESOURCE_METADATA_ID_KEY,private static final java.lang.String RESOURCE_METADATA_TYPE_KEY,private static final java.lang.String REST_EXCEPTION_SKIP_CAUSE,private static final boolean REST_EXCEPTION_SKIP_CAUSE_DEFAULT,public static final java.lang.String REST_EXCEPTION_SKIP_STACK_TRACE,public static final boolean REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT,private static final java.lang.String ROOT_CAUSE,private static final java.lang.String SHARD_METADATA_KEY,private static final java.lang.String STACK_TRACE,private static final org.elasticsearch.common.xcontent.ParseField SUPPRESSED,private static final java.lang.String TYPE,private static final org.elasticsearch.Version UNKNOWN_VERSION_ADDED,private final Map<java.lang.String,List<java.lang.String>> headers,private final Map<java.lang.String,List<java.lang.String>> metadata
crate_crate
crate/server/src/main/java/org/elasticsearch/index/translog/TranslogReader.java
TranslogReader
open
class TranslogReader extends BaseTranslogReader implements Closeable { protected final long length; private final int totalOperations; private final Checkpoint checkpoint; protected final AtomicBoolean closed = new AtomicBoolean(false); /** * Create a translog writer against the specified translog file channel. * * @param checkpoint the translog checkpoint * @param channel the translog file channel to open a translog reader against * @param path the path to the translog * @param header the header of the translog file */ TranslogReader(final Checkpoint checkpoint, final FileChannel channel, final Path path, final TranslogHeader header) { super(checkpoint.generation, channel, path, header); this.length = checkpoint.offset; this.totalOperations = checkpoint.numOps; this.checkpoint = checkpoint; } /** * Given a file channel, opens a {@link TranslogReader}, taking care of checking and validating the file header. * * @param channel the translog file channel * @param path the path to the translog * @param checkpoint the translog checkpoint * @param translogUUID the tranlog UUID * @return a new TranslogReader * @throws IOException if any of the file operations resulted in an I/O exception */ public static TranslogReader open( final FileChannel channel, final Path path, final Checkpoint checkpoint, final String translogUUID) throws IOException {<FILL_FUNCTION_BODY>} /** * Closes current reader and creates new one with new checkoint and same file channel */ TranslogReader closeIntoTrimmedReader(long aboveSeqNo, ChannelFactory channelFactory) throws IOException { if (closed.compareAndSet(false, true)) { Closeable toCloseOnFailure = channel; final TranslogReader newReader; try { if (aboveSeqNo < checkpoint.trimmedAboveSeqNo || aboveSeqNo < checkpoint.maxSeqNo && checkpoint.trimmedAboveSeqNo == SequenceNumbers.UNASSIGNED_SEQ_NO) { final Path checkpointFile = path.getParent().resolve(getCommitCheckpointFileName(checkpoint.generation)); final Checkpoint newCheckpoint = new Checkpoint(checkpoint.offset, checkpoint.numOps, checkpoint.generation, checkpoint.minSeqNo, checkpoint.maxSeqNo, checkpoint.globalCheckpoint, checkpoint.minTranslogGeneration, aboveSeqNo); Checkpoint.write(channelFactory, checkpointFile, newCheckpoint, StandardOpenOption.WRITE); IOUtils.fsync(checkpointFile, false); IOUtils.fsync(checkpointFile.getParent(), true); newReader = new TranslogReader(newCheckpoint, channel, path, header); } else { newReader = new TranslogReader(checkpoint, channel, path, header); } toCloseOnFailure = null; return newReader; } finally { IOUtils.close(toCloseOnFailure); } } else { throw new AlreadyClosedException(toString() + " is already closed"); } } public long sizeInBytes() { return length; } public int totalOperations() { return totalOperations; } @Override final Checkpoint getCheckpoint() { return checkpoint; } /** * reads an operation at the given position into the given buffer. */ protected void readBytes(ByteBuffer buffer, long position) throws IOException { if (position >= length) { throw new EOFException("read requested past EOF. pos [" + position + "] end: [" + length + "]"); } if (position < getFirstOperationOffset()) { throw new IOException("read requested before position of first ops. pos [" + position + "] first op on: [" + getFirstOperationOffset() + "]"); } Channels.readFromFileChannelWithEofException(channel, position, buffer); } @Override public final void close() throws IOException { if (closed.compareAndSet(false, true)) { channel.close(); } } protected final boolean isClosed() { return closed.get(); } protected void ensureOpen() { if (isClosed()) { throw new AlreadyClosedException(toString() + " is already closed"); } } }
final TranslogHeader header = TranslogHeader.read(translogUUID, path, channel); return new TranslogReader(checkpoint, channel, path, header);
1,131
42
1,173
<methods>public void <init>(long, java.nio.channels.FileChannel, java.nio.file.Path, org.elasticsearch.index.translog.TranslogHeader) ,public int compareTo(org.elasticsearch.index.translog.BaseTranslogReader) ,public final long getFirstOperationOffset() ,public long getGeneration() ,public long getLastModifiedTime() throws java.io.IOException,public final long getPrimaryTerm() ,public org.elasticsearch.index.translog.TranslogSnapshot newSnapshot() ,public java.nio.file.Path path() ,public abstract long sizeInBytes() ,public java.lang.String toString() ,public abstract int totalOperations() <variables>protected final non-sealed java.nio.channels.FileChannel channel,protected final non-sealed long generation,protected final non-sealed org.elasticsearch.index.translog.TranslogHeader header,protected final non-sealed java.nio.file.Path path
crate_crate
crate/server/src/main/java/org/elasticsearch/index/translog/TranslogStats.java
TranslogStats
toString
class TranslogStats { private final long translogSizeInBytes; private final int numberOfOperations; private final long uncommittedSizeInBytes; private final int uncommittedOperations; public TranslogStats(int numberOfOperations, long translogSizeInBytes, int uncommittedOperations, long uncommittedSizeInBytes) { if (numberOfOperations < 0) { throw new IllegalArgumentException("numberOfOperations must be >= 0"); } if (translogSizeInBytes < 0) { throw new IllegalArgumentException("translogSizeInBytes must be >= 0"); } if (uncommittedOperations < 0) { throw new IllegalArgumentException("uncommittedOperations must be >= 0"); } if (uncommittedSizeInBytes < 0) { throw new IllegalArgumentException("uncommittedSizeInBytes must be >= 0"); } this.numberOfOperations = numberOfOperations; this.translogSizeInBytes = translogSizeInBytes; this.uncommittedSizeInBytes = uncommittedSizeInBytes; this.uncommittedOperations = uncommittedOperations; } public long getTranslogSizeInBytes() { return translogSizeInBytes; } public int estimatedNumberOfOperations() { return numberOfOperations; } /** the size of the generations in the translog that weren't yet to committed to lucene */ public long getUncommittedSizeInBytes() { return uncommittedSizeInBytes; } /** the number of operations in generations of the translog that weren't yet to committed to lucene */ public int getUncommittedOperations() { return uncommittedOperations; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "TranslogStats{" + "translogSizeInBytes=" + translogSizeInBytes + ", numberOfOperations=" + numberOfOperations + ", uncommittedSizeInBytes=" + uncommittedSizeInBytes + ", uncommittedOperations=" + uncommittedOperations + '}';
467
85
552
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/indices/IndicesModule.java
IndicesModule
getEngineFactories
class IndicesModule extends AbstractModule { private final MapperRegistry mapperRegistry; public IndicesModule(List<MapperPlugin> mapperPlugins) { this.mapperRegistry = new MapperRegistry(getMappers(mapperPlugins), getMetadataMappers(mapperPlugins)); } public static List<NamedWriteableRegistry.Entry> getNamedWriteables() { return List.of(); } public static List<NamedXContentRegistry.Entry> getNamedXContents() { return Collections.emptyList(); } public static Map<String, Mapper.TypeParser> getMappers(List<MapperPlugin> mapperPlugins) { Map<String, Mapper.TypeParser> mappers = new LinkedHashMap<>(); // builtin mappers for (NumberFieldMapper.NumberType type : NumberFieldMapper.NumberType.values()) { mappers.put(type.typeName(), new NumberFieldMapper.TypeParser(type)); } mappers.put(BooleanFieldMapper.CONTENT_TYPE, new BooleanFieldMapper.TypeParser()); mappers.put(DateFieldMapper.CONTENT_TYPE, new DateFieldMapper.TypeParser()); mappers.put(IpFieldMapper.CONTENT_TYPE, new IpFieldMapper.TypeParser()); mappers.put(TextFieldMapper.CONTENT_TYPE, new TextFieldMapper.TypeParser()); mappers.put(KeywordFieldMapper.CONTENT_TYPE, new KeywordFieldMapper.TypeParser()); mappers.put(ObjectMapper.CONTENT_TYPE, new ObjectMapper.TypeParser()); mappers.put(GeoPointFieldMapper.CONTENT_TYPE, new GeoPointFieldMapper.TypeParser()); mappers.put(BitStringFieldMapper.CONTENT_TYPE, new BitStringFieldMapper.TypeParser()); mappers.put(FloatVectorType.INSTANCE_ONE.getName(), new FloatVectorFieldMapper.TypeParser()); mappers.put(ArrayMapper.CONTENT_TYPE, new ArrayTypeParser()); if (ShapesAvailability.JTS_AVAILABLE && ShapesAvailability.SPATIAL4J_AVAILABLE) { mappers.put(GeoShapeFieldMapper.CONTENT_TYPE, new GeoShapeFieldMapper.TypeParser()); } for (MapperPlugin mapperPlugin : mapperPlugins) { for (Map.Entry<String, Mapper.TypeParser> entry : mapperPlugin.getMappers().entrySet()) { if (mappers.put(entry.getKey(), entry.getValue()) != null) { throw new IllegalArgumentException("Mapper [" + entry.getKey() + "] is already registered"); } } } return Collections.unmodifiableMap(mappers); } private static final Map<String, MetadataFieldMapper.TypeParser> BUILT_IN_METADATA_MAPPERS = initBuiltInMetadataMappers(); private static Map<String, MetadataFieldMapper.TypeParser> initBuiltInMetadataMappers() { Map<String, MetadataFieldMapper.TypeParser> builtInMetadataMappers; // Use a LinkedHashMap for metadataMappers because iteration order matters builtInMetadataMappers = new LinkedHashMap<>(); // UID so it will be the first stored field to load // (so will benefit from "fields: []" early termination builtInMetadataMappers.put(IdFieldMapper.NAME, new IdFieldMapper.TypeParser()); builtInMetadataMappers.put(SourceFieldMapper.NAME, new SourceFieldMapper.TypeParser()); //_field_names must be added last so that it has a chance to see all the other mappers builtInMetadataMappers.put(FieldNamesFieldMapper.NAME, new FieldNamesFieldMapper.TypeParser()); return Collections.unmodifiableMap(builtInMetadataMappers); } public static Map<String, MetadataFieldMapper.TypeParser> getMetadataMappers(List<MapperPlugin> mapperPlugins) { Map<String, MetadataFieldMapper.TypeParser> metadataMappers = new LinkedHashMap<>(); int i = 0; Map.Entry<String, MetadataFieldMapper.TypeParser> fieldNamesEntry = null; for (Map.Entry<String, MetadataFieldMapper.TypeParser> entry : BUILT_IN_METADATA_MAPPERS.entrySet()) { if (i < BUILT_IN_METADATA_MAPPERS.size() - 1) { metadataMappers.put(entry.getKey(), entry.getValue()); } else { assert entry.getKey().equals(FieldNamesFieldMapper.NAME) : "_field_names must be the last registered mapper, order counts"; fieldNamesEntry = entry; } i++; } assert fieldNamesEntry != null; for (MapperPlugin mapperPlugin : mapperPlugins) { for (Map.Entry<String, MetadataFieldMapper.TypeParser> entry : mapperPlugin.getMetadataMappers().entrySet()) { if (entry.getKey().equals(FieldNamesFieldMapper.NAME)) { throw new IllegalArgumentException("Plugin cannot contain metadata mapper [" + FieldNamesFieldMapper.NAME + "]"); } if (metadataMappers.put(entry.getKey(), entry.getValue()) != null) { throw new IllegalArgumentException("MetadataFieldMapper [" + entry.getKey() + "] is already registered"); } } } // we register _field_names here so that it has a chance to see all the other mappers, including from plugins metadataMappers.put(fieldNamesEntry.getKey(), fieldNamesEntry.getValue()); return Collections.unmodifiableMap(metadataMappers); } @Override protected void configure() { bind(IndicesStore.class).asEagerSingleton(); bind(IndicesClusterStateService.class).asEagerSingleton(); bind(SyncedFlushService.class).asEagerSingleton(); bind(TransportResyncReplicationAction.class).asEagerSingleton(); bind(PrimaryReplicaSyncer.class).asEagerSingleton(); bind(RetentionLeaseSyncAction.class).asEagerSingleton(); bind(RetentionLeaseBackgroundSyncAction.class).asEagerSingleton(); bind(RetentionLeaseSyncer.class).asEagerSingleton(); } /** * A registry for all field mappers. */ public MapperRegistry getMapperRegistry() { return mapperRegistry; } public Collection<Function<IndexSettings, Optional<EngineFactory>>> getEngineFactories() {<FILL_FUNCTION_BODY>} }
return List.of( indexSettings -> { if (indexSettings.getSettings().get(LogicalReplicationSettings.REPLICATION_SUBSCRIPTION_NAME.getKey()) != null) { return Optional.of(SubscriberEngine::new); } return Optional.empty(); } );
1,679
83
1,762
<methods>public non-sealed void <init>() ,public final synchronized void configure(org.elasticsearch.common.inject.Binder) <variables>org.elasticsearch.common.inject.Binder binder
crate_crate
crate/server/src/main/java/org/elasticsearch/indices/ShardLimitValidator.java
ShardLimitValidator
checkShardLimit
class ShardLimitValidator { public static final Setting<Integer> SETTING_CLUSTER_MAX_SHARDS_PER_NODE = Setting.intSetting("cluster.max_shards_per_node", 1000, 1, Property.Dynamic, Property.NodeScope, Property.Exposed); protected final AtomicInteger shardLimitPerNode = new AtomicInteger(); public ShardLimitValidator(final Settings settings, ClusterService clusterService) { this.shardLimitPerNode.set(SETTING_CLUSTER_MAX_SHARDS_PER_NODE.get(settings)); clusterService.getClusterSettings().addSettingsUpdateConsumer(SETTING_CLUSTER_MAX_SHARDS_PER_NODE, this::setShardLimitPerNode); } private void setShardLimitPerNode(int newValue) { this.shardLimitPerNode.set(newValue); } /** * Gets the currently configured value of the {@link ShardLimitValidator#SETTING_CLUSTER_MAX_SHARDS_PER_NODE} setting. * @return the current value of the setting */ public int getShardLimitPerNode() { return shardLimitPerNode.get(); } /** * Checks whether an index can be created without going over the cluster shard limit. * * @param settings the settings of the index to be created * @param state the current cluster state * @throws ValidationException if creating this index would put the cluster over the cluster shard limit */ public void validateShardLimit(final Settings settings, final ClusterState state) { final int numberOfShards = INDEX_NUMBER_OF_SHARDS_SETTING.get(settings); final int numberOfReplicas = IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.get(settings); final int shardsToCreate = numberOfShards * (1 + numberOfReplicas); final Optional<String> shardLimit = checkShardLimit(shardsToCreate, state); if (shardLimit.isPresent()) { final ValidationException e = new ValidationException(); e.addValidationError(shardLimit.get()); throw e; } } /** * Checks to see if an operation can be performed without taking the cluster over the cluster-wide shard limit. * Returns an error message if appropriate, or an empty {@link Optional} otherwise. * * @param newShards The number of shards to be added by this operation * @param state The current cluster state * @return If present, an error message to be given as the reason for failing * an operation. If empty, a sign that the operation is valid. */ public Optional<String> checkShardLimit(int newShards, ClusterState state) { return checkShardLimit(newShards, state, getShardLimitPerNode()); } // package-private for testing static Optional<String> checkShardLimit(int newShards, ClusterState state, int maxShardsPerNodeSetting) {<FILL_FUNCTION_BODY>} }
int nodeCount = state.nodes().getDataNodes().size(); // Only enforce the shard limit if we have at least one data node, so that we don't block // index creation during cluster setup if (nodeCount == 0 || newShards < 0) { return Optional.empty(); } int maxShardsPerNode = maxShardsPerNodeSetting; int maxShardsInCluster = maxShardsPerNode * nodeCount; int currentOpenShards = state.metadata().getTotalOpenIndexShards(); if ((currentOpenShards + newShards) > maxShardsInCluster) { String errorMessage = "this action would add [" + newShards + "] total shards, but this cluster currently has [" + currentOpenShards + "]/[" + maxShardsInCluster + "] maximum shards open"; return Optional.of(errorMessage); } return Optional.empty();
787
229
1,016
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/indices/breaker/BreakerSettings.java
BreakerSettings
toString
class BreakerSettings { private final String name; private final long limitBytes; private final CircuitBreaker.Type type; public BreakerSettings(String name, long limitBytes, CircuitBreaker.Type type) { this.name = name; this.limitBytes = limitBytes; this.type = type; } public String getName() { return this.name; } public long getLimit() { return this.limitBytes; } public CircuitBreaker.Type getType() { return this.type; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "[" + this.name + ",type=" + this.type.toString() + ",limit=" + this.limitBytes + "/" + new ByteSizeValue(this.limitBytes) + "]";
174
56
230
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/indices/breaker/CircuitBreakerStats.java
CircuitBreakerStats
toString
class CircuitBreakerStats { private final String name; private final long limit; private final long used; private final long trippedCount; private final double overhead; @ConstructorProperties({"name", "limit", "used", "trippedCount", "overhead"}) public CircuitBreakerStats(String name, long limit, long used, long trippedCount, double overhead) { this.name = name; this.limit = limit; this.used = used; this.trippedCount = trippedCount; this.overhead = overhead; } public String getName() { return this.name; } public long getLimit() { return this.limit; } public long getUsed() { return this.used; } public long getTrippedCount() { return this.trippedCount; } /** * Kept around for BWC of JMX metrics * * Overhead cannot be set by the user anymore and must always be 1.0 **/ @Deprecated public double getOverhead() { return this.overhead; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "[" + this.name + ",limit=" + this.limit + "/" + new ByteSizeValue(this.limit) + ",estimated=" + this.used + "/" + new ByteSizeValue(this.used) + ",overhead=" + this.overhead + ",tripped=" + this.trippedCount + "]";
335
92
427
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/indices/recovery/BlobRecoveryTarget.java
StartTransferRequestHandler
messageReceived
class StartTransferRequestHandler implements TransportRequestHandler<BlobRecoveryStartTransferRequest> { @Override public void messageReceived(BlobRecoveryStartTransferRequest request, TransportChannel channel) throws Exception {<FILL_FUNCTION_BODY>} }
BlobRecoveryStatus status = onGoingBlobRecoveries.get(request.recoveryId()); LOGGER.debug("received BlobRecoveryStartTransferRequest for file {} with size {}", request.path(), request.size()); if (status == null) { throw new IllegalBlobRecoveryStateException("Could not retrieve onGoingRecoveryStatus"); } if (status.canceled()) { throw new IndexShardClosedException(status.shardId()); } BlobShard shard = status.blobShard; String tmpPath = request.path() + "." + request.transferId(); Path baseDirectory = shard.blobContainer().getBaseDirectory(); FileOutputStream outputStream = new FileOutputStream(baseDirectory.resolve(tmpPath).toFile()); request.content().writeTo(outputStream); if (request.size() == request.content().length()) { // start request contains the whole file. outputStream.close(); Path source = baseDirectory.resolve(tmpPath); Path target = baseDirectory.resolve(request.path()); Files.move(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } else { BlobRecoveryTransferStatus transferStatus = new BlobRecoveryTransferStatus( request.transferId(), outputStream, tmpPath, request.path() ); status.onGoingTransfers().put(request.transferId(), transferStatus); } channel.sendResponse(TransportResponse.Empty.INSTANCE);
66
395
461
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/indices/recovery/MultiChunkTransfer.java
MultiChunkTransfer
handleItems
class MultiChunkTransfer<Source, Request extends MultiChunkTransfer.ChunkRequest> implements Closeable { private Status status = Status.PROCESSING; private final Logger logger; private final ActionListener<Void> listener; private final LocalCheckpointTracker requestSeqIdTracker = new LocalCheckpointTracker(NO_OPS_PERFORMED, NO_OPS_PERFORMED); private final AsyncIOProcessor<FileChunkResponseItem<Source>> processor; private final int maxConcurrentChunks; private Source currentSource = null; private final Iterator<Source> remainingSources; private Tuple<Source, Request> readAheadRequest = null; protected MultiChunkTransfer(Logger logger, ActionListener<Void> listener, int maxConcurrentChunks, List<Source> sources) { this.logger = logger; this.maxConcurrentChunks = maxConcurrentChunks; this.listener = listener; this.processor = new AsyncIOProcessor<FileChunkResponseItem<Source>>(logger, maxConcurrentChunks) { @Override protected void write(List<Tuple<FileChunkResponseItem<Source>, Consumer<Exception>>> items) throws IOException { handleItems(items); } }; this.remainingSources = sources.iterator(); } public final void start() { addItem(UNASSIGNED_SEQ_NO, null, null); // put a dummy item to start the processor } private void addItem(long requestSeqId, Source resource, Exception failure) { processor.put( new FileChunkResponseItem<>(requestSeqId, resource, failure), e -> { assert e == null : e; } ); } private void handleItems(List<Tuple<FileChunkResponseItem<Source>, Consumer<Exception>>> items) {<FILL_FUNCTION_BODY>} private void onCompleted(Exception failure) { if (Assertions.ENABLED && status != Status.PROCESSING) { throw new AssertionError("invalid status: expected [" + Status.PROCESSING + "] actual [" + status + "]", failure); } status = failure == null ? Status.SUCCESS : Status.FAILED; try { IOUtils.close(failure, this); } catch (Exception e) { listener.onFailure(e); return; } listener.onResponse(null); } private Tuple<Source, Request> getNextRequest() throws Exception { try { if (currentSource == null) { if (remainingSources.hasNext()) { currentSource = remainingSources.next(); onNewResource(currentSource); } else { return null; } } final Source md = currentSource; final Request request = nextChunkRequest(md); if (request.lastChunk()) { currentSource = null; } return new Tuple<>(md, request); } catch (Exception e) { handleError(currentSource, e); throw e; } } /** * This method is called when starting sending/requesting a new source. Subclasses should override * this method to reset the file offset or close the previous file and open a new file if needed. */ protected void onNewResource(Source resource) throws IOException { } protected abstract Request nextChunkRequest(Source resource) throws IOException; protected abstract void executeChunkRequest(Request request, ActionListener<Void> listener); protected abstract void handleError(Source resource, Exception e) throws Exception; private static class FileChunkResponseItem<Source> { final long requestSeqId; final Source source; final Exception failure; FileChunkResponseItem(long requestSeqId, Source source, Exception failure) { this.requestSeqId = requestSeqId; this.source = source; this.failure = failure; } } public interface ChunkRequest { /** * @return {@code true} if this chunk request is the last chunk of the current file */ boolean lastChunk(); } private enum Status { PROCESSING, SUCCESS, FAILED } }
if (status != Status.PROCESSING) { assert status == Status.FAILED : "must not receive any response after the transfer was completed"; // These exceptions will be ignored as we record only the first failure, log them for debugging purpose. items.stream().filter(item -> item.v1().failure != null).forEach(item -> logger.debug(new ParameterizedMessage("failed to transfer a chunk request {}", item.v1().source), item.v1().failure)); return; } try { for (Tuple<FileChunkResponseItem<Source>, Consumer<Exception>> item : items) { final FileChunkResponseItem<Source> resp = item.v1(); if (resp.requestSeqId == UNASSIGNED_SEQ_NO) { continue; // not an actual item } requestSeqIdTracker.markSeqNoAsProcessed(resp.requestSeqId); if (resp.failure != null) { handleError(resp.source, resp.failure); throw resp.failure; } } while (requestSeqIdTracker.getMaxSeqNo() - requestSeqIdTracker.getProcessedCheckpoint() < maxConcurrentChunks) { final Tuple<Source, Request> request = readAheadRequest != null ? readAheadRequest : getNextRequest(); readAheadRequest = null; if (request == null) { assert currentSource == null && remainingSources.hasNext() == false; if (requestSeqIdTracker.getMaxSeqNo() == requestSeqIdTracker.getProcessedCheckpoint()) { onCompleted(null); } return; } final long requestSeqId = requestSeqIdTracker.generateSeqNo(); executeChunkRequest(request.v2(), ActionListener.wrap( r -> addItem(requestSeqId, request.v1(), null), e -> addItem(requestSeqId, request.v1(), e))); } // While we are waiting for the responses, we can prepare the next request in advance // so we can send it immediately when the responses arrive to reduce the transfer time. if (readAheadRequest == null) { readAheadRequest = getNextRequest(); } } catch (Exception e) { onCompleted(e); }
1,087
598
1,685
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/indices/recovery/RecoveryFilesInfoRequest.java
RecoveryFilesInfoRequest
writeTo
class RecoveryFilesInfoRequest extends RecoveryTransportRequest { private final long recoveryId; private final ShardId shardId; final List<String> phase1FileNames; final List<Long> phase1FileSizes; final List<String> phase1ExistingFileNames; final List<Long> phase1ExistingFileSizes; int totalTranslogOps; RecoveryFilesInfoRequest(long recoveryId, long requestSeqNo, ShardId shardId, List<String> phase1FileNames, List<Long> phase1FileSizes, List<String> phase1ExistingFileNames, List<Long> phase1ExistingFileSizes, int totalTranslogOps) { super(requestSeqNo); this.recoveryId = recoveryId; this.shardId = shardId; this.phase1FileNames = phase1FileNames; this.phase1FileSizes = phase1FileSizes; this.phase1ExistingFileNames = phase1ExistingFileNames; this.phase1ExistingFileSizes = phase1ExistingFileSizes; this.totalTranslogOps = totalTranslogOps; } public long recoveryId() { return this.recoveryId; } public ShardId shardId() { return shardId; } public RecoveryFilesInfoRequest(StreamInput in) throws IOException { super(in); recoveryId = in.readLong(); shardId = new ShardId(in); int size = in.readVInt(); phase1FileNames = new ArrayList<>(size); for (int i = 0; i < size; i++) { phase1FileNames.add(in.readString()); } size = in.readVInt(); phase1FileSizes = new ArrayList<>(size); for (int i = 0; i < size; i++) { phase1FileSizes.add(in.readVLong()); } size = in.readVInt(); phase1ExistingFileNames = new ArrayList<>(size); for (int i = 0; i < size; i++) { phase1ExistingFileNames.add(in.readString()); } size = in.readVInt(); phase1ExistingFileSizes = new ArrayList<>(size); for (int i = 0; i < size; i++) { phase1ExistingFileSizes.add(in.readVLong()); } totalTranslogOps = in.readVInt(); } @Override public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>} }
super.writeTo(out); out.writeLong(recoveryId); shardId.writeTo(out); out.writeVInt(phase1FileNames.size()); for (String phase1FileName : phase1FileNames) { out.writeString(phase1FileName); } out.writeVInt(phase1FileSizes.size()); for (Long phase1FileSize : phase1FileSizes) { out.writeVLong(phase1FileSize); } out.writeVInt(phase1ExistingFileNames.size()); for (String phase1ExistingFileName : phase1ExistingFileNames) { out.writeString(phase1ExistingFileName); } out.writeVInt(phase1ExistingFileSizes.size()); for (Long phase1ExistingFileSize : phase1ExistingFileSizes) { out.writeVLong(phase1ExistingFileSize); } out.writeVInt(totalTranslogOps);
688
254
942
<methods>public long requestSeqNo() ,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>private final non-sealed long requestSeqNo
crate_crate
crate/server/src/main/java/org/elasticsearch/indices/recovery/RecoverySourceHandler.java
FileChunk
sendFiles
class FileChunk implements MultiChunkTransfer.ChunkRequest, Releasable { final StoreFileMetadata md; final BytesReference content; final long position; final boolean lastChunk; final Releasable onClose; FileChunk(StoreFileMetadata md, BytesReference content, long position, boolean lastChunk, Releasable onClose) { this.md = md; this.content = content; this.position = position; this.lastChunk = lastChunk; this.onClose = onClose; } @Override public boolean lastChunk() { return lastChunk; } @Override public void close() { onClose.close(); } } void sendFiles(Store store, StoreFileMetadata[] files, IntSupplier translogOps, ActionListener<Void> listener) {<FILL_FUNCTION_BODY>
ArrayUtil.timSort(files, Comparator.comparingLong(StoreFileMetadata::length)); // send smallest first final MultiChunkTransfer<StoreFileMetadata, FileChunk> multiFileSender = new MultiChunkTransfer<StoreFileMetadata, FileChunk>( logger, listener, maxConcurrentFileChunks, Arrays.asList(files)) { final Deque<byte[]> buffers = new ConcurrentLinkedDeque<>(); InputStreamIndexInput currentInput = null; long offset = 0; @Override protected void onNewResource(StoreFileMetadata md) throws IOException { offset = 0; IOUtils.close(currentInput, () -> currentInput = null); final IndexInput indexInput = store.directory().openInput(md.name(), IOContext.READONCE); currentInput = new InputStreamIndexInput(indexInput, md.length()) { @Override public void close() throws IOException { IOUtils.close(indexInput, super::close); // InputStreamIndexInput's close is a noop } }; } private byte[] acquireBuffer() { final byte[] buffer = buffers.pollFirst(); if (buffer != null) { return buffer; } return new byte[chunkSizeInBytes]; } @Override protected FileChunk nextChunkRequest(StoreFileMetadata md) throws IOException { assert Transports.assertNotTransportThread("read file chunk"); cancellableThreads.checkForCancel(); final byte[] buffer = acquireBuffer(); final int bytesRead = currentInput.read(buffer); if (bytesRead == -1) { throw new CorruptIndexException("file truncated; length=" + md.length() + " offset=" + offset, md.name()); } final boolean lastChunk = offset + bytesRead == md.length(); final FileChunk chunk = new FileChunk(md, new BytesArray(buffer, 0, bytesRead), offset, lastChunk, () -> buffers.addFirst(buffer)); offset += bytesRead; return chunk; } @Override protected void executeChunkRequest(FileChunk request, ActionListener<Void> listener) { cancellableThreads.checkForCancel(); recoveryTarget.writeFileChunk( request.md, request.position, request.content, request.lastChunk, translogOps.getAsInt(), ActionListener.runBefore(listener, request::close)); } @Override protected void handleError(StoreFileMetadata md, Exception e) throws Exception { handleErrorOnSendFiles(store, e, new StoreFileMetadata[]{md}); } @Override public void close() throws IOException { IOUtils.close(currentInput, () -> currentInput = null); } }; resources.add(multiFileSender); multiFileSender.start();
236
728
964
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/indices/recovery/StartRecoveryRequest.java
StartRecoveryRequest
writeTo
class StartRecoveryRequest extends TransportRequest { private final long recoveryId; private final ShardId shardId; private final String targetAllocationId; private final DiscoveryNode sourceNode; private final DiscoveryNode targetNode; private final Store.MetadataSnapshot metadataSnapshot; private final boolean primaryRelocation; private final long startingSeqNo; /** * Construct a request for starting a peer recovery. * * @param shardId the shard ID to recover * @param targetAllocationId the allocation id of the target shard * @param sourceNode the source node to remover from * @param targetNode the target node to recover to * @param metadataSnapshot the Lucene metadata * @param primaryRelocation whether or not the recovery is a primary relocation * @param recoveryId the recovery ID * @param startingSeqNo the starting sequence number */ public StartRecoveryRequest(final ShardId shardId, final String targetAllocationId, final DiscoveryNode sourceNode, final DiscoveryNode targetNode, final Store.MetadataSnapshot metadataSnapshot, final boolean primaryRelocation, final long recoveryId, final long startingSeqNo) { this.recoveryId = recoveryId; this.shardId = shardId; this.targetAllocationId = targetAllocationId; this.sourceNode = sourceNode; this.targetNode = targetNode; this.metadataSnapshot = metadataSnapshot; this.primaryRelocation = primaryRelocation; this.startingSeqNo = startingSeqNo; assert startingSeqNo == SequenceNumbers.UNASSIGNED_SEQ_NO || metadataSnapshot.getHistoryUUID() != null : "starting seq no is set but not history uuid"; } public long recoveryId() { return this.recoveryId; } public ShardId shardId() { return shardId; } public String targetAllocationId() { return targetAllocationId; } public DiscoveryNode sourceNode() { return sourceNode; } public DiscoveryNode targetNode() { return targetNode; } public boolean isPrimaryRelocation() { return primaryRelocation; } public Store.MetadataSnapshot metadataSnapshot() { return metadataSnapshot; } public long startingSeqNo() { return startingSeqNo; } public StartRecoveryRequest(StreamInput in) throws IOException { super(in); recoveryId = in.readLong(); shardId = new ShardId(in); targetAllocationId = in.readString(); sourceNode = new DiscoveryNode(in); targetNode = new DiscoveryNode(in); metadataSnapshot = new Store.MetadataSnapshot(in); primaryRelocation = in.readBoolean(); startingSeqNo = in.readLong(); } @Override public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>} }
super.writeTo(out); out.writeLong(recoveryId); shardId.writeTo(out); out.writeString(targetAllocationId); sourceNode.writeTo(out); targetNode.writeTo(out); metadataSnapshot.writeTo(out); out.writeBoolean(primaryRelocation); out.writeLong(startingSeqNo);
777
100
877
<methods>public void <init>() ,public void <init>(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public org.elasticsearch.tasks.TaskId getParentTask() ,public void setParentTask(org.elasticsearch.tasks.TaskId) ,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>private org.elasticsearch.tasks.TaskId parentTaskId
crate_crate
crate/server/src/main/java/org/elasticsearch/monitor/fs/FsHealthService.java
FsHealthMonitor
monitorFSHealth
class FsHealthMonitor implements Runnable { static final String TEMP_FILE_NAME = ".es_temp_file"; private byte[] byteToWrite; FsHealthMonitor() { this.byteToWrite = UUIDs.randomBase64UUID().getBytes(StandardCharsets.UTF_8); } @Override public void run() { try { if (enabled) { monitorFSHealth(); LOGGER.debug("health check succeeded"); } } catch (Exception e) { LOGGER.error("health check failed", e); } } private void monitorFSHealth() {<FILL_FUNCTION_BODY>} }
Set<Path> currentUnhealthyPaths = null; for (Path path : nodeEnv.nodeDataPaths()) { long executionStartTime = currentTimeMillisSupplier.getAsLong(); try { if (Files.exists(path)) { Path tempDataPath = path.resolve(TEMP_FILE_NAME); Files.deleteIfExists(tempDataPath); try (OutputStream os = Files.newOutputStream(tempDataPath, StandardOpenOption.CREATE_NEW)) { os.write(byteToWrite); IOUtils.fsync(tempDataPath, false); } Files.delete(tempDataPath); final long elapsedTime = currentTimeMillisSupplier.getAsLong() - executionStartTime; if (elapsedTime > slowPathLoggingThreshold.millis()) { LOGGER.warn("health check of [{}] took [{}ms] which is above the warn threshold of [{}]", path, elapsedTime, slowPathLoggingThreshold); } } } catch (Exception ex) { LOGGER.error(new ParameterizedMessage("health check of [{}] failed", path), ex); if (currentUnhealthyPaths == null) { currentUnhealthyPaths = new HashSet<>(1); } currentUnhealthyPaths.add(path); } } unhealthyPaths = currentUnhealthyPaths;
176
353
529
<methods>public void addLifecycleListener(org.elasticsearch.common.component.LifecycleListener) ,public void close() ,public org.elasticsearch.common.component.Lifecycle.State lifecycleState() ,public void removeLifecycleListener(org.elasticsearch.common.component.LifecycleListener) ,public void start() ,public void stop() <variables>protected final org.elasticsearch.common.component.Lifecycle lifecycle,private final List<org.elasticsearch.common.component.LifecycleListener> listeners
crate_crate
crate/server/src/main/java/org/elasticsearch/monitor/jvm/JvmGcMonitorService.java
GcThreshold
doStart
class GcThreshold { public final String name; public final long warnThreshold; public final long infoThreshold; public final long debugThreshold; GcThreshold(String name, long warnThreshold, long infoThreshold, long debugThreshold) { this.name = name; this.warnThreshold = warnThreshold; this.infoThreshold = infoThreshold; this.debugThreshold = debugThreshold; } @Override public String toString() { return "GcThreshold{" + "name='" + name + '\'' + ", warnThreshold=" + warnThreshold + ", infoThreshold=" + infoThreshold + ", debugThreshold=" + debugThreshold + '}'; } } public JvmGcMonitorService(Settings settings, ThreadPool threadPool) { this.threadPool = threadPool; this.enabled = ENABLED_SETTING.get(settings); this.interval = REFRESH_INTERVAL_SETTING.get(settings); Map<String, GcThreshold> gcThresholds = new HashMap<>(); Map<String, Settings> gcThresholdGroups = GC_SETTING.get(settings).getAsGroups(); for (Map.Entry<String, Settings> entry : gcThresholdGroups.entrySet()) { String name = entry.getKey(); TimeValue warn = getValidThreshold(entry.getValue(), entry.getKey(), "warn"); TimeValue info = getValidThreshold(entry.getValue(), entry.getKey(), "info"); TimeValue debug = getValidThreshold(entry.getValue(), entry.getKey(), "debug"); gcThresholds.put(name, new GcThreshold(name, warn.millis(), info.millis(), debug.millis())); } gcThresholds.putIfAbsent(GcNames.YOUNG, new GcThreshold(GcNames.YOUNG, 1000, 700, 400)); gcThresholds.putIfAbsent(GcNames.OLD, new GcThreshold(GcNames.OLD, 10000, 5000, 2000)); gcThresholds.putIfAbsent("default", new GcThreshold("default", 10000, 5000, 2000)); this.gcThresholds = unmodifiableMap(gcThresholds); if (GC_OVERHEAD_WARN_SETTING.get(settings) <= GC_OVERHEAD_INFO_SETTING.get(settings)) { final String message = String.format( Locale.ROOT, "[%s] must be greater than [%s] [%d] but was [%d]", GC_OVERHEAD_WARN_SETTING.getKey(), GC_OVERHEAD_INFO_SETTING.getKey(), GC_OVERHEAD_INFO_SETTING.get(settings), GC_OVERHEAD_WARN_SETTING.get(settings)); throw new IllegalArgumentException(message); } if (GC_OVERHEAD_INFO_SETTING.get(settings) <= GC_OVERHEAD_DEBUG_SETTING.get(settings)) { final String message = String.format( Locale.ROOT, "[%s] must be greater than [%s] [%d] but was [%d]", GC_OVERHEAD_INFO_SETTING.getKey(), GC_OVERHEAD_DEBUG_SETTING.getKey(), GC_OVERHEAD_DEBUG_SETTING.get(settings), GC_OVERHEAD_INFO_SETTING.get(settings)); throw new IllegalArgumentException(message); } this.gcOverheadThreshold = new GcOverheadThreshold( GC_OVERHEAD_WARN_SETTING.get(settings), GC_OVERHEAD_INFO_SETTING.get(settings), GC_OVERHEAD_DEBUG_SETTING.get(settings)); LOGGER.debug( "enabled [{}], interval [{}], gc_threshold [{}], overhead [{}, {}, {}]", this.enabled, this.interval, this.gcThresholds, this.gcOverheadThreshold.warnThreshold, this.gcOverheadThreshold.infoThreshold, this.gcOverheadThreshold.debugThreshold); } private static TimeValue getValidThreshold(Settings settings, String key, String level) { final TimeValue threshold; try { threshold = settings.getAsTime(level, null); } catch (RuntimeException ex) { final String settingValue = settings.get(level); throw new IllegalArgumentException("failed to parse setting [" + getThresholdName(key, level) + "] with value [" + settingValue + "] as a time value", ex); } if (threshold == null) { throw new IllegalArgumentException("missing gc_threshold for [" + getThresholdName(key, level) + "]"); } return threshold; } private static String getThresholdName(String key, String level) { return GC_COLLECTOR_PREFIX + key + "." + level; } @Override protected void doStart() {<FILL_FUNCTION_BODY>
if (!enabled) { return; } scheduledFuture = threadPool.scheduleWithFixedDelay(new JvmMonitor(gcThresholds, gcOverheadThreshold) { @Override void onMonitorFailure(Exception e) { LOGGER.debug("failed to monitor", e); } @Override void onSlowGc(final Threshold threshold, final long seq, final SlowGcEvent slowGcEvent) { logSlowGc(LOGGER, threshold, seq, slowGcEvent, JvmGcMonitorService::buildPools); } @Override void onGcOverhead(final Threshold threshold, final long current, final long elapsed, final long seq) { logGcOverhead(LOGGER, threshold, current, elapsed, seq); } }, interval, Names.SAME);
1,377
220
1,597
<methods>public void addLifecycleListener(org.elasticsearch.common.component.LifecycleListener) ,public void close() ,public org.elasticsearch.common.component.Lifecycle.State lifecycleState() ,public void removeLifecycleListener(org.elasticsearch.common.component.LifecycleListener) ,public void start() ,public void stop() <variables>protected final org.elasticsearch.common.component.Lifecycle lifecycle,private final List<org.elasticsearch.common.component.LifecycleListener> listeners
crate_crate
crate/server/src/main/java/org/elasticsearch/monitor/jvm/JvmService.java
JvmService
stats
class JvmService { private static final Logger LOGGER = LogManager.getLogger(JvmService.class); private final JvmInfo jvmInfo; private final TimeValue refreshInterval; private JvmStats jvmStats; public static final Setting<TimeValue> REFRESH_INTERVAL_SETTING = Setting.timeSetting("monitor.jvm.refresh_interval", TimeValue.timeValueSeconds(1), TimeValue.timeValueSeconds(1), Property.NodeScope); public JvmService(Settings settings) { this.jvmInfo = JvmInfo.jvmInfo(); this.jvmStats = JvmStats.jvmStats(); this.refreshInterval = REFRESH_INTERVAL_SETTING.get(settings); LOGGER.debug("using refresh_interval [{}]", refreshInterval); } public JvmInfo info() { return this.jvmInfo; } public synchronized JvmStats stats() {<FILL_FUNCTION_BODY>} }
if ((System.currentTimeMillis() - jvmStats.getTimestamp()) > refreshInterval.millis()) { jvmStats = JvmStats.jvmStats(); } return jvmStats;
268
54
322
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/monitor/os/OsStats.java
Cpu
writeTo
class Cpu implements Writeable { private final short percent; private final double[] loadAverage; public Cpu(short systemCpuPercent, double[] systemLoadAverage) { this.percent = systemCpuPercent; this.loadAverage = systemLoadAverage; } public Cpu(StreamInput in) throws IOException { this.percent = in.readShort(); if (in.readBoolean()) { this.loadAverage = in.readDoubleArray(); } else { this.loadAverage = null; } } @Override public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>} public short getPercent() { return percent; } public double[] getLoadAverage() { return loadAverage; } }
out.writeShort(percent); if (loadAverage == null) { out.writeBoolean(false); } else { out.writeBoolean(true); out.writeDoubleArray(loadAverage); }
220
61
281
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/monitor/process/ProcessProbe.java
ProcessProbeHolder
getUnixMethod
class ProcessProbeHolder { private static final ProcessProbe INSTANCE = new ProcessProbe(); } public static ProcessProbe getInstance() { return ProcessProbeHolder.INSTANCE; } private ProcessProbe() { } /** * Returns the maximum number of file descriptors allowed on the system, or -1 if not supported. */ public long getMaxFileDescriptorCount() { if (GET_MAX_FILE_DESCRIPTOR_COUNT_FIELD == null) { return -1; } try { return (Long) GET_MAX_FILE_DESCRIPTOR_COUNT_FIELD.invoke(OS_MX_BEAN); } catch (Exception t) { return -1; } } /** * Returns the number of opened file descriptors associated with the current process, or -1 if not supported. */ public long getOpenFileDescriptorCount() { if (GET_OPEN_FILE_DESCRIPTOR_COUNT_FIELD == null) { return -1; } try { return (Long) GET_OPEN_FILE_DESCRIPTOR_COUNT_FIELD.invoke(OS_MX_BEAN); } catch (Exception t) { return -1; } } /** * Returns the process CPU usage in percent */ public short getProcessCpuPercent() { return Probes.getLoadAndScaleToPercent(GET_PROCESS_CPU_LOAD, OS_MX_BEAN); } /** * Returns the CPU time (in milliseconds) used by the process on which the Java virtual machine is running, or -1 if not supported. */ public long getProcessCpuTotalTime() { if (GET_PROCESS_CPU_TIME != null) { try { long time = (long) GET_PROCESS_CPU_TIME.invoke(OS_MX_BEAN); if (time >= 0) { return (time / 1_000_000L); } } catch (Exception t) { return -1; } } return -1; } /** * Returns the size (in bytes) of virtual memory that is guaranteed to be available to the running process */ public long getTotalVirtualMemorySize() { if (GET_COMMITTED_VIRTUAL_MEMORY_SIZE != null) { try { long virtual = (long) GET_COMMITTED_VIRTUAL_MEMORY_SIZE.invoke(OS_MX_BEAN); if (virtual >= 0) { return virtual; } } catch (Exception t) { return -1; } } return -1; } public ProcessInfo processInfo(long refreshInterval) { return new ProcessInfo(jvmInfo().pid(), BootstrapInfo.isMemoryLocked(), refreshInterval); } public ProcessStats processStats() { ProcessStats.Cpu cpu = new ProcessStats.Cpu(getProcessCpuPercent(), getProcessCpuTotalTime()); ProcessStats.Mem mem = new ProcessStats.Mem(getTotalVirtualMemorySize()); return new ProcessStats(System.currentTimeMillis(), getOpenFileDescriptorCount(), getMaxFileDescriptorCount(), cpu, mem); } /** * Returns a given method of the OperatingSystemMXBean, * or null if the method is not found or unavailable. */ private static Method getMethod(String methodName) { try { return Class.forName("com.sun.management.OperatingSystemMXBean").getMethod(methodName); } catch (Exception t) { // not available return null; } } /** * Returns a given method of the UnixOperatingSystemMXBean, * or null if the method is not found or unavailable. */ private static Method getUnixMethod(String methodName) {<FILL_FUNCTION_BODY>
try { return Class.forName("com.sun.management.UnixOperatingSystemMXBean").getMethod(methodName); } catch (Exception t) { // not available return null; }
1,007
58
1,065
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/node/InternalSettingsPreparer.java
InternalSettingsPreparer
prepareEnvironment
class InternalSettingsPreparer { private InternalSettingsPreparer() {} /** * Prepares the settings by gathering all elasticsearch system properties, optionally loading the configuration settings. * * @param input the custom settings to use; these are not overwritten by settings in the configuration file * @param properties map of properties key/value pairs (usually from the command-line) * @param configPath path to config directory; (use null to indicate the default) * @param defaultNodeName supplier for the default node.name if the setting isn't defined * @return the {@link Environment} */ public static Environment prepareEnvironment(Settings input, Map<String, String> properties, Path configPath, Supplier<String> defaultNodeName) {<FILL_FUNCTION_BODY>} /** * Initializes the builder with the given input settings, and applies settings from the specified map (these settings typically come * from the command line). * * @param output the settings builder to apply the input and default settings to * @param input the input settings * @param esSettings a map from which to apply settings */ static void initializeSettings(final Settings.Builder output, final Settings input, final Map<String, String> esSettings) { output.put(input); output.putProperties(esSettings, UnaryOperator.identity()); output.replacePropertyPlaceholders(); } /** * Finish preparing settings by replacing forced settings and any defaults that need to be added. */ private static void finalizeSettings(Settings.Builder output, Supplier<String> defaultNodeName) { // allow to force set properties based on configuration of the settings provided List<String> forcedSettings = new ArrayList<>(); for (String setting : output.keys()) { if (setting.startsWith("force.")) { forcedSettings.add(setting); } } for (String forcedSetting : forcedSettings) { String value = output.remove(forcedSetting); output.put(forcedSetting.substring("force.".length()), value); } output.replacePropertyPlaceholders(); // put the cluster and node name if they aren't set if (output.get(ClusterName.CLUSTER_NAME_SETTING.getKey()) == null) { output.put(ClusterName.CLUSTER_NAME_SETTING.getKey(), ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY).value()); } if (output.get(Node.NODE_NAME_SETTING.getKey()) == null) { output.put(Node.NODE_NAME_SETTING.getKey(), defaultNodeName.get()); } } }
// just create enough settings to build the environment, to get the config dir Settings.Builder output = Settings.builder(); initializeSettings(output, input, properties); Environment environment = new Environment(output.build(), configPath); output = Settings.builder(); // start with a fresh output Path path = environment.configFile().resolve("crate.yml"); if (Files.exists(path)) { try { output.loadFromPath(path); } catch (IOException e) { throw new SettingsException("Failed to load settings from " + path.toString(), e); } } // re-initialize settings now that the config file has been loaded initializeSettings(output, input, properties); finalizeSettings(output, defaultNodeName); environment = new Environment(output.build(), configPath); // we put back the path.logs so we can use it in the logging configuration file output.put(Environment.PATH_LOGS_SETTING.getKey(), environment.logsFile().toAbsolutePath().normalize().toString()); return new Environment(output.build(), configPath);
676
276
952
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/node/NodeNames.java
NodeNames
nodeNames
class NodeNames { public static String randomNodeName() { List<String> names = nodeNames(); int index = ThreadLocalRandom.current().nextInt(names.size()); return names.get(index); } static List<String> nodeNames() {<FILL_FUNCTION_BODY>} }
InputStream input = NodeNames.class.getResourceAsStream("/config/names.txt"); try { List<String> names = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) { String line = reader.readLine(); while (line != null) { String[] fields = line.split("\t"); if (fields.length == 0) { throw new RuntimeException("Failed to parse the names.txt. Malformed record: " + line); } names.add(fields[0]); line = reader.readLine(); } } return names; } catch (IOException e) { throw new RuntimeException("Could not read node names list", e); } finally { IOUtils.closeWhileHandlingException(input); }
83
216
299
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/plugins/PluginInfo.java
PluginInfo
readFromProperties
class PluginInfo { public static final String ES_PLUGIN_PROPERTIES = "plugin-descriptor.properties"; private final String name; private final String description; private final String classname; /** * Construct plugin info. * * @param name the name of the plugin * @param description a description of the plugin * @param classname the entry point to the plugin * @param extendedPlugins other plugins this plugin extends through SPI */ public PluginInfo(String name, String description, String classname, List<String> extendedPlugins) { this.name = name; this.description = description; this.classname = classname; } /** * Reads the plugin descriptor file. * * @param path the path to the root directory for the plugin * @return the plugin info * @throws IOException if an I/O exception occurred reading the plugin descriptor */ public static PluginInfo readFromProperties(final Path path) throws IOException {<FILL_FUNCTION_BODY>} /** * The name of the plugin. * * @return the plugin name */ public String getName() { return name; } /** * The description of the plugin. * * @return the plugin description */ public String getDescription() { return description; } /** * The entry point to the plugin. * * @return the entry point to the plugin */ public String getClassname() { return classname; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PluginInfo that = (PluginInfo) o; return name.equals(that.name); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return toString(""); } public String toString(String prefix) { final StringBuilder information = new StringBuilder() .append(prefix).append("- Plugin information:\n") .append(prefix).append("Name: ").append(name).append("\n") .append(prefix).append("Description: ").append(description).append("\n") .append(prefix).append(" * Classname: ").append(classname); return information.toString(); } }
final Path descriptor = path.resolve(ES_PLUGIN_PROPERTIES); final Map<String, String> propsMap; { final Properties props = new Properties(); try (InputStream stream = Files.newInputStream(descriptor)) { props.load(stream); } propsMap = props.stringPropertyNames().stream().collect(Collectors.toMap(Function.identity(), props::getProperty)); } final String name = propsMap.remove("name"); if (name == null || name.isEmpty()) { throw new IllegalArgumentException( "property [name] is missing in [" + descriptor + "]"); } final String description = propsMap.remove("description"); if (description == null) { throw new IllegalArgumentException( "property [description] is missing for plugin [" + name + "]"); } final String classname = propsMap.remove("classname"); if (classname == null) { throw new IllegalArgumentException( "property [classname] is missing for plugin [" + name + "]"); } final String extendedString = propsMap.remove("extended.plugins"); final List<String> extendedPlugins; if (extendedString == null) { extendedPlugins = Collections.emptyList(); } else { extendedPlugins = Arrays.asList(Strings.delimitedListToStringArray(extendedString, ",")); } if (propsMap.isEmpty() == false) { throw new IllegalArgumentException("Unknown properties in plugin descriptor: " + propsMap.keySet()); } return new PluginInfo( name, description, classname, extendedPlugins );
650
427
1,077
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/repositories/IndexId.java
IndexId
equals
class IndexId implements Writeable, ToXContentObject { protected static final String NAME = "name"; protected static final String ID = "id"; private final String name; private final String id; private final int hashCode; public IndexId(final String name, final String id) { this.name = name; this.id = id; this.hashCode = computeHashCode(); } public IndexId(final StreamInput in) throws IOException { this.name = in.readString(); this.id = in.readString(); this.hashCode = computeHashCode(); } /** * The name of the index. */ public String getName() { return name; } /** * The unique ID for the index within the repository. This is *not* the same as the * index's UUID, but merely a unique file/URL friendly identifier that a repository can * use to name blobs for the index. * * We could not use the index's actual UUID (See {@link Index#getUUID()}) because in the * case of snapshot/restore, the index UUID in the snapshotted index will be different * from the index UUID assigned to it when it is restored. Hence, the actual index UUID * is not useful in the context of snapshot/restore for tying a snapshotted index to the * index it was snapshot from, and so we are using a separate UUID here. */ public String getId() { return id; } @Override public String toString() { return "[" + name + "/" + id + "]"; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return hashCode; } private int computeHashCode() { return Objects.hash(name, id); } @Override public void writeTo(final StreamOutput out) throws IOException { out.writeString(name); out.writeString(id); } @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); builder.field(NAME, name); builder.field(ID, id); builder.endObject(); return builder; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IndexId that = (IndexId) o; return Objects.equals(name, that.name) && Objects.equals(id, that.id);
603
85
688
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/repositories/RepositoriesModule.java
RepositoriesModule
create
class RepositoriesModule extends AbstractModule { private final RepositoriesService repositoriesService; public RepositoriesModule(Environment env, List<RepositoryPlugin> repoPlugins, TransportService transportService, ClusterService clusterService, LogicalReplicationService logicalReplicationService, RemoteClusters remoteClusters, ThreadPool threadPool, NamedXContentRegistry namedXContentRegistry, LogicalReplicationSettings replicationSettings, RecoverySettings recoverySettings) { Map<String, Repository.Factory> factories = new HashMap<>(); factories.put(FsRepository.TYPE, new Repository.Factory() { @Override public TypeSettings settings() { return new TypeSettings(FsRepository.mandatorySettings(), FsRepository.optionalSettings()); } @Override public Repository create(RepositoryMetadata metadata) throws Exception { return new FsRepository(metadata, env, namedXContentRegistry, clusterService, recoverySettings); } }); factories.put( LogicalReplicationRepository.TYPE, new Repository.Factory() { @Override public Repository create(RepositoryMetadata metadata) throws Exception {<FILL_FUNCTION_BODY>} @Override public TypeSettings settings() { return new TypeSettings(List.of(), List.of()); } } ); for (RepositoryPlugin repoPlugin : repoPlugins) { Map<String, Repository.Factory> newRepoTypes = repoPlugin.getRepositories(env, namedXContentRegistry, clusterService, recoverySettings); for (Map.Entry<String, Repository.Factory> entry : newRepoTypes.entrySet()) { if (factories.put(entry.getKey(), entry.getValue()) != null) { throw new IllegalArgumentException("Repository type [" + entry.getKey() + "] is already registered"); } } } Map<String, Repository.Factory> repositoryTypes = Collections.unmodifiableMap(factories); repositoriesService = new RepositoriesService(env.settings(), clusterService, transportService, repositoryTypes, threadPool); } @Override protected void configure() { Map<String, Repository.Factory> repositoryTypes = repositoriesService.typesRegistry(); MapBinder<String, Repository.Factory> typesBinder = MapBinder.newMapBinder(binder(), String.class, Repository.Factory.class); repositoryTypes.forEach((k, v) -> typesBinder.addBinding(k).toInstance(v)); MapBinder<String, TypeSettings> typeSettingsBinder = MapBinder.newMapBinder( binder(), String.class, TypeSettings.class); for (var e : repositoryTypes.entrySet()) { String repoScheme = e.getKey(); var repoSettings = e.getValue().settings(); typeSettingsBinder.addBinding(repoScheme).toInstance(repoSettings); } } public RepositoriesService repositoryService() { return repositoriesService; } }
return new LogicalReplicationRepository( clusterService, logicalReplicationService, remoteClusters, metadata, threadPool, replicationSettings);
771
46
817
<methods>public non-sealed void <init>() ,public final synchronized void configure(org.elasticsearch.common.inject.Binder) <variables>org.elasticsearch.common.inject.Binder binder
crate_crate
crate/server/src/main/java/org/elasticsearch/search/profile/AbstractInternalProfileTree.java
AbstractInternalProfileTree
getProfileBreakdown
class AbstractInternalProfileTree<PB extends AbstractProfileBreakdown<?>, E> { protected ArrayList<PB> timings; /** Maps the Query to it's list of children. This is basically the dependency tree */ protected ArrayList<ArrayList<Integer>> tree; /** A list of the original queries, keyed by index position */ protected ArrayList<E> elements; /** A list of top-level "roots". Each root can have its own tree of profiles */ protected ArrayList<Integer> roots; /** A temporary stack used to record where we are in the dependency tree. */ protected Deque<Integer> stack; private int currentToken = 0; public AbstractInternalProfileTree() { timings = new ArrayList<>(10); stack = new ArrayDeque<>(10); tree = new ArrayList<>(10); elements = new ArrayList<>(10); roots = new ArrayList<>(10); } /** * Returns a {@link QueryProfileBreakdown} for a scoring query. Scoring queries (e.g. those * that are past the rewrite phase and are now being wrapped by createWeight() ) follow * a recursive progression. We can track the dependency tree by a simple stack * * The only hiccup is that the first scoring query will be identical to the last rewritten * query, so we need to take special care to fix that * * @param query The scoring query we wish to profile * @return A ProfileBreakdown for this query */ public PB getProfileBreakdown(E query) {<FILL_FUNCTION_BODY>} /** * Helper method to add a new node to the dependency tree. * * Initializes a new list in the dependency tree, saves the query and * generates a new {@link QueryProfileBreakdown} to track the timings of * this query * * @param element * The element to profile * @param token * The assigned token for this element * @return A ProfileBreakdown to profile this element */ private PB addDependencyNode(E element, int token) { // Add a new slot in the dependency tree tree.add(new ArrayList<>(5)); // Save our query for lookup later elements.add(element); PB queryTimings = createProfileBreakdown(); timings.add(token, queryTimings); return queryTimings; } protected abstract PB createProfileBreakdown(); /** * Removes the last (e.g. most recent) value on the stack */ public void pollLast() { stack.pollLast(); } /** * After the query has been run and profiled, we need to merge the flat timing map * with the dependency graph to build a data structure that mirrors the original * query tree * * @return a hierarchical representation of the profiled query tree */ public List<ProfileResult> getTree() { ArrayList<ProfileResult> results = new ArrayList<>(5); for (Integer root : roots) { results.add(doGetTree(root)); } return results; } /** * Recursive helper to finalize a node in the dependency tree * @param token The node we are currently finalizing * @return A hierarchical representation of the tree inclusive of children at this level */ private ProfileResult doGetTree(int token) { E element = elements.get(token); PB breakdown = timings.get(token); Map<String, Long> timings = breakdown.toTimingMap(); List<Integer> children = tree.get(token); List<ProfileResult> childrenProfileResults = Collections.emptyList(); if (children != null) { childrenProfileResults = new ArrayList<>(children.size()); for (Integer child : children) { ProfileResult childNode = doGetTree(child); childrenProfileResults.add(childNode); } } // TODO this would be better done bottom-up instead of top-down to avoid // calculating the same times over and over...but worth the effort? String type = getTypeFromElement(element); String description = getDescriptionFromElement(element); return new ProfileResult(type, description, timings, childrenProfileResults); } protected abstract String getTypeFromElement(E element); protected abstract String getDescriptionFromElement(E element); /** * Internal helper to add a child to the current parent node * * @param childToken The child to add to the current parent */ private void updateParent(int childToken) { Integer parent = stack.peekLast(); ArrayList<Integer> parentNode = tree.get(parent); parentNode.add(childToken); tree.set(parent, parentNode); } }
int token = currentToken; boolean stackEmpty = stack.isEmpty(); // If the stack is empty, we are a new root query if (stackEmpty) { // We couldn't find a rewritten query to attach to, so just add it as a // top-level root. This is just a precaution: it really shouldn't happen. // We would only get here if a top-level query that never rewrites for some reason. roots.add(token); // Increment the token since we are adding a new node, but notably, do not // updateParent() because this was added as a root currentToken += 1; stack.add(token); return addDependencyNode(query, token); } updateParent(token); // Increment the token since we are adding a new node currentToken += 1; stack.add(token); return addDependencyNode(query, token);
1,217
238
1,455
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/search/profile/query/ProfileWeight.java
ProfileWeight
scorerSupplier
class ProfileWeight extends Weight { private final Weight subQueryWeight; private final QueryProfileBreakdown profile; public ProfileWeight(Query query, Weight subQueryWeight, QueryProfileBreakdown profile) throws IOException { super(query); this.subQueryWeight = subQueryWeight; this.profile = profile; } @Override public Scorer scorer(LeafReaderContext context) throws IOException { ScorerSupplier supplier = scorerSupplier(context); if (supplier == null) { return null; } return supplier.get(Long.MAX_VALUE); } @Override public ScorerSupplier scorerSupplier(LeafReaderContext context) throws IOException {<FILL_FUNCTION_BODY>} @Override public BulkScorer bulkScorer(LeafReaderContext context) throws IOException { // We use the default bulk scorer instead of the specialized one. The reason // is that Lucene's BulkScorers do everything at once: finding matches, // scoring them and calling the collector, so they make it impossible to // see where time is spent, which is the purpose of query profiling. // The default bulk scorer will pull a scorer and iterate over matches, // this might be a significantly different execution path for some queries // like disjunctions, but in general this is what is done anyway return super.bulkScorer(context); } @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { return subQueryWeight.explain(context, doc); } @Override public boolean isCacheable(LeafReaderContext ctx) { return subQueryWeight.isCacheable(ctx); } }
Timer timer = profile.getTimer(QueryTimingType.BUILD_SCORER); timer.start(); final ScorerSupplier subQueryScorerSupplier; try { subQueryScorerSupplier = subQueryWeight.scorerSupplier(context); } finally { timer.stop(); } if (subQueryScorerSupplier == null) { return null; } final ProfileWeight weight = this; return new ScorerSupplier() { @Override public Scorer get(long loadCost) throws IOException { timer.start(); try { return new ProfileScorer(weight, subQueryScorerSupplier.get(loadCost), profile); } finally { timer.stop(); } } @Override public long cost() { timer.start(); try { return subQueryScorerSupplier.cost(); } finally { timer.stop(); } } };
434
250
684
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/snapshots/InFlightShardSnapshotStates.java
InFlightShardSnapshotStates
generationForShard
class InFlightShardSnapshotStates { /** * Compute information about all shard ids that currently have in-flight state for the given repository. * * @param repoName repository name * @param snapshots snapshots in progress * @return in flight shard states for all snapshot operation running for the given repository name */ public static InFlightShardSnapshotStates forRepo(String repoName, List<SnapshotsInProgress.Entry> snapshots) { final Map<String, Map<Integer, String>> generations = new HashMap<>(); final Map<String, Set<Integer>> busyIds = new HashMap<>(); for (SnapshotsInProgress.Entry runningSnapshot : snapshots) { if (runningSnapshot.repository().equals(repoName) == false) { continue; } for (ObjectObjectCursor<ShardId, SnapshotsInProgress.ShardSnapshotStatus> shard : runningSnapshot.shards()) { final ShardId sid = shard.key; addStateInformation(generations, busyIds, shard.value, sid.id(), sid.getIndexName()); } } return new InFlightShardSnapshotStates(generations, busyIds); } private static void addStateInformation(Map<String, Map<Integer, String>> generations, Map<String, Set<Integer>> busyIds, SnapshotsInProgress.ShardSnapshotStatus shardState, int shardId, String indexName) { if (shardState.isActive()) { busyIds.computeIfAbsent(indexName, k -> new HashSet<>()).add(shardId); assert assertGenerationConsistency(generations, indexName, shardId, shardState.generation()); } else if (shardState.state() == SnapshotsInProgress.ShardState.SUCCESS) { assert busyIds.getOrDefault(indexName, Collections.emptySet()).contains(shardId) == false : "Can't have a successful operation queued after an in-progress operation"; generations.computeIfAbsent(indexName, k -> new HashMap<>()).put(shardId, shardState.generation()); } } /** * Map that maps index name to a nested map of shard id to most recent successful shard generation for that * shard id. */ private final Map<String, Map<Integer, String>> generations; /** * Map of index name to a set of shard ids that currently are actively executing an operation on the repository. */ private final Map<String, Set<Integer>> activeShardIds; private InFlightShardSnapshotStates(Map<String, Map<Integer, String>> generations, Map<String, Set<Integer>> activeShardIds) { this.generations = generations; this.activeShardIds = activeShardIds; } private static boolean assertGenerationConsistency(Map<String, Map<Integer, String>> generations, String indexName, int shardId, @Nullable String activeGeneration) { final String bestGeneration = generations.getOrDefault(indexName, Collections.emptyMap()).get(shardId); assert bestGeneration == null || activeGeneration == null || activeGeneration.equals(bestGeneration); return true; } /** * Check if a given shard currently has an actively executing shard operation. * * @param indexName name of the shard's index * @param shardId shard id of the shard * @return true if shard has an actively executing shard operation */ boolean isActive(String indexName, int shardId) { return activeShardIds.getOrDefault(indexName, Collections.emptySet()).contains(shardId); } /** * Determine the current generation for a shard by first checking if any in-flight but successful new shard * snapshots or clones have set a relevant generation and then falling back to {@link ShardGenerations#getShardGen} * if not. * * @param indexId index id of the shard * @param shardId shard id of the shard * @param shardGenerations current shard generations in the repository data * @return most recent shard generation for the given shard */ @Nullable String generationForShard(IndexId indexId, int shardId, ShardGenerations shardGenerations) {<FILL_FUNCTION_BODY>} }
final String inFlightBest = generations.getOrDefault(indexId.getName(), Collections.emptyMap()).get(shardId); if (inFlightBest != null) { return inFlightBest; } return shardGenerations.getShardGen(indexId, shardId);
1,120
79
1,199
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/snapshots/InternalSnapshotsInfoService.java
FetchingSnapshotShardSizeRunnable
invariant
class FetchingSnapshotShardSizeRunnable extends AbstractRunnable { private final SnapshotShard snapshotShard; private boolean removed; FetchingSnapshotShardSizeRunnable(SnapshotShard snapshotShard) { super(); this.snapshotShard = snapshotShard; this.removed = false; } @Override protected void doRun() throws Exception { final RepositoriesService repositories = repositoriesService.get(); assert repositories != null; final Repository repository = repositories.repository(snapshotShard.snapshot.getRepository()); LOGGER.debug("fetching snapshot shard size for {}", snapshotShard); repository.getShardSnapshotStatus( snapshotShard.snapshot().getSnapshotId(), snapshotShard.index(), snapshotShard.shardId()).thenAccept(shardSnapshotStatus -> { final long snapshotShardSize = shardSnapshotStatus == null ? 0 : shardSnapshotStatus.totalSize(); LOGGER.debug("snapshot shard size for {}: {} bytes", snapshotShard, snapshotShardSize); boolean updated = false; synchronized (mutex) { removed = unknownSnapshotShards.remove(snapshotShard); assert removed : "snapshot shard to remove does not exist " + snapshotShardSize; if (isMaster) { final ImmutableOpenMap.Builder<SnapshotShard, Long> newSnapshotShardSizes = ImmutableOpenMap.builder(knownSnapshotShards); updated = newSnapshotShardSizes.put(snapshotShard, snapshotShardSize) == null; assert updated : "snapshot shard size already exists for " + snapshotShard; knownSnapshotShards = newSnapshotShardSizes.build(); } activeFetches -= 1; assert invariant(); } if (updated) { rerouteService.get().reroute("snapshot shard size updated", Priority.HIGH, REROUTE_LISTENER); } }); } @Override public void onFailure(Exception e) { LOGGER.warn(() -> new ParameterizedMessage("failed to retrieve shard size for {}", snapshotShard), e); boolean failed = false; synchronized (mutex) { if (isMaster) { failed = failedSnapshotShards.add(snapshotShard); assert failed : "snapshot shard size already failed for " + snapshotShard; } if (removed == false) { unknownSnapshotShards.remove(snapshotShard); } activeFetches -= 1; assert invariant(); } if (failed) { rerouteService.get().reroute("snapshot shard size failed", Priority.HIGH, REROUTE_LISTENER); } } @Override public void onAfter() { fetchNextSnapshotShard(); } } private void cleanUpSnapshotShardSizes(Set<SnapshotShard> requiredSnapshotShards) { assert Thread.holdsLock(mutex); ImmutableOpenMap.Builder<SnapshotShard, Long> newSnapshotShardSizes = null; for (ObjectCursor<SnapshotShard> shard : knownSnapshotShards.keys()) { if (requiredSnapshotShards.contains(shard.value) == false) { if (newSnapshotShardSizes == null) { newSnapshotShardSizes = ImmutableOpenMap.builder(knownSnapshotShards); } newSnapshotShardSizes.remove(shard.value); } } if (newSnapshotShardSizes != null) { knownSnapshotShards = newSnapshotShardSizes.build(); } failedSnapshotShards.retainAll(requiredSnapshotShards); } private boolean invariant() {<FILL_FUNCTION_BODY>
assert Thread.holdsLock(mutex); assert activeFetches >= 0 : "active fetches should be greater than or equal to zero but got: " + activeFetches; assert activeFetches <= maxConcurrentFetches : activeFetches + " <= " + maxConcurrentFetches; for (ObjectCursor<SnapshotShard> cursor : knownSnapshotShards.keys()) { assert unknownSnapshotShards.contains(cursor.value) == false : "cannot be known and unknown at same time: " + cursor.value; assert failedSnapshotShards.contains(cursor.value) == false : "cannot be known and failed at same time: " + cursor.value; } for (SnapshotShard shard : unknownSnapshotShards) { assert knownSnapshotShards.keys().contains(shard) == false : "cannot be unknown and known at same time: " + shard; assert failedSnapshotShards.contains(shard) == false : "cannot be unknown and failed at same time: " + shard; } for (SnapshotShard shard : failedSnapshotShards) { assert knownSnapshotShards.keys().contains(shard) == false : "cannot be failed and known at same time: " + shard; assert unknownSnapshotShards.contains(shard) == false : "cannot be failed and unknown at same time: " + shard; } return true;
974
338
1,312
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/snapshots/RestoreInfo.java
Fields
equals
class Fields { static final String SNAPSHOT = "snapshot"; static final String INDICES = "indices"; static final String SHARDS = "shards"; static final String TOTAL = "total"; static final String FAILED = "failed"; static final String SUCCESSFUL = "successful"; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(Fields.SNAPSHOT, name); builder.startArray(Fields.INDICES); for (String index : indices) { builder.value(index); } builder.endArray(); builder.startObject(Fields.SHARDS); builder.field(Fields.TOTAL, totalShards); builder.field(Fields.FAILED, failedShards()); builder.field(Fields.SUCCESSFUL, successfulShards); builder.endObject(); builder.endObject(); return builder; } private static final ObjectParser<RestoreInfo, Void> PARSER = new ObjectParser<>(RestoreInfo.class.getName(), true, RestoreInfo::new); static { ObjectParser<RestoreInfo, Void> shardsParser = new ObjectParser<>("shards", true, null); shardsParser.declareInt((r, s) -> r.totalShards = s, new ParseField(Fields.TOTAL)); shardsParser.declareInt((r, s) -> { /* only consume, don't set */ }, new ParseField(Fields.FAILED)); shardsParser.declareInt((r, s) -> r.successfulShards = s, new ParseField(Fields.SUCCESSFUL)); PARSER.declareString((r, n) -> r.name = n, new ParseField(Fields.SNAPSHOT)); PARSER.declareStringArray((r, i) -> r.indices = i, new ParseField(Fields.INDICES)); PARSER.declareField(shardsParser::parse, new ParseField(Fields.SHARDS), ObjectParser.ValueType.OBJECT); } public static RestoreInfo fromXContent(XContentParser parser) throws IOException { return PARSER.parse(parser, null); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(name); out.writeStringCollection(indices); out.writeVInt(totalShards); out.writeVInt(successfulShards); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RestoreInfo that = (RestoreInfo) o; return totalShards == that.totalShards && successfulShards == that.successfulShards && Objects.equals(name, that.name) && Objects.equals(indices, that.indices);
675
104
779
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/snapshots/Snapshot.java
Snapshot
equals
class Snapshot implements Writeable { private final String repository; private final SnapshotId snapshotId; private final int hashCode; /** * Constructs a snapshot. */ public Snapshot(final String repository, final SnapshotId snapshotId) { this.repository = Objects.requireNonNull(repository); this.snapshotId = Objects.requireNonNull(snapshotId); this.hashCode = computeHashCode(); } /** * Constructs a snapshot from the stream input. */ public Snapshot(final StreamInput in) throws IOException { repository = in.readString(); snapshotId = new SnapshotId(in); hashCode = computeHashCode(); } /** * Gets the repository name for the snapshot. */ public String getRepository() { return repository; } /** * Gets the snapshot id for the snapshot. */ public SnapshotId getSnapshotId() { return snapshotId; } @Override public String toString() { return repository + ":" + snapshotId.toString(); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return hashCode; } private int computeHashCode() { return Objects.hash(repository, snapshotId); } @Override public void writeTo(final StreamOutput out) throws IOException { out.writeString(repository); snapshotId.writeTo(out); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Snapshot that = (Snapshot) o; return repository.equals(that.repository) && snapshotId.equals(that.snapshotId);
402
81
483
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/snapshots/SnapshotId.java
SnapshotId
equals
class SnapshotId implements Comparable<SnapshotId>, Writeable, ToXContentObject { private static final String NAME = "name"; private static final String UUID = "uuid"; private final String name; private final String uuid; // Caching hash code private final int hashCode; /** * Constructs a new snapshot * * @param name snapshot name * @param uuid snapshot uuid */ public SnapshotId(final String name, final String uuid) { this.name = Objects.requireNonNull(name); this.uuid = Objects.requireNonNull(uuid); this.hashCode = computeHashCode(); } /** * Constructs a new snapshot from a input stream * * @param in input stream */ public SnapshotId(final StreamInput in) throws IOException { name = in.readString(); uuid = in.readString(); hashCode = computeHashCode(); } /** * Returns snapshot name * * @return snapshot name */ public String getName() { return name; } /** * Returns the snapshot UUID * * @return snapshot uuid */ public String getUUID() { return uuid; } @Override public String toString() { return name + "/" + uuid; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return hashCode; } @Override public int compareTo(final SnapshotId other) { return this.name.compareTo(other.name); } private int computeHashCode() { return Objects.hash(name, uuid); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(name); out.writeString(uuid); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(NAME, name); builder.field(UUID, uuid); builder.endObject(); return builder; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final SnapshotId that = (SnapshotId) o; return name.equals(that.name) && uuid.equals(that.uuid);
584
82
666
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/snapshots/SnapshotShardSizeInfo.java
SnapshotShardSizeInfo
getShardSize
class SnapshotShardSizeInfo { public static final SnapshotShardSizeInfo EMPTY = new SnapshotShardSizeInfo(ImmutableOpenMap.of()); private final ImmutableOpenMap<InternalSnapshotsInfoService.SnapshotShard, Long> snapshotShardSizes; public SnapshotShardSizeInfo(ImmutableOpenMap<InternalSnapshotsInfoService.SnapshotShard, Long> snapshotShardSizes) { this.snapshotShardSizes = snapshotShardSizes; } public Long getShardSize(ShardRouting shardRouting) {<FILL_FUNCTION_BODY>} public long getShardSize(ShardRouting shardRouting, long fallback) { final Long shardSize = getShardSize(shardRouting); if (shardSize == null || shardSize == ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE) { return fallback; } return shardSize; } }
if (shardRouting.primary() && shardRouting.active() == false && shardRouting.recoverySource().getType() == RecoverySource.Type.SNAPSHOT) { final RecoverySource.SnapshotRecoverySource snapshotRecoverySource = (RecoverySource.SnapshotRecoverySource) shardRouting.recoverySource(); return snapshotShardSizes.get(new InternalSnapshotsInfoService.SnapshotShard( snapshotRecoverySource.snapshot(), snapshotRecoverySource.index(), shardRouting.shardId())); } assert false : "Expected shard with snapshot recovery source but was " + shardRouting; return null;
253
167
420
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/snapshots/SnapshotUtils.java
SnapshotUtils
filterIndices
class SnapshotUtils { /** * Filters out list of available indices based on the list of selected indices. * * @param availableIndices list of available indices * @param selectedIndices list of selected indices * @param indicesOptions ignore indices flag * @return filtered out indices */ public static List<String> filterIndices(List<String> availableIndices, List<String> selectedIndices, IndicesOptions indicesOptions) {<FILL_FUNCTION_BODY>} }
if (IndexNameExpressionResolver.isAllIndices(selectedIndices)) { return availableIndices; } Set<String> result = null; for (int i = 0; i < selectedIndices.size(); i++) { String indexOrPattern = selectedIndices.get(i); boolean add = true; if (!indexOrPattern.isEmpty()) { if (availableIndices.contains(indexOrPattern)) { if (result == null) { result = new HashSet<>(); } result.add(indexOrPattern); continue; } if (indexOrPattern.charAt(0) == '+') { add = true; indexOrPattern = indexOrPattern.substring(1); // if its the first, add empty set if (i == 0) { result = new HashSet<>(); } } else if (indexOrPattern.charAt(0) == '-') { // if its the first, fill it with all the indices... if (i == 0) { result = new HashSet<>(availableIndices); } add = false; indexOrPattern = indexOrPattern.substring(1); } } if (indexOrPattern.isEmpty() || !Regex.isSimpleMatchPattern(indexOrPattern)) { if (!availableIndices.contains(indexOrPattern)) { if (!indicesOptions.ignoreUnavailable()) { throw new IndexNotFoundException(indexOrPattern); } else { if (result == null) { // add all the previous ones... result = new HashSet<>(availableIndices.subList(0, i)); } } } else { if (result != null) { if (add) { result.add(indexOrPattern); } else { result.remove(indexOrPattern); } } } continue; } if (result == null) { // add all the previous ones... result = new HashSet<>(availableIndices.subList(0, i)); } boolean found = false; for (String index : availableIndices) { if (Regex.simpleMatch(indexOrPattern, index)) { found = true; if (add) { result.add(index); } else { result.remove(index); } } } if (!found && !indicesOptions.allowNoIndices()) { throw new IndexNotFoundException(indexOrPattern); } } if (result == null) { return Collections.unmodifiableList(new ArrayList<>(selectedIndices)); } return Collections.unmodifiableList(new ArrayList<>(result));
127
686
813
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/threadpool/FixedExecutorBuilder.java
FixedExecutorBuilder
formatInfo
class FixedExecutorBuilder extends ExecutorBuilder<FixedExecutorBuilder.FixedExecutorSettings> { private final Setting<Integer> sizeSetting; private final Setting<Integer> queueSizeSetting; /** * Construct a fixed executor builder; the settings will have the key prefix "thread_pool." followed by the executor name. * * @param settings the node-level settings * @param name the name of the executor * @param size the fixed number of threads * @param queueSize the size of the backing queue, -1 for unbounded */ FixedExecutorBuilder(final Settings settings, final String name, final int size, final int queueSize) { this(settings, name, size, queueSize, "thread_pool." + name); } /** * Construct a fixed executor builder. * * @param settings the node-level settings * @param name the name of the executor * @param size the fixed number of threads * @param queueSize the size of the backing queue, -1 for unbounded * @param prefix the prefix for the settings keys */ public FixedExecutorBuilder(final Settings settings, final String name, final int size, final int queueSize, final String prefix) { super(name); final String sizeKey = settingsKey(prefix, "size"); this.sizeSetting = new Setting<>( sizeKey, s -> Integer.toString(size), s -> Setting.parseInt(s, 1, applyHardSizeLimit(settings, name), sizeKey), DataTypes.INTEGER, Setting.Property.NodeScope ); final String queueSizeKey = settingsKey(prefix, "queue_size"); this.queueSizeSetting = Setting.intSetting(queueSizeKey, queueSize, Setting.Property.NodeScope); } @Override public List<Setting<?>> getRegisteredSettings() { return Arrays.asList(sizeSetting, queueSizeSetting); } @Override FixedExecutorSettings getSettings(Settings settings) { final String nodeName = Node.NODE_NAME_SETTING.get(settings); final int size = sizeSetting.get(settings); final int queueSize = queueSizeSetting.get(settings); return new FixedExecutorSettings(nodeName, size, queueSize); } @Override ThreadPool.ExecutorHolder build(final FixedExecutorSettings settings) { int size = settings.size; int queueSize = settings.queueSize; final ThreadFactory threadFactory = EsExecutors.daemonThreadFactory(EsExecutors.threadName(settings.nodeName, name())); final ExecutorService executor = EsExecutors.newFixed( settings.nodeName + "/" + name(), size, queueSize, threadFactory ); final ThreadPool.Info info = new ThreadPool.Info(name(), ThreadPool.ThreadPoolType.FIXED, size, size, null, queueSize < 0 ? null : new SizeValue(queueSize)); return new ThreadPool.ExecutorHolder(executor, info); } @Override String formatInfo(ThreadPool.Info info) {<FILL_FUNCTION_BODY>} static class FixedExecutorSettings extends ExecutorBuilder.ExecutorSettings { private final int size; private final int queueSize; FixedExecutorSettings(final String nodeName, final int size, final int queueSize) { super(nodeName); this.size = size; this.queueSize = queueSize; } } }
return String.format( Locale.ROOT, "name [%s], size [%d], queue size [%s]", info.getName(), info.getMax(), info.getQueueSize() == null ? "unbounded" : info.getQueueSize());
872
73
945
<methods>public void <init>(java.lang.String) ,public abstract List<Setting<?>> getRegisteredSettings() <variables>private final non-sealed java.lang.String name
crate_crate
crate/server/src/main/java/org/elasticsearch/threadpool/ScalingExecutorBuilder.java
ScalingExecutorBuilder
build
class ScalingExecutorBuilder extends ExecutorBuilder<ScalingExecutorBuilder.ScalingExecutorSettings> { private final Setting<Integer> coreSetting; private final Setting<Integer> maxSetting; private final Setting<TimeValue> keepAliveSetting; /** * Construct a scaling executor builder; the settings will have the * key prefix "thread_pool." followed by the executor name. * * @param name the name of the executor * @param core the minimum number of threads in the pool * @param max the maximum number of threads in the pool * @param keepAlive the time that spare threads above {@code core} * threads will be kept alive */ public ScalingExecutorBuilder(final String name, final int core, final int max, final TimeValue keepAlive) { this(name, core, max, keepAlive, "thread_pool." + name); } /** * Construct a scaling executor builder; the settings will have the * specified key prefix. * * @param name the name of the executor * @param core the minimum number of threads in the pool * @param max the maximum number of threads in the pool * @param keepAlive the time that spare threads above {@code core} * threads will be kept alive * @param prefix the prefix for the settings keys */ public ScalingExecutorBuilder(final String name, final int core, final int max, final TimeValue keepAlive, final String prefix) { super(name); this.coreSetting = Setting.intSetting(settingsKey(prefix, "core"), core, Setting.Property.NodeScope); this.maxSetting = Setting.intSetting(settingsKey(prefix, "max"), max, Setting.Property.NodeScope); this.keepAliveSetting = Setting.timeSetting(settingsKey(prefix, "keep_alive"), keepAlive, Setting.Property.NodeScope); } @Override public List<Setting<?>> getRegisteredSettings() { return Arrays.asList(coreSetting, maxSetting, keepAliveSetting); } @Override ScalingExecutorSettings getSettings(Settings settings) { final String nodeName = Node.NODE_NAME_SETTING.get(settings); final int coreThreads = coreSetting.get(settings); final int maxThreads = maxSetting.get(settings); final TimeValue keepAlive = keepAliveSetting.get(settings); return new ScalingExecutorSettings(nodeName, coreThreads, maxThreads, keepAlive); } @Override ThreadPool.ExecutorHolder build(final ScalingExecutorSettings settings) {<FILL_FUNCTION_BODY>} @Override String formatInfo(ThreadPool.Info info) { return String.format( Locale.ROOT, "name [%s], core [%d], max [%d], keep alive [%s]", info.getName(), info.getMin(), info.getMax(), info.getKeepAlive()); } static class ScalingExecutorSettings extends ExecutorBuilder.ExecutorSettings { private final int core; private final int max; private final TimeValue keepAlive; ScalingExecutorSettings(final String nodeName, final int core, final int max, final TimeValue keepAlive) { super(nodeName); this.core = core; this.max = max; this.keepAlive = keepAlive; } } }
TimeValue keepAlive = settings.keepAlive; int core = settings.core; int max = settings.max; final ThreadPool.Info info = new ThreadPool.Info(name(), ThreadPool.ThreadPoolType.SCALING, core, max, keepAlive, null); final ThreadFactory threadFactory = EsExecutors.daemonThreadFactory(EsExecutors.threadName(settings.nodeName, name())); final ExecutorService executor = EsExecutors.newScaling( settings.nodeName + "/" + name(), core, max, keepAlive.millis(), TimeUnit.MILLISECONDS, threadFactory); return new ThreadPool.ExecutorHolder(executor, info);
874
180
1,054
<methods>public void <init>(java.lang.String) ,public abstract List<Setting<?>> getRegisteredSettings() <variables>private final non-sealed java.lang.String name
crate_crate
crate/server/src/main/java/org/elasticsearch/threadpool/ScheduledCancellableAdapter.java
ScheduledCancellableAdapter
compareTo
class ScheduledCancellableAdapter implements Scheduler.ScheduledCancellable { private final ScheduledFuture<?> scheduledFuture; ScheduledCancellableAdapter(ScheduledFuture<?> scheduledFuture) { assert scheduledFuture != null; this.scheduledFuture = scheduledFuture; } @Override public long getDelay(TimeUnit unit) { return scheduledFuture.getDelay(unit); } @Override public int compareTo(Delayed other) {<FILL_FUNCTION_BODY>} @Override public boolean cancel() { return FutureUtils.cancel(scheduledFuture); } @Override public boolean isCancelled() { return scheduledFuture.isCancelled(); } }
// unwrap other by calling on it. return -other.compareTo(scheduledFuture);
196
27
223
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/transport/CloseableConnection.java
CloseableConnection
close
class CloseableConnection implements Transport.Connection { private final CompletableFuture<Void> closeContext = new CompletableFuture<>(); @Override public void addCloseListener(ActionListener<Void> listener) { closeContext.whenComplete(listener); } @Override public boolean isClosed() { return closeContext.isDone(); } @Override public void close() {<FILL_FUNCTION_BODY>} }
// This method is safe to call multiple times as the close context will provide concurrency // protection and only be completed once. The attached listeners will only be notified once. closeContext.complete(null);
119
51
170
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/transport/InboundAggregator.java
InboundAggregator
finishAggregation
class InboundAggregator implements Releasable { private final Supplier<CircuitBreaker> circuitBreaker; private final Predicate<String> requestCanTripBreaker; private ReleasableBytesReference firstContent; private ArrayList<ReleasableBytesReference> contentAggregation; private Header currentHeader; private Exception aggregationException; private boolean canTripBreaker = true; private boolean isClosed = false; public InboundAggregator(Supplier<CircuitBreaker> circuitBreaker, Function<String, RequestHandlerRegistry<TransportRequest>> registryFunction) { this(circuitBreaker, (Predicate<String>) actionName -> { final RequestHandlerRegistry<TransportRequest> reg = registryFunction.apply(actionName); if (reg == null) { throw new ActionNotFoundTransportException(actionName); } else { return reg.canTripCircuitBreaker(); } }); } // Visible for testing InboundAggregator(Supplier<CircuitBreaker> circuitBreaker, Predicate<String> requestCanTripBreaker) { this.circuitBreaker = circuitBreaker; this.requestCanTripBreaker = requestCanTripBreaker; } public void headerReceived(Header header) { ensureOpen(); assert isAggregating() == false; assert firstContent == null && contentAggregation == null; currentHeader = header; if (currentHeader.isRequest() && currentHeader.needsToReadVariableHeader() == false) { initializeRequestState(); } } public void aggregate(ReleasableBytesReference content) { ensureOpen(); assert isAggregating(); if (isShortCircuited() == false) { if (isFirstContent()) { firstContent = content.retain(); } else { if (contentAggregation == null) { contentAggregation = new ArrayList<>(4); assert firstContent != null; contentAggregation.add(firstContent); firstContent = null; } contentAggregation.add(content.retain()); } } } public InboundMessage finishAggregation() throws IOException {<FILL_FUNCTION_BODY>} public boolean isAggregating() { return currentHeader != null; } private void shortCircuit(Exception exception) { this.aggregationException = exception; } private boolean isShortCircuited() { return aggregationException != null; } private boolean isFirstContent() { return firstContent == null && contentAggregation == null; } @Override public void close() { isClosed = true; closeCurrentAggregation(); } private void closeCurrentAggregation() { releaseContent(); resetCurrentAggregation(); } private void releaseContent() { if (contentAggregation == null) { Releasables.close(firstContent); } else { Releasables.close(contentAggregation); } } private void resetCurrentAggregation() { firstContent = null; contentAggregation = null; currentHeader = null; aggregationException = null; canTripBreaker = true; } private void ensureOpen() { if (isClosed) { throw new IllegalStateException("Aggregator is already closed"); } } private void initializeRequestState() { assert currentHeader.needsToReadVariableHeader() == false; assert currentHeader.isRequest(); if (currentHeader.isHandshake()) { canTripBreaker = false; return; } final String actionName = currentHeader.getActionName(); try { canTripBreaker = requestCanTripBreaker.test(actionName); } catch (ActionNotFoundTransportException e) { shortCircuit(e); } } private void checkBreaker(final Header header, final int contentLength, final BreakerControl breakerControl) { if (header.isRequest() == false) { return; } assert header.needsToReadVariableHeader() == false; if (canTripBreaker) { try { circuitBreaker.get().addEstimateBytesAndMaybeBreak(contentLength, header.getActionName()); breakerControl.setReservedBytes(contentLength); } catch (CircuitBreakingException e) { shortCircuit(e); } } else { circuitBreaker.get().addWithoutBreaking(contentLength); breakerControl.setReservedBytes(contentLength); } } private static class BreakerControl implements Releasable { private static final int CLOSED = -1; private final Supplier<CircuitBreaker> circuitBreaker; private final AtomicInteger bytesToRelease = new AtomicInteger(0); private BreakerControl(Supplier<CircuitBreaker> circuitBreaker) { this.circuitBreaker = circuitBreaker; } private void setReservedBytes(int reservedBytes) { final boolean set = bytesToRelease.compareAndSet(0, reservedBytes); assert set : "Expected bytesToRelease to be 0, found " + bytesToRelease.get(); } @Override public void close() { final int toRelease = bytesToRelease.getAndSet(CLOSED); assert toRelease != CLOSED; if (toRelease > 0) { circuitBreaker.get().addWithoutBreaking(-toRelease); } } } }
ensureOpen(); final ReleasableBytesReference releasableContent; if (isFirstContent()) { releasableContent = ReleasableBytesReference.wrap(BytesArray.EMPTY); } else if (contentAggregation == null) { releasableContent = firstContent; } else { final ReleasableBytesReference[] references = contentAggregation.toArray(new ReleasableBytesReference[0]); final BytesReference content = CompositeBytesReference.of(references); releasableContent = new ReleasableBytesReference(content, () -> Releasables.close(references)); } final BreakerControl breakerControl = new BreakerControl(circuitBreaker); final InboundMessage aggregated = new InboundMessage(currentHeader, releasableContent, breakerControl); boolean success = false; try { if (aggregated.getHeader().needsToReadVariableHeader()) { aggregated.getHeader().finishParsingHeader(aggregated.openOrGetStreamInput()); if (aggregated.getHeader().isRequest()) { initializeRequestState(); } } if (isShortCircuited() == false) { checkBreaker(aggregated.getHeader(), aggregated.getContentLength(), breakerControl); } if (isShortCircuited()) { aggregated.close(); success = true; return new InboundMessage(aggregated.getHeader(), aggregationException); } else { success = true; return aggregated; } } finally { resetCurrentAggregation(); if (success == false) { aggregated.close(); } }
1,425
429
1,854
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/transport/InboundMessage.java
InboundMessage
takeBreakerReleaseControl
class InboundMessage implements Releasable { private final Header header; private final ReleasableBytesReference content; private final Exception exception; private final boolean isPing; private Releasable breakerRelease; private StreamInput streamInput; public InboundMessage(Header header, ReleasableBytesReference content, Releasable breakerRelease) { this.header = header; this.content = content; this.breakerRelease = breakerRelease; this.exception = null; this.isPing = false; } public InboundMessage(Header header, Exception exception) { this.header = header; this.content = null; this.breakerRelease = null; this.exception = exception; this.isPing = false; } public InboundMessage(Header header, boolean isPing) { this.header = header; this.content = null; this.breakerRelease = null; this.exception = null; this.isPing = isPing; } public Header getHeader() { return header; } public int getContentLength() { if (content == null) { return 0; } else { return content.length(); } } public Exception getException() { return exception; } public boolean isPing() { return isPing; } public boolean isShortCircuit() { return exception != null; } public Releasable takeBreakerReleaseControl() {<FILL_FUNCTION_BODY>} public StreamInput openOrGetStreamInput() throws IOException { assert isPing == false && content != null; if (streamInput == null) { streamInput = content.streamInput(); streamInput.setVersion(header.getVersion()); } return streamInput; } @Override public void close() { IOUtils.closeWhileHandlingException(streamInput); Releasables.closeIgnoringException(content, breakerRelease); } @Override public String toString() { return "InboundMessage{" + header + "}"; } }
final Releasable toReturn = breakerRelease; breakerRelease = null; if (toReturn != null) { return toReturn; } else { return () -> {}; }
563
57
620
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/transport/OutboundHandler.java
OutboundHandler
sendRequest
class OutboundHandler { private static final Logger LOGGER = LogManager.getLogger(OutboundHandler.class); private final String nodeName; private final Version version; private final StatsTracker statsTracker; private final ThreadPool threadPool; private final BigArrays bigArrays; private volatile TransportMessageListener messageListener = TransportMessageListener.NOOP_LISTENER; OutboundHandler(String nodeName, Version version, StatsTracker statsTracker, ThreadPool threadPool, BigArrays bigArrays) { this.nodeName = nodeName; this.version = version; this.statsTracker = statsTracker; this.threadPool = threadPool; this.bigArrays = bigArrays; } ChannelFuture sendBytes(CloseableChannel channel, byte[] bytes) { channel.markAccessed(threadPool.relativeTimeInMillis()); try { ChannelFuture future = channel.writeAndFlush(Unpooled.wrappedBuffer(bytes)); future.addListener(f -> { if (f.isSuccess()) { statsTracker.incrementBytesSent(bytes.length); } else { LOGGER.warn("send message failed [channel: {}]", channel, f.cause()); } }); return future; } catch (RuntimeException ex) { channel.close(); throw ex; } } /** * Sends the request to the given channel. This method should be used to send {@link TransportRequest} * objects back to the caller. */ public void sendRequest(final DiscoveryNode node, final CloseableChannel channel, final long requestId, final String action, final TransportRequest request, final TransportRequestOptions options, final Version channelVersion, final boolean compressRequest, final boolean isHandshake) throws IOException, TransportException {<FILL_FUNCTION_BODY>} /** * Sends the response to the given channel. This method should be used to send {@link TransportResponse} * objects back to the caller. * */ void sendResponse(final Version nodeVersion, final CloseableChannel channel, final long requestId, final String action, final TransportResponse response, final boolean compress, final boolean isHandshake) throws IOException { Version version = Version.min(this.version, nodeVersion); OutboundMessage.Response message = new OutboundMessage.Response( response, version, requestId, isHandshake, compress ); ChannelFuture future = sendMessage(channel, message); future.addListener(f -> messageListener.onResponseSent(requestId, action, response)); } /** * Sends back an error response to the caller via the given channel */ void sendErrorResponse(final Version nodeVersion, final CloseableChannel channel, final long requestId, final String action, final Exception error) throws IOException { Version version = Version.min(this.version, nodeVersion); TransportAddress address = new TransportAddress(channel.getLocalAddress()); RemoteTransportException tx = new RemoteTransportException(nodeName, address, action, error); OutboundMessage.Response message = new OutboundMessage.Response( tx, version, requestId, false, false ); ChannelFuture future = sendMessage(channel, message); future.addListener(f -> messageListener.onResponseSent(requestId, action, error)); } private ChannelFuture sendMessage(CloseableChannel channel, OutboundMessage networkMessage) throws IOException { channel.markAccessed(threadPool.relativeTimeInMillis()); var bytesStreamOutput = new ReleasableBytesStreamOutput(bigArrays); try { BytesReference msg = networkMessage.serialize(bytesStreamOutput); ChannelFuture future = channel.writeAndFlush(Netty4Utils.toByteBuf(msg)); future.addListener(f -> { statsTracker.incrementBytesSent(msg.length()); bytesStreamOutput.close(); if (!f.isSuccess()) { LOGGER.warn("send message failed [channel: {}]", channel, f.cause()); } }); return future; } catch (RuntimeException ex) { bytesStreamOutput.close(); channel.close(); throw ex; } } void setMessageListener(TransportMessageListener listener) { if (messageListener == TransportMessageListener.NOOP_LISTENER) { messageListener = listener; } else { throw new IllegalStateException("Cannot set message listener twice"); } } }
Version version = Version.min(this.version, channelVersion); OutboundMessage.Request message = new OutboundMessage.Request( request, version, action, requestId, isHandshake, compressRequest ); ChannelFuture future = sendMessage(channel, message); future.addListener(f -> messageListener.onRequestSent(node, requestId, action, request, options));
1,173
107
1,280
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/transport/OutboundMessage.java
OutboundMessage
writeMessage
class OutboundMessage { private final Writeable message; protected final Version version; protected final long requestId; protected final byte status; OutboundMessage(Version version, byte status, long requestId, Writeable message) { this.version = version; this.status = status; this.requestId = requestId; this.message = message; } BytesReference serialize(BytesStreamOutput bytesStream) throws IOException { bytesStream.setVersion(version); bytesStream.skip(TcpHeader.headerSize(version)); // The compressible bytes stream will not close the underlying bytes stream BytesReference reference; int variableHeaderLength = -1; final long preHeaderPosition = bytesStream.position(); if (version.onOrAfter(TcpHeader.VERSION_WITH_HEADER_SIZE)) { writeVariableHeader(bytesStream); variableHeaderLength = Math.toIntExact(bytesStream.position() - preHeaderPosition); } try (CompressibleBytesOutputStream stream = new CompressibleBytesOutputStream(bytesStream, TransportStatus.isCompress(status))) { stream.setVersion(version); if (variableHeaderLength == -1) { writeVariableHeader(stream); } reference = writeMessage(stream); } bytesStream.seek(0); final int contentSize = reference.length() - TcpHeader.headerSize(version); TcpHeader.writeHeader(bytesStream, requestId, status, version, contentSize, variableHeaderLength); return reference; } protected void writeVariableHeader(StreamOutput stream) throws IOException { ThreadContext.bwcWriteHeaders(stream); } protected BytesReference writeMessage(CompressibleBytesOutputStream stream) throws IOException {<FILL_FUNCTION_BODY>} static class Request extends OutboundMessage { private final String action; Request(Writeable message, Version version, String action, long requestId, boolean isHandshake, boolean compress) { super(version, setStatus(compress, isHandshake, message), requestId, message); this.action = action; } @Override protected void writeVariableHeader(StreamOutput stream) throws IOException { super.writeVariableHeader(stream); if (version.before(Version.V_4_3_0)) { // empty features array stream.writeStringArray(Strings.EMPTY_ARRAY); } stream.writeString(action); } private static byte setStatus(boolean compress, boolean isHandshake, Writeable message) { byte status = 0; status = TransportStatus.setRequest(status); if (compress && OutboundMessage.canCompress(message)) { status = TransportStatus.setCompress(status); } if (isHandshake) { status = TransportStatus.setHandshake(status); } return status; } } static class Response extends OutboundMessage { Response(Writeable message, Version version, long requestId, boolean isHandshake, boolean compress) { super(version, setStatus(compress, isHandshake, message), requestId, message); } private static byte setStatus(boolean compress, boolean isHandshake, Writeable message) { byte status = 0; status = TransportStatus.setResponse(status); if (message instanceof RemoteTransportException) { status = TransportStatus.setError(status); } if (compress) { status = TransportStatus.setCompress(status); } if (isHandshake) { status = TransportStatus.setHandshake(status); } return status; } } private static boolean canCompress(Writeable message) { return message instanceof BytesTransportRequest == false; } }
final BytesReference zeroCopyBuffer; if (message instanceof BytesTransportRequest) { BytesTransportRequest bRequest = (BytesTransportRequest) message; bRequest.writeThin(stream); zeroCopyBuffer = bRequest.bytes; } else if (message instanceof RemoteTransportException) { stream.writeException((RemoteTransportException) message); zeroCopyBuffer = BytesArray.EMPTY; } else { message.writeTo(stream); zeroCopyBuffer = BytesArray.EMPTY; } // we have to call materializeBytes() here before accessing the bytes. A CompressibleBytesOutputStream // might be implementing compression. And materializeBytes() ensures that some marker bytes (EOS marker) // are written. Otherwise we barf on the decompressing end when we read past EOF on purpose in the // #validateRequest method. this might be a problem in deflate after all but it's important to write // the marker bytes. final BytesReference message = stream.materializeBytes(); if (zeroCopyBuffer.length() == 0) { return message; } else { return CompositeBytesReference.of(message, zeroCopyBuffer); }
982
295
1,277
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/transport/RemoteTransportException.java
RemoteTransportException
fillInStackTrace
class RemoteTransportException extends ActionTransportException implements ElasticsearchWrapperException { public RemoteTransportException(String msg, Throwable cause) { super(msg, null, null, cause); } public RemoteTransportException(String name, TransportAddress address, String action, Throwable cause) { super(name, address, action, cause); } public RemoteTransportException(StreamInput in) throws IOException { super(in); } @Override @SuppressWarnings("sync-override") public Throwable fillInStackTrace() {<FILL_FUNCTION_BODY>} }
// no need for stack trace here, we always have cause return this;
156
22
178
<methods>public void <init>(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public void <init>(java.lang.String, org.elasticsearch.common.transport.TransportAddress, java.lang.String, java.lang.Throwable) ,public void <init>(java.lang.String, org.elasticsearch.common.transport.TransportAddress, java.lang.String, java.lang.String, java.lang.Throwable) ,public java.lang.String action() ,public org.elasticsearch.common.transport.TransportAddress address() ,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>private final non-sealed java.lang.String action,private final non-sealed org.elasticsearch.common.transport.TransportAddress address
crate_crate
crate/server/src/main/java/org/elasticsearch/transport/TcpHeader.java
TcpHeader
headerSize
class TcpHeader { public static final Version VERSION_WITH_HEADER_SIZE = Version.V_4_5_0; public static final int MARKER_BYTES_SIZE = 2; public static final int MESSAGE_LENGTH_SIZE = 4; public static final int REQUEST_ID_SIZE = 8; public static final int STATUS_SIZE = 1; public static final int VERSION_ID_SIZE = 4; public static final int VARIABLE_HEADER_SIZE = 4; public static final int BYTES_REQUIRED_FOR_MESSAGE_SIZE = MARKER_BYTES_SIZE + MESSAGE_LENGTH_SIZE; public static final int VERSION_POSITION = MARKER_BYTES_SIZE + MESSAGE_LENGTH_SIZE + REQUEST_ID_SIZE + STATUS_SIZE; public static final int VARIABLE_HEADER_SIZE_POSITION = VERSION_POSITION + VERSION_ID_SIZE; private static final int PRE_76_HEADER_SIZE = VERSION_POSITION + VERSION_ID_SIZE; public static final int BYTES_REQUIRED_FOR_VERSION = PRE_76_HEADER_SIZE; private static final int HEADER_SIZE = PRE_76_HEADER_SIZE + VARIABLE_HEADER_SIZE; public static int headerSize(Version version) {<FILL_FUNCTION_BODY>} private static final byte[] PREFIX = {(byte) 'E', (byte) 'S'}; public static void writeHeader(StreamOutput output, long requestId, byte status, Version version, int contentSize, int variableHeaderSize) throws IOException { output.writeBytes(PREFIX); // write the size, the size indicates the remaining message size, not including the size int if (version.onOrAfter(VERSION_WITH_HEADER_SIZE)) { output.writeInt(contentSize + REQUEST_ID_SIZE + STATUS_SIZE + VERSION_ID_SIZE + VARIABLE_HEADER_SIZE); } else { output.writeInt(contentSize + REQUEST_ID_SIZE + STATUS_SIZE + VERSION_ID_SIZE); } output.writeLong(requestId); output.writeByte(status); output.writeInt(version.internalId); if (version.onOrAfter(VERSION_WITH_HEADER_SIZE)) { assert variableHeaderSize != -1 : "Variable header size not set"; output.writeInt(variableHeaderSize); } } }
if (version.onOrAfter(VERSION_WITH_HEADER_SIZE)) { return HEADER_SIZE; } else { return PRE_76_HEADER_SIZE; }
656
54
710
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/transport/TransportActionProxy.java
ProxyResponseHandler
handleException
class ProxyResponseHandler<T extends TransportResponse> implements TransportResponseHandler<T> { private final Writeable.Reader<T> reader; private final TransportChannel channel; ProxyResponseHandler(TransportChannel channel, Writeable.Reader<T> reader) { this.reader = reader; this.channel = channel; } @Override public T read(StreamInput in) throws IOException { return reader.read(in); } @Override public void handleResponse(T response) { try { channel.sendResponse(response); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public void handleException(TransportException exp) {<FILL_FUNCTION_BODY>} @Override public String executor() { return ThreadPool.Names.SAME; } }
try { channel.sendResponse(exp); } catch (IOException e) { throw new UncheckedIOException(e); }
227
39
266
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/transport/TransportDecompressor.java
TransportDecompressor
pollDecompressedPage
class TransportDecompressor implements Closeable { private final Inflater inflater; private final PageCacheRecycler recycler; private final ArrayDeque<Recycler.V<byte[]>> pages; private int pageOffset = PageCacheRecycler.BYTE_PAGE_SIZE; private boolean hasReadHeader = false; public TransportDecompressor(PageCacheRecycler recycler) { this.recycler = recycler; inflater = new Inflater(true); pages = new ArrayDeque<>(4); } public int decompress(BytesReference bytesReference) throws IOException { int bytesConsumed = 0; if (hasReadHeader == false) { if (CompressorFactory.COMPRESSOR.isCompressed(bytesReference) == false) { int maxToRead = Math.min(bytesReference.length(), 10); StringBuilder sb = new StringBuilder("stream marked as compressed, but no compressor found, first [") .append(maxToRead).append("] content bytes out of [").append(bytesReference.length()) .append("] readable bytes with message size [").append(bytesReference.length()).append("] ").append("] are ["); for (int i = 0; i < maxToRead; i++) { sb.append(bytesReference.get(i)).append(","); } sb.append("]"); throw new IllegalStateException(sb.toString()); } hasReadHeader = true; int headerLength = CompressorFactory.COMPRESSOR.headerLength(); bytesReference = bytesReference.slice(headerLength, bytesReference.length() - headerLength); bytesConsumed += headerLength; } BytesRefIterator refIterator = bytesReference.iterator(); BytesRef ref; while ((ref = refIterator.next()) != null) { inflater.setInput(ref.bytes, ref.offset, ref.length); bytesConsumed += ref.length; boolean continueInflating = true; while (continueInflating) { final Recycler.V<byte[]> page; final boolean isNewPage = pageOffset == PageCacheRecycler.BYTE_PAGE_SIZE; if (isNewPage) { pageOffset = 0; page = recycler.bytePage(false); } else { page = pages.getLast(); } byte[] output = page.v(); try { int bytesInflated = inflater.inflate(output, pageOffset, PageCacheRecycler.BYTE_PAGE_SIZE - pageOffset); pageOffset += bytesInflated; if (isNewPage) { if (bytesInflated == 0) { page.close(); pageOffset = PageCacheRecycler.BYTE_PAGE_SIZE; } else { pages.add(page); } } } catch (DataFormatException e) { throw new IOException("Exception while inflating bytes", e); } if (inflater.needsInput()) { continueInflating = false; } if (inflater.finished()) { bytesConsumed -= inflater.getRemaining(); continueInflating = false; } assert inflater.needsDictionary() == false; } } return bytesConsumed; } public boolean canDecompress(int bytesAvailable) { return hasReadHeader || bytesAvailable >= CompressorFactory.COMPRESSOR.headerLength(); } public boolean isEOS() { return inflater.finished(); } public ReleasableBytesReference pollDecompressedPage() {<FILL_FUNCTION_BODY>} @Override public void close() { inflater.end(); for (Recycler.V<byte[]> page : pages) { page.close(); } } }
if (pages.isEmpty()) { return null; } else if (pages.size() == 1) { if (isEOS()) { Recycler.V<byte[]> page = pages.pollFirst(); ReleasableBytesReference reference = new ReleasableBytesReference(new BytesArray(page.v(), 0, pageOffset), page); pageOffset = 0; return reference; } else { return null; } } else { Recycler.V<byte[]> page = pages.pollFirst(); return new ReleasableBytesReference(new BytesArray(page.v()), page); }
991
168
1,159
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/transport/TransportHandshaker.java
TransportHandshaker
sendHandshake
class TransportHandshaker { static final String HANDSHAKE_ACTION_NAME = "internal:tcp/handshake"; private final ConcurrentMap<Long, HandshakeResponseHandler> pendingHandshakes = new ConcurrentHashMap<>(); private final CounterMetric numHandshakes = new CounterMetric(); private final Version version; private final ThreadPool threadPool; private final HandshakeRequestSender handshakeRequestSender; TransportHandshaker(Version version, ThreadPool threadPool, HandshakeRequestSender handshakeRequestSender) { this.version = version; this.threadPool = threadPool; this.handshakeRequestSender = handshakeRequestSender; } void sendHandshake(long requestId, DiscoveryNode node, CloseableChannel channel, TimeValue timeout, ActionListener<Version> listener) {<FILL_FUNCTION_BODY>} void handleHandshake(TransportChannel channel, long requestId, StreamInput stream) throws IOException { // Must read the handshake request to exhaust the stream new HandshakeRequest(stream); final int nextByte = stream.read(); if (nextByte != -1) { throw new IllegalStateException("Handshake request not fully read for requestId [" + requestId + "], action [" + TransportHandshaker.HANDSHAKE_ACTION_NAME + "], available [" + stream.available() + "]; resetting"); } channel.sendResponse(new HandshakeResponse(this.version)); } TransportResponseHandler<HandshakeResponse> removeHandlerForHandshake(long requestId) { return pendingHandshakes.remove(requestId); } int getNumPendingHandshakes() { return pendingHandshakes.size(); } long getNumHandshakes() { return numHandshakes.count(); } private class HandshakeResponseHandler implements TransportResponseHandler<HandshakeResponse> { private final long requestId; private final Version currentVersion; private final ActionListener<Version> listener; private final AtomicBoolean isDone = new AtomicBoolean(false); private HandshakeResponseHandler(long requestId, Version currentVersion, ActionListener<Version> listener) { this.requestId = requestId; this.currentVersion = currentVersion; this.listener = listener; } @Override public HandshakeResponse read(StreamInput in) throws IOException { return new HandshakeResponse(in); } @Override public void handleResponse(HandshakeResponse response) { if (isDone.compareAndSet(false, true)) { Version version = response.responseVersion; if (currentVersion.isCompatible(version) == false) { listener.onFailure(new IllegalStateException("Received message from unsupported version: [" + version + "] minimal compatible version is: [" + currentVersion.minimumCompatibilityVersion() + "]")); } else { listener.onResponse(version); } } } @Override public void handleException(TransportException e) { if (isDone.compareAndSet(false, true)) { listener.onFailure(new IllegalStateException("handshake failed", e)); } } void handleLocalException(TransportException e) { if (removeHandlerForHandshake(requestId) != null && isDone.compareAndSet(false, true)) { listener.onFailure(e); } } @Override public String executor() { return ThreadPool.Names.SAME; } } static final class HandshakeRequest extends TransportRequest { private final Version version; HandshakeRequest(Version version) { this.version = version; } HandshakeRequest(StreamInput streamInput) throws IOException { super(streamInput); BytesReference remainingMessage; try { remainingMessage = streamInput.readBytesReference(); } catch (EOFException e) { remainingMessage = null; } if (remainingMessage == null) { version = null; } else { try (StreamInput messageStreamInput = remainingMessage.streamInput()) { this.version = Version.readVersion(messageStreamInput); } } } @Override public void writeTo(StreamOutput streamOutput) throws IOException { super.writeTo(streamOutput); assert version != null; try (BytesStreamOutput messageStreamOutput = new BytesStreamOutput(4)) { Version.writeVersion(version, messageStreamOutput); BytesReference reference = messageStreamOutput.bytes(); streamOutput.writeBytesReference(reference); } } } static final class HandshakeResponse extends TransportResponse { private final Version responseVersion; HandshakeResponse(Version version) { this.responseVersion = version; } private HandshakeResponse(StreamInput in) throws IOException { responseVersion = Version.readVersion(in); } @Override public void writeTo(StreamOutput out) throws IOException { assert responseVersion != null; Version.writeVersion(responseVersion, out); } Version getResponseVersion() { return responseVersion; } } @FunctionalInterface interface HandshakeRequestSender { void sendRequest(DiscoveryNode node, CloseableChannel channel, long requestId, Version version) throws IOException; } }
numHandshakes.inc(); final HandshakeResponseHandler handler = new HandshakeResponseHandler(requestId, version, listener); pendingHandshakes.put(requestId, handler); channel.addCloseListener(ActionListener.wrap( () -> handler.handleLocalException(new TransportException("handshake failed because connection reset")))); boolean success = false; try { // for the request we use the minCompatVersion since we don't know what's the version of the node we talk to // we also have no payload on the request but the response will contain the actual version of the node we talk // to as the payload. final Version minCompatVersion = version.minimumCompatibilityVersion(); handshakeRequestSender.sendRequest(node, channel, requestId, minCompatVersion); threadPool.schedule( () -> handler.handleLocalException(new ConnectTransportException(node, "handshake_timeout[" + timeout + "]")), timeout, ThreadPool.Names.GENERIC ); success = true; } catch (Exception e) { handler.handleLocalException(new ConnectTransportException(node, "failure to send " + HANDSHAKE_ACTION_NAME, e)); } finally { if (success == false) { TransportResponseHandler<?> removed = pendingHandshakes.remove(requestId); assert removed == null : "Handshake should not be pending if exception was thrown"; } }
1,385
365
1,750
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/transport/TransportLogger.java
TransportLogger
format
class TransportLogger { private static final Logger LOGGER = LogManager.getLogger(TransportLogger.class); private static final int HEADER_SIZE = TcpHeader.MARKER_BYTES_SIZE + TcpHeader.MESSAGE_LENGTH_SIZE; static void logInboundMessage(CloseableChannel channel, InboundMessage message) { if (LOGGER.isTraceEnabled()) { try { String logMessage = format(channel, message, "READ"); LOGGER.trace(logMessage); } catch (IOException e) { LOGGER.warn("an exception occurred formatting a READ trace message", e); } } } private static String format(CloseableChannel channel, InboundMessage message, String event) throws IOException {<FILL_FUNCTION_BODY>} }
final StringBuilder sb = new StringBuilder(); sb.append(channel); if (message.isPing()) { sb.append(" [ping]").append(' ').append(event).append(": ").append(6).append('B'); } else { boolean success = false; Header header = message.getHeader(); int networkMessageSize = header.getNetworkMessageSize(); int messageLengthWithHeader = HEADER_SIZE + networkMessageSize; StreamInput streamInput = message.openOrGetStreamInput(); try { final long requestId = header.getRequestId(); final boolean isRequest = header.isRequest(); final String type = isRequest ? "request" : "response"; final String version = header.getVersion().toString(); sb.append(" [length: ").append(messageLengthWithHeader); sb.append(", request id: ").append(requestId); sb.append(", type: ").append(type); sb.append(", version: ").append(version); // TODO: Maybe Fix for BWC if (header.needsToReadVariableHeader() == false && isRequest) { sb.append(", action: ").append(header.getActionName()); } sb.append(']'); sb.append(' ').append(event).append(": ").append(messageLengthWithHeader).append('B'); success = true; } finally { if (success) { IOUtils.close(streamInput); } else { IOUtils.closeWhileHandlingException(streamInput); } } } return sb.toString();
203
410
613
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/transport/TransportRequestDeduplicator.java
CompositeListener
addListener
class CompositeListener implements ActionListener<Void> { private final List<ActionListener<Void>> listeners = new ArrayList<>(); private final T request; private boolean isNotified; private Exception failure; CompositeListener(T request) { this.request = request; } CompositeListener addListener(ActionListener<Void> listener) {<FILL_FUNCTION_BODY>} private void onCompleted(Exception failure) { synchronized (this) { this.failure = failure; this.isNotified = true; } try { if (failure == null) { ActionListener.onResponse(listeners, null); } else { ActionListener.onFailure(listeners, failure); } } finally { requests.remove(request); } } @Override public void onResponse(final Void aVoid) { onCompleted(null); } @Override public void onFailure(Exception failure) { onCompleted(failure); } }
synchronized (this) { if (this.isNotified == false) { listeners.add(listener); return listeners.size() == 1 ? this : null; } } if (failure != null) { listener.onFailure(failure); } else { listener.onResponse(null); } return null;
279
96
375
<no_super_class>
crate_crate
crate/server/src/main/java/org/elasticsearch/transport/netty4/Netty4InboundStatsHandler.java
Netty4InboundStatsHandler
channelActive
class Netty4InboundStatsHandler extends ChannelInboundHandlerAdapter implements Releasable { final Set<Channel> openChannels = Collections.newSetFromMap(new ConcurrentHashMap<>()); final StatsTracker statsTracker; final Logger logger; public Netty4InboundStatsHandler(StatsTracker statsTracker, Logger logger) { this.statsTracker = statsTracker; this.logger = logger; } final ChannelFutureListener remover = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { boolean removed = openChannels.remove(future.channel()); if (removed) { statsTracker.decrementOpenChannels(); } if (logger.isTraceEnabled()) { logger.trace("channel closed: {}", future.channel()); } } }; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception {<FILL_FUNCTION_BODY>} @Override public void close() { try { Netty4Utils.closeChannels(openChannels); } catch (IOException e) { logger.trace("exception while closing channels", e); } openChannels.clear(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ByteBuf bb) { statsTracker.incrementBytesReceived(bb.readableBytes()); statsTracker.incrementMessagesReceived(); } else { logger.warn("Message sent is: {} and not a ByteBuf, cannot track received bytes or message count", msg.getClass().getCanonicalName()); } super.channelRead(ctx, msg); } }
if (logger.isTraceEnabled()) { logger.trace("channel opened: {}", ctx.channel()); } final boolean added = openChannels.add(ctx.channel()); if (added) { statsTracker.incrementOpenChannels(); ctx.channel().closeFuture().addListener(remover); } super.channelActive(ctx);
448
95
543
<no_super_class>
citerus_dddsample-core
dddsample-core/src/main/java/com/pathfinder/internal/GraphDAOStub.java
GraphDAOStub
getTransitEdge
class GraphDAOStub implements GraphDAO{ private static final Random random = new Random(); public List<String> listAllNodes() { return new ArrayList<String>(List.of( "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" )); } public String getTransitEdge(String from, String to) {<FILL_FUNCTION_BODY>} }
final int i = random.nextInt(5); if (i == 0) return "0100S"; if (i == 1) return "0200T"; if (i == 2) return "0300A"; if (i == 3) return "0301S"; return "0400S";
159
90
249
<no_super_class>
citerus_dddsample-core
dddsample-core/src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java
GraphTraversalServiceImpl
findShortestPath
class GraphTraversalServiceImpl implements GraphTraversalService { private GraphDAO dao; private Random random; private static final long ONE_MIN_MS = 1000 * 60; private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; public GraphTraversalServiceImpl(GraphDAO dao) { this.dao = dao; this.random = new Random(); } public List<TransitPath> findShortestPath( final String originNode, final String destinationNode, final Properties limitations) {<FILL_FUNCTION_BODY>} private Instant nextDate(Instant date) { return date.plus(1, ChronoUnit.DAYS).plus((random.nextInt(1000) - 500), ChronoUnit.MINUTES); } private int getRandomNumberOfCandidates() { return 3 + random.nextInt(3); } private List<String> getRandomChunkOfNodes(List<String> allNodes) { Collections.shuffle(allNodes); final int total = allNodes.size(); final int chunk = total > 4 ? 1 + random.nextInt(5) : total; return allNodes.subList(0, chunk); } }
List<String> allVertices = dao.listAllNodes(); allVertices.remove(originNode); allVertices.remove(destinationNode); int candidateCount = getRandomNumberOfCandidates(); List<TransitPath> candidates = new ArrayList<>(candidateCount); for (int i = 0; i < candidateCount; i++) { allVertices = getRandomChunkOfNodes(allVertices); List<TransitEdge> transitEdges = new ArrayList<>(allVertices.size() - 1); String fromNode = originNode; Instant date = Instant.now(); for (int j = 0; j <= allVertices.size(); ++j) { Instant fromDate = nextDate(date); Instant toDate = nextDate(fromDate); String toNode = (j >= allVertices.size() ? destinationNode : allVertices.get(j)); transitEdges.add( new TransitEdge( dao.getTransitEdge(fromNode, toNode), fromNode, toNode, fromDate, toDate)); fromNode = toNode; date = nextDate(toDate); } candidates.add(new TransitPath(transitEdges)); } return candidates;
341
320
661
<no_super_class>
citerus_dddsample-core
dddsample-core/src/main/java/se/citerus/dddsample/application/impl/BookingServiceImpl.java
BookingServiceImpl
changeDestination
class BookingServiceImpl implements BookingService { private final CargoRepository cargoRepository; private final LocationRepository locationRepository; private final RoutingService routingService; private final CargoFactory cargoFactory; private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); public BookingServiceImpl(final CargoRepository cargoRepository, final LocationRepository locationRepository, final RoutingService routingService, final CargoFactory cargoFactory) { this.cargoRepository = cargoRepository; this.locationRepository = locationRepository; this.routingService = routingService; this.cargoFactory = cargoFactory; } @Override @Transactional public TrackingId bookNewCargo(final UnLocode originUnLocode, final UnLocode destinationUnLocode, final Instant arrivalDeadline) { Cargo cargo = cargoFactory.createCargo(originUnLocode, destinationUnLocode, arrivalDeadline); cargoRepository.store(cargo); logger.info("Booked new cargo with tracking id {}", cargo.trackingId().idString()); return cargo.trackingId(); } @Override @Transactional public List<Itinerary> requestPossibleRoutesForCargo(final TrackingId trackingId) { final Cargo cargo = cargoRepository.find(trackingId); if (cargo == null) { return Collections.emptyList(); } return routingService.fetchRoutesForSpecification(cargo.routeSpecification()); } @Override @Transactional public void assignCargoToRoute(final Itinerary itinerary, final TrackingId trackingId) { final Cargo cargo = cargoRepository.find(trackingId); if (cargo == null) { throw new IllegalArgumentException("Can't assign itinerary to non-existing cargo " + trackingId); } cargo.assignToRoute(itinerary); cargoRepository.store(cargo); logger.info("Assigned cargo {} to new route", trackingId); } @Override @Transactional public void changeDestination(final TrackingId trackingId, final UnLocode unLocode) {<FILL_FUNCTION_BODY>} }
final Cargo cargo = cargoRepository.find(trackingId); final Location newDestination = locationRepository.find(unLocode); final RouteSpecification routeSpecification = new RouteSpecification( cargo.origin(), newDestination, cargo.routeSpecification().arrivalDeadline() ); cargo.specifyNewRoute(routeSpecification); cargoRepository.store(cargo); logger.info("Changed destination for cargo {} to {}", trackingId, routeSpecification.destination());
579
126
705
<no_super_class>