Search in sources :

Example 1 with TimerTask

use of org.jboss.netty.util.TimerTask in project pinpoint by naver.

the class PinpointServerAcceptor method sendPing.

private void sendPing() {
    logger.debug("sendPing");
    final TimerTask pintTask = new TimerTask() {

        @Override
        public void run(Timeout timeout) throws Exception {
            if (timeout.isCancelled()) {
                newPingTimeout(this);
                return;
            }
            final ChannelGroupFuture write = channelGroup.write(PingPacket.PING_PACKET);
            if (logger.isWarnEnabled()) {
                write.addListener(new ChannelGroupFutureListener() {

                    private final ChannelFutureListener listener = new WriteFailFutureListener(logger, "ping write fail", "ping write success");

                    @Override
                    public void operationComplete(ChannelGroupFuture future) throws Exception {
                        if (logger.isWarnEnabled()) {
                            for (ChannelFuture channelFuture : future) {
                                channelFuture.addListener(listener);
                            }
                        }
                    }
                });
            }
            newPingTimeout(this);
        }
    };
    newPingTimeout(pintTask);
}
Also used : TimerTask(org.jboss.netty.util.TimerTask) Timeout(org.jboss.netty.util.Timeout) ChannelGroupFuture(org.jboss.netty.channel.group.ChannelGroupFuture) ChannelGroupFutureListener(org.jboss.netty.channel.group.ChannelGroupFutureListener) WriteFailFutureListener(com.navercorp.pinpoint.rpc.client.WriteFailFutureListener) PinpointSocketException(com.navercorp.pinpoint.rpc.PinpointSocketException)

Example 2 with TimerTask

use of org.jboss.netty.util.TimerTask in project pinpoint by naver.

the class ZookeeperClient method reconnectWhenSessionExpired.

public void reconnectWhenSessionExpired() {
    if (!stateContext.isStarted()) {
        logger.warn("ZookeeperClient.reconnectWhenSessionExpired() failed. Error: Already closed.");
        return;
    }
    ZooKeeper zookeeper = this.zookeeper;
    if (zookeeper.getState().isConnected()) {
        logger.warn("ZookeeperClient.reconnectWhenSessionExpired() failed. Error: session(0x{}) is connected.", Long.toHexString(zookeeper.getSessionId()));
        return;
    }
    logger.warn("Execute ZookeeperClient.reconnectWhenSessionExpired()(Expired session:0x{}).", Long.toHexString(zookeeper.getSessionId()));
    try {
        zookeeper.close();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    ZooKeeper newZookeeper = createNewZookeeper();
    if (newZookeeper == null) {
        logger.warn("Failed to create new Zookeeper instance. It will be retry  AFTER {}ms.", reconnectDelayWhenSessionExpired);
        timer.newTimeout(new TimerTask() {

            @Override
            public void run(Timeout timeout) throws Exception {
                if (timeout.isCancelled()) {
                    return;
                }
                reconnectWhenSessionExpired();
            }
        }, reconnectDelayWhenSessionExpired, TimeUnit.MILLISECONDS);
    } else {
        this.zookeeper = newZookeeper;
    }
}
Also used : ZooKeeper(org.apache.zookeeper.ZooKeeper) TimerTask(org.jboss.netty.util.TimerTask) Timeout(org.jboss.netty.util.Timeout) NoNodeException(com.navercorp.pinpoint.web.cluster.zookeeper.exception.NoNodeException) TimeoutException(com.navercorp.pinpoint.web.cluster.zookeeper.exception.TimeoutException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) AuthException(com.navercorp.pinpoint.web.cluster.zookeeper.exception.AuthException) BadOperationException(com.navercorp.pinpoint.web.cluster.zookeeper.exception.BadOperationException) ConnectionException(com.navercorp.pinpoint.web.cluster.zookeeper.exception.ConnectionException) PinpointZookeeperException(com.navercorp.pinpoint.web.cluster.zookeeper.exception.PinpointZookeeperException) UnknownException(com.navercorp.pinpoint.web.cluster.zookeeper.exception.UnknownException)

Example 3 with TimerTask

use of org.jboss.netty.util.TimerTask in project distributedlog by twitter.

the class StreamImpl method scheduleTimeout.

void scheduleTimeout(final StreamOp op) {
    final Timeout timeout = requestTimer.newTimeout(new TimerTask() {

        @Override
        public void run(Timeout timeout) throws Exception {
            if (!timeout.isCancelled()) {
                serviceTimeout.inc();
                handleServiceTimeout("Operation " + op.getClass().getName() + " timeout");
            }
        }
    }, serviceTimeoutMs, TimeUnit.MILLISECONDS);
    op.responseHeader().ensure(new Function0<BoxedUnit>() {

        @Override
        public BoxedUnit apply() {
            timeout.cancel();
            return null;
        }
    });
}
Also used : TimerTask(org.jboss.netty.util.TimerTask) Timeout(org.jboss.netty.util.Timeout) BoxedUnit(scala.runtime.BoxedUnit) AlreadyClosedException(com.twitter.distributedlog.exceptions.AlreadyClosedException) UnexpectedException(com.twitter.distributedlog.exceptions.UnexpectedException) OverCapacityException(com.twitter.distributedlog.exceptions.OverCapacityException) DLException(com.twitter.distributedlog.exceptions.DLException) StreamNotReadyException(com.twitter.distributedlog.exceptions.StreamNotReadyException) StreamUnavailableException(com.twitter.distributedlog.exceptions.StreamUnavailableException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) InvalidStreamNameException(com.twitter.distributedlog.exceptions.InvalidStreamNameException) IOException(java.io.IOException) OwnershipAcquireFailedException(com.twitter.distributedlog.exceptions.OwnershipAcquireFailedException)

Example 4 with TimerTask

use of org.jboss.netty.util.TimerTask in project opentsdb by OpenTSDB.

the class PutDataPointRpc method execute.

/**
   * Handles HTTP RPC put requests
   * @param tsdb The TSDB to which we belong
   * @param query The HTTP query from the user
   * @throws IOException if there is an error parsing the query or formatting 
   * the output
   * @throws BadRequestException if the user supplied bad data
   * @since 2.0
   */
public void execute(final TSDB tsdb, final HttpQuery query) throws IOException {
    requests.incrementAndGet();
    // only accept POST
    if (query.method() != HttpMethod.POST) {
        throw new BadRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED, "Method not allowed", "The HTTP method [" + query.method().getName() + "] is not permitted for this endpoint");
    }
    final List<IncomingDataPoint> dps = query.serializer().parsePutV1();
    if (dps.size() < 1) {
        throw new BadRequestException("No datapoints found in content");
    }
    final boolean show_details = query.hasQueryStringParam("details");
    final boolean show_summary = query.hasQueryStringParam("summary");
    final boolean synchronous = query.hasQueryStringParam("sync");
    final int sync_timeout = query.hasQueryStringParam("sync_timeout") ? Integer.parseInt(query.getQueryStringParam("sync_timeout")) : 0;
    // this is used to coordinate timeouts
    final AtomicBoolean sending_response = new AtomicBoolean();
    sending_response.set(false);
    final ArrayList<HashMap<String, Object>> details = show_details ? new ArrayList<HashMap<String, Object>>() : null;
    int queued = 0;
    final List<Deferred<Boolean>> deferreds = synchronous ? new ArrayList<Deferred<Boolean>>(dps.size()) : null;
    for (final IncomingDataPoint dp : dps) {
        /** Handles passing a data point to the storage exception handler if 
       * we were unable to store it for any reason */
        final class PutErrback implements Callback<Boolean, Exception> {

            public Boolean call(final Exception arg) {
                handleStorageException(tsdb, dp, arg);
                hbase_errors.incrementAndGet();
                if (show_details) {
                    details.add(getHttpDetails("Storage exception: " + arg.getMessage(), dp));
                }
                return false;
            }

            public String toString() {
                return "HTTP Put Exception CB";
            }
        }
        /** Simply marks the put as successful */
        final class SuccessCB implements Callback<Boolean, Object> {

            @Override
            public Boolean call(final Object obj) {
                return true;
            }

            public String toString() {
                return "HTTP Put success CB";
            }
        }
        try {
            if (dp.getMetric() == null || dp.getMetric().isEmpty()) {
                if (show_details) {
                    details.add(this.getHttpDetails("Metric name was empty", dp));
                }
                LOG.warn("Metric name was empty: " + dp);
                illegal_arguments.incrementAndGet();
                continue;
            }
            if (dp.getTimestamp() <= 0) {
                if (show_details) {
                    details.add(this.getHttpDetails("Invalid timestamp", dp));
                }
                LOG.warn("Invalid timestamp: " + dp);
                illegal_arguments.incrementAndGet();
                continue;
            }
            if (dp.getValue() == null || dp.getValue().isEmpty()) {
                if (show_details) {
                    details.add(this.getHttpDetails("Empty value", dp));
                }
                LOG.warn("Empty value: " + dp);
                invalid_values.incrementAndGet();
                continue;
            }
            if (dp.getTags() == null || dp.getTags().size() < 1) {
                if (show_details) {
                    details.add(this.getHttpDetails("Missing tags", dp));
                }
                LOG.warn("Missing tags: " + dp);
                illegal_arguments.incrementAndGet();
                continue;
            }
            final Deferred<Object> deferred;
            if (Tags.looksLikeInteger(dp.getValue())) {
                deferred = tsdb.addPoint(dp.getMetric(), dp.getTimestamp(), Tags.parseLong(dp.getValue()), dp.getTags());
            } else {
                deferred = tsdb.addPoint(dp.getMetric(), dp.getTimestamp(), Float.parseFloat(dp.getValue()), dp.getTags());
            }
            if (synchronous) {
                deferreds.add(deferred.addCallback(new SuccessCB()));
            }
            deferred.addErrback(new PutErrback());
            ++queued;
        } catch (NumberFormatException x) {
            if (show_details) {
                details.add(this.getHttpDetails("Unable to parse value to a number", dp));
            }
            LOG.warn("Unable to parse value to a number: " + dp);
            invalid_values.incrementAndGet();
        } catch (IllegalArgumentException iae) {
            if (show_details) {
                details.add(this.getHttpDetails(iae.getMessage(), dp));
            }
            LOG.warn(iae.getMessage() + ": " + dp);
            illegal_arguments.incrementAndGet();
        } catch (NoSuchUniqueName nsu) {
            if (show_details) {
                details.add(this.getHttpDetails("Unknown metric", dp));
            }
            LOG.warn("Unknown metric: " + dp);
            unknown_metrics.incrementAndGet();
        }
    }
    /** A timer task that will respond to the user with the number of timeouts
     * for synchronous writes. */
    class PutTimeout implements TimerTask {

        final int queued;

        public PutTimeout(final int queued) {
            this.queued = queued;
        }

        @Override
        public void run(final Timeout timeout) throws Exception {
            if (sending_response.get()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Put data point call " + query + " already responded successfully");
                }
                return;
            } else {
                sending_response.set(true);
            }
            // figure out how many writes are outstanding
            int good_writes = 0;
            int failed_writes = 0;
            int timeouts = 0;
            for (int i = 0; i < deferreds.size(); i++) {
                try {
                    if (deferreds.get(i).join(1)) {
                        ++good_writes;
                    } else {
                        ++failed_writes;
                    }
                } catch (TimeoutException te) {
                    if (show_details) {
                        details.add(getHttpDetails("Write timedout", dps.get(i)));
                    }
                    ++timeouts;
                }
            }
            writes_timedout.addAndGet(timeouts);
            final int failures = dps.size() - queued;
            if (!show_summary && !show_details) {
                throw new BadRequestException(HttpResponseStatus.BAD_REQUEST, "The put call has timedout with " + good_writes + " successful writes, " + failed_writes + " failed writes and " + timeouts + " timed out writes.", "Please see the TSD logs or append \"details\" to the put request");
            } else {
                final HashMap<String, Object> summary = new HashMap<String, Object>();
                summary.put("success", good_writes);
                summary.put("failed", failures + failed_writes);
                summary.put("timeouts", timeouts);
                if (show_details) {
                    summary.put("errors", details);
                }
                query.sendReply(HttpResponseStatus.BAD_REQUEST, query.serializer().formatPutV1(summary));
            }
        }
    }
    // now after everything has been sent we can schedule a timeout if so
    // the caller asked for a synchronous write.
    final Timeout timeout = sync_timeout > 0 ? tsdb.getTimer().newTimeout(new PutTimeout(queued), sync_timeout, TimeUnit.MILLISECONDS) : null;
    /** Serializes the response to the client */
    class GroupCB implements Callback<Object, ArrayList<Boolean>> {

        final int queued;

        public GroupCB(final int queued) {
            this.queued = queued;
        }

        @Override
        public Object call(final ArrayList<Boolean> results) {
            if (sending_response.get()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Put data point call " + query + " was marked as timedout");
                }
                return null;
            } else {
                sending_response.set(true);
                if (timeout != null) {
                    timeout.cancel();
                }
            }
            int good_writes = 0;
            int failed_writes = 0;
            for (final boolean result : results) {
                if (result) {
                    ++good_writes;
                } else {
                    ++failed_writes;
                }
            }
            final int failures = dps.size() - queued;
            if (!show_summary && !show_details) {
                if (failures + failed_writes > 0) {
                    query.sendReply(HttpResponseStatus.BAD_REQUEST, query.serializer().formatErrorV1(new BadRequestException(HttpResponseStatus.BAD_REQUEST, "One or more data points had errors", "Please see the TSD logs or append \"details\" to the put request")));
                } else {
                    query.sendReply(HttpResponseStatus.NO_CONTENT, "".getBytes());
                }
            } else {
                final HashMap<String, Object> summary = new HashMap<String, Object>();
                if (sync_timeout > 0) {
                    summary.put("timeouts", 0);
                }
                summary.put("success", results.isEmpty() ? queued : good_writes);
                summary.put("failed", failures + failed_writes);
                if (show_details) {
                    summary.put("errors", details);
                }
                if (failures > 0) {
                    query.sendReply(HttpResponseStatus.BAD_REQUEST, query.serializer().formatPutV1(summary));
                } else {
                    query.sendReply(query.serializer().formatPutV1(summary));
                }
            }
            return null;
        }

        @Override
        public String toString() {
            return "put data point serialization callback";
        }
    }
    /** Catches any unexpected exceptions thrown in the callback chain */
    class ErrCB implements Callback<Object, Exception> {

        @Override
        public Object call(final Exception e) throws Exception {
            if (sending_response.get()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Put data point call " + query + " was marked as timedout");
                }
                return null;
            } else {
                sending_response.set(true);
                if (timeout != null) {
                    timeout.cancel();
                }
            }
            LOG.error("Unexpected exception", e);
            throw new RuntimeException("Unexpected exception", e);
        }

        @Override
        public String toString() {
            return "put data point error callback";
        }
    }
    if (synchronous) {
        Deferred.groupInOrder(deferreds).addCallback(new GroupCB(queued)).addErrback(new ErrCB());
    } else {
        new GroupCB(queued).call(EMPTY_DEFERREDS);
    }
}
Also used : HashMap(java.util.HashMap) Deferred(com.stumbleupon.async.Deferred) ArrayList(java.util.ArrayList) TimerTask(org.jboss.netty.util.TimerTask) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TimeoutException(com.stumbleupon.async.TimeoutException) Timeout(org.jboss.netty.util.Timeout) IncomingDataPoint(net.opentsdb.core.IncomingDataPoint) IncomingDataPoint(net.opentsdb.core.IncomingDataPoint) IOException(java.io.IOException) TimeoutException(com.stumbleupon.async.TimeoutException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callback(com.stumbleupon.async.Callback) NoSuchUniqueName(net.opentsdb.uid.NoSuchUniqueName)

Example 5 with TimerTask

use of org.jboss.netty.util.TimerTask in project pinpoint by naver.

the class DefaultZookeeperClient method reconnectWhenSessionExpired.

@Override
public void reconnectWhenSessionExpired() {
    if (!stateContext.isStarted()) {
        logger.warn("ZookeeperClient.reconnectWhenSessionExpired() failed. Error: Already closed.");
        return;
    }
    ZooKeeper zookeeper = this.zookeeper;
    if (zookeeper.getState().isConnected()) {
        logger.warn("ZookeeperClient.reconnect() failed. Error: session(0x{}) is connected.", Long.toHexString(zookeeper.getSessionId()));
        return;
    }
    logger.warn("Execute ZookeeperClient.reconnectWhenSessionExpired()(Expired session:0x{}).", Long.toHexString(zookeeper.getSessionId()));
    try {
        zookeeper.close();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    ZooKeeper newZookeeper = createNewZookeeper();
    if (!stateContext.isStarted()) {
        logger.warn("ZookeeperClient.reconnectWhenSessionExpired() failed. Error: Already closed.");
        return;
    }
    if (newZookeeper == null) {
        logger.warn("Failed to create new Zookeeper instance. It will be retry  AFTER {}ms.", reconnectDelayWhenSessionExpired);
        timer.newTimeout(new TimerTask() {

            @Override
            public void run(Timeout timeout) throws Exception {
                if (timeout.isCancelled()) {
                    return;
                }
                reconnectWhenSessionExpired();
            }
        }, reconnectDelayWhenSessionExpired, TimeUnit.MILLISECONDS);
    } else {
        this.zookeeper = newZookeeper;
    }
}
Also used : ZooKeeper(org.apache.zookeeper.ZooKeeper) TimerTask(org.jboss.netty.util.TimerTask) Timeout(org.jboss.netty.util.Timeout) AuthException(com.navercorp.pinpoint.collector.cluster.zookeeper.exception.AuthException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) UnknownException(com.navercorp.pinpoint.collector.cluster.zookeeper.exception.UnknownException) TimeoutException(com.navercorp.pinpoint.collector.cluster.zookeeper.exception.TimeoutException) ConnectionException(com.navercorp.pinpoint.collector.cluster.zookeeper.exception.ConnectionException) PinpointZookeeperException(com.navercorp.pinpoint.collector.cluster.zookeeper.exception.PinpointZookeeperException) BadOperationException(com.navercorp.pinpoint.collector.cluster.zookeeper.exception.BadOperationException) NoNodeException(com.navercorp.pinpoint.collector.cluster.zookeeper.exception.NoNodeException)

Aggregations

Timeout (org.jboss.netty.util.Timeout)7 TimerTask (org.jboss.netty.util.TimerTask)7 IOException (java.io.IOException)4 HashMap (java.util.HashMap)3 SQLException (java.sql.SQLException)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 KeeperException (org.apache.zookeeper.KeeperException)2 ZooKeeper (org.apache.zookeeper.ZooKeeper)2 Device (org.traccar.model.Device)2 Event (org.traccar.model.Event)2 Position (org.traccar.model.Position)2 AuthException (com.navercorp.pinpoint.collector.cluster.zookeeper.exception.AuthException)1 BadOperationException (com.navercorp.pinpoint.collector.cluster.zookeeper.exception.BadOperationException)1 ConnectionException (com.navercorp.pinpoint.collector.cluster.zookeeper.exception.ConnectionException)1 NoNodeException (com.navercorp.pinpoint.collector.cluster.zookeeper.exception.NoNodeException)1 PinpointZookeeperException (com.navercorp.pinpoint.collector.cluster.zookeeper.exception.PinpointZookeeperException)1 TimeoutException (com.navercorp.pinpoint.collector.cluster.zookeeper.exception.TimeoutException)1 UnknownException (com.navercorp.pinpoint.collector.cluster.zookeeper.exception.UnknownException)1 PinpointSocketException (com.navercorp.pinpoint.rpc.PinpointSocketException)1 WriteFailFutureListener (com.navercorp.pinpoint.rpc.client.WriteFailFutureListener)1