diff --git a/eureka-client/runservice.sh b/eureka-client/runservice.sh deleted file mode 100755 index 06eb5e296..000000000 --- a/eureka-client/runservice.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash -#Copy all libraries -TEST_CLASSPATH= -for i in testlibs/WEB-INF/lib/* -do - if [ "$TEST_CLASSPATH" = "" ] ; then - TEST_CLASSPATH=$i - fi - TEST_CLASSPATH=$TEST_CLASSPATH:$i -done -TEST_CLASSPATH=$TEST_CLASSPATH:build/classes/main:conf/sampleservice - -echo CLASSPATH:$TEST_CLASSPATH -java -Deureka.region=default -Deureka.environment=test -Deureka.client.props=sample-eureka-service -cp $TEST_CLASSPATH com.netflix.eureka.SampleEurekaService - diff --git a/eureka-core/src/main/java/com/netflix/discovery/CurrentRequestVersion.java b/eureka-core/src/main/java/com/netflix/discovery/CurrentRequestVersion.java deleted file mode 100644 index 37a814b3d..000000000 --- a/eureka-core/src/main/java/com/netflix/discovery/CurrentRequestVersion.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2012 Netflix, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.netflix.discovery; - - -/** - * A thread-scoped value that holds the "current {@link Version}" for the - * request. - * - *
This is not intended as a general mechanism for passing data. - * Rather it is here to support those cases where someplace deep in - * a library we need to know about the context of the request that - * initially triggered the current request.
- * - * @author Karthik Ranganathan, Greg Kim - */ -public final class CurrentRequestVersion { - - private static final ThreadLocal- * The information required for configuring eureka server is provided in a - * configuration file.The configuration file is searched for in the classpath - * with the name specified by the property eureka.server.props and with - * the suffix .properties. If the property is not specified, - * eureka-server.properties is assumed as the default.The properties - * that are looked up uses the namespace passed on to this class. - *
- * - *
- * If the eureka.environment property is specified, additionally
- * eureka-server-
- * The eureka server is configured by using the configuration - * {@link EurekaServerConfig} specified by eureka.server.props in the - * classpath.The eureka client component is also initialized by using the - * configuration {@link EurekaInstanceConfig} specified by - * eureka.client.props. If the server runs in the AWS cloud, the eurea - * server binds it to the elastic ip as specified. - *
- * - * @author Karthik Ranganathan, Greg Kim - * - */ -public class EurekaBootStrap implements ServletContextListener { - private static final String TEST = "test"; - - private static final String ARCHAIUS_DEPLOYMENT_ENVIRONMENT = "archaius.deployment.environment"; - - private static final String EUREKA_ENVIRONMENT = "eureka.environment"; - - private static final String CLOUD = "cloud"; - - private static final String ARCHAIUS_DEPLOYMENT_DATACENTER = "archaius.deployment.datacenter"; - - private static final String EUREKA_DATACENTER = "eureka.datacenter"; - - private static final Logger logger = LoggerFactory - .getLogger(EurekaBootStrap.class); - - private static final int EIP_BIND_SLEEP_TIME_MS = 1000; - private static final Timer timer = new Timer("Eureka-EIPBinder", true); - - /* - * (non-Javadoc) - * - * @see - * javax.servlet.ServletContextListener#contextInitialized(javax.servlet - * .ServletContextEvent) - */ - public void contextInitialized(ServletContextEvent event) { - try { - initEurekaEnvironment(); - - // For backward compatibility - JsonXStream.getInstance().registerConverter( - new V1AwareInstanceInfoConverter(), - XStream.PRIORITY_VERY_HIGH); - XmlXStream.getInstance().registerConverter( - new V1AwareInstanceInfoConverter(), - XStream.PRIORITY_VERY_HIGH); - InstanceInfo info = ApplicationInfoManager.getInstance().getInfo(); - - PeerAwareInstanceRegistry registry = PeerAwareInstanceRegistry - .getInstance(); - - // Copy registry from neighboring eureka node - registry.syncUp(); - - // Only in AWS, enable the binding functionality - if (Name.Amazon.equals(info.getDataCenterInfo().getName())) { - handleEIPbinding(); - } - // Register all monitoring statistics. - EurekaMonitors.registerAllStats(); - - for (PeerEurekaNode node : registry.getReplicaNodes()) { - logger.info("Replica node URL: " + node.getServiceUrl()); - } - - } catch (Throwable e) { - throw new RuntimeException("Cannot bootstrap eureka server :", e); - } - } - - /** - * Users can override to initialize the environment themselves. - */ - protected void initEurekaEnvironment() { - logger.info("Setting the eureka configuration.."); - EurekaServerConfig eurekaServerConfig = new DefaultEurekaServerConfig(); - EurekaServerConfigurationManager.getInstance().setConfiguration( - eurekaServerConfig); - - String dataCenter = ConfigurationManager.getConfigInstance() - .getString(EUREKA_DATACENTER); - if (dataCenter == null) { - logger.info("Eureka data center value eureka.datacenter is not set, defaulting to cloud"); - ConfigurationManager.getConfigInstance().setProperty( - ARCHAIUS_DEPLOYMENT_DATACENTER, CLOUD); - } else { - ConfigurationManager.getConfigInstance().setProperty( - ARCHAIUS_DEPLOYMENT_DATACENTER, dataCenter); - } - String environment = ConfigurationManager.getConfigInstance() - .getString(EUREKA_ENVIRONMENT); - if (environment == null) { - ConfigurationManager.getConfigInstance().setProperty( - ARCHAIUS_DEPLOYMENT_ENVIRONMENT, TEST); - logger.info("Eureka environment value eureka.environment is not set, defaulting to test"); - } - EurekaInstanceConfig config; - if (CLOUD.equals(ConfigurationManager.getDeploymentContext() - .getDeploymentDatacenter())) { - config = new CloudInstanceConfig(); - } else { - config = new MyDataCenterInstanceConfig(); - } - logger.info("Initializing the eureka client..."); - - DiscoveryManager.getInstance().initComponent(config, - new DefaultEurekaClientConfig()); - } - - /* - * (non-Javadoc) - * - * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet. - * ServletContextEvent) - */ - public void contextDestroyed(ServletContextEvent event) { - try { - logger.info(new Date().toString() - + " Shutting down Discovery service..."); - InstanceInfo info = ApplicationInfoManager.getInstance().getInfo(); - // Unregister all MBeans associated w/ DSCounters - EurekaMonitors.shutdown(); - for (int i = 0; i < EurekaServerConfigurationManager.getInstance() - .getConfiguration().getEIPBindRebindRetries(); i++) { - try { - if (Name.Amazon.equals(info.getDataCenterInfo().getName())) { - EIPManager.getInstance().unbindEIP(); - } - break; - } catch (Throwable e) { - logger.warn("Cannot unbind the EIP from the instance"); - Thread.sleep(1000); - continue; - } - } - PeerAwareInstanceRegistry.getInstance().shutdown(); - destoryEurekaEnvironment(); - - } catch (Throwable e) { - logger.error("Error shutting down eureka", e); - } - logger.info(new Date().toString() - + " Eureka Service is now shutdown..."); - } - - /** - * Users can override to clean up the environment themselves. - */ - protected void destoryEurekaEnvironment() { - - } - - /** - * Handles EIP binding process in AWS Cloud. - * - * @throws InterruptedException - */ - private void handleEIPbinding() - throws InterruptedException { - EurekaServerConfig eurekaServerConfig = EurekaServerConfigurationManager.getInstance().getConfiguration(); - int retries = eurekaServerConfig.getEIPBindRebindRetries(); - // Bind to EIP if needed - for (int i = 0; i < retries; i++) { - if (bindEIP()) { - break; - } - } - // Schedule a timer which periodically checks for EIP binding. - scheduleEIPBindTask(eurekaServerConfig); - } - - /** - * Schedules a EIP binding timer task which constantly polls for EIP in the - * same zone and binds it to itself.If the EIP is taken away for some - * reason, this task tries to get the EIP back. Hence it is advised to take - * one EIP assignment per instance in a zone. - * - * @param eurekaServerConfig - * the Eureka Server Configuration. - */ - private void scheduleEIPBindTask( - EurekaServerConfig eurekaServerConfig) { - timer.schedule(new TimerTask() { - - @Override - public void run() { - try { - bindEIP(); - } catch (Throwable ignore) { - - } - } - }, eurekaServerConfig.getEIPBindingRetryIntervalMs(), - eurekaServerConfig.getEIPBindingRetryIntervalMs()); - } - - /** - * Binds the EIP if it is not already bound. - * - * @return - * @throws InterruptedException - */ - private boolean bindEIP() throws InterruptedException { - try { - EIPManager.getInstance().bindToEIP(); - return true; - } catch (Throwable e) { - logger.error("Cannot bind to EIP", e); - Thread.sleep(EIP_BIND_SLEEP_TIME_MS); - return false; - } - } - -} diff --git a/eureka-core/src/main/java/com/netflix/discovery/EurekaServerConfig.java b/eureka-core/src/main/java/com/netflix/discovery/EurekaServerConfig.java deleted file mode 100644 index 5a1542156..000000000 --- a/eureka-core/src/main/java/com/netflix/discovery/EurekaServerConfig.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - * Copyright 2012 Netflix, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.netflix.discovery; - -import com.netflix.appinfo.InstanceInfo.InstanceStatus; - -/** - * Configuration information required by the eureka server to operate. - * - *- * Most of the required information is provided by the default configuration - * {@link DefaultServerConfig}. - * - * Note that all configurations are not effective at runtime unless and - * otherwise specified. - *
- * - * @author Karthik Ranganathan - * - */ -public interface EurekaServerConfig { - - /** - * Gets the AWS Access Id. This is primarily used for - * Elastic IP Biding. The access id should be provided with - * appropriate AWS permissions to bind the EIP. - * - * @return - */ - String getAWSAccessId(); - - /** - * Gets the AWS Secret Key. This is primarily used for - * Elastic IP Biding. The access id should be provided with - * appropriate AWS permissions to bind the EIP. - * - * @return - */ - String getAWSSecretKey(); - - /** - * Gets the number of times the server should try to bind to the candidate - * EIP. - * - * @return the number of times the server should try to bind to the - * candidate EIP. - */ - int getEIPBindRebindRetries(); - - /** - * Gets the interval with which the server should check if the EIP is bound - * and should try to bind in the case if it is already not bound. - * - * @return the time in milliseconds. - */ - int getEIPBindingRetryIntervalMs(); - - /** - * Checks to see if the eureka server is enabled for self preservation. - * - *
- * When enabled, the server keeps track of the number of renewals
- * it should receive from the server. Any time, the number of renewals drops
- * below the threshold percentage as defined by
- * {@link #getRenewalPercentThreshold()}, the server turns off expirations
- * to avert danger.This will help the server in maintaining the registry
- * information in case of network problems between client and the server.
- *
- * @return true to enable self preservation, false otherwise.
- */
- boolean shouldEnableSelfPreservation();
-
- /**
- * The minimum percentage of renewals that is expected from the clients in
- * the period specified by {@link #getRenewalThresholdUpdateIntervalMs()}. If
- * the renewals drop below the threshold, the expirations are disabled if
- * the {@link #shouldEnableSelfPreservation()} is enabled.
- *
- * @return value between 0 and 1 indicating the percentage. For example,
- * 85%
will be specified as 0.85
.
- */
- double getRenewalPercentThreshold();
-
- /**
- * The interval with which the threshold as specified in
- * {@link #getRenewalPercentThreshold()} needs to be updated.
- *
- * @return time in milliseconds indicating the interval.
- */
- int getRenewalThresholdUpdateIntervalMs();
-
- /**
- * The interval with which the information about the changes in peer eureka
- * nodes is updated. The user can use the DNS mechanism or dynamic
- * configuration provided by {@link https://github.com/Netflix/archaius} to
- * change the information dynamically.
- *
- * @return timer in milliseconds indicating the interval.
- */
- int getPeerEurekaNodesUpdateIntervalMs();
-
- /**
- * Get the number of times the replication events should be retried with
- * peers.
- *
- * @return the number of retries.
- */
- int getNumberOfReplicationRetries();
-
- /**
- * Checks whether the replication events should only be sent to peer eureka
- * nodes if their status is {@link InstanceStatus#UP} in the instance's
- * {@link InstanceRegistry}.
- *
- *
- * This check will avoid unnecessary connection attempts to peer eureka - * nodes. The connection attempts for a non existent instance can build up - * file descriptors in an AWS environment because of the way the AWS - * firewall works. - *
- * - * @return true to replicate if the peer node's status is - * {@link InstanceStatus#UP}, false otherwise. - */ - boolean shouldReplicateOnlyIfUP(); - - /** - * Gets the interval with which the status information about peer nodes is - * updated. - * - * @return time in milliseconds indicating the interval. - */ - int getPeerEurekaStatusRefreshTimeIntervalMs(); - - /** - * Gets the time to wait when the eureka server starts up unable to get - * instances from peer nodes. It is better not to start serving rightaway - * during these scenarios as the information that is stored in the registry - * may not be complete. - * - * When the instance registry starts up empty, it builds over time when the - * clients start to send heartbeats and the server requests the clients for - * registration information. - * - * @return time in milliseconds. - */ - int getWaitTimeInMsWhenSyncEmpty(); - - /** - * Gets the timeout value for connecting to peer eureka nodes for - * replication. - * - * @return timeout value in milliseconds. - */ - int getPeerNodeConnectTimeoutMs(); - - /** - * Gets the timeout value for reading information from peer eureka nodes for - * replication. - * - * @return timeout value in milliseconds. - */ - int getPeerNodeReadTimeoutMs(); - - /** - * Gets the total number of HTTP connections allowed to peer eureka - * nodes for replication. - * - * @return total number of allowed HTTP connections. - */ - int getPeerNodeTotalConnections(); - - /** - * Gets the total number of HTTP connections allowed to a - * particular peer eureka node for replication. - * - * @return total number of allowed HTTP connections for a peer - * node. - */ - int getPeerNodeTotalConnectionsPerHost(); - - /** - * Gets the idle time after which the HTTP connection should be - * cleaned up. - * - * @return idle time in seconds. - */ - int getPeerNodeConnectionIdleTimeoutSeconds(); - - /** - * Check to see if the {@link InstanceStatus} status updates should be - * retried indefinitely in case of network problems. - * - *- * This is specially important if the status is updated by the external - * process. - *
- * - * @return true, to retry indefinitely, false otherwise. - */ - boolean shouldRetryIndefinitelyToReplicateStatus(); - - /** - * Get the time for which the delta information should be cached for the - * clients to retrieve the value without missing it. - * - * @return time in milliseconds - */ - long getRetentionTimeInMSInDeltaQueue(); - - /** - * Get the time interval with which the clean up task should wake up and - * check for expired delta information. - * - * @return time in milliseconds. - */ - long getDeltaRetentionTimerIntervalInMs(); - - /** - * Get the time interval with which the task that expires instances should - * wake up and run. - * - * @return time in milliseconds. - */ - long getEvictionIntervalTimerInMs(); - - /** - * Get the timeout value for querying the AWS for ASG - * information. - * - * @return timeout value in milliseconds. - */ - int getASGQueryTimeoutMs(); - - /** - * Get the time interval with which the ASG information must be - * queried from AWS - * - * @return time in milliseconds. - */ - long getASGUpdateIntervalMs(); - - /** - * Gets the time for which the registry payload should be kept in the cache - * if it is not invalidated by change events. - * - * @return time in seconds. - */ - long getResponseCacheAutoExpirationInSeconds(); - - /** - * Gets the time interval with which the payload cache of the client should - * be updated. - * - * @return time in milliseconds. - */ - long getResponseCacheUpdateIntervalMs(); - - /** - * Checks to see if the delta information can be served to client or not. - * - * @return true if the delta information is allowed to be served, false - * otherwise. - */ - boolean shouldDisableDelta(); - - /** - * Get the idle time for which the status replication threads can stay - * alive. - * - * @return time in minutes. - */ - long getMaxIdleThreadInMinutesAgeForStatusReplication(); - - /** - * Get the minimum number of threads to be used for status replication. - * - * @return minimum number of threads to be used for status replication. - */ - int getMinThreadsForStatusReplication(); - - /** - * Get the maximum number of threads to be used for status replication. - * - * @return maximum number of threads to be used for status replication. - */ - int getMaxThreadsForStatusReplication(); - - /** - * Get the maximum number of replication events that can be allowed to back - * up in the status replication pool. - *- * Depending on the memory allowed, timeout and the replication traffic, - * this value can vary. - *
- * - * @return the maximum number of replication events that can be allowed to - * back up. - */ - int getMaxElementsInStatusReplicationPool(); - - /** - * Get the maximum number of replication events that can be allowed to back - * up in the replication pool. This replication pool is responsible for all - * events except status updates. - *- * Depending on the memory allowed, timeout and the replication traffic, - * this value can vary. - *
- * - * @return the maximum number of replication events that can be allowed to - * back up. - */ - int getMaxElementsInReplicationPool(); - - /** - * Get the idle time for which the replication threads can stay alive. - * - * @return time in minutes. - */ - long getMaxIdleThreadAgeInMinutesForReplication(); - - /** - * Get the minimum number of threads to be used for replication. - * - * @return minimum number of threads to be used for replication. - */ - int getMinThreadsForReplication(); - - /** - * Get the maximum number of threads to be used for replication. - * - * @return maximum number of threads to be used for replication. - */ - int getMaxThreadsForReplication(); - - /** - * Checks whether to synchronize instances when timestamp differs. - * - * @return true, to synchronize, false otherwise. - */ - boolean shouldSyncWhenTimestampDiffers(); -} diff --git a/eureka-core/src/main/java/com/netflix/discovery/EurekaServerConfigurationManager.java b/eureka-core/src/main/java/com/netflix/discovery/EurekaServerConfigurationManager.java deleted file mode 100644 index 82fe044e3..000000000 --- a/eureka-core/src/main/java/com/netflix/discovery/EurekaServerConfigurationManager.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2012 Netflix, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.netflix.discovery; - -/** - * - * The class that caches the configuration of the instance of - * {@link EurekaServerConfig} that the server started with. - * - * @author Karthik Ranganathan. - * - */ -public class EurekaServerConfigurationManager { - private EurekaServerConfig config; - private static final EurekaServerConfigurationManager instance = new EurekaServerConfigurationManager(); - - private EurekaServerConfigurationManager() { - } - - public static EurekaServerConfigurationManager getInstance() { - return instance; - } - - public void setConfiguration(EurekaServerConfig config) { - this.config = config; - } - - public EurekaServerConfig getConfiguration() { - return this.config; - } -} diff --git a/eureka-core/src/main/java/com/netflix/discovery/InstanceRegistry.java b/eureka-core/src/main/java/com/netflix/discovery/InstanceRegistry.java deleted file mode 100644 index 372230ad3..000000000 --- a/eureka-core/src/main/java/com/netflix/discovery/InstanceRegistry.java +++ /dev/null @@ -1,780 +0,0 @@ -/* - * Copyright 2012 Netflix, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.netflix.discovery; - -import static com.netflix.discovery.util.EurekaMonitors.CANCEL; -import static com.netflix.discovery.util.EurekaMonitors.CANCEL_NOT_FOUND; -import static com.netflix.discovery.util.EurekaMonitors.EXPIRED; -import static com.netflix.discovery.util.EurekaMonitors.GET_ALL_CACHE_MISS; -import static com.netflix.discovery.util.EurekaMonitors.GET_ALL_CACHE_MISS_DELTA; -import static com.netflix.discovery.util.EurekaMonitors.REGISTER; -import static com.netflix.discovery.util.EurekaMonitors.RENEW; -import static com.netflix.discovery.util.EurekaMonitors.RENEW_NOT_FOUND; -import static com.netflix.discovery.util.EurekaMonitors.STATUS_UPDATE; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.cache.CacheBuilder; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.appinfo.InstanceInfo.ActionType; -import com.netflix.appinfo.InstanceInfo.InstanceStatus; -import com.netflix.appinfo.LeaseInfo; -import com.netflix.discovery.lease.Lease; -import com.netflix.discovery.lease.LeaseManager; -import com.netflix.discovery.resources.ResponseCache; -import com.netflix.discovery.shared.Application; -import com.netflix.discovery.shared.Applications; -import com.netflix.discovery.shared.LookupService; -import com.netflix.discovery.shared.Pair; -import com.netflix.discovery.util.AwsAsgUtil; -import com.netflix.discovery.util.MeasuredRate; -import com.netflix.servo.annotations.DataSourceType; -import com.netflix.servo.monitor.Monitors; - -/** - * Handles all registry requests from eureka clients. - * - *- * Primary operations that are performed are the - * Registers,Renewals,Cancels,Expirations and Status Changes. The - * registry also stores only the delta operations - *
- * - * @author Karthik Ranganathan - * - */ -public abstract class InstanceRegistry implements LeaseManager- * This is normally invoked by a client when it shuts down informing the - * server to remove the instance from traffic. - *
- * - * @param appName - * the application name of the application. - * @param id - * the unique identifier of the instance. - * @param isReplication - * true if this is a replication event from other nodes, false - * otherwise. - * @return true if the instance was removed from the - * {@link InstanceRegistry} successfully, false otherwise. - */ - public boolean cancel(String appName, String id, boolean isReplication) { - try { - read.lock(); - CANCEL.increment(isReplication); - Map- * Primary operations that are replicated are the - * Registers,Renewals,Cancels,Expirations and Status Changes - *
- * - *- * When the eureka server starts up it tries to fetch all the registry - * information from the peer eureka nodes.If for some reason this operation - * fails, the server does not allow the user to get the registry information for - * a period specified in - * {@link EurekaServerConfig#getWaitTimeInMsWhenSyncEmpty()}. - *
- * - *- * One important thing to note about renewals.If the renewal drops more - * than the specified threshold as specified in - * {@link EurekaServerConfig#getRenewalPercentThreshold()} within a period of - * {@link EurekaServerConfig#getRenewalThresholdUpdateIntervalMs()}, eureka - * perceives this as a danger and stops expiring instances. - *
- * - * @author Karthik Ranganathan, Greg Kim - * - */ -public class PeerAwareInstanceRegistry extends InstanceRegistry { - private static final Logger logger = LoggerFactory - .getLogger(PeerAwareInstanceRegistry.class); - - private static final EurekaServerConfig eurekaServerConfig = EurekaServerConfigurationManager - .getInstance().getConfiguration(); - private static final String DICOVERY_FAILED_REPLICATION_AFTER_RETRY = "FailedReplicationAfterRetry"; - - private static final int REPL_RETRY_SLEEP_TIME_IN_MS = 40; - - private long startupTime = 0; - - private boolean peerInstancesTransferEmptyOnStartup = true; - - private static final Timer timerReplicaNodes = new Timer( - "Eureka-PeerNodesUpdater", true); - - enum Action { - Heartbeat, Register, Cancel, StatusUpdate; - - private com.netflix.servo.monitor.Timer timer = Monitors.newTimer(this - .name()); - - public com.netflix.servo.monitor.Timer getTimer() { - return this.timer; - } - - } - - private final static Comparator- * The self-preservation mode is enabled if the expected number of renewals - * per minute {@link #getNumOfRenewsInLastMin()} is lesser than the expected - * threshold which is determined by {@link #getNumOfRenewsPerMinThreshold()} - * . Eureka perceives this as a danger and stops expiring instances as this - * is most likely because of a network event. The mode is disabled only when - * the renewals get back to above the threshold or if the flag - * {@link EurekaServerConfig#shouldEnableSelfPreservation()} is set to - * false. - *
- * - * @return true if the self-preservation mode is enabled, false otherwise. - */ - public boolean isSelfPreservationModeEnabled() { - return eurekaServerConfig.shouldEnableSelfPreservation(); - } - - /** - * Perform all cleanup and shutdown operations. - */ - void shutdown() { - try { - this.replicationExecutorPool.shutdown(); - DefaultMonitorRegistry.getInstance().unregister( - Monitors.newObjectMonitor(this)); - } catch (Throwable t) { - logger.error("Cannot shutdown ReplicaAwareInstanceRegistry", t); - } - } - - @Override - public InstanceInfo getNextServerFromEureka(String virtualHostname, boolean secure) { - // TODO Auto-generated method stub - return null; - } - - /** - * Updates the renewal threshold based on the current number of - * renewals. The threshold is a percentage as specified in - * {@link EurekaServerConfig#getRenewalPercentThreshold()} of renewals - * received per minute {@link #getNumOfRenewsInLastMin()}. - */ - private void updateRenewalThreshold() { - try { - LookupService lookupService = DiscoveryManager.getInstance() - .getLookupService(); - Applications apps = lookupService.getApplications(); - int count = 0; - for (Application app : apps.getRegisteredApplications()) { - for (InstanceInfo instance : app.getInstances()) { - ++count; - } - } - // Update threshold only if the threshold is greater than the - // current expected threshold. - if ((count * 2) > (eurekaServerConfig.getRenewalPercentThreshold() * numberOfRenewsPerMinThreshold)) { - numberOfRenewsPerMinThreshold = (int) ((count * 2) * eurekaServerConfig - .getRenewalPercentThreshold()); - logger.info("Updated the renewal threshold to : {}", - numberOfRenewsPerMinThreshold); - } - } catch (Throwable e) { - logger.error("Cannot update renewal threshold", e); - } - } - - /** - * Gets the list of all {@link Applications} from the registry in sorted - * lexical order of {@link Application#getName()}. - * - * @return the list of {@link Applications} in lexical order. - */ - public ListThe latest versions are always recommended.
- * - * @author Karthik Ranganathan, Greg Kim - * - */ -public enum Version { - V1, V2; - - public static Version toEnum(String v){ - for(Version version : Version.values()){ - if(version.name().equalsIgnoreCase(v)){ - return version; - } - } - //Defaults to v2 - return V2; - } -} diff --git a/eureka-core/src/main/java/com/netflix/discovery/cluster/PeerEurekaNode.java b/eureka-core/src/main/java/com/netflix/discovery/cluster/PeerEurekaNode.java deleted file mode 100644 index f510dd7a6..000000000 --- a/eureka-core/src/main/java/com/netflix/discovery/cluster/PeerEurekaNode.java +++ /dev/null @@ -1,471 +0,0 @@ -/* - * Copyright 2012 Netflix, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.netflix.discovery.cluster; - -import java.util.Date; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response.Status; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.appinfo.InstanceInfo.InstanceStatus; -import com.netflix.discovery.CurrentRequestVersion; -import com.netflix.discovery.EurekaServerConfig; -import com.netflix.discovery.EurekaServerConfigurationManager; -import com.netflix.discovery.PeerAwareInstanceRegistry; -import com.netflix.discovery.Version; -import com.netflix.discovery.resources.ASGResource.ASGStatus; -import com.netflix.discovery.shared.EurekaJerseyClient; -import com.netflix.discovery.shared.EurekaJerseyClient.JerseyClient; -import com.netflix.servo.annotations.DataSourceType; -import com.netflix.servo.monitor.Monitors; -import com.netflix.servo.monitor.Stopwatch; -import com.netflix.servo.monitor.Timer; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.client.apache4.ApacheHttpClient4; - -/** - * ThePeerEurekaNode
represents a peer node to which information
- * should be shared from this node.
- *
- * - * This class handles replicating all update operations like - * Register,Renew,Cancel,Expiration and Status Changes to the eureka - * node it represents. - *
- *
- * @author Karthik Ranganathan, Greg Kim
- *
- */
-public class PeerEurekaNode {
-
- private static final Logger logger = LoggerFactory
- .getLogger(PeerEurekaNode.class);
-
- private static final int RETRY_SLEEP_TIME_MS = 100;
-
- public static final String HEADER_REPLICATION = "x-netflix-discovery-replication";
- private static final EurekaServerConfig config = EurekaServerConfigurationManager
- .getInstance().getConfiguration();
- private final Timer registerTimer = Monitors.newTimer("Register");
- private final Timer cancelTimer = Monitors.newTimer("Cancel");
- private final Timer renewTimer = Monitors.newTimer("Renew");
- private final Timer asgStatusUpdateTimer = Monitors
- .newTimer("ASGStatusUpdate");
- private final Timer instanceStatusUpdateTimer = Monitors
- .newTimer("InstanceStatusUpdate");
- private final String serviceUrl;
- private final String name;
- private JerseyClient jerseyClient;
- private ApacheHttpClient4 jerseyApacheClient;
- private ThreadPoolExecutor statusReplicationPool;
- private volatile boolean statusReplication = true;
-
- public PeerEurekaNode(String serviceUrl) {
- this.serviceUrl = serviceUrl.intern();
- this.name = getClass().getSimpleName() + ": " + serviceUrl + "apps/: ";
-
- ThreadFactory threadFactory = new ThreadFactoryBuilder()
- .setDaemon(false)
- .setNameFormat("Eureka-ReplicaNode-Thread-" + serviceUrl)
- .build();
-
- statusReplicationPool = new ThreadPoolExecutor(
- config.getMinThreadsForStatusReplication(),
- config.getMaxThreadsForStatusReplication(),
- config.getMaxIdleThreadInMinutesAgeForStatusReplication(),
- TimeUnit.MINUTES, new ArrayBlockingQueue
- * ASG (Autoscaling group) names are available for instances in AWS and the
- * ASG information is used for determining if the instance should be
- * registered as {@link InstanceStatus#DOWN} or {@link InstanceStatus#UP}.
- *
- * @param asgName
- * the asg name if any of this instance.
- * @param newStatus
- * the new status of the ASG.
- * @return true if the status update succeeds, false otherwise.
- * @throws Exception
- */
- public boolean statusUpdate(String asgName, ASGStatus newStatus)
- throws Exception {
- ClientResponse response = null;
- Stopwatch tracer = asgStatusUpdateTimer.start();
- try {
- String urlPath = "asg/" + asgName + "/status";
- response = jerseyApacheClient.resource(serviceUrl).path(urlPath)
- .queryParam("value", newStatus.name())
- .header(HEADER_REPLICATION, "true")
- .put(ClientResponse.class);
-
- if (response.getStatus() != 200) {
- logger.error(name + asgName + " : statusUpdate: failed!");
- } else {
- return true;
- }
- tracer.stop();
- return false;
- } finally {
- if (response != null) {
- response.close();
- }
- if (tracer != null) {
- tracer.stop();
- }
- }
- }
-
- /**
- *
- * Send the status update of the instance.
- *
- * @param appName
- * the application name of the instance.
- * @param id
- * the unique identifier of the instance.
- * @param newStatus
- * the new status of the instance.
- * @return true if the udpate succeeded, false otherwise.
- * @throws Throwable
- */
- public boolean statusUpdate(final String appName, final String id,
- final InstanceStatus newStatus) throws Throwable {
- statusReplicationPool.execute(new Runnable() {
-
- @Override
- public void run() {
- CurrentRequestVersion.set(Version.V2);
- boolean success = false;
- while (!success) {
- ClientResponse response = null;
- Stopwatch tracer = instanceStatusUpdateTimer.start();
- try {
- String urlPath = "apps/" + appName + "/" + id
- + "/status";
- response = jerseyApacheClient.resource(serviceUrl)
- .path(urlPath)
- .queryParam("value", newStatus.name())
- .header(HEADER_REPLICATION, "true")
- .put(ClientResponse.class);
- if (response.getStatus() != 200) {
- logger.error(name + appName + "/" + id
- + " : statusUpdate: failed!");
- }
- success = true;
- } catch (Throwable e) {
- logger.error(name + appName + "/" + id
- + " : statusUpdate: failed!", e);
- try {
- Thread.sleep(RETRY_SLEEP_TIME_MS);
- } catch (InterruptedException e1) {
-
- }
- if ((!config.shouldRetryIndefinitelyToReplicateStatus())
- || (!statusReplication)) {
- success = true;
- }
-
- } finally {
- if (response != null) {
- response.close();
- }
- if (tracer != null) {
- tracer.stop();
- }
- }
-
- }
-
- }
-
- });
- return true;
- }
-
- /**
- * Get the service Url of the peer eureka node.
- *
- * @return the service Url of the peer eureka node.
- */
- public String getServiceUrl() {
- return serviceUrl;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result
- + ((serviceUrl == null) ? 0 : serviceUrl.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- PeerEurekaNode other = (PeerEurekaNode) obj;
- if (serviceUrl == null) {
- if (other.serviceUrl != null)
- return false;
- } else if (!serviceUrl.equals(other.serviceUrl))
- return false;
- return true;
- }
-
- /**
- * Get the number of items in the replication pipeline yet to be replicated.
- *
- * @return the long value representing the number of items in the
- * replication pipeline yet to be replicated..
- */
- @com.netflix.servo.annotations.Monitor(name = "itemsInReplicationPipeline", type = DataSourceType.GAUGE)
- public long getNumOfItemsInReplicationPipeline() {
- return statusReplicationPool.getQueue().size();
- }
-
- /**
- * Disables the status replication and clears the internal queue.
- */
- public void disableStatusReplication() {
- if (statusReplicationPool.getQueue().size() > 0) {
- logger.info("Clearing the internal status queue for {}", serviceUrl);
- statusReplicationPool.getQueue().clear();
- }
- this.statusReplication = false;
- }
-
- /**
- * Enable the status replication.
- */
- public void enableStatusReplication() {
- this.statusReplication = true;
- }
-
-}
diff --git a/eureka-core/src/main/java/com/netflix/discovery/lease/Lease.java b/eureka-core/src/main/java/com/netflix/discovery/lease/Lease.java
deleted file mode 100644
index 60748cd45..000000000
--- a/eureka-core/src/main/java/com/netflix/discovery/lease/Lease.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright 2012 Netflix, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.netflix.discovery.lease;
-
-import com.netflix.appinfo.InstanceInfo;
-import com.netflix.discovery.InstanceRegistry;
-
-/**
- * Describes a time-based availability of a {@link T}. Purpose is to avoid
- * accumulation of instances in {@link InstanceRegistry} as result of ungraceful
- * shutdowns that is not uncommon in AWS environments.
- *
- * If a lease elapses without renewals, it will eventually expire consequently
- * marking the associated {@link T} for immediate eviction - this is similar to
- * an explicit cancellation except that there is no communication between the
- * {@link T} and {@link LeaseManager}.
- *
- * @author Karthik Ranganathan, Greg Kim
- */
-public class Lease
- * Leases determine what instances receive traffic. When there is no renewal
- * request from the client, the lease gets expired and the instances are evicted
- * out of {@link InstanceRegistry}. This is key to instances receiving traffic
- * or not.
- *
- *
- * @author Karthik Ranganathan, Greg Kim
- *
- * @param
- * The ASG status is used in AWS environments to automatically
- * enable/disable instance registration based on the status of the ASG. This is
- * particularly useful in red/black deployment scenarios where it is
- * easy to switch to a new version and incase of problems switch back to the old
- * versions of the deployment.
- *
- * During such a scenario, when an ASG is disabled and the instances go away and
- * get refilled by an ASG - which is normal in AWS environments,the instances
- * automatically go in the {@link InstanceStatus#OUT_OF_SERVICE} state when they
- * are refilled by the ASG and if the ASG is disabled by as indicated by a flag
- * in the ASG as described in {@link AwsAsgUtil#isASGEnabled(String)}
- *
- * The delta changes represent the registry information change for a period
- * as configured by
- * {@link EurekaServerConfig#getRetentionTimeInMSInDeltaQueue()}. The
- * changes that can happen in a registry include
- * Registrations,Cancels,Status Changes and Expirations. Normally
- * the changes to the registry are infrequent and hence getting just the
- * delta will be much more efficient than getting the complete registry.
- *
- * Since the delta information is cached over a period of time, the requests
- * may return the same data multiple times within the window configured by
- * {@link EurekaServerConfig#getRetentionTimeInMSInDeltaQueue()}.The clients
- * are expected to handle this duplicate information.
- *
- *
- * @param version
- * the version of the request.
- * @param acceptHeader
- * the accept header of the request to indicate whether to serve
- * JSON or XML data.
- *
- * @param acceptEncoding
- * the accept header of the request to indicate whether to serve
- * compressed or uncompressed data.
- * @param uriInfo
- * the {@link URI} information of the request made.
- * @return response containing the delta information of the
- * {@link InstanceRegistry}.z
- */
- @Path("delta")
- @GET
- public Response getContainerDifferential(
- @PathParam("version") String version,
- @HeaderParam(HEADER_ACCEPT) String acceptHeader,
- @HeaderParam(HEADER_ACCEPT_ENCODING) String acceptEncoding,
- @Context UriInfo uriInfo) {
- // If the delta flag is disabled in discovery or if the lease expiration
- // has been disabled, redirect clients to get all instances
- if ((eurekaConfig.shouldDisableDelta())
- || (!PeerAwareInstanceRegistry.getInstance()
- .isLeaseExpirationEnabled() || (!PeerAwareInstanceRegistry
- .getInstance().shouldAllowAccess()))) {
- return Response.status(Status.FORBIDDEN).build();
- }
- EurekaMonitors.GET_ALL_DELTA.increment();
- CurrentRequestVersion.set(Version.toEnum(version));
- KeyType keyType = KeyType.JSON;
- if (acceptHeader == null || !acceptHeader.contains(HEADER_JSON_VALUE)) {
- keyType = KeyType.XML;
- }
- Key cacheKey = new Key(ResponseCache.ALL_APPS_DELTA, keyType,
- CurrentRequestVersion.get());
- if (acceptEncoding != null
- && acceptEncoding.contains(HEADER_GZIP_VALUE)) {
- return Response.ok(ResponseCache.getInstance().getGZIP(cacheKey))
- .header(HEADER_CONTENT_ENCODING, HEADER_GZIP_VALUE).build();
- } else {
- return Response.ok(ResponseCache.getInstance().get(cacheKey))
- .build();
- }
- }
-}
diff --git a/eureka-core/src/main/java/com/netflix/discovery/resources/InstanceResource.java b/eureka-core/src/main/java/com/netflix/discovery/resources/InstanceResource.java
deleted file mode 100644
index 708e167a7..000000000
--- a/eureka-core/src/main/java/com/netflix/discovery/resources/InstanceResource.java
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * Copyright 2012 Netflix, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.netflix.discovery.resources;
-
-import java.util.Date;
-
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.netflix.appinfo.InstanceInfo;
-import com.netflix.appinfo.InstanceInfo.InstanceStatus;
-import com.netflix.discovery.EurekaServerConfigurationManager;
-import com.netflix.discovery.PeerAwareInstanceRegistry;
-import com.netflix.discovery.cluster.PeerEurekaNode;
-
-/**
- * A jersey resource that handles operations for a particular instance.
- *
- * @author Karthik Ranganathan, Greg Kim
- *
- */
-@Produces({ "application/xml", "application/json" })
-public class InstanceResource {
- private final static Logger logger = LoggerFactory
- .getLogger(InstanceResource.class);
-
- private final static PeerAwareInstanceRegistry registry = PeerAwareInstanceRegistry
- .getInstance();
-
- String id;
- ApplicationResource app;
-
- public InstanceResource(ApplicationResource app, String id) {
- this.id = id;
- this.app = app;
- }
-
- /**
- * Get requests returns the information about the instance's
- * {@link InstanceInfo}.
- *
- * @return response containing information about the the instance's
- * {@link InstanceInfo}.
- */
- @GET
- public Response getInstanceInfo() {
- InstanceInfo appInfo = registry
- .getInstanceByAppAndId(app.getName(), id);
- if (appInfo != null) {
- logger.debug("Found: {} - {}", app.getName(), id);
- return Response.ok(appInfo).build();
- } else {
- logger.debug("Not Found: {} - {}", app.getName(), id);
- return Response.status(Status.NOT_FOUND).build();
- }
- }
-
- /**
- * A put request for renewing lease from a client instance.
- *
- * @param isReplication
- * a header parameter containing information whether this is
- * replicated from other nodes.
- * @param overriddenStatus
- * overridden status if any.
- * @param status
- * the {@link InstanceStatus} of the instance.
- * @param lastDirtyTimestamp
- * last timestamp when this instance information was updated.
- * @return response indicating whether the operation was a success or
- * failure.
- */
- @PUT
- public Response renewLease(
- @HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication,
- @QueryParam("overriddenstatus") String overriddenStatus,
- @QueryParam("status") String status,
- @QueryParam("lastDirtyTimestamp") String lastDirtyTimestamp) {
- boolean isFromReplicaNode = "true".equals(isReplication);
- boolean isSuccess = registry
- .renew(app.getName(), id, isFromReplicaNode);
-
- // Not found in the registry, immediately ask for a register
- if (!isSuccess) {
- logger.debug("Not Found (Renew): {} - {}", app.getName(), id);
- return Response.status(Status.NOT_FOUND).build();
- }
- // Check if we need to sync based on dirty time stamp, the client
- // instance might have changed some value
- Response response = null;
- if (lastDirtyTimestamp != null
- && EurekaServerConfigurationManager.getInstance()
- .getConfiguration().shouldSyncWhenTimestampDiffers()) {
- response = this.validateDirtyTimestamp(
- Long.valueOf(lastDirtyTimestamp), isFromReplicaNode);
- // Store the overridden status since the validation found out the
- // node that
- // replicates wins
- if (response.getStatus() == Response.Status.NOT_FOUND
- .getStatusCode()
- && (overriddenStatus != null)
- && !(InstanceStatus.UNKNOWN.equals(overriddenStatus))
- && isFromReplicaNode) {
- registry.storeOverriddenStatusIfRequired(overriddenStatus,
- InstanceStatus.valueOf(overriddenStatus));
- }
- return response;
- }
- logger.debug("Found (Renew): {} - {}" + app.getName(), id);
- return Response.ok().build();
- }
-
- /**
- * Handles {@link InstanceStatus} updates.
- *
- *
- * The status updates are normally done for administrative purposes to
- * change the instance status between {@link InstanceStatus#UP} and
- * {@link InstanceStatus#OUT_OF_SERVICE} to select or remove instances for
- * receiving traffic.
- *
- * The cache is maintained in compressed and non-compressed form for three
- * categories of requests - all applications, delta changes and for individual
- * applications. The compressed form is probably the most efficient in terms of
- * network traffic especially when querying all applications.
- *
- * The cache also maintains separate pay load for JSON and XML
- * formats and for multiple versions too. The cache is updated periodically to
- * reflect the latest information configured by
- * {@link EurekaServerConfig#getResponseCacheUpdateIntervalMs()}.
- *
- * If the cached information is not available it is generated on the first
- * request. After the first request, the information is then updated
- * periodically by a background thread.
- *
- * The names are obtained from the {@link InstanceRegistry} which is then
- * used for querying the AWS.
- *
- * Eureka clients talk to Eureka servers bound with well known
- *
- * This binding mechanism gravitates towards one eureka server per zone for
- * resilience.Atleast one elastic ip should be slotted for each eureka server in
- * a zone. If more than eureka server is launched per zone and there are not
- * enough elastic ips slotted, the ips keeps switching back and forth between
- * the eureka servers in the zone.
- *
- * if an EIP is already bound to this instance this method simply returns.
- * Otherwise, this method tries to find an unused EIP based on the registry
- * information. If it cannot find any unused EIP this method simply picks an
- * EIP of an instance with the earliest registration timestamp.
- *
- * This mechanism looks for the EIP pool in the zone the instance is in by
- * looking up the DNS name
- * Eureka Monitoring is done using {@link https://github.com/Netflix/servo}. The
- * users who wants to take advantage of the monitoring should read up on
- * Servo
- *
- *
- * @author Karthik Ranganathan, Greg Kim
- *
- */
-public enum EurekaMonitors {
- RENEW("renewCounter", "Number of total renews seen since startup"), CANCEL(
- "cancelCounter", "Number of total cancels seen since startup"), GET_ALL_CACHE_MISS(
- "getAllCacheMissCounter",
- "Number of total registery queries seen since startup"), GET_ALL_CACHE_MISS_DELTA(
- "getAllCacheMissDeltaCounter",
- "Number of total registery queries for delta seen since startup"), GET_ALL_DELTA(
- "getAllDeltaCounter", "Number of total deltas since startup"), GET_ALL(
- "getAllCounter",
- "Number of total registry queries seen since startup"), REGISTER(
- "registerCounter", "Number of total registers seen since startup"), EXPIRED(
- "expiredCounter", "Number of total expired leases since startup"), STATUS_UPDATE(
- "statusUpdateCounter",
- "Number of total admin status updates since startup"), CANCEL_NOT_FOUND(
- "cancelNotFoundCounter",
- "Number of total cancel requests on non-existing instance since startup"), RENEW_NOT_FOUND(
- "renewNotFoundexpiredCounter",
- "Number of total renew on non-existing instance since startup"), REJECTED_REPLICATIONS(
- "numOfRejectedReplications",
- "Number of replications rejected because of full queue"), FAILED_REPLICATIONS(
- "numOfFailedReplications",
- "Number of failed replications - likely from timeouts");
-
- private final String name;
-
- private final String myZoneCounterName;
-
- private final String description;
-
- private EurekaMonitors(String name, String description) {
- this.name = name;
- this.description = description;
-
- DataCenterInfo dcInfo = ApplicationInfoManager.getInstance().getInfo()
- .getDataCenterInfo();
- if (dcInfo.getName() == Name.Amazon) {
- myZoneCounterName = ((AmazonInfo) dcInfo)
- .get(MetaDataKey.availabilityZone) + "." + name;
- } else {
- myZoneCounterName = "dcmaster." + name;
- }
- }
-
- @com.netflix.servo.annotations.Monitor(name = "count", type = DataSourceType.COUNTER)
- private final AtomicLong counter = new AtomicLong();
-
- @com.netflix.servo.annotations.Monitor(name = "count-minus-replication", type = DataSourceType.COUNTER)
- private final AtomicLong myZoneCounter = new AtomicLong();
-
- /**
- * Increment the counter for the given statistic.
- */
- public void increment() {
- increment(false);
- }
-
- /**
- * Increment the counter for the given statistic based on whether this is
- * because of replication from other eureka servers or it is a eureka client
- * initiated action.
- *
- * @param isReplication
- * true if this a replication, false otherwise.
- */
- public void increment(boolean isReplication) {
- counter.incrementAndGet();
-
- if (!isReplication) {
- myZoneCounter.incrementAndGet();
- }
- }
-
- /**
- * Gets the statistic name of this monitor.
- *
- * @return the statistic name.
- */
- public String getName() {
- return name;
- }
-
- /**
- * Gets the zone specific statistic name of this monitor. Applies only for
- * AWS cloud.
- *
- * @return the zone specific statistic name.
- */
- public String getZoneSpecificName() {
- return myZoneCounterName;
- }
-
- /**
- * Gets the description of this statistic means.
- *
- * @return the description of this statistic means.
- */
- public String getDescription() {
- return description;
- }
-
- /**
- * Gets the actual counter value for this statistic.
- *
- * @return the long value representing the number of times this statistic
- * has occurred.
- */
- public long getCount() {
- return counter.get();
- }
-
- /**
- * Gets the zone specific counter value for this statistic. This is
- * application only for AWS cloud environment.
- *
- * @return the long value representing the number of times this statistic
- * has occurred.
- */
- public long getZoneSpecificCount() {
- return myZoneCounter.get();
- }
-
- /**
- * Register all statistics with Servo.
- */
- public static void registerAllStats() {
- for (EurekaMonitors c : EurekaMonitors.values()) {
- Monitors.registerObject(c.getName(), c);
- }
- }
-
- /**
- * Unregister all statistics from Servo.
- */
- public static void shutdown() {
- for (EurekaMonitors c : EurekaMonitors.values()) {
- DefaultMonitorRegistry.getInstance().unregister(
- Monitors.newObjectMonitor(c.name(), c));
- }
- }
-}
diff --git a/eureka-core/src/main/java/com/netflix/discovery/util/MeasuredRate.java b/eureka-core/src/main/java/com/netflix/discovery/util/MeasuredRate.java
deleted file mode 100644
index fd37a9fef..000000000
--- a/eureka-core/src/main/java/com/netflix/discovery/util/MeasuredRate.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright 2012 Netflix, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.netflix.discovery.util;
-
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.atomic.AtomicLong;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Utility class for getting a count in last X milliseconds
- *
- * @author Karthik Ranganathan,Greg Kim
- */
-public class MeasuredRate {
- private static final Logger logger = LoggerFactory
- .getLogger(MeasuredRate.class);
- private final AtomicLong lastBucket = new AtomicLong(0);
- private final AtomicLong currentBucket = new AtomicLong(0);
- private final long sampleInterval;
- private Timer timer = new Timer("Eureka-MeasureRateTimer", true);
-
- /**
- * @param sampleInterval
- * in milliseconds
- */
- public MeasuredRate(long sampleInterval) {
- this.sampleInterval = sampleInterval;
- timer.schedule(new TimerTask() {
-
- @Override
- public void run() {
- try {
- // Zero out the current bucket.
- lastBucket.set(currentBucket.getAndSet(0));
- } catch (Throwable e) {
- logger.error("Cannot reset the Measured Rate", e);
- }
- }
- }, sampleInterval, sampleInterval);
- }
-
- /**
- * Returns the count in the last sample interval.
- */
- public long getCount() {
- return lastBucket.get();
- }
-
- /**
- * Increments the count in the current sample interval.
- */
- public void increment() {
- currentBucket.incrementAndGet();
- }
-}
diff --git a/eureka-core/src/main/java/com/netflix/discovery/util/StatusInfo.java b/eureka-core/src/main/java/com/netflix/discovery/util/StatusInfo.java
deleted file mode 100644
index 31ee89115..000000000
--- a/eureka-core/src/main/java/com/netflix/discovery/util/StatusInfo.java
+++ /dev/null
@@ -1,139 +0,0 @@
-package com.netflix.discovery.util;
-
-import java.lang.management.ManagementFactory;
-import java.text.DecimalFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-
-import com.netflix.appinfo.ApplicationInfoManager;
-import com.netflix.appinfo.InstanceInfo;
-import com.netflix.config.ConfigurationManager;
-import com.netflix.discovery.provider.Serializer;
-import com.thoughtworks.xstream.annotations.XStreamAlias;
-import com.thoughtworks.xstream.annotations.XStreamOmitField;
-
-/**
- * An utility class for exposing status information of an instance.
- *
- * @author Greg Kim
- */
-@Serializer("com.netflix.discovery.converters.EntityBodyConverter")
-@XStreamAlias("status")
-public class StatusInfo {
- private final static String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss Z";
-
- public static final class Builder {
-
- @XStreamOmitField
- private StatusInfo result;
-
- private Builder() {
- result = new StatusInfo();
- }
-
- public static Builder newBuilder() {
- return new Builder();
- }
-
- public Builder isHealthy(boolean b) {
- result.isHeathly = Boolean.valueOf(b);
- return this;
- }
-
- /**
- * Add any application specific status data.
- */
- public Builder add(String key, String value) {
- if (result.applicationStats == null) {
- result.applicationStats = new HashMapappName
- * and id
- *
- * @param appName
- * - unique id of the application.
- * @param id
- * - unique id within appName.
- * @param isReplication
- * - whether this is a replicated entry from another eureka node.
- * @return true, if the operation was successful, false otherwise.
- */
- boolean cancel(String appName, String id, boolean isReplication);
-
- /**
- * Renew the {@link Lease} associated w/ the passed in appName
- * and id
- *
- * @param id
- * - unique id within appName
- * @param isReplication
- * - whether this is a replicated entry from another ds node
- * @return whether the operation of successful
- */
- boolean renew(String appName, String id, boolean isReplication);
-
- /**
- * Evict {@link T}s with expired {@link Lease}(s).
- */
- void evict();
-}
diff --git a/eureka-core/src/main/java/com/netflix/discovery/resources/ASGResource.java b/eureka-core/src/main/java/com/netflix/discovery/resources/ASGResource.java
deleted file mode 100644
index 80d562a52..000000000
--- a/eureka-core/src/main/java/com/netflix/discovery/resources/ASGResource.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright 2012 Netflix, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.netflix.discovery.resources;
-
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Response;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.netflix.appinfo.InstanceInfo.InstanceStatus;
-import com.netflix.discovery.PeerAwareInstanceRegistry;
-import com.netflix.discovery.cluster.PeerEurekaNode;
-import com.netflix.discovery.util.AwsAsgUtil;
-
-/**
- * A jersey resource for handling updates to {@link ASGStatus}.
- *
- * IP address
.
- *
- * IP addresses
since that is the most reliable mechanism to
- * discover the Eureka servers. When Eureka servers come up they bind
- * themselves to a well known elastic ip
- * {zone}.{region}.{domainName}
. The
- * zone is fetched from the {@link InstanceInfo} object;the region is picked
- * up from the specified configuration
- * {@link EurekaServerConfig#getRegion()};the domain name is picked up from
- * the specified configuration {@link EurekaServerConfig#getDomainName()}.
- *