@Override
 public int compareTo(QueueEntry another) {
   if (systemTimeMilliseconds == another.getSystemTimeMilliseconds()) {
     // if time is the same we want to the save original order from config
     return Integer.valueOf(orderIdx).compareTo(another.orderIdx);
   }
   return Long.valueOf(systemTimeMilliseconds).compareTo(another.getSystemTimeMilliseconds());
 }
 private long getSleepTimeDurationMilliseconds() {
   if (entries.isEmpty()) {
     return TimeUtils.daysToMillis(SKConstants.TEST_QUEUE_NORMAL_SIZE_IN_DAYS);
   } else {
     QueueEntry entry = entries.peek();
     long value = entry.getSystemTimeMilliseconds() - System.currentTimeMillis();
     return value;
   }
 }
Exemplo n.º 3
0
  @Override
  public boolean remove(Object o) {
    T t = cast(o);
    QueueEntry<T> entry = findEntry(t);
    if (entry == null) return false;
    QueueEntry<T> prev = entry.prev;
    QueueEntry<T> next = entry.next;

    prev.next = next;
    next.prev = prev;

    set.remove(entry);
    return true;
  }
  public boolean mightAssign(final QueueEntry entry, QueueConsumer sub) {
    Object groupVal = entry.getMessage().getMessageHeader().getHeader(_groupId);

    if (groupVal == null) {
      return true;
    } else {
      QueueConsumer assignedSub = _groupMap.get(groupVal.hashCode() & _groupMask);
      return assignedSub == null || assignedSub == sub;
    }
  }
    public boolean visit(final QueueEntry entry) {
      if (!entry.isAvailable()) {
        return false;
      }

      Object groupId = entry.getMessage().getMessageHeader().getHeader(_groupId);
      if (groupId == null) {
        return false;
      }

      Integer group = groupId.hashCode() & _groupMask;
      QueueConsumer<?> assignedSub = _groupMap.get(group);
      if (assignedSub == _sub) {
        _entry = entry;
        return true;
      } else {
        return false;
      }
    }
 public int enqueue(int messageNo, IMessage message, MessageFuture future) throws IOException {
   QueueEntry qe = new QueueEntry();
   qe.messageNo = messageNo;
   qe.score = computeMessageScore(messageNo, message);
   qe.messageClass = message.getClass();
   qe.messageStream = messenger.serializeMessage(message);
   qe.future = future;
   if (LogUtil.isLogAvailable()) {
     // precompute the expected queue size...this is because the writer thread may quickly pick
     // up the queue item which, while swell, means the debug output may be confusing
     int newExpectedQueueSize = queue.size() + 1;
     Log.i(
         TAG,
         "Message "
             + qe.messageNo
             + " enqueued, it's a "
             + qe.messageClass.getSimpleName()
             + ", "
             + qe.messageStream.available()
             + " bytes in length, "
             + newExpectedQueueSize
             + " entries in the queue");
   }
   queue.add(qe);
   return qe.messageNo;
 }
 private void processCanceled() throws IOException {
   Set<Integer> canceled = new HashSet<Integer>();
   synchronized (queueLock) {
     canceled.addAll(this.canceled);
     this.canceled.clear();
   }
   for (int messageNo : canceled) {
     QueueEntry found = removeQueueEntry(messageNo);
     if (found != null) {
       if (LogUtil.isLogAvailable()) {
         Log.d(TAG, "Message " + messageNo + " canceled");
       }
       PacketFormat cancelPacket = new PacketFormat(messageNo, new byte[0]);
       cancelPacket.addControlCode(ControlCode.Cancelled);
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       cancelPacket.serialize(baos);
       found.messageStream = new ByteArrayInputStream(baos.toByteArray());
       found.score = messageNo * CANCEL_TRANSFER_SCORE_MULTIPLIER;
       queue.add(found);
     }
   }
 }
  private static <C extends Command<R>, R extends Serializable> void executeCommand(
      CommandExecutor<C, R> executor,
      ZNode executorNode,
      final QueueEntry<C, R> entry,
      final NodeContext nodeContext) {
    String relativePath = entry.getResultPath().substring(executorNode.getPath().length() + 1);
    final ZNode output = executorNode.child(relativePath);
    final NodeCommandExecutionListener<C> listener = entry.getListener();

    try {
      C command = entry.getCommand();
      listener.onCommandExecutionStarted(command, nodeContext);
      R result = executor.execute(command, nodeContext);
      log.debug("Command {} executed", command);
      listener.onCommandExecuted(command);
      output.setObject(CommandExecutionResult.success(result));
    } catch (Throwable throwable) {
      // todo add fail event
      log.error("error during task execution", throwable);
      output.setObject(CommandExecutionResult.fail(throwable));
    }
  }
  // The queue is populated with all events for a given day.
  // The events in the queue are run through, until all are processed.
  public boolean canExecute(QueueEntry entry, long time) {
    long timeUntilEntry = Math.abs(entry.getSystemTimeMilliseconds() - time);
    long timeWindow = SK2AppSettings.getSK2AppSettingsInstance().getTestStartWindow();
    if (timeWindow == 60000) {
      if (timeUntilEntry < timeWindow) {
        return true;
      }
    }
    timeWindow /= 2;
    if (timeUntilEntry < timeWindow) {
      return true;
    }

    // This allows us to override the value in the debugger...
    return false;
  }
Exemplo n.º 10
0
  public final boolean hasInterest(QueueEntry entry) {
    // check that the message hasn't been rejected
    if (entry.isRejectedBy(this)) {

      return false;
    }

    if (entry.getMessage().getClass() == _messageClass) {
      if (_noLocal) {
        Object connectionRef = entry.getMessage().getConnectionReference();
        if (connectionRef != null && connectionRef == _sessionReference) {
          return false;
        }
      }
    } else {
      // no interest in messages we can't convert
      if (_messageClass != null
          && MessageConverterRegistry.getConverter(entry.getMessage().getClass(), _messageClass)
              == null) {
        return false;
      }
    }

    if (_filters == null) {
      return true;
    } else {
      MessageReference ref = entry.newMessageReference();
      if (ref != null) {
        try {

          Filterable msg = entry.asFilterable();
          try {
            return _filters.allAllow(msg);
          } catch (SelectorParsingException e) {
            LOGGER.info(
                this
                    + " could not evaluate filter ["
                    + _filters
                    + "]  against message "
                    + msg
                    + ". Error was : "
                    + e.getMessage());
            return false;
          }
        } finally {
          ref.release();
        }
      } else {
        return false;
      }
    }
  }
Exemplo n.º 11
0
  @Override
  public boolean add(@NotNull T t) {
    QueueEntry<T> newLast = new QueueEntry<T>(t);
    boolean added = set.add(newLast);
    if (!added) return false;
    QueueEntry<T> oldLast = TOMB.prev;

    oldLast.next = newLast;
    newLast.prev = oldLast;
    newLast.next = TOMB;
    TOMB.prev = newLast;

    return true;
  }
 private boolean assignMessage(QueueConsumer<?> sub, QueueEntry entry) {
   Object groupVal = entry.getMessage().getMessageHeader().getHeader(_groupId);
   if (groupVal == null) {
     return true;
   } else {
     Integer group = groupVal.hashCode() & _groupMask;
     QueueConsumer assignedSub = _groupMap.get(group);
     if (assignedSub == sub) {
       return true;
     } else {
       if (assignedSub == null) {
         _logger.debug("Assigning group {} to sub {}", groupVal, sub);
         assignedSub = _groupMap.putIfAbsent(group, sub);
         return assignedSub == null || assignedSub == sub;
       } else {
         return false;
       }
     }
   }
 }
Exemplo n.º 13
0
 public HashSetQueue() {
   TOMB.next = TOMB.prev = TOMB;
 }
 public boolean acceptMessage(QueueConsumer<?> sub, QueueEntry entry) {
   return assignMessage(sub, entry) && entry.acquire(sub);
 }
  /** @return reschedule time duration in milliseconds */
  public long executeReturnRescheduleDurationMilliseconds() {

    // TODO - is the following assertion something that should be re-activated?
    // SKLogger.sAssert(getClass(), (accumulatedTestBytes == 0L));

    TestExecutor scheduledTestExecutor = new TestExecutor(tc);
    long time = System.currentTimeMillis();

    // The events in the queue are run through, until all are processed.
    // So, we must start by clearing-out all tests that pre-date the current time.
    while (true) {
      QueueEntry entry = entries.peek();
      if (entry != null && !canExecute(entry, time) && entry.getSystemTimeMilliseconds() < time) {
        entries.remove();
        SKLogger.d(this, "removing test scheduled at: " + entry.getSystemTimeAsDebugString());
      } else {
        break;
      }
    }

    boolean result = true;
    boolean fail = false;
    if (canExecute(time)) {
      scheduledTestExecutor.start();

      while (canExecute(time)) {
        QueueEntry entry = entries.remove();
        long maximumTestUsage = tc.config == null ? 0 : tc.config.maximumTestUsage;
        // if data cap is going to be breached do not run test
        // the datacap condition is successful if the datacap is not reached

        boolean dataCapLikelyToBeReachedFlag =
            SK2AppSettings.getSK2AppSettingsInstance().isDataCapLikelyToBeReached(maximumTestUsage);
        // If we're not going to reach the limit, then success is true.
        // If we're going to reach the limit, then success is false.
        boolean dataCapSuccessFlag = !dataCapLikelyToBeReachedFlag;
        DatacapCondition dc = new DatacapCondition(dataCapSuccessFlag);

        if (dc.isSuccess()) {
          ConditionGroupResult tr = scheduledTestExecutor.executeBackgroundTestGroup(entry.groupId);
          accumulatedTestBytes += scheduledTestExecutor.getAccumulatedTestBytes();
          result = tr.isSuccess;
        } else {
          SKLogger.d(this, "Active metrics won't be collected due to potential datacap breach");
          scheduledTestExecutor
              .getResultsContainer()
              .addFailedCondition(DatacapCondition.JSON_DATACAP);
        }
        scheduledTestExecutor.getResultsContainer().addCondition(dc.getCondition());
      }

      scheduledTestExecutor.stop();
      scheduledTestExecutor.save("scheduled_tests", -1);
    }

    extendSize();

    if (fail) {
      RetryFailAction failAction = tc.config.retryFailAction;
      if (failAction != null) {
        return tc.config.retryFailAction.delay; // reschedule
      } else {
        SKLogger.e(this, "can't find on test fail action, just skipping the test.");
        entries.remove();
      }
    }

    return getSleepTimeDurationMilliseconds();
  }
Exemplo n.º 16
0
 public boolean wouldSuspend(final QueueEntry msg) {
   return !_target.allocateCredit(msg.getMessage());
 }
Exemplo n.º 17
0
 public void restoreCredit(final QueueEntry queueEntry) {
   _target.restoreCredit(queueEntry.getMessage());
 }