Package com.netflix.servo.monitor

Examples of com.netflix.servo.monitor.Stopwatch


   
    @GET
    @Path("/v1/logs/{key}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getLogs(final @PathParam("key") String key) {
      Stopwatch stopwatch = statsTimer.start();
      try {
          // increment request counter
          requestCounter.increment();
                     
            List<String> logs = store.getLogs(key);
           
            logger.debug("retrieved key={} logs={}", key, logs);
           
            return Response.ok(gson.toJson(logs)).build();           
        } catch (Exception ex) {
          // increment error counter
          errorCounter.increment();

            logger.error("Error processing the get request.", ex);
           
            return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build();
        } finally {
            stopwatch.stop();
           
            statsTimer.record(stopwatch.getDuration(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
        }
    }
View Full Code Here


   
    @POST
    @Path("/v1/log/{key}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response addLog(final @PathParam("key") String key, final @QueryParam("log") String log) {   
      Stopwatch stopwatch = statsTimer.start();
      try {
          // increment request counter
          requestCounter.increment();
         
          String decodedLog = URLDecoder.decode(log, Charsets.UTF_8.name());
                     
            long timestamp = store.addLog(key, decodedLog);
           
            logger.debug("added key={} log={} timestamp={}", key, decodedLog, timestamp);
           
            // return response
            return Response.ok(gson.toJson(String.valueOf(timestamp))).build();           
        } catch (Exception ex) {
          // increment error counter
          errorCounter.increment();

            logger.error("Error processing the add request.", ex);
           
            return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build();
        } finally {
            stopwatch.stop();
           
            statsTimer.record(stopwatch.getDuration(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
        }
    }
View Full Code Here

                }
            }

            @Override
            public void run() {
                Stopwatch start = executionTimeStats.start();
                try {
                    apacheHttpClient
                    .getClientHandler()
                    .getHttpClient()
                    .getConnectionManager()
                    .closeIdleConnections(connectionIdleTimeout, TimeUnit.SECONDS);
                } catch (Throwable e) {
                    s_logger.error("Cannot clean connections", e);
                    cleanupFailed.increment();
                } finally {
                    if (null != start) {
                        start.stop();
                    }
                }

            }
View Full Code Here

     * Fetch the registry information from the remote region.
     * @return true, if the fetch was successful, false otherwise.
     */
    private boolean fetchRegistry() {
        ClientResponse response = null;
        Stopwatch tracer = fetchRegistryTimer.start();

        try {
            // If the delta is disabled or if it is the first time, get all
            // applications
            if (EUREKA_SERVER_CONFIG.shouldDisableDeltaForRemoteRegions()
                    || (getApplications() == null)
                    || (getApplications().getRegisteredApplications().size() == 0)) {
                logger.info("Disable delta property : {}", EUREKA_SERVER_CONFIG
                        .shouldDisableDeltaForRemoteRegions());
                logger.info("Application is null : {}",
                        (getApplications() == null));
                logger.info(
                        "Registered Applications size is zero : {}",
                        (getApplications().getRegisteredApplications().size() == 0));
                response = storeFullRegistry();
            } else {
                Applications delta = null;
                response = fetchRemoteRegistry(true);
                if (null != response) {
                    if (response.getStatus() == Status.OK.getStatusCode()) {
                        delta = response.getEntity(Applications.class);
                        this.applicationsDelta.set(delta);
                    }
                    if (delta == null) {
                        logger.warn("The server does not allow the delta revision to be applied because it is not "
                                + "safe. Hence got the full registry.");
                        this.closeResponse(response);
                        response = fetchRemoteRegistry(true);
                    } else {
                        updateDelta(delta);
                        String reconcileHashCode = getApplications()
                                .getReconcileHashCode();
                        // There is a diff in number of instances for some reason
                        if ((!reconcileHashCode.equals(delta.getAppsHashCode()))) {
                            response = reconcileAndLogDifference(response, delta, reconcileHashCode);

                        }
                    }
                }
            }
            logTotalInstances();

            logger.debug("Remote Registry Fetch Status : {}", null == response ? null : response.getStatus());
        } catch (Throwable e) {
            logger.error(
                    "Unable to fetch registry information from the remote registry "
                            + this.remoteRegionURL.toString(), e);
            return false;

        } finally {
            if (tracer != null) {
                tracer.stop();
            }
            closeResponse(response);
        }
        return null != response;
    }
View Full Code Here

     *         otherwise.
     */
    private Boolean isASGEnabledinAWS(Object key) {
        String myKey = (String) key;
        try {
            Stopwatch t = this.loadASGInfoTimer.start();
            boolean returnValue = !isAddToLoadBalancerSuspended(myKey);
            t.stop();
            return returnValue;
        } catch (Throwable e) {
            logger.error("Could not get ASG information from AWS: ", e);
        }
        return Boolean.TRUE;
View Full Code Here

    /*
     * Generate pay load for the given key.
     */
    private Value generatePayload(Key key) {
        Stopwatch tracer = null;
        InstanceRegistry registry = PeerAwareInstanceRegistry.getInstance();
        try {
            String payload;
            switch (key.getEntityType()) {
                case Application:
                    boolean isRemoteRegionRequested = key.hasRegions();

                    if (ALL_APPS.equals(key.getName())) {
                        if (isRemoteRegionRequested) {
                            tracer = serializeAllAppsWithRemoteRegionTimer.start();
                            payload = getPayLoad(key, registry.getApplicationsFromMultipleRegions(key.getRegions()));
                        } else {
                            tracer = serializeAllAppsTimer.start();
                            payload = getPayLoad(key, registry.getApplications());
                        }
                    } else if (ALL_APPS_DELTA.equals(key.getName())) {
                        if (isRemoteRegionRequested) {
                            tracer = serializeDeltaAppsWithRemoteRegionTimer.start();
                            versionDeltaWithRegions.incrementAndGet();
                            payload = getPayLoad(key,
                                    registry.getApplicationDeltasFromMultipleRegions(key.getRegions()));
                        } else {
                            tracer = serializeDeltaAppsTimer.start();
                            versionDelta.incrementAndGet();
                            payload = getPayLoad(key, registry.getApplicationDeltas());
                        }
                    } else {
                        tracer = serializeOneApptimer.start();
                        payload = getPayLoad(key, registry.getApplication(key.getName()));
                    }
                    break;
                case VIP:
                case SVIP:
                    tracer = serializeViptimer.start();
                    payload = getPayLoad(key, getApplicationsForVip(key, registry));
                    break;
                default:
                    logger.error("Unidentified entity type: " + key.getEntityType() + " found in the cache key.");
                    payload = "";
                    break;
            }
            return new Value(payload);
        } finally {
            if (tracer != null) {
                tracer.stop();
            }
        }
    }
View Full Code Here

        private byte[] gzipped;

        public Value(String payload) {
            this.payload = payload;
            if (payload != EMPTY_PAYLOAD) {
                Stopwatch tracer = compressPayloadTimer.start();
                try {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    GZIPOutputStream out = new GZIPOutputStream(bos);
                    byte[] rawBytes = payload.getBytes();
                    out.write(rawBytes);
                    // Finish creation of gzip file
                    out.finish();
                    out.close();
                    bos.close();
                    gzipped = bos.toByteArray();
                } catch (IOException e) {
                    gzipped = null;
                } finally {
                    if (tracer != null) {
                        tracer.stop();
                    }
                }
            } else {
                gzipped = null;
            }
View Full Code Here

     *
     */
    private void replicateToPeers(Action action, String appName, String id,
            InstanceInfo info /* optional */,
            InstanceStatus newStatus /* optional */, boolean isReplication) {
        Stopwatch tracer = action.getTimer().start();
        try {

            if (isReplication) {
                numberOfReplicationsLastMin.increment();
            }
            // If it is a replication already, do not replicate again as this
            // will create a poison replication
            if (peerEurekaNodes == Collections.EMPTY_LIST || isReplication) {
                return;
            }

            for (final PeerEurekaNode node : peerEurekaNodes.get()) {
                // If the url represents this host, do not replicate
                // to yourself.
                if (isThisMe(node.getServiceUrl())) {
                    continue;
                }
                replicateInstanceActionsToPeers(action, appName, id, info,
                        newStatus, node);
            }
        } finally {
            tracer.stop();
        }
    }
View Full Code Here

     *
     * @return true if the registry was fetched
     */
    private boolean fetchRegistry(boolean forceFullRegistryFetch) {
        ClientResponse response = null;
        Stopwatch tracer = FETCH_REGISTRY_TIMER.start();

        try {
            // If the delta is disabled or if it is the first time, get all
            // applications
            Applications applications = getApplications();

            if (clientConfig.shouldDisableDelta()
                || (!Strings.isNullOrEmpty(clientConfig.getRegistryRefreshSingleVipAddress()))
                || forceFullRegistryFetch
                || (applications == null)
                || (applications.getRegisteredApplications().size() == 0)
                || (applications.getVersion() == -1)) //Client application does not have latest library supporting delta
            {
                logger.info("Disable delta property : {}", clientConfig.shouldDisableDelta());
                logger.info("Single vip registry refresh property : {}", clientConfig.getRegistryRefreshSingleVipAddress());
                logger.info("Force full registry fetch : {}", forceFullRegistryFetch);
                logger.info("Application is null : {}", (applications == null));
                logger.info("Registered Applications size is zero : {}",
                        (applications.getRegisteredApplications().size() == 0));
                logger.info("Application version is -1: {}", (applications.getVersion() == -1));
                response = getAndStoreFullRegistry();
            } else {
                response = getAndUpdateDelta(applications);
            }
            applications.setAppsHashCode(applications.getReconcileHashCode());
            logTotalInstances();

            logger.debug(PREFIX + appPathIdentifier + " -  refresh status: "
                    + response.getStatus());

            updateInstanceRemoteStatus();

        } catch (Throwable e) {
            logger.error(
                    PREFIX + appPathIdentifier
                            + " - was unable to refresh its cache! status = "
                            + e.getMessage(), e);
            return false;
        } finally {
            if (tracer != null) {
                tracer.stop();
            }
            closeResponse(response);
        }
        return true;
    }
View Full Code Here

     *             on any error.
     */
    private ClientResponse makeRemoteCall(Action action, int serviceUrlIndex)
            throws Throwable {
        String urlPath = null;
        Stopwatch tracer = null;
        String serviceUrl = eurekaServiceUrls.get().get(serviceUrlIndex);
        ClientResponse response = null;
        logger.debug("Discovery Client talking to the server {}", serviceUrl);
        try {
            // If the application is unknown do not register/renew/cancel but
            // refresh
            if ((UNKNOWN.equals(instanceInfo.getAppName())
                    && (!Action.Refresh.equals(action)) && (!Action.Refresh_Delta
                    .equals(action)))) {
                return null;
            }
            WebResource r = discoveryApacheClient.resource(serviceUrl);
            String remoteRegionsToFetchStr;
            switch (action) {
            case Renew:
                tracer = RENEW_TIMER.start();
                urlPath = "apps/" + appPathIdentifier;
                response = r
                        .path(urlPath)
                        .queryParam("status",
                                instanceInfo.getStatus().toString())
                        .queryParam("lastDirtyTimestamp",
                                instanceInfo.getLastDirtyTimestamp().toString())
                        .put(ClientResponse.class);
                break;
            case Refresh:
                tracer = REFRESH_TIMER.start();
                final String vipAddress = clientConfig.getRegistryRefreshSingleVipAddress();
                urlPath = vipAddress == null ? "apps/" : "vips/" + vipAddress;
                remoteRegionsToFetchStr = remoteRegionsToFetch.get();
                if (!Strings.isNullOrEmpty(remoteRegionsToFetchStr)) {
                    urlPath += "?regions=" + remoteRegionsToFetchStr;
                }
                response = getUrl(serviceUrl + urlPath);
                break;
            case Refresh_Delta:
                tracer = REFRESH_DELTA_TIMER.start();
                urlPath = "apps/delta";
                remoteRegionsToFetchStr = remoteRegionsToFetch.get();
                if (!Strings.isNullOrEmpty(remoteRegionsToFetchStr)) {
                    urlPath += "?regions=" + remoteRegionsToFetchStr;
                }
                response = getUrl(serviceUrl + urlPath);
                break;
            case Register:
                tracer = REGISTER_TIMER.start();
                urlPath = "apps/" + instanceInfo.getAppName();
                response = r.path(urlPath)
                        .type(MediaType.APPLICATION_JSON_TYPE)
                        .post(ClientResponse.class, instanceInfo);
                break;
            case Cancel:
                tracer = CANCEL_TIMER.start();
                urlPath = "apps/" + appPathIdentifier;
                response = r.path(urlPath).delete(ClientResponse.class);
                // Return without during de-registration if it is not registered
                // already and if we get a 404
                if ((!isRegisteredWithDiscovery)
                        && (response.getStatus() == Status.NOT_FOUND
                                .getStatusCode())) {
                    return response;
                }
                break;
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Finished a call to service url {} and url path {} with status code {}.",
                            new String[] {serviceUrl, urlPath, String.valueOf(response.getStatus())});
            }
            if (isOk(action, response.getStatus())) {
                return response;
            } else {
                logger.warn("Action: " + action + "  => returned status of "
                        + response.getStatus() + " from " + serviceUrl
                        + urlPath);
                throw new RuntimeException("Bad status: "
                        + response.getStatus());
            }
        } catch (Throwable t) {
            closeResponse(response);
            String msg = "Can't get a response from " + serviceUrl + urlPath;
            if (eurekaServiceUrls.get().size() > (++serviceUrlIndex)) {
                logger.warn(msg, t);
                logger.warn("Trying backup: "
                        + eurekaServiceUrls.get().get(serviceUrlIndex));
                SERVER_RETRY_COUNTER.increment();
                return makeRemoteCall(action, serviceUrlIndex);
            } else {
                ALL_SERVER_FAILURE_COUNT.increment();
                logger.error(
                        msg
                                + "\nCan't contact any eureka nodes - possibly a security group issue?",
                        t);
                throw t;
            }
        } finally {
            if (tracer != null) {
                tracer.stop();
            }
        }
    }
View Full Code Here

TOP

Related Classes of com.netflix.servo.monitor.Stopwatch

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.