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
|
|---|---|---|---|---|---|---|---|---|---|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/FileReceiver.java
|
FileReceiver
|
readChunk
|
class FileReceiver extends TransmissionReceiver {
/** Handler to notify when a file has been received. */
private final Consumer<File> hnd;
/** File to receive data into. */
private File file;
/** The corresponding file channel to work with. */
@GridToStringExclude
private FileIO fileIo;
/**
* @param meta Initial file meta info.
* @param stopChecker Node stop or prcoess interrupt checker.
* @param factory Factory to produce IO interface on files.
* @param hnd Transmission handler provider to process download result.
* @param path File path to destination receiver source.
* @param log Ignite logger.
*/
public FileReceiver(
TransmissionMeta meta,
int chunkSize,
BooleanSupplier stopChecker,
FileIOFactory factory,
Consumer<File> hnd,
String path,
IgniteLogger log
) {
super(meta, stopChecker, log, chunkSize);
A.notNull(hnd, "FileHandler must be provided by transmission handler");
A.notNull(path, "File absolute path cannot be null");
A.ensure(!path.trim().isEmpty(), "File absolute path cannot be empty ");
this.hnd = hnd;
file = new File(path);
try {
fileIo = factory.create(file);
fileIo.position(meta.offset());
}
catch (IOException e) {
throw new IgniteException("Unable to open destination file. Receiver will be stopped: " +
file.getAbsolutePath(), e);
}
}
/** {@inheritDoc} */
@Override public void receive(ReadableByteChannel ch) throws IOException, InterruptedException {
super.receive(ch);
if (transferred == meta.count())
hnd.accept(file);
}
/** {@inheritDoc} */
@Override protected void readChunk(ReadableByteChannel ch) throws IOException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void close() {
U.closeQuiet(fileIo);
try {
if (transferred != meta.count())
Files.delete(file.toPath());
}
catch (IOException e) {
U.error(log, "Error deleting not fully loaded file: " + file, e);
}
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(FileReceiver.class, this, "super", super.toString());
}
}
|
assert fileIo != null;
long batchSize = Math.min(chunkSize, meta.count() - transferred);
long read = fileIo.transferFrom(ch, meta.offset() + transferred, batchSize);
if (read == 0)
throw new IOException("Channel is reached the end of stream. Probably, channel is closed on the remote node");
if (read > 0)
transferred += read;
| 657
| 109
| 766
|
<methods>public void receive(java.nio.channels.ReadableByteChannel) throws java.io.IOException, java.lang.InterruptedException<variables>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/FileSender.java
|
FileSender
|
updateSenderState
|
class FileSender extends AbstractTransmission {
/** Corresponding file channel to work with a given file. */
@GridToStringExclude
private FileIO fileIo;
/**
* @param file File which is going to be sent by chunks.
* @param off File offset.
* @param cnt Number of bytes to transfer.
* @param params Additional file params.
* @param plc Policy of handling data on remote.
* @param stopChecker Node stop or process interrupt checker.
* @param log Ignite logger.
* @param factory Factory to produce IO interface on given file.
* @param chunkSize Size of chunks.
* @throws IOException If fails.
*/
public FileSender(
File file,
long off,
long cnt,
Map<String, Serializable> params,
TransmissionPolicy plc,
BooleanSupplier stopChecker,
IgniteLogger log,
FileIOFactory factory,
int chunkSize
) throws IOException {
super(new TransmissionMeta(file.getName(), off, cnt, params, plc, null), stopChecker, log, chunkSize);
assert file != null;
fileIo = factory.create(file);
}
/**
* @param ch Output channel to write file to.
* @param oo Channel to write meta info to.
* @param rcvMeta Connection meta received.
* @throws IOException If a transport exception occurred.
* @throws InterruptedException If thread interrupted.
*/
public void send(WritableByteChannel ch,
ObjectOutput oo,
@Nullable TransmissionMeta rcvMeta
) throws IOException, InterruptedException {
updateSenderState(rcvMeta);
// Write flag to remote to keep currnet transmission opened.
oo.writeBoolean(false);
// Send meta about current file to remote.
oo.writeObject(new TransmissionMeta(meta.name(),
meta.offset() + transferred,
meta.count() - transferred,
meta.params(),
meta.policy(),
null));
while (hasNextChunk()) {
if (Thread.currentThread().isInterrupted())
throw new InterruptedException("Sender thread has been interruped");
if (stopped())
throw new IgniteException("Sender has been cancelled due to the local node is stopping");
writeChunk(ch);
}
assert transferred == meta.count() : "File is not fully transferred [expect=" + meta.count() +
", actual=" + transferred + ']';
}
/**
* @param rcvMeta Conneciton meta info.
*/
private void updateSenderState(TransmissionMeta rcvMeta) {<FILL_FUNCTION_BODY>}
/**
* @param ch Channel to write data to.
* @throws IOException If fails.
*/
private void writeChunk(WritableByteChannel ch) throws IOException {
long batchSize = Math.min(chunkSize, meta.count() - transferred);
long sent = fileIo.transferTo(meta.offset() + transferred, batchSize, ch);
if (sent > 0)
transferred += sent;
}
/** {@inheritDoc} */
@Override public void close() {
U.closeQuiet(fileIo);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(FileSender.class, this, "super", super.toString());
}
}
|
// The remote node doesn't have a file meta info.
if (rcvMeta == null || rcvMeta.offset() < 0) {
transferred = 0;
return;
}
long uploadedBytes = rcvMeta.offset() - meta.offset();
assertParameter(meta.name().equals(rcvMeta.name()), "Attempt to transfer different file " +
"while previous is not completed [meta=" + meta + ", meta=" + rcvMeta + ']');
assertParameter(uploadedBytes >= 0, "Incorrect sync meta [offset=" + rcvMeta.offset() +
", meta=" + meta + ']');
// No need to set new file position, if it is not changed.
if (uploadedBytes == 0)
return;
transferred = uploadedBytes;
U.log(log, "The number of transferred bytes after reconnect has been updated: " + uploadedBytes);
| 885
| 232
| 1,117
|
<methods>public org.apache.ignite.internal.managers.communication.TransmissionMeta state() ,public java.lang.String toString() ,public long transferred() <variables>protected final non-sealed int chunkSize,protected final non-sealed org.apache.ignite.IgniteLogger log,protected org.apache.ignite.internal.managers.communication.TransmissionMeta meta,private final non-sealed java.util.function.BooleanSupplier stopChecker,protected long transferred
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/IgniteMessageFactoryImpl.java
|
IgniteMessageFactoryImpl
|
register
|
class IgniteMessageFactoryImpl implements IgniteMessageFactory {
/** Offset. */
private static final int OFF = -Short.MIN_VALUE;
/** Array size. */
private static final int ARR_SIZE = 1 << Short.SIZE;
/** Message suppliers. */
private final Supplier<Message>[] msgSuppliers = (Supplier<Message>[])Array.newInstance(Supplier.class, ARR_SIZE);
/** Initialized flag. If {@code true} then new message type couldn't be registered. */
private boolean initialized;
/** Min index of registered message supplier. */
private int minIdx = Integer.MAX_VALUE;
/** Max index of registered message supplier. */
private int maxIdx = -1;
/** Count of registered message suppliers. */
private int cnt;
/**
* Contructor.
*
* @param factories Concrete message factories or message factory providers. Cfn't be empty or {@code null}.
*/
public IgniteMessageFactoryImpl(MessageFactory[] factories) {
if (factories == null || factories.length == 0)
throw new IllegalArgumentException("Message factory couldn't be initialized. Factories aren't provided.");
List<MessageFactory> old = new ArrayList<>(factories.length);
for (MessageFactory factory : factories) {
if (factory instanceof MessageFactoryProvider) {
MessageFactoryProvider p = (MessageFactoryProvider)factory;
p.registerAll(this);
}
else
old.add(factory);
}
if (!old.isEmpty()) {
for (int i = 0; i < ARR_SIZE; i++) {
Supplier<Message> curr = msgSuppliers[i];
if (curr == null) {
short directType = indexToDirectType(i);
for (MessageFactory factory : old) {
Message msg = factory.create(directType);
if (msg != null)
register(directType, () -> factory.create(directType));
}
}
}
}
initialized = true;
}
/** {@inheritDoc} */
@Override public void register(short directType, Supplier<Message> supplier) throws IgniteException {<FILL_FUNCTION_BODY>}
/**
* Creates new message instance of provided direct type.
*
* @param directType Message direct type.
* @return Message instance.
* @throws IgniteException If there are no any message factory for given {@code directType}.
*/
@Override public @Nullable Message create(short directType) {
Supplier<Message> supplier = msgSuppliers[directTypeToIndex(directType)];
if (supplier == null)
throw new IgniteException("Invalid message type: " + directType);
return supplier.get();
}
/**
* Returns direct types of all registered messages.
*
* @return Direct types of all registered messages.
*/
public short[] registeredDirectTypes() {
short[] res = new short[cnt];
if (cnt > 0) {
for (int i = minIdx, p = 0; i <= maxIdx; i++) {
if (msgSuppliers[i] != null)
res[p++] = indexToDirectType(i);
}
}
return res;
}
/**
* @param directType Direct type.
*/
private static int directTypeToIndex(short directType) {
return directType + OFF;
}
/**
* @param idx Index.
*/
private static short indexToDirectType(int idx) {
int res = idx - OFF;
assert res >= Short.MIN_VALUE && res <= Short.MAX_VALUE;
return (short)res;
}
}
|
if (initialized) {
throw new IllegalStateException("Message factory is already initialized. " +
"Registration of new message types is forbidden.");
}
int idx = directTypeToIndex(directType);
Supplier<Message> curr = msgSuppliers[idx];
if (curr == null) {
msgSuppliers[idx] = supplier;
minIdx = Math.min(idx, minIdx);
maxIdx = Math.max(idx, maxIdx);
cnt++;
}
else
throw new IgniteException("Message factory is already registered for direct type: " + directType);
| 967
| 167
| 1,134
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentInfoBean.java
|
GridDeploymentInfoBean
|
equals
|
class GridDeploymentInfoBean implements Message, GridDeploymentInfo, Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** */
private IgniteUuid clsLdrId;
/** */
private DeploymentMode depMode;
/** */
private String userVer;
/** */
@Deprecated // Left for backward compatibility only.
private boolean locDepOwner;
/** Node class loader participant map. */
@GridToStringInclude
@GridDirectMap(keyType = UUID.class, valueType = IgniteUuid.class)
private Map<UUID, IgniteUuid> participants;
/**
* Required by {@link Externalizable}.
*/
public GridDeploymentInfoBean() {
/* No-op. */
}
/**
* @param clsLdrId Class loader ID.
* @param userVer User version.
* @param depMode Deployment mode.
* @param participants Participants.
*/
public GridDeploymentInfoBean(
IgniteUuid clsLdrId,
String userVer,
DeploymentMode depMode,
Map<UUID, IgniteUuid> participants
) {
this.clsLdrId = clsLdrId;
this.depMode = depMode;
this.userVer = userVer;
this.participants = participants;
}
/**
* @param dep Grid deployment.
*/
public GridDeploymentInfoBean(GridDeploymentInfo dep) {
clsLdrId = dep.classLoaderId();
depMode = dep.deployMode();
userVer = dep.userVersion();
participants = dep.participants();
}
/** {@inheritDoc} */
@Override public IgniteUuid classLoaderId() {
return clsLdrId;
}
/** {@inheritDoc} */
@Override public DeploymentMode deployMode() {
return depMode;
}
/** {@inheritDoc} */
@Override public String userVersion() {
return userVer;
}
/** {@inheritDoc} */
@Override public long sequenceNumber() {
return clsLdrId.localId();
}
/** {@inheritDoc} */
@Override public boolean localDeploymentOwner() {
return locDepOwner;
}
/** {@inheritDoc} */
@Override public Map<UUID, IgniteUuid> participants() {
return participants;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public int hashCode() {
return clsLdrId.hashCode();
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeIgniteUuid("clsLdrId", clsLdrId))
return false;
writer.incrementState();
case 1:
if (!writer.writeByte("depMode", depMode != null ? (byte)depMode.ordinal() : -1))
return false;
writer.incrementState();
case 2:
if (!writer.writeBoolean("locDepOwner", locDepOwner))
return false;
writer.incrementState();
case 3:
if (!writer.writeMap("participants", participants, MessageCollectionItemType.UUID, MessageCollectionItemType.IGNITE_UUID))
return false;
writer.incrementState();
case 4:
if (!writer.writeString("userVer", userVer))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
clsLdrId = reader.readIgniteUuid("clsLdrId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
byte depModeOrd;
depModeOrd = reader.readByte("depMode");
if (!reader.isLastRead())
return false;
depMode = DeploymentMode.fromOrdinal(depModeOrd);
reader.incrementState();
case 2:
locDepOwner = reader.readBoolean("locDepOwner");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 3:
participants = reader.readMap("participants", MessageCollectionItemType.UUID, MessageCollectionItemType.IGNITE_UUID, false);
if (!reader.isLastRead())
return false;
reader.incrementState();
case 4:
userVer = reader.readString("userVer");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridDeploymentInfoBean.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return 10;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 5;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeIgniteUuid(out, clsLdrId);
U.writeEnum(out, depMode);
U.writeString(out, userVer);
out.writeBoolean(locDepOwner);
U.writeMap(out, participants);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
clsLdrId = U.readIgniteUuid(in);
depMode = DeploymentMode.fromOrdinal(in.readByte());
userVer = U.readString(in);
locDepOwner = in.readBoolean();
participants = U.readMap(in);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridDeploymentInfoBean.class, this);
}
}
|
return o == this || o instanceof GridDeploymentInfoBean &&
clsLdrId.equals(((GridDeploymentInfoBean)o).clsLdrId);
| 1,713
| 42
| 1,755
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentStoreAdapter.java
|
GridDeploymentStoreAdapter
|
clearSerializationCaches
|
class GridDeploymentStoreAdapter implements GridDeploymentStore {
/** Logger. */
protected final IgniteLogger log;
/** Deployment SPI. */
protected final DeploymentSpi spi;
/** Kernal context. */
protected final GridKernalContext ctx;
/** Deployment communication. */
protected final GridDeploymentCommunication comm;
/**
* @param spi Underlying SPI.
* @param ctx Grid kernal context.
* @param comm Deployment communication.
*/
GridDeploymentStoreAdapter(DeploymentSpi spi, GridKernalContext ctx, GridDeploymentCommunication comm) {
assert spi != null;
assert ctx != null;
assert comm != null;
this.spi = spi;
this.ctx = ctx;
this.comm = comm;
log = ctx.log(getClass());
}
/**
* @return Startup log message.
*/
protected final String startInfo() {
return "Deployment store started: " + this;
}
/**
* @return Stop log message.
*/
protected final String stopInfo() {
return "Deployment store stopped: " + this;
}
/** {@inheritDoc} */
@Override public void onKernalStart() throws IgniteCheckedException {
if (log.isDebugEnabled())
log.debug("Ignoring kernel started callback: " + this);
}
/** {@inheritDoc} */
@Override public void onKernalStop() {
/* No-op. */
}
/** {@inheritDoc} */
@Nullable @Override public GridDeployment explicitDeploy(Class<?> cls, ClassLoader clsLdr) throws IgniteCheckedException {
if (log.isDebugEnabled())
log.debug("Ignoring explicit deploy [cls=" + cls + ", clsLdr=" + clsLdr + ']');
return null;
}
/**
* @param ldr Class loader.
* @return User version.
*/
protected final String userVersion(ClassLoader ldr) {
return ctx.userVersion(ldr);
}
/**
* @param cls Class to check.
* @return {@code True} if class is task class.
*/
protected final boolean isTask(Class<?> cls) {
return ComputeTask.class.isAssignableFrom(cls);
}
/**
* Clears serialization caches to avoid PermGen memory leaks.
* This method should be called on each undeployment.
* <p>
* For more information: http://www.szegedi.org/articles/memleak3.html.
*/
protected final void clearSerializationCaches() {<FILL_FUNCTION_BODY>}
/**
* @param cls Class name.
* @param fieldName Field name.
* @throws IllegalAccessException If field can't be accessed.
* @throws NoSuchFieldException If class can't be found.
*/
private void clearSerializationCache(Class cls, String fieldName)
throws NoSuchFieldException, IllegalAccessException {
Field f = cls.getDeclaredField(fieldName);
f.setAccessible(true);
Object fieldVal = f.get(null);
if (fieldVal instanceof Map)
((Map<?, ?>)fieldVal).clear();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridDeploymentStoreAdapter.class, this);
}
}
|
try {
clearSerializationCache(Class.forName("java.io.ObjectInputStream$Caches"), "subclassAudits");
clearSerializationCache(Class.forName("java.io.ObjectOutputStream$Caches"), "subclassAudits");
clearSerializationCache(Class.forName("java.io.ObjectStreamClass$Caches"), "localDescs");
clearSerializationCache(Class.forName("java.io.ObjectStreamClass$Caches"), "reflectors");
}
catch (ClassNotFoundException e) {
if (log.isDebugEnabled())
log.debug("Class not found: " + e.getMessage());
}
catch (NoSuchFieldException e) {
if (log.isDebugEnabled())
log.debug("Field not found: " + e.getMessage());
}
catch (IllegalAccessException e) {
if (log.isDebugEnabled())
log.debug("Field can't be accessed: " + e.getMessage());
}
| 915
| 245
| 1,160
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/discovery/DiscoveryMessageResultsCollector.java
|
NodeMessage
|
onNodeFailed
|
class NodeMessage<M> {
/** */
boolean nodeFailed;
/** */
M msg;
/**
* @param msg Message.
*/
NodeMessage(M msg) {
this.msg = msg;
}
/**
* @return Message or {@code null} if node failed.
*/
@Nullable public M message() {
return msg;
}
/**
* @return {@code True} if node result was not set before.
*/
boolean onNodeFailed() {<FILL_FUNCTION_BODY>}
/**
* @param msg Received message.
* @return {@code True} if node result was not set before.
*/
boolean set(M msg) {
assert msg != null;
if (this.msg != null)
return false;
this.msg = msg;
return !nodeFailed;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(NodeMessage.class, this);
}
}
|
if (nodeFailed || msg != null)
return false;
nodeFailed = true;
return true;
| 273
| 34
| 307
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/indexing/GridIndexingManager.java
|
GridIndexingManager
|
query
|
class GridIndexingManager extends GridManagerAdapter<IndexingSpi> {
/** */
private final GridSpinBusyLock busyLock = new GridSpinBusyLock();
/**
* @param ctx Kernal context.
*/
public GridIndexingManager(GridKernalContext ctx) {
super(ctx, ctx.config().getIndexingSpi());
}
/**
* @throws IgniteCheckedException Thrown in case of any errors.
*/
@Override public void start() throws IgniteCheckedException {
startSpi();
if (log.isDebugEnabled())
log.debug(startInfo());
}
/** {@inheritDoc} */
@Override protected void onKernalStop0(boolean cancel) {
busyLock.block();
}
/**
* @throws IgniteCheckedException Thrown in case of any errors.
*/
@Override public void stop(boolean cancel) throws IgniteCheckedException {
stopSpi();
if (log.isDebugEnabled())
log.debug(stopInfo());
}
/**
* Writes key-value pair to index.
*
* @param cacheName Cache name.
* @param key Key.
* @param val Value.
* @param expirationTime Expiration time or 0 if never expires.
* @throws IgniteCheckedException In case of error.
*/
public <K, V> void store(final String cacheName, final K key, final V val, long expirationTime)
throws IgniteCheckedException {
assert key != null;
assert val != null;
assert enabled();
if (!busyLock.enterBusy())
throw new IllegalStateException("Failed to write to index (grid is stopping).");
try {
if (log.isDebugEnabled())
log.debug("Storing key to cache query index [key=" + key + ", value=" + val + "]");
getSpi().store(cacheName, key, val, expirationTime);
}
finally {
busyLock.leaveBusy();
}
}
/**
* @param cacheName Cache name.
* @param key Key.
* @throws IgniteCheckedException Thrown in case of any errors.
*/
public void remove(String cacheName, Object key) throws IgniteCheckedException {
assert key != null;
assert enabled();
if (!busyLock.enterBusy())
throw new IllegalStateException("Failed to remove from index (grid is stopping).");
try {
getSpi().remove(cacheName, key);
}
finally {
busyLock.leaveBusy();
}
}
/**
* @param cacheName Cache name.
* @param params Parameters collection.
* @param filters Filters.
* @return Query result.
* @throws IgniteCheckedException If failed.
*/
public IgniteSpiCloseableIterator<?> query(String cacheName, Collection<Object> params, IndexingQueryFilter filters)
throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
}
|
if (!enabled())
throw new IgniteCheckedException("Indexing SPI is not configured.");
if (!busyLock.enterBusy())
throw new IllegalStateException("Failed to execute query (grid is stopping).");
try {
final Iterator<?> res = getSpi().query(cacheName, params, filters);
if (res == null)
return new GridEmptyCloseableIterator<>();
return new IgniteSpiCloseableIterator<Object>() {
@Override public void close() throws IgniteCheckedException {
if (res instanceof AutoCloseable) {
try {
((AutoCloseable)res).close();
}
catch (Exception e) {
throw new IgniteCheckedException(e);
}
}
}
@Override public boolean hasNext() {
return res.hasNext();
}
@Override public Object next() {
return res.next();
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
};
}
finally {
busyLock.leaveBusy();
}
| 792
| 281
| 1,073
|
<methods>public void collectGridNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public void collectJoiningNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public org.apache.ignite.internal.GridComponent.DiscoveryDataExchangeType discoveryDataType() ,public boolean enabled() ,public void onAfterSpiStart() ,public void onBeforeSpiStart() ,public void onDisconnected(IgniteFuture<?>) throws org.apache.ignite.IgniteCheckedException,public void onGridDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.GridDiscoveryData) ,public void onJoiningNodeDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) ,public final void onKernalStart(boolean) throws org.apache.ignite.IgniteCheckedException,public final void onKernalStop(boolean) ,public IgniteInternalFuture<?> onReconnected(boolean) throws org.apache.ignite.IgniteCheckedException,public void printMemoryStats() ,public final java.lang.String toString() ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode) ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode, org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) <variables>protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,private final non-sealed boolean enabled,private boolean injected,protected final non-sealed org.apache.ignite.IgniteLogger log,private final Map<org.apache.ignite.spi.IgniteSpi,java.lang.Boolean> spiMap,private final non-sealed org.apache.ignite.spi.indexing.IndexingSpi[] spis
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/loadbalancer/GridLoadBalancerManager.java
|
GridLoadBalancerManager
|
getLoadBalancer
|
class GridLoadBalancerManager extends GridManagerAdapter<LoadBalancingSpi> {
/**
* @param ctx Grid kernal context.
*/
public GridLoadBalancerManager(GridKernalContext ctx) {
super(ctx, ctx.config().getLoadBalancingSpi());
}
/** {@inheritDoc} */
@Override public void start() throws IgniteCheckedException {
startSpi();
if (log.isDebugEnabled())
log.debug(startInfo());
}
/** {@inheritDoc} */
@Override public void stop(boolean cancel) throws IgniteCheckedException {
stopSpi();
if (log.isDebugEnabled())
log.debug(stopInfo());
}
/**
* @param ses Task session.
* @param top Task topology.
* @param job Job to balance.
* @return Next balanced node.
* @throws IgniteException If anything failed.
*/
public ClusterNode getBalancedNode(GridTaskSessionImpl ses, List<ClusterNode> top, ComputeJob job)
throws IgniteException {
assert ses != null;
assert top != null;
assert job != null;
LoadBalancingSpi spi = getSpi(ses.getLoadBalancingSpi());
if (ses.isInternal() && !(spi instanceof RoundRobinLoadBalancingSpi))
return getSpi(RoundRobinLoadBalancingSpi.class.getSimpleName()).getBalancedNode(ses, top, job);
return spi.getBalancedNode(ses, top, job);
}
/**
* @param ses Grid task session.
* @param top Task topology.
* @return Load balancer.
*/
@SuppressWarnings("ExternalizableWithoutPublicNoArgConstructor")
public ComputeLoadBalancer getLoadBalancer(final GridTaskSessionImpl ses, final List<ClusterNode> top) {<FILL_FUNCTION_BODY>}
}
|
assert ses != null;
// Return value is not intended for sending over network.
return new GridLoadBalancerAdapter() {
@Nullable @Override public ClusterNode getBalancedNode(ComputeJob job, @Nullable Collection<ClusterNode> exclNodes) {
A.notNull(job, "job");
if (F.isEmpty(exclNodes))
return GridLoadBalancerManager.this.getBalancedNode(ses, top, job);
List<ClusterNode> nodes = F.loseList(top, true, exclNodes);
if (nodes.isEmpty())
return null;
// Exclude list of nodes from topology.
return GridLoadBalancerManager.this.getBalancedNode(ses, nodes, job);
}
};
| 498
| 193
| 691
|
<methods>public void collectGridNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public void collectJoiningNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public org.apache.ignite.internal.GridComponent.DiscoveryDataExchangeType discoveryDataType() ,public boolean enabled() ,public void onAfterSpiStart() ,public void onBeforeSpiStart() ,public void onDisconnected(IgniteFuture<?>) throws org.apache.ignite.IgniteCheckedException,public void onGridDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.GridDiscoveryData) ,public void onJoiningNodeDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) ,public final void onKernalStart(boolean) throws org.apache.ignite.IgniteCheckedException,public final void onKernalStop(boolean) ,public IgniteInternalFuture<?> onReconnected(boolean) throws org.apache.ignite.IgniteCheckedException,public void printMemoryStats() ,public final java.lang.String toString() ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode) ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode, org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) <variables>protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,private final non-sealed boolean enabled,private boolean injected,protected final non-sealed org.apache.ignite.IgniteLogger log,private final Map<org.apache.ignite.spi.IgniteSpi,java.lang.Boolean> spiMap,private final non-sealed org.apache.ignite.spi.loadbalancing.LoadBalancingSpi[] spis
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/FiltrableSystemViewAdapter.java
|
FiltrableSystemViewAdapter
|
iterator
|
class FiltrableSystemViewAdapter<R, D> extends AbstractSystemView<R> implements FiltrableSystemView<R> {
/** Data supplier for the view. */
private Function<Map<String, Object>, Iterable<D>> dataSupplier;
/** Row function. */
private final Function<D, R> rowFunc;
/**
* @param name Name.
* @param desc Description.
* @param walker Walker.
* @param dataSupplier Data supplier.
* @param rowFunc Row function.
*/
public FiltrableSystemViewAdapter(String name, String desc, SystemViewRowAttributeWalker<R> walker,
Function<Map<String, Object>, Iterable<D>> dataSupplier, Function<D, R> rowFunc) {
super(name, desc, walker);
A.notNull(dataSupplier, "dataSupplier");
this.dataSupplier = dataSupplier;
this.rowFunc = rowFunc;
}
/** {@inheritDoc} */
@NotNull @Override public Iterator<R> iterator(Map<String, Object> filter) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@NotNull @Override public Iterator<R> iterator() {
return iterator(Collections.emptyMap());
}
/** {@inheritDoc} */
@Override public int size() {
return F.size(dataSupplier.apply(Collections.emptyMap()).iterator());
}
}
|
if (filter == null)
filter = Collections.emptyMap();
return F.iterator(dataSupplier.apply(filter), rowFunc::apply, true);
| 374
| 44
| 418
|
<methods>public java.lang.String description() ,public java.lang.String name() ,public SystemViewRowAttributeWalker<R> walker() <variables>private final non-sealed java.lang.String desc,private final non-sealed java.lang.String name,private final non-sealed SystemViewRowAttributeWalker<R> walker
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/SqlViewExporterSpi.java
|
SqlViewExporterSpi
|
register
|
class SqlViewExporterSpi extends AbstractSystemViewExporterSpi {
/** */
private GridKernalContext ctx;
/** {@inheritDoc} */
@Override protected void onContextInitialized0(IgniteSpiContext spiCtx) throws IgniteSpiException {
ctx = ((IgniteEx)ignite()).context();
sysViewReg.forEach(this::register);
sysViewReg.addSystemViewCreationListener(this::register);
}
/**
* Registers system view as SQL View.
*
* @param sysView System view.
*/
private void register(SystemView<?> sysView) {<FILL_FUNCTION_BODY>}
}
|
if (log.isDebugEnabled())
log.debug("Found new system view [name=" + sysView.name() + ']');
ctx.query().schemaManager().createSystemView(SCHEMA_SYS, sysView);
| 175
| 61
| 236
|
<methods>public non-sealed void <init>() ,public void setExportFilter(Predicate<SystemView<?>>) ,public void setSystemViewRegistry(org.apache.ignite.spi.systemview.ReadOnlySystemViewRegistry) ,public void spiStart(java.lang.String) throws org.apache.ignite.spi.IgniteSpiException,public void spiStop() throws org.apache.ignite.spi.IgniteSpiException<variables>protected Predicate<SystemView<?>> filter,protected org.apache.ignite.spi.systemview.ReadOnlySystemViewRegistry sysViewReg
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/BinaryMetadataViewWalker.java
|
BinaryMetadataViewWalker
|
visitAll
|
class BinaryMetadataViewWalker implements SystemViewRowAttributeWalker<BinaryMetadataView> {
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void visitAll(BinaryMetadataView row, AttributeWithValueVisitor v) {
v.acceptInt(0, "typeId", row.typeId());
v.accept(1, "typeName", String.class, row.typeName());
v.accept(2, "affKeyFieldName", String.class, row.affKeyFieldName());
v.acceptInt(3, "fieldsCount", row.fieldsCount());
v.accept(4, "fields", String.class, row.fields());
v.accept(5, "schemasIds", String.class, row.schemasIds());
v.acceptBoolean(6, "isEnum", row.isEnum());
}
/** {@inheritDoc} */
@Override public int count() {
return 7;
}
}
|
v.accept(0, "typeId", int.class);
v.accept(1, "typeName", String.class);
v.accept(2, "affKeyFieldName", String.class);
v.accept(3, "fieldsCount", int.class);
v.accept(4, "fields", String.class);
v.accept(5, "schemasIds", String.class);
v.accept(6, "isEnum", boolean.class);
| 260
| 116
| 376
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/ClientConnectionViewWalker.java
|
ClientConnectionViewWalker
|
visitAll
|
class ClientConnectionViewWalker implements SystemViewRowAttributeWalker<ClientConnectionView> {
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {
v.accept(0, "connectionId", long.class);
v.accept(1, "localAddress", InetSocketAddress.class);
v.accept(2, "remoteAddress", InetSocketAddress.class);
v.accept(3, "type", String.class);
v.accept(4, "user", String.class);
v.accept(5, "version", String.class);
}
/** {@inheritDoc} */
@Override public void visitAll(ClientConnectionView row, AttributeWithValueVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int count() {
return 6;
}
}
|
v.acceptLong(0, "connectionId", row.connectionId());
v.accept(1, "localAddress", InetSocketAddress.class, row.localAddress());
v.accept(2, "remoteAddress", InetSocketAddress.class, row.remoteAddress());
v.accept(3, "type", String.class, row.type());
v.accept(4, "user", String.class, row.user());
v.accept(5, "version", String.class, row.version());
| 218
| 126
| 344
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/ComputeJobViewWalker.java
|
ComputeJobViewWalker
|
visitAll
|
class ComputeJobViewWalker implements SystemViewRowAttributeWalker<ComputeJobView> {
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {
v.accept(0, "id", IgniteUuid.class);
v.accept(1, "sessionId", IgniteUuid.class);
v.accept(2, "originNodeId", UUID.class);
v.accept(3, "taskName", String.class);
v.accept(4, "taskClassName", String.class);
v.accept(5, "affinityCacheIds", String.class);
v.accept(6, "affinityPartitionId", int.class);
v.accept(7, "createTime", long.class);
v.accept(8, "startTime", long.class);
v.accept(9, "finishTime", long.class);
v.accept(10, "executorName", String.class);
v.accept(11, "isFinishing", boolean.class);
v.accept(12, "isInternal", boolean.class);
v.accept(13, "isStarted", boolean.class);
v.accept(14, "isTimedOut", boolean.class);
v.accept(15, "state", ComputeJobState.class);
}
/** {@inheritDoc} */
@Override public void visitAll(ComputeJobView row, AttributeWithValueVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int count() {
return 16;
}
}
|
v.accept(0, "id", IgniteUuid.class, row.id());
v.accept(1, "sessionId", IgniteUuid.class, row.sessionId());
v.accept(2, "originNodeId", UUID.class, row.originNodeId());
v.accept(3, "taskName", String.class, row.taskName());
v.accept(4, "taskClassName", String.class, row.taskClassName());
v.accept(5, "affinityCacheIds", String.class, row.affinityCacheIds());
v.acceptInt(6, "affinityPartitionId", row.affinityPartitionId());
v.acceptLong(7, "createTime", row.createTime());
v.acceptLong(8, "startTime", row.startTime());
v.acceptLong(9, "finishTime", row.finishTime());
v.accept(10, "executorName", String.class, row.executorName());
v.acceptBoolean(11, "isFinishing", row.isFinishing());
v.acceptBoolean(12, "isInternal", row.isInternal());
v.acceptBoolean(13, "isStarted", row.isStarted());
v.acceptBoolean(14, "isTimedOut", row.isTimedOut());
v.accept(15, "state", ComputeJobState.class, row.state());
| 404
| 350
| 754
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/PagesListViewWalker.java
|
PagesListViewWalker
|
visitAll
|
class PagesListViewWalker implements SystemViewRowAttributeWalker<PagesListView> {
/** Filter key for attribute "bucketNumber" */
public static final String BUCKET_NUMBER_FILTER = "bucketNumber";
/** List of filtrable attributes. */
private static final List<String> FILTRABLE_ATTRS = Collections.unmodifiableList(F.asList(
"bucketNumber"
));
/** {@inheritDoc} */
@Override public List<String> filtrableAttributes() {
return FILTRABLE_ATTRS;
}
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void visitAll(PagesListView row, AttributeWithValueVisitor v) {
v.accept(0, "name", String.class, row.name());
v.acceptInt(1, "bucketNumber", row.bucketNumber());
v.acceptLong(2, "bucketSize", row.bucketSize());
v.acceptInt(3, "stripesCount", row.stripesCount());
v.acceptInt(4, "cachedPagesCount", row.cachedPagesCount());
v.acceptInt(5, "pageFreeSpace", row.pageFreeSpace());
}
/** {@inheritDoc} */
@Override public int count() {
return 6;
}
}
|
v.accept(0, "name", String.class);
v.accept(1, "bucketNumber", int.class);
v.accept(2, "bucketSize", long.class);
v.accept(3, "stripesCount", int.class);
v.accept(4, "cachedPagesCount", int.class);
v.accept(5, "pageFreeSpace", int.class);
| 365
| 104
| 469
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/PartitionStateViewWalker.java
|
PartitionStateViewWalker
|
visitAll
|
class PartitionStateViewWalker implements SystemViewRowAttributeWalker<PartitionStateView> {
/** Filter key for attribute "cacheGroupId" */
public static final String CACHE_GROUP_ID_FILTER = "cacheGroupId";
/** Filter key for attribute "nodeId" */
public static final String NODE_ID_FILTER = "nodeId";
/** Filter key for attribute "partitionId" */
public static final String PARTITION_ID_FILTER = "partitionId";
/** List of filtrable attributes. */
private static final List<String> FILTRABLE_ATTRS = Collections.unmodifiableList(F.asList(
"cacheGroupId", "nodeId", "partitionId"
));
/** {@inheritDoc} */
@Override public List<String> filtrableAttributes() {
return FILTRABLE_ATTRS;
}
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {
v.accept(0, "cacheGroupId", int.class);
v.accept(1, "nodeId", UUID.class);
v.accept(2, "partitionId", int.class);
v.accept(3, "state", String.class);
v.accept(4, "isPrimary", boolean.class);
}
/** {@inheritDoc} */
@Override public void visitAll(PartitionStateView row, AttributeWithValueVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int count() {
return 5;
}
}
|
v.acceptInt(0, "cacheGroupId", row.cacheGroupId());
v.accept(1, "nodeId", UUID.class, row.nodeId());
v.acceptInt(2, "partitionId", row.partitionId());
v.accept(3, "state", String.class, row.state());
v.acceptBoolean(4, "isPrimary", row.isPrimary());
| 398
| 99
| 497
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/ReentrantLockViewWalker.java
|
ReentrantLockViewWalker
|
visitAll
|
class ReentrantLockViewWalker implements SystemViewRowAttributeWalker<ReentrantLockView> {
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void visitAll(ReentrantLockView row, AttributeWithValueVisitor v) {
v.accept(0, "name", String.class, row.name());
v.acceptBoolean(1, "locked", row.locked());
v.acceptBoolean(2, "hasQueuedThreads", row.hasQueuedThreads());
v.acceptBoolean(3, "failoverSafe", row.failoverSafe());
v.acceptBoolean(4, "fair", row.fair());
v.acceptBoolean(5, "broken", row.broken());
v.accept(6, "groupName", String.class, row.groupName());
v.acceptInt(7, "groupId", row.groupId());
v.acceptBoolean(8, "removed", row.removed());
}
/** {@inheritDoc} */
@Override public int count() {
return 9;
}
}
|
v.accept(0, "name", String.class);
v.accept(1, "locked", boolean.class);
v.accept(2, "hasQueuedThreads", boolean.class);
v.accept(3, "failoverSafe", boolean.class);
v.accept(4, "fair", boolean.class);
v.accept(5, "broken", boolean.class);
v.accept(6, "groupName", String.class);
v.accept(7, "groupId", int.class);
v.accept(8, "removed", boolean.class);
| 293
| 147
| 440
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/ScanQueryViewWalker.java
|
ScanQueryViewWalker
|
visitAll
|
class ScanQueryViewWalker implements SystemViewRowAttributeWalker<ScanQueryView> {
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void visitAll(ScanQueryView row, AttributeWithValueVisitor v) {
v.accept(0, "originNodeId", UUID.class, row.originNodeId());
v.acceptLong(1, "queryId", row.queryId());
v.accept(2, "cacheName", String.class, row.cacheName());
v.acceptInt(3, "cacheId", row.cacheId());
v.acceptInt(4, "cacheGroupId", row.cacheGroupId());
v.accept(5, "cacheGroupName", String.class, row.cacheGroupName());
v.acceptLong(6, "startTime", row.startTime());
v.acceptLong(7, "duration", row.duration());
v.acceptBoolean(8, "canceled", row.canceled());
v.accept(9, "filter", String.class, row.filter());
v.acceptBoolean(10, "keepBinary", row.keepBinary());
v.acceptBoolean(11, "local", row.local());
v.acceptInt(12, "pageSize", row.pageSize());
v.acceptInt(13, "partition", row.partition());
v.accept(14, "subjectId", UUID.class, row.subjectId());
v.accept(15, "taskName", String.class, row.taskName());
v.accept(16, "topology", String.class, row.topology());
v.accept(17, "transformer", String.class, row.transformer());
}
/** {@inheritDoc} */
@Override public int count() {
return 18;
}
}
|
v.accept(0, "originNodeId", UUID.class);
v.accept(1, "queryId", long.class);
v.accept(2, "cacheName", String.class);
v.accept(3, "cacheId", int.class);
v.accept(4, "cacheGroupId", int.class);
v.accept(5, "cacheGroupName", String.class);
v.accept(6, "startTime", long.class);
v.accept(7, "duration", long.class);
v.accept(8, "canceled", boolean.class);
v.accept(9, "filter", String.class);
v.accept(10, "keepBinary", boolean.class);
v.accept(11, "local", boolean.class);
v.accept(12, "pageSize", int.class);
v.accept(13, "partition", int.class);
v.accept(14, "subjectId", UUID.class);
v.accept(15, "taskName", String.class);
v.accept(16, "topology", String.class);
v.accept(17, "transformer", String.class);
| 472
| 297
| 769
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/SemaphoreViewWalker.java
|
SemaphoreViewWalker
|
visitAll
|
class SemaphoreViewWalker implements SystemViewRowAttributeWalker<SemaphoreView> {
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {
v.accept(0, "name", String.class);
v.accept(1, "availablePermits", long.class);
v.accept(2, "hasQueuedThreads", boolean.class);
v.accept(3, "queueLength", int.class);
v.accept(4, "failoverSafe", boolean.class);
v.accept(5, "broken", boolean.class);
v.accept(6, "groupName", String.class);
v.accept(7, "groupId", int.class);
v.accept(8, "removed", boolean.class);
}
/** {@inheritDoc} */
@Override public void visitAll(SemaphoreView row, AttributeWithValueVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int count() {
return 9;
}
}
|
v.accept(0, "name", String.class, row.name());
v.acceptLong(1, "availablePermits", row.availablePermits());
v.acceptBoolean(2, "hasQueuedThreads", row.hasQueuedThreads());
v.acceptInt(3, "queueLength", row.queueLength());
v.acceptBoolean(4, "failoverSafe", row.failoverSafe());
v.acceptBoolean(5, "broken", row.broken());
v.accept(6, "groupName", String.class, row.groupName());
v.acceptInt(7, "groupId", row.groupId());
v.acceptBoolean(8, "removed", row.removed());
| 268
| 175
| 443
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/SetViewWalker.java
|
SetViewWalker
|
visitAll
|
class SetViewWalker implements SystemViewRowAttributeWalker<SetView> {
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {
v.accept(0, "id", IgniteUuid.class);
v.accept(1, "name", String.class);
v.accept(2, "size", int.class);
v.accept(3, "groupName", String.class);
v.accept(4, "groupId", int.class);
v.accept(5, "collocated", boolean.class);
v.accept(6, "removed", boolean.class);
}
/** {@inheritDoc} */
@Override public void visitAll(SetView row, AttributeWithValueVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int count() {
return 7;
}
}
|
v.accept(0, "id", IgniteUuid.class, row.id());
v.accept(1, "name", String.class, row.name());
v.acceptInt(2, "size", row.size());
v.accept(3, "groupName", String.class, row.groupName());
v.acceptInt(4, "groupId", row.groupId());
v.acceptBoolean(5, "collocated", row.collocated());
v.acceptBoolean(6, "removed", row.removed());
| 228
| 135
| 363
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/SqlQueryHistoryViewWalker.java
|
SqlQueryHistoryViewWalker
|
visitAll
|
class SqlQueryHistoryViewWalker implements SystemViewRowAttributeWalker<SqlQueryHistoryView> {
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {
v.accept(0, "schemaName", String.class);
v.accept(1, "sql", String.class);
v.accept(2, "local", boolean.class);
v.accept(3, "executions", long.class);
v.accept(4, "failures", long.class);
v.accept(5, "durationMin", long.class);
v.accept(6, "durationMax", long.class);
v.accept(7, "lastStartTime", Date.class);
}
/** {@inheritDoc} */
@Override public void visitAll(SqlQueryHistoryView row, AttributeWithValueVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int count() {
return 8;
}
}
|
v.accept(0, "schemaName", String.class, row.schemaName());
v.accept(1, "sql", String.class, row.sql());
v.acceptBoolean(2, "local", row.local());
v.acceptLong(3, "executions", row.executions());
v.acceptLong(4, "failures", row.failures());
v.acceptLong(5, "durationMin", row.durationMin());
v.acceptLong(6, "durationMax", row.durationMax());
v.accept(7, "lastStartTime", Date.class, row.lastStartTime());
| 249
| 154
| 403
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/SqlQueryViewWalker.java
|
SqlQueryViewWalker
|
visitAll
|
class SqlQueryViewWalker implements SystemViewRowAttributeWalker<SqlQueryView> {
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {
v.accept(0, "queryId", String.class);
v.accept(1, "sql", String.class);
v.accept(2, "originNodeId", UUID.class);
v.accept(3, "startTime", Date.class);
v.accept(4, "duration", long.class);
v.accept(5, "initiatorId", String.class);
v.accept(6, "local", boolean.class);
v.accept(7, "schemaName", String.class);
v.accept(8, "subjectId", UUID.class);
}
/** {@inheritDoc} */
@Override public void visitAll(SqlQueryView row, AttributeWithValueVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int count() {
return 9;
}
}
|
v.accept(0, "queryId", String.class, row.queryId());
v.accept(1, "sql", String.class, row.sql());
v.accept(2, "originNodeId", UUID.class, row.originNodeId());
v.accept(3, "startTime", Date.class, row.startTime());
v.acceptLong(4, "duration", row.duration());
v.accept(5, "initiatorId", String.class, row.initiatorId());
v.acceptBoolean(6, "local", row.local());
v.accept(7, "schemaName", String.class, row.schemaName());
v.accept(8, "subjectId", UUID.class, row.subjectId());
| 263
| 186
| 449
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/SqlViewColumnViewWalker.java
|
SqlViewColumnViewWalker
|
visitAll
|
class SqlViewColumnViewWalker implements SystemViewRowAttributeWalker<SqlViewColumnView> {
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {
v.accept(0, "columnName", String.class);
v.accept(1, "viewName", String.class);
v.accept(2, "schemaName", String.class);
v.accept(3, "defaultValue", String.class);
v.accept(4, "nullable", boolean.class);
v.accept(5, "precision", int.class);
v.accept(6, "scale", int.class);
v.accept(7, "type", String.class);
}
/** {@inheritDoc} */
@Override public void visitAll(SqlViewColumnView row, AttributeWithValueVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int count() {
return 8;
}
}
|
v.accept(0, "columnName", String.class, row.columnName());
v.accept(1, "viewName", String.class, row.viewName());
v.accept(2, "schemaName", String.class, row.schemaName());
v.accept(3, "defaultValue", String.class, row.defaultValue());
v.acceptBoolean(4, "nullable", row.nullable());
v.acceptInt(5, "precision", row.precision());
v.acceptInt(6, "scale", row.scale());
v.accept(7, "type", String.class, row.type());
| 248
| 158
| 406
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/SqlViewViewWalker.java
|
SqlViewViewWalker
|
visitAll
|
class SqlViewViewWalker implements SystemViewRowAttributeWalker<SqlViewView> {
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void visitAll(SqlViewView row, AttributeWithValueVisitor v) {
v.accept(0, "name", String.class, row.name());
v.accept(1, "schema", String.class, row.schema());
v.accept(2, "description", String.class, row.description());
}
/** {@inheritDoc} */
@Override public int count() {
return 3;
}
}
|
v.accept(0, "name", String.class);
v.accept(1, "schema", String.class);
v.accept(2, "description", String.class);
| 176
| 48
| 224
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/StatisticsColumnGlobalDataViewWalker.java
|
StatisticsColumnGlobalDataViewWalker
|
visitAll
|
class StatisticsColumnGlobalDataViewWalker implements SystemViewRowAttributeWalker<StatisticsColumnGlobalDataView> {
/** Filter key for attribute "schema" */
public static final String SCHEMA_FILTER = "schema";
/** Filter key for attribute "type" */
public static final String TYPE_FILTER = "type";
/** Filter key for attribute "name" */
public static final String NAME_FILTER = "name";
/** Filter key for attribute "column" */
public static final String COLUMN_FILTER = "column";
/** List of filtrable attributes. */
private static final List<String> FILTRABLE_ATTRS = Collections.unmodifiableList(F.asList(
"schema", "type", "name", "column"
));
/** {@inheritDoc} */
@Override public List<String> filtrableAttributes() {
return FILTRABLE_ATTRS;
}
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {
v.accept(0, "schema", String.class);
v.accept(1, "type", String.class);
v.accept(2, "name", String.class);
v.accept(3, "column", String.class);
v.accept(4, "rowsCount", long.class);
v.accept(5, "distinct", long.class);
v.accept(6, "nulls", long.class);
v.accept(7, "total", long.class);
v.accept(8, "size", int.class);
v.accept(9, "version", long.class);
v.accept(10, "lastUpdateTime", Timestamp.class);
}
/** {@inheritDoc} */
@Override public void visitAll(StatisticsColumnGlobalDataView row, AttributeWithValueVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int count() {
return 11;
}
}
|
v.accept(0, "schema", String.class, row.schema());
v.accept(1, "type", String.class, row.type());
v.accept(2, "name", String.class, row.name());
v.accept(3, "column", String.class, row.column());
v.acceptLong(4, "rowsCount", row.rowsCount());
v.acceptLong(5, "distinct", row.distinct());
v.acceptLong(6, "nulls", row.nulls());
v.acceptLong(7, "total", row.total());
v.acceptInt(8, "size", row.size());
v.acceptLong(9, "version", row.version());
v.accept(10, "lastUpdateTime", Timestamp.class, row.lastUpdateTime());
| 509
| 206
| 715
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/TransactionViewWalker.java
|
TransactionViewWalker
|
visitAll
|
class TransactionViewWalker implements SystemViewRowAttributeWalker<TransactionView> {
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {
v.accept(0, "originatingNodeId", UUID.class);
v.accept(1, "state", TransactionState.class);
v.accept(2, "xid", IgniteUuid.class);
v.accept(3, "label", String.class);
v.accept(4, "startTime", long.class);
v.accept(5, "isolation", TransactionIsolation.class);
v.accept(6, "concurrency", TransactionConcurrency.class);
v.accept(7, "keysCount", int.class);
v.accept(8, "cacheIds", String.class);
v.accept(9, "colocated", boolean.class);
v.accept(10, "dht", boolean.class);
v.accept(11, "duration", long.class);
v.accept(12, "implicit", boolean.class);
v.accept(13, "implicitSingle", boolean.class);
v.accept(14, "internal", boolean.class);
v.accept(15, "local", boolean.class);
v.accept(16, "localNodeId", UUID.class);
v.accept(17, "near", boolean.class);
v.accept(18, "onePhaseCommit", boolean.class);
v.accept(19, "otherNodeId", UUID.class);
v.accept(20, "subjectId", UUID.class);
v.accept(21, "system", boolean.class);
v.accept(22, "threadId", long.class);
v.accept(23, "timeout", long.class);
v.accept(24, "topVer", String.class);
}
/** {@inheritDoc} */
@Override public void visitAll(TransactionView row, AttributeWithValueVisitor v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int count() {
return 25;
}
}
|
v.accept(0, "originatingNodeId", UUID.class, row.originatingNodeId());
v.accept(1, "state", TransactionState.class, row.state());
v.accept(2, "xid", IgniteUuid.class, row.xid());
v.accept(3, "label", String.class, row.label());
v.acceptLong(4, "startTime", row.startTime());
v.accept(5, "isolation", TransactionIsolation.class, row.isolation());
v.accept(6, "concurrency", TransactionConcurrency.class, row.concurrency());
v.acceptInt(7, "keysCount", row.keysCount());
v.accept(8, "cacheIds", String.class, row.cacheIds());
v.acceptBoolean(9, "colocated", row.colocated());
v.acceptBoolean(10, "dht", row.dht());
v.acceptLong(11, "duration", row.duration());
v.acceptBoolean(12, "implicit", row.implicit());
v.acceptBoolean(13, "implicitSingle", row.implicitSingle());
v.acceptBoolean(14, "internal", row.internal());
v.acceptBoolean(15, "local", row.local());
v.accept(16, "localNodeId", UUID.class, row.localNodeId());
v.acceptBoolean(17, "near", row.near());
v.acceptBoolean(18, "onePhaseCommit", row.onePhaseCommit());
v.accept(19, "otherNodeId", UUID.class, row.otherNodeId());
v.accept(20, "subjectId", UUID.class, row.subjectId());
v.acceptBoolean(21, "system", row.system());
v.acceptLong(22, "threadId", row.threadId());
v.acceptLong(23, "timeout", row.timeout());
v.accept(24, "topVer", String.class, row.topVer());
| 544
| 512
| 1,056
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/OptimizedObjectSharedStreamRegistry.java
|
OptimizedObjectSharedStreamRegistry
|
closeIn
|
class OptimizedObjectSharedStreamRegistry extends OptimizedObjectStreamRegistry {
/** */
private static final ThreadLocal<StreamHolder> holders = new ThreadLocal<>();
/** {@inheritDoc} */
@Override OptimizedObjectOutputStream out() {
return holder().acquireOut();
}
/** {@inheritDoc} */
@Override OptimizedObjectInputStream in() {
return holder().acquireIn();
}
/** {@inheritDoc} */
@Override void closeOut(OptimizedObjectOutputStream out) {
U.close(out, null);
StreamHolder holder = holders.get();
if (holder != null)
holder.releaseOut();
}
/** {@inheritDoc} */
@Override void closeIn(OptimizedObjectInputStream in) {<FILL_FUNCTION_BODY>}
/**
* Closes and releases not cached input stream.
*
* @param in Object input stream.
*/
void closeNotCachedIn(OptimizedObjectInputStream in) {
U.close(in, null);
StreamHolder holder = holders.get();
if (holder != null) {
holder.releaseIn();
holders.set(null);
}
}
/**
* Gets holder from pool or thread local.
*
* @return Stream holder.
*/
private static StreamHolder holder() {
StreamHolder holder = holders.get();
if (holder == null)
holders.set(holder = new StreamHolder());
return holder;
}
/**
* Streams holder.
*/
private static class StreamHolder {
/** Output stream. */
private final OptimizedObjectOutputStream out = createOut();
/** Input stream. */
private final OptimizedObjectInputStream in = createIn();
/** Output streams counter. */
private int outAcquireCnt;
/** Input streams counter. */
private int inAcquireCnt;
/**
* Gets output stream.
*
* @return Object output stream.
*/
OptimizedObjectOutputStream acquireOut() {
return outAcquireCnt++ > 0 ? createOut() : out;
}
/**
* Gets input stream.
*
* @return Object input stream.
*/
OptimizedObjectInputStream acquireIn() {
return inAcquireCnt++ > 0 ? createIn() : in;
}
/**
* Releases output stream.
*/
void releaseOut() {
outAcquireCnt--;
}
/**
* Releases input stream.
*/
void releaseIn() {
inAcquireCnt--;
}
}
}
|
U.close(in, null);
StreamHolder holder = holders.get();
if (holder != null)
holder.releaseIn();
| 681
| 42
| 723
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/OptimizedObjectStreamRegistry.java
|
OptimizedObjectStreamRegistry
|
createIn
|
class OptimizedObjectStreamRegistry {
/**
* Gets output stream.
*
* @return Object output stream.
* @throws org.apache.ignite.internal.IgniteInterruptedCheckedException If thread is interrupted while trying to take holder from pool.
*/
abstract OptimizedObjectOutputStream out() throws IgniteInterruptedCheckedException;
/**
* Gets input stream.
*
* @return Object input stream.
* @throws org.apache.ignite.internal.IgniteInterruptedCheckedException If thread is interrupted while trying to take holder from pool.
*/
abstract OptimizedObjectInputStream in() throws IgniteInterruptedCheckedException;
/**
* Closes and releases output stream.
*
* @param out Object output stream.
*/
abstract void closeOut(OptimizedObjectOutputStream out);
/**
* Closes and releases input stream.
*
* @param in Object input stream.
*/
abstract void closeIn(OptimizedObjectInputStream in);
/**
* Creates output stream.
*
* @return Object output stream.
*/
static OptimizedObjectOutputStream createOut() {
try {
return new OptimizedObjectOutputStream(new GridUnsafeDataOutput(4 * 1024));
}
catch (IOException e) {
throw new IgniteException("Failed to create object output stream.", e);
}
}
/**
* Creates input stream.
*
* @return Object input stream.
*/
static OptimizedObjectInputStream createIn() {<FILL_FUNCTION_BODY>}
}
|
try {
return new OptimizedObjectInputStream(new GridUnsafeDataInput());
}
catch (IOException e) {
throw new IgniteException("Failed to create object input stream.", e);
}
| 401
| 54
| 455
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/PageUtils.java
|
PageUtils
|
getBytes
|
class PageUtils {
/**
* @param addr Start address.
* @param off Offset.
* @return Byte value from given address.
*/
public static byte getByte(long addr, int off) {
assert addr > 0 : addr;
assert off >= 0;
return GridUnsafe.getByte(addr + off);
}
/**
*
* @param addr Start address.
* @param off Offset.
* @return Byte value from given address.
*/
public static int getUnsignedByte(long addr, int off) {
assert addr > 0 : addr;
assert off >= 0;
return GridUnsafe.getByte(addr + off) & 0xFF;
}
/**
* @param addr Start address.
* @param off Offset.
* @param len Bytes length.
* @return Bytes from given address.
*/
public static byte[] getBytes(long addr, int off, int len) {
assert addr > 0 : addr;
assert off >= 0;
assert len >= 0;
byte[] bytes = new byte[len];
GridUnsafe.copyMemory(null, addr + off, bytes, GridUnsafe.BYTE_ARR_OFF, len);
return bytes;
}
/**
* @param srcAddr Source address.
* @param srcOff Source offset.
* @param dst Destination array.
* @param dstOff Destination offset.
* @param len Length.
*/
public static void getBytes(long srcAddr, int srcOff, byte[] dst, int dstOff, int len) {<FILL_FUNCTION_BODY>}
/**
* @param addr Address.
* @param off Offset.
* @return Value.
*/
public static short getShort(long addr, int off) {
assert addr > 0 : addr;
assert off >= 0;
return GridUnsafe.getShort(addr + off);
}
/**
* @param addr Address.
* @param off Offset.
* @return Value.
*/
public static int getInt(long addr, int off) {
assert addr > 0 : addr;
assert off >= 0;
return GridUnsafe.getInt(addr + off);
}
/**
* @param addr Address.
* @param off Offset.
* @return Value.
*/
public static long getLong(long addr, int off) {
assert addr > 0 : addr;
assert off >= 0;
return GridUnsafe.getLong(addr + off);
}
/**
* @param addr Address.
* @param off Offset.
* @param bytes Bytes.
*/
public static void putBytes(long addr, int off, byte[] bytes) {
assert addr > 0 : addr;
assert off >= 0;
assert bytes != null;
GridUnsafe.copyMemory(bytes, GridUnsafe.BYTE_ARR_OFF, null, addr + off, bytes.length);
}
/**
* @param addr Address.
* @param off Offset.
* @param bytes Bytes array.
* @param bytesOff Bytes array offset.
*/
public static void putBytes(long addr, int off, byte[] bytes, int bytesOff) {
assert addr > 0 : addr;
assert off >= 0;
assert bytes != null;
assert bytesOff >= 0 && (bytesOff < bytes.length || bytes.length == 0) : bytesOff;
GridUnsafe.copyMemory(bytes, GridUnsafe.BYTE_ARR_OFF + bytesOff, null, addr + off, bytes.length - bytesOff);
}
/**
* @param addr Address.
* @param off Offset.
* @param bytes Bytes array.
* @param bytesOff Bytes array offset.
* @param len Length.
*/
public static void putBytes(long addr, int off, byte[] bytes, int bytesOff, int len) {
assert addr > 0 : addr;
assert off >= 0;
assert bytes != null;
assert bytesOff >= 0 && (bytesOff < bytes.length || bytes.length == 0) : bytesOff;
GridUnsafe.copyMemory(bytes, GridUnsafe.BYTE_ARR_OFF + bytesOff, null, addr + off, len);
}
/**
* @param addr Address.
* @param off Offset.
* @param v Value.
*/
public static void putByte(long addr, int off, byte v) {
assert addr > 0 : addr;
assert off >= 0;
GridUnsafe.putByte(addr + off, v);
}
/**
* @param addr Address.
* @param off Offset.
* @param v Value.
*/
public static void putUnsignedByte(long addr, int off, int v) {
assert addr > 0 : addr;
assert off >= 0;
assert v >= 0 && v <= 255;
GridUnsafe.putByte(addr + off, (byte)v);
}
/**
* @param addr Address.
* @param off Offset.
* @param v Value.
*/
public static void putShort(long addr, int off, short v) {
assert addr > 0 : addr;
assert off >= 0;
GridUnsafe.putShort(addr + off, v);
}
/**
* @param addr Address.
* @param off Offset.
* @param v Value.
*/
public static void putInt(long addr, int off, int v) {
assert addr > 0 : addr;
assert off >= 0;
GridUnsafe.putInt(addr + off, v);
}
/**
* @param addr Address.
* @param off Offset.
* @param v Value.
*/
public static void putLong(long addr, int off, long v) {
assert addr > 0 : addr;
assert off >= 0;
GridUnsafe.putLong(addr + off, v);
}
}
|
assert srcAddr > 0;
assert srcOff > 0;
assert dst != null;
assert dstOff >= 0;
assert len >= 0;
GridUnsafe.copyMemory(null, srcAddr + srcOff, dst, GridUnsafe.BYTE_ARR_OFF + dstOff, len);
| 1,555
| 82
| 1,637
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/DataEntry.java
|
DataEntry
|
flags
|
class DataEntry {
/** Empty flags. */
public static final byte EMPTY_FLAGS = 0;
/** */
public static final byte PRIMARY_FLAG = 0b00000001;
/** */
public static final byte PRELOAD_FLAG = 0b00000010;
/** */
public static final byte FROM_STORE_FLAG = 0b00000100;
/** Cache ID. */
@GridToStringInclude
protected int cacheId;
/** Cache object key. */
protected KeyCacheObject key;
/** Cache object value. May be {@code} null for {@link GridCacheOperation#DELETE} */
@Nullable protected CacheObject val;
/** Entry operation performed. */
@GridToStringInclude
protected GridCacheOperation op;
/** Near transaction version. */
@GridToStringInclude
protected GridCacheVersion nearXidVer;
/** Write version. */
@GridToStringInclude
protected GridCacheVersion writeVer;
/** Expire time. */
protected long expireTime;
/** Partition ID. */
@GridToStringInclude
protected int partId;
/** */
@GridToStringInclude
protected long partCnt;
/**
* Bit flags.
* <ul>
* <li>0 bit - primary - seted when current node is primary for entry partition.</li>
* <li>1 bit - preload - seted when entry logged during preload(rebalance).</li>
* <li>2 bit - fromStore - seted when entry loaded from third-party store.</li>
* </ul>
*/
@GridToStringInclude
protected byte flags;
/** Constructor. */
private DataEntry() {
// No-op, used from factory methods.
}
/**
* @param cacheId Cache ID.
* @param key Key.
* @param val Value or null for delete operation.
* @param op Operation.
* @param nearXidVer Near transaction version.
* @param writeVer Write version.
* @param expireTime Expire time.
* @param partId Partition ID.
* @param partCnt Partition counter.
* @param flags Entry flags.
*/
public DataEntry(
int cacheId,
KeyCacheObject key,
@Nullable CacheObject val,
GridCacheOperation op,
GridCacheVersion nearXidVer,
GridCacheVersion writeVer,
long expireTime,
int partId,
long partCnt,
byte flags
) {
this.cacheId = cacheId;
this.key = key;
this.val = val;
this.op = op;
this.nearXidVer = nearXidVer;
this.writeVer = writeVer;
this.expireTime = expireTime;
this.partId = partId;
this.partCnt = partCnt;
this.flags = flags;
// Only READ, CREATE, UPDATE and DELETE operations should be stored in WAL.
assert op == GridCacheOperation.READ
|| op == GridCacheOperation.CREATE
|| op == GridCacheOperation.UPDATE
|| op == GridCacheOperation.DELETE : op;
}
/**
* @param primary {@code True} if node is primary for partition in the moment of logging.
* @return Flags value.
*/
public static byte flags(boolean primary) {
return flags(primary, false, false);
}
/**
* @param primary {@code True} if node is primary for partition in the moment of logging.
* @param preload {@code True} if logged during preload(rebalance).
* @param fromStore {@code True} if logged during loading from third-party store.
* @return Flags value.
*/
public static byte flags(boolean primary, boolean preload, boolean fromStore) {<FILL_FUNCTION_BODY>}
/**
* @return Cache ID.
*/
public int cacheId() {
return cacheId;
}
/**
* @return Key cache object.
*/
public KeyCacheObject key() {
return key;
}
/**
* @return Value cache object.
*/
public CacheObject value() {
return val;
}
/**
* @return Cache operation.
*/
public GridCacheOperation op() {
return op;
}
/**
* @return Near transaction version if the write was transactional.
*/
public GridCacheVersion nearXidVersion() {
return nearXidVer;
}
/**
* @return Write version.
*/
public GridCacheVersion writeVersion() {
return writeVer;
}
/**
* @return Partition ID.
*/
public int partitionId() {
return partId;
}
/**
* @return Partition counter.
*/
public long partitionCounter() {
return partCnt;
}
/**
* Sets partition update counter to entry.
*
* @param partCnt Partition update counter.
* @return {@code this} for chaining.
*/
public DataEntry partitionCounter(long partCnt) {
this.partCnt = partCnt;
return this;
}
/**
* @return Expire time.
*/
public long expireTime() {
return expireTime;
}
/**
* Entry flags.
* @see #flags
*/
public byte flags() {
return flags;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(DataEntry.class, this);
}
}
|
byte val = EMPTY_FLAGS;
val |= primary ? PRIMARY_FLAG : EMPTY_FLAGS;
val |= preload ? PRELOAD_FLAG : EMPTY_FLAGS;
val |= fromStore ? FROM_STORE_FLAG : EMPTY_FLAGS;
return val;
| 1,469
| 81
| 1,550
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/IncrementalSnapshotFinishRecord.java
|
IncrementalSnapshotFinishRecord
|
dataSize
|
class IncrementalSnapshotFinishRecord extends WALRecord {
/** Incremental snapshot ID. */
@GridToStringInclude
private final UUID id;
/**
* Set of transactions committed between {@link IncrementalSnapshotStartRecord} and {@link IncrementalSnapshotFinishRecord}
* to include into the incremental snapshot.
*/
@GridToStringInclude
private final Set<GridCacheVersion> included;
/**
* Set of transactions committed before {@link IncrementalSnapshotStartRecord} to exclude from the incremental snapshot.
*/
@GridToStringInclude
private final Set<GridCacheVersion> excluded;
/** */
public IncrementalSnapshotFinishRecord(UUID id, Set<GridCacheVersion> included, Set<GridCacheVersion> excluded) {
this.id = id;
this.included = included;
this.excluded = excluded;
}
/** */
public Set<GridCacheVersion> included() {
return included;
}
/** */
public Set<GridCacheVersion> excluded() {
return excluded;
}
/** */
public UUID id() {
return id;
}
/** {@inheritDoc} */
@Override public RecordType type() {
return RecordType.INCREMENTAL_SNAPSHOT_FINISH_RECORD;
}
/**
* Calculating the size of the record.
*
* @return Size in bytes.
*/
public int dataSize() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(IncrementalSnapshotFinishRecord.class, this);
}
}
|
int size = 16 + 4 + 4; // ID, included and excluded tx count.
for (GridCacheVersion v: included)
size += CacheVersionIO.size(v, false);
for (GridCacheVersion v: excluded)
size += CacheVersionIO.size(v, false);
return size;
| 429
| 83
| 512
|
<methods>public non-sealed void <init>() ,public void chainSize(int) ,public int chainSize() ,public org.apache.ignite.internal.processors.cache.persistence.wal.WALPointer position() ,public void position(org.apache.ignite.internal.processors.cache.persistence.wal.WALPointer) ,public org.apache.ignite.internal.pagemem.wal.record.WALRecord previous() ,public void previous(org.apache.ignite.internal.pagemem.wal.record.WALRecord) ,public int size() ,public void size(int) ,public java.lang.String toString() ,public abstract org.apache.ignite.internal.pagemem.wal.record.WALRecord.RecordType type() <variables>private int chainSize,private org.apache.ignite.internal.processors.cache.persistence.wal.WALPointer pos,private org.apache.ignite.internal.pagemem.wal.record.WALRecord prev,private int size
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/IndexRenameRootPageRecord.java
|
IndexRenameRootPageRecord
|
writeRecord
|
class IndexRenameRootPageRecord extends WALRecord {
/** Cache id. */
private final int cacheId;
/** Old name of underlying index tree name. */
private final String oldTreeName;
/** New name of underlying index tree name. */
private final String newTreeName;
/** Number of segments. */
private final int segments;
/**
* Constructor.
*
* @param cacheId Cache id.
* @param oldTreeName Old name of underlying index tree name.
* @param newTreeName New name of underlying index tree name.
* @param segments Number of segments.
*/
public IndexRenameRootPageRecord(int cacheId, String oldTreeName, String newTreeName, int segments) {
this.cacheId = cacheId;
this.oldTreeName = oldTreeName;
this.newTreeName = newTreeName;
this.segments = segments;
}
/**
* Constructor.
*
* @param in Data input.
* @throws IOException If there are errors while reading the data.
* @see #writeRecord
* @see #dataSize
*/
public IndexRenameRootPageRecord(DataInput in) throws IOException {
cacheId = in.readInt();
segments = in.readInt();
byte[] oldTreeNameBytes = new byte[in.readInt()];
in.readFully(oldTreeNameBytes);
oldTreeName = new String(oldTreeNameBytes, UTF_8);
byte[] newTreeNameBytes = new byte[in.readInt()];
in.readFully(newTreeNameBytes);
newTreeName = new String(newTreeNameBytes, UTF_8);
}
/** {@inheritDoc} */
@Override public RecordType type() {
return RecordType.INDEX_ROOT_PAGE_RENAME_RECORD;
}
/**
* Getting cache id.
*
* @return Cache id.
*/
public int cacheId() {
return cacheId;
}
/**
* Getting old name of underlying index tree name.
*
* @return Old name of underlying index tree name.
*/
public String oldTreeName() {
return oldTreeName;
}
/**
* Getting new name of underlying index tree name.
*
* @return New name of underlying index tree name.
*/
public String newTreeName() {
return newTreeName;
}
/**
* Getting number of segments.
*
* @return Number of segments.
*/
public int segments() {
return segments;
}
/**
* Calculating the size of the data.
*
* @return Size in bytes.
* @see #IndexRenameRootPageRecord(DataInput)
* @see #writeRecord
*/
public int dataSize() {
return /* cacheId */4 + /* segments */4 + /* oldTreeNameLen */4 + oldTreeName.getBytes(UTF_8).length +
/* newTreeNameLen */4 + newTreeName.getBytes(UTF_8).length;
}
/**
* Writing data to the buffer.
*
* @param buf Output buffer.
* @see #IndexRenameRootPageRecord(DataInput)
* @see #dataSize
*/
public void writeRecord(ByteBuffer buf) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(IndexRenameRootPageRecord.class, this);
}
}
|
buf.putInt(cacheId);
buf.putInt(segments);
byte[] oldTreeNameBytes = oldTreeName.getBytes(UTF_8);
buf.putInt(oldTreeNameBytes.length);
buf.put(oldTreeNameBytes);
byte[] newTreeNameBytes = newTreeName.getBytes(UTF_8);
buf.putInt(newTreeNameBytes.length);
buf.put(newTreeNameBytes);
| 905
| 115
| 1,020
|
<methods>public non-sealed void <init>() ,public void chainSize(int) ,public int chainSize() ,public org.apache.ignite.internal.processors.cache.persistence.wal.WALPointer position() ,public void position(org.apache.ignite.internal.processors.cache.persistence.wal.WALPointer) ,public org.apache.ignite.internal.pagemem.wal.record.WALRecord previous() ,public void previous(org.apache.ignite.internal.pagemem.wal.record.WALRecord) ,public int size() ,public void size(int) ,public java.lang.String toString() ,public abstract org.apache.ignite.internal.pagemem.wal.record.WALRecord.RecordType type() <variables>private int chainSize,private org.apache.ignite.internal.processors.cache.persistence.wal.WALPointer pos,private org.apache.ignite.internal.pagemem.wal.record.WALRecord prev,private int size
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/LazyDataEntry.java
|
LazyDataEntry
|
key
|
class LazyDataEntry extends DataEntry implements MarshalledDataEntry {
/** */
private GridCacheSharedContext cctx;
/** Data Entry key type code. See {@link CacheObject} for built-in value type codes */
private byte keyType;
/** Key value bytes. */
private byte[] keyBytes;
/** Data Entry Value type code. See {@link CacheObject} for built-in value type codes */
private byte valType;
/** Value value bytes. */
private byte[] valBytes;
/**
* @param cctx Shared context.
* @param cacheId Cache ID.
* @param keyType Object type code for Key.
* @param keyBytes Data Entry Key value bytes.
* @param valType Object type code for Value.
* @param valBytes Data Entry Value value bytes.
* @param op Operation.
* @param nearXidVer Near transaction version.
* @param writeVer Write version.
* @param expireTime Expire time.
* @param partId Partition ID.
* @param partCnt Partition counter.
* @param flags Flags.
*/
public LazyDataEntry(
GridCacheSharedContext cctx,
int cacheId,
byte keyType,
byte[] keyBytes,
byte valType,
byte[] valBytes,
GridCacheOperation op,
GridCacheVersion nearXidVer,
GridCacheVersion writeVer,
long expireTime,
int partId,
long partCnt,
byte flags
) {
super(cacheId, null, null, op, nearXidVer, writeVer, expireTime, partId, partCnt, flags);
this.cctx = cctx;
this.keyType = keyType;
this.keyBytes = keyBytes;
this.valType = valType;
this.valBytes = valBytes;
}
/** {@inheritDoc} */
@Override public KeyCacheObject key() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public CacheObject value() {
if (val == null && valBytes != null) {
GridCacheContext cacheCtx = cctx.cacheContext(cacheId);
if (cacheCtx == null)
throw new IgniteException("Failed to find cache context for the given cache ID: " + cacheId);
IgniteCacheObjectProcessor co = cctx.kernalContext().cacheObjects();
val = co.toCacheObject(cacheCtx.cacheObjectContext(), valType, valBytes);
}
return val;
}
/** {@inheritDoc} */
@Override public byte getKeyType() {
return keyType;
}
/** {@inheritDoc} */
@Override public byte[] getKeyBytes() {
return keyBytes;
}
/** {@inheritDoc} */
@Override public byte getValType() {
return valType;
}
/** {@inheritDoc} */
@Override public byte[] getValBytes() {
return valBytes;
}
}
|
try {
if (key == null) {
GridCacheContext cacheCtx = cctx.cacheContext(cacheId);
if (cacheCtx == null)
throw new IgniteException("Failed to find cache context for the given cache ID: " + cacheId);
IgniteCacheObjectProcessor co = cctx.kernalContext().cacheObjects();
key = co.toKeyCacheObject(cacheCtx.cacheObjectContext(), keyType, keyBytes);
if (key.partition() == -1)
key.partition(partId);
}
return key;
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
| 767
| 175
| 942
|
<methods>public void <init>(int, org.apache.ignite.internal.processors.cache.KeyCacheObject, org.apache.ignite.internal.processors.cache.CacheObject, org.apache.ignite.internal.processors.cache.GridCacheOperation, org.apache.ignite.internal.processors.cache.version.GridCacheVersion, org.apache.ignite.internal.processors.cache.version.GridCacheVersion, long, int, long, byte) ,public int cacheId() ,public long expireTime() ,public static byte flags(boolean) ,public static byte flags(boolean, boolean, boolean) ,public byte flags() ,public org.apache.ignite.internal.processors.cache.KeyCacheObject key() ,public org.apache.ignite.internal.processors.cache.version.GridCacheVersion nearXidVersion() ,public org.apache.ignite.internal.processors.cache.GridCacheOperation op() ,public long partitionCounter() ,public org.apache.ignite.internal.pagemem.wal.record.DataEntry partitionCounter(long) ,public int partitionId() ,public java.lang.String toString() ,public org.apache.ignite.internal.processors.cache.CacheObject value() ,public org.apache.ignite.internal.processors.cache.version.GridCacheVersion writeVersion() <variables>public static final byte EMPTY_FLAGS,public static final byte FROM_STORE_FLAG,public static final byte PRELOAD_FLAG,public static final byte PRIMARY_FLAG,protected int cacheId,protected long expireTime,protected byte flags,protected org.apache.ignite.internal.processors.cache.KeyCacheObject key,protected org.apache.ignite.internal.processors.cache.version.GridCacheVersion nearXidVer,protected org.apache.ignite.internal.processors.cache.GridCacheOperation op,protected long partCnt,protected int partId,protected org.apache.ignite.internal.processors.cache.CacheObject val,protected org.apache.ignite.internal.processors.cache.version.GridCacheVersion writeVer
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/UnwrapDataEntry.java
|
UnwrapDataEntry
|
unwrappedValue
|
class UnwrapDataEntry extends DataEntry implements UnwrappedDataEntry {
/** Cache object value context. Context is used for unwrapping objects. */
private final CacheObjectValueContext cacheObjValCtx;
/** Keep binary. This flag disables converting of non-primitive types (BinaryObjects). */
private final boolean keepBinary;
/**
* @param cacheId Cache ID.
* @param key Key.
* @param val Value or null for delete operation.
* @param op Operation.
* @param nearXidVer Near transaction version.
* @param writeVer Write version.
* @param expireTime Expire time.
* @param partId Partition ID.
* @param partCnt Partition counter.
* @param cacheObjValCtx cache object value context for unwrapping objects.
* @param keepBinary disable unwrapping for non primitive objects, Binary Objects would be returned instead.
* @param flags Flags.
*/
public UnwrapDataEntry(
final int cacheId,
final KeyCacheObject key,
final CacheObject val,
final GridCacheOperation op,
final GridCacheVersion nearXidVer,
final GridCacheVersion writeVer,
final long expireTime,
final int partId,
final long partCnt,
final CacheObjectValueContext cacheObjValCtx,
final boolean keepBinary,
final byte flags) {
super(cacheId, key, val, op, nearXidVer, writeVer, expireTime, partId, partCnt, flags);
this.cacheObjValCtx = cacheObjValCtx;
this.keepBinary = keepBinary;
}
/** {@inheritDoc} */
@Override public Object unwrappedKey() {
try {
return unwrapKey(key, keepBinary, cacheObjValCtx);
}
catch (Exception e) {
cacheObjValCtx.kernalContext().log(UnwrapDataEntry.class)
.error("Unable to convert key [" + key + "]", e);
return null;
}
}
/** {@inheritDoc} */
@Override public Object unwrappedValue() {<FILL_FUNCTION_BODY>}
/** */
public static Object unwrapKey(KeyCacheObject key, boolean keepBinary, CacheObjectValueContext cacheObjValCtx) {
if (keepBinary && key instanceof BinaryObject)
return key;
Object unwrapped = key.value(cacheObjValCtx, false);
if (unwrapped instanceof BinaryObject) {
if (keepBinary)
return unwrapped;
unwrapped = ((BinaryObject)unwrapped).deserialize();
}
return unwrapped;
}
/** */
public static Object unwrapValue(CacheObject val, boolean keepBinary, CacheObjectValueContext cacheObjValCtx) {
if (val == null)
return null;
if (keepBinary && val instanceof BinaryObject)
return val;
return val.value(cacheObjValCtx, false);
}
/** {@inheritDoc} */
@Override public String toString() {
SB sb = new SB();
sb.a(getClass().getSimpleName()).a('[');
if (S.includeSensitive())
sb.a("k = ").a(unwrappedKey()).a(", v = [ ").a(unwrappedValue()).a("], ");
return sb.a("super = [").a(super.toString()).a("]]").toString();
}
}
|
try {
return unwrapValue(val, keepBinary, cacheObjValCtx);
}
catch (Exception e) {
cacheObjValCtx.kernalContext().log(UnwrapDataEntry.class)
.error("Unable to convert value [" + value() + "]", e);
return null;
}
| 888
| 86
| 974
|
<methods>public void <init>(int, org.apache.ignite.internal.processors.cache.KeyCacheObject, org.apache.ignite.internal.processors.cache.CacheObject, org.apache.ignite.internal.processors.cache.GridCacheOperation, org.apache.ignite.internal.processors.cache.version.GridCacheVersion, org.apache.ignite.internal.processors.cache.version.GridCacheVersion, long, int, long, byte) ,public int cacheId() ,public long expireTime() ,public static byte flags(boolean) ,public static byte flags(boolean, boolean, boolean) ,public byte flags() ,public org.apache.ignite.internal.processors.cache.KeyCacheObject key() ,public org.apache.ignite.internal.processors.cache.version.GridCacheVersion nearXidVersion() ,public org.apache.ignite.internal.processors.cache.GridCacheOperation op() ,public long partitionCounter() ,public org.apache.ignite.internal.pagemem.wal.record.DataEntry partitionCounter(long) ,public int partitionId() ,public java.lang.String toString() ,public org.apache.ignite.internal.processors.cache.CacheObject value() ,public org.apache.ignite.internal.processors.cache.version.GridCacheVersion writeVersion() <variables>public static final byte EMPTY_FLAGS,public static final byte FROM_STORE_FLAG,public static final byte PRELOAD_FLAG,public static final byte PRIMARY_FLAG,protected int cacheId,protected long expireTime,protected byte flags,protected org.apache.ignite.internal.processors.cache.KeyCacheObject key,protected org.apache.ignite.internal.processors.cache.version.GridCacheVersion nearXidVer,protected org.apache.ignite.internal.processors.cache.GridCacheOperation op,protected long partCnt,protected int partId,protected org.apache.ignite.internal.processors.cache.CacheObject val,protected org.apache.ignite.internal.processors.cache.version.GridCacheVersion writeVer
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/delta/InnerReplaceRecord.java
|
InnerReplaceRecord
|
applyDelta
|
class InnerReplaceRecord<L> extends PageDeltaRecord {
/** */
private int dstIdx;
/** */
private long srcPageId;
/** */
private int srcIdx;
/** */
private long rmvId;
/**
* @param grpId Cache group ID.
* @param pageId Page ID.
* @param dstIdx Destination index.
* @param srcPageId Source page ID.
* @param srcIdx Source index.
*/
public InnerReplaceRecord(int grpId, long pageId, int dstIdx, long srcPageId, int srcIdx, long rmvId) {
super(grpId, pageId);
this.dstIdx = dstIdx;
this.srcPageId = srcPageId;
this.srcIdx = srcIdx;
this.rmvId = rmvId;
throw new IgniteException("Inner replace record should not be used directly (see GG-11640). " +
"Clear the database directory and restart the node.");
}
/** {@inheritDoc} */
@Override public void applyDelta(PageMemory pageMem, long pageAddr) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public RecordType type() {
return RecordType.BTREE_PAGE_INNER_REPLACE;
}
/**
* @return Destination index.
*/
public int destinationIndex() {
return dstIdx;
}
/**
* @return Source page ID.
*/
public long sourcePageId() {
return srcPageId;
}
/**
* @return Source index.
*/
public int sourceIndex() {
return srcIdx;
}
/**
* @return Remove ID.
*/
public long removeId() {
return rmvId;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(InnerReplaceRecord.class, this, "super", super.toString());
}
}
|
throw new IgniteCheckedException("Inner replace record should not be logged.");
| 547
| 21
| 568
|
<methods>public abstract void applyDelta(org.apache.ignite.internal.pagemem.PageMemory, long) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.pagemem.FullPageId fullPageId() ,public int groupId() ,public long pageId() ,public java.lang.String toString() <variables>private int grpId,private long pageId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/delta/MergeRecord.java
|
MergeRecord
|
toString
|
class MergeRecord<L> extends PageDeltaRecord {
/** */
@GridToStringExclude
private long prntId;
/** */
@GridToStringExclude
private long rightId;
/** */
private int prntIdx;
/** */
private boolean emptyBranch;
/**
* @param grpId Cache group ID.
* @param pageId Page ID.
* @param prntId Parent ID.
* @param prntIdx Index in parent page.
* @param rightId Right ID.
* @param emptyBranch We are merging empty branch.
*/
public MergeRecord(int grpId, long pageId, long prntId, int prntIdx, long rightId, boolean emptyBranch) {
super(grpId, pageId);
this.prntId = prntId;
this.rightId = rightId;
this.prntIdx = prntIdx;
this.emptyBranch = emptyBranch;
throw new IgniteException("Merge record should not be used directly (see GG-11640). " +
"Clear the database directory and restart the node.");
}
/** {@inheritDoc} */
@Override public void applyDelta(PageMemory pageMem, long pageAddr) throws IgniteCheckedException {
throw new IgniteCheckedException("Merge record should not be logged.");
}
/** {@inheritDoc} */
@Override public RecordType type() {
return RecordType.BTREE_PAGE_MERGE;
}
/** */
public long parentId() {
return prntId;
}
/** */
public int parentIndex() {
return prntIdx;
}
/** */
public long rightId() {
return rightId;
}
/** */
public boolean isEmptyBranch() {
return emptyBranch;
}
/** {@inheritDoc} */
@Override public String toString() {<FILL_FUNCTION_BODY>}
}
|
return S.toString(MergeRecord.class, this, "prntId", U.hexLong(prntId), "rightId", U.hexLong(rightId),
"super", super.toString());
| 520
| 53
| 573
|
<methods>public abstract void applyDelta(org.apache.ignite.internal.pagemem.PageMemory, long) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.pagemem.FullPageId fullPageId() ,public int groupId() ,public long pageId() ,public java.lang.String toString() <variables>private int grpId,private long pageId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/delta/MetaPageInitRootInlineRecord.java
|
MetaPageInitRootInlineRecord
|
applyDelta
|
class MetaPageInitRootInlineRecord extends MetaPageInitRootRecord {
/** */
private final int inlineSize;
/**
* @param grpId Cache group ID.
* @param pageId Meta page ID.
* @param rootId
* @param inlineSize Inline size.
*/
public MetaPageInitRootInlineRecord(int grpId, long pageId, long rootId, int inlineSize) {
super(grpId, pageId, rootId);
this.inlineSize = inlineSize;
}
/**
* @return Inline size.
*/
public int inlineSize() {
return inlineSize;
}
/** {@inheritDoc} */
@Override public void applyDelta(PageMemory pageMem, long pageAddr) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public RecordType type() {
return RecordType.BTREE_META_PAGE_INIT_ROOT2;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(MetaPageInitRootInlineRecord.class, this, "super", super.toString());
}
}
|
BPlusMetaIO io = BPlusMetaIO.VERSIONS.forPage(pageAddr);
io.initRoot(pageAddr, rootId, pageMem.realPageSize(groupId()));
io.setInlineSize(pageAddr, inlineSize);
| 309
| 63
| 372
|
<methods>public void <init>(int, long, long) ,public void applyDelta(org.apache.ignite.internal.pagemem.PageMemory, long) throws org.apache.ignite.IgniteCheckedException,public long rootId() ,public java.lang.String toString() ,public org.apache.ignite.internal.pagemem.wal.record.WALRecord.RecordType type() <variables>protected long rootId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/delta/MetaPageUpdateLastAllocatedIndex.java
|
MetaPageUpdateLastAllocatedIndex
|
applyDelta
|
class MetaPageUpdateLastAllocatedIndex extends PageDeltaRecord {
/** */
private final int lastAllocatedIdx;
/**
* @param pageId Meta page ID.
*/
public MetaPageUpdateLastAllocatedIndex(int grpId, long pageId, int lastAllocatedIdx) {
super(grpId, pageId);
this.lastAllocatedIdx = lastAllocatedIdx;
}
/** {@inheritDoc} */
@Override public void applyDelta(PageMemory pageMem, long pageAddr) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public RecordType type() {
return RecordType.META_PAGE_UPDATE_LAST_ALLOCATED_INDEX;
}
/**
* @return Root ID.
*/
public int lastAllocatedIndex() {
return lastAllocatedIdx;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(MetaPageUpdateLastAllocatedIndex.class, this, "super", super.toString());
}
}
|
int type = PageIO.getType(pageAddr);
assert type == PageIO.T_META || type == PageIO.T_PART_META;
PageMetaIO io = PageIO.getPageIO(type, PageIO.getVersion(pageAddr));
io.setLastAllocatedPageCount(pageAddr, lastAllocatedIdx);
| 287
| 90
| 377
|
<methods>public abstract void applyDelta(org.apache.ignite.internal.pagemem.PageMemory, long) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.pagemem.FullPageId fullPageId() ,public int groupId() ,public long pageId() ,public java.lang.String toString() <variables>private int grpId,private long pageId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/delta/MetaPageUpdatePartitionDataRecord.java
|
MetaPageUpdatePartitionDataRecord
|
applyDelta
|
class MetaPageUpdatePartitionDataRecord extends PageDeltaRecord {
/** */
private long updateCntr;
/** */
private long globalRmvId;
/** TODO: Partition size may be long */
private int partSize;
/** */
private byte state;
/** */
private int allocatedIdxCandidate;
/** */
private long cntrsPageId;
/**
* @param grpId Cache group ID.
* @param pageId Page ID.
* @param allocatedIdxCandidate Page Allocated index candidate
*/
public MetaPageUpdatePartitionDataRecord(
int grpId,
long pageId,
long updateCntr,
long globalRmvId,
int partSize,
long cntrsPageId,
byte state,
int allocatedIdxCandidate) {
super(grpId, pageId);
this.updateCntr = updateCntr;
this.globalRmvId = globalRmvId;
this.partSize = partSize;
this.state = state;
this.allocatedIdxCandidate = allocatedIdxCandidate;
this.cntrsPageId = cntrsPageId;
}
/**
* @param in Input.
*/
public MetaPageUpdatePartitionDataRecord(DataInput in) throws IOException {
super(in.readInt(), in.readLong());
this.updateCntr = in.readLong();
this.globalRmvId = in.readLong();
this.partSize = in.readInt();
this.cntrsPageId = in.readLong();
this.state = in.readByte();
this.allocatedIdxCandidate = in.readInt();
}
/**
* @return Update counter.
*/
public long updateCounter() {
return updateCntr;
}
/**
* @return Global remove ID.
*/
public long globalRemoveId() {
return globalRmvId;
}
/**
* @return Partition size.
*/
public int partitionSize() {
return partSize;
}
/**
* @return Partition size.
*/
public long countersPageId() {
return cntrsPageId;
}
/**
* @return Partition state
*/
public byte state() {
return state;
}
/** {@inheritDoc} */
@Override public void applyDelta(PageMemory pageMem, long pageAddr) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/**
*
*/
public int allocatedIndexCandidate() {
return allocatedIdxCandidate;
}
/**
* @param buf Buffer.
*/
public void toBytes(ByteBuffer buf) {
buf.putInt(groupId());
buf.putLong(pageId());
buf.putLong(updateCounter());
buf.putLong(globalRemoveId());
buf.putInt(partitionSize());
buf.putLong(countersPageId());
buf.put(state());
buf.putInt(allocatedIndexCandidate());
}
/** {@inheritDoc} */
@Override public RecordType type() {
return RecordType.PARTITION_META_PAGE_UPDATE_COUNTERS;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(MetaPageUpdatePartitionDataRecord.class, this, "partId", PageIdUtils.partId(pageId()), "super", super.toString());
}
}
|
PagePartitionMetaIO io = PagePartitionMetaIO.VERSIONS.forPage(pageAddr);
io.setUpdateCounter(pageAddr, updateCntr);
io.setGlobalRemoveId(pageAddr, globalRmvId);
io.setSize(pageAddr, partSize);
io.setCountersPageId(pageAddr, cntrsPageId);
io.setPartitionState(pageAddr, state);
io.setCandidatePageCount(pageAddr, allocatedIdxCandidate);
| 915
| 123
| 1,038
|
<methods>public abstract void applyDelta(org.apache.ignite.internal.pagemem.PageMemory, long) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.pagemem.FullPageId fullPageId() ,public int groupId() ,public long pageId() ,public java.lang.String toString() <variables>private int grpId,private long pageId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/delta/MetaPageUpdatePartitionDataRecordV3.java
|
MetaPageUpdatePartitionDataRecordV3
|
applyDelta
|
class MetaPageUpdatePartitionDataRecordV3 extends MetaPageUpdatePartitionDataRecordV2 {
/** Index of the last reencrypted page. */
private int encryptedPageIdx;
/** Total pages to be reencrypted. */
private int encryptedPageCnt;
/**
* @param grpId Group id.
* @param pageId Page id.
* @param updateCntr Update counter.
* @param globalRmvId Global remove id.
* @param partSize Partition size.
* @param cntrsPageId Cntrs page id.
* @param state State.
* @param allocatedIdxCandidate Allocated index candidate.
* @param link Link.
* @param encryptedPageIdx Index of the last reencrypted page.
* @param encryptedPageCnt Total pages to be reencrypted.
*/
public MetaPageUpdatePartitionDataRecordV3(
int grpId,
long pageId,
long updateCntr,
long globalRmvId,
int partSize,
long cntrsPageId,
byte state,
int allocatedIdxCandidate,
long link,
int encryptedPageIdx,
int encryptedPageCnt) {
super(grpId, pageId, updateCntr, globalRmvId, partSize, cntrsPageId, state, allocatedIdxCandidate, link);
this.encryptedPageIdx = encryptedPageIdx;
this.encryptedPageCnt = encryptedPageCnt;
}
/**
* @param in Input.
*/
public MetaPageUpdatePartitionDataRecordV3(DataInput in) throws IOException {
super(in);
encryptedPageIdx = in.readInt();
encryptedPageCnt = in.readInt();
}
/** {@inheritDoc} */
@Override public void applyDelta(PageMemory pageMem, long pageAddr) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/**
* @return Index of the last reencrypted page.
*/
public int encryptedPageIndex() {
return encryptedPageIdx;
}
/**
* @return Total pages to be reencrypted.
*/
public int encryptedPageCount() {
return encryptedPageCnt;
}
/** {@inheritDoc} */
@Override public void toBytes(ByteBuffer buf) {
super.toBytes(buf);
buf.putInt(encryptedPageIndex());
buf.putInt(encryptedPageCount());
}
/** {@inheritDoc} */
@Override public RecordType type() {
return RecordType.PARTITION_META_PAGE_DELTA_RECORD_V3;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(MetaPageUpdatePartitionDataRecordV3.class, this, "partId",
PageIdUtils.partId(pageId()), "super", super.toString());
}
}
|
super.applyDelta(pageMem, pageAddr);
PagePartitionMetaIOV3 io = (PagePartitionMetaIOV3)PagePartitionMetaIO.VERSIONS.forPage(pageAddr);
io.setEncryptedPageIndex(pageAddr, encryptedPageIdx);
io.setEncryptedPageCount(pageAddr, encryptedPageCnt);
| 751
| 86
| 837
|
<methods>public void <init>(int, long, long, long, int, long, byte, int, long) ,public void <init>(java.io.DataInput) throws java.io.IOException,public void applyDelta(org.apache.ignite.internal.pagemem.PageMemory, long) throws org.apache.ignite.IgniteCheckedException,public long link() ,public void toBytes(java.nio.ByteBuffer) ,public java.lang.String toString() ,public org.apache.ignite.internal.pagemem.wal.record.WALRecord.RecordType type() <variables>private long link
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/delta/PagesListRemovePageRecord.java
|
PagesListRemovePageRecord
|
applyDelta
|
class PagesListRemovePageRecord extends PageDeltaRecord {
/** */
@GridToStringExclude
private final long rmvdPageId;
/**
* @param cacheId Cache ID.
* @param pageId Page ID.
* @param rmvdPageId Data page ID to remove.
*/
public PagesListRemovePageRecord(int cacheId, long pageId, long rmvdPageId) {
super(cacheId, pageId);
this.rmvdPageId = rmvdPageId;
}
/**
* @return Removed page ID.
*/
public long removedPageId() {
return rmvdPageId;
}
/** {@inheritDoc} */
@Override public void applyDelta(PageMemory pageMem, long pageAddr) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public RecordType type() {
return RecordType.PAGES_LIST_REMOVE_PAGE;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(PagesListRemovePageRecord.class, this,
"rmvdPageId", U.hexLong(rmvdPageId),
"pageId", U.hexLong(pageId()),
"grpId", groupId(),
"super", super.toString());
}
}
|
PagesListNodeIO io = PagesListNodeIO.VERSIONS.forPage(pageAddr);
boolean rmvd = io.removePage(pageAddr, rmvdPageId);
assert rmvd;
| 343
| 52
| 395
|
<methods>public abstract void applyDelta(org.apache.ignite.internal.pagemem.PageMemory, long) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.pagemem.FullPageId fullPageId() ,public int groupId() ,public long pageId() ,public java.lang.String toString() <variables>private int grpId,private long pageId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/GridAffinityUtils.java
|
GridAffinityUtils
|
affinityMessage
|
class GridAffinityUtils {
/**
* Creates a job that will look up {@link AffinityKeyMapper} and {@link AffinityFunction} on a
* cache with given name. If they exist, this job will serialize and transfer them together with all deployment
* information needed to unmarshal objects on remote node. Result is returned as a {@link GridTuple3},
* where first object is {@link GridAffinityMessage} for {@link AffinityFunction}, second object
* is {@link GridAffinityMessage} for {@link AffinityKeyMapper} and third object is affinity assignment
* for given topology version.
*
* @param cacheName Cache name.
* @return Affinity job.
*/
static Callable<GridTuple3<GridAffinityMessage, GridAffinityMessage, GridAffinityAssignment>> affinityJob(
String cacheName, AffinityTopologyVersion topVer) {
return new AffinityJob(cacheName, topVer);
}
/**
* @param ctx {@code GridKernalContext} instance which provides deployment manager
* @param o Object for which deployment should be obtained.
* @return Deployment object for given instance,
* @throws IgniteCheckedException If node cannot create deployment for given object.
*/
private static GridAffinityMessage affinityMessage(GridKernalContext ctx, Object o) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/**
* Unmarshalls transfer object from remote node within a given context.
*
* @param ctx Grid kernal context that provides deployment and marshalling services.
* @param sndNodeId {@link UUID} of the sender node.
* @param msg Transfer object that contains original serialized object and deployment information.
* @return Unmarshalled object.
* @throws IgniteCheckedException If node cannot obtain deployment.
*/
static Object unmarshall(GridKernalContext ctx, UUID sndNodeId, GridAffinityMessage msg)
throws IgniteCheckedException {
GridDeployment dep = ctx.deploy().getGlobalDeployment(
msg.deploymentMode(),
msg.sourceClassName(),
msg.sourceClassName(),
msg.userVersion(),
sndNodeId,
msg.classLoaderId(),
msg.loaderParticipants(),
null);
if (dep == null)
throw new IgniteDeploymentCheckedException("Failed to obtain affinity object (is peer class loading turned on?): " +
msg);
Object src = U.unmarshal(ctx, msg.source(),
U.resolveClassLoader(dep.classLoader(), ctx.config()));
// Resource injection.
ctx.resource().inject(dep, dep.deployedClass(msg.sourceClassName()).get1(), src);
return src;
}
/** Ensure singleton. */
private GridAffinityUtils() {
// No-op.
}
/**
*
*/
@GridInternal
private static class AffinityJob implements
Callable<GridTuple3<GridAffinityMessage, GridAffinityMessage, GridAffinityAssignment>>,
Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** */
@IgniteInstanceResource
private Ignite ignite;
/** */
@LoggerResource
private IgniteLogger log;
/** */
private String cacheName;
/** */
private AffinityTopologyVersion topVer;
/**
* @param cacheName Cache name.
* @param topVer Topology version.
*/
private AffinityJob(@Nullable String cacheName, @NotNull AffinityTopologyVersion topVer) {
this.cacheName = cacheName;
this.topVer = topVer;
}
/**
*
*/
public AffinityJob() {
// No-op.
}
/** {@inheritDoc} */
@Override public GridTuple3<GridAffinityMessage, GridAffinityMessage, GridAffinityAssignment> call()
throws Exception {
assert ignite != null;
assert log != null;
IgniteKernal kernal = ((IgniteKernal)ignite);
GridCacheContext<Object, Object> cctx = kernal.internalCache(cacheName).context();
assert cctx != null;
GridKernalContext ctx = kernal.context();
cctx.affinity().affinityReadyFuture(topVer).get();
AffinityAssignment assign0 = cctx.affinity().assignment(topVer);
//using legacy GridAffinityAssignment for compatibility.
return F.t(
affinityMessage(ctx, cctx.config().getAffinity()),
affinityMessage(ctx, cctx.config().getAffinityMapper()),
new GridAffinityAssignment(topVer, assign0.assignment(), assign0.idealAssignment())
);
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeString(out, cacheName);
out.writeObject(topVer);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
cacheName = U.readString(in);
topVer = (AffinityTopologyVersion)in.readObject();
}
}
}
|
Class cls = o.getClass();
GridDeployment dep = ctx.deploy().deploy(cls, cls.getClassLoader());
if (dep == null)
throw new IgniteDeploymentCheckedException("Failed to deploy affinity object with class: " + cls.getName());
return new GridAffinityMessage(
U.marshal(ctx, o),
cls.getName(),
dep.classLoaderId(),
dep.deployMode(),
dep.userVersion(),
dep.participants());
| 1,354
| 136
| 1,490
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/IdealAffinityAssignment.java
|
IdealAffinityAssignment
|
calculatePrimaries
|
class IdealAffinityAssignment {
/** Topology version. */
private final AffinityTopologyVersion topologyVersion;
/** Assignment. */
private final List<List<ClusterNode>> assignment;
/** Ideal primaries. */
private final Map<Object, Set<Integer>> idealPrimaries;
/**
* @param topologyVersion Topology version.
* @param assignment Assignment.
* @param idealPrimaries Ideal primaries.
*/
private IdealAffinityAssignment(
AffinityTopologyVersion topologyVersion,
List<List<ClusterNode>> assignment,
Map<Object, Set<Integer>> idealPrimaries
) {
this.topologyVersion = topologyVersion;
this.assignment = assignment;
this.idealPrimaries = idealPrimaries;
}
/**
* @param clusterNode Cluster node.
*/
public Set<Integer> idealPrimaries(ClusterNode clusterNode) {
Object consistentId = clusterNode.consistentId();
assert consistentId != null : clusterNode;
return idealPrimaries.getOrDefault(consistentId, Collections.emptySet());
}
/**
* @param partition Partition.
*/
public ClusterNode currentPrimary(int partition) {
return assignment.get(partition).get(0);
}
/**
*
*/
public List<List<ClusterNode>> assignment() {
return assignment;
}
/**
*
*/
public AffinityTopologyVersion topologyVersion() {
return topologyVersion;
}
/**
* @param nodes Nodes.
* @param assignment Assignment.
*/
public static Map<Object, Set<Integer>> calculatePrimaries(
@Nullable List<ClusterNode> nodes,
List<List<ClusterNode>> assignment
) {<FILL_FUNCTION_BODY>}
/**
* @param topVer Topology version.
* @param assignment Assignment.
*/
public static IdealAffinityAssignment create(AffinityTopologyVersion topVer, List<List<ClusterNode>> assignment) {
return create(topVer, null, assignment);
}
/**
* @param topVer Topology version.
* @param nodes Nodes.
* @param assignment Assignment.
*/
public static IdealAffinityAssignment create(
AffinityTopologyVersion topVer,
@Nullable List<ClusterNode> nodes,
List<List<ClusterNode>> assignment
) {
return new IdealAffinityAssignment(topVer, assignment, calculatePrimaries(nodes, assignment));
}
/**
* @param topVer Topology version.
* @param assignment Assignment.
* @param previousAssignment Previous assignment.
*/
public static IdealAffinityAssignment createWithPreservedPrimaries(
AffinityTopologyVersion topVer,
List<List<ClusterNode>> assignment,
IdealAffinityAssignment previousAssignment
) {
return new IdealAffinityAssignment(topVer, assignment, previousAssignment.idealPrimaries);
}
}
|
int nodesSize = nodes != null ? nodes.size() : 100;
Map<Object, Set<Integer>> primaryPartitions = U.newHashMap(nodesSize);
for (int size = assignment.size(), p = 0; p < size; p++) {
List<ClusterNode> affNodes = assignment.get(p);
if (!affNodes.isEmpty()) {
ClusterNode primary = affNodes.get(0);
primaryPartitions.computeIfAbsent(primary.consistentId(),
id -> new HashSet<>(U.capacity(size / nodesSize * 2))).add(p);
}
}
return primaryPartitions;
| 782
| 172
| 954
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/authentication/User.java
|
User
|
equals
|
class User implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** Default user name. */
public static final String DFAULT_USER_NAME = "ignite";
/** Default user password. */
private static final String DFLT_USER_PASSWORD = "ignite";
/**
* @see BCrypt#GENSALT_DEFAULT_LOG2_ROUNDS
*/
private static int bCryptGensaltLog2Rounds = 10;
/** User name. */
private String name;
/** Hashed password. */
@GridToStringExclude
private String hashedPasswd;
/**
* Constructor.
*/
public User() {
}
/**
* @param name User name.
* @param hashedPasswd Hashed password.
*/
private User(String name, String hashedPasswd) {
this.name = name;
this.hashedPasswd = hashedPasswd;
}
/**
* @return User name.
*/
public String name() {
return name;
}
/**
* Create new user.
* @param name User name.
* @param passwd Plain text password.
* @return Created user.
*/
public static User create(String name, String passwd) {
return new User(name, password(passwd));
}
/**
* Create empty user by login name.
* @param name User name.
* @return User.
*/
public static User create(String name) {
return new User(name, null);
}
/**
* Create new user.
*
* @return Created user.
*/
public static User defaultUser() {
return create(DFAULT_USER_NAME, DFLT_USER_PASSWORD);
}
/**
* @param passwd Plain text password.
* @return Hashed password.
*/
@Nullable public static String password(String passwd) {
return password_bcrypt(passwd);
}
/**
* @param passwd Plain text password.
* @return Hashed password.
*/
@Nullable private static String password_bcrypt(String passwd) {
return BCrypt.hashpw(passwd, BCrypt.gensalt(bCryptGensaltLog2Rounds));
}
/**
* @param passwd Plain text password.
* @return {@code true} If user authorized, otherwise returns {@code false}.
*/
public boolean authorize(String passwd) {
if (F.isEmpty(passwd))
return hashedPasswd == null;
return BCrypt.checkpw(passwd, hashedPasswd);
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
int result = Objects.hash(name, hashedPasswd);
return result;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(User.class, this);
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
User u = (User)o;
return F.eq(name, u.name) && F.eq(hashedPasswd, u.hashedPasswd);
| 818
| 82
| 900
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/authentication/UserAuthenticateRequestMessage.java
|
UserAuthenticateRequestMessage
|
readFrom
|
class UserAuthenticateRequestMessage implements Message {
/** */
private static final long serialVersionUID = 0L;
/** User name. */
private String name;
/** User password.. */
private String passwd;
/** Request ID. */
private IgniteUuid id = IgniteUuid.randomUuid();
/**
*
*/
public UserAuthenticateRequestMessage() {
// No-op.
}
/**
* @param name User name.
* @param passwd User password.
*/
public UserAuthenticateRequestMessage(String name, String passwd) {
this.name = name;
this.passwd = passwd;
}
/**
* @return User name.
*/
public String name() {
return name;
}
/**
* @return User password.
*/
public String password() {
return passwd;
}
/**
* @return Request ID.
*/
public IgniteUuid id() {
return id;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeIgniteUuid("id", id))
return false;
writer.incrementState();
case 1:
if (!writer.writeString("name", name))
return false;
writer.incrementState();
case 2:
if (!writer.writeString("passwd", passwd))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public short directType() {
return 131;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 3;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(UserAuthenticateRequestMessage.class, this);
}
}
|
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
id = reader.readIgniteUuid("id");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
name = reader.readString("name");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 2:
passwd = reader.readString("passwd");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(UserAuthenticateRequestMessage.class);
| 654
| 194
| 848
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/authentication/UserAuthenticateResponseMessage.java
|
UserAuthenticateResponseMessage
|
readFrom
|
class UserAuthenticateResponseMessage implements Message {
/** */
private static final long serialVersionUID = 0L;
/** Request ID. */
private IgniteUuid id;
/** Error message. */
private String errMsg;
/**
*
*/
public UserAuthenticateResponseMessage() {
// No-op.
}
/**
* @param id Request ID.
* @param errMsg error message
*/
public UserAuthenticateResponseMessage(IgniteUuid id, String errMsg) {
this.id = id;
this.errMsg = errMsg;
}
/**
* @return Success flag.
*/
public boolean success() {
return errMsg == null;
}
/**
* @return Error message.
*/
public String errorMessage() {
return errMsg;
}
/**
* @return Request ID.
*/
public IgniteUuid id() {
return id;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeString("errMsg", errMsg))
return false;
writer.incrementState();
case 1:
if (!writer.writeIgniteUuid("id", id))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public short directType() {
return 132;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 2;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(UserAuthenticateResponseMessage.class, this);
}
}
|
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
errMsg = reader.readString("errMsg");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
id = reader.readIgniteUuid("id");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(UserAuthenticateResponseMessage.class);
| 603
| 151
| 754
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/bulkload/BulkLoadProcessor.java
|
BulkLoadProcessor
|
processBatch
|
class BulkLoadProcessor implements AutoCloseable {
/** Parser of the input bytes. */
private final BulkLoadParser inputParser;
/**
* Converter, which transforms the list of strings parsed from the input stream to the key+value entry to add to
* the cache.
*/
private final IgniteClosureX<List<?>, IgniteBiTuple<?, ?>> dataConverter;
/** Streamer that puts actual key/value into the cache. */
private final BulkLoadCacheWriter outputStreamer;
/** Becomes true after {@link #close()} method is called. */
private boolean isClosed;
/** Running query manager. */
private final RunningQueryManager runningQryMgr;
/** Query id. */
private final long qryId;
/** Exception, current load process ended with, or {@code null} if in progress or if succeded. */
private Exception failReason;
/** Tracing processor. */
private final Tracing tracing;
/** Span of the running query. */
private final Span qrySpan;
/**
* Creates bulk load processor.
*
* @param inputParser Parser of the input bytes.
* @param dataConverter Converter, which transforms the list of strings parsed from the input stream to the
* key+value entry to add to the cache.
* @param outputStreamer Streamer that puts actual key/value into the cache.
* @param runningQryMgr Running query manager.
* @param qryId Running query id.
* @param tracing Tracing processor.
*/
public BulkLoadProcessor(BulkLoadParser inputParser, IgniteClosureX<List<?>, IgniteBiTuple<?, ?>> dataConverter,
BulkLoadCacheWriter outputStreamer, RunningQueryManager runningQryMgr, long qryId, Tracing tracing) {
this.inputParser = inputParser;
this.dataConverter = dataConverter;
this.outputStreamer = outputStreamer;
this.runningQryMgr = runningQryMgr;
this.qryId = qryId;
this.tracing = tracing;
GridRunningQueryInfo qryInfo = runningQryMgr.runningQueryInfo(qryId);
qrySpan = qryInfo == null ? NoopSpan.INSTANCE : qryInfo.span();
isClosed = false;
}
/**
* Returns the streamer that puts actual key/value into the cache.
*
* @return Streamer that puts actual key/value into the cache.
*/
public BulkLoadCacheWriter outputStreamer() {
return outputStreamer;
}
/**
* Processes the incoming batch and writes data to the cache by calling the data converter and output streamer.
*
* @param batchData Data from the current batch.
* @param isLastBatch true if this is the last batch.
* @throws IgniteIllegalStateException when called after {@link #close()}.
*/
public void processBatch(byte[] batchData, boolean isLastBatch) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/**
* Is called to notify processor, that bulk load execution, this processor is performing, failed with specified
* exception.
*
* @param failReason why current load failed.
*/
public void onError(Exception failReason) {
this.failReason = failReason;
}
/**
* Aborts processing and closes the underlying objects ({@link IgniteDataStreamer}).
*/
@Override public void close() throws Exception {
if (isClosed)
return;
try {
isClosed = true;
outputStreamer.close();
}
catch (Exception e) {
if (failReason == null)
failReason = e;
throw e;
}
finally {
runningQryMgr.unregister(qryId, failReason);
}
}
}
|
try (TraceSurroundings ignored = MTC.support(tracing.create(SQL_BATCH_PROCESS, qrySpan))) {
if (isClosed)
throw new IgniteIllegalStateException("Attempt to process a batch on a closed BulkLoadProcessor");
Iterable<List<Object>> inputRecords = inputParser.parseBatch(batchData, isLastBatch);
for (List<Object> record : inputRecords) {
IgniteBiTuple<?, ?> kv = dataConverter.apply(record);
outputStreamer.apply(kv);
}
}
| 1,002
| 151
| 1,153
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/bulkload/pipeline/CsvLineProcessorBlock.java
|
CsvLineProcessorBlock
|
accept
|
class CsvLineProcessorBlock extends PipelineBlock<String, String[]> {
/** Empty string array. */
public static final String[] EMPTY_STR_ARRAY = new String[0];
/** Field delimiter pattern. */
private final char fldDelim;
/** Quote character. */
private final char quoteChars;
/** Null string. */
private final String nullString;
/** Trim field string content. */
private final boolean trim;
/** Lines count. */
private int line = 0;
/** Symbol count. */
private int symbol = 0;
/**
* Creates a CSV line parser.
*/
public CsvLineProcessorBlock(BulkLoadCsvFormat format) {
this.fldDelim = format.fieldSeparator().toString().charAt(0);
this.quoteChars = format.quoteChars().charAt(0);
this.nullString = format.nullString();
this.trim = format.trim();
}
/**
* {@inheritDoc}
*/
@Override public void accept(String input, boolean isLastPortion) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/**
*
* @param fields row fields.
* @param fieldVal field value.
*/
private void addField(List<String> fields, StringBuilder fieldVal, boolean quoted) {
final String val = trim ? fieldVal.toString().trim() : fieldVal.toString();
fields.add(val.equals(nullString) ? null : val);
}
/**
*
*/
private enum ReaderState {
/** */
IDLE,
/** */
UNQUOTED,
/** */
QUOTED
}
}
|
List<String> fields = new ArrayList<>();
StringBuilder curField = new StringBuilder(256);
ReaderState state = ReaderState.IDLE;
final int length = input.length();
int copy = 0;
int cur = 0;
int prev = -1;
int copyStart = 0;
boolean quotesMatched = true;
line++;
symbol = 0;
while (true) {
if (cur == length) {
if (!quotesMatched)
throw new IgniteCheckedException(new SQLException("Unmatched quote found at the end of line "
+ line + ", symbol " + symbol));
if (copy > 0)
curField.append(input, copyStart, copyStart + copy);
addField(fields, curField, prev == quoteChars);
break;
}
final char c = input.charAt(cur++);
symbol++;
if (state == ReaderState.QUOTED) {
if (c == quoteChars) {
state = ReaderState.IDLE;
quotesMatched = !quotesMatched;
if (copy > 0) {
curField.append(input, copyStart, copyStart + copy);
copy = 0;
}
copyStart = cur;
}
else
copy++;
}
else {
if (c == fldDelim) {
if (copy > 0) {
curField.append(input, copyStart, copyStart + copy);
copy = 0;
}
addField(fields, curField, prev == quoteChars);
curField = new StringBuilder();
copyStart = cur;
state = ReaderState.IDLE;
}
else if (c == quoteChars && state != ReaderState.UNQUOTED) {
state = ReaderState.QUOTED;
quotesMatched = !quotesMatched;
if (prev == quoteChars)
copy++;
else
copyStart = cur;
}
else {
if (c == quoteChars) {
if (state == ReaderState.UNQUOTED)
throw new IgniteCheckedException(
new SQLException("Unexpected quote in the field, line " + line
+ ", symbol " + symbol));
quotesMatched = !quotesMatched;
}
copy++;
if (state == ReaderState.IDLE)
state = ReaderState.UNQUOTED;
}
}
prev = c;
}
nextBlock.accept(fields.toArray(EMPTY_STR_ARRAY), isLastPortion);
| 453
| 679
| 1,132
|
<methods>public abstract void accept(java.lang.String, boolean) throws org.apache.ignite.IgniteCheckedException,public PipelineBlock<java.lang.String[],N> append(PipelineBlock<java.lang.String[],N>) <variables>PipelineBlock<java.lang.String[],?> nextBlock
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/AutoClosableCursorIterator.java
|
AutoClosableCursorIterator
|
hasNext
|
class AutoClosableCursorIterator<T> implements Iterator<T> {
/** Cursor. */
private final QueryCursor cursor;
/** Iterator. */
private final Iterator<T> iter;
/**
* Constructor.
*
* @param cursor Query cursor.
* @param iter Wrapped iterator.
*/
public AutoClosableCursorIterator(QueryCursor cursor, Iterator<T> iter) {
this.cursor = cursor;
this.iter = iter;
}
/** {@inheritDoc} */
@Override public boolean hasNext() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public T next() {
return iter.next();
}
}
|
boolean hasNext = iter.hasNext();
if (!hasNext)
cursor.close();
return hasNext;
| 190
| 35
| 225
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheConfigurationOverride.java
|
CacheConfigurationOverride
|
isEmpty
|
class CacheConfigurationOverride {
/** */
private CacheMode mode;
/** */
private Integer backups;
/** */
private String cacheGroup;
/** */
private String dataRegion;
/** */
private CacheWriteSynchronizationMode writeSync;
/**
* @return Cache mode.
*/
public CacheMode mode() {
return mode;
}
/**
* @param mode New cache mode.
* @return {@code this} for chaining.
*/
public CacheConfigurationOverride mode(CacheMode mode) {
this.mode = mode;
return this;
}
/**
* @return Number of backup nodes for one partition.
*/
public Integer backups() {
return backups;
}
/**
* @param backups New number of backup nodes for one partition.
* @return {@code this} for chaining.
*/
public CacheConfigurationOverride backups(Integer backups) {
this.backups = backups;
return this;
}
/**
* @return Cache group name.
*/
public String cacheGroup() {
return cacheGroup;
}
/**
* @param grpName New cache group name.
* @return {@code this} for chaining.
*/
public CacheConfigurationOverride cacheGroup(String grpName) {
this.cacheGroup = grpName;
return this;
}
/**
* @return Data region name.
*/
public String dataRegion() {
return dataRegion;
}
/**
* @param dataRegName Data region name.
* @return {@code this} for chaining.
*/
public CacheConfigurationOverride dataRegion(String dataRegName) {
this.dataRegion = dataRegName;
return this;
}
/**
* @return Write synchronization mode.
*/
public CacheWriteSynchronizationMode writeSynchronizationMode() {
return writeSync;
}
/**
* @param writeSync New write synchronization mode.
* @return {@code this} for chaining.
*/
public CacheConfigurationOverride writeSynchronizationMode(CacheWriteSynchronizationMode writeSync) {
this.writeSync = writeSync;
return this;
}
/**
* Apply overrides to specified cache configuration.
*
* @param ccfg Cache configuration to override.
* @return Updated cache configuration to permit fluent-style method calls.
*/
public CacheConfiguration apply(CacheConfiguration ccfg) {
assert ccfg != null;
if (mode != null)
ccfg.setCacheMode(mode);
if (backups != null)
ccfg.setBackups(backups);
if (cacheGroup != null)
ccfg.setGroupName(cacheGroup);
if (dataRegion != null)
ccfg.setDataRegionName(dataRegion);
if (writeSync != null)
ccfg.setWriteSynchronizationMode(writeSync);
return ccfg;
}
/**
* @return {@code true} If nothing was set.
*/
public boolean isEmpty() {<FILL_FUNCTION_BODY>}
}
|
return mode == null &&
backups == null &&
cacheGroup == null &&
dataRegion == null &&
writeSync == null;
| 819
| 37
| 856
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheConfigurationSplitterImpl.java
|
CacheConfigurationSplitterImpl
|
supports
|
class CacheConfigurationSplitterImpl implements CacheConfigurationSplitter {
/** Cache configuration to hold default field values. */
private static final CacheConfiguration<?, ?> DEFAULT_CACHE_CONFIG = new CacheConfiguration<>();
/** Near cache configuration to hold default field values. */
private static final NearCacheConfiguration<?, ?> DEFAULT_NEAR_CACHE_CONFIG = new NearCacheConfiguration<>();
/** Fields set for V1 splitter protocol. */
private static final String[] FIELDS_V1 = {"evictPlcFactory", "evictFilter", "storeFactory", "storeSesLsnrs"};
/** Marshaller. */
private final Marshaller marshaller;
/** Kernal context. */
private final GridKernalContext ctx;
/**
* Creates a new instance of splitter.
*
* @param ctx Kernal context.
* @param marshaller Marshaller to be used for seserialization.
*/
public CacheConfigurationSplitterImpl(GridKernalContext ctx, Marshaller marshaller) {
this.marshaller = marshaller;
this.ctx = ctx;
}
/** {@inheritDoc} */
@Override public T2<CacheConfiguration, CacheConfigurationEnrichment> split(CacheConfiguration ccfg) {
try {
CacheConfiguration cfgCp = new CacheConfiguration(ccfg);
CacheConfigurationEnrichment enrichment = buildEnrichment(
CacheConfiguration.class, cfgCp, DEFAULT_CACHE_CONFIG);
return new T2<>(cfgCp, enrichment);
}
catch (Exception e) {
throw new IgniteException("Failed to split cache configuration", e);
}
}
/**
* Builds {@link CacheConfigurationEnrichment} from given config.
* It extracts all field values to enrichment object replacing values of that fields with default.
*
* @param cfgCls Configuration class.
* @param cfg Configuration to build enrichment from.
* @param dfltCfg Default configuration to replace enriched values with default.
* @param <T> Configuration class.
* @return Enrichment object for given config.
* @throws IllegalAccessException If failed.
*/
private <T> CacheConfigurationEnrichment buildEnrichment(
Class<T> cfgCls,
T cfg,
T dfltCfg
) throws IllegalAccessException {
Map<String, byte[]> enrichment = new HashMap<>();
Map<String, String> fieldClsNames = new HashMap<>();
for (Field field : cfgCls.getDeclaredFields()) {
if (supports(field)) {
field.setAccessible(true);
Object val = field.get(cfg);
byte[] serializedVal = serialize(field.getName(), val);
enrichment.put(field.getName(), serializedVal);
fieldClsNames.put(field.getName(), val != null ? val.getClass().getName() : null);
// Replace field in original configuration with default value.
field.set(cfg, field.get(dfltCfg));
}
}
return new CacheConfigurationEnrichment(enrichment, fieldClsNames);
}
/**
* Returns {@code true} if this splitter supports the specified field.
*
* @param field Field.
* @return True if splitter serialization is supported, false otherwise.
*/
private boolean supports(Field field) {<FILL_FUNCTION_BODY>}
/**
* @param fieldName Field name to serialize.
* @param val Field value.
*
* @return Serialized value.
*/
private byte[] serialize(String fieldName, Object val) {
try {
return U.marshal(marshaller, val);
}
catch (Exception e) {
throw new IgniteException("Failed to serialize field [fieldName=" + fieldName + ", value=" + val + ']', e);
}
}
}
|
if (field.getDeclaredAnnotation(SerializeSeparately.class) == null)
return false;
if (IgniteFeatures.allNodesSupport(ctx.config().getDiscoverySpi(), IgniteFeatures.SPLITTED_CACHE_CONFIGURATIONS_V2))
return true;
for (String filedName : FIELDS_V1) {
if (filedName.equals(field.getName()))
return true;
}
return false;
| 1,019
| 124
| 1,143
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryImpl.java
|
CacheEntryImpl
|
unwrap
|
class CacheEntryImpl<K, V> implements Cache.Entry<K, V>, Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** */
private K key;
/** */
private V val;
/** Entry version. */
private GridCacheVersion ver;
/**
* Required by {@link Externalizable}.
*/
public CacheEntryImpl() {
// No-op.
}
/**
* @param key Key.
* @param val Value.
*/
public CacheEntryImpl(K key, V val) {
this.key = key;
this.val = val;
}
/**
* @param key Key.
* @param val Value.
* @param ver Entry version.
*/
public CacheEntryImpl(K key, V val, GridCacheVersion ver) {
this.key = key;
this.val = val;
this.ver = ver;
}
/** {@inheritDoc} */
@Override public K getKey() {
return key;
}
/** {@inheritDoc} */
@Override public V getValue() {
return val;
}
/** {@inheritDoc} */
@Override public <T> T unwrap(Class<T> cls) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(key);
out.writeObject(val);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
key = (K)in.readObject();
val = (V)in.readObject();
}
/** {@inheritDoc} */
@Override public String toString() {
return "Entry [key=" + key + ", val=" + val + ']';
}
}
|
if (cls.isAssignableFrom(getClass()))
return cls.cast(this);
if (cls.isAssignableFrom(CacheEntry.class))
return (T)new CacheEntryImplEx<>(key, val, ver);
throw new IllegalArgumentException("Unwrapping to class is not supported: " + cls);
| 493
| 87
| 580
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntryInfoCollection.java
|
CacheEntryInfoCollection
|
writeTo
|
class CacheEntryInfoCollection implements Message {
/** */
private static final long serialVersionUID = 0L;
/** */
@GridDirectCollection(GridCacheEntryInfo.class)
private List<GridCacheEntryInfo> infos;
/** */
public CacheEntryInfoCollection() {
// No-op
}
/**
* @param infos List of cache entry info.
*/
public CacheEntryInfoCollection(List<GridCacheEntryInfo> infos) {
this.infos = infos;
}
/**
*
*/
public void init() {
infos = new ArrayList<>();
}
/**
* @return Entries.
*/
public List<GridCacheEntryInfo> infos() {
return infos;
}
/**
* @param info Entry.
*/
public void add(GridCacheEntryInfo info) {
infos.add(info);
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
infos = reader.readCollection("infos", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(CacheEntryInfoCollection.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return 92;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 1;
}
/** {@inheritDoc} */
@Override public String toString() {
StringBuilder b = new StringBuilder();
b.append("[");
for (int i = 0; i < infos().size(); i++) {
GridCacheEntryInfo info = infos().get(i);
Object k = info.key().value(null, false);
b.append("[key=").append(k == null ? "null" : k).append(", ver=").
append(info.version()).append(", val=").append(info.value()).append(']');
}
b.append(']');
return b.toString();
}
}
|
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeCollection("infos", infos, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
}
return true;
| 673
| 121
| 794
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeResult.java
|
CacheInvokeResult
|
get
|
class CacheInvokeResult<T> implements EntryProcessorResult<T>, Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** */
@GridToStringInclude(sensitive = true)
private T res;
/** */
private Exception err;
/**
* Empty constructor required by {@link Externalizable}.
*/
public CacheInvokeResult() {
// No-op.
}
/**
* Static constructor.
*
* @param res Computed result.
* @return New instance.
*/
public static <T> CacheInvokeResult<T> fromResult(T res) {
CacheInvokeResult<T> cacheRes = new CacheInvokeResult<>();
cacheRes.res = res;
return cacheRes;
}
/**
* @return Result.
*/
public T result() {
return res;
}
/**
* Entry processor error;
*/
public Exception error() {
return err;
}
/**
* Static constructor.
*
* @param err Exception thrown by {@link EntryProcessor#process(MutableEntry, Object...)}.
* @return New instance.
*/
public static <T> CacheInvokeResult<T> fromError(Exception err) {
assert err != null;
CacheInvokeResult<T> res = new CacheInvokeResult<>();
res.err = err;
return res;
}
/** {@inheritDoc} */
@Override public T get() throws EntryProcessorException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(res);
out.writeObject(err);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
res = (T)in.readObject();
err = (Exception)in.readObject();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(CacheInvokeResult.class, this);
}
}
|
if (err != null) {
if (err instanceof UnregisteredClassException || err instanceof UnregisteredBinaryTypeException)
throw (IgniteException)err;
if (err instanceof EntryProcessorException)
throw (EntryProcessorException)err;
throw new EntryProcessorException(err);
}
return res;
| 558
| 85
| 643
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheJoinNodeDiscoveryData.java
|
CacheInfo
|
readObject
|
class CacheInfo implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** */
@GridToStringInclude
private StoredCacheData cacheData;
/** */
@GridToStringInclude
private CacheType cacheType;
/** */
@GridToStringInclude
private boolean sql;
/** Flags added for future usage. */
private long flags;
/** Statically configured flag */
private boolean staticallyConfigured;
/**
* @param cacheData Cache data.
* @param cacheType Cache type.
* @param sql SQL flag - {@code true} if cache was created with {@code CREATE TABLE}.
* @param flags Flags (for future usage).
* @param staticallyConfigured {@code true} if it was configured by static config and {@code false} otherwise.
*/
public CacheInfo(StoredCacheData cacheData, CacheType cacheType, boolean sql, long flags,
boolean staticallyConfigured) {
this.cacheData = cacheData;
this.cacheType = cacheType;
this.sql = sql;
this.flags = flags;
this.staticallyConfigured = staticallyConfigured;
}
/**
* @return Cache data.
*/
public StoredCacheData cacheData() {
return cacheData;
}
/**
* @return Cache type.
*/
public CacheType cacheType() {
return cacheType;
}
/**
* @return SQL flag - {@code true} if cache was created with {@code CREATE TABLE}.
*/
public boolean sql() {
return sql;
}
/**
* @return {@code true} if it was configured by static config and {@code false} otherwise.
*/
public boolean isStaticallyConfigured() {
return staticallyConfigured;
}
/**
* @return Long which bits represent some flags.
*/
public long getFlags() {
return flags;
}
/**
* @param ois ObjectInputStream.
*/
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(CacheInfo.class, this);
}
}
|
ObjectInputStream.GetField gf = ois.readFields();
cacheData = (StoredCacheData)gf.get("cacheData", null);
cacheType = (CacheType)gf.get("cacheType", null);
sql = gf.get("sql", false);
flags = gf.get("flags", 0L);
staticallyConfigured = gf.get("staticallyConfigured", true);
| 594
| 109
| 703
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheObjectAdapter.java
|
CacheObjectAdapter
|
putValue
|
class CacheObjectAdapter implements CacheObject, Externalizable {
/** */
private static final long serialVersionUID = 2006765505127197251L;
/** Head size. */
protected static final int HEAD_SIZE = 5; // 4 bytes len + 1 byte type
/** */
@GridToStringInclude(sensitive = true)
@GridDirectTransient
protected Object val;
/** */
protected byte[] valBytes;
/**
* @param ctx Context.
* @return {@code True} need to copy value returned to user.
*/
protected boolean needCopy(CacheObjectValueContext ctx) {
return ctx.copyOnGet() && val != null && !ctx.kernalContext().cacheObjects().immutable(val);
}
/**
* @return Value bytes from value.
*/
protected byte[] valueBytesFromValue(CacheObjectValueContext ctx) throws IgniteCheckedException {
byte[] bytes = ctx.kernalContext().cacheObjects().marshal(ctx, val);
return CacheObjectTransformerUtils.transformIfNecessary(bytes, ctx);
}
/**
* @return Value from value bytes.
*/
protected Object valueFromValueBytes(CacheObjectValueContext ctx, ClassLoader ldr) throws IgniteCheckedException {
byte[] bytes = CacheObjectTransformerUtils.restoreIfNecessary(valBytes, ctx);
return ctx.kernalContext().cacheObjects().unmarshal(ctx, bytes, ldr);
}
/** {@inheritDoc} */
@Override public byte cacheObjectType() {
return TYPE_REGULAR;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
assert valBytes != null;
U.writeByteArray(out, valBytes);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
valBytes = U.readByteArray(in);
}
/** {@inheritDoc} */
@Override public boolean putValue(ByteBuffer buf) throws IgniteCheckedException {
assert valBytes != null : "Value bytes must be initialized before object is stored";
return putValue(buf, 0, objectPutSize(valBytes.length));
}
/** {@inheritDoc} */
@Override public int putValue(long addr) throws IgniteCheckedException {
assert valBytes != null : "Value bytes must be initialized before object is stored";
return putValue(addr, cacheObjectType(), valBytes);
}
/**
* @param addr Write address.
* @param type Object type.
* @param valBytes Value bytes array.
* @return Offset shift compared to initial address.
*/
public static int putValue(long addr, byte type, byte[] valBytes) {
return putValue(addr, type, valBytes, 0, valBytes.length);
}
/**
* @param addr Write address.
* @param type Object type.
* @param srcBytes Source value bytes array.
* @param srcOff Start position in sourceBytes.
* @param len Number of bytes for write.
* @return Offset shift compared to initial address.
*/
public static int putValue(long addr, byte type, byte[] srcBytes, int srcOff, int len) {
int off = 0;
PageUtils.putInt(addr, off, len);
off += 4;
PageUtils.putByte(addr, off, type);
off++;
PageUtils.putBytes(addr, off, srcBytes, srcOff, len);
off += len;
return off;
}
/** {@inheritDoc} */
@Override public boolean putValue(final ByteBuffer buf, int off, int len) throws IgniteCheckedException {
assert valBytes != null : "Value bytes must be initialized before object is stored";
return putValue(cacheObjectType(), buf, off, len, valBytes, 0);
}
/** {@inheritDoc} */
@Override public int valueBytesLength(CacheObjectContext ctx) throws IgniteCheckedException {
if (valBytes == null)
valueBytes(ctx);
return objectPutSize(valBytes.length);
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
valBytes = reader.readByteArray("valBytes");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(CacheObjectAdapter.class);
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeByteArray("valBytes", valBytes))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 1;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(S.includeSensitive() ? getClass().getSimpleName() : "CacheObject",
"val", val, true,
"hasValBytes", valBytes != null, false);
}
/**
* @param dataLen Serialized value length.
* @return Full size required to store cache object.
* @see #putValue(byte, ByteBuffer, int, int, byte[], int)
*/
public static int objectPutSize(int dataLen) {
return dataLen + HEAD_SIZE;
}
/**
* @param cacheObjType Cache object type.
* @param buf Buffer to write value to.
* @param off Offset in source binary data.
* @param len Length of the data to write.
* @param valBytes Binary data.
* @param start Start offset in binary data.
* @return {@code True} if data were successfully written.
* @throws IgniteCheckedException If failed.
*/
public static boolean putValue(byte cacheObjType,
final ByteBuffer buf,
int off,
int len,
byte[] valBytes,
final int start
) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
}
|
int dataLen = valBytes.length;
if (buf.remaining() < len)
return false;
if (off == 0 && len >= HEAD_SIZE) {
buf.putInt(dataLen);
buf.put(cacheObjType);
len -= HEAD_SIZE;
}
else if (off >= HEAD_SIZE)
off -= HEAD_SIZE;
else {
// Partial header write.
final ByteBuffer head = ByteBuffer.allocate(HEAD_SIZE);
head.order(buf.order());
head.putInt(dataLen);
head.put(cacheObjType);
head.position(off);
if (len < head.capacity())
head.limit(off + Math.min(len, head.capacity() - off));
buf.put(head);
if (head.limit() < HEAD_SIZE)
return true;
len -= HEAD_SIZE - off;
off = 0;
}
buf.put(valBytes, start + off, len);
return true;
| 1,706
| 282
| 1,988
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheObjectByteArrayImpl.java
|
CacheObjectByteArrayImpl
|
putValue
|
class CacheObjectByteArrayImpl implements CacheObject, Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** */
protected byte[] val;
/**
* Required by {@link Message}.
*/
public CacheObjectByteArrayImpl() {
// No-op.
}
/**
* @param val Value.
*/
public CacheObjectByteArrayImpl(byte[] val) {
assert val != null;
this.val = val;
}
/** {@inheritDoc} */
@Override public void finishUnmarshal(CacheObjectValueContext ctx, ClassLoader ldr) throws IgniteCheckedException {
// No-op.
}
/** {@inheritDoc} */
@Nullable @Override public <T> T value(CacheObjectValueContext ctx, boolean cpy) {
return value(ctx, cpy, null);
}
/** {@inheritDoc} */
@Nullable @Override public <T> T value(CacheObjectValueContext ctx, boolean cpy, ClassLoader ldr) {
if (cpy)
return (T)Arrays.copyOf(val, val.length);
return (T)val;
}
/** {@inheritDoc} */
@Override public byte[] valueBytes(CacheObjectValueContext ctx) throws IgniteCheckedException {
return val;
}
/** {@inheritDoc} */
@Override public boolean putValue(ByteBuffer buf) throws IgniteCheckedException {
assert val != null : "Value is not initialized";
return putValue(buf, 0, CacheObjectAdapter.objectPutSize(val.length));
}
/** {@inheritDoc} */
@Override public int putValue(long addr) throws IgniteCheckedException {
return CacheObjectAdapter.putValue(addr, cacheObjectType(), val);
}
/** {@inheritDoc} */
@Override public boolean putValue(final ByteBuffer buf, int off, int len) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int valueBytesLength(CacheObjectContext ctx) throws IgniteCheckedException {
return CacheObjectAdapter.objectPutSize(val.length);
}
/** {@inheritDoc} */
@Override public byte cacheObjectType() {
return TYPE_BYTE_ARR;
}
/** {@inheritDoc} */
@Override public boolean isPlatformType() {
return true;
}
/** {@inheritDoc} */
@Override public CacheObject prepareForCache(CacheObjectContext ctx) {
return this;
}
/** {@inheritDoc} */
@Override public void prepareMarshal(CacheObjectValueContext ctx) throws IgniteCheckedException {
// No-op.
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeByteArray("val", val))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
val = reader.readByteArray("val");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(CacheObjectByteArrayImpl.class);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
val = U.readByteArray(in);
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeByteArray(out, val);
}
/** {@inheritDoc} */
@Override public short directType() {
return 105;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 1;
}
/** {@inheritDoc} */
@Override public String toString() {
return "CacheObjectByteArrayImpl [arrLen=" + (val != null ? val.length : 0) + ']';
}
}
|
assert val != null : "Value is not initialized";
return CacheObjectAdapter.putValue(cacheObjectType(), buf, off, len, val, 0);
| 1,193
| 43
| 1,236
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheObjectImpl.java
|
CacheObjectImpl
|
finishUnmarshal
|
class CacheObjectImpl extends CacheObjectAdapter {
/** */
private static final long serialVersionUID = 0L;
/**
*
*/
public CacheObjectImpl() {
// No-op.
}
/**
* @param val Value.
* @param valBytes Value bytes.
*/
public CacheObjectImpl(Object val, byte[] valBytes) {
assert val != null || valBytes != null;
this.val = val;
this.valBytes = valBytes;
}
/** {@inheritDoc} */
@Override public boolean isPlatformType() {
return true;
}
/** {@inheritDoc} */
@Override public <T> @Nullable T value(CacheObjectValueContext ctx, boolean cpy) {
return value(ctx, cpy, null);
}
/** {@inheritDoc} */
@Nullable @Override public <T> T value(CacheObjectValueContext ctx, boolean cpy, ClassLoader ldr) {
cpy = cpy && needCopy(ctx);
try {
GridKernalContext kernalCtx = ctx.kernalContext();
IgniteCacheObjectProcessor proc = ctx.kernalContext().cacheObjects();
if (cpy) {
if (valBytes == null) {
assert val != null;
valBytes = valueBytesFromValue(ctx);
}
if (ldr == null) {
if (val != null)
ldr = val.getClass().getClassLoader();
else if (kernalCtx.config().isPeerClassLoadingEnabled())
ldr = kernalCtx.cache().context().deploy().globalLoader();
}
return (T)proc.unmarshal(ctx, valBytes, ldr);
}
if (val != null)
return (T)val;
assert valBytes != null;
Object val = valueFromValueBytes(ctx, kernalCtx.config().isPeerClassLoadingEnabled() ?
kernalCtx.cache().context().deploy().globalLoader() : null);
if (ctx.storeValue())
this.val = val;
return (T)val;
}
catch (IgniteCheckedException e) {
throw new IgniteException("Failed to unmarshall object.", e);
}
}
/** {@inheritDoc} */
@Override public byte[] valueBytes(CacheObjectValueContext ctx) throws IgniteCheckedException {
if (valBytes == null)
valBytes = valueBytesFromValue(ctx);
return valBytes;
}
/** {@inheritDoc} */
@Override public void prepareMarshal(CacheObjectValueContext ctx) throws IgniteCheckedException {
assert val != null || valBytes != null;
if (valBytes == null)
valBytes = valueBytesFromValue(ctx);
}
/** {@inheritDoc} */
@Override public void finishUnmarshal(CacheObjectValueContext ctx, ClassLoader ldr) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public short directType() {
return 89;
}
/** {@inheritDoc} */
@Override public int hashCode() {
assert false;
return super.hashCode();
}
/** {@inheritDoc} */
@Override public boolean equals(Object obj) {
assert false;
return super.equals(obj);
}
/** {@inheritDoc} */
@Override public CacheObject prepareForCache(CacheObjectContext ctx) {
return this;
}
}
|
assert val != null || valBytes != null;
if (val == null && ctx.storeValue())
val = valueFromValueBytes(ctx, ldr);
| 948
| 45
| 993
|
<methods>public non-sealed void <init>() ,public byte cacheObjectType() ,public byte fieldsCount() ,public static int objectPutSize(int) ,public boolean putValue(java.nio.ByteBuffer) throws org.apache.ignite.IgniteCheckedException,public int putValue(long) throws org.apache.ignite.IgniteCheckedException,public static int putValue(long, byte, byte[]) ,public static int putValue(long, byte, byte[], int, int) ,public boolean putValue(java.nio.ByteBuffer, int, int) throws org.apache.ignite.IgniteCheckedException,public static boolean putValue(byte, java.nio.ByteBuffer, int, int, byte[], int) throws org.apache.ignite.IgniteCheckedException,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public boolean readFrom(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageReader) ,public java.lang.String toString() ,public int valueBytesLength(org.apache.ignite.internal.processors.cache.CacheObjectContext) throws org.apache.ignite.IgniteCheckedException,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException,public boolean writeTo(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageWriter) <variables>protected static final int HEAD_SIZE,private static final long serialVersionUID,protected java.lang.Object val,protected byte[] valBytes
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/ClientCacheChangeDummyDiscoveryMessage.java
|
ClientCacheChangeDummyDiscoveryMessage
|
toString
|
class ClientCacheChangeDummyDiscoveryMessage extends AbstractCachePartitionExchangeWorkerTask
implements DiscoveryCustomMessage {
/** */
private static final long serialVersionUID = 0L;
/** */
private final UUID reqId;
/** */
private final Map<String, DynamicCacheChangeRequest> startReqs;
/** */
@GridToStringInclude
private final Set<String> cachesToClose;
/**
* @param secCtx Security context in which current task must be executed.
* @param reqId Start request ID.
* @param startReqs Caches start requests.
* @param cachesToClose Cache to close.
*/
public ClientCacheChangeDummyDiscoveryMessage(
SecurityContext secCtx,
UUID reqId,
@Nullable Map<String, DynamicCacheChangeRequest> startReqs,
@Nullable Set<String> cachesToClose
) {
super(secCtx);
assert reqId != null;
assert startReqs != null ^ cachesToClose != null;
this.reqId = reqId;
this.startReqs = startReqs;
this.cachesToClose = cachesToClose;
}
/** {@inheritDoc} */
@Override public boolean skipForExchangeMerge() {
return true;
}
/**
* @return Start request ID.
*/
UUID requestId() {
return reqId;
}
/**
* @return Cache start requests.
*/
@Nullable Map<String, DynamicCacheChangeRequest> startRequests() {
return startReqs;
}
/**
* @return Client caches to close.
*/
Set<String> cachesToClose() {
return cachesToClose;
}
/** {@inheritDoc} */
@Override public IgniteUuid id() {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Nullable @Override public DiscoveryCustomMessage ackMessage() {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public boolean isMutable() {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Nullable @Override public DiscoCache createDiscoCache(GridDiscoveryManager mgr,
AffinityTopologyVersion topVer, DiscoCache discoCache) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public String toString() {<FILL_FUNCTION_BODY>}
}
|
return S.toString(ClientCacheChangeDummyDiscoveryMessage.class, this,
"startCaches", (startReqs != null ? startReqs.keySet() : ""));
| 655
| 50
| 705
|
<methods>public org.apache.ignite.internal.processors.security.SecurityContext securityContext() <variables>private final non-sealed org.apache.ignite.internal.processors.security.SecurityContext secCtx
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/EntryProcessorResourceInjectorProxy.java
|
EntryProcessorResourceInjectorProxy
|
process
|
class EntryProcessorResourceInjectorProxy<K, V, T> implements EntryProcessor<K, V, T>, Serializable {
/** */
private static final long serialVersionUID = 0L;
/** Delegate. */
private EntryProcessor<K, V, T> delegate;
/** Injected flag. */
private transient boolean injected;
/**
* @param delegate Delegate.
*/
private EntryProcessorResourceInjectorProxy(EntryProcessor<K, V, T> delegate) {
this.delegate = delegate;
}
/** {@inheritDoc} */
@Override public T process(MutableEntry<K, V> entry, Object... arguments) throws EntryProcessorException {<FILL_FUNCTION_BODY>}
/**
* @return Delegate entry processor.
*/
public EntryProcessor<K, V, T> delegate() {
return delegate;
}
/**
* Wraps EntryProcessor if needed.
*
* @param ctx Context.
* @param proc Entry proc.
* @return Wrapped entry proc if wrapping is needed.
*/
public static <K, V, T> EntryProcessor<K, V, T> wrap(GridKernalContext ctx,
@Nullable EntryProcessor<K, V, T> proc) {
if (proc == null || proc instanceof EntryProcessorResourceInjectorProxy)
return proc;
GridResourceProcessor rsrcProc = ctx.resource();
return rsrcProc.isAnnotationsPresent(null, proc, GridResourceIoc.AnnotationSet.ENTRY_PROCESSOR) ?
new EntryProcessorResourceInjectorProxy<>(proc) : proc;
}
/**
* Unwraps EntryProcessor as Object if needed.
*
* @param obj Entry processor.
* @return Unwrapped entry processor.
*/
static Object unwrap(Object obj) {
return (obj instanceof EntryProcessorResourceInjectorProxy) ? ((EntryProcessorResourceInjectorProxy)obj).delegate() : obj;
}
}
|
if (!injected) {
GridCacheContext cctx = entry.unwrap(GridCacheContext.class);
GridResourceProcessor rsrc = cctx.kernalContext().resource();
try {
rsrc.inject(delegate, GridResourceIoc.AnnotationSet.ENTRY_PROCESSOR, cctx.name());
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
injected = true;
}
return delegate.process(entry, arguments);
| 511
| 137
| 648
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/FetchActiveTxOwnerTraceClosure.java
|
FetchActiveTxOwnerTraceClosure
|
call
|
class FetchActiveTxOwnerTraceClosure implements IgniteCallable<String> {
/** */
private static final long serialVersionUID = 0L;
/** */
private final long txOwnerThreadId;
/** */
public FetchActiveTxOwnerTraceClosure(long txOwnerThreadId) {
this.txOwnerThreadId = txOwnerThreadId;
}
/**
* Builds the stack trace dump of the transaction owner thread
*
* @return stack trace dump string
* @throws Exception If failed
*/
@Override public String call() throws Exception {<FILL_FUNCTION_BODY>}
}
|
GridStringBuilder traceDump = new GridStringBuilder("Stack trace of the transaction owner thread:\n");
try {
U.printStackTrace(txOwnerThreadId, traceDump);
}
catch (SecurityException | IllegalArgumentException e) {
traceDump = new GridStringBuilder("Could not get stack trace of the transaction owner thread: " + e.getMessage());
}
return traceDump.toString();
| 160
| 105
| 265
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheLoaderWriterStoreFactory.java
|
GridCacheLoaderWriterStoreFactory
|
create
|
class GridCacheLoaderWriterStoreFactory<K, V> implements Factory<CacheStore<K, V>> {
/** */
private static final long serialVersionUID = 0L;
/** */
private final Factory<CacheLoader<K, V>> ldrFactory;
/** */
private final Factory<CacheWriter<K, V>> writerFactory;
/**
* @param ldrFactory Loader factory.
* @param writerFactory Writer factory.
*/
GridCacheLoaderWriterStoreFactory(@Nullable Factory<CacheLoader<K, V>> ldrFactory,
@Nullable Factory<CacheWriter<K, V>> writerFactory) {
this.ldrFactory = ldrFactory;
this.writerFactory = writerFactory;
assert ldrFactory != null || writerFactory != null;
}
/** {@inheritDoc} */
@Override public CacheStore<K, V> create() {<FILL_FUNCTION_BODY>}
/**
* @return Loader factory.
*/
Factory<CacheLoader<K, V>> loaderFactory() {
return ldrFactory;
}
/**
* @return Writer factory.
*/
Factory<CacheWriter<K, V>> writerFactory() {
return writerFactory;
}
}
|
CacheLoader<K, V> ldr = ldrFactory == null ? null : ldrFactory.create();
CacheWriter<K, V> writer = writerFactory == null ? null : writerFactory.create();
return new GridCacheLoaderWriterStore<>(ldr, writer);
| 315
| 70
| 385
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheManagerAdapter.java
|
GridCacheManagerAdapter
|
onKernalStop
|
class GridCacheManagerAdapter<K, V> implements GridCacheManager<K, V> {
/** Context. */
protected GridCacheContext cctx;
/** Logger. */
protected IgniteLogger log;
/** Starting flag. */
protected final AtomicBoolean starting = new AtomicBoolean(false);
/** {@inheritDoc} */
@Override public final void start(GridCacheContext<K, V> cctx) throws IgniteCheckedException {
if (!starting.compareAndSet(false, true))
assert false : "Method start is called more than once for manager: " + this;
assert cctx != null;
this.cctx = cctx;
log = cctx.logger(getClass());
start0();
if (log.isDebugEnabled())
log.debug(startInfo());
}
/**
* @return Logger.
*/
protected IgniteLogger log() {
return log;
}
/**
* @return Context.
*/
protected GridCacheContext<K, V> context() {
return cctx;
}
/**
* @throws IgniteCheckedException If failed.
*/
protected void start0() throws IgniteCheckedException {
// No-op.
}
/** {@inheritDoc} */
@Override public final void stop(boolean cancel, boolean destroy) {
if (!starting.get())
// Ignoring attempt to stop manager that has never been started.
return;
stop0(cancel, destroy);
if (log != null && log.isDebugEnabled())
log.debug(stopInfo());
}
/**
* @param cancel Cancel flag.
* @param destroy Cache destroy flag.
*/
protected void stop0(boolean cancel, boolean destroy) {
// No-op.
}
/** {@inheritDoc} */
@Override public final void onKernalStart() throws IgniteCheckedException {
onKernalStart0();
if (log != null && log.isDebugEnabled())
log.debug(kernalStartInfo());
}
/** {@inheritDoc} */
@Override public final void onKernalStop(boolean cancel) {<FILL_FUNCTION_BODY>}
/**
* @throws IgniteCheckedException If failed.
*/
protected void onKernalStart0() throws IgniteCheckedException {
// No-op.
}
/**
* @param cancel Cancel flag.
*/
protected void onKernalStop0(boolean cancel) {
// No-op.
}
/** {@inheritDoc} */
@Override public void onDisconnected(IgniteFuture<?> reconnectFut) {
// No-op.
}
/** {@inheritDoc} */
@Override public void printMemoryStats() {
// No-op.
}
/**
* @return Start info.
*/
protected String startInfo() {
return "Cache manager started: " + cctx.name();
}
/**
* @return Stop info.
*/
protected String stopInfo() {
return "Cache manager stopped: " + cctx.name();
}
/**
* @return Start info.
*/
protected String kernalStartInfo() {
return "Cache manager received onKernalStart() callback: " + cctx.name();
}
/**
* @return Stop info.
*/
protected String kernalStopInfo() {
return "Cache manager received onKernalStop() callback: " + cctx.name();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheManagerAdapter.class, this);
}
}
|
if (!starting.get())
// Ignoring attempt to stop manager that has never been started.
return;
onKernalStop0(cancel);
if (log != null && log.isDebugEnabled())
log.debug(kernalStopInfo());
| 956
| 71
| 1,027
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/QueryCursorImpl.java
|
QueryCursorImpl
|
closeIter
|
class QueryCursorImpl<T> implements QueryCursorEx<T>, FieldsQueryCursor<T> {
/** */
private static final AtomicReferenceFieldUpdater<QueryCursorImpl, State> STATE_UPDATER =
AtomicReferenceFieldUpdater.newUpdater(QueryCursorImpl.class, State.class, "state");
/** Query executor. */
private final Iterable<T> iterExec;
/** Result type flag - result set or update counter. */
private final boolean isQry;
/** */
private Iterator<T> iter;
/** */
private volatile State state = IDLE;
/** */
private List<GridQueryFieldMetadata> fieldsMeta;
/** */
private final GridQueryCancel cancel;
/** */
private final boolean lazy;
/** Partition result. */
private PartitionResult partRes;
/**
* @param iterExec Query executor.
*/
public QueryCursorImpl(Iterable<T> iterExec) {
this(iterExec, null, true, false);
}
/**
* @param iterExec Query executor.
* @param isQry Result type flag - {@code true} for query, {@code false} for update operation.
*/
public QueryCursorImpl(Iterable<T> iterExec, GridQueryCancel cancel, boolean isQry, boolean lazy) {
this.iterExec = iterExec;
this.cancel = cancel;
this.isQry = isQry;
this.lazy = lazy;
}
/** {@inheritDoc} */
@Override public Iterator<T> iterator() {
return new AutoClosableCursorIterator<>(this, iter());
}
/**
* @return An simple iterator.
*/
protected Iterator<T> iter() {
if (!STATE_UPDATER.compareAndSet(this, IDLE, EXECUTING))
throw new IgniteException("Iterator is already fetched or query was cancelled.");
iter = iterExec.iterator();
if (!lazy && !STATE_UPDATER.compareAndSet(this, EXECUTING, COMPLETED)) {
// Handle race with cancel and make sure the iterator resources are freed correctly.
closeIter();
throw new CacheException(new QueryCancelledException());
}
assert iter != null;
if (lazy)
iter = new LazyIterator<>(iter);
return iter;
}
/** {@inheritDoc} */
@Override public List<T> getAll() {
List<T> all = new ArrayList<>();
try {
Iterator<T> iter = iter(); // Implicitly calls iterator() to do all checks.
while (iter.hasNext())
all.add(iter.next());
}
finally {
close();
}
return all;
}
/** {@inheritDoc} */
@Override public void getAll(QueryCursorEx.Consumer<T> clo) throws IgniteCheckedException {
try {
Iterator<T> iter = iter(); // Implicitly calls iterator() to do all checks.
while (iter.hasNext())
clo.consume(iter.next());
}
finally {
close();
}
}
/** {@inheritDoc} */
@Override public void close() {
while (state != CLOSED) {
if (STATE_UPDATER.compareAndSet(this, COMPLETED, CLOSED)) {
closeIter();
return;
}
if (STATE_UPDATER.compareAndSet(this, EXECUTING, CLOSED)) {
if (cancel != null)
cancel.cancel();
closeIter();
return;
}
if (STATE_UPDATER.compareAndSet(this, IDLE, CLOSED))
return;
}
}
/**
* Closes iterator.
*/
private void closeIter() {<FILL_FUNCTION_BODY>}
/**
* @return {@code true} if this cursor corresponds to a {@link ResultSet} as a result of query,
* {@code false} if query was modifying operation like INSERT, UPDATE, or DELETE.
*/
@Override public boolean isQuery() {
return isQry;
}
/**
* @param fieldsMeta SQL Fields query result metadata.
*/
public void fieldsMeta(List<GridQueryFieldMetadata> fieldsMeta) {
this.fieldsMeta = fieldsMeta;
}
/**
* @return SQL Fields query result metadata.
*/
@Override public List<GridQueryFieldMetadata> fieldsMeta() {
return fieldsMeta;
}
/** {@inheritDoc} */
@Override public String getFieldName(int idx) {
assert this.fieldsMeta != null;
GridQueryFieldMetadata metadata = fieldsMeta.get(idx);
return metadata.fieldName();
}
/** {@inheritDoc} */
@Override public int getColumnsCount() {
assert this.fieldsMeta != null;
return fieldsMeta.size();
}
/** Query cursor state */
protected enum State {
/** Idle. */
IDLE,
/** Executing. */
EXECUTING,
/** Execution completed. */
COMPLETED,
/** Closed. */
CLOSED,
}
/**
* @return Partition result.
*/
public PartitionResult partitionResult() {
return partRes;
}
/**
* @return Lazy mode flag.
*/
protected boolean lazy() {
return lazy;
}
/**
* @param partRes New partition result.
*/
public void partitionResult(PartitionResult partRes) {
this.partRes = partRes;
}
/**
* Iterator wrapper for lazy results. Updates cursor state when all rows are read,
* otherwise just delegates invocation.
*/
public class LazyIterator<Type> implements Iterator<Type>, AutoCloseable {
/** */
private final Iterator<Type> delegate;
/**
* @param delegate Iterator.
*/
public LazyIterator(Iterator<Type> delegate) {
this.delegate = delegate;
}
/** {@inheritDoc} */
@Override public boolean hasNext() {
if (delegate.hasNext())
return true;
STATE_UPDATER.compareAndSet(QueryCursorImpl.this, EXECUTING, COMPLETED);
return false;
}
/** {@inheritDoc} */
@Override public Type next() {
return delegate.next();
}
/** {@inheritDoc} */
@Override public void remove() {
delegate.remove();
}
/** {@inheritDoc} */
@Override public void forEachRemaining(java.util.function.Consumer<? super Type> action) {
delegate.forEachRemaining(action);
}
/** {@inheritDoc} */
@Override public void close() throws Exception {
if (delegate instanceof AutoCloseable)
((AutoCloseable)delegate).close();
}
}
}
|
if (iter instanceof AutoCloseable) {
try {
((AutoCloseable)iter).close();
}
catch (Exception e) {
throw new IgniteException(e);
}
}
| 1,834
| 56
| 1,890
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/affinity/GridCacheAffinityImpl.java
|
GridCacheAffinityImpl
|
mapKeysToNodes
|
class GridCacheAffinityImpl<K, V> implements Affinity<K> {
/** */
public static final String FAILED_TO_FIND_CACHE_ERR_MSG = "Failed to find cache (cache was not started " +
"yet or cache was already stopped): ";
/** Cache context. */
private GridCacheContext<K, V> cctx;
/** Logger. */
private IgniteLogger log;
/**
* @param cctx Context.
*/
public GridCacheAffinityImpl(GridCacheContext<K, V> cctx) {
this.cctx = cctx;
log = cctx.logger(getClass());
}
/** {@inheritDoc} */
@Override public int partitions() {
return cctx.group().affinityFunction().partitions();
}
/** {@inheritDoc} */
@Override public int partition(K key) {
A.notNull(key, "key");
return cctx.affinity().partition(key);
}
/** {@inheritDoc} */
@Override public boolean isPrimary(ClusterNode n, K key) {
A.notNull(n, "n", key, "key");
return cctx.affinity().primaryByKey(n, key, topologyVersion());
}
/** {@inheritDoc} */
@Override public boolean isBackup(ClusterNode n, K key) {
A.notNull(n, "n", key, "key");
return cctx.affinity().backupsByKey(key, topologyVersion()).contains(n);
}
/** {@inheritDoc} */
@Override public boolean isPrimaryOrBackup(ClusterNode n, K key) {
A.notNull(n, "n", key, "key");
return cctx.affinity().partitionBelongs(n, cctx.affinity().partition(key), topologyVersion());
}
/** {@inheritDoc} */
@Override public int[] primaryPartitions(ClusterNode n) {
A.notNull(n, "n");
Set<Integer> parts = cctx.affinity().primaryPartitions(n.id(), topologyVersion());
return U.toIntArray(parts);
}
/** {@inheritDoc} */
@Override public int[] backupPartitions(ClusterNode n) {
A.notNull(n, "n");
Set<Integer> parts = cctx.affinity().backupPartitions(n.id(), topologyVersion());
return U.toIntArray(parts);
}
/** {@inheritDoc} */
@Override public int[] allPartitions(ClusterNode n) {
A.notNull(n, "p");
Collection<Integer> parts = new HashSet<>();
AffinityTopologyVersion topVer = topologyVersion();
for (int partsCnt = partitions(), part = 0; part < partsCnt; part++) {
for (ClusterNode affNode : cctx.affinity().nodesByPartition(part, topVer)) {
if (n.id().equals(affNode.id())) {
parts.add(part);
break;
}
}
}
return U.toIntArray(parts);
}
/** {@inheritDoc} */
@Override public ClusterNode mapPartitionToNode(int part) {
A.ensure(part >= 0 && part < partitions(), "part >= 0 && part < total partitions");
return F.first(cctx.affinity().nodesByPartition(part, topologyVersion()));
}
/** {@inheritDoc} */
@Override public Map<Integer, ClusterNode> mapPartitionsToNodes(Collection<Integer> parts) {
A.notNull(parts, "parts");
Map<Integer, ClusterNode> map = new HashMap<>();
if (!F.isEmpty(parts)) {
for (int p : parts)
map.put(p, mapPartitionToNode(p));
}
return map;
}
/** {@inheritDoc} */
@Override public Object affinityKey(K key) {
A.notNull(key, "key");
if (key instanceof CacheObject && !(key instanceof BinaryObject)) {
CacheObjectContext ctx = cctx.cacheObjectContext();
if (ctx == null)
throw new IgniteException(FAILED_TO_FIND_CACHE_ERR_MSG + cctx.name());
key = ((CacheObject)key).value(ctx, false);
}
CacheConfiguration ccfg = cctx.config();
if (ccfg == null)
throw new IgniteException(FAILED_TO_FIND_CACHE_ERR_MSG + cctx.name());
return ccfg.getAffinityMapper().affinityKey(key);
}
/** {@inheritDoc} */
@Override @Nullable public ClusterNode mapKeyToNode(K key) {
A.notNull(key, "key");
return F.first(mapKeysToNodes(F.asList(key)).keySet());
}
/** {@inheritDoc} */
@Override public Map<ClusterNode, Collection<K>> mapKeysToNodes(@Nullable Collection<? extends K> keys) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public Collection<ClusterNode> mapKeyToPrimaryAndBackups(K key) {
A.notNull(key, "key");
return cctx.affinity().nodesByPartition(partition(key), topologyVersion());
}
/** {@inheritDoc} */
@Override public Collection<ClusterNode> mapPartitionToPrimaryAndBackups(int part) {
A.ensure(part >= 0 && part < partitions(), "part >= 0 && part < total partitions");
return cctx.affinity().nodesByPartition(part, topologyVersion());
}
/**
* Gets current topology version.
*
* @return Topology version.
*/
private AffinityTopologyVersion topologyVersion() {
return cctx.affinity().affinityTopologyVersion();
}
}
|
A.notNull(keys, "keys");
AffinityTopologyVersion topVer = topologyVersion();
int nodesCnt = cctx.discovery().cacheGroupAffinityNodes(cctx.groupId(), topVer).size();
// Must return empty map if no alive nodes present or keys is empty.
Map<ClusterNode, Collection<K>> res = new HashMap<>(nodesCnt, 1.0f);
for (K key : keys) {
ClusterNode primary = cctx.affinity().primaryByKey(key, topVer);
if (primary == null)
throw new IgniteException("Failed to get primary node [topVer=" + topVer + ", key=" + key + ']');
Collection<K> mapped = res.get(primary);
if (mapped == null) {
mapped = new ArrayList<>(Math.max(keys.size() / nodesCnt, 16));
res.put(primary, mapped);
}
mapped.add(key);
}
return res;
| 1,510
| 263
| 1,773
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/binary/IgniteBinaryImpl.java
|
IgniteBinaryImpl
|
registerClass
|
class IgniteBinaryImpl implements IgniteBinary {
/** */
private GridKernalContext ctx;
/** */
private IgniteCacheObjectProcessor proc;
/**
* @param ctx Context.
*/
public IgniteBinaryImpl(GridKernalContext ctx, IgniteCacheObjectProcessor proc) {
this.ctx = ctx;
this.proc = proc;
}
/** {@inheritDoc} */
@Override public int typeId(String typeName) {
guard();
try {
return proc.typeId(typeName);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <T> T toBinary(@Nullable Object obj) throws BinaryObjectException {
guard();
try {
return (T)proc.marshalToBinary(obj, false);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public BinaryObjectBuilder builder(String typeName) {
guard();
try {
return proc.builder(typeName);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public BinaryObjectBuilder builder(BinaryObject binaryObj) {
guard();
try {
return proc.builder(binaryObj);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Nullable @Override public BinaryType type(Class<?> cls) throws BinaryObjectException {
guard();
try {
return proc.metadata(proc.typeId(cls.getName()));
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Nullable @Override public BinaryType type(String typeName) throws BinaryObjectException {
guard();
try {
return proc.metadata(proc.typeId(typeName));
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Nullable @Override public BinaryType type(int typeId) throws BinaryObjectException {
guard();
try {
return proc.metadata(typeId);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public Collection<BinaryType> types() throws BinaryObjectException {
guard();
try {
return proc.metadata();
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public BinaryObject buildEnum(String typeName, int ord) {
guard();
try {
return proc.buildEnum(typeName, ord);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public BinaryObject buildEnum(String typeName, String name) {
guard();
try {
return proc.buildEnum(typeName, name);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public BinaryType registerEnum(String typeName, Map<String, Integer> vals) {
guard();
try {
return proc.registerEnum(typeName, vals);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public BinaryType registerClass(Class<?> cls) throws BinaryObjectException {<FILL_FUNCTION_BODY>}
/**
* @return Binary processor.
*/
public IgniteCacheObjectProcessor processor() {
return proc;
}
/**
* <tt>ctx.gateway().readLock()</tt>
*/
private void guard() {
ctx.gateway().readLock();
}
/**
* <tt>ctx.gateway().readUnlock()</tt>
*/
private void unguard() {
ctx.gateway().readUnlock();
}
}
|
guard();
try {
return proc.registerClass(cls);
}
finally {
unguard();
}
| 1,024
| 37
| 1,061
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/binary/MetadataRemoveProposedMessage.java
|
MetadataRemoveProposedMessage
|
ackMessage
|
class MetadataRemoveProposedMessage implements DiscoveryCustomMessage {
/** */
private static final long serialVersionUID = 0L;
/** */
private final IgniteUuid id = IgniteUuid.randomUuid();
/** Node UUID which initiated metadata update. */
private final UUID origNodeId;
/** Metadata type id. */
private final int typeId;
/** Message acceptance status. */
private ProposalStatus status = ProposalStatus.SUCCESSFUL;
/** Message received on coordinator. */
private boolean onCoordinator = true;
/** */
private BinaryObjectException err;
/**
* @param typeId Binary type ID.
* @param origNodeId ID of node requested update.
*/
public MetadataRemoveProposedMessage(int typeId, UUID origNodeId) {
assert origNodeId != null;
this.origNodeId = origNodeId;
this.typeId = typeId;
}
/** {@inheritDoc} */
@Override public IgniteUuid id() {
return id;
}
/** {@inheritDoc} */
@Nullable @Override public DiscoveryCustomMessage ackMessage() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean isMutable() {
return true;
}
/** {@inheritDoc} */
@Nullable @Override public DiscoCache createDiscoCache(GridDiscoveryManager mgr,
AffinityTopologyVersion topVer, DiscoCache discoCache) {
throw new UnsupportedOperationException();
}
/**
* @param err Error caused this update to be rejected.
*/
void markRejected(BinaryObjectException err) {
status = ProposalStatus.REJECTED;
this.err = err;
}
/** */
boolean rejected() {
return status == ProposalStatus.REJECTED;
}
/** */
BinaryObjectException rejectionError() {
return err;
}
/** */
UUID origNodeId() {
return origNodeId;
}
/** */
public int typeId() {
return typeId;
}
/** */
public boolean isOnCoordinator() {
return onCoordinator;
}
/** */
public void setOnCoordinator(boolean onCoordinator) {
this.onCoordinator = onCoordinator;
}
/** Message acceptance status. */
private enum ProposalStatus {
/** */
SUCCESSFUL,
/** */
REJECTED
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(MetadataRemoveProposedMessage.class, this);
}
}
|
return (status == ProposalStatus.SUCCESSFUL) ? new MetadataRemoveAcceptedMessage(typeId) : null;
| 711
| 35
| 746
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTtlUpdateRequest.java
|
GridCacheTtlUpdateRequest
|
prepareMarshal
|
class GridCacheTtlUpdateRequest extends GridCacheIdMessage {
/** */
private static final long serialVersionUID = 0L;
/** Entries keys. */
@GridToStringInclude
@GridDirectCollection(KeyCacheObject.class)
private List<KeyCacheObject> keys;
/** Entries versions. */
@GridDirectCollection(GridCacheVersion.class)
private List<GridCacheVersion> vers;
/** Near entries keys. */
@GridToStringInclude
@GridDirectCollection(KeyCacheObject.class)
private List<KeyCacheObject> nearKeys;
/** Near entries versions. */
@GridDirectCollection(GridCacheVersion.class)
private List<GridCacheVersion> nearVers;
/** New TTL. */
private long ttl;
/** Topology version. */
private AffinityTopologyVersion topVer;
/**
* Required empty constructor.
*/
public GridCacheTtlUpdateRequest() {
// No-op.
}
/**
* @param cacheId Cache ID.
* @param topVer Topology version.
* @param ttl TTL.
*/
public GridCacheTtlUpdateRequest(int cacheId, AffinityTopologyVersion topVer, long ttl) {
assert ttl >= 0 || ttl == CU.TTL_ZERO : ttl;
this.cacheId = cacheId;
this.topVer = topVer;
this.ttl = ttl;
}
/**
* @return Topology version.
*/
@Override public AffinityTopologyVersion topologyVersion() {
return topVer;
}
/**
* @return TTL.
*/
public long ttl() {
return ttl;
}
/**
* @param key Key.
* @param ver Version.
*/
public void addEntry(KeyCacheObject key, GridCacheVersion ver) {
if (keys == null) {
keys = new ArrayList<>();
vers = new ArrayList<>();
}
keys.add(key);
vers.add(ver);
}
/**
* @param key Key.
* @param ver Version.
*/
public void addNearEntry(KeyCacheObject key, GridCacheVersion ver) {
if (nearKeys == null) {
nearKeys = new ArrayList<>();
nearVers = new ArrayList<>();
}
nearKeys.add(key);
nearVers.add(ver);
}
/**
* @return Keys.
*/
public List<KeyCacheObject> keys() {
return keys;
}
/**
* @return Versions.
*/
public List<GridCacheVersion> versions() {
return vers;
}
/**
* @param idx Entry index.
* @return Version.
*/
public GridCacheVersion version(int idx) {
assert idx >= 0 && idx < vers.size() : idx;
return vers.get(idx);
}
/**
* @return Keys for near cache.
*/
public List<KeyCacheObject> nearKeys() {
return nearKeys;
}
/**
* @return Versions for near cache entries.
*/
public List<GridCacheVersion> nearVersions() {
return nearVers;
}
/** {@inheritDoc} */
@Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr)
throws IgniteCheckedException {
super.finishUnmarshal(ctx, ldr);
GridCacheContext cctx = ctx.cacheContext(cacheId);
finishUnmarshalCacheObjects(keys, cctx, ldr);
finishUnmarshalCacheObjects(nearKeys, cctx, ldr);
}
/** {@inheritDoc} */
@Override public boolean addDeploymentInfo() {
return false;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!super.writeTo(buf, writer))
return false;
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 4:
if (!writer.writeCollection("keys", keys, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
case 5:
if (!writer.writeCollection("nearKeys", nearKeys, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
case 6:
if (!writer.writeCollection("nearVers", nearVers, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
case 7:
if (!writer.writeAffinityTopologyVersion("topVer", topVer))
return false;
writer.incrementState();
case 8:
if (!writer.writeLong("ttl", ttl))
return false;
writer.incrementState();
case 9:
if (!writer.writeCollection("vers", vers, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
if (!super.readFrom(buf, reader))
return false;
switch (reader.state()) {
case 4:
keys = reader.readCollection("keys", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
case 5:
nearKeys = reader.readCollection("nearKeys", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
case 6:
nearVers = reader.readCollection("nearVers", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
case 7:
topVer = reader.readAffinityTopologyVersion("topVer");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 8:
ttl = reader.readLong("ttl");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 9:
vers = reader.readCollection("vers", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridCacheTtlUpdateRequest.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return 20;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 10;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheTtlUpdateRequest.class, this, "super", super.toString());
}
}
|
super.prepareMarshal(ctx);
GridCacheContext cctx = ctx.cacheContext(cacheId);
prepareMarshalCacheObjects(keys, cctx);
prepareMarshalCacheObjects(nearKeys, cctx);
| 1,922
| 59
| 1,981
|
<methods>public non-sealed void <init>() ,public boolean cacheGroupMessage() ,public int cacheId() ,public void cacheId(int) ,public byte fieldsCount() ,public int handlerId() ,public boolean readFrom(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageReader) ,public java.lang.String toString() ,public boolean writeTo(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageWriter) <variables>protected int cacheId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryRequest.java
|
GridCacheTxRecoveryRequest
|
readFrom
|
class GridCacheTxRecoveryRequest extends GridDistributedBaseMessage {
/** */
private static final long serialVersionUID = 0L;
/** Future ID. */
private IgniteUuid futId;
/** Mini future ID. */
private IgniteUuid miniId;
/** Near transaction ID. */
private GridCacheVersion nearXidVer;
/** Expected number of transactions on node. */
private int txNum;
/** System transaction flag. */
private boolean sys;
/** {@code True} if should check only tx on near node. */
private boolean nearTxCheck;
/**
* Empty constructor required by {@link Externalizable}
*/
public GridCacheTxRecoveryRequest() {
// No-op.
}
/**
* @param tx Transaction.
* @param txNum Expected number of transactions on remote node.
* @param nearTxCheck {@code True} if should check only tx on near node.
* @param futId Future ID.
* @param miniId Mini future ID.
* @param addDepInfo Deployment info flag.
*/
public GridCacheTxRecoveryRequest(IgniteInternalTx tx,
int txNum,
boolean nearTxCheck,
IgniteUuid futId,
IgniteUuid miniId,
boolean addDepInfo
) {
super(tx.xidVersion(), 0, addDepInfo);
nearXidVer = tx.nearXidVersion();
sys = tx.system();
this.futId = futId;
this.miniId = miniId;
this.txNum = txNum;
this.nearTxCheck = nearTxCheck;
}
/**
* @return {@code True} if should check only tx on near node.
*/
public boolean nearTxCheck() {
return nearTxCheck;
}
/**
* @return Near version.
*/
public GridCacheVersion nearXidVersion() {
return nearXidVer;
}
/**
* @return Future ID.
*/
public IgniteUuid futureId() {
return futId;
}
/**
* @return Mini future ID.
*/
public IgniteUuid miniId() {
return miniId;
}
/**
* @return Expected number of transactions on node.
*/
public int transactions() {
return txNum;
}
/**
* @return System transaction flag.
*/
public boolean system() {
return sys;
}
/** {@inheritDoc} */
@Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
return ctx.txRecoveryMessageLogger();
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!super.writeTo(buf, writer))
return false;
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 8:
if (!writer.writeIgniteUuid("futId", futId))
return false;
writer.incrementState();
case 9:
if (!writer.writeIgniteUuid("miniId", miniId))
return false;
writer.incrementState();
case 10:
if (!writer.writeBoolean("nearTxCheck", nearTxCheck))
return false;
writer.incrementState();
case 11:
if (!writer.writeMessage("nearXidVer", nearXidVer))
return false;
writer.incrementState();
case 12:
if (!writer.writeBoolean("sys", sys))
return false;
writer.incrementState();
case 13:
if (!writer.writeInt("txNum", txNum))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public short directType() {
return 16;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 14;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheTxRecoveryRequest.class, this, "super", super.toString());
}
}
|
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
if (!super.readFrom(buf, reader))
return false;
switch (reader.state()) {
case 8:
futId = reader.readIgniteUuid("futId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 9:
miniId = reader.readIgniteUuid("miniId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 10:
nearTxCheck = reader.readBoolean("nearTxCheck");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 11:
nearXidVer = reader.readMessage("nearXidVer");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 12:
sys = reader.readBoolean("sys");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 13:
txNum = reader.readInt("txNum");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridCacheTxRecoveryRequest.class);
| 1,185
| 365
| 1,550
|
<methods>public boolean addDeploymentInfo() ,public Collection<org.apache.ignite.internal.processors.cache.version.GridCacheVersion> committedVersions() ,public void completedVersions(Collection<org.apache.ignite.internal.processors.cache.version.GridCacheVersion>, Collection<org.apache.ignite.internal.processors.cache.version.GridCacheVersion>) ,public boolean readFrom(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageReader) ,public Collection<org.apache.ignite.internal.processors.cache.version.GridCacheVersion> rolledbackVersions() ,public java.lang.String toString() ,public org.apache.ignite.internal.processors.cache.version.GridCacheVersion version() ,public void version(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) ,public boolean writeTo(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageWriter) <variables>private byte[] candsByIdxBytes,private int cnt,private Collection<org.apache.ignite.internal.processors.cache.version.GridCacheVersion> committedVers,private Collection<org.apache.ignite.internal.processors.cache.version.GridCacheVersion> rolledbackVers,private static final long serialVersionUID,protected org.apache.ignite.internal.processors.cache.version.GridCacheVersion ver
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxMapping.java
|
GridDistributedTxMapping
|
addBackups
|
class GridDistributedTxMapping {
/** */
private static final AtomicReferenceFieldUpdater<GridDistributedTxMapping, Set> BACKUPS_FIELD_UPDATER
= AtomicReferenceFieldUpdater.newUpdater(GridDistributedTxMapping.class, Set.class, "backups");
/** Mapped node. */
@GridToStringExclude
private final ClusterNode primary;
/** Mapped backup nodes. */
private volatile Set<UUID> backups;
/** Entries. */
@GridToStringInclude
private final Collection<IgniteTxEntry> entries;
/** Explicit lock flag. */
private boolean explicitLock;
/** Query update flag. */
private boolean queryUpdate;
/** DHT version. */
private GridCacheVersion dhtVer;
/** {@code True} if this is last mapping for node. */
private boolean last;
/** Near cache entries count. */
private int nearEntries;
/** {@code True} if this is first mapping for optimistic tx on client node. */
private boolean clientFirst;
/**
* @param primary Primary node.
*/
public GridDistributedTxMapping(ClusterNode primary) {
this.primary = primary;
entries = new LinkedHashSet<>();
}
/**
* @return {@code True} if this is last mapping for node.
*/
public boolean last() {
return last;
}
/**
* @param last If {@code True} this is last mapping for node.
*/
public void last(boolean last) {
this.last = last;
}
/**
* @return {@code True} if this is first mapping for optimistic tx on client node.
*/
public boolean clientFirst() {
return clientFirst;
}
/**
* @param clientFirst {@code True} if this is first mapping for optimistic tx on client node.
*/
public void clientFirst(boolean clientFirst) {
this.clientFirst = clientFirst;
}
/**
* @return {@code True} if has colocated cache entries.
*/
public boolean hasColocatedCacheEntries() {
return entries.size() > nearEntries;
}
/**
* @return {@code True} if has near cache entries.
*/
public boolean hasNearCacheEntries() {
return nearEntries > 0;
}
/**
* @return Node.
*/
public ClusterNode primary() {
return primary;
}
/**
* @return Entries.
*/
public Collection<IgniteTxEntry> entries() {
return entries;
}
/**
* @return Near cache entries.
*/
@Nullable public Collection<IgniteTxEntry> nearCacheEntries() {
assert nearEntries > 0;
return F.view(entries, CU.FILTER_NEAR_CACHE_ENTRY);
}
/**
* @return {@code True} if mapping was created for a query update.
*/
public boolean queryUpdate() {
return queryUpdate;
}
/**
* Sets query update flag to {@code true}.
*/
public void markQueryUpdate() {
queryUpdate = true;
}
/**
* @return {@code True} if lock is explicit.
*/
public boolean explicitLock() {
return explicitLock;
}
/**
* Sets explicit flag to {@code true}.
*/
public void markExplicitLock() {
explicitLock = true;
}
/**
* @return DHT version.
*/
public GridCacheVersion dhtVersion() {
return dhtVer;
}
/**
* @param dhtVer DHT version.
* @param writeVer DHT writeVersion.
*/
public void dhtVersion(GridCacheVersion dhtVer, GridCacheVersion writeVer) {
this.dhtVer = dhtVer;
for (IgniteTxEntry e : entries)
e.dhtVersion(writeVer);
}
/**
* @return Reads.
*/
public Collection<IgniteTxEntry> reads() {
return F.view(entries, CU.READ_FILTER);
}
/**
* @return Writes.
*/
public Collection<IgniteTxEntry> writes() {
return F.view(entries, CU.WRITE_FILTER);
}
/**
* @return Near cache reads.
*/
public Collection<IgniteTxEntry> nearEntriesReads() {
assert hasNearCacheEntries();
return F.view(entries, CU.READ_FILTER_NEAR);
}
/**
* @return Near cache writes.
*/
public Collection<IgniteTxEntry> nearEntriesWrites() {
assert hasNearCacheEntries();
return F.view(entries, CU.WRITE_FILTER_NEAR);
}
/**
* @return Colocated cache reads.
*/
public Collection<IgniteTxEntry> colocatedEntriesReads() {
assert hasColocatedCacheEntries();
return F.view(entries, CU.READ_FILTER_COLOCATED);
}
/**
* @return Colocated cache writes.
*/
public Collection<IgniteTxEntry> colocatedEntriesWrites() {
assert hasColocatedCacheEntries();
return F.view(entries, CU.WRITE_FILTER_COLOCATED);
}
/**
* @param entry Adds entry.
*/
public void add(IgniteTxEntry entry) {
if (entries.add(entry) && entry.context().isNear())
nearEntries++;
}
/**
* @param entry Entry to remove.
* @return {@code True} if entry was removed.
*/
public boolean removeEntry(IgniteTxEntry entry) {
return entries.remove(entry);
}
/**
* @param keys Keys to evict readers for.
*/
public void evictReaders(@Nullable Collection<IgniteTxKey> keys) {
if (keys == null || keys.isEmpty())
return;
evictReaders(keys, entries);
}
/**
* @param keys Keys to evict readers for.
* @param entries Entries to check.
*/
private void evictReaders(Collection<IgniteTxKey> keys, @Nullable Collection<IgniteTxEntry> entries) {
if (entries == null || entries.isEmpty())
return;
for (Iterator<IgniteTxEntry> it = entries.iterator(); it.hasNext();) {
IgniteTxEntry entry = it.next();
if (keys.contains(entry.txKey()))
it.remove();
}
}
/**
* Whether empty or not.
*
* @return Empty or not.
*/
public boolean empty() {
return entries.isEmpty();
}
/**
* @param newBackups Backups to be added to this mapping.
*/
public void addBackups(Collection<UUID> newBackups) {<FILL_FUNCTION_BODY>}
/**
* @return Mapped backup nodes.
*/
public Set<UUID> backups() {
return backups != null ? backups : Collections.emptySet();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridDistributedTxMapping.class, this, "node", primary.id());
}
}
|
if (newBackups == null)
return;
if (backups == null)
BACKUPS_FIELD_UPDATER.compareAndSet(this, null, Collections.newSetFromMap(new ConcurrentHashMap<>()));
backups.addAll(newBackups);
| 1,941
| 76
| 2,017
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/IgniteExternalizableExpiryPolicy.java
|
IgniteExternalizableExpiryPolicy
|
writeDuration
|
class IgniteExternalizableExpiryPolicy implements ExpiryPolicy, Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** */
private ExpiryPolicy plc;
/** */
private static final byte CREATE_TTL_MASK = 0x01;
/** */
private static final byte UPDATE_TTL_MASK = 0x02;
/** */
private static final byte ACCESS_TTL_MASK = 0x04;
/** */
private Duration forCreate;
/** */
private Duration forUpdate;
/** */
private Duration forAccess;
/**
* Required by {@link Externalizable}.
*/
public IgniteExternalizableExpiryPolicy() {
// No-op.
}
/**
* @param plc Expiry policy.
*/
public IgniteExternalizableExpiryPolicy(ExpiryPolicy plc) {
assert plc != null;
this.plc = plc;
}
/** {@inheritDoc} */
@Override public Duration getExpiryForCreation() {
return forCreate;
}
/** {@inheritDoc} */
@Override public Duration getExpiryForAccess() {
return forAccess;
}
/** {@inheritDoc} */
@Override public Duration getExpiryForUpdate() {
return forUpdate;
}
/**
* @param out Output stream.
* @param duration Duration.
* @throws IOException If failed.
*/
private void writeDuration(ObjectOutput out, @Nullable Duration duration) throws IOException {<FILL_FUNCTION_BODY>}
/**
* @param in Input stream.
* @return Duration.
* @throws IOException If failed.
*/
private Duration readDuration(ObjectInput in) throws IOException {
long ttl = in.readLong();
assert ttl >= 0 || ttl == CU.TTL_ZERO : ttl;
if (ttl == 0)
return Duration.ETERNAL;
else if (ttl == CU.TTL_ZERO)
return Duration.ZERO;
return new Duration(TimeUnit.MILLISECONDS, ttl);
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
byte flags = 0;
Duration create = plc.getExpiryForCreation();
if (create != null)
flags |= CREATE_TTL_MASK;
Duration update = plc.getExpiryForUpdate();
if (update != null)
flags |= UPDATE_TTL_MASK;
Duration access = plc.getExpiryForAccess();
if (access != null)
flags |= ACCESS_TTL_MASK;
out.writeByte(flags);
writeDuration(out, create);
writeDuration(out, update);
writeDuration(out, access);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
byte flags = in.readByte();
if ((flags & CREATE_TTL_MASK) != 0)
forCreate = readDuration(in);
if ((flags & UPDATE_TTL_MASK) != 0)
forUpdate = readDuration(in);
if ((flags & ACCESS_TTL_MASK) != 0)
forAccess = readDuration(in);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(IgniteExternalizableExpiryPolicy.class, this);
}
}
|
if (duration != null) {
if (duration.getDurationAmount() == 0L) {
if (duration.isEternal())
out.writeLong(0);
else
out.writeLong(CU.TTL_ZERO);
}
else
out.writeLong(duration.getTimeUnit().toMillis(duration.getDurationAmount()));
}
| 945
| 99
| 1,044
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtUnreservedPartitionException.java
|
GridDhtUnreservedPartitionException
|
toString
|
class GridDhtUnreservedPartitionException extends IgniteCheckedException {
/** */
private static final long serialVersionUID = 0L;
/** Partition. */
private final int part;
/** Topology version. */
private final AffinityTopologyVersion topVer;
/**
* @param part Partition.
* @param topVer Affinity topology version.
* @param msg Message.
*/
public GridDhtUnreservedPartitionException(int part, AffinityTopologyVersion topVer, String msg) {
super(msg);
this.part = part;
this.topVer = topVer;
}
/**
* @return Partition.
*/
public int partition() {
return part;
}
/**
* @return Affinity topology version.
*/
public AffinityTopologyVersion topologyVersion() {
return topVer;
}
/** {@inheritDoc} */
@Override public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass() + " [part=" + part + ", msg=" + getMessage() + ']';
| 262
| 30
| 292
|
<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, boolean) ,public void <init>(java.lang.String, java.lang.Throwable) ,public T getCause(Class<T>) ,public final transient boolean hasCause(Class<? extends java.lang.Throwable>[]) ,public java.lang.String toString() <variables>private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/PartitionUpdateCountersMessage.java
|
PartitionUpdateCountersMessage
|
readFrom
|
class PartitionUpdateCountersMessage implements Message {
/** */
private static final int ITEM_SIZE = 4 /* partition */ + 8 /* initial counter */ + 8 /* updates count */;
/** */
private static final long serialVersionUID = 193442457510062844L;
/** */
private byte data[];
/** */
private int cacheId;
/** */
@GridDirectTransient
private int size;
/** Used for assigning counters to cache entries during tx finish. */
@GridDirectTransient
private Map<Integer, Long> counters;
/** */
public PartitionUpdateCountersMessage() {
// No-op.
}
/**
* @param cacheId Cache id.
* @param initSize Initial size.
*/
public PartitionUpdateCountersMessage(int cacheId, int initSize) {
assert initSize >= 1;
this.cacheId = cacheId;
data = new byte[initSize * ITEM_SIZE];
}
/**
* @return Cache id.
*/
public int cacheId() {
return cacheId;
}
/**
* @return Size.
*/
public int size() {
return size;
}
/**
* @param idx Item number.
* @return Partition number.
*/
public int partition(int idx) {
if (idx >= size)
throw new ArrayIndexOutOfBoundsException();
long off = GridUnsafe.BYTE_ARR_OFF + idx * ITEM_SIZE;
return GridUnsafe.getInt(data, off);
}
/**
* @param idx Item number.
* @return Partition number.
*/
public long initialCounter(int idx) {
if (idx >= size)
throw new ArrayIndexOutOfBoundsException();
long off = GridUnsafe.BYTE_ARR_OFF + idx * ITEM_SIZE + 4;
return GridUnsafe.getLong(data, off);
}
/**
* @param idx Item number.
* @param value Initial partition counter.
*/
public void initialCounter(int idx, long value) {
if (idx >= size)
throw new ArrayIndexOutOfBoundsException();
long off = GridUnsafe.BYTE_ARR_OFF + idx * ITEM_SIZE + 4;
GridUnsafe.putLong(data, off, value);
}
/**
* @param idx Item number.
* @return Update counter delta.
*/
public long updatesCount(int idx) {
if (idx >= size)
throw new ArrayIndexOutOfBoundsException();
long off = GridUnsafe.BYTE_ARR_OFF + idx * ITEM_SIZE + 12;
return GridUnsafe.getLong(data, off);
}
/**
* @param part Partition number.
* @param init Init partition counter.
* @param updatesCnt Update counter delta.
*/
public void add(int part, long init, long updatesCnt) {
ensureSpace(size + 1);
long off = GridUnsafe.BYTE_ARR_OFF + size++ * ITEM_SIZE;
GridUnsafe.putInt(data, off, part); off += 4;
GridUnsafe.putLong(data, off, init); off += 8;
GridUnsafe.putLong(data, off, updatesCnt);
}
/**
* Calculate next counter for partition.
*
* @param partId Partition id.
*
* @return Next counter for partition.
*/
public Long nextCounter(int partId) {
if (counters == null) {
counters = U.newHashMap(size);
for (int i = 0; i < size; i++)
counters.put(partition(i), initialCounter(i));
}
return counters.computeIfPresent(partId, (key, cntr) -> cntr + 1);
}
/**
* Clears message.
*/
public void clear() {
size = 0;
}
/**
* Check if there is enough space is allocated.
*
* @param newSize Size to ensure.
*/
private void ensureSpace(int newSize) {
int req = newSize * ITEM_SIZE;
if (data.length < req)
data = Arrays.copyOf(data, data.length << 1);
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeInt("cacheId", cacheId))
return false;
writer.incrementState();
case 1:
if (!writer.writeByteArray("data", data, 0, size * ITEM_SIZE))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public short directType() {
return 157;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 2;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append("[part=")
.append(partition(i))
.append(", initCntr=")
.append(initialCounter(i))
.append(", cntr=")
.append(updatesCount(i))
.append(']');
}
return "PartitionUpdateCountersMessage{" +
"cacheId=" + cacheId +
", size=" + size +
", cntrs=" + sb +
'}';
}
}
|
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
cacheId = reader.readInt("cacheId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
data = reader.readByteArray("data");
if (!reader.isLastRead())
return false;
size = data.length / ITEM_SIZE;
reader.incrementState();
}
return reader.afterMessageRead(PartitionUpdateCountersMessage.class);
| 1,638
| 163
| 1,801
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicCheckUpdateRequest.java
|
GridNearAtomicCheckUpdateRequest
|
writeTo
|
class GridNearAtomicCheckUpdateRequest extends GridCacheIdMessage {
/** */
private static final long serialVersionUID = 0L;
/** Cache message index. */
public static final int CACHE_MSG_IDX = nextIndexId();
/** */
@GridDirectTransient
private GridNearAtomicAbstractUpdateRequest updateReq;
/** */
private int partId;
/** */
private long futId;
/**
*
*/
public GridNearAtomicCheckUpdateRequest() {
// No-op.
}
/**
* @param updateReq Related update request.
*/
GridNearAtomicCheckUpdateRequest(GridNearAtomicAbstractUpdateRequest updateReq) {
assert updateReq != null && updateReq.fullSync() : updateReq;
this.updateReq = updateReq;
this.cacheId = updateReq.cacheId();
this.partId = updateReq.partition();
this.futId = updateReq.futureId();
assert partId >= 0;
}
/**
* @return Future ID on near node.
*/
public final long futureId() {
return futId;
}
/**
* @return Related update request.
*/
GridNearAtomicAbstractUpdateRequest updateRequest() {
return updateReq;
}
/** {@inheritDoc} */
@Override public int partition() {
return partId;
}
/** {@inheritDoc} */
@Override public int lookupIndex() {
return CACHE_MSG_IDX;
}
/** {@inheritDoc} */
@Override public boolean addDeploymentInfo() {
return false;
}
/** {@inheritDoc} */
@Override public short directType() {
return -50;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 6;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
if (!super.readFrom(buf, reader))
return false;
switch (reader.state()) {
case 4:
futId = reader.readLong("futId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 5:
partId = reader.readInt("partId");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridNearAtomicCheckUpdateRequest.class);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridNearAtomicCheckUpdateRequest.class, this);
}
}
|
writer.setBuffer(buf);
if (!super.writeTo(buf, writer))
return false;
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 4:
if (!writer.writeLong("futId", futId))
return false;
writer.incrementState();
case 5:
if (!writer.writeInt("partId", partId))
return false;
writer.incrementState();
}
return true;
| 786
| 169
| 955
|
<methods>public non-sealed void <init>() ,public boolean cacheGroupMessage() ,public int cacheId() ,public void cacheId(int) ,public byte fieldsCount() ,public int handlerId() ,public boolean readFrom(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageReader) ,public java.lang.String toString() ,public boolean writeTo(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageWriter) <variables>protected int cacheId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtDetachedCacheEntry.java
|
GridDhtDetachedCacheEntry
|
storeValue
|
class GridDhtDetachedCacheEntry extends GridDistributedCacheEntry {
/**
* @param ctx Cache context.
* @param key Cache key.
*/
public GridDhtDetachedCacheEntry(GridCacheContext ctx, KeyCacheObject key) {
super(ctx, key);
}
/**
* Sets value to detached entry so it can be retrieved in transactional gets.
*
* @param val Value.
* @param ver Version.
*/
public void resetFromPrimary(CacheObject val, GridCacheVersion ver) {
value(val);
this.ver = ver;
}
/** {@inheritDoc} */
@Nullable @Override public CacheDataRow unswap(CacheDataRow row, boolean checkExpire) throws IgniteCheckedException {
return null;
}
/** {@inheritDoc} */
@Override protected void value(@Nullable CacheObject val) {
this.val = val;
}
/** {@inheritDoc} */
@Override protected boolean storeValue(CacheObject val,
long expireTime,
GridCacheVersion ver) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override protected void logUpdate(
GridCacheOperation op,
CacheObject val,
GridCacheVersion writeVer,
long expireTime,
long updCntr,
boolean primary
) throws IgniteCheckedException {
// No-op for detached entries, index is updated on primary or backup nodes.
}
/** {@inheritDoc} */
@Override protected WALPointer logTxUpdate(
IgniteInternalTx tx,
CacheObject val,
GridCacheVersion writeVer,
long expireTime,
long updCntr
) {
return null;
}
/** {@inheritDoc} */
@Override protected void removeValue() throws IgniteCheckedException {
// No-op for detached entries, index is updated on primary or backup nodes.
}
/** {@inheritDoc} */
@Override public boolean detached() {
return true;
}
/** {@inheritDoc} */
@Override public String toString() {
return toStringWithTryLock(() -> S.toString(GridDhtDetachedCacheEntry.class, this, "super", super.toString()));
}
/** {@inheritDoc} */
@Override public boolean addRemoved(GridCacheVersion ver) {
// No-op for detached cache entry.
return true;
}
/** {@inheritDoc} */
@Override public int partition() {
return cctx.affinity().partition(key);
}
}
|
return false;
// No-op for detached entries, index is updated on primary nodes.
| 663
| 26
| 689
|
<methods>public void <init>(GridCacheContext#RAW, org.apache.ignite.internal.processors.cache.KeyCacheObject) ,public org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate addLocal(long, org.apache.ignite.internal.processors.cache.version.GridCacheVersion, org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion, long, boolean, boolean, boolean, boolean) throws org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException,public void addRemote(java.util.UUID, java.util.UUID, long, org.apache.ignite.internal.processors.cache.version.GridCacheVersion, boolean, boolean, org.apache.ignite.internal.processors.cache.version.GridCacheVersion) throws org.apache.ignite.internal.processors.cache.distributed.GridDistributedLockCancelledException, org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException,public boolean addRemoved(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) ,public void doneRemote(org.apache.ignite.internal.processors.cache.version.GridCacheVersion, org.apache.ignite.internal.processors.cache.version.GridCacheVersion, Collection<org.apache.ignite.internal.processors.cache.version.GridCacheVersion>, Collection<org.apache.ignite.internal.processors.cache.version.GridCacheVersion>, Collection<org.apache.ignite.internal.processors.cache.version.GridCacheVersion>, boolean) throws org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException,public org.apache.ignite.internal.processors.cache.CacheLockCandidates readyLock(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) throws org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException,public void readyNearLock(org.apache.ignite.internal.processors.cache.version.GridCacheVersion, org.apache.ignite.internal.processors.cache.version.GridCacheVersion, Collection<org.apache.ignite.internal.processors.cache.version.GridCacheVersion>, Collection<org.apache.ignite.internal.processors.cache.version.GridCacheVersion>, Collection<org.apache.ignite.internal.processors.cache.version.GridCacheVersion>) throws org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException,public boolean recheck(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) ,public transient Collection<org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate> remoteMvccSnapshot(org.apache.ignite.internal.processors.cache.version.GridCacheVersion[]) ,public void removeExplicitNodeLocks(java.util.UUID) throws org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException,public org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate removeLock() ,public boolean removeLock(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) throws org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException,public boolean tmLock(org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx, long, org.apache.ignite.internal.processors.cache.version.GridCacheVersion, org.apache.ignite.internal.processors.cache.version.GridCacheVersion, boolean) throws org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException, org.apache.ignite.internal.processors.cache.distributed.GridDistributedLockCancelledException,public java.lang.String toString() <variables>private volatile List<org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate> rmts
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysRequest.java
|
GridDhtForceKeysRequest
|
writeTo
|
class GridDhtForceKeysRequest extends GridCacheIdMessage implements GridCacheDeployable {
/** */
private static final long serialVersionUID = 0L;
/** Future ID. */
private IgniteUuid futId;
/** Mini-future ID. */
private IgniteUuid miniId;
/** Keys to request. */
@GridToStringInclude
@GridDirectCollection(KeyCacheObject.class)
private Collection<KeyCacheObject> keys;
/** Topology version for which keys are requested. */
private AffinityTopologyVersion topVer;
/**
* Required by {@link Externalizable}.
*/
public GridDhtForceKeysRequest() {
// No-op.
}
/**
* @param cacheId Cache ID.
* @param futId Future ID.
* @param miniId Mini-future ID.
* @param keys Keys.
* @param topVer Topology version.
* @param addDepInfo Deployment info.
*/
GridDhtForceKeysRequest(
int cacheId,
IgniteUuid futId,
IgniteUuid miniId,
Collection<KeyCacheObject> keys,
AffinityTopologyVersion topVer,
boolean addDepInfo
) {
assert futId != null;
assert miniId != null;
assert !F.isEmpty(keys);
this.cacheId = cacheId;
this.futId = futId;
this.miniId = miniId;
this.keys = keys;
this.topVer = topVer;
this.addDepInfo = addDepInfo;
}
/**
* @return Future ID.
*/
public IgniteUuid futureId() {
return futId;
}
/**
* @return Mini-future ID.
*/
public IgniteUuid miniId() {
return miniId;
}
/**
* @return Keys.
*/
public Collection<KeyCacheObject> keys() {
return keys;
}
/**
* @return Topology version for which keys are requested.
*/
@Override public AffinityTopologyVersion topologyVersion() {
return topVer;
}
/** {@inheritDoc} */
@Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {
super.prepareMarshal(ctx);
GridCacheContext cctx = ctx.cacheContext(cacheId);
prepareMarshalCacheObjects(keys, cctx);
}
/** {@inheritDoc} */
@Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
super.finishUnmarshal(ctx, ldr);
GridCacheContext cctx = ctx.cacheContext(cacheId);
finishUnmarshalCacheObjects(keys, cctx, ldr);
}
/** {@inheritDoc} */
@Override public boolean addDeploymentInfo() {
return addDepInfo;
}
/**
* @return Key count.
*/
private int keyCount() {
return keys.size();
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
if (!super.readFrom(buf, reader))
return false;
switch (reader.state()) {
case 4:
futId = reader.readIgniteUuid("futId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 5:
keys = reader.readCollection("keys", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
case 6:
miniId = reader.readIgniteUuid("miniId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 7:
topVer = reader.readAffinityTopologyVersion("topVer");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridDhtForceKeysRequest.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return 42;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 8;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridDhtForceKeysRequest.class, this, "keyCnt", keyCount(), "super", super.toString());
}
}
|
writer.setBuffer(buf);
if (!super.writeTo(buf, writer))
return false;
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 4:
if (!writer.writeIgniteUuid("futId", futId))
return false;
writer.incrementState();
case 5:
if (!writer.writeCollection("keys", keys, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
case 6:
if (!writer.writeIgniteUuid("miniId", miniId))
return false;
writer.incrementState();
case 7:
if (!writer.writeAffinityTopologyVersion("topVer", topVer))
return false;
writer.incrementState();
}
return true;
| 1,249
| 259
| 1,508
|
<methods>public non-sealed void <init>() ,public boolean cacheGroupMessage() ,public int cacheId() ,public void cacheId(int) ,public byte fieldsCount() ,public int handlerId() ,public boolean readFrom(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageReader) ,public java.lang.String toString() ,public boolean writeTo(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageWriter) <variables>protected int cacheId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionSupplyMessageV2.java
|
GridDhtPartitionSupplyMessageV2
|
writeTo
|
class GridDhtPartitionSupplyMessageV2 extends GridDhtPartitionSupplyMessage {
/** */
private static final long serialVersionUID = 0L;
/** Available since. */
public static final IgniteProductVersion AVAILABLE_SINCE = IgniteProductVersion.fromString("2.7.0");
/** Supplying process error. */
@GridDirectTransient
private Throwable err;
/** Supplying process error bytes. */
private byte[] errBytes;
/**
* Default constructor.
*/
public GridDhtPartitionSupplyMessageV2() {
}
/**
* @param rebalanceId Rebalance id.
* @param grpId Group id.
* @param topVer Topology version.
* @param addDepInfo Add dep info.
* @param err Supply process error.
*/
public GridDhtPartitionSupplyMessageV2(
long rebalanceId,
int grpId,
AffinityTopologyVersion topVer,
boolean addDepInfo,
Throwable err
) {
super(rebalanceId, grpId, topVer, addDepInfo);
this.err = err;
}
/** {@inheritDoc} */
@Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {
super.prepareMarshal(ctx);
if (err != null && errBytes == null)
errBytes = U.marshal(ctx, err);
}
/** {@inheritDoc} */
@Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
super.finishUnmarshal(ctx, ldr);
if (errBytes != null && err == null)
err = U.unmarshal(ctx, errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
if (!super.readFrom(buf, reader))
return false;
switch (reader.state()) {
case 13:
errBytes = reader.readByteArray("errBytes");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridDhtPartitionSupplyMessageV2.class);
}
/** {@inheritDoc} */
@Nullable @Override public Throwable error() {
return err;
}
/** {@inheritDoc} */
@Override public short directType() {
return 158;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 14;
}
}
|
writer.setBuffer(buf);
if (!super.writeTo(buf, writer))
return false;
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 13:
if (!writer.writeByteArray("errBytes", errBytes))
return false;
writer.incrementState();
}
return true;
| 762
| 134
| 896
|
<methods>public void <init>() ,public boolean addDeploymentInfo() ,public void addEstimatedKeysCount(long) ,public void addKeysForCache(int, long) ,public short directType() ,public long estimatedKeysCount() ,public byte fieldsCount() ,public void finishUnmarshal(GridCacheSharedContext#RAW, java.lang.ClassLoader) throws org.apache.ignite.IgniteCheckedException,public boolean ignoreClassErrors() ,public long keysForCache(int) ,public boolean readFrom(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageReader) ,public int size() ,public java.lang.String toString() ,public org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion topologyVersion() ,public boolean writeTo(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageWriter) <variables>private Collection<java.lang.Integer> clean,private long estimatedKeysCnt,private Map<java.lang.Integer,org.apache.ignite.internal.processors.cache.CacheEntryInfoCollection> infos,private Map<java.lang.Integer,java.lang.Long> keysPerCache,private Map<java.lang.Integer,java.lang.Long> last,private Collection<java.lang.Integer> missed,private int msgSize,private long rebalanceId,private static final long serialVersionUID,private org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion topVer
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/IgniteDhtPartitionCountersMap2.java
|
IgniteDhtPartitionCountersMap2
|
get
|
class IgniteDhtPartitionCountersMap2 implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** */
private Map<Integer, CachePartitionFullCountersMap> map;
/**
* @return {@code True} if map is empty.
*/
public synchronized boolean empty() {
return map == null || map.isEmpty();
}
/**
* @param cacheId Cache ID.
* @param cntrMap Counters map.
*/
public synchronized void putIfAbsent(int cacheId, CachePartitionFullCountersMap cntrMap) {
if (map == null)
map = new HashMap<>();
if (!map.containsKey(cacheId))
map.put(cacheId, cntrMap);
}
/**
* @param cacheId Cache ID.
* @return Counters map.
*/
public synchronized CachePartitionFullCountersMap get(int cacheId) {<FILL_FUNCTION_BODY>}
}
|
if (map == null)
return null;
CachePartitionFullCountersMap cntrMap = map.get(cacheId);
if (cntrMap == null)
return null;
return cntrMap;
| 259
| 63
| 322
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/IgniteDhtPartitionsToReloadMap.java
|
IgniteDhtPartitionsToReloadMap
|
put
|
class IgniteDhtPartitionsToReloadMap implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** */
private Map<UUID, Map<Integer, Set<Integer>>> map;
/**
* @param nodeId Node ID.
* @param cacheId Cache ID.
* @return Collection of partitions to reload.
*/
public synchronized Set<Integer> get(UUID nodeId, int cacheId) {
if (map == null)
return Collections.emptySet();
Map<Integer, Set<Integer>> nodeMap = map.get(nodeId);
if (nodeMap == null)
return Collections.emptySet();
Set<Integer> parts = nodeMap.get(cacheId);
if (parts == null)
return Collections.emptySet();
return parts;
}
/**
* @param nodeId Node ID.
* @param cacheId Cache ID.
* @param partId Partition ID.
*/
public synchronized void put(UUID nodeId, int cacheId, int partId) {<FILL_FUNCTION_BODY>}
/**
* @return {@code True} if empty.
*/
public synchronized boolean isEmpty() {
return map == null || map.isEmpty();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(IgniteDhtPartitionsToReloadMap.class, this);
}
}
|
if (map == null)
map = new HashMap<>();
Map<Integer, Set<Integer>> nodeMap = map.get(nodeId);
if (nodeMap == null) {
nodeMap = new HashMap<>();
map.put(nodeId, nodeMap);
}
Set<Integer> parts = nodeMap.get(cacheId);
if (parts == null) {
parts = new HashSet<>();
nodeMap.put(cacheId, parts);
}
parts.add(partId);
| 375
| 140
| 515
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/IgniteRebalanceIteratorImpl.java
|
IgniteRebalanceIteratorImpl
|
remove
|
class IgniteRebalanceIteratorImpl implements IgniteRebalanceIterator {
/** */
private static final long serialVersionUID = 0L;
/** Iterators for full preloading, ordered by partition ID. */
@Nullable private final NavigableMap<Integer, GridCloseableIterator<CacheDataRow>> fullIterators;
/** Iterator for historical preloading. */
@Nullable private final IgniteHistoricalIterator historicalIterator;
/** Partitions marked as missing. */
private final Set<Integer> missingParts = new HashSet<>();
/** Current full iterator. */
private Map.Entry<Integer, GridCloseableIterator<CacheDataRow>> current;
/** Next value. */
private CacheDataRow cached;
/** */
private boolean reachedEnd;
/** */
private boolean closed;
/**
* @param fullIterators
* @param historicalIterator
* @throws IgniteCheckedException
*/
public IgniteRebalanceIteratorImpl(
NavigableMap<Integer, GridCloseableIterator<CacheDataRow>> fullIterators,
IgniteHistoricalIterator historicalIterator) throws IgniteCheckedException {
this.fullIterators = fullIterators;
this.historicalIterator = historicalIterator;
advance();
}
/** */
private synchronized void advance() throws IgniteCheckedException {
if (fullIterators.isEmpty())
reachedEnd = true;
while (!reachedEnd && (current == null || !current.getValue().hasNextX() || missingParts.contains(current.getKey()))) {
if (current == null)
current = fullIterators.firstEntry();
else {
current = fullIterators.ceilingEntry(current.getKey() + 1);
if (current == null)
reachedEnd = true;
}
}
assert current != null || reachedEnd;
}
/** {@inheritDoc} */
@Override public synchronized boolean historical(int partId) {
return historicalIterator != null && historicalIterator.contains(partId);
}
/** {@inheritDoc} */
@Override public synchronized boolean isPartitionDone(int partId) {
if (missingParts.contains(partId))
return false;
if (historical(partId))
return historicalIterator.isDone(partId);
if (cached != null)
return cached.partition() > partId;
return current == null || current.getKey() > partId;
}
/** {@inheritDoc} */
@Override public synchronized boolean isPartitionMissing(int partId) {
return missingParts.contains(partId);
}
/** {@inheritDoc} */
@Override public synchronized void setPartitionMissing(int partId) {
missingParts.add(partId);
}
/** {@inheritDoc} */
@Override public synchronized boolean hasNextX() throws IgniteCheckedException {
if (historicalIterator != null && historicalIterator.hasNextX())
return true;
return current != null && current.getValue().hasNextX();
}
/** {@inheritDoc} */
@Override public synchronized CacheDataRow nextX() throws IgniteCheckedException {
if (historicalIterator != null && historicalIterator.hasNextX())
return historicalIterator.nextX();
if (current == null || !current.getValue().hasNextX())
throw new NoSuchElementException();
CacheDataRow result = current.getValue().nextX();
assert result.partition() == current.getKey();
advance();
return result;
}
/** {@inheritDoc} */
@Override public synchronized CacheDataRow peek() {
if (cached == null) {
if (!hasNext())
return null;
cached = next();
}
return cached;
}
/** {@inheritDoc} */
@Override public synchronized void removeX() throws IgniteCheckedException {
throw new UnsupportedOperationException("remove");
}
/** {@inheritDoc} */
@Override public synchronized void close() throws IgniteCheckedException {
cached = null;
if (historicalIterator != null)
historicalIterator.close();
if (fullIterators != null) {
for (GridCloseableIterator<CacheDataRow> iter : fullIterators.values())
iter.close();
}
closed = true;
}
/** {@inheritDoc} */
@Override public synchronized boolean isClosed() {
return closed;
}
/** {@inheritDoc} */
@Override public synchronized Iterator<CacheDataRow> iterator() {
return this;
}
/** {@inheritDoc} */
@Override public synchronized boolean hasNext() {
try {
if (cached != null)
return true;
return hasNextX();
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
}
/** {@inheritDoc} */
@Override public synchronized CacheDataRow next() {
try {
if (cached != null) {
CacheDataRow res = cached;
cached = null;
return res;
}
return nextX();
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
}
/** {@inheritDoc} */
@Override public synchronized void remove() {<FILL_FUNCTION_BODY>}
}
|
try {
removeX();
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
| 1,383
| 40
| 1,423
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/topology/PartitionDefferedDeleteQueueCleanupTask.java
|
PartitionDefferedDeleteQueueCleanupTask
|
run
|
class PartitionDefferedDeleteQueueCleanupTask implements GridTimeoutObject {
/** */
private final IgniteUuid id = IgniteUuid.randomUuid();
/** */
private final long endTime;
/** */
private final long timeout;
/** */
private final GridCacheSharedContext cctx;
/** */
private final IgniteLogger log;
/**
* @param timeout Timeout.
*/
public PartitionDefferedDeleteQueueCleanupTask(GridCacheSharedContext cctx, long timeout) {
this.timeout = timeout;
endTime = U.currentTimeMillis() + timeout;
this.cctx = cctx;
log = cctx.logger(getClass());
}
/** {@inheritDoc} */
@Override public IgniteUuid timeoutId() {
return id;
}
/** {@inheritDoc} */
@Override public long endTime() {
return endTime;
}
/** {@inheritDoc} */
@Override public void onTimeout() {
cctx.kernalContext().closure().runLocalSafe(new GridPlainRunnable() {
@Override public void run() {<FILL_FUNCTION_BODY>}
}, true);
}
}
|
try {
for (CacheGroupContext grp : cctx.cache().cacheGroups()) {
if (grp.affinityNode()) {
GridDhtPartitionTopology top = null;
try {
top = grp.topology();
}
catch (IllegalStateException ignore) {
// Cache stopped.
}
if (top != null) {
for (GridDhtLocalPartition part : top.currentLocalPartitions())
part.cleanupRemoveQueue();
}
if (cctx.kernalContext().isStopping())
return;
}
}
}
catch (Exception e) {
U.error(log, "Failed to cleanup removed cache items: " + e, e);
}
if (cctx.kernalContext().isStopping())
return;
// Re-schedule task after finish.
cctx.time().addTimeoutObject(new PartitionDefferedDeleteQueueCleanupTask(cctx, timeout));
| 317
| 254
| 571
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFastFinishFuture.java
|
GridNearTxFastFinishFuture
|
finish
|
class GridNearTxFastFinishFuture extends GridFutureAdapter<IgniteInternalTx> implements NearTxFinishFuture {
/** */
private final GridNearTxLocal tx;
/** */
private final boolean commit;
/**
* @param tx Transaction.
* @param commit Commit flag.
*/
GridNearTxFastFinishFuture(GridNearTxLocal tx, boolean commit) {
this.tx = tx;
this.commit = commit;
}
/** {@inheritDoc} */
@Override public boolean commit() {
return commit;
}
/** {@inheritDoc} */
@Override public GridNearTxLocal tx() {
return tx;
}
/**
* @param clearThreadMap {@code True} if need remove tx from thread map.
*/
@Override public void finish(boolean commit, boolean clearThreadMap, boolean onTimeout) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void onNodeStop(IgniteCheckedException e) {
onDone(tx, e);
}
}
|
try {
if (commit) {
tx.state(PREPARING);
tx.state(PREPARED);
tx.state(COMMITTING);
tx.context().tm().fastFinishTx(tx, true, true);
tx.state(COMMITTED);
}
else {
tx.state(PREPARING);
tx.state(PREPARED);
tx.state(ROLLING_BACK);
tx.context().tm().fastFinishTx(tx, false, clearThreadMap);
tx.state(ROLLED_BACK);
}
}
finally {
onDone(tx);
}
| 277
| 171
| 448
|
<methods>public non-sealed void <init>() ,public boolean cancel() throws org.apache.ignite.IgniteCheckedException,public IgniteInternalFuture<T> chain(IgniteClosure<? super IgniteInternalFuture<org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx>,T>) ,public IgniteInternalFuture<T> chain(IgniteOutClosure<T>) ,public IgniteInternalFuture<T> chain(IgniteClosure<? super IgniteInternalFuture<org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx>,T>, java.util.concurrent.Executor) ,public IgniteInternalFuture<T> chain(IgniteOutClosure<T>, java.util.concurrent.Executor) ,public IgniteInternalFuture<T> chainCompose(IgniteClosure<? super IgniteInternalFuture<org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx>,IgniteInternalFuture<T>>) ,public IgniteInternalFuture<T> chainCompose(IgniteClosure<? super IgniteInternalFuture<org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx>,IgniteInternalFuture<T>>, java.util.concurrent.Executor) ,public java.lang.Throwable error() ,public org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx get() throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx get(long) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx get(long, java.util.concurrent.TimeUnit) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx getUninterruptibly() throws org.apache.ignite.IgniteCheckedException,public void ignoreInterrupts() ,public boolean isCancelled() ,public boolean isDone() ,public boolean isFailed() ,public void listen(IgniteInClosure<? super IgniteInternalFuture<org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx>>) ,public void listen(org.apache.ignite.lang.IgniteRunnable) ,public org.apache.ignite.IgniteLogger logger() ,public boolean onCancelled() ,public final boolean onDone() ,public final boolean onDone(org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx) ,public final boolean onDone(java.lang.Throwable) ,public boolean onDone(org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx, java.lang.Throwable) ,public void reset() ,public org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx result() ,public java.lang.String toString() <variables>private static final java.lang.Object CANCELLED,private static final java.lang.String DONE,private static final org.apache.ignite.internal.util.future.GridFutureAdapter.Node INIT,private volatile boolean ignoreInterrupts,private volatile java.lang.Object state,private static final AtomicReferenceFieldUpdater<GridFutureAdapter#RAW,java.lang.Object> stateUpdater
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/IgniteTxMappingsImpl.java
|
IgniteTxMappingsImpl
|
localMapping
|
class IgniteTxMappingsImpl implements IgniteTxMappings {
/** */
private final Map<UUID, GridDistributedTxMapping> mappings = new ConcurrentHashMap<>();
/** {@inheritDoc} */
@Override public void clear() {
mappings.clear();
}
/** {@inheritDoc} */
@Override public boolean empty() {
return mappings.isEmpty();
}
/** {@inheritDoc} */
@Override public GridDistributedTxMapping get(UUID nodeId) {
return mappings.get(nodeId);
}
/** {@inheritDoc} */
@Override public void put(GridDistributedTxMapping mapping) {
mappings.put(mapping.primary().id(), mapping);
}
/** {@inheritDoc} */
@Override public GridDistributedTxMapping remove(UUID nodeId) {
return mappings.remove(nodeId);
}
/** {@inheritDoc} */
@Nullable @Override public GridDistributedTxMapping localMapping() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean single() {
return false;
}
/** {@inheritDoc} */
@Nullable @Override public GridDistributedTxMapping singleMapping() {
assert mappings.size() == 1 : mappings;
return F.firstValue(mappings);
}
/** {@inheritDoc} */
@Override public Collection<GridDistributedTxMapping> mappings() {
return mappings.values();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(IgniteTxMappingsImpl.class, this);
}
}
|
for (GridDistributedTxMapping m : mappings.values()) {
if (m.primary().isLocal())
return m;
}
return null;
| 419
| 45
| 464
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/extras/GridCacheAttributesObsoleteEntryExtras.java
|
GridCacheAttributesObsoleteEntryExtras
|
mvcc
|
class GridCacheAttributesObsoleteEntryExtras extends GridCacheEntryExtrasAdapter {
/** Obsolete version. */
private GridCacheVersion obsoleteVer;
/**
* Constructor.
*
* @param obsoleteVer Obsolete version.
*/
GridCacheAttributesObsoleteEntryExtras(GridCacheVersion obsoleteVer) {
assert obsoleteVer != null;
this.obsoleteVer = obsoleteVer;
}
/** {@inheritDoc} */
@Override public GridCacheEntryExtras mvcc(GridCacheMvcc mvcc) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public GridCacheVersion obsoleteVersion() {
return obsoleteVer;
}
/** {@inheritDoc} */
@Override public GridCacheEntryExtras obsoleteVersion(GridCacheVersion obsoleteVer) {
if (obsoleteVer != null) {
this.obsoleteVer = obsoleteVer;
return this;
}
else
return new GridCacheAttributesEntryExtras();
}
/** {@inheritDoc} */
@Override public GridCacheEntryExtras ttlAndExpireTime(long ttl, long expireTime) {
return expireTime != CU.EXPIRE_TIME_ETERNAL ? new GridCacheAttributesObsoleteTtlEntryExtras(obsoleteVer, ttl, expireTime) :
this;
}
/** {@inheritDoc} */
@Override public int size() {
return 8;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheAttributesObsoleteEntryExtras.class, this);
}
}
|
return mvcc != null ? new GridCacheAttributesMvccObsoleteEntryExtras(mvcc, obsoleteVer) : this;
| 446
| 38
| 484
|
<methods>public non-sealed void <init>() ,public long expireTime() ,public org.apache.ignite.internal.processors.cache.GridCacheMvcc mvcc() ,public org.apache.ignite.internal.processors.cache.version.GridCacheVersion obsoleteVersion() ,public long ttl() <variables>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/extras/GridCacheAttributesObsoleteTtlEntryExtras.java
|
GridCacheAttributesObsoleteTtlEntryExtras
|
obsoleteVersion
|
class GridCacheAttributesObsoleteTtlEntryExtras extends GridCacheEntryExtrasAdapter {
/** Obsolete version. */
private GridCacheVersion obsoleteVer;
/** TTL. */
private long ttl;
/** Expire time. */
private long expireTime;
/**
* Constructor.
*
* @param obsoleteVer Obsolete version.
* @param ttl TTL.
* @param expireTime Expire time.
*/
GridCacheAttributesObsoleteTtlEntryExtras(GridCacheVersion obsoleteVer,
long ttl, long expireTime) {
assert obsoleteVer != null;
assert expireTime != CU.EXPIRE_TIME_ETERNAL;
this.obsoleteVer = obsoleteVer;
this.ttl = ttl;
this.expireTime = expireTime;
}
/** {@inheritDoc} */
@Override public GridCacheEntryExtras mvcc(GridCacheMvcc mvcc) {
return mvcc != null ? new GridCacheAttributesMvccObsoleteTtlEntryExtras(mvcc, obsoleteVer, ttl,
expireTime) : this;
}
/** {@inheritDoc} */
@Override public GridCacheVersion obsoleteVersion() {
return obsoleteVer;
}
/** {@inheritDoc} */
@Override public GridCacheEntryExtras obsoleteVersion(GridCacheVersion obsoleteVer) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public long ttl() {
return ttl;
}
/** {@inheritDoc} */
@Override public long expireTime() {
return expireTime;
}
/** {@inheritDoc} */
@Override public GridCacheEntryExtras ttlAndExpireTime(long ttl, long expireTime) {
if (expireTime != CU.EXPIRE_TIME_ETERNAL) {
this.ttl = ttl;
this.expireTime = expireTime;
return this;
}
else
return new GridCacheAttributesObsoleteEntryExtras(obsoleteVer);
}
/** {@inheritDoc} */
@Override public int size() {
return 24;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheAttributesObsoleteTtlEntryExtras.class, this);
}
}
|
if (obsoleteVer != null) {
this.obsoleteVer = obsoleteVer;
return this;
}
else
return new GridCacheAttributesTtlEntryExtras(ttl, expireTime);
| 640
| 62
| 702
|
<methods>public non-sealed void <init>() ,public long expireTime() ,public org.apache.ignite.internal.processors.cache.GridCacheMvcc mvcc() ,public org.apache.ignite.internal.processors.cache.version.GridCacheVersion obsoleteVersion() ,public long ttl() <variables>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/extras/GridCacheMvccObsoleteEntryExtras.java
|
GridCacheMvccObsoleteEntryExtras
|
mvcc
|
class GridCacheMvccObsoleteEntryExtras extends GridCacheEntryExtrasAdapter {
/** MVCC. */
private GridCacheMvcc mvcc;
/** Obsolete version. */
private GridCacheVersion obsoleteVer;
/**
* Constructor.
*
* @param mvcc MVCC.
* @param obsoleteVer Obsolete version.
*/
GridCacheMvccObsoleteEntryExtras(GridCacheMvcc mvcc, GridCacheVersion obsoleteVer) {
assert mvcc != null;
assert obsoleteVer != null;
this.mvcc = mvcc;
this.obsoleteVer = obsoleteVer;
}
/** {@inheritDoc} */
@Override public GridCacheMvcc mvcc() {
return mvcc;
}
/** {@inheritDoc} */
@Override public GridCacheEntryExtras mvcc(GridCacheMvcc mvcc) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public GridCacheVersion obsoleteVersion() {
return obsoleteVer;
}
/** {@inheritDoc} */
@Override public GridCacheEntryExtras obsoleteVersion(GridCacheVersion obsoleteVer) {
if (obsoleteVer != null) {
this.obsoleteVer = obsoleteVer;
return this;
}
else
return new GridCacheMvccEntryExtras(mvcc);
}
/** {@inheritDoc} */
@Override public GridCacheEntryExtras ttlAndExpireTime(long ttl, long expireTime) {
return expireTime != CU.EXPIRE_TIME_ETERNAL ? new GridCacheMvccObsoleteTtlEntryExtras(mvcc, obsoleteVer, ttl, expireTime) : this;
}
/** {@inheritDoc} */
@Override public int size() {
return 16;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheMvccObsoleteEntryExtras.class, this);
}
}
|
if (mvcc != null) {
this.mvcc = mvcc;
return this;
}
else
return new GridCacheObsoleteEntryExtras(obsoleteVer);
| 558
| 55
| 613
|
<methods>public non-sealed void <init>() ,public long expireTime() ,public org.apache.ignite.internal.processors.cache.GridCacheMvcc mvcc() ,public org.apache.ignite.internal.processors.cache.version.GridCacheVersion obsoleteVersion() ,public long ttl() <variables>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/CacheStripedExecutor.java
|
CacheStripedExecutor
|
submit
|
class CacheStripedExecutor {
/** Error appeared during submitted task execution. */
private final AtomicReference<IgniteCheckedException> error = new AtomicReference<>();
/** Delegate striped executor. */
private final StripedExecutor exec;
/** Limit number of concurrent tasks submitted to the executor. Helps to avoid OOM error. */
private final Semaphore semaphore;
/** */
public CacheStripedExecutor(StripedExecutor exec) {
this.exec = exec;
semaphore = new Semaphore(semaphorePermits(exec));
}
/**
* Submit task to striped executor.
*
* @param task Runnable task.
* @param grpId Group ID.
* @param partId Partition ID.
*/
public void submit(Runnable task, int grpId, int partId) {<FILL_FUNCTION_BODY>}
/**
* Awaits while all submitted tasks completed.
*
* @throws IgniteCheckedException if any os submitted tasks failed.
*/
public void awaitApplyComplete() throws IgniteCheckedException {
try {
// Await completion apply tasks in all stripes.
exec.awaitComplete();
}
catch (InterruptedException e) {
throw new IgniteInterruptedException(e);
}
// Checking error after all task applied.
IgniteCheckedException err = error.get();
if (err != null)
throw err;
}
/** @return {@code true} if any of submitted tasks failed. */
public boolean error() {
return error.get() != null;
}
/** @param e Error appeared during submitted task execution. */
public void onError(IgniteCheckedException e) {
error.compareAndSet(null, e);
}
/** @return Underlying striped executor. */
public StripedExecutor executor() {
return exec;
}
/**
* Calculate the maximum number of concurrent tasks for apply through the striped executor.
*
* @param exec Striped executor.
* @return Number of permits.
*/
private int semaphorePermits(StripedExecutor exec) {
// 4 task per-stripe by default.
int permits = exec.stripesCount() * 4;
long maxMemory = Runtime.getRuntime().maxMemory();
// Heuristic calculation part of heap size as a maximum number of concurrent tasks.
int permits0 = (int)((maxMemory * 0.2) / (4096 * 2));
// May be for small heap. Get a low number of permits.
if (permits0 < permits)
permits = permits0;
// Property for override any calculation.
return getInteger(IGNITE_RECOVERY_SEMAPHORE_PERMITS, permits);
}
}
|
int stripes = exec.stripesCount();
int stripe = U.stripeIdx(stripes, grpId, partId);
assert stripe >= 0 && stripe <= stripes : "idx=" + stripe + ", stripes=" + stripes;
try {
semaphore.acquire();
}
catch (InterruptedException e) {
throw new IgniteInterruptedException(e);
}
exec.execute(stripe, () -> {
// WA for avoid assert check in PageMemory, that current thread hold chpLock.
CHECKPOINT_LOCK_HOLD_COUNT.set(1);
try {
task.run();
}
catch (Throwable err) {
onError(new IgniteCheckedException("Failed to execute submitted task [grpId=" + grpId + ", partId=" + partId + ']', err));
}
finally {
CHECKPOINT_LOCK_HOLD_COUNT.set(0);
semaphore.release();
}
});
| 744
| 268
| 1,012
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/CleanCacheStoresMaintenanceAction.java
|
CleanCacheStoresMaintenanceAction
|
execute
|
class CleanCacheStoresMaintenanceAction implements MaintenanceAction<Void> {
/** */
public static final String ACTION_NAME = "clean_data_files";
/** */
private final File rootStoreDir;
/** */
private final String[] cacheStoreDirs;
/**
* @param rootStoreDir
* @param cacheStoreDirs
*/
public CleanCacheStoresMaintenanceAction(File rootStoreDir, String[] cacheStoreDirs) {
this.rootStoreDir = rootStoreDir;
this.cacheStoreDirs = cacheStoreDirs;
}
/** {@inheritDoc} */
@Override public Void execute() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public @NotNull String name() {
return ACTION_NAME;
}
/** {@inheritDoc} */
@Override public @Nullable String description() {
return "Cleans data files of cache groups";
}
}
|
for (String cacheStoreDirName : cacheStoreDirs) {
File cacheStoreDir = new File(rootStoreDir, cacheStoreDirName);
if (cacheStoreDir.exists() && cacheStoreDir.isDirectory()) {
for (File file : cacheStoreDir.listFiles()) {
if (!file.getName().equals(CACHE_DATA_FILENAME))
file.delete();
}
}
}
return null;
| 248
| 113
| 361
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/checkpoint/CheckpointEntry.java
|
GroupStateLazyStore
|
remap
|
class GroupStateLazyStore {
/** */
private static final AtomicIntegerFieldUpdater<GroupStateLazyStore> initGuardUpdater =
AtomicIntegerFieldUpdater.newUpdater(GroupStateLazyStore.class, "initGuard");
/** Cache states. Initialized lazily. */
@Nullable private volatile Map<Integer, GroupState> grpStates;
/** */
private final CountDownLatch latch;
/** */
@SuppressWarnings("unused")
private volatile int initGuard;
/** Initialization exception. */
private IgniteCheckedException initEx;
/**
* Default constructor.
*/
private GroupStateLazyStore() {
this(null);
}
/**
* Constructor with group state map.
*
* @param stateMap Group state map.
*/
GroupStateLazyStore(@Nullable Map<Integer, GroupState> stateMap) {
if (stateMap != null) {
initGuard = 1;
latch = new CountDownLatch(0);
}
else
latch = new CountDownLatch(1);
this.grpStates = stateMap;
}
/**
* @param stateRec Cache group state.
*/
private static Map<Integer, GroupState> remap(@NotNull Map<Integer, CacheState> stateRec) {<FILL_FUNCTION_BODY>}
/**
* @return Partitions' states by group id.
*/
@Nullable Map<Integer, GroupState> groupStates() {
return grpStates;
}
/**
* @param grpId Group id.
* @param part Partition id.
* @return Partition counter.
*/
private Long partitionCounter(int grpId, int part) {
assert initGuard != 0 : initGuard;
if (initEx != null || grpStates == null)
return null;
GroupState state = grpStates.get(grpId);
if (state != null) {
long cntr = state.counterByPartition(part);
return cntr < 0 ? null : cntr;
}
return null;
}
/**
* @param wal Write ahead log manager.
* @param ptr Checkpoint wal pointer.
* @throws IgniteCheckedException If failed to read WAL entry.
*/
private void initIfNeeded(
IgniteWriteAheadLogManager wal,
WALPointer ptr
) throws IgniteCheckedException {
if (initGuardUpdater.compareAndSet(this, 0, 1)) {
try (WALIterator it = wal.replay(ptr)) {
if (it.hasNextX()) {
IgniteBiTuple<WALPointer, WALRecord> tup = it.nextX();
CheckpointRecord rec = (CheckpointRecord)tup.get2();
Map<Integer, CacheState> stateRec = rec.cacheGroupStates();
grpStates = remap(stateRec);
}
else {
throw new IgniteCheckedException(
"Failed to find checkpoint record at the given WAL pointer: " + ptr);
}
}
catch (IgniteCheckedException e) {
initEx = e;
throw e;
}
finally {
latch.countDown();
}
}
else {
U.await(latch);
if (initEx != null)
throw initEx;
}
}
}
|
if (stateRec.isEmpty())
return Collections.emptyMap();
Map<Integer, GroupState> grpStates = U.newHashMap(stateRec.size());
for (Integer grpId : stateRec.keySet()) {
CacheState recState = stateRec.get(grpId);
GroupState grpState = new GroupState(recState.size());
for (int i = 0; i < recState.size(); i++) {
byte partState = recState.stateByIndex(i);
if (GridDhtPartitionState.fromOrdinal(partState) != GridDhtPartitionState.OWNING)
continue;
grpState.addPartitionCounter(
recState.partitionByIndex(i),
recState.partitionCounterByIndex(i)
);
}
grpStates.put(grpId, grpState);
}
return grpStates;
| 920
| 238
| 1,158
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/diagnostic/pagelocktracker/PageLockTrackerManager.java
|
PageLockTrackerManager
|
dumpLocksToFile
|
class PageLockTrackerManager implements LifecycleAware {
/** No-op page lock listener. */
public static final PageLockListener NOOP_LSNR = new PageLockListener() {
@Override public void onBeforeWriteLock(int cacheId, long pageId, long page) {
// No-op.
}
@Override public void onWriteLock(int cacheId, long pageId, long page, long pageAddr) {
// No-op.
}
@Override public void onWriteUnlock(int cacheId, long pageId, long page, long pageAddr) {
// No-op.
}
@Override public void onBeforeReadLock(int cacheId, long pageId, long page) {
// No-op.
}
@Override public void onReadLock(int cacheId, long pageId, long page, long pageAddr) {
// No-op.
}
@Override public void onReadUnlock(int cacheId, long pageId, long page, long pageAddr) {
// No-op.
}
@Override public void close() {
// No-op.
}
};
/** */
private static final long OVERHEAD_SIZE = 16 + 8 + 8 + 8 + 8;
/** */
private final MemoryCalculator memoryCalculator = new MemoryCalculator();
/** MXbean */
private final PageLockTrackerMXBean mxBean;
/** */
private final SharedPageLockTracker sharedPageLockTracker;
/** */
private final IgniteLogger log;
/** */
private Set<PageLockThreadState> threads;
/** */
private final String managerNameId;
/** */
private final boolean trackingEnabled;
/**
* Default constructor.
*/
public PageLockTrackerManager(IgniteLogger log) {
this(log, "mgr_" + UUID.randomUUID());
}
/**
* @param log Ignite logger.
* @param managerNameId Manager name.
*/
public PageLockTrackerManager(IgniteLogger log, String managerNameId) {
this.trackingEnabled = getInteger(IGNITE_PAGE_LOCK_TRACKER_TYPE, HEAP_LOG) != -1;
this.managerNameId = managerNameId;
this.mxBean = new PageLockTrackerMXBeanImpl(this, memoryCalculator);
this.sharedPageLockTracker = new SharedPageLockTracker(this::onHangThreads, memoryCalculator);
this.log = log;
memoryCalculator.onHeapAllocated(OVERHEAD_SIZE);
}
/**
* @param threads Hang threads.
*/
private void onHangThreads(@NotNull Set<PageLockThreadState> threads) {
assert threads != null;
// Processe only one for same list thread state.
// Protection of spam.
if (!threads.equals(this.threads)) {
this.threads = threads;
SharedPageLockTrackerDump dump = sharedPageLockTracker.dump();
StringBuilder sb = new StringBuilder();
threads.forEach(s -> {
Thread th = s.thread;
sb.append("(")
.append(th.getName())
.append("-")
.append(th.getId())
.append(", ")
.append(th.getState())
.append(")");
});
log.warning("Threads hanged: [" + sb + "]");
// If some thread is hangs
// Print to log.
log.warning(ToStringDumpHelper.toStringDump(dump));
try {
// Write dump to file.
Path path = Paths.get(U.defaultWorkDirectory(), DEFAULT_TARGET_FOLDER);
ToFileDumpProcessor.toFileDump(dump, path, managerNameId);
}
catch (IgniteCheckedException e) {
log.warning("Failed to save locks dump file.", e);
}
}
}
/**
* @param name Lock tracker name.
* @return Instance of {@link PageLockListener} for tracking lock/unlock operations.
*/
public PageLockListener createPageLockTracker(String name) {
return trackingEnabled ? sharedPageLockTracker.registerStructure(name) : NOOP_LSNR;
}
/**
* Creates a page lock dump.
*/
public SharedPageLockTrackerDump dumpLocks() {
return sharedPageLockTracker.dump();
}
/**
* Take page locks dump.
*
* @return String representation of page locks dump.
*/
public String dumpLocksToString() {
return ToStringDumpHelper.toStringDump(dumpLocks());
}
/**
* Take page locks dump and print it to console.
*/
public void dumpLocksToLog() {
log.warning(dumpLocksToString());
}
/**
* Take page locks dump and save to file.
*
* @return Absolute file path.
*/
public String dumpLocksToFile() {<FILL_FUNCTION_BODY>}
/**
* Take page locks dump and save to file for specific path.
*
* @param path Path to save file.
* @return Absolute file path.
*/
public String dumpLocksToFile(String path) {
try {
return ToFileDumpProcessor.toFileDump(dumpLocks(), Paths.get(path), managerNameId);
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
}
/**
* Getter.
*
* @return PageLockTrackerMXBean object.
*/
public PageLockTrackerMXBean mxBean() {
return mxBean;
}
/**
* @return Total heap overhead in bytes.
*/
public long getHeapOverhead() {
return memoryCalculator.getHeapUsed();
}
/**
* @return Total offheap overhead in bytes.
*/
public long getOffHeapOverhead() {
return memoryCalculator.getOffHeapUsed();
}
/**
* @return Total overhead in bytes.
*/
public long getTotalOverhead() {
return getHeapOverhead() + getOffHeapOverhead();
}
/** {@inheritDoc} */
@Override public void start() throws IgniteException {
sharedPageLockTracker.start();
}
/** {@inheritDoc} */
@Override public void stop() throws IgniteException {
sharedPageLockTracker.stop();
}
}
|
try {
Path path = Paths.get(U.defaultWorkDirectory(), DEFAULT_TARGET_FOLDER);
return ToFileDumpProcessor.toFileDump(dumpLocks(), path, managerNameId);
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
| 1,699
| 86
| 1,785
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/diagnostic/pagelocktracker/dumpprocessors/ToFileDumpProcessor.java
|
ToFileDumpProcessor
|
toFileDump
|
class ToFileDumpProcessor {
/** Date format. */
public static final DateTimeFormatter DATE_FMT = DateTimeFormatter
.ofPattern("yyyy_MM_dd_HH_mm_ss_SSS")
.withZone(ZoneId.systemDefault());
/** File name prefix. */
public static final String PREFIX_NAME = "page_lock_dump_";
/**
* @param pageLockDump Dump.
* @param dir Directory to save.
*/
public static String toFileDump(SharedPageLockTrackerDump pageLockDump, Path dir, String name) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
}
|
try {
Files.createDirectories(dir);
String dumpName = PREFIX_NAME + name + "_" + DATE_FMT.format(Instant.ofEpochMilli(pageLockDump.time));
Path file = dir.resolve(dumpName);
Files.write(file, toStringDump(pageLockDump).getBytes(StandardCharsets.UTF_8));
return file.toAbsolutePath().toString();
}
catch (IOException e) {
throw new IgniteCheckedException(e);
}
| 173
| 141
| 314
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/diagnostic/pagelocktracker/store/OffHeapPageMetaInfoStore.java
|
OffHeapPageMetaInfoStore
|
free
|
class OffHeapPageMetaInfoStore implements PageMetaInfoStore {
/** */
private static final long OVERHEAD_SIZE = 16 + 4 + 4 + 8 + 8;
/** */
private static final int PAGE_ID_OFFSET = 0;
/** */
private static final int PAGE_HEADER_ADDRESS_OFFSET = 8;
/** */
private static final int PAGE_ADDRESS_OFFSET = 16;
/** */
private static final int PAGE_META_OFFSET = 24;
/** */
private static final int ITEM_SIZE = 4;
/** */
private final int size;
/** */
private final int capacity;
/** */
private final long ptr;
/** */
private final MemoryCalculator memCalc;
/** */
public OffHeapPageMetaInfoStore(int capacity, @Nullable MemoryCalculator memCalc) {
this.capacity = capacity;
this.size = this.capacity * (8 * ITEM_SIZE);
this.ptr = allocate(size);
this.memCalc = memCalc;
if (memCalc != null) {
memCalc.onHeapAllocated(OVERHEAD_SIZE);
memCalc.onOffHeapAllocated(size);
}
}
/**
*
*/
private long allocate(int size) {
long ptr = GridUnsafe.allocateMemory(size);
GridUnsafe.zeroMemory(ptr, size);
return ptr;
}
/** {@inheritDoc} */
@Override public int capacity() {
return capacity;
}
/** {@inheritDoc} */
@Override public boolean isEmpty() {
for (int i = 0; i < size; i++) {
if (GridUnsafe.getByte(ptr + i) != 0)
return false;
}
return true;
}
/** {@inheritDoc} */
@Override public void add(int itemIdx, int op, int structureId, long pageId, long pageAddrHeader, long pageAddr) {
GridUnsafe.putLong(offset(itemIdx) + PAGE_ID_OFFSET, pageId);
GridUnsafe.putLong(offset(itemIdx) + PAGE_HEADER_ADDRESS_OFFSET, pageAddrHeader);
GridUnsafe.putLong(offset(itemIdx) + PAGE_ADDRESS_OFFSET, pageAddr);
GridUnsafe.putLong(offset(itemIdx) + PAGE_META_OFFSET, join(structureId, op));
}
/** {@inheritDoc} */
@Override public void remove(int itemIdx) {
GridUnsafe.putLong(offset(itemIdx) + PAGE_ID_OFFSET, 0);
GridUnsafe.putLong(offset(itemIdx) + PAGE_HEADER_ADDRESS_OFFSET, 0);
GridUnsafe.putLong(offset(itemIdx) + PAGE_ADDRESS_OFFSET, 0);
GridUnsafe.putLong(offset(itemIdx) + PAGE_META_OFFSET, 0);
}
/** {@inheritDoc} */
@Override public int getOperation(int itemIdx) {
long structureIdAndOp = GridUnsafe.getLong(offset(itemIdx) + PAGE_META_OFFSET);
return (int)((structureIdAndOp >> 32) & LOCK_OP_MASK);
}
/** {@inheritDoc} */
@Override public int getStructureId(int itemIdx) {
long structureIdAndOp = GridUnsafe.getLong(offset(itemIdx) + PAGE_META_OFFSET);
return (int)(structureIdAndOp);
}
/** {@inheritDoc} */
@Override public long getPageId(int itemIdx) {
return GridUnsafe.getLong(offset(itemIdx) + PAGE_ID_OFFSET);
}
/** {@inheritDoc} */
@Override public long getPageAddrHeader(int itemIdx) {
return GridUnsafe.getLong(offset(itemIdx) + PAGE_HEADER_ADDRESS_OFFSET);
}
/** {@inheritDoc} */
@Override public long getPageAddr(int itemIdx) {
return GridUnsafe.getLong(offset(itemIdx) + PAGE_ADDRESS_OFFSET);
}
/** */
private long offset(long itemIdx) {
long offset = ptr + itemIdx * 8 * ITEM_SIZE;
assert offset >= ptr && offset <= ((ptr + size) - 8 * ITEM_SIZE) : "offset=" + (offset - ptr) + ", size=" + size;
return offset;
}
/** {@inheritDoc} */
@Override public PageMetaInfoStore copy() {
long[] arr = new long[capacity * 4];
GridUnsafe.copyMemory(null, ptr, arr, GridUnsafe.LONG_ARR_OFF, size);
return new HeapPageMetaInfoStore(arr);
}
/** {@inheritDoc} */
@Override public void free() {<FILL_FUNCTION_BODY>}
/**
* Build long from two int.
*
* @param structureId Structure id.
* @param op Operation.
*/
private long join(int structureId, int op) {
long major = ((long)op) << 32;
long minor = structureId & 0xFFFFFFFFL;
return major | minor;
}
}
|
GridUnsafe.freeMemory(ptr);
if (memCalc != null) {
memCalc.onHeapFree(OVERHEAD_SIZE);
memCalc.onOffHeapFree(size);
}
| 1,424
| 61
| 1,485
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/file/AbstractFileIO.java
|
AbstractFileIO
|
writeFully
|
class AbstractFileIO implements FileIO {
/** Max io timeout milliseconds. */
private static final int MAX_IO_TIMEOUT_MS = 2000;
/**
*
*/
private interface IOOperation {
/**
* @param offs Offset.
*
* @return Number of bytes operated.
*/
public int run(int offs) throws IOException;
}
/**
* @param operation IO operation.
*
* @param num Number of bytes to operate.
*
* @return Number of bytes operated.
*/
private int fully(IOOperation operation, long position, int num, boolean write) throws IOException {
if (num > 0) {
long time = 0;
for (int i = 0; i < num; ) {
int n = operation.run(i);
if (n > 0) {
i += n;
time = 0;
}
else if (n == 0 || i > 0) {
if (!write && available(num - i, position + i) == 0)
return i;
if (time == 0)
time = System.nanoTime();
else if ((System.nanoTime() - time) >= U.millisToNanos(MAX_IO_TIMEOUT_MS)) {
String errMsg = " operation unsuccessful, timeout exceeds the maximum IO timeout ("
+ U.millisToNanos(MAX_IO_TIMEOUT_MS) + " ms). ";
if (write && (position + i) == size())
errMsg = "Write" + errMsg + "Failed to extend file.";
else {
errMsg = (write ? "Write" : "Read") + errMsg +
"Probably disk is too busy, please check your device.";
}
throw new IOException(errMsg);
}
}
else
return -1;
}
}
return num;
}
/** {@inheritDoc} */
@Override public int readFully(final ByteBuffer destBuf) throws IOException {
return fully(new IOOperation() {
@Override public int run(int offs) throws IOException {
return read(destBuf);
}
}, position(), destBuf.remaining(), false);
}
/** {@inheritDoc} */
@Override public int readFully(final ByteBuffer destBuf, final long position) throws IOException {
return fully(new IOOperation() {
@Override public int run(int offs) throws IOException {
return read(destBuf, position + offs);
}
}, position, destBuf.remaining(), false);
}
/** {@inheritDoc} */
@Override public int readFully(final byte[] buf, final int off, final int len) throws IOException {
return fully(new IOOperation() {
@Override public int run(int offs) throws IOException {
return read(buf, off + offs, len - offs);
}
}, position(), len, false);
}
/** {@inheritDoc} */
@Override public int writeFully(final ByteBuffer srcBuf) throws IOException {
return fully(new IOOperation() {
@Override public int run(int offs) throws IOException {
return write(srcBuf);
}
}, position(), srcBuf.remaining(), true);
}
/** {@inheritDoc} */
@Override public int writeFully(final ByteBuffer srcBuf, final long position) throws IOException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int writeFully(final byte[] buf, final int off, final int len) throws IOException {
return fully(new IOOperation() {
@Override public int run(int offs) throws IOException {
return write(buf, off + offs, len - offs);
}
}, position(), len, true);
}
/**
* @param requested Requested.
* @param position Position.
*
* @return Bytes available.
*/
private int available(int requested, long position) throws IOException {
long avail = size() - position;
return requested > avail ? (int)avail : requested;
}
}
|
return fully(new IOOperation() {
@Override public int run(int offs) throws IOException {
return write(srcBuf, position + offs);
}
}, position, srcBuf.remaining(), true);
| 1,048
| 57
| 1,105
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/file/AsyncFileIO.java
|
AsyncFileIO
|
read
|
class AsyncFileIO extends AbstractFileIO {
/**
* File channel associated with {@code file}
*/
private final AsynchronousFileChannel ch;
/** Native file descriptor. */
private final int fd;
/** */
private final int fsBlockSize;
/**
* Channel's position.
*/
private volatile long position;
/** */
private final ThreadLocal<ChannelOpFuture> holder;
/** */
private GridConcurrentHashSet<ChannelOpFuture> asyncFuts = new GridConcurrentHashSet<>();
/**
* Creates I/O implementation for specified {@code file}
* @param file Random access file
* @param modes Open modes.
*/
public AsyncFileIO(File file, ThreadLocal<ChannelOpFuture> holder, OpenOption... modes) throws IOException {
ch = AsynchronousFileChannel.open(file.toPath(), modes);
fd = getFileDescriptor(ch);
fsBlockSize = FileSystemUtils.getFileSystemBlockSize(fd);
this.holder = holder;
}
/**
* @param ch File channel.
* @return Native file descriptor.
*/
private static int getFileDescriptor(AsynchronousFileChannel ch) {
FileDescriptor fd = U.field(ch, "fdObj");
return U.field(fd, "fd");
}
/** {@inheritDoc} */
@Override public int getFileSystemBlockSize() {
return fsBlockSize;
}
/** {@inheritDoc} */
@Override public long getSparseSize() {
return FileSystemUtils.getSparseFileSize(fd);
}
/** {@inheritDoc} */
@Override public int punchHole(long position, int len) {
return (int)FileSystemUtils.punchHole(fd, position, len, fsBlockSize);
}
/** {@inheritDoc} */
@Override public long position() throws IOException {
return position;
}
/** {@inheritDoc} */
@Override public void position(long newPosition) throws IOException {
this.position = newPosition;
}
/** {@inheritDoc} */
@Override public int read(ByteBuffer destBuf) throws IOException {
ChannelOpFuture fut = holder.get();
fut.reset();
ch.read(destBuf, position, this, fut);
try {
return fut.getUninterruptibly();
}
catch (IgniteCheckedException e) {
throw new IOException(e);
}
}
/** {@inheritDoc} */
@Override public int read(ByteBuffer destBuf, long position) throws IOException {
ChannelOpFuture fut = holder.get();
fut.reset();
ch.read(destBuf, position, null, fut);
try {
return fut.getUninterruptibly();
}
catch (IgniteCheckedException e) {
throw new IOException(e);
}
finally {
asyncFuts.remove(fut);
}
}
/** {@inheritDoc} */
@Override public int read(byte[] buf, int off, int
length) throws IOException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int write(ByteBuffer srcBuf) throws IOException {
ChannelOpFuture fut = holder.get();
fut.reset();
ch.write(srcBuf, position, this, fut);
try {
return fut.getUninterruptibly();
}
catch (IgniteCheckedException e) {
throw new IOException(e);
}
}
/** {@inheritDoc} */
@Override public int write(ByteBuffer srcBuf, long position) throws IOException {
ChannelOpFuture fut = holder.get();
fut.reset();
asyncFuts.add(fut);
ch.write(srcBuf, position, null, fut);
try {
return fut.getUninterruptibly();
}
catch (IgniteCheckedException e) {
throw new IOException(e);
}
finally {
asyncFuts.remove(fut);
}
}
/** {@inheritDoc} */
@Override public int write(byte[] buf, int off, int len) throws IOException {
ChannelOpFuture fut = holder.get();
fut.reset();
ch.write(ByteBuffer.wrap(buf, off, len), position, this, fut);
try {
return fut.getUninterruptibly();
}
catch (IgniteCheckedException e) {
throw new IOException(e);
}
}
/** {@inheritDoc} */
@Override public MappedByteBuffer map(int sizeBytes) throws IOException {
throw new UnsupportedOperationException("AsynchronousFileChannel doesn't support mmap.");
}
/** {@inheritDoc} */
@Override public void force() throws IOException {
force(false);
}
/** {@inheritDoc} */
@Override public void force(boolean withMetadata) throws IOException {
ch.force(withMetadata);
}
/** {@inheritDoc} */
@Override public long size() throws IOException {
return ch.size();
}
/** {@inheritDoc} */
@Override public void clear() throws IOException {
ch.truncate(0);
this.position = 0;
}
/** {@inheritDoc} */
@Override public void close() throws IOException {
for (ChannelOpFuture asyncFut : asyncFuts) {
try {
asyncFut.getUninterruptibly(); // Ignore interrupts while waiting for channel close.
}
catch (IgniteCheckedException e) {
throw new IOException(e);
}
}
ch.close();
}
/** */
static class ChannelOpFuture extends GridFutureAdapter<Integer> implements CompletionHandler<Integer, AsyncFileIO> {
/** {@inheritDoc} */
@Override public void completed(Integer res, AsyncFileIO attach) {
if (attach != null) {
if (res != -1)
attach.position += res;
}
// Release waiter and allow next operation to begin.
super.onDone(res, null);
}
/** {@inheritDoc} */
@Override public void failed(Throwable exc, AsyncFileIO attach) {
super.onDone(exc);
}
}
}
|
ChannelOpFuture fut = holder.get();
fut.reset();
ch.read(ByteBuffer.wrap(buf, off, length), position, this, fut);
try {
return fut.getUninterruptibly();
}
catch (IgniteCheckedException e) {
throw new IOException(e);
}
| 1,604
| 86
| 1,690
|
<methods>public non-sealed void <init>() ,public int readFully(java.nio.ByteBuffer) throws java.io.IOException,public int readFully(java.nio.ByteBuffer, long) throws java.io.IOException,public int readFully(byte[], int, int) throws java.io.IOException,public int writeFully(java.nio.ByteBuffer) throws java.io.IOException,public int writeFully(java.nio.ByteBuffer, long) throws java.io.IOException,public int writeFully(byte[], int, int) throws java.io.IOException<variables>private static final int MAX_IO_TIMEOUT_MS
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/file/AsyncFileIOFactory.java
|
AsyncFileIOFactory
|
create
|
class AsyncFileIOFactory implements FileIOFactory {
/** */
private static final long serialVersionUID = 0L;
/** Thread local channel future holder. */
private transient volatile ThreadLocal<AsyncFileIO.ChannelOpFuture> holder = initHolder();
/** {@inheritDoc} */
@Override public FileIO create(File file, OpenOption... modes) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Initializes thread local channel future holder.
*/
private ThreadLocal<AsyncFileIO.ChannelOpFuture> initHolder() {
return new ThreadLocal<AsyncFileIO.ChannelOpFuture>() {
@Override protected AsyncFileIO.ChannelOpFuture initialValue() {
return new AsyncFileIO.ChannelOpFuture();
}
};
}
}
|
if (holder == null) {
synchronized (this) {
if (holder == null)
holder = initHolder();
}
}
return new AsyncFileIO(file, holder, modes);
| 196
| 57
| 253
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/file/UnzipFileIO.java
|
UnzipFileIO
|
position
|
class UnzipFileIO extends AbstractFileIO {
/** Zip input stream. */
private final ZipInputStream zis;
/** Byte array for draining data. */
private final byte[] arr = new byte[128 * 1024];
/** Size of uncompressed data. */
private final long size;
/** Total bytes read counter. */
private long totalBytesRead = 0;
/**
* @param zip Compressed file.
*/
public UnzipFileIO(File zip) throws IOException {
zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zip)));
ZipEntry entry = zis.getNextEntry();
size = entry.getSize();
}
/** {@inheritDoc} */
@Override public int getFileSystemBlockSize() {
return -1;
}
/** {@inheritDoc} */
@Override public long getSparseSize() {
return -1;
}
/** {@inheritDoc} */
@Override public int punchHole(long position, int len) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public long position() throws IOException {
return totalBytesRead;
}
/** {@inheritDoc} */
@Override public void position(long newPosition) throws IOException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int read(ByteBuffer dstBuf) throws IOException {
int bytesRead = zis.read(arr, 0, Math.min(dstBuf.remaining(), arr.length));
if (bytesRead == -1)
return -1;
dstBuf.put(arr, 0, bytesRead);
totalBytesRead += bytesRead;
return bytesRead;
}
/** {@inheritDoc} */
@Override public int read(ByteBuffer dstBuf, long position) throws IOException {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public int read(byte[] buf, int off, int len) throws IOException {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public int write(ByteBuffer srcBuf) throws IOException {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public int write(ByteBuffer srcBuf, long position) throws IOException {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public int write(byte[] buf, int off, int len) throws IOException {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public void force() throws IOException {
force(false);
}
/** {@inheritDoc} */
@Override public void force(boolean withMetadata) throws IOException {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public long size() throws IOException {
return size;
}
/** {@inheritDoc} */
@Override public void clear() throws IOException {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public MappedByteBuffer map(int sizeBytes) throws IOException {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public void close() throws IOException {
zis.close();
}
}
|
if (newPosition == totalBytesRead)
return;
if (newPosition < totalBytesRead)
throw new UnsupportedOperationException("Seeking backwards is not supported.");
long bytesRemaining = newPosition - totalBytesRead;
while (bytesRemaining > 0) {
int bytesToRead = bytesRemaining > arr.length ? arr.length : (int)bytesRemaining;
bytesRemaining -= zis.read(arr, 0, bytesToRead);
}
| 855
| 124
| 979
|
<methods>public non-sealed void <init>() ,public int readFully(java.nio.ByteBuffer) throws java.io.IOException,public int readFully(java.nio.ByteBuffer, long) throws java.io.IOException,public int readFully(byte[], int, int) throws java.io.IOException,public int writeFully(java.nio.ByteBuffer) throws java.io.IOException,public int writeFully(java.nio.ByteBuffer, long) throws java.io.IOException,public int writeFully(byte[], int, int) throws java.io.IOException<variables>private static final int MAX_IO_TIMEOUT_MS
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/freelist/io/PagesListMetaIO.java
|
PagesListMetaIO
|
getBucketsData
|
class PagesListMetaIO extends PageIO {
/** */
private static final int CNT_OFF = COMMON_HEADER_END;
/** */
private static final int NEXT_META_PAGE_OFF = CNT_OFF + 2;
/** */
public static final int ITEMS_OFF = NEXT_META_PAGE_OFF + 8;
/** */
public static final int ITEM_SIZE = 10;
/** */
public static final IOVersions<PagesListMetaIO> VERSIONS = new IOVersions<>(
new PagesListMetaIO(1)
);
/**
* @param ver Page format version.
*/
private PagesListMetaIO(int ver) {
super(T_PAGE_LIST_META, ver);
}
/** {@inheritDoc} */
@Override public void initNewPage(long pageAddr, long pageId, int pageSize, PageMetrics metrics) {
super.initNewPage(pageAddr, pageId, pageSize, metrics);
setCount(pageAddr, 0);
setNextMetaPageId(pageAddr, 0L);
}
/**
* @param pageAddr Page address.
* @return Stored items count.
*/
private int getCount(long pageAddr) {
return PageUtils.getShort(pageAddr, CNT_OFF);
}
/**
* @param pageAddr Page address.
* @param cnt Stored items count.
*/
private void setCount(long pageAddr, int cnt) {
assert cnt >= 0 && cnt <= Short.MAX_VALUE : cnt;
assertPageType(pageAddr);
PageUtils.putShort(pageAddr, CNT_OFF, (short)cnt);
}
/**
* @param pageAddr Page address.
* @return Next meta page ID.
*/
public long getNextMetaPageId(long pageAddr) {
return PageUtils.getLong(pageAddr, NEXT_META_PAGE_OFF);
}
/**
* @param pageAddr Page address.
* @param metaPageId Next meta page ID.
*/
public void setNextMetaPageId(long pageAddr, long metaPageId) {
assertPageType(pageAddr);
PageUtils.putLong(pageAddr, NEXT_META_PAGE_OFF, metaPageId);
}
/**
* @param pageAddr Page address.
*/
public void resetCount(long pageAddr) {
setCount(pageAddr, 0);
}
/**
* @param pageSize Page size.
* @param pageAddr Page address.
* @param bucket Bucket number.
* @param tails Tails.
* @param tailsOff Tails offset.
* @return Number of items written.
*/
public int addTails(int pageSize, long pageAddr, int bucket, PagesList.Stripe[] tails, int tailsOff) {
assert bucket >= 0 && bucket <= Short.MAX_VALUE : bucket;
assertPageType(pageAddr);
int cnt = getCount(pageAddr);
int cap = getCapacity(pageSize, pageAddr);
if (cnt == cap)
return 0;
int off = offset(cnt);
int write = Math.min(cap - cnt, tails.length - tailsOff);
for (int i = 0; i < write; i++) {
PageUtils.putShort(pageAddr, off, (short)bucket);
PageUtils.putLong(pageAddr, off + 2, tails[tailsOff].tailId);
tailsOff++;
off += ITEM_SIZE;
}
setCount(pageAddr, cnt + write);
return write;
}
/**
* @param pageAddr Page address.
* @param res Results map.
*/
public void getBucketsData(long pageAddr, Map<Integer, GridLongList> res) {<FILL_FUNCTION_BODY>}
/**
* @param pageAddr Page address.
* @return Maximum number of items which can be stored in buffer.
*/
public int getCapacity(int pageSize, long pageAddr) {
return (pageSize - ITEMS_OFF) / ITEM_SIZE;
}
/**
* @param idx Item index.
* @return Item offset.
*/
private int offset(int idx) {
return ITEMS_OFF + ITEM_SIZE * idx;
}
/** {@inheritDoc} */
@Override protected void printPage(long addr, int pageSize, GridStringBuilder sb) throws IgniteCheckedException {
int cnt = getCount(addr);
sb.a("PagesListMeta [\n\tnextMetaPageId=").appendHex(getNextMetaPageId(addr))
.a(",\n\tcount=").a(cnt)
.a(",\n\tbucketData={");
Map<Integer, GridLongList> bucketsData = new HashMap<>(cnt);
getBucketsData(addr, bucketsData);
for (Map.Entry<Integer, GridLongList> e : bucketsData.entrySet())
sb.a("\n\t\tbucket=").a(e.getKey()).a(", list=").a(e.getValue());
sb.a("\n\t}\n]");
}
/** {@inheritDoc} */
@Override public int getFreeSpace(int pageSize, long pageAddr) {
return (getCapacity(pageSize, pageAddr) - getCount(pageAddr)) * ITEM_SIZE;
}
}
|
int cnt = getCount(pageAddr);
assert cnt >= 0 && cnt <= Short.MAX_VALUE : cnt;
if (cnt == 0)
return;
int off = offset(0);
for (int i = 0; i < cnt; i++) {
int bucket = (int)PageUtils.getShort(pageAddr, off);
assert bucket >= 0 && bucket <= Short.MAX_VALUE : bucket;
long tailId = PageUtils.getLong(pageAddr, off + 2);
assert tailId != 0;
GridLongList list = res.get(bucket);
if (list == null)
res.put(bucket, list = new GridLongList());
list.add(tailId);
off += ITEM_SIZE;
}
| 1,440
| 208
| 1,648
|
<methods>public static org.apache.ignite.internal.metric.IndexPageType deriveIndexPageType(long) ,public static Q getBPlusIO(long) throws org.apache.ignite.IgniteCheckedException,public static Q getBPlusIO(int, int) throws org.apache.ignite.IgniteCheckedException,public static short getCompactedSize(java.nio.ByteBuffer) ,public static short getCompactedSize(long) ,public static short getCompressedSize(java.nio.ByteBuffer) ,public static short getCompressedSize(long) ,public static byte getCompressionType(java.nio.ByteBuffer) ,public static byte getCompressionType(long) ,public static int getCrc(long) ,public static int getCrc(java.nio.ByteBuffer) ,public abstract int getFreeSpace(int, long) ,public static IOVersions<? extends BPlusInnerIO<?>> getInnerVersions(int) ,public static IOVersions<? extends BPlusLeafIO<?>> getLeafVersions(int) ,public static Q getPageIO(long) throws org.apache.ignite.IgniteCheckedException,public static Q getPageIO(java.nio.ByteBuffer) throws org.apache.ignite.IgniteCheckedException,public static Q getPageIO(int, int) throws org.apache.ignite.IgniteCheckedException,public static long getPageId(java.nio.ByteBuffer) ,public static long getPageId(long) ,public static int getRotatedIdPart(long) ,public static int getType(java.nio.ByteBuffer) ,public static int getType(long) ,public final int getType() ,public static int getVersion(java.nio.ByteBuffer) ,public static int getVersion(long) ,public final int getVersion() ,public void initNewPage(long, long, int, org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMetrics) ,public static boolean isDataPageType(int) ,public static boolean isIndexPage(int) ,public static java.lang.String printPage(long, int) ,public static void registerH2(IOVersions<? extends BPlusInnerIO<?>>, IOVersions<? extends BPlusLeafIO<?>>) ,public static void registerH2ExtraInner(IOVersions<? extends BPlusInnerIO<?>>) ,public static void registerH2ExtraLeaf(IOVersions<? extends BPlusLeafIO<?>>) ,public static void registerTest(BPlusInnerIO<?>, BPlusLeafIO<?>) ,public static void registerTest(org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO) ,public static void setCompactedSize(java.nio.ByteBuffer, short) ,public static void setCompressedSize(java.nio.ByteBuffer, short) ,public static void setCompressionType(java.nio.ByteBuffer, byte) ,public static void setCrc(long, int) ,public static void setCrc(java.nio.ByteBuffer, int) ,public static void setPageId(long, long) ,public static void setRotatedIdPart(long, int) ,public static void setType(long, int) ,public java.lang.String toString() <variables>public static final int COMMON_HEADER_END,private static final int COMPACTED_SIZE_OFF,private static final int COMPRESSED_SIZE_OFF,private static final int COMPRESSION_TYPE_OFF,public static final int CRC_OFF,public static final short MAX_PAYLOAD_SIZE,public static final int PAGE_ID_OFF,private static final int RESERVED_2_OFF,private static final int RESERVED_3_OFF,private static final int RESERVED_SHORT_OFF,public static final int ROTATED_ID_PART_OFF,public static final int TYPE_OFF,public static final short T_BPLUS_META,public static final short T_CACHE_ID_AWARE_DATA_REF_INNER,public static final short T_CACHE_ID_AWARE_DATA_REF_LEAF,public static final short T_CACHE_ID_AWARE_PENDING_REF_INNER,public static final short T_CACHE_ID_AWARE_PENDING_REF_LEAF,public static final short T_DATA,public static final short T_DATA_METASTORAGE,public static final short T_DATA_PART,public static final short T_DATA_REF_INNER,public static final short T_DATA_REF_LEAF,public static final short T_DATA_REF_METASTORAGE_INNER,public static final short T_DATA_REF_METASTORAGE_LEAF,public static final short T_DEFRAG_LINK_MAPPING_INNER,public static final short T_DEFRAG_LINK_MAPPING_LEAF,public static final short T_H2_EX_REF_INNER_END,public static final short T_H2_EX_REF_INNER_START,public static final short T_H2_EX_REF_LEAF_END,public static final short T_H2_EX_REF_LEAF_START,public static final short T_H2_REF_INNER,public static final short T_H2_REF_LEAF,public static final short T_MARKER_PAGE,public static final short T_META,public static final short T_METASTORE_INNER,public static final short T_METASTORE_LEAF,public static final short T_PAGE_LIST_META,public static final short T_PAGE_LIST_NODE,public static final short T_PAGE_UPDATE_TRACKING,public static final short T_PART_CNTRS,public static final short T_PART_META,public static final short T_PENDING_REF_INNER,public static final short T_PENDING_REF_LEAF,public static final int VER_OFF,private static final List<IOVersions<? extends BPlusInnerIO<?>>> h2ExtraInnerIOs,private static final List<IOVersions<? extends BPlusLeafIO<?>>> h2ExtraLeafIOs,private static IOVersions<? extends BPlusInnerIO<?>> h2InnerIOs,private static IOVersions<? extends BPlusLeafIO<?>> h2LeafIOs,private static BPlusInnerIO<?> innerTestIO,private static BPlusLeafIO<?> leafTestIO,private static org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO testIO,private final non-sealed int type,private final non-sealed int ver
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/metastorage/MetastoragePageIOUtils.java
|
MetastoragePageIOUtils
|
storeByOffset
|
class MetastoragePageIOUtils {
/**
* @see MetastorageBPlusIO#getLink(long, int)
*/
public static <IO extends BPlusIO<MetastorageRow> & MetastorageBPlusIO> long getLink(
IO io,
long pageAddr,
int idx
) {
assert idx < io.getCount(pageAddr) : idx;
return PageUtils.getLong(pageAddr, io.offset(idx));
}
/**
* @see MetastorageBPlusIO#getKeySize(long, int)
*/
public static <IO extends BPlusIO<MetastorageRow> & MetastorageBPlusIO> short getKeySize(
IO io,
long pageAddr, int idx
) {
return PageUtils.getShort(pageAddr, io.offset(idx) + 8);
}
/**
* @see MetastorageBPlusIO#getKey(long, int, MetastorageRowStore)
*/
public static <IO extends BPlusIO<MetastorageRow> & MetastorageBPlusIO> String getKey(
IO io,
long pageAddr,
int idx,
MetastorageRowStore rowStore
) throws IgniteCheckedException {
int off = io.offset(idx);
int len = PageUtils.getShort(pageAddr, off + 8);
if (len > MetastorageTree.MAX_KEY_LEN) {
long keyLink = PageUtils.getLong(pageAddr, off + 10);
byte[] keyBytes = rowStore.readRow(keyLink);
assert keyBytes != null : "[pageAddr=" + Long.toHexString(pageAddr) + ", idx=" + idx + ']';
return new String(keyBytes);
}
else {
byte[] keyBytes = PageUtils.getBytes(pageAddr, off + 10, len);
return new String(keyBytes);
}
}
/**
* @see MetastorageBPlusIO#getDataRow(long, int, MetastorageRowStore)
*/
public static <IO extends BPlusIO<MetastorageRow> & MetastorageBPlusIO> MetastorageDataRow getDataRow(
IO io,
long pageAddr,
int idx,
MetastorageRowStore rowStore
) throws IgniteCheckedException {
long link = io.getLink(pageAddr, idx);
int off = io.offset(idx);
int len = PageUtils.getShort(pageAddr, off + 8);
if (len > MetastorageTree.MAX_KEY_LEN) {
long keyLink = PageUtils.getLong(pageAddr, off + 10);
byte[] keyBytes = rowStore.readRow(keyLink);
assert keyBytes != null : "[pageAddr=" + Long.toHexString(pageAddr) + ", idx=" + idx + ']';
return new MetastorageDataRow(link, new String(keyBytes), keyLink);
}
else {
byte[] keyBytes = PageUtils.getBytes(pageAddr, off + 10, len);
return new MetastorageDataRow(link, new String(keyBytes), 0L);
}
}
/**
* @see BPlusIO#store(long, int, org.apache.ignite.internal.processors.cache.persistence.tree.io.BPlusIO, long, int)
*/
public static <IO extends BPlusIO<MetastorageRow> & MetastorageBPlusIO> void store(
IO dstIo,
long dstPageAddr,
int dstIdx,
BPlusIO<MetastorageRow> srcIo,
long srcPageAddr,
int srcIdx
) {
int srcOff = srcIo.offset(srcIdx);
int dstOff = dstIo.offset(dstIdx);
GridUnsafe.copyMemory(srcPageAddr + srcOff, dstPageAddr + dstOff, MetastorageTree.MAX_KEY_LEN + 10);
}
/**
* @see BPlusIO#storeByOffset(long, int, Object)
*/
public static <IO extends BPlusIO<MetastorageRow> & MetastorageBPlusIO> void storeByOffset(
IO io,
long pageAddr,
int off,
MetastorageRow row
) {<FILL_FUNCTION_BODY>}
}
|
assert row.link() != 0;
PageUtils.putLong(pageAddr, off, row.link());
byte[] bytes = row.key().getBytes();
assert bytes.length <= Short.MAX_VALUE;
if (row.keyLink() != 0) {
PageUtils.putShort(pageAddr, off + 8, (short)bytes.length);
PageUtils.putLong(pageAddr, off + 10, row.keyLink());
}
else {
assert bytes.length <= MetastorageTree.MAX_KEY_LEN;
PageUtils.putShort(pageAddr, off + 8, (short)bytes.length);
PageUtils.putBytes(pageAddr, off + 10, bytes);
}
| 1,120
| 187
| 1,307
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/DelayedDirtyPageStoreWrite.java
|
DelayedDirtyPageStoreWrite
|
finishReplacement
|
class DelayedDirtyPageStoreWrite implements PageStoreWriter {
/** Real flush dirty page implementation. */
private final PageStoreWriter flushDirtyPage;
/** Page size. */
private final int pageSize;
/** Thread local with byte buffers. */
private final ThreadLocal<ByteBuffer> byteBufThreadLoc;
/** Replacing pages tracker, used to register & unregister pages being written. */
private final DelayedPageReplacementTracker tracker;
/** Full page id to be written on {@link #finishReplacement()} or null if nothing to write. */
@Nullable private FullPageId fullPageId;
/** Byte buffer with page data to be written on {@link #finishReplacement()} or null if nothing to write. */
@Nullable private ByteBuffer byteBuf;
/** Partition update tag to be used in{@link #finishReplacement()} or null if -1 to write. */
private int tag = -1;
/**
* @param flushDirtyPage real writer to save page to store.
* @param byteBufThreadLoc thread local buffers to use for pages copying.
* @param pageSize page size.
* @param tracker tracker to lock/unlock page reads.
*/
public DelayedDirtyPageStoreWrite(
PageStoreWriter flushDirtyPage,
ThreadLocal<ByteBuffer> byteBufThreadLoc,
int pageSize,
DelayedPageReplacementTracker tracker
) {
this.flushDirtyPage = flushDirtyPage;
this.pageSize = pageSize;
this.byteBufThreadLoc = byteBufThreadLoc;
this.tracker = tracker;
}
/** {@inheritDoc} */
@Override public void writePage(FullPageId fullPageId, ByteBuffer byteBuf, int tag) {
tracker.lock(fullPageId);
ByteBuffer tlb = byteBufThreadLoc.get();
tlb.rewind();
long writeAddr = GridUnsafe.bufferAddress(tlb);
long origBufAddr = GridUnsafe.bufferAddress(byteBuf);
GridUnsafe.copyMemory(origBufAddr, writeAddr, pageSize);
this.fullPageId = fullPageId;
this.byteBuf = tlb;
this.tag = tag;
}
/**
* Runs actual write if required. Method is 'no op' if there was no page selected for replacement.
* @throws IgniteCheckedException if write failed.
*/
public void finishReplacement() throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
}
|
if (byteBuf == null && fullPageId == null)
return;
try {
flushDirtyPage.writePage(fullPageId, byteBuf, tag);
}
finally {
tracker.unlock(fullPageId);
fullPageId = null;
byteBuf = null;
tag = -1;
}
| 646
| 90
| 736
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/PageReadWriteManagerImpl.java
|
PageReadWriteManagerImpl
|
write
|
class PageReadWriteManagerImpl implements PageReadWriteManager {
/** */
private final GridKernalContext ctx;
/** */
@GridToStringExclude
protected final PageStoreCollection pageStores;
/** */
@SuppressWarnings("unused")
private final String name;
/**
* @param ctx Kernal context.
* @param pageStores Page stores.
*/
public PageReadWriteManagerImpl(
GridKernalContext ctx,
PageStoreCollection pageStores,
String name
) {
this.ctx = ctx;
this.pageStores = pageStores;
this.name = name;
}
/** {@inheritDoc} */
@Override public void read(int grpId, long pageId, ByteBuffer pageBuf, boolean keepCrc) throws IgniteCheckedException {
PageStore store = pageStores.getStore(grpId, PageIdUtils.partId(pageId));
try {
store.read(pageId, pageBuf, keepCrc);
ctx.compress().decompressPage(pageBuf, store.getPageSize());
}
catch (StorageException e) {
ctx.failure().process(new FailureContext(FailureType.CRITICAL_ERROR, e));
throw e;
}
}
/** {@inheritDoc} */
@Override public PageStore write(
int grpId,
long pageId,
ByteBuffer pageBuf,
int tag,
boolean calculateCrc
) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public long allocatePage(int grpId, int partId, byte flags) throws IgniteCheckedException {
assert partId <= MAX_PARTITION_ID || partId == INDEX_PARTITION;
PageStore store = pageStores.getStore(grpId, partId);
try {
long pageIdx = store.allocatePage();
return PageIdUtils.pageId(partId, flags, (int)pageIdx);
}
catch (StorageException e) {
ctx.failure().process(new FailureContext(FailureType.CRITICAL_ERROR, e));
throw e;
}
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(PageReadWriteManagerImpl.class, this);
}
}
|
int partId = PageIdUtils.partId(pageId);
PageStore store = pageStores.getStore(grpId, partId);
try {
int pageSize = store.getPageSize();
int compressedPageSize = pageSize;
CacheGroupContext grpCtx = ctx.cache().cacheGroup(grpId);
if (grpCtx != null) {
assert pageBuf.position() == 0 && pageBuf.limit() == pageSize : pageBuf;
ByteBuffer compressedPageBuf = grpCtx.compressionHandler().compressPage(pageBuf, store);
if (compressedPageBuf != pageBuf) {
compressedPageSize = PageIO.getCompressedSize(compressedPageBuf);
if (!calculateCrc) {
calculateCrc = true;
PageIO.setCrc(compressedPageBuf, 0); // It will be recalculated over compressed data further.
}
PageIO.setCrc(pageBuf, 0); // It is expected to be reset to 0 after each write.
pageBuf = compressedPageBuf;
}
}
store.write(pageId, pageBuf, tag, calculateCrc);
if (pageSize > compressedPageSize)
store.punchHole(pageId, compressedPageSize); // TODO maybe add async punch mode?
}
catch (StorageException e) {
ctx.failure().process(new FailureContext(FailureType.CRITICAL_ERROR, e));
throw e;
}
return store;
| 623
| 392
| 1,015
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/PagesWriteThrottle.java
|
PagesWriteThrottle
|
onMarkDirty
|
class PagesWriteThrottle implements PagesWriteThrottlePolicy {
/** Page memory. */
private final PageMemoryImpl pageMemory;
/** Database manager. */
private final IgniteOutClosure<CheckpointProgress> cpProgress;
/** If true, throttle will only protect from checkpoint buffer overflow, not from dirty pages ratio cap excess. */
private final boolean throttleOnlyPagesInCheckpoint;
/** Checkpoint lock state checker. */
private final CheckpointLockStateChecker stateChecker;
/** In-checkpoint protection logic. */
private final ExponentialBackoffThrottlingStrategy inCheckpointProtection
= new ExponentialBackoffThrottlingStrategy();
/** Not-in-checkpoint protection logic. */
private final ExponentialBackoffThrottlingStrategy notInCheckpointProtection
= new ExponentialBackoffThrottlingStrategy();
/** Checkpoint Buffer-related logic used to keep it safe. */
private final CheckpointBufferOverflowWatchdog cpBufferWatchdog;
/** Logger. */
private final IgniteLogger log;
/** Threads that are throttled due to checkpoint buffer overflow. */
private final ConcurrentHashMap<Long, Thread> cpBufThrottledThreads = new ConcurrentHashMap<>();
/**
* @param pageMemory Page memory.
* @param cpProgress Database manager.
* @param stateChecker checkpoint lock state checker.
* @param throttleOnlyPagesInCheckpoint If true, throttle will only protect from checkpoint buffer overflow.
* @param log Logger.
*/
public PagesWriteThrottle(PageMemoryImpl pageMemory,
IgniteOutClosure<CheckpointProgress> cpProgress,
CheckpointLockStateChecker stateChecker,
boolean throttleOnlyPagesInCheckpoint,
IgniteLogger log
) {
this.pageMemory = pageMemory;
this.cpProgress = cpProgress;
this.stateChecker = stateChecker;
this.throttleOnlyPagesInCheckpoint = throttleOnlyPagesInCheckpoint;
cpBufferWatchdog = new CheckpointBufferOverflowWatchdog(pageMemory);
this.log = log;
assert throttleOnlyPagesInCheckpoint || cpProgress != null
: "cpProgress must be not null if ratio based throttling mode is used";
}
/** {@inheritDoc} */
@Override public void onMarkDirty(boolean isPageInCheckpoint) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void wakeupThrottledThreads() {
if (!isCpBufferOverflowThresholdExceeded()) {
inCheckpointProtection.resetBackoff();
unparkParkedThreads();
}
}
/**
* Unparks all the threads that were parked by us.
*/
private void unparkParkedThreads() {
cpBufThrottledThreads.values().forEach(LockSupport::unpark);
}
/** {@inheritDoc} */
@Override public void onBeginCheckpoint() {
}
/** {@inheritDoc} */
@Override public void onFinishCheckpoint() {
inCheckpointProtection.resetBackoff();
notInCheckpointProtection.resetBackoff();
}
/** {@inheritDoc} */
@Override public boolean isCpBufferOverflowThresholdExceeded() {
return cpBufferWatchdog.isInDangerZone();
}
}
|
assert stateChecker.checkpointLockIsHeldByThread();
boolean shouldThrottle = false;
if (isPageInCheckpoint)
shouldThrottle = isCpBufferOverflowThresholdExceeded();
if (!shouldThrottle && !throttleOnlyPagesInCheckpoint) {
CheckpointProgress progress = cpProgress.apply();
AtomicInteger writtenPagesCntr = progress == null ? null : cpProgress.apply().writtenPagesCounter();
if (progress == null || writtenPagesCntr == null)
return; // Don't throttle if checkpoint is not running.
int cpWrittenPages = writtenPagesCntr.get();
int cpTotalPages = progress.currentCheckpointPagesCount();
if (cpWrittenPages == cpTotalPages) {
// Checkpoint is already in fsync stage, increasing maximum ratio of dirty pages to 3/4
shouldThrottle = pageMemory.shouldThrottle(3.0 / 4);
}
else {
double dirtyRatioThreshold = ((double)cpWrittenPages) / cpTotalPages;
// Starting with 0.05 to avoid throttle right after checkpoint start
// 7/12 is maximum ratio of dirty pages
dirtyRatioThreshold = (dirtyRatioThreshold * 0.95 + 0.05) * 7 / 12;
shouldThrottle = pageMemory.shouldThrottle(dirtyRatioThreshold);
}
}
ExponentialBackoffThrottlingStrategy exponentialThrottle = isPageInCheckpoint
? inCheckpointProtection : notInCheckpointProtection;
if (shouldThrottle) {
long throttleParkTimeNs = exponentialThrottle.protectionParkTime();
Thread curThread = Thread.currentThread();
if (throttleParkTimeNs > LOGGING_THRESHOLD) {
U.warn(log, "Parking thread=" + curThread.getName()
+ " for timeout(ms)=" + (throttleParkTimeNs / 1_000_000));
}
long startTime = U.currentTimeMillis();
if (isPageInCheckpoint) {
cpBufThrottledThreads.put(curThread.getId(), curThread);
try {
LockSupport.parkNanos(throttleParkTimeNs);
}
finally {
cpBufThrottledThreads.remove(curThread.getId());
if (throttleParkTimeNs > LOGGING_THRESHOLD) {
U.warn(log, "Unparking thread=" + curThread.getName()
+ " with park timeout(ms)=" + (throttleParkTimeNs / 1_000_000));
}
}
}
else
LockSupport.parkNanos(throttleParkTimeNs);
pageMemory.metrics().addThrottlingTime(U.currentTimeMillis() - startTime);
}
else {
boolean backoffWasAlreadyStarted = exponentialThrottle.resetBackoff();
if (isPageInCheckpoint && backoffWasAlreadyStarted)
unparkParkedThreads();
}
| 886
| 858
| 1,744
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.