Search in sources :

Example 1 with ODatabaseDocumentInternal

use of com.orientechnologies.orient.core.db.ODatabaseDocumentInternal in project orientdb by orientechnologies.

the class ODistributedTransactionManager method createUndoTasksFromTx.

/**
   * Create undo content for distributed 2-phase rollback. This list of undo tasks is sent to all the nodes to revert a transaction
   * and it's also applied locally.
   *
   * @param iTx Current transaction
   *
   * @return List of remote undo tasks
   */
protected List<OAbstractRemoteTask> createUndoTasksFromTx(final OTransaction iTx) {
    final List<OAbstractRemoteTask> undoTasks = new ArrayList<OAbstractRemoteTask>();
    for (ORecordOperation op : iTx.getAllRecordEntries()) {
        OAbstractRemoteTask undoTask = null;
        final ORecord record = op.getRecord();
        switch(op.type) {
            case ORecordOperation.CREATED:
                // CREATE UNDO TASK LATER ONCE THE RID HAS BEEN ASSIGNED
                break;
            case ORecordOperation.UPDATED:
            case ORecordOperation.DELETED:
                // CREATE UNDO TASK WITH THE PREVIOUS RECORD CONTENT/VERSION
                final ORecordId rid = (ORecordId) record.getIdentity();
                final AtomicReference<ORecord> previousRecord = new AtomicReference<ORecord>();
                OScenarioThreadLocal.executeAsDefault(new Callable<Object>() {

                    @Override
                    public Object call() throws Exception {
                        final ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.INSTANCE.get();
                        final ORecordOperation txEntry = db.getTransaction().getRecordEntry(rid);
                        if (txEntry != null && txEntry.type == ORecordOperation.DELETED)
                            // GET DELETED RECORD FROM TX
                            previousRecord.set(txEntry.getRecord());
                        else {
                            final OStorageOperationResult<ORawBuffer> loadedBuffer = ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getUnderlying().readRecord(rid, null, true, false, null);
                            if (loadedBuffer != null) {
                                // LOAD THE RECORD FROM THE STORAGE AVOIDING USING THE DB TO GET THE TRANSACTIONAL CHANGES
                                final ORecord loaded = Orient.instance().getRecordFactoryManager().newInstance(loadedBuffer.getResult().recordType);
                                ORecordInternal.fill(loaded, rid, loadedBuffer.getResult().version, loadedBuffer.getResult().getBuffer(), false);
                                previousRecord.set(loaded);
                            } else
                                // RECORD NOT FOUND ON LOCAL STORAGE, ASK TO DB BECAUSE IT COULD BE SHARDED AND RESIDE ON ANOTHER SERVER
                                previousRecord.set(db.load(rid));
                        }
                        return null;
                    }
                });
                if (previousRecord.get() == null)
                    throw new ORecordNotFoundException(rid);
                if (op.type == ORecordOperation.UPDATED)
                    undoTask = new OFixUpdateRecordTask(previousRecord.get(), ORecordVersionHelper.clearRollbackMode(previousRecord.get().getVersion()));
                else
                    undoTask = new OResurrectRecordTask(previousRecord.get());
                break;
            default:
                continue;
        }
        if (undoTask != null)
            undoTasks.add(undoTask);
    }
    return undoTasks;
}
Also used : OStorageOperationResult(com.orientechnologies.orient.core.storage.OStorageOperationResult) AtomicReference(java.util.concurrent.atomic.AtomicReference) ORecordId(com.orientechnologies.orient.core.id.ORecordId) OException(com.orientechnologies.common.exception.OException) ONeedRetryException(com.orientechnologies.common.concur.ONeedRetryException) IOException(java.io.IOException) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal) ORecordOperation(com.orientechnologies.orient.core.db.record.ORecordOperation) ORecord(com.orientechnologies.orient.core.record.ORecord)

Example 2 with ODatabaseDocumentInternal

use of com.orientechnologies.orient.core.db.ODatabaseDocumentInternal in project orientdb by orientechnologies.

the class OStorageRemote method copy.

@Override
public OStorageRemote copy(final ODatabaseDocumentTx source, final ODatabaseDocumentTx dest) {
    ODatabaseDocumentInternal origin = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
    final OStorageRemoteSession session = (OStorageRemoteSession) ODatabaseDocumentTxInternal.getSessionMetadata(source);
    if (session != null) {
        // TODO:may run a session reopen
        final OStorageRemoteSession newSession = new OStorageRemoteSession(sessionSerialId.decrementAndGet());
        newSession.connectionUserName = session.connectionUserName;
        newSession.connectionUserPassword = session.connectionUserPassword;
        ODatabaseDocumentTxInternal.setSessionMetadata(dest, newSession);
    }
    try {
        dest.activateOnCurrentThread();
        openRemoteDatabase();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        ODatabaseRecordThreadLocal.INSTANCE.set(origin);
    }
    return this;
}
Also used : OIOException(com.orientechnologies.common.io.OIOException) IOException(java.io.IOException) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)

Example 3 with ODatabaseDocumentInternal

use of com.orientechnologies.orient.core.db.ODatabaseDocumentInternal in project orientdb by orientechnologies.

the class OStorageRemote method command.

/**
 * Execute the command remotely and get the results back.
 */
public Object command(final OCommandRequestText iCommand) {
    if (!(iCommand instanceof OSerializableStream))
        throw new OCommandExecutionException("Cannot serialize the command to be executed to the server side.");
    final boolean live = iCommand instanceof OLiveQuery;
    final ODatabaseDocument database = ODatabaseRecordThreadLocal.INSTANCE.get();
    return networkOperation(new OStorageRemoteOperation<Object>() {

        @Override
        public Object execute(final OChannelBinaryAsynchClient network, OStorageRemoteSession session) throws IOException {
            Object result = null;
            session.commandExecuting = true;
            try {
                final boolean asynch = iCommand instanceof OCommandRequestAsynch && ((OCommandRequestAsynch) iCommand).isAsynchronous();
                try {
                    beginRequest(network, OChannelBinaryProtocol.REQUEST_COMMAND, session);
                    if (live) {
                        network.writeByte((byte) 'l');
                    } else {
                        // ASYNC / SYNC
                        network.writeByte((byte) (asynch ? 'a' : 's'));
                    }
                    network.writeBytes(OStreamSerializerAnyStreamable.INSTANCE.toStream(iCommand));
                } finally {
                    endRequest(network);
                }
                try {
                    beginResponse(network, session);
                    // Collection of prefetched temporary record (nested projection record), to refer for avoid garbage collection.
                    List<ORecord> temporaryResults = new ArrayList<ORecord>();
                    boolean addNextRecord = true;
                    if (asynch) {
                        byte status;
                        // ASYNCH: READ ONE RECORD AT TIME
                        while ((status = network.readByte()) > 0) {
                            final ORecord record = (ORecord) OChannelBinaryProtocol.readIdentifiable(network);
                            if (record == null)
                                continue;
                            switch(status) {
                                case 1:
                                    // PUT AS PART OF THE RESULT SET. INVOKE THE LISTENER
                                    if (addNextRecord) {
                                        addNextRecord = iCommand.getResultListener().result(record);
                                        database.getLocalCache().updateRecord(record);
                                    }
                                    break;
                                case 2:
                                    if (record.getIdentity().getClusterId() == -2)
                                        temporaryResults.add(record);
                                    // PUT IN THE CLIENT LOCAL CACHE
                                    database.getLocalCache().updateRecord(record);
                            }
                        }
                    } else {
                        result = readSynchResult(network, database, temporaryResults);
                        if (live) {
                            final ODocument doc = ((List<ODocument>) result).get(0);
                            final Integer token = doc.field("token");
                            final Boolean unsubscribe = doc.field("unsubscribe");
                            if (token != null) {
                                if (Boolean.TRUE.equals(unsubscribe)) {
                                    if (OStorageRemote.this.asynchEventListener != null)
                                        OStorageRemote.this.asynchEventListener.unregisterLiveListener(token);
                                } else {
                                    final OLiveResultListener listener = (OLiveResultListener) iCommand.getResultListener();
                                    ODatabaseDocumentInternal current = ODatabaseRecordThreadLocal.INSTANCE.get();
                                    final ODatabaseDocument dbCopy = current.copy();
                                    ORemoteConnectionPool pool = OStorageRemote.this.connectionManager.getPool(network.getServerURL());
                                    OStorageRemote.this.asynchEventListener.registerLiveListener(pool, token, new OLiveResultListener() {

                                        @Override
                                        public void onUnsubscribe(int iLiveToken) {
                                            listener.onUnsubscribe(iLiveToken);
                                            dbCopy.close();
                                        }

                                        @Override
                                        public void onLiveResult(int iLiveToken, ORecordOperation iOp) throws OException {
                                            dbCopy.activateOnCurrentThread();
                                            listener.onLiveResult(iLiveToken, iOp);
                                        }

                                        @Override
                                        public void onError(int iLiveToken) {
                                            listener.onError(iLiveToken);
                                            dbCopy.close();
                                        }
                                    });
                                }
                            } else {
                                throw new OStorageException("Cannot execute live query, returned null token");
                            }
                        }
                    }
                    if (!temporaryResults.isEmpty()) {
                        if (result instanceof OBasicResultSet<?>) {
                            ((OBasicResultSet<?>) result).setTemporaryRecordCache(temporaryResults);
                        }
                    }
                    return result;
                } finally {
                    endResponse(network);
                }
            } finally {
                session.commandExecuting = false;
                if (iCommand.getResultListener() != null && !live)
                    iCommand.getResultListener().end();
            }
        }
    }, "Error on executing command: " + iCommand);
}
Also used : OIOException(com.orientechnologies.common.io.OIOException) IOException(java.io.IOException) OChannelBinaryAsynchClient(com.orientechnologies.orient.client.binary.OChannelBinaryAsynchClient) OCommandRequestAsynch(com.orientechnologies.orient.core.command.OCommandRequestAsynch) OLiveResultListener(com.orientechnologies.orient.core.sql.query.OLiveResultListener) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ORecordOperation(com.orientechnologies.orient.core.db.record.ORecordOperation) ODatabaseDocument(com.orientechnologies.orient.core.db.document.ODatabaseDocument) OLiveQuery(com.orientechnologies.orient.core.sql.query.OLiveQuery) ORecord(com.orientechnologies.orient.core.record.ORecord) OSerializableStream(com.orientechnologies.orient.core.serialization.OSerializableStream) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 4 with ODatabaseDocumentInternal

use of com.orientechnologies.orient.core.db.ODatabaseDocumentInternal in project orientdb by orientechnologies.

the class ODocument method setup.

/**
 * Internal.
 */
@Override
protected void setup() {
    super.setup();
    final ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
    if (db != null)
        _recordFormat = db.getSerializer();
    if (_recordFormat == null)
        // GET THE DEFAULT ONE
        _recordFormat = ODatabaseDocumentTx.getDefaultSerializer();
}
Also used : ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)

Example 5 with ODatabaseDocumentInternal

use of com.orientechnologies.orient.core.db.ODatabaseDocumentInternal in project orientdb by orientechnologies.

the class ODocument method fetchClassName.

private void fetchClassName() {
    final ODatabaseDocumentInternal database = getDatabaseIfDefinedInternal();
    if (database != null && database.getStorageVersions() != null && database.getStorageVersions().classesAreDetectedByClusterId()) {
        if (_recordId.getClusterId() < 0) {
            checkForLoading();
            checkForFields(ODocumentHelper.ATTRIBUTE_CLASS);
        } else {
            final OSchema schema = ((OMetadataInternal) database.getMetadata()).getImmutableSchemaSnapshot();
            if (schema != null) {
                OClass _clazz = schema.getClassByClusterId(_recordId.getClusterId());
                if (_clazz != null)
                    _className = _clazz.getName();
            }
        }
    } else {
        // CLASS NOT FOUND: CHECK IF NEED LOADING AND UNMARSHALLING
        checkForLoading();
        checkForFields(ODocumentHelper.ATTRIBUTE_CLASS);
    }
}
Also used : OMetadataInternal(com.orientechnologies.orient.core.metadata.OMetadataInternal) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)

Aggregations

ODatabaseDocumentInternal (com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)149 OCommandSQL (com.orientechnologies.orient.core.sql.OCommandSQL)42 OStorage (com.orientechnologies.orient.core.storage.OStorage)31 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)26 OStorageProxy (com.orientechnologies.orient.core.storage.OStorageProxy)20 OCommandExecutionException (com.orientechnologies.orient.core.exception.OCommandExecutionException)18 OAutoshardedStorage (com.orientechnologies.orient.core.storage.OAutoshardedStorage)18 ODatabaseDocumentTx (com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx)16 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)16 ORID (com.orientechnologies.orient.core.id.ORID)14 OException (com.orientechnologies.common.exception.OException)13 IOException (java.io.IOException)13 ORecordId (com.orientechnologies.orient.core.id.ORecordId)12 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)10 OSchemaException (com.orientechnologies.orient.core.exception.OSchemaException)10 ORecord (com.orientechnologies.orient.core.record.ORecord)8 ODatabaseDocument (com.orientechnologies.orient.core.db.document.ODatabaseDocument)7 OMetadataInternal (com.orientechnologies.orient.core.metadata.OMetadataInternal)6 ODatabaseException (com.orientechnologies.orient.core.exception.ODatabaseException)5 OSecurityException (com.orientechnologies.orient.core.exception.OSecurityException)5