Search in sources :

Example 6 with Lease

use of com.netflix.eureka.lease.Lease in project eureka by Netflix.

the class AbstractInstanceRegistry method getApplication.

/**
     * Get application information.
     *
     * @param appName The name of the application
     * @param includeRemoteRegion true, if we need to include applications from remote regions
     *                            as indicated by the region {@link URL} by this property
     *                            {@link EurekaServerConfig#getRemoteRegionUrls()}, false otherwise
     * @return the application
     */
@Override
public Application getApplication(String appName, boolean includeRemoteRegion) {
    Application app = null;
    Map<String, Lease<InstanceInfo>> leaseMap = registry.get(appName);
    if (leaseMap != null && leaseMap.size() > 0) {
        for (Entry<String, Lease<InstanceInfo>> entry : leaseMap.entrySet()) {
            if (app == null) {
                app = new Application(appName);
            }
            app.addInstance(decorateInstanceInfo(entry.getValue()));
        }
    } else if (includeRemoteRegion) {
        for (RemoteRegionRegistry remoteRegistry : this.regionNameVSRemoteRegistry.values()) {
            Application application = remoteRegistry.getApplication(appName);
            if (application != null) {
                return application;
            }
        }
    }
    return app;
}
Also used : Lease(com.netflix.eureka.lease.Lease) Application(com.netflix.discovery.shared.Application)

Example 7 with Lease

use of com.netflix.eureka.lease.Lease in project eureka by Netflix.

the class AbstractInstanceRegistry method deleteStatusOverride.

/**
     * Removes status override for a give instance.
     *
     * @param appName the application name of the instance.
     * @param id the unique identifier of the instance.
     * @param newStatus the new {@link InstanceStatus}.
     * @param lastDirtyTimestamp last timestamp when this instance information was updated.
     * @param isReplication true if this is a replication event from other nodes, false
     *                      otherwise.
     * @return true if the status was successfully updated, false otherwise.
     */
@Override
public boolean deleteStatusOverride(String appName, String id, InstanceStatus newStatus, String lastDirtyTimestamp, boolean isReplication) {
    try {
        read.lock();
        STATUS_OVERRIDE_DELETE.increment(isReplication);
        Map<String, Lease<InstanceInfo>> gMap = registry.get(appName);
        Lease<InstanceInfo> lease = null;
        if (gMap != null) {
            lease = gMap.get(id);
        }
        if (lease == null) {
            return false;
        } else {
            lease.renew();
            InstanceInfo info = lease.getHolder();
            // This log statement is provided as a safeguard, in case this invariant is violated.
            if (info == null) {
                logger.error("Found Lease without a holder for instance id {}", id);
            }
            InstanceStatus currentOverride = overriddenInstanceStatusMap.remove(id);
            if (currentOverride != null && info != null) {
                info.setOverriddenStatus(InstanceStatus.UNKNOWN);
                info.setStatus(newStatus);
                long replicaDirtyTimestamp = 0;
                if (lastDirtyTimestamp != null) {
                    replicaDirtyTimestamp = Long.valueOf(lastDirtyTimestamp);
                }
                // it to the replica's.
                if (replicaDirtyTimestamp > info.getLastDirtyTimestamp()) {
                    info.setLastDirtyTimestamp(replicaDirtyTimestamp);
                }
                info.setActionType(ActionType.MODIFIED);
                recentlyChangedQueue.add(new RecentlyChangedItem(lease));
                info.setLastUpdatedTimestamp();
                invalidateCache(appName, info.getVIPAddress(), info.getSecureVipAddress());
            }
            return true;
        }
    } finally {
        read.unlock();
    }
}
Also used : Lease(com.netflix.eureka.lease.Lease) InstanceStatus(com.netflix.appinfo.InstanceInfo.InstanceStatus) InstanceInfo(com.netflix.appinfo.InstanceInfo)

Example 8 with Lease

use of com.netflix.eureka.lease.Lease in project eureka by Netflix.

the class AbstractInstanceRegistry method register.

/**
     * Registers a new instance with a given duration.
     *
     * @see com.netflix.eureka.lease.LeaseManager#register(java.lang.Object, int, boolean)
     */
public void register(InstanceInfo registrant, int leaseDuration, boolean isReplication) {
    try {
        read.lock();
        Map<String, Lease<InstanceInfo>> gMap = registry.get(registrant.getAppName());
        REGISTER.increment(isReplication);
        if (gMap == null) {
            final ConcurrentHashMap<String, Lease<InstanceInfo>> gNewMap = new ConcurrentHashMap<String, Lease<InstanceInfo>>();
            gMap = registry.putIfAbsent(registrant.getAppName(), gNewMap);
            if (gMap == null) {
                gMap = gNewMap;
            }
        }
        Lease<InstanceInfo> existingLease = gMap.get(registrant.getId());
        // Retain the last dirty timestamp without overwriting it, if there is already a lease
        if (existingLease != null && (existingLease.getHolder() != null)) {
            Long existingLastDirtyTimestamp = existingLease.getHolder().getLastDirtyTimestamp();
            Long registrationLastDirtyTimestamp = registrant.getLastDirtyTimestamp();
            logger.debug("Existing lease found (existing={}, provided={}", existingLastDirtyTimestamp, registrationLastDirtyTimestamp);
            if (existingLastDirtyTimestamp > registrationLastDirtyTimestamp) {
                logger.warn("There is an existing lease and the existing lease's dirty timestamp {} is greater" + " than the one that is being registered {}", existingLastDirtyTimestamp, registrationLastDirtyTimestamp);
                logger.warn("Using the existing instanceInfo instead of the new instanceInfo as the registrant");
                registrant = existingLease.getHolder();
            }
        } else {
            // The lease does not exist and hence it is a new registration
            synchronized (lock) {
                if (this.expectedNumberOfRenewsPerMin > 0) {
                    // Since the client wants to cancel it, reduce the threshold
                    // (1
                    // for 30 seconds, 2 for a minute)
                    this.expectedNumberOfRenewsPerMin = this.expectedNumberOfRenewsPerMin + 2;
                    this.numberOfRenewsPerMinThreshold = (int) (this.expectedNumberOfRenewsPerMin * serverConfig.getRenewalPercentThreshold());
                }
            }
            logger.debug("No previous lease information found; it is new registration");
        }
        Lease<InstanceInfo> lease = new Lease<InstanceInfo>(registrant, leaseDuration);
        if (existingLease != null) {
            lease.setServiceUpTimestamp(existingLease.getServiceUpTimestamp());
        }
        gMap.put(registrant.getId(), lease);
        synchronized (recentRegisteredQueue) {
            recentRegisteredQueue.add(new Pair<Long, String>(System.currentTimeMillis(), registrant.getAppName() + "(" + registrant.getId() + ")"));
        }
        // This is where the initial state transfer of overridden status happens
        if (!InstanceStatus.UNKNOWN.equals(registrant.getOverriddenStatus())) {
            logger.debug("Found overridden status {} for instance {}. Checking to see if needs to be add to the " + "overrides", registrant.getOverriddenStatus(), registrant.getId());
            if (!overriddenInstanceStatusMap.containsKey(registrant.getId())) {
                logger.info("Not found overridden id {} and hence adding it", registrant.getId());
                overriddenInstanceStatusMap.put(registrant.getId(), registrant.getOverriddenStatus());
            }
        }
        InstanceStatus overriddenStatusFromMap = overriddenInstanceStatusMap.get(registrant.getId());
        if (overriddenStatusFromMap != null) {
            logger.info("Storing overridden status {} from map", overriddenStatusFromMap);
            registrant.setOverriddenStatus(overriddenStatusFromMap);
        }
        // Set the status based on the overridden status rules
        InstanceStatus overriddenInstanceStatus = getOverriddenInstanceStatus(registrant, existingLease, isReplication);
        registrant.setStatusWithoutDirty(overriddenInstanceStatus);
        // If the lease is registered with UP status, set lease service up timestamp
        if (InstanceStatus.UP.equals(registrant.getStatus())) {
            lease.serviceUp();
        }
        registrant.setActionType(ActionType.ADDED);
        recentlyChangedQueue.add(new RecentlyChangedItem(lease));
        registrant.setLastUpdatedTimestamp();
        invalidateCache(registrant.getAppName(), registrant.getVIPAddress(), registrant.getSecureVipAddress());
        logger.info("Registered instance {}/{} with status {} (replication={})", registrant.getAppName(), registrant.getId(), registrant.getStatus(), isReplication);
    } finally {
        read.unlock();
    }
}
Also used : Lease(com.netflix.eureka.lease.Lease) InstanceStatus(com.netflix.appinfo.InstanceInfo.InstanceStatus) AtomicLong(java.util.concurrent.atomic.AtomicLong) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) InstanceInfo(com.netflix.appinfo.InstanceInfo)

Example 9 with Lease

use of com.netflix.eureka.lease.Lease in project eureka by Netflix.

the class AbstractInstanceRegistry method internalCancel.

/**
     * {@link #cancel(String, String, boolean)} method is overridden by {@link PeerAwareInstanceRegistry}, so each
     * cancel request is replicated to the peers. This is however not desired for expires which would be counted
     * in the remote peers as valid cancellations, so self preservation mode would not kick-in.
     */
protected boolean internalCancel(String appName, String id, boolean isReplication) {
    try {
        read.lock();
        CANCEL.increment(isReplication);
        Map<String, Lease<InstanceInfo>> gMap = registry.get(appName);
        Lease<InstanceInfo> leaseToCancel = null;
        if (gMap != null) {
            leaseToCancel = gMap.remove(id);
        }
        synchronized (recentCanceledQueue) {
            recentCanceledQueue.add(new Pair<Long, String>(System.currentTimeMillis(), appName + "(" + id + ")"));
        }
        InstanceStatus instanceStatus = overriddenInstanceStatusMap.remove(id);
        if (instanceStatus != null) {
            logger.debug("Removed instance id {} from the overridden map which has value {}", id, instanceStatus.name());
        }
        if (leaseToCancel == null) {
            CANCEL_NOT_FOUND.increment(isReplication);
            logger.warn("DS: Registry: cancel failed because Lease is not registered for: {}/{}", appName, id);
            return false;
        } else {
            leaseToCancel.cancel();
            InstanceInfo instanceInfo = leaseToCancel.getHolder();
            String vip = null;
            String svip = null;
            if (instanceInfo != null) {
                instanceInfo.setActionType(ActionType.DELETED);
                recentlyChangedQueue.add(new RecentlyChangedItem(leaseToCancel));
                instanceInfo.setLastUpdatedTimestamp();
                vip = instanceInfo.getVIPAddress();
                svip = instanceInfo.getSecureVipAddress();
            }
            invalidateCache(appName, vip, svip);
            logger.info("Cancelled instance {}/{} (replication={})", appName, id, isReplication);
            return true;
        }
    } finally {
        read.unlock();
    }
}
Also used : Lease(com.netflix.eureka.lease.Lease) InstanceStatus(com.netflix.appinfo.InstanceInfo.InstanceStatus) AtomicLong(java.util.concurrent.atomic.AtomicLong) InstanceInfo(com.netflix.appinfo.InstanceInfo)

Example 10 with Lease

use of com.netflix.eureka.lease.Lease in project eureka by Netflix.

the class AbstractInstanceRegistry method getInstancesById.

/**
     * @deprecated Try {@link #getInstanceByAppAndId(String, String, boolean)} instead.
     *
     * Get the list of instances by its unique id.
     *
     * @param id the unique id of the instance
     * @param includeRemoteRegions true, if we need to include applications from remote regions
     *                             as indicated by the region {@link URL} by this property
     *                             {@link EurekaServerConfig#getRemoteRegionUrls()}, false otherwise
     * @return list of InstanceInfo objects.
     */
@Deprecated
public List<InstanceInfo> getInstancesById(String id, boolean includeRemoteRegions) {
    List<InstanceInfo> list = new ArrayList<InstanceInfo>();
    for (Iterator<Entry<String, Map<String, Lease<InstanceInfo>>>> iter = registry.entrySet().iterator(); iter.hasNext(); ) {
        Map<String, Lease<InstanceInfo>> leaseMap = iter.next().getValue();
        if (leaseMap != null) {
            Lease<InstanceInfo> lease = leaseMap.get(id);
            if (lease == null || (isLeaseExpirationEnabled() && lease.isExpired())) {
                continue;
            }
            if (list == Collections.EMPTY_LIST) {
                list = new ArrayList<InstanceInfo>();
            }
            list.add(decorateInstanceInfo(lease));
        }
    }
    if (list.isEmpty() && includeRemoteRegions) {
        for (RemoteRegionRegistry remoteRegistry : this.regionNameVSRemoteRegistry.values()) {
            for (Application application : remoteRegistry.getApplications().getRegisteredApplications()) {
                InstanceInfo instanceInfo = application.getByInstanceId(id);
                if (instanceInfo != null) {
                    list.add(instanceInfo);
                    return list;
                }
            }
        }
    }
    return list;
}
Also used : Entry(java.util.Map.Entry) Lease(com.netflix.eureka.lease.Lease) ArrayList(java.util.ArrayList) InstanceInfo(com.netflix.appinfo.InstanceInfo) Application(com.netflix.discovery.shared.Application)

Aggregations

Lease (com.netflix.eureka.lease.Lease)10 InstanceInfo (com.netflix.appinfo.InstanceInfo)9 InstanceStatus (com.netflix.appinfo.InstanceInfo.InstanceStatus)4 Application (com.netflix.discovery.shared.Application)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ConcurrentMap (java.util.concurrent.ConcurrentMap)3 Applications (com.netflix.discovery.shared.Applications)2 ArrayList (java.util.ArrayList)2 AtomicLong (java.util.concurrent.atomic.AtomicLong)2 Entry (java.util.Map.Entry)1 Random (java.util.Random)1