Package com.linkedin.databus2.core

Examples of com.linkedin.databus2.core.DatabusException


      _registeredMbeans.add(objectName);
    }
    catch(Exception ex)
    {
      _log.error("Failed to register the gg-source statistics mbean for source (" + source.getSourceName() + ") due to an exception.", ex);
      throw new DatabusException("Failed to initialize gg event statistics mbeans.", ex);
    }

  }
View Full Code Here


          }
          else //If the max scn is set to <0, this is a special case that we use to let the trail file notifier that you want to override the default behaviour of starting with the latest scn.
          {
              _log.info("Overridding default behaviour (start with latest scn), using scn : " + scn + " to start the relay");
              if(scn != TrailFilePositionSetter.USE_EARLIEST_SCN && scn != TrailFilePositionSetter.USE_LATEST_SCN)
                throw new DatabusException("The scn you have passed is neither EARLIEST or LATEST  setting, cannot proceed with using this scn");

              _scn.set(scn);
          }

        }
View Full Code Here

      _log.info("File position at : "+ filePositionResult);
      switch(filePositionResult.getStatus())
      {
        case ERROR:
          _log.fatal("Unable to locate the scn in the trail file.");
          throw new DatabusException("Unable to find the given scn " + _scn.get() + " in the trail files");
        case NO_TXNS_FOUND:

          //If the latest scn is not found in the trail files, then use the earliest scn.
          if(_scn.get() == TrailFilePositionSetter.USE_LATEST_SCN)
          {
            _log.info("Switching from USE_LATEST_SCN to USE_EARLIEST_SCN because no trail files were not found");
            _scn.set(TrailFilePositionSetter.USE_EARLIEST_SCN);
          }

          long noTxnsFoundSleepTime = 500;                      //TODO sleep get configuration for sleep time
          _log.info("NO_TXNS_FOUND, sleeping for "+ noTxnsFoundSleepTime + " ms before retrying");
          Thread.sleep(noTxnsFoundSleepTime);
          break;
        case EXACT_SCN_NOT_FOUND:
        {
          _log.info("Exact SCN was not found, the closest scn found was: " + filePositionResult.getTxnPos().getMinScn());
          compositeInputStream = new ConcurrentAppendableCompositeFileInputStream(xmlDir,
                                                                                  filePositionResult.getTxnPos().getFile(),
                                                                                  filePositionResult.getTxnPos().getFileOffset(),
                                                                                  new TrailFilePositionSetter.FileFilter(new File(xmlDir), xmlPrefix),
                                                                                  false);
          long foundScn = filePositionResult.getTxnPos().getMaxScn();
          /**
           * If exact scn is not found, the trail file position setter returns the next immediate available scn, i.e., the contract guarantees
           * a scn always greater than the given scn (foundscn > _scn). We use the _scn (requested scn to be found) as the prevScn to start the event buffer.
           * And the scn found as the current scn(first event in the relay).
           */
          if(foundScn <= _scn.get())
            throw new DatabusException("EXACT_SCN_NOT_FOUND, but foundScn is <= _scn ");

          _startPrevScn.set(_scn.get());
          _log.info("Changing current scn from " + _scn.get() + " to " + foundScn);
          _log.info("Planning to use prevScn " + _startPrevScn);
          _scn.set(foundScn);
          break;
        }
        case FOUND:
        {
          _log.info("Exact SCN was  found" + filePositionResult.getTxnPos().getMaxScn());
          compositeInputStream = new ConcurrentAppendableCompositeFileInputStream(xmlDir,
                                                                                  filePositionResult.getTxnPos().getFile(),
                                                                                  filePositionResult.getTxnPos().getFileOffset(),
                                                                                  new TrailFilePositionSetter.FileFilter(new File(xmlDir), xmlPrefix),
                                                                                  false);
          /**
           * The trail file position setter returns FOUND in two cases:
           * 1. MaxScn was given as input.
           * 2. Earliest or Latest scn was given as input.
           * For both the cases, we set the prevScn to the foundScn-1 and the foundScn as the currentScn.
           */
          long foundScn = filePositionResult.getTxnPos().getMaxScn();

          //Assert that if maxScn was requested, the trail file position setter has returned the exact scn (It has returned FOUND).
          if(_scn.get() >=0 && _scn.get() != foundScn)
          {
            throw new DatabusException("The exact scn was not found, but the trail file position setter has returned FOUND!");
          }

          _startPrevScn.set(foundScn - 1);
          _scn.set(foundScn);
          break;
        }
        default:
          throw new DatabusException("Unhandled file position result in switch case, terminating producer.");
      }
    }

    if(filePositionResult == null)
    {
      _log.info(trailFilePositionSetter);
      throw new DatabusException("file position Result returned by TrailFilePositionSetter is null!");
    }

    if(_scn.get() <= 0)
    {
      _log.info("The scn is <=0, using scn from file position setter:" + filePositionResult);
View Full Code Here

   */
  static protected Object obtainKey(DbUpdateState.DBUpdateImage dbUpdate)
      throws DatabusException
  {
    if (null == dbUpdate) {
      throw new DatabusException("DBUpdateImage is null");
    }
    List<KeyPair> pairs = dbUpdate.getKeyPairs();
    if (null == pairs || pairs.size() == 0) {
      throw new DatabusException("There do not seem to be any keys");
    }

    if (pairs.size() == 1) {
      Object key = dbUpdate.getKeyPairs().get(0).getKey();
      Schema.Type pKeyType = dbUpdate.getKeyPairs().get(0).getKeyType();
      Object keyObj = null;
      if (pKeyType == Schema.Type.INT)
      {
        if (key instanceof Integer)
        {
          keyObj = key;
        }
        else
        {
          throw new DatabusException(
              "Schema.Type does not match actual key type (INT) "
                  + key.getClass().getName());
        }

      } else if (pKeyType == Schema.Type.LONG)
      {
        if (key instanceof Long)
        {
          keyObj = key;
        }
        else
        {
          throw new DatabusException(
              "Schema.Type does not match actual key type (LONG) "
                  + key.getClass().getName());
        }

        keyObj = key;
      }
      else
      {
        keyObj = key;
      }

      return keyObj;
    } else {
      // Treat multiple keys as a separate case to avoid unnecessary casts
      Iterator<KeyPair> li = pairs.iterator();
      String compositeKey = "";
      while (li.hasNext())
      {
        KeyPair kp = li.next();
        Schema.Type pKeyType = kp.getKeyType();
        Object key = kp.getKey();
        if (pKeyType == Schema.Type.INT)
        {
          if (key instanceof Integer)
            compositeKey += kp.getKey().toString();
          else
            throw new DatabusException(
                "Schema.Type does not match actual key type (INT) "
                    + key.getClass().getName());
        }
        else if (pKeyType == Schema.Type.LONG)
        {
          if (key instanceof Long)
            compositeKey += key.toString();
          else
            throw new DatabusException(
                "Schema.Type does not match actual key type (LONG) "
                    + key.getClass().getName());
        }
        else
        {
View Full Code Here

   */
  protected void addEventToBuffer(List<TransactionState.PerSourceTransactionalUpdate> dbUpdates, TransactionInfo ti)
      throws DatabusException, UnsupportedKeyException
  {
    if(dbUpdates.size() == 0)
      throw new DatabusException("Cannot handle empty dbUpdates");

    long scn = ti.getScn();
    long timestamp = ti.getTransactionTimeStampNs();
    EventSourceStatistics globalStats = getSource(GLOBAL_SOURCE_ID).getStatisticsBean();

    /**
     * We skip the start scn of the relay, we have already added a EOP for this SCN in the buffer.
     * Why is this not a problem ?
     * There are two cases:
     * 1. When we use the earliest/latest scn if there is no maxScn (We don't really have a start point). So it's really OK to miss the first event.
     * 2. If it's the maxSCN, then event was already seen by the relay.
     */
    if(scn == _startPrevScn.get())
    {
      _log.info("Skipping this transaction, EOP already send for this event");
      return;
    }

    getEventBuffer().startEvents();

    int eventsInTransactionCount = 0;

    List<EventReaderSummary> summaries = new ArrayList<EventReaderSummary>();

    for (int i = 0; i < dbUpdates.size(); ++i)
    {
      GenericRecord record = null;
      TransactionState.PerSourceTransactionalUpdate perSourceUpdate = dbUpdates.get(i);
      short sourceId = (short)perSourceUpdate.getSourceId();
      // prepare stats collection per source
      EventSourceStatistics perSourceStats = getSource(sourceId).getStatisticsBean();

      Iterator<DbUpdateState.DBUpdateImage> dbUpdateIterator = perSourceUpdate.getDbUpdatesSet().iterator();
      int eventsInDbUpdate = 0;
      long dbUpdatesEventsSize = 0;
      long startDbUpdatesMs = System.currentTimeMillis();

      while(dbUpdateIterator.hasNext())  //TODO verify if there is any case where we need to rollback.
      {
        DbUpdateState.DBUpdateImage dbUpdate =  dbUpdateIterator.next();

        //Construct the Databus Event key, determine the key type and construct the key
        Object keyObj = obtainKey(dbUpdate);
        DbusEventKey eventKey = new DbusEventKey(keyObj);

        //Get the logicalparition id
        PartitionFunction partitionFunction = _partitionFunctionHashMap.get((int)sourceId);
        short lPartitionId = partitionFunction.getPartition(eventKey);

        record = dbUpdate.getGenericRecord();
        //Write the event to the buffer
        if (record == null)
          throw new DatabusException("Cannot write event to buffer because record = " + record);

        if(record.getSchema() == null)
          throw new DatabusException("The record does not have a schema (null schema)");

        try
        {
          //Collect stats on number of dbUpdates for one source
          eventsInDbUpdate++;

          //Count of all the events in the current transaction
          eventsInTransactionCount++;
          // Serialize the row
          ByteArrayOutputStream bos = new ByteArrayOutputStream();
          Encoder encoder = new BinaryEncoder(bos);
          GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<GenericRecord>(
              record.getSchema());
          writer.write(record, encoder);
          byte[] serializedValue = bos.toByteArray();

          //Get the md5 for the schema
          SchemaId schemaId = SchemaId.createWithMd5(dbUpdate.getSchema());

          //Determine the operation type and convert to dbus opcode
          DbusOpcode opCode;
          if(dbUpdate.getOpType() == DbUpdateState.DBUpdateImage.OpType.INSERT || dbUpdate.getOpType() == DbUpdateState.DBUpdateImage.OpType.UPDATE)
          {
            opCode = DbusOpcode.UPSERT;
            if(_log.isDebugEnabled())
              _log.debug("The event with scn "+ scn +" is INSERT/UPDATE");
          }
          else if(dbUpdate.getOpType() == DbUpdateState.DBUpdateImage.OpType.DELETE)
          {
            opCode = DbusOpcode.DELETE;
            if(_log.isDebugEnabled())
              _log.debug("The event with scn "+ scn +" is DELETE");
          }
          else
          {
            throw new DatabusException("Unknown opcode from dbUpdate for event with scn:" + scn);
          }


          //Construct the dbusEvent info
          DbusEventInfo dbusEventInfo = new DbusEventInfo(opCode,
                                                          scn,
                                                          (short)_pConfig.getId(),
                                                          lPartitionId,
                                                          timestamp,
                                                          sourceId,
                                                          schemaId.getByteArray(),
                                                          serializedValue,
                                                          false,
                                                          false);
          dbusEventInfo.setReplicated(dbUpdate.isReplicated());

          perSourceStats.addEventCycle(1, ti.getTransactionTimeRead(), serializedValue.length, scn);
          globalStats.addEventCycle(1, ti.getTransactionTimeRead(), serializedValue.length, scn);

          long tsEnd = System.currentTimeMillis();
          perSourceStats.addTimeOfLastDBAccess(tsEnd);
          globalStats.addTimeOfLastDBAccess(tsEnd);

          //Append to the event buffer
          getEventBuffer().appendEvent(eventKey, dbusEventInfo, _statsCollector);
          _rc.incrementEventCount();
          dbUpdatesEventsSize += serializedValue.length;
        }
        catch (IOException io)
        {
          perSourceStats.addError();
          globalStats.addEmptyEventCycle();
          _log.error("Cannot create byte stream payload: " + dbUpdates.get(i).getSourceId());
        }
      }
      long endDbUpdatesMs = System.currentTimeMillis();
      long dbUpdatesElapsedTimeMs = endDbUpdatesMs - startDbUpdatesMs;

      // Log Event Summary at logical source level
      EventReaderSummary summary = new EventReaderSummary(sourceId, _monitoredSources.get(sourceId).getSourceName(),
                                                          scn, eventsInDbUpdate, dbUpdatesEventsSize,-1L /* Not supported */,
                                                          dbUpdatesElapsedTimeMs,  timestamp, timestamp, -1L /* Not supported */);
      if (_eventsLog.isInfoEnabled())
      {
        _eventsLog.info(summary.toString());
      }
      summaries.add(summary);

      if(_log.isDebugEnabled())
        _log.debug("There are "+ eventsInDbUpdate + " events seen in the current dbUpdate");
    }

    // Log Event Summary at Physical source level
    ReadEventCycleSummary summary = new ReadEventCycleSummary(_pConfig.getName(),
                                                              summaries,
                                                              scn,
                                                              -1 /* Overall time including query time not calculated */);

    if (_eventsLog.isInfoEnabled())
    {
      _eventsLog.info(summary.toString());
    }

    _log.info("Writing "+ eventsInTransactionCount + " events from transaction with scn: " + scn);
    if(scn <= 0)
      throw new DatabusException("Unable to write events to buffer because of negative/zero scn: " + scn);

    getEventBuffer().endEvents(scn, _statsCollector);
    _scn.set(scn);

    if (getMaxScnReaderWriter() != null)
View Full Code Here

        String xmlPrefix = GGEventGenerationFactory.uriToXmlPrefix(_pConfig.getUri());
        File file = new File(xmlDir);
        if(!file.exists() || !file.isDirectory())
        {
          _log.fatal("Unable to load the directory: "+ xmlDir + " it doesn't seem to be a valid directory");
          throw new DatabusException("Invalid trail file directory");
        }

        boolean parseError = false;
        do
        {
View Full Code Here

          }
        }
        _writer.flush();
      } catch (IOException e) {
        LOG.error("Got Exception :", e);
        throw new DatabusException(e);
      }
      return true;
    }
View Full Code Here

      _registeredMbeans.add(objectName);
    }
    catch(Exception ex)
    {
      _log.error("Failed to register the or-source statistics mbean for source (" + source.getSourceName() + ") due to an exception.", ex);
      throw new DatabusException("Failed to initialize or event statistics mbeans.", ex);
    }
  }
View Full Code Here

    Map<Short, String> srcSchemaVersions = new HashMap<Short, String>();
    srcSchemaVersions.put(docSchemaV1, docSchema1);
    srcSchemaVersions.put(docSchemaV2, docSchema2);

    DatabusException expectedCause = new DatabusException("FakeException");
    SchemaRegistryService mockSchemaReg = EasyMock.createMock(SchemaRegistryService.class);
    EasyMock.expect(mockSchemaReg.fetchAllSchemaVersionsBySourceName(srcName1)).andThrow(expectedCause);
                                                                                         EasyMock.replay(mockSchemaReg);

    HttpRelay mockRelay = EasyMock.createMock(HttpRelay.class);
View Full Code Here

          _maxSCNReaderWriter.saveMaxScn(txn.getScn());
        }
        catch (UnsupportedKeyException e)
        {
          _log.fatal("Got UnsupportedKeyException exception while adding txn (" + txn + ") to the buffer", e);
          throw new DatabusException(e);
        }
        catch (EventCreationException e)
        {
          _log.fatal("Got EventCreationException exception while adding txn (" + txn + ") to the buffer", e);
          throw new DatabusException(e);
        }
      }

      if (isShutdownRequested())
      {
View Full Code Here

TOP

Related Classes of com.linkedin.databus2.core.DatabusException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.