Search in sources :

Example 1 with Serializer

use of org.janusgraph.graphdb.database.serialize.Serializer in project janusgraph by JanusGraph.

the class ManagementLogger method read.

@Override
public void read(Message message) {
    ReadBuffer in = message.getContent().asReadBuffer();
    String senderId = message.getSenderId();
    Serializer serializer = graph.getDataSerializer();
    MgmtLogType logType = serializer.readObjectNotNull(in, MgmtLogType.class);
    Preconditions.checkNotNull(logType);
    switch(logType) {
        case CACHED_TYPE_EVICTION:
            {
                long evictionId = VariableLong.readPositive(in);
                long numEvictions = VariableLong.readPositive(in);
                for (int i = 0; i < numEvictions; i++) {
                    long typeId = VariableLong.readPositive(in);
                    schemaCache.expireSchemaElement(typeId);
                }
                final GraphCacheEvictionAction action = serializer.readObjectNotNull(in, GraphCacheEvictionAction.class);
                Preconditions.checkNotNull(action);
                final Thread ack = new Thread(new SendAckOnTxClose(evictionId, senderId, graph.getOpenTransactions(), action, graph.getGraphName()));
                ack.setDaemon(true);
                ack.start();
                break;
            }
        case CACHED_TYPE_EVICTION_ACK:
            {
                String receiverId = serializer.readObjectNotNull(in, String.class);
                long evictionId = VariableLong.readPositive(in);
                if (receiverId.equals(graph.getConfiguration().getUniqueGraphId())) {
                    // Acknowledgements targeted at this instance
                    EvictionTrigger evictTrigger = evictionTriggerMap.get(evictionId);
                    if (evictTrigger != null) {
                        evictTrigger.receivedAcknowledgement(senderId);
                    } else
                        log.error("Could not find eviction trigger for {} from {}", evictionId, senderId);
                }
                break;
            }
        default:
            assert logType == MgmtLogType.CONFIG_MUTATION;
            break;
    }
}
Also used : ReadBuffer(org.janusgraph.diskstorage.ReadBuffer) Serializer(org.janusgraph.graphdb.database.serialize.Serializer)

Example 2 with Serializer

use of org.janusgraph.graphdb.database.serialize.Serializer in project janusgraph by JanusGraph.

the class StandardTransactionLogProcessor method restoreExternalIndexes.

private void restoreExternalIndexes(Predicate<String> isFailedIndex, TransactionLogHeader.Entry entry) {
    // 1) Collect all elements (vertices and relations) and the indexes for which they need to be restored
    SetMultimap<String, IndexRestore> indexRestores = HashMultimap.create();
    BackendOperation.execute(() -> {
        final StandardJanusGraphTx tx = (StandardJanusGraphTx) graph.newTransaction();
        try {
            entry.getContentAsModifications(serializer).stream().map(m -> ModificationDeserializer.parseRelation(m, tx)).forEach(rel -> {
                // Collect affected vertex indexes
                for (final MixedIndexType index : getMixedIndexes(rel.getType())) {
                    if (index.getElement() == ElementCategory.VERTEX && isFailedIndex.apply(index.getBackingIndexName())) {
                        assert rel.isProperty();
                        indexRestores.put(index.getBackingIndexName(), new IndexRestore(rel.getVertex(0).longId(), ElementCategory.VERTEX, getIndexId(index)));
                    }
                }
                // See if relation itself is affected
                for (final RelationType relType : rel.getPropertyKeysDirect()) {
                    for (final MixedIndexType index : getMixedIndexes(relType)) {
                        if (index.getElement().isInstance(rel) && isFailedIndex.apply(index.getBackingIndexName())) {
                            assert rel.id() instanceof RelationIdentifier;
                            indexRestores.put(index.getBackingIndexName(), new IndexRestore(rel.id(), ElementCategory.getByClazz(rel.getClass()), getIndexId(index)));
                        }
                    }
                }
            });
        } finally {
            if (tx.isOpen())
                tx.rollback();
        }
        return true;
    }, readTime);
    // 2) Restore elements per backing index
    for (final String indexName : indexRestores.keySet()) {
        final StandardJanusGraphTx tx = (StandardJanusGraphTx) graph.newTransaction();
        try {
            BackendTransaction btx = tx.getTxHandle();
            final IndexTransaction indexTx = btx.getIndexTransaction(indexName);
            BackendOperation.execute(new Callable<Boolean>() {

                @Override
                public Boolean call() throws Exception {
                    Map<String, Map<String, List<IndexEntry>>> restoredDocs = Maps.newHashMap();
                    indexRestores.get(indexName).forEach(restore -> {
                        JanusGraphSchemaVertex indexV = (JanusGraphSchemaVertex) tx.getVertex(restore.indexId);
                        MixedIndexType index = (MixedIndexType) indexV.asIndexType();
                        JanusGraphElement element = restore.retrieve(tx);
                        if (element != null) {
                            graph.getIndexSerializer().reindexElement(element, index, restoredDocs);
                        } else {
                            // Element is deleted
                            graph.getIndexSerializer().removeElement(restore.elementId, index, restoredDocs);
                        }
                    });
                    indexTx.restore(restoredDocs);
                    indexTx.commit();
                    return true;
                }

                @Override
                public String toString() {
                    return "IndexMutation";
                }
            }, persistenceTime);
        } finally {
            if (tx.isOpen())
                tx.rollback();
        }
    }
}
Also used : SchemaSource(org.janusgraph.graphdb.types.SchemaSource) org.janusgraph.diskstorage.log(org.janusgraph.diskstorage.log) StandardJanusGraphTx(org.janusgraph.graphdb.transaction.StandardJanusGraphTx) BackgroundThread(org.janusgraph.util.system.BackgroundThread) BackendOperation(org.janusgraph.diskstorage.util.BackendOperation) LoggerFactory(org.slf4j.LoggerFactory) IndexTransaction(org.janusgraph.diskstorage.indexing.IndexTransaction) HashCodeBuilder(org.apache.commons.lang.builder.HashCodeBuilder) Callable(java.util.concurrent.Callable) IndexTypeWrapper(org.janusgraph.graphdb.types.indextype.IndexTypeWrapper) JanusGraphTransaction(org.janusgraph.core.JanusGraphTransaction) Future(java.util.concurrent.Future) Serializer(org.janusgraph.graphdb.database.serialize.Serializer) IndexEntry(org.janusgraph.diskstorage.indexing.IndexEntry) Duration(java.time.Duration) Map(java.util.Map) Predicates(com.google.common.base.Predicates) MixedIndexType(org.janusgraph.graphdb.types.MixedIndexType) JanusGraphException(org.janusgraph.core.JanusGraphException) IndexType(org.janusgraph.graphdb.types.IndexType) com.google.common.collect(com.google.common.collect) LogTxStatus(org.janusgraph.graphdb.database.log.LogTxStatus) JanusGraphElement(org.janusgraph.core.JanusGraphElement) TransactionLogHeader(org.janusgraph.graphdb.database.log.TransactionLogHeader) TransactionRecovery(org.janusgraph.core.log.TransactionRecovery) RelationType(org.janusgraph.core.RelationType) Logger(org.slf4j.Logger) TimestampProvider(org.janusgraph.diskstorage.util.time.TimestampProvider) StandardJanusGraph(org.janusgraph.graphdb.database.StandardJanusGraph) JanusGraphSchemaVertex(org.janusgraph.graphdb.types.vertices.JanusGraphSchemaVertex) LogTxMeta(org.janusgraph.graphdb.database.log.LogTxMeta) Instant(java.time.Instant) ElementCategory(org.janusgraph.graphdb.internal.ElementCategory) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) com.google.common.cache(com.google.common.cache) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) RelationIdentifier(org.janusgraph.graphdb.relations.RelationIdentifier) Predicate(com.google.common.base.Predicate) GraphDatabaseConfiguration(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration) Preconditions(com.google.common.base.Preconditions) InternalRelationType(org.janusgraph.graphdb.internal.InternalRelationType) Collections(java.util.Collections) org.janusgraph.diskstorage(org.janusgraph.diskstorage) MixedIndexType(org.janusgraph.graphdb.types.MixedIndexType) IndexTransaction(org.janusgraph.diskstorage.indexing.IndexTransaction) RelationIdentifier(org.janusgraph.graphdb.relations.RelationIdentifier) JanusGraphException(org.janusgraph.core.JanusGraphException) ExecutionException(java.util.concurrent.ExecutionException) JanusGraphElement(org.janusgraph.core.JanusGraphElement) StandardJanusGraphTx(org.janusgraph.graphdb.transaction.StandardJanusGraphTx) RelationType(org.janusgraph.core.RelationType) InternalRelationType(org.janusgraph.graphdb.internal.InternalRelationType) JanusGraphSchemaVertex(org.janusgraph.graphdb.types.vertices.JanusGraphSchemaVertex) List(java.util.List) Map(java.util.Map)

Example 3 with Serializer

use of org.janusgraph.graphdb.database.serialize.Serializer in project janusgraph by JanusGraph.

the class IDManagementTest method edgeTypeIDTest.

@Test
public void edgeTypeIDTest() {
    int partitionBits = 16;
    IDManager eid = new IDManager(partitionBits);
    int trails = 1000000;
    assertEquals(eid.getPartitionBound(), (1L << partitionBits));
    Serializer serializer = new StandardSerializer();
    for (int t = 0; t < trails; t++) {
        long count = RandomGenerator.randomLong(1, IDManager.getSchemaCountBound());
        long id;
        IDHandler.DirectionID dirID;
        RelationCategory type;
        if (Math.random() < 0.5) {
            id = IDManager.getSchemaId(IDManager.VertexIDType.UserEdgeLabel, count);
            assertTrue(eid.isEdgeLabelId(id));
            assertFalse(IDManager.isSystemRelationTypeId(id));
            type = RelationCategory.EDGE;
            if (Math.random() < 0.5)
                dirID = IDHandler.DirectionID.EDGE_IN_DIR;
            else
                dirID = IDHandler.DirectionID.EDGE_OUT_DIR;
        } else {
            type = RelationCategory.PROPERTY;
            id = IDManager.getSchemaId(IDManager.VertexIDType.UserPropertyKey, count);
            assertTrue(eid.isPropertyKeyId(id));
            assertFalse(IDManager.isSystemRelationTypeId(id));
            dirID = IDHandler.DirectionID.PROPERTY_DIR;
        }
        assertTrue(eid.isRelationTypeId(id));
        StaticBuffer b = IDHandler.getRelationType(id, dirID, false);
        // System.out.println(dirID);
        // System.out.println(getBinary(id));
        // System.out.println(getBuffer(b.asReadBuffer()));
        ReadBuffer rb = b.asReadBuffer();
        IDHandler.RelationTypeParse parse = IDHandler.readRelationType(rb);
        assertEquals(id, parse.typeId);
        assertEquals(dirID, parse.dirID);
        assertFalse(rb.hasRemaining());
        // Inline edge type
        WriteBuffer wb = new WriteByteBuffer(9);
        IDHandler.writeInlineRelationType(wb, id);
        long newId = IDHandler.readInlineRelationType(wb.getStaticBuffer().asReadBuffer());
        assertEquals(id, newId);
        // Compare to Kryo
        DataOutput out = serializer.getDataOutput(10);
        IDHandler.writeRelationType(out, id, dirID, false);
        assertEquals(b, out.getStaticBuffer());
        // Make sure the bounds are right
        StaticBuffer[] bounds = IDHandler.getBounds(type, false);
        assertTrue(bounds[0].compareTo(b) < 0);
        assertTrue(bounds[1].compareTo(b) > 0);
        bounds = IDHandler.getBounds(RelationCategory.RELATION, false);
        assertTrue(bounds[0].compareTo(b) < 0);
        assertTrue(bounds[1].compareTo(b) > 0);
    }
}
Also used : DataOutput(org.janusgraph.graphdb.database.serialize.DataOutput) WriteBuffer(org.janusgraph.diskstorage.WriteBuffer) ReadBuffer(org.janusgraph.diskstorage.ReadBuffer) RelationCategory(org.janusgraph.graphdb.internal.RelationCategory) WriteByteBuffer(org.janusgraph.diskstorage.util.WriteByteBuffer) StandardSerializer(org.janusgraph.graphdb.database.serialize.StandardSerializer) IDHandler(org.janusgraph.graphdb.database.idhandling.IDHandler) StaticBuffer(org.janusgraph.diskstorage.StaticBuffer) StandardSerializer(org.janusgraph.graphdb.database.serialize.StandardSerializer) Serializer(org.janusgraph.graphdb.database.serialize.Serializer) Test(org.junit.Test)

Example 4 with Serializer

use of org.janusgraph.graphdb.database.serialize.Serializer in project janusgraph by JanusGraph.

the class JanusGraphTest method simpleLogTest.

public void simpleLogTest(final boolean withLogFailure) throws InterruptedException {
    final String userLogName = "test";
    final Serializer serializer = graph.getDataSerializer();
    final EdgeSerializer edgeSerializer = graph.getEdgeSerializer();
    final TimestampProvider times = graph.getConfiguration().getTimestampProvider();
    final Instant startTime = times.getTime();
    clopen(option(SYSTEM_LOG_TRANSACTIONS), true, option(LOG_BACKEND, USER_LOG), (withLogFailure ? TestMockLog.class.getName() : LOG_BACKEND.getDefaultValue()), option(TestMockLog.LOG_MOCK_FAILADD, USER_LOG), withLogFailure, option(KCVSLog.LOG_READ_LAG_TIME, USER_LOG), Duration.ofMillis(50), option(LOG_READ_INTERVAL, USER_LOG), Duration.ofMillis(250), option(LOG_SEND_DELAY, USER_LOG), Duration.ofMillis(100), option(KCVSLog.LOG_READ_LAG_TIME, TRANSACTION_LOG), Duration.ofMillis(50), option(LOG_READ_INTERVAL, TRANSACTION_LOG), Duration.ofMillis(250), option(MAX_COMMIT_TIME), Duration.ofSeconds(1));
    final String instanceId = graph.getConfiguration().getUniqueGraphId();
    PropertyKey weight = tx.makePropertyKey("weight").dataType(Float.class).cardinality(Cardinality.SINGLE).make();
    EdgeLabel knows = tx.makeEdgeLabel("knows").make();
    JanusGraphVertex n1 = tx.addVertex("weight", 10.5);
    newTx();
    final Instant[] txTimes = new Instant[4];
    // Transaction with custom user log name
    txTimes[0] = times.getTime();
    JanusGraphTransaction tx2 = graph.buildTransaction().logIdentifier(userLogName).start();
    JanusGraphVertex v1 = tx2.addVertex("weight", 111.1);
    v1.addEdge("knows", v1);
    tx2.commit();
    final long v1id = getId(v1);
    txTimes[1] = times.getTime();
    tx2 = graph.buildTransaction().logIdentifier(userLogName).start();
    JanusGraphVertex v2 = tx2.addVertex("weight", 222.2);
    v2.addEdge("knows", getV(tx2, v1id));
    tx2.commit();
    final long v2id = getId(v2);
    // Only read tx
    tx2 = graph.buildTransaction().logIdentifier(userLogName).start();
    v1 = getV(tx2, v1id);
    assertEquals(111.1, v1.<Float>value("weight").doubleValue(), 0.01);
    assertEquals(222.2, getV(tx2, v2).<Float>value("weight").doubleValue(), 0.01);
    tx2.commit();
    // Deleting transaction
    txTimes[2] = times.getTime();
    tx2 = graph.buildTransaction().logIdentifier(userLogName).start();
    v2 = getV(tx2, v2id);
    assertEquals(222.2, v2.<Float>value("weight").doubleValue(), 0.01);
    v2.remove();
    tx2.commit();
    // Edge modifying transaction
    txTimes[3] = times.getTime();
    tx2 = graph.buildTransaction().logIdentifier(userLogName).start();
    v1 = getV(tx2, v1id);
    assertEquals(111.1, v1.<Float>value("weight").doubleValue(), 0.01);
    final Edge e = Iterables.getOnlyElement(v1.query().direction(Direction.OUT).labels("knows").edges());
    assertFalse(e.property("weight").isPresent());
    e.property("weight", 44.4);
    tx2.commit();
    close();
    final Instant endTime = times.getTime();
    final ReadMarker startMarker = ReadMarker.fromTime(startTime);
    final Log transactionLog = openTxLog();
    final Log userLog = openUserLog(userLogName);
    final EnumMap<LogTxStatus, AtomicInteger> txMsgCounter = new EnumMap<>(LogTxStatus.class);
    for (final LogTxStatus status : LogTxStatus.values()) txMsgCounter.put(status, new AtomicInteger(0));
    final AtomicInteger userLogMeta = new AtomicInteger(0);
    transactionLog.registerReader(startMarker, new MessageReader() {

        @Override
        public void read(Message message) {
            final Instant msgTime = message.getTimestamp();
            assertTrue(msgTime.isAfter(startTime) || msgTime.equals(startTime));
            assertNotNull(message.getSenderId());
            final TransactionLogHeader.Entry txEntry = TransactionLogHeader.parse(message.getContent(), serializer, times);
            final TransactionLogHeader header = txEntry.getHeader();
            // System.out.println(header.getTimestamp(TimeUnit.MILLISECONDS));
            assertTrue(header.getTimestamp().isAfter(startTime) || header.getTimestamp().equals(startTime));
            assertTrue(header.getTimestamp().isBefore(msgTime) || header.getTimestamp().equals(msgTime));
            assertNotNull(txEntry.getMetadata());
            assertNull(txEntry.getMetadata().get(LogTxMeta.GROUPNAME));
            final LogTxStatus status = txEntry.getStatus();
            if (status == LogTxStatus.PRECOMMIT) {
                assertTrue(txEntry.hasContent());
                final Object logId = txEntry.getMetadata().get(LogTxMeta.LOG_ID);
                if (logId != null) {
                    assertTrue(logId instanceof String);
                    assertEquals(userLogName, logId);
                    userLogMeta.incrementAndGet();
                }
            } else if (withLogFailure) {
                assertTrue(status.isPrimarySuccess() || status == LogTxStatus.SECONDARY_FAILURE);
                if (status == LogTxStatus.SECONDARY_FAILURE) {
                    final TransactionLogHeader.SecondaryFailures secFail = txEntry.getContentAsSecondaryFailures(serializer);
                    assertTrue(secFail.failedIndexes.isEmpty());
                    assertTrue(secFail.userLogFailure);
                }
            } else {
                assertFalse(txEntry.hasContent());
                assertTrue(status.isSuccess());
            }
            txMsgCounter.get(txEntry.getStatus()).incrementAndGet();
        }

        @Override
        public void updateState() {
        }
    });
    final EnumMap<Change, AtomicInteger> userChangeCounter = new EnumMap<>(Change.class);
    for (final Change change : Change.values()) userChangeCounter.put(change, new AtomicInteger(0));
    final AtomicInteger userLogMsgCounter = new AtomicInteger(0);
    userLog.registerReader(startMarker, new MessageReader() {

        @Override
        public void read(Message message) {
            final Instant msgTime = message.getTimestamp();
            assertTrue(msgTime.isAfter(startTime) || msgTime.equals(startTime));
            assertNotNull(message.getSenderId());
            final StaticBuffer content = message.getContent();
            assertTrue(content != null && content.length() > 0);
            final TransactionLogHeader.Entry transactionEntry = TransactionLogHeader.parse(content, serializer, times);
            final Instant txTime = transactionEntry.getHeader().getTimestamp();
            assertTrue(txTime.isBefore(msgTime) || txTime.equals(msgTime));
            assertTrue(txTime.isAfter(startTime) || txTime.equals(msgTime));
            final long transactionId = transactionEntry.getHeader().getId();
            assertTrue(transactionId > 0);
            transactionEntry.getContentAsModifications(serializer).forEach(modification -> {
                assertTrue(modification.state == Change.ADDED || modification.state == Change.REMOVED);
                userChangeCounter.get(modification.state).incrementAndGet();
            });
            userLogMsgCounter.incrementAndGet();
        }

        @Override
        public void updateState() {
        }
    });
    Thread.sleep(4000);
    assertEquals(5, txMsgCounter.get(LogTxStatus.PRECOMMIT).get());
    assertEquals(4, txMsgCounter.get(LogTxStatus.PRIMARY_SUCCESS).get());
    assertEquals(1, txMsgCounter.get(LogTxStatus.COMPLETE_SUCCESS).get());
    assertEquals(4, userLogMeta.get());
    if (withLogFailure)
        assertEquals(4, txMsgCounter.get(LogTxStatus.SECONDARY_FAILURE).get());
    else
        assertEquals(4, txMsgCounter.get(LogTxStatus.SECONDARY_SUCCESS).get());
    // User-Log
    if (withLogFailure) {
        assertEquals(0, userLogMsgCounter.get());
    } else {
        assertEquals(4, userLogMsgCounter.get());
        assertEquals(7, userChangeCounter.get(Change.ADDED).get());
        assertEquals(4, userChangeCounter.get(Change.REMOVED).get());
    }
    clopen(option(VERBOSE_TX_RECOVERY), true);
    /*
        Transaction Recovery
         */
    final TransactionRecovery recovery = JanusGraphFactory.startTransactionRecovery(graph, startTime);
    /*
        Use user log processing framework
         */
    final AtomicInteger userLogCount = new AtomicInteger(0);
    final LogProcessorFramework userLogs = JanusGraphFactory.openTransactionLog(graph);
    userLogs.addLogProcessor(userLogName).setStartTime(startTime).setRetryAttempts(1).addProcessor((tx, txId, changes) -> {
        assertEquals(instanceId, txId.getInstanceId());
        // Just some reasonable upper bound
        assertTrue(txId.getTransactionId() > 0 && txId.getTransactionId() < 100);
        final Instant txTime = txId.getTransactionTime();
        // Times should be within a second
        assertTrue(String.format("tx timestamp %s not between start %s and end time %s", txTime, startTime, endTime), (txTime.isAfter(startTime) || txTime.equals(startTime)) && (txTime.isBefore(endTime) || txTime.equals(endTime)));
        assertTrue(tx.containsRelationType("knows"));
        assertTrue(tx.containsRelationType("weight"));
        final EdgeLabel knows1 = tx.getEdgeLabel("knows");
        final PropertyKey weight1 = tx.getPropertyKey("weight");
        Instant txTimeMicro = txId.getTransactionTime();
        int txNo;
        if (txTimeMicro.isBefore(txTimes[1])) {
            txNo = 1;
            // v1 addition transaction
            assertEquals(1, Iterables.size(changes.getVertices(Change.ADDED)));
            assertEquals(0, Iterables.size(changes.getVertices(Change.REMOVED)));
            assertEquals(1, Iterables.size(changes.getVertices(Change.ANY)));
            assertEquals(2, Iterables.size(changes.getRelations(Change.ADDED)));
            assertEquals(1, Iterables.size(changes.getRelations(Change.ADDED, knows1)));
            assertEquals(1, Iterables.size(changes.getRelations(Change.ADDED, weight1)));
            assertEquals(2, Iterables.size(changes.getRelations(Change.ANY)));
            assertEquals(0, Iterables.size(changes.getRelations(Change.REMOVED)));
            final JanusGraphVertex v = Iterables.getOnlyElement(changes.getVertices(Change.ADDED));
            assertEquals(v1id, getId(v));
            final VertexProperty<Float> p = Iterables.getOnlyElement(changes.getProperties(v, Change.ADDED, "weight"));
            assertEquals(111.1, p.value().doubleValue(), 0.01);
            assertEquals(1, Iterables.size(changes.getEdges(v, Change.ADDED, OUT)));
            assertEquals(1, Iterables.size(changes.getEdges(v, Change.ADDED, BOTH)));
        } else if (txTimeMicro.isBefore(txTimes[2])) {
            txNo = 2;
            // v2 addition transaction
            assertEquals(1, Iterables.size(changes.getVertices(Change.ADDED)));
            assertEquals(0, Iterables.size(changes.getVertices(Change.REMOVED)));
            assertEquals(2, Iterables.size(changes.getVertices(Change.ANY)));
            assertEquals(2, Iterables.size(changes.getRelations(Change.ADDED)));
            assertEquals(1, Iterables.size(changes.getRelations(Change.ADDED, knows1)));
            assertEquals(1, Iterables.size(changes.getRelations(Change.ADDED, weight1)));
            assertEquals(2, Iterables.size(changes.getRelations(Change.ANY)));
            assertEquals(0, Iterables.size(changes.getRelations(Change.REMOVED)));
            final JanusGraphVertex v = Iterables.getOnlyElement(changes.getVertices(Change.ADDED));
            assertEquals(v2id, getId(v));
            final VertexProperty<Float> p = Iterables.getOnlyElement(changes.getProperties(v, Change.ADDED, "weight"));
            assertEquals(222.2, p.value().doubleValue(), 0.01);
            assertEquals(1, Iterables.size(changes.getEdges(v, Change.ADDED, OUT)));
            assertEquals(1, Iterables.size(changes.getEdges(v, Change.ADDED, BOTH)));
        } else if (txTimeMicro.isBefore(txTimes[3])) {
            txNo = 3;
            // v2 deletion transaction
            assertEquals(0, Iterables.size(changes.getVertices(Change.ADDED)));
            assertEquals(1, Iterables.size(changes.getVertices(Change.REMOVED)));
            assertEquals(2, Iterables.size(changes.getVertices(Change.ANY)));
            assertEquals(0, Iterables.size(changes.getRelations(Change.ADDED)));
            assertEquals(2, Iterables.size(changes.getRelations(Change.REMOVED)));
            assertEquals(1, Iterables.size(changes.getRelations(Change.REMOVED, knows1)));
            assertEquals(1, Iterables.size(changes.getRelations(Change.REMOVED, weight1)));
            assertEquals(2, Iterables.size(changes.getRelations(Change.ANY)));
            final JanusGraphVertex v = Iterables.getOnlyElement(changes.getVertices(Change.REMOVED));
            assertEquals(v2id, getId(v));
            final VertexProperty<Float> p = Iterables.getOnlyElement(changes.getProperties(v, Change.REMOVED, "weight"));
            assertEquals(222.2, p.value().doubleValue(), 0.01);
            assertEquals(1, Iterables.size(changes.getEdges(v, Change.REMOVED, OUT)));
            assertEquals(0, Iterables.size(changes.getEdges(v, Change.ADDED, BOTH)));
        } else {
            txNo = 4;
            // v1 edge modification
            assertEquals(0, Iterables.size(changes.getVertices(Change.ADDED)));
            assertEquals(0, Iterables.size(changes.getVertices(Change.REMOVED)));
            assertEquals(1, Iterables.size(changes.getVertices(Change.ANY)));
            assertEquals(1, Iterables.size(changes.getRelations(Change.ADDED)));
            assertEquals(1, Iterables.size(changes.getRelations(Change.REMOVED)));
            assertEquals(1, Iterables.size(changes.getRelations(Change.REMOVED, knows1)));
            assertEquals(2, Iterables.size(changes.getRelations(Change.ANY)));
            final JanusGraphVertex v = Iterables.getOnlyElement(changes.getVertices(Change.ANY));
            assertEquals(v1id, getId(v));
            JanusGraphEdge e1 = Iterables.getOnlyElement(changes.getEdges(v, Change.REMOVED, Direction.OUT, "knows"));
            assertFalse(e1.property("weight").isPresent());
            assertEquals(v, e1.vertex(Direction.IN));
            e1 = Iterables.getOnlyElement(changes.getEdges(v, Change.ADDED, Direction.OUT, "knows"));
            assertEquals(44.4, e1.<Float>value("weight").doubleValue(), 0.01);
            assertEquals(v, e1.vertex(Direction.IN));
        }
        // See only current state of graph in transaction
        final JanusGraphVertex v11 = getV(tx, v1id);
        assertNotNull(v11);
        assertTrue(v11.isLoaded());
        if (txNo != 2) {
            // In the transaction that adds v2, v2 will be considered "loaded"
            assertMissing(tx, v2id);
        // assertTrue(txNo + " - " + v2, v2 == null || v2.isRemoved());
        }
        assertEquals(111.1, v11.<Float>value("weight").doubleValue(), 0.01);
        assertCount(1, v11.query().direction(Direction.OUT).edges());
        userLogCount.incrementAndGet();
    }).build();
    // wait
    Thread.sleep(22000L);
    recovery.shutdown();
    long[] recoveryStats = ((StandardTransactionLogProcessor) recovery).getStatistics();
    if (withLogFailure) {
        assertEquals(1, recoveryStats[0]);
        assertEquals(4, recoveryStats[1]);
    } else {
        assertEquals(5, recoveryStats[0]);
        assertEquals(0, recoveryStats[1]);
    }
    userLogs.removeLogProcessor(userLogName);
    userLogs.shutdown();
    assertEquals(4, userLogCount.get());
}
Also used : ManagementUtil(org.janusgraph.core.util.ManagementUtil) JanusGraphVertex(org.janusgraph.core.JanusGraphVertex) BasicVertexCentricQueryBuilder(org.janusgraph.graphdb.query.vertex.BasicVertexCentricQueryBuilder) Arrays(java.util.Arrays) MessageReader(org.janusgraph.diskstorage.log.MessageReader) Geoshape(org.janusgraph.core.attribute.Geoshape) JanusGraphTransaction(org.janusgraph.core.JanusGraphTransaction) WriteConfiguration(org.janusgraph.diskstorage.configuration.WriteConfiguration) Cardinality(org.janusgraph.core.Cardinality) Serializer(org.janusgraph.graphdb.database.serialize.Serializer) Cardinality.single(org.apache.tinkerpop.gremlin.structure.VertexProperty.Cardinality.single) Duration(java.time.Duration) Map(java.util.Map) StaticBuffer(org.janusgraph.diskstorage.StaticBuffer) LogTxStatus(org.janusgraph.graphdb.database.log.LogTxStatus) Metrics(org.apache.tinkerpop.gremlin.process.traversal.util.Metrics) EnumSet(java.util.EnumSet) JanusGraphSchemaType(org.janusgraph.core.schema.JanusGraphSchemaType) IndexRepairJob(org.janusgraph.graphdb.olap.job.IndexRepairJob) PropertyKey(org.janusgraph.core.PropertyKey) JanusGraphFactory(org.janusgraph.core.JanusGraphFactory) EnumMap(java.util.EnumMap) TimestampProvider(org.janusgraph.diskstorage.util.time.TimestampProvider) StandardJanusGraph(org.janusgraph.graphdb.database.StandardJanusGraph) Order.decr(org.apache.tinkerpop.gremlin.process.traversal.Order.decr) Set(java.util.Set) EdgeSerializer(org.janusgraph.graphdb.database.EdgeSerializer) Vertex(org.apache.tinkerpop.gremlin.structure.Vertex) EdgeLabel(org.janusgraph.core.EdgeLabel) JanusGraphVertexProperty(org.janusgraph.core.JanusGraphVertexProperty) Category(org.junit.experimental.categories.Category) CountDownLatch(java.util.concurrent.CountDownLatch) LogProcessorFramework(org.janusgraph.core.log.LogProcessorFramework) RelationTypeIndex(org.janusgraph.core.schema.RelationTypeIndex) GraphTraversalSource(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource) JanusGraphVertexStep(org.janusgraph.graphdb.tinkerpop.optimize.JanusGraphVertexStep) Iterables(com.google.common.collect.Iterables) StartStep(org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.StartStep) TestGraphConfigs(org.janusgraph.testutil.TestGraphConfigs) GraphStep(org.apache.tinkerpop.gremlin.process.traversal.step.map.GraphStep) SimpleQueryProfiler(org.janusgraph.graphdb.query.profile.SimpleQueryProfiler) ArrayList(java.util.ArrayList) StandardTransactionLogProcessor(org.janusgraph.graphdb.log.StandardTransactionLogProcessor) ScanMetrics(org.janusgraph.diskstorage.keycolumnvalue.scan.ScanMetrics) Lists(com.google.common.collect.Lists) Change(org.janusgraph.core.log.Change) Cmp(org.janusgraph.core.attribute.Cmp) ConsistencyModifier(org.janusgraph.core.schema.ConsistencyModifier) JanusGraphException(org.janusgraph.core.JanusGraphException) StreamSupport(java.util.stream.StreamSupport) StandardEdgeLabelMaker(org.janusgraph.graphdb.types.StandardEdgeLabelMaker) JanusGraphElement(org.janusgraph.core.JanusGraphElement) TransactionLogHeader(org.janusgraph.graphdb.database.log.TransactionLogHeader) Test(org.junit.Test) T(org.apache.tinkerpop.gremlin.structure.T) ExecutionException(java.util.concurrent.ExecutionException) Direction(org.apache.tinkerpop.gremlin.structure.Direction) ChronoUnit(java.time.temporal.ChronoUnit) Traversal(org.apache.tinkerpop.gremlin.process.traversal.Traversal) GraphDatabaseConfiguration(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration) JanusGraphVertexQuery(org.janusgraph.core.JanusGraphVertexQuery) Preconditions(com.google.common.base.Preconditions) VertexLabel(org.janusgraph.core.VertexLabel) TraversalMetrics(org.apache.tinkerpop.gremlin.process.traversal.util.TraversalMetrics) JanusGraphAssert(org.janusgraph.testutil.JanusGraphAssert) Assert(org.junit.Assert) SpecialIntSerializer(org.janusgraph.graphdb.serializer.SpecialIntSerializer) JanusGraphConfigurationException(org.janusgraph.core.JanusGraphConfigurationException) Log(org.janusgraph.diskstorage.log.Log) StandardJanusGraphTx(org.janusgraph.graphdb.transaction.StandardJanusGraphTx) PropertyKeyDefinition(org.janusgraph.graphdb.schema.PropertyKeyDefinition) LoggerFactory(org.slf4j.LoggerFactory) ConfigOption(org.janusgraph.diskstorage.configuration.ConfigOption) Random(java.util.Random) JanusGraphEdge(org.janusgraph.core.JanusGraphEdge) SchemaAction(org.janusgraph.core.schema.SchemaAction) Order.incr(org.apache.tinkerpop.gremlin.process.traversal.Order.incr) OrderList(org.janusgraph.graphdb.internal.OrderList) JanusGraphManagement(org.janusgraph.core.schema.JanusGraphManagement) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SchemaStatus(org.janusgraph.core.schema.SchemaStatus) JanusGraphIndex(org.janusgraph.core.schema.JanusGraphIndex) JanusGraphPropertiesStep(org.janusgraph.graphdb.tinkerpop.optimize.JanusGraphPropertiesStep) P(org.apache.tinkerpop.gremlin.process.traversal.P) TransactionRecovery(org.janusgraph.core.log.TransactionRecovery) Multiplicity(org.janusgraph.core.Multiplicity) RelationType(org.janusgraph.core.RelationType) EdgeLabelDefinition(org.janusgraph.graphdb.schema.EdgeLabelDefinition) Property(org.apache.tinkerpop.gremlin.structure.Property) SchemaViolationException(org.janusgraph.core.SchemaViolationException) Mapping(org.janusgraph.core.schema.Mapping) ImmutableMap(com.google.common.collect.ImmutableMap) IndexRemoveJob(org.janusgraph.graphdb.olap.job.IndexRemoveJob) BrittleTests(org.janusgraph.testcategory.BrittleTests) LogTxMeta(org.janusgraph.graphdb.database.log.LogTxMeta) StandardPropertyKeyMaker(org.janusgraph.graphdb.types.StandardPropertyKeyMaker) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) List(java.util.List) RelationIdentifier(org.janusgraph.graphdb.relations.RelationIdentifier) ImplicitKey(org.janusgraph.graphdb.types.system.ImplicitKey) LocalStep(org.apache.tinkerpop.gremlin.process.traversal.step.branch.LocalStep) GraphCentricQueryBuilder(org.janusgraph.graphdb.query.graph.GraphCentricQueryBuilder) InternalRelationType(org.janusgraph.graphdb.internal.InternalRelationType) JanusGraphStep(org.janusgraph.graphdb.tinkerpop.optimize.JanusGraphStep) SchemaContainer(org.janusgraph.graphdb.schema.SchemaContainer) Backend(org.janusgraph.diskstorage.Backend) Iterators(com.google.common.collect.Iterators) SpecialInt(org.janusgraph.graphdb.serializer.SpecialInt) JanusGraphQuery(org.janusgraph.core.JanusGraphQuery) OrderGlobalStep(org.apache.tinkerpop.gremlin.process.traversal.step.map.OrderGlobalStep) HashSet(java.util.HashSet) VertexProperty(org.apache.tinkerpop.gremlin.structure.VertexProperty) ImmutableList(com.google.common.collect.ImmutableList) ConfigElement(org.janusgraph.diskstorage.configuration.ConfigElement) Message(org.janusgraph.diskstorage.log.Message) RelationCategory(org.janusgraph.graphdb.internal.RelationCategory) GraphOfTheGodsFactory(org.janusgraph.example.GraphOfTheGodsFactory) Edge(org.apache.tinkerpop.gremlin.structure.Edge) BackendException(org.janusgraph.diskstorage.BackendException) QueryProfiler(org.janusgraph.graphdb.query.profile.QueryProfiler) Logger(org.slf4j.Logger) KCVSLog(org.janusgraph.diskstorage.log.kcvs.KCVSLog) Iterator(java.util.Iterator) BaseVertexLabel(org.janusgraph.graphdb.types.system.BaseVertexLabel) VertexList(org.janusgraph.core.VertexList) org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__) JanusGraph(org.janusgraph.core.JanusGraph) GraphTraversal(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal) ElementCategory(org.janusgraph.graphdb.internal.ElementCategory) Order(org.janusgraph.graphdb.internal.Order) Step(org.apache.tinkerpop.gremlin.process.traversal.Step) TimeUnit(java.util.concurrent.TimeUnit) ManagementSystem(org.janusgraph.graphdb.database.management.ManagementSystem) TraversalFilterStep(org.apache.tinkerpop.gremlin.process.traversal.step.filter.TraversalFilterStep) ReadMarker(org.janusgraph.diskstorage.log.ReadMarker) VertexLabelDefinition(org.janusgraph.graphdb.schema.VertexLabelDefinition) Contain(org.janusgraph.core.attribute.Contain) TransactionRecovery(org.janusgraph.core.log.TransactionRecovery) Message(org.janusgraph.diskstorage.log.Message) JanusGraphEdge(org.janusgraph.core.JanusGraphEdge) MessageReader(org.janusgraph.diskstorage.log.MessageReader) JanusGraphTransaction(org.janusgraph.core.JanusGraphTransaction) JanusGraphVertex(org.janusgraph.core.JanusGraphVertex) EdgeSerializer(org.janusgraph.graphdb.database.EdgeSerializer) StaticBuffer(org.janusgraph.diskstorage.StaticBuffer) TransactionLogHeader(org.janusgraph.graphdb.database.log.TransactionLogHeader) JanusGraphVertexProperty(org.janusgraph.core.JanusGraphVertexProperty) VertexProperty(org.apache.tinkerpop.gremlin.structure.VertexProperty) LogTxStatus(org.janusgraph.graphdb.database.log.LogTxStatus) EnumMap(java.util.EnumMap) Serializer(org.janusgraph.graphdb.database.serialize.Serializer) EdgeSerializer(org.janusgraph.graphdb.database.EdgeSerializer) SpecialIntSerializer(org.janusgraph.graphdb.serializer.SpecialIntSerializer) Log(org.janusgraph.diskstorage.log.Log) KCVSLog(org.janusgraph.diskstorage.log.kcvs.KCVSLog) Instant(java.time.Instant) EdgeLabel(org.janusgraph.core.EdgeLabel) ReadMarker(org.janusgraph.diskstorage.log.ReadMarker) Change(org.janusgraph.core.log.Change) LogProcessorFramework(org.janusgraph.core.log.LogProcessorFramework) TimestampProvider(org.janusgraph.diskstorage.util.time.TimestampProvider) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StandardTransactionLogProcessor(org.janusgraph.graphdb.log.StandardTransactionLogProcessor) JanusGraphEdge(org.janusgraph.core.JanusGraphEdge) Edge(org.apache.tinkerpop.gremlin.structure.Edge) PropertyKey(org.janusgraph.core.PropertyKey)

Example 5 with Serializer

use of org.janusgraph.graphdb.database.serialize.Serializer in project janusgraph by JanusGraph.

the class StandardJanusGraphTxTest method createTxWithMockedInternals.

private StandardJanusGraphTx createTxWithMockedInternals() {
    StandardJanusGraph mockGraph = createMock(StandardJanusGraph.class);
    TransactionConfiguration txConfig = createMock(TransactionConfiguration.class);
    GraphDatabaseConfiguration gdbConfig = createMock(GraphDatabaseConfiguration.class);
    TimestampProvider tsProvider = createMock(TimestampProvider.class);
    Serializer mockSerializer = createMock(Serializer.class);
    EdgeSerializer mockEdgeSerializer = createMock(EdgeSerializer.class);
    IndexSerializer mockIndexSerializer = createMock(IndexSerializer.class);
    RelationType relationType = createMock(RelationType.class);
    IDManager idManager = createMock(IDManager.class);
    PropertyKey propertyKey = createMock(PropertyKey.class);
    DefaultSchemaMaker defaultSchemaMaker = createMock(DefaultSchemaMaker.class);
    expect(mockGraph.getConfiguration()).andReturn(gdbConfig);
    expect(mockGraph.isOpen()).andReturn(true).anyTimes();
    expect(mockGraph.getDataSerializer()).andReturn(mockSerializer);
    expect(mockGraph.getEdgeSerializer()).andReturn(mockEdgeSerializer);
    expect(mockGraph.getIndexSerializer()).andReturn(mockIndexSerializer);
    expect(mockGraph.getIDManager()).andReturn(idManager);
    expect(gdbConfig.getTimestampProvider()).andReturn(tsProvider);
    expect(txConfig.isSingleThreaded()).andReturn(true);
    expect(txConfig.hasPreloadedData()).andReturn(false);
    expect(txConfig.hasVerifyExternalVertexExistence()).andReturn(false);
    expect(txConfig.hasVerifyInternalVertexExistence()).andReturn(false);
    expect(txConfig.getVertexCacheSize()).andReturn(6);
    expect(txConfig.isReadOnly()).andReturn(true);
    expect(txConfig.getDirtyVertexSize()).andReturn(2);
    expect(txConfig.getIndexCacheWeight()).andReturn(2L);
    expect(txConfig.getGroupName()).andReturn(null);
    expect(txConfig.getAutoSchemaMaker()).andReturn(defaultSchemaMaker);
    expect(defaultSchemaMaker.makePropertyKey(isA(PropertyKeyMaker.class), notNull())).andReturn(propertyKey);
    expect(relationType.isPropertyKey()).andReturn(false);
    expect(propertyKey.isPropertyKey()).andReturn(true);
    replayAll();
    StandardJanusGraphTx partialMock = createMockBuilder(StandardJanusGraphTx.class).withConstructor(mockGraph, txConfig).addMockedMethod("getRelationType").createMock();
    expect(partialMock.getRelationType("Foo")).andReturn(null);
    expect(partialMock.getRelationType("Qux")).andReturn(propertyKey);
    expect(partialMock.getRelationType("Baz")).andReturn(relationType);
    replay(partialMock);
    return partialMock;
}
Also used : IndexSerializer(org.janusgraph.graphdb.database.IndexSerializer) IDManager(org.janusgraph.graphdb.idmanagement.IDManager) GraphDatabaseConfiguration(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration) PropertyKeyMaker(org.janusgraph.core.schema.PropertyKeyMaker) TimestampProvider(org.janusgraph.diskstorage.util.time.TimestampProvider) DefaultSchemaMaker(org.janusgraph.core.schema.DefaultSchemaMaker) RelationType(org.janusgraph.core.RelationType) EdgeSerializer(org.janusgraph.graphdb.database.EdgeSerializer) PropertyKey(org.janusgraph.core.PropertyKey) StandardJanusGraph(org.janusgraph.graphdb.database.StandardJanusGraph) EdgeSerializer(org.janusgraph.graphdb.database.EdgeSerializer) IndexSerializer(org.janusgraph.graphdb.database.IndexSerializer) Serializer(org.janusgraph.graphdb.database.serialize.Serializer)

Aggregations

Serializer (org.janusgraph.graphdb.database.serialize.Serializer)5 RelationType (org.janusgraph.core.RelationType)3 TimestampProvider (org.janusgraph.diskstorage.util.time.TimestampProvider)3 GraphDatabaseConfiguration (org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration)3 StandardJanusGraph (org.janusgraph.graphdb.database.StandardJanusGraph)3 Preconditions (com.google.common.base.Preconditions)2 Duration (java.time.Duration)2 Instant (java.time.Instant)2 List (java.util.List)2 Map (java.util.Map)2 ExecutionException (java.util.concurrent.ExecutionException)2 TimeUnit (java.util.concurrent.TimeUnit)2 PropertyKey (org.janusgraph.core.PropertyKey)2 StaticBuffer (org.janusgraph.diskstorage.StaticBuffer)2 EdgeSerializer (org.janusgraph.graphdb.database.EdgeSerializer)2 RelationCategory (org.janusgraph.graphdb.internal.RelationCategory)2 Test (org.junit.Test)2 Predicate (com.google.common.base.Predicate)1 Predicates (com.google.common.base.Predicates)1 com.google.common.cache (com.google.common.cache)1