Search in sources :

Example 36 with KeyCacheObject

use of org.apache.ignite.internal.processors.cache.KeyCacheObject in project ignite by apache.

the class UserKeyCacheObjectImpl method prepareForCache.

/**
 * {@inheritDoc}
 */
@Override
public CacheObject prepareForCache(CacheObjectContext ctx) {
    try {
        IgniteCacheObjectProcessor proc = ctx.kernalContext().cacheObjects();
        if (!proc.immutable(val)) {
            if (valBytes == null)
                valBytes = proc.marshal(ctx, val);
            boolean p2pEnabled = ctx.kernalContext().config().isPeerClassLoadingEnabled();
            ClassLoader ldr = p2pEnabled ? IgniteUtils.detectClassLoader(IgniteUtils.detectClass(this.val)) : U.gridClassLoader();
            Object val = proc.unmarshal(ctx, valBytes, ldr);
            KeyCacheObject key = new KeyCacheObjectImpl(val, valBytes, partition());
            key.partition(partition());
            return key;
        }
        KeyCacheObject key = new KeyCacheObjectImpl(val, valBytes, partition());
        key.partition(partition());
        return key;
    } catch (IgniteCheckedException e) {
        throw new IgniteException("Failed to marshal object: " + val, e);
    }
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) KeyCacheObjectImpl(org.apache.ignite.internal.processors.cache.KeyCacheObjectImpl) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject)

Example 37 with KeyCacheObject

use of org.apache.ignite.internal.processors.cache.KeyCacheObject in project ignite by apache.

the class DataStreamerImpl method load0.

/**
 * @param entries Entries.
 * @param resFut Result future.
 * @param activeKeys Active keys.
 * @param remaps Remaps count.
 */
private void load0(Collection<? extends DataStreamerEntry> entries, final GridFutureAdapter<Object> resFut, @Nullable final Collection<KeyCacheObjectWrapper> activeKeys, final int remaps) {
    try {
        assert entries != null;
        final boolean remap = remaps > 0;
        if (!remap) {
            // Failed data should be processed prior to new data.
            acquireRemapSemaphore();
        }
        if (!isWarningPrinted) {
            synchronized (this) {
                if (!allowOverwrite() && !isWarningPrinted) {
                    U.warn(log, "Data streamer will not overwrite existing cache entries for better performance " + "(to change, set allowOverwrite to true)");
                }
                isWarningPrinted = true;
            }
        }
        Map<ClusterNode, Collection<DataStreamerEntry>> mappings = new HashMap<>();
        boolean initPda = ctx.deploy().enabled() && jobPda == null;
        GridCacheAdapter cache = ctx.cache().internalCache(cacheName);
        if (cache == null)
            throw new IgniteCheckedException("Cache not created or already destroyed.");
        GridCacheContext cctx = cache.context();
        GridCacheGateway gate = null;
        AffinityTopologyVersion topVer;
        if (!cctx.isLocal())
            topVer = ctx.cache().context().exchange().lastTopologyFuture().get();
        else
            topVer = ctx.cache().context().exchange().readyAffinityVersion();
        List<List<ClusterNode>> assignments = cctx.affinity().assignments(topVer);
        if (!allowOverwrite() && !cctx.isLocal()) {
            // Cases where cctx required.
            gate = cctx.gate();
            gate.enter();
        }
        try {
            for (DataStreamerEntry entry : entries) {
                List<ClusterNode> nodes;
                try {
                    KeyCacheObject key = entry.getKey();
                    assert key != null;
                    if (initPda) {
                        if (cacheObjCtx.addDeploymentInfo())
                            jobPda = new DataStreamerPda(key.value(cacheObjCtx, false), entry.getValue() != null ? entry.getValue().value(cacheObjCtx, false) : null, rcvr);
                        else if (rcvr != null)
                            jobPda = new DataStreamerPda(rcvr);
                        initPda = false;
                    }
                    if (key.partition() == -1)
                        key.partition(cctx.affinity().partition(key, false));
                    nodes = nodes(key, topVer, cctx);
                } catch (IgniteCheckedException e) {
                    resFut.onDone(e);
                    return;
                }
                if (F.isEmpty(nodes)) {
                    resFut.onDone(new ClusterTopologyException("Failed to map key to node " + "(no nodes with cache found in topology) [infos=" + entries.size() + ", cacheName=" + cacheName + ']'));
                    return;
                }
                for (ClusterNode node : nodes) {
                    Collection<DataStreamerEntry> col = mappings.get(node);
                    if (col == null)
                        mappings.put(node, col = new ArrayList<>());
                    col.add(entry);
                }
            }
            for (final Map.Entry<ClusterNode, Collection<DataStreamerEntry>> e : mappings.entrySet()) {
                final UUID nodeId = e.getKey().id();
                Buffer buf = bufMappings.get(nodeId);
                if (buf == null) {
                    Buffer old = bufMappings.putIfAbsent(nodeId, buf = new Buffer(e.getKey()));
                    if (old != null)
                        buf = old;
                }
                final Collection<DataStreamerEntry> entriesForNode = e.getValue();
                IgniteInClosure<IgniteInternalFuture<?>> lsnr = new IgniteInClosure<IgniteInternalFuture<?>>() {

                    @Override
                    public void apply(IgniteInternalFuture<?> t) {
                        try {
                            t.get();
                            if (activeKeys != null) {
                                for (DataStreamerEntry e : entriesForNode) activeKeys.remove(new KeyCacheObjectWrapper(e.getKey()));
                                if (activeKeys.isEmpty())
                                    resFut.onDone();
                            } else {
                                assert entriesForNode.size() == 1;
                                // That has been a single key,
                                // so complete result future right away.
                                resFut.onDone();
                            }
                        } catch (IgniteClientDisconnectedCheckedException e1) {
                            if (log.isDebugEnabled())
                                log.debug("Future finished with disconnect error [nodeId=" + nodeId + ", err=" + e1 + ']');
                            resFut.onDone(e1);
                        } catch (IgniteCheckedException e1) {
                            if (log.isDebugEnabled())
                                log.debug("Future finished with error [nodeId=" + nodeId + ", err=" + e1 + ']');
                            if (cancelled) {
                                resFut.onDone(new IgniteCheckedException("Data streamer has been cancelled: " + DataStreamerImpl.this, e1));
                            } else if (remaps + 1 > maxRemapCnt) {
                                resFut.onDone(new IgniteCheckedException("Failed to finish operation (too many remaps): " + remaps, e1));
                            } else {
                                try {
                                    remapSem.acquire();
                                    final Runnable r = new Runnable() {

                                        @Override
                                        public void run() {
                                            try {
                                                if (cancelled)
                                                    closedException();
                                                load0(entriesForNode, resFut, activeKeys, remaps + 1);
                                            } catch (Throwable ex) {
                                                resFut.onDone(new IgniteCheckedException("DataStreamer remapping failed. ", ex));
                                            } finally {
                                                remapSem.release();
                                            }
                                        }
                                    };
                                    dataToRemap.add(r);
                                    if (!remapOwning.get() && remapOwning.compareAndSet(false, true)) {
                                        ctx.closure().callLocalSafe(new GPC<Boolean>() {

                                            @Override
                                            public Boolean call() {
                                                boolean locked = true;
                                                while (locked || !dataToRemap.isEmpty()) {
                                                    if (!locked && !remapOwning.compareAndSet(false, true))
                                                        return false;
                                                    try {
                                                        Runnable r = dataToRemap.poll();
                                                        if (r != null)
                                                            r.run();
                                                    } finally {
                                                        if (!dataToRemap.isEmpty())
                                                            locked = true;
                                                        else {
                                                            remapOwning.set(false);
                                                            locked = false;
                                                        }
                                                    }
                                                }
                                                return true;
                                            }
                                        }, true);
                                    }
                                } catch (InterruptedException e2) {
                                    resFut.onDone(e2);
                                }
                            }
                        }
                    }
                };
                GridCompoundFuture opFut = new SilentCompoundFuture();
                opFut.listen(lsnr);
                final List<GridFutureAdapter<?>> futs;
                try {
                    futs = buf.update(entriesForNode, topVer, assignments, opFut, remap);
                    opFut.markInitialized();
                } catch (IgniteInterruptedCheckedException e1) {
                    resFut.onDone(e1);
                    return;
                }
                if (ctx.discovery().node(nodeId) == null) {
                    if (bufMappings.remove(nodeId, buf)) {
                        final Buffer buf0 = buf;
                        waitAffinityAndRun(new Runnable() {

                            @Override
                            public void run() {
                                buf0.onNodeLeft();
                                if (futs != null) {
                                    Throwable ex = new ClusterTopologyCheckedException("Failed to wait for request completion (node has left): " + nodeId);
                                    for (int i = 0; i < futs.size(); i++) futs.get(i).onDone(ex);
                                }
                            }
                        }, ctx.discovery().topologyVersion(), false);
                    }
                }
            }
        } finally {
            if (gate != null)
                gate.leave();
        }
    } catch (Exception ex) {
        resFut.onDone(new IgniteCheckedException("DataStreamer data loading failed.", ex));
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) IgniteInterruptedException(org.apache.ignite.IgniteInterruptedException) GridCompoundFuture(org.apache.ignite.internal.util.future.GridCompoundFuture) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridCacheAdapter(org.apache.ignite.internal.processors.cache.GridCacheAdapter) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) ArrayList(java.util.ArrayList) List(java.util.List) GridCacheGateway(org.apache.ignite.internal.processors.cache.GridCacheGateway) UUID(java.util.UUID) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) ClusterNode(org.apache.ignite.cluster.ClusterNode) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteDataStreamerTimeoutException(org.apache.ignite.IgniteDataStreamerTimeoutException) IgniteInterruptedException(org.apache.ignite.IgniteInterruptedException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) ClusterTopologyServerNotFoundException(org.apache.ignite.internal.cluster.ClusterTopologyServerNotFoundException) IgniteClientDisconnectedCheckedException(org.apache.ignite.internal.IgniteClientDisconnectedCheckedException) IgniteException(org.apache.ignite.IgniteException) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) IgniteFutureTimeoutCheckedException(org.apache.ignite.internal.IgniteFutureTimeoutCheckedException) ClusterTopologyException(org.apache.ignite.cluster.ClusterTopologyException) CacheException(javax.cache.CacheException) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) GridDhtInvalidPartitionException(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtInvalidPartitionException) Collection(java.util.Collection) IgniteInClosure(org.apache.ignite.lang.IgniteInClosure) IgniteClientDisconnectedCheckedException(org.apache.ignite.internal.IgniteClientDisconnectedCheckedException) ClusterTopologyException(org.apache.ignite.cluster.ClusterTopologyException) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)

Example 38 with KeyCacheObject

use of org.apache.ignite.internal.processors.cache.KeyCacheObject in project ignite by apache.

the class DataStreamerImpl method addData.

/**
 * {@inheritDoc}
 */
@Override
public IgniteFuture<?> addData(K key, V val) {
    A.notNull(key, "key");
    if (val == null)
        checkSecurityPermission(SecurityPermission.CACHE_REMOVE);
    else
        checkSecurityPermission(SecurityPermission.CACHE_PUT);
    KeyCacheObject key0 = cacheObjProc.toCacheKeyObject(cacheObjCtx, null, key, true);
    CacheObject val0 = cacheObjProc.toCacheObject(cacheObjCtx, val, true);
    return addDataInternal(Collections.singleton(new DataStreamerEntry(key0, val0)));
}
Also used : CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject)

Example 39 with KeyCacheObject

use of org.apache.ignite.internal.processors.cache.KeyCacheObject in project ignite by apache.

the class GridCacheStoreManagerAdapter method loadAllFromStore.

/**
 * @param tx Cache transaction.
 * @param keys Keys to load.
 * @param vis Key/value closure (only one of vis or verVis can be specified).
 * @param verVis Key/value/version closure (only one of vis or verVis can be specified).
 * @throws IgniteCheckedException If failed.
 */
private void loadAllFromStore(@Nullable IgniteInternalTx tx, Collection<? extends KeyCacheObject> keys, @Nullable final IgniteBiInClosure<KeyCacheObject, Object> vis, @Nullable final GridInClosure3<KeyCacheObject, Object, GridCacheVersion> verVis) throws IgniteCheckedException {
    assert vis != null ^ verVis != null;
    assert verVis == null || locStore;
    final boolean convert = verVis == null;
    if (!keys.isEmpty()) {
        if (keys.size() == 1) {
            KeyCacheObject key = F.first(keys);
            if (convert)
                vis.apply(key, load(tx, key));
            else {
                IgniteBiTuple<Object, GridCacheVersion> t = (IgniteBiTuple<Object, GridCacheVersion>) loadFromStore(tx, key, false);
                if (t != null)
                    verVis.apply(key, t.get1(), t.get2());
            }
            return;
        }
        Collection<Object> keys0 = F.viewReadOnly(keys, new C1<KeyCacheObject, Object>() {

            @Override
            public Object apply(KeyCacheObject key) {
                return cctx.unwrapBinaryIfNeeded(key, !convertBinary());
            }
        });
        if (log.isDebugEnabled())
            log.debug("Loading values from store for keys: " + keys0);
        sessionInit0(tx, StoreOperation.READ, false);
        boolean threwEx = true;
        try {
            IgniteBiInClosure<Object, Object> c = new CI2<Object, Object>() {

                @SuppressWarnings("ConstantConditions")
                @Override
                public void apply(Object k, Object val) {
                    if (convert) {
                        Object v = convert(val);
                        vis.apply(cctx.toCacheKeyObject(k), v);
                    } else {
                        IgniteBiTuple<Object, GridCacheVersion> v = (IgniteBiTuple<Object, GridCacheVersion>) val;
                        if (v != null)
                            verVis.apply(cctx.toCacheKeyObject(k), v.get1(), v.get2());
                    }
                }
            };
            if (keys.size() > singleThreadGate.loadAllThreshold()) {
                Map<Object, Object> map = store.loadAll(keys0);
                if (map != null) {
                    for (Map.Entry<Object, Object> e : map.entrySet()) c.apply(cctx.toCacheKeyObject(e.getKey()), e.getValue());
                }
            } else
                singleThreadGate.loadAll(keys0, c);
            threwEx = false;
        } catch (ClassCastException e) {
            handleClassCastException(e);
        } catch (CacheLoaderException e) {
            throw new IgniteCheckedException(e);
        } catch (Exception e) {
            throw new IgniteCheckedException(new CacheLoaderException(e));
        } finally {
            sessionEnd0(tx, threwEx);
        }
        if (log.isDebugEnabled())
            log.debug("Loaded values from store for keys: " + keys0);
    }
}
Also used : IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) CI2(org.apache.ignite.internal.util.typedef.CI2) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) CacheWriterException(javax.cache.integration.CacheWriterException) CacheLoaderException(javax.cache.integration.CacheLoaderException) NoSuchElementException(java.util.NoSuchElementException) CacheStorePartialUpdateException(org.apache.ignite.internal.processors.cache.CacheStorePartialUpdateException) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) CacheLoaderException(javax.cache.integration.CacheLoaderException) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) GridLeanMap(org.apache.ignite.internal.util.GridLeanMap) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject)

Example 40 with KeyCacheObject

use of org.apache.ignite.internal.processors.cache.KeyCacheObject in project ignite by apache.

the class GridCacheStoreManagerAdapter method putAll.

/**
 * {@inheritDoc}
 */
@Override
public final boolean putAll(@Nullable IgniteInternalTx tx, Map<? extends KeyCacheObject, IgniteBiTuple<? extends CacheObject, GridCacheVersion>> map) throws IgniteCheckedException {
    if (F.isEmpty(map))
        return true;
    if (map.size() == 1) {
        Map.Entry<? extends KeyCacheObject, IgniteBiTuple<? extends CacheObject, GridCacheVersion>> e = ((Map<? extends KeyCacheObject, IgniteBiTuple<? extends CacheObject, GridCacheVersion>>) map).entrySet().iterator().next();
        return put(tx, e.getKey(), e.getValue().get1(), e.getValue().get2());
    } else {
        if (store != null) {
            EntriesView entries = new EntriesView(map);
            if (log.isDebugEnabled())
                log.debug("Storing values in cache store [entries=" + entries + ']');
            sessionInit0(tx, StoreOperation.WRITE, false);
            boolean threwEx = true;
            try {
                store.writeAll(entries);
                threwEx = false;
            } catch (ClassCastException e) {
                handleClassCastException(e);
            } catch (Exception e) {
                if (!(e instanceof CacheWriterException))
                    e = new CacheWriterException(e);
                if (!entries.isEmpty()) {
                    List<Object> keys = new ArrayList<>(entries.size());
                    for (Cache.Entry<?, ?> entry : entries) keys.add(entry.getKey());
                    throw new CacheStorePartialUpdateException(keys, e);
                }
                throw new IgniteCheckedException(e);
            } finally {
                sessionEnd0(tx, threwEx);
            }
            if (log.isDebugEnabled())
                log.debug("Stored value in cache store [entries=" + entries + ']');
            return true;
        }
        return false;
    }
}
Also used : IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) CacheWriterException(javax.cache.integration.CacheWriterException) CacheLoaderException(javax.cache.integration.CacheLoaderException) NoSuchElementException(java.util.NoSuchElementException) CacheStorePartialUpdateException(org.apache.ignite.internal.processors.cache.CacheStorePartialUpdateException) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) CacheStorePartialUpdateException(org.apache.ignite.internal.processors.cache.CacheStorePartialUpdateException) List(java.util.List) ArrayList(java.util.ArrayList) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) GridLeanMap(org.apache.ignite.internal.util.GridLeanMap) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) CacheWriterException(javax.cache.integration.CacheWriterException)

Aggregations

KeyCacheObject (org.apache.ignite.internal.processors.cache.KeyCacheObject)118 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)67 CacheObject (org.apache.ignite.internal.processors.cache.CacheObject)65 GridCacheEntryRemovedException (org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException)57 GridCacheVersion (org.apache.ignite.internal.processors.cache.version.GridCacheVersion)42 ArrayList (java.util.ArrayList)30 ClusterTopologyCheckedException (org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)28 Map (java.util.Map)25 ClusterNode (org.apache.ignite.cluster.ClusterNode)25 GridCacheEntryEx (org.apache.ignite.internal.processors.cache.GridCacheEntryEx)25 AffinityTopologyVersion (org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)24 EntryGetResult (org.apache.ignite.internal.processors.cache.EntryGetResult)16 GridTimeoutObject (org.apache.ignite.internal.processors.timeout.GridTimeoutObject)15 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)14 IgniteTxKey (org.apache.ignite.internal.processors.cache.transactions.IgniteTxKey)14 HashMap (java.util.HashMap)13 LinkedHashMap (java.util.LinkedHashMap)13 IgniteException (org.apache.ignite.IgniteException)13 CacheStorePartialUpdateException (org.apache.ignite.internal.processors.cache.CacheStorePartialUpdateException)13 NodeStoppingException (org.apache.ignite.internal.NodeStoppingException)12