@Override protected void awaitResultAsync(final RemoteInvocationOptions optionsCopy, final RemotePromise<Object> result, final RemoteServiceRequest request, final String responseName) { if (!optionsCopy.isResultExpected()) { return; } Long startTime = 0L; if (request != null && request.getArgs() != null && request.getArgs().length > 3) { startTime = (Long)request.getArgs()[3]; } long delay = startTime - System.currentTimeMillis(); if (delay > 0) { commandExecutor.getConnectionManager().newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { ScheduledTasksService.super.awaitResultAsync(optionsCopy, result, request, responseName); } }, delay, TimeUnit.MILLISECONDS); } else { super.awaitResultAsync(optionsCopy, result, request, responseName); } }
private synchronized void scheduleReconnect() { if (_stop) return; if (_timeout != null) return; Constants.ahessianLogger.warn("channel closed wait to reconnect ..."); _retryCounter++; long retryIntervall = Math.min(RECONNECT_DELAY * _retryCounter, MAX_RECONNECT_DELAY); _timeout = _timer.newTimeout(new TimerTask() { public void run(Timeout timeout) throws Exception { _timeout = null; connect(_bootstrap.getBootstrap()); } }, retryIntervall, TimeUnit.MILLISECONDS); }
public HeartbeatHandlerInbound(final String name, final Timer timer, final long timeout) { _name = name; final TimerTask task = new TimerTask() { public void run(Timeout nTimeout) throws Exception { if (((getLastCalled() + timeout) <= System.currentTimeMillis()) && isConnected()) try { _action.timedOut(_ctx); } catch (Exception e) { Constants.ahessianLogger.warn("", e); } } }; _intervalTimer = new IntervalTimer(timer, task, timeout); }
public T poll(int group) { LinkedList<T> q = _queues[group]; T result = null; if (q != null) { result = q.poll(); if (result != null) { Timeout timer = _timers.remove(result); if (timer != null) timer.cancel(); } } return result; }
@Override public void run(Timeout timeout) throws Exception { Connection connection = this.connection; if (connection == null || !connection.isConnected()) { Logs.HB.info("heartbeat timeout times={}, connection disconnected, conn={}", timeoutTimes, connection); return; } if (connection.isReadTimeout()) { if (++timeoutTimes > CC.mp.core.max_hb_timeout_times) { connection.close(); Logs.HB.warn("client heartbeat timeout times={}, do close conn={}", timeoutTimes, connection); return; } else { Logs.HB.info("client heartbeat timeout times={}, connection={}", timeoutTimes, connection); } } else { timeoutTimes = 0; } startTimeout(); }
@Override public void run(Timeout timeout) throws Exception { if (timeout.isCancelled()) { return; } if (log.isDebugEnabled()) { log.debug("[{}] [{}] Batching the messages from the batch container from timer thread", topic, producerName); } // semaphore acquired when message was enqueued to container synchronized (ProducerImpl.this) { batchMessageAndSend(); } // schedule the next batch message task client.timer().newTimeout(this, conf.getBatchingMaxPublishDelayMs(), TimeUnit.MILLISECONDS); }
public void start(PulsarClientImpl client, ConsumerBase consumerBase, long ackTimeoutMillis) { this.stop(); timeout = client.timer().newTimeout(new TimerTask() { @Override public void run(Timeout t) throws Exception { if (isAckTimeout()) { log.warn("[{}] {} messages have timed-out", consumerBase, oldOpenSet.size()); Set<MessageIdImpl> messageIds = new HashSet<>(); oldOpenSet.forEach(messageIds::add); oldOpenSet.clear(); consumerBase.redeliverUnacknowledgedMessages(messageIds); } toggle(); timeout = client.timer().newTimeout(this, ackTimeoutMillis, TimeUnit.MILLISECONDS); } }, ackTimeoutMillis, TimeUnit.MILLISECONDS); }
/** * {@inheritDoc} * @see io.netty.util.Timer#newTimeout(io.netty.util.TimerTask, long, java.util.concurrent.TimeUnit) */ @Override public Timeout newTimeout(final TimerTask task, final long delay, final TimeUnit unit) { final WrappedTimeout[] t = new WrappedTimeout[1]; t[0] = new WrappedTimeout(timer.newTimeout(new TimerTask(){ @Override public void run(final Timeout timeout) throws Exception { try { task.run(t[0]); } finally { pendingTimeouts.decrementAndGet(); timeouts.increment(); } } }, delay, unit)); return t[0]; }
private void scheduleRequestTimeout(RequestHeader requestHeader) { UInteger requestHandle = requestHeader.getRequestHandle(); long timeoutHint = requestHeader.getTimeoutHint() != null ? requestHeader.getTimeoutHint().longValue() : DEFAULT_TIMEOUT_MS; Timeout timeout = wheelTimer.newTimeout(t -> { if (timeouts.remove(requestHandle) != null && !t.isCancelled()) { CompletableFuture<UaResponseMessage> f = pending.remove(requestHandle); if (f != null) { String message = "request timed out after " + timeoutHint + "ms"; f.completeExceptionally(new UaException(StatusCodes.Bad_Timeout, message)); } } }, timeoutHint, TimeUnit.MILLISECONDS); timeouts.put(requestHandle, timeout); }
@Override public void run(Timeout timeout) throws Exception { log.debug("Timeout occured for Session {}", id); //Notify the listener that timeout has occured final SessionValue session = sessionManager.getSession(id); //Do not proceed if the session is null if (session == null) { log.error("could not find session value for id {}. Registry Size : {}", id, sessionManager.getSessionEntries().size()); return; } //Check first if the promise has been completed if (session.getClientPromise() != null && !session.getClientPromise().isDone() && !session.getClientPromise().isCancelled() && !timeout.isCancelled()) { //Send a ReadTimeoutException to the client session.getClientPromise().completeExceptionally(new ReadTimeoutException(id, String.format("Timeout occured for '%s' Started: %f seconds ago", id, ((double) Duration.ofMillis(System.currentTimeMillis() - session.getTimeRegistered()).toMillis() / 1000.0)))); } }
/** * Intentional private local constructor * @param key the request key * @param request the request object * @param window the window * @param timeoutMillis the time after which this future will be cancelled * @param timer the timer used to implement the timeout functionality */ private TimedDeferredRequest(final K key, final R request, final Window<K, R, D> window, final Timer timer, final long timeoutMillis) { super(key, request, window); this.timeout = checkNotNull(timer).newTimeout(new TimerTask() { @Override public void run(Timeout timerTask) throws Exception { window.fail(checkNotNull(key), new TimeoutException("The operation timed out (Window full)")); } }, timeoutMillis, TimeUnit.MILLISECONDS); }
private void newRefreshTask() { if (refreshTaskMap.containsKey(getName())) { return; } Timeout task = commandExecutor.getConnectionManager().newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { expire(internalLockLeaseTime, TimeUnit.MILLISECONDS); refreshTaskMap.remove(getName()); newRefreshTask(); // reschedule itself } }, internalLockLeaseTime / 3, TimeUnit.MILLISECONDS); if (refreshTaskMap.putIfAbsent(getName(), task) != null) { task.cancel(); } }
@Override public void itemsReceived(CpfItem[] items) { int connectionId = ((ConnectedAddressItem) items[0]).getConnectionId(); ByteBuf buffer = ((ConnectedDataItemResponse) items[1]).getData(); int sequenceNumber = buffer.readShort(); ByteBuf data = buffer.readSlice(buffer.readableBytes()).retain(); Timeout timeout = timeouts.remove(sequenceNumber); if (timeout != null) timeout.cancel(); CompletableFuture<ByteBuf> future = pending.remove(sequenceNumber); if (future != null) { future.complete(data); } else { ReferenceCountUtil.release(data); } ReferenceCountUtil.release(buffer); }
@SuppressWarnings("unchecked") private PendingRequest(CompletableFuture<T> future, Timeout timeout) { this.timeout = timeout; promise.whenComplete((r, ex) -> { if (r != null) { try { future.complete((T) r); } catch (ClassCastException e) { future.completeExceptionally(e); } } else { future.completeExceptionally(ex); } }); }
/** * {@inheritDoc} * <br/> * Sends for each remote participant a report containing the status * of this session participant. */ @Override public void run(Timeout timeout) throws Exception { if (!this.running.get()) { return; } // send status update per remote participant final long currentSsrc = this.localParticipant.getSsrc(); final SourceDescriptionPacket sdesPacket = buildSdesPacket(currentSsrc); this.participantDatabase.doWithReceivers(new ParticipantOperation() { @Override public void doWithParticipant(RtpParticipant participant) throws Exception { AbstractReportPacket report = buildReportPacket(currentSsrc, participant); // TODO: really to all other participants? // i would use: // writeToControl(new CompoundControlPacket(report, sdesPacket), participant.getControlDestination()); internalSendControl(new CompoundControlPacket(report, sdesPacket)); } }); if (!this.running.get()) { return; } this.timer.newTimeout(this, this.updatePeriodicRtcpSendInterval(), TimeUnit.SECONDS); }
@SuppressWarnings("unchecked") private PendingRequest(CompletableFuture<T> future, Timeout timeout, Timer.Context context) { this.timeout = timeout; this.context = context; promise.whenComplete((r, ex) -> { if (r != null) { try { future.complete((T) r); } catch (ClassCastException e) { future.completeExceptionally(e); } } else { future.completeExceptionally(ex); } }); }
private void startRedelegationTimer(final PCCTunnel tunnel, final PlspId plspId, final PCCSession session) { final Timeout newRedelegationTimeout = this.timer.newTimeout(timeout -> { //remove delegation PCCTunnelManagerImpl.this.setDelegation(plspId, null); //delegate to another PCE int index = session.getId(); for (int i = 1; i < PCCTunnelManagerImpl.this.sessions.size(); i++) { index++; if (index == PCCTunnelManagerImpl.this.sessions.size()) { index = 0; } final PCCSession nextSession = PCCTunnelManagerImpl.this.sessions.get(index); if (nextSession != null) { tunnel.cancelTimeouts(); final Tlvs tlvs = buildTlvs(tunnel, plspId.getValue(), Optional.absent()); nextSession.sendReport(createPcRtpMessage( createLsp(plspId.getValue(), true, Optional.fromNullable(tlvs), true, false), NO_SRP, tunnel.getLspState())); tunnel.setDelegationHolder(nextSession.getId()); break; } } }, this.redelegationTimeout, TimeUnit.SECONDS); tunnel.setRedelegationTimeout(newRedelegationTimeout); }
public void fireNext(final ChannelHandlerContext ctx, final long delay) { final Event readyForNext = new Event(currentConversationId); if(delay > timerTickSize) { timer.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) { if(logger.isDebugEnabled()) { logger.debug("running after delay: {}", delay); } if(readyForNext.conversationId != currentConversationId) { logger.debug("pending 'next' event found obsolete, aborting"); return; } ctx.pipeline().fireChannelRead(readyForNext); } }, delay, TimeUnit.MILLISECONDS); } else { ctx.pipeline().fireChannelRead(readyForNext); } }
@Override public void run(Timeout timeout) throws Exception { if (!sw.isConnected()) { log.debug("Switch {} disconnected. Aborting meter stats collection", sw.getStringId()); return; } log.trace("Collecting stats for {}", sw.getStringId()); sendMeterStatisticRequest(); if (!this.stopTimer) { log.trace("Scheduling stats collection in {} seconds for {}", this.refreshInterval, this.sw.getStringId()); timeout.timer().newTimeout(this, refreshInterval, TimeUnit.SECONDS); } }
/** * Execute this method every t milliseconds. Loops over all ports * labeled as fast and sends out an LLDP. Send out an LLDP on a single slow * port. * * @param t timeout */ @Override public void run(Timeout t) { if (isStopped()) { return; } if (context.mastershipService().isLocalMaster(device.id())) { log.trace("Sending probes from {}", device.id()); ports.forEach(this::sendProbes); } if (!isStopped()) { timeout = t.timer().newTimeout(this, context.probeRate(), MILLISECONDS); } }
private void scheduleRequestTimeout(RequestHeader requestHeader) { UInteger requestHandle = requestHeader.getRequestHandle(); long timeoutHint = requestHeader.getTimeoutHint() != null ? requestHeader.getTimeoutHint().longValue() : DEFAULT_TIMEOUT_MS; Timeout timeout = wheelTimer.newTimeout(t -> { timeouts.remove(requestHandle); if (!t.isCancelled()) { CompletableFuture<UaResponseMessage> f = pending.remove(requestHandle); if (f != null) { String message = "request timed out after " + timeoutHint + "ms"; f.completeExceptionally(new UaException(StatusCodes.Bad_Timeout, message)); } } }, timeoutHint, TimeUnit.MILLISECONDS); timeouts.put(requestHandle, timeout); }
@Override public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { try { return timer.newTimeout(task, delay, unit); } catch (IllegalStateException e) { // timer is shutdown return dummyTimeout; } }
private void applyResponseTimeout(CompletableFuture<List<SmtpResponse>> responseFuture, Optional<Duration> responseTimeout, Supplier<String> debugStringSupplier) { responseTimeout = responseTimeout.isPresent() ? responseTimeout : defaultResponseTimeout; responseTimeout.ifPresent(timeout -> { Timeout hwtTimeout = TIMER.newTimeout(ignored -> { String message = String.format("[%s] Timed out waiting for a response to [%s]", connectionId, debugStringSupplier.get()); responseFuture.completeExceptionally(new TimeoutException(message)); }, timeout.toMillis(), TimeUnit.MILLISECONDS); responseFuture.whenComplete((ignored1, ignored2) -> hwtTimeout.cancel()); }); }
@Override public void run(Timeout timeout) throws Exception { if (timeout.isCancelled()) { return; } if (!ctx.channel().isOpen()) { return; } if (!handler.isClientConnection && ((handler.remoteNode == null || !handler.rpcService.isConnected(handler.remoteNode. getNodeId())))) ctx.fireExceptionCaught(EXCEPTION); }
@Override public void run(Timeout timeout) throws Exception { if (timeout.isCancelled()) { return; } if (!ctx.channel().isOpen()) { return; } ctx.channel().disconnect(); }
@Override public void run(Timeout timeout) throws Exception { if (timeout.isCancelled()) { return; } if (!ctx.channel().isOpen()) { return; } if (channelHandler.syncManager.ready == false) ctx.channel().disconnect(); }
@Override public void run(Timeout timeout) throws Exception { if (!timeout.isCancelled()) { log.warn("App handshake plugin for {} timed out. Returning result {}.", sw, defaultResult); exitPlugin(defaultResult); } }
@Override public void run(Timeout timeout) throws Exception { Deliverable<?> removed = xidDeliverableMap.remove(xid); if (removed != null && !removed.isDone()) { removed.deliverError(new TimeoutException( "timeout - did not receive answer for xid " + xid)); } }
@Override public void run(Timeout timeout) throws Exception { if (timeout.isCancelled()) { return; } if (!ctx.channel().isOpen()) { return; } if (!handshakeHandler.isSwitchHandshakeComplete()) ctx.fireExceptionCaught(EXCEPTION); }
@Before public void setUp() throws Exception { /* * This needs to be called explicitly to ensure the featuresReply is not null. * Otherwise, there is no guarantee @Before will for setUpFeaturesReply() will * call that function before our @Before setUp() here. */ setUpFeaturesReply(); switchManager = createMock(IOFSwitchManager.class); roleManager = createMock(RoleManager.class); sw = createMock(IOFSwitchBackend.class); timer = createMock(Timer.class); expect(timer.newTimeout(anyObject(TimerTask.class), anyLong(), anyObject(TimeUnit.class))).andReturn(EasyMock.createNiceMock(Timeout.class)); replay(timer); seenXids = null; // TODO: should mock IDebugCounterService and make sure // the expected counters are updated. debugCounterService = new DebugCounterServiceImpl(); SwitchManagerCounters counters = new SwitchManagerCounters(debugCounterService); expect(switchManager.getCounters()).andReturn(counters).anyTimes(); replay(switchManager); connection = new MockOFConnection(featuresReply.getDatapathId(), OFAuxId.MAIN); switchHandler = new OFSwitchHandshakeHandler(connection, featuresReply, switchManager, roleManager, timer); // replay sw. Reset it if you need more specific behavior replay(sw); }
/** * Get SASL handler * @param bootstrap to reconnect to * @return new SASL handler * @throws java.io.IOException if handler failed to create */ private SaslClientHandler getSaslHandler(final UserGroupInformation realTicket, final Bootstrap bootstrap) throws IOException { return new SaslClientHandler(realTicket, authMethod, token, serverPrincipal, client.fallbackAllowed, client.conf.get("hbase.rpc.protection", SaslUtil.QualityOfProtection.AUTHENTICATION.name().toLowerCase()), new SaslClientHandler.SaslExceptionHandler() { @Override public void handle(int retryCount, Random random, Throwable cause) { try { // Handle Sasl failure. Try to potentially get new credentials handleSaslConnectionFailure(retryCount, cause, realTicket); // Try to reconnect client.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { connect(bootstrap); } }, random.nextInt(reloginMaxBackoff) + 1, TimeUnit.MILLISECONDS); } catch (IOException | InterruptedException e) { close(e); } } }, new SaslClientHandler.SaslSuccessfulConnectHandler() { @Override public void onSuccess(Channel channel) { startHBaseConnection(channel); } }); }
/** * Retry to connect or close * * @param bootstrap to connect with * @param connectCounter amount of tries * @param e exception of fail */ private void retryOrClose(final Bootstrap bootstrap, int connectCounter, Throwable e) { if (connectCounter < client.maxRetries) { client.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { connect(bootstrap); } }, client.failureSleep, TimeUnit.MILLISECONDS); } else { client.failedServers.addToFailedServers(address); close(e); } }
public void stop() { _stop = true; Timeout timeout = _timeout; _timeout = null; timeout.cancel(); }