idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
17,200 | public static JsonElement parse ( JsonReader reader ) throws JsonParseException { boolean isEmpty = true ; try { reader . peek ( ) ; isEmpty = false ; return TypeAdapters . JSON_ELEMENT . read ( reader ) ; } catch ( EOFException e ) { if ( isEmpty ) { return JsonNull . INSTANCE ; } throw new JsonSyntaxException ( e ) ; } catch ( MalformedJsonException e ) { throw new JsonSyntaxException ( e ) ; } catch ( IOException e ) { throw new JsonIOException ( e ) ; } catch ( NumberFormatException e ) { throw new JsonSyntaxException ( e ) ; } } | Takes a reader in any state and returns the next value as a JsonElement . |
17,201 | public static void write ( JsonElement element , JsonWriter writer ) throws IOException { TypeAdapters . JSON_ELEMENT . write ( writer , element ) ; } | Writes the JSON element to the writer recursively . |
17,202 | private String getCustSerializedName ( FieldOptions options , String defaultName ) { for ( Extension < FieldOptions , String > extension : serializedNameExtensions ) { if ( options . hasExtension ( extension ) ) { return options . getExtension ( extension ) ; } } return protoFormat . to ( jsonFormat , defaultName ) ; } | Retrieves the custom field name from the given options and if not found returns the specified default name . |
17,203 | private String getCustSerializedEnumValue ( EnumValueOptions options , String defaultValue ) { for ( Extension < EnumValueOptions , String > extension : serializedEnumValueExtensions ) { if ( options . hasExtension ( extension ) ) { return options . getExtension ( extension ) ; } } return defaultValue ; } | Retrieves the custom enum value name from the given options and if not found returns the specified default value . |
17,204 | public void addPackage ( String packageName ) throws IOException { if ( this . packagePrefix != null ) { throw new IllegalStateException ( ) ; } out . write ( "package " ) ; out . write ( packageName ) ; out . write ( ";\n" ) ; this . packagePrefix = packageName + "." ; } | Emit a package declaration . |
17,205 | public void field ( String type , String name , int modifiers ) throws IOException { field ( type , name , modifiers , null ) ; } | Emits a field declaration . |
17,206 | public void beginMethod ( String returnType , String name , int modifiers , String ... parameters ) throws IOException { indent ( ) ; modifiers ( modifiers ) ; if ( returnType != null ) { type ( returnType ) ; out . write ( " " ) ; out . write ( name ) ; } else { type ( name ) ; } out . write ( "(" ) ; for ( int p = 0 ; p < parameters . length ; ) { if ( p != 0 ) { out . write ( ", " ) ; } type ( parameters [ p ++ ] ) ; out . write ( " " ) ; type ( parameters [ p ++ ] ) ; } out . write ( ")" ) ; if ( ( modifiers & Modifier . ABSTRACT ) != 0 ) { out . write ( ";\n" ) ; pushScope ( Scope . ABSTRACT_METHOD ) ; } else { out . write ( " {\n" ) ; pushScope ( Scope . NON_ABSTRACT_METHOD ) ; } } | Emit a method declaration . |
17,207 | public void endMethod ( ) throws IOException { Scope popped = popScope ( ) ; if ( popped == Scope . NON_ABSTRACT_METHOD ) { indent ( ) ; out . write ( "}\n" ) ; } else if ( popped != Scope . ABSTRACT_METHOD ) { throw new IllegalStateException ( ) ; } } | Completes the current method declaration . |
17,208 | private void modifiers ( int modifiers ) throws IOException { if ( ( modifiers & Modifier . PUBLIC ) != 0 ) { out . write ( "public " ) ; } if ( ( modifiers & Modifier . PRIVATE ) != 0 ) { out . write ( "private " ) ; } if ( ( modifiers & Modifier . PROTECTED ) != 0 ) { out . write ( "protected " ) ; } if ( ( modifiers & Modifier . STATIC ) != 0 ) { out . write ( "static " ) ; } if ( ( modifiers & Modifier . FINAL ) != 0 ) { out . write ( "final " ) ; } if ( ( modifiers & Modifier . ABSTRACT ) != 0 ) { out . write ( "abstract " ) ; } if ( ( modifiers & Modifier . SYNCHRONIZED ) != 0 ) { out . write ( "synchronized " ) ; } if ( ( modifiers & Modifier . TRANSIENT ) != 0 ) { out . write ( "transient " ) ; } if ( ( modifiers & Modifier . VOLATILE ) != 0 ) { out . write ( "volatile " ) ; } } | Emit modifier names . |
17,209 | public void add ( Boolean bool ) { elements . add ( bool == null ? JsonNull . INSTANCE : new JsonPrimitive ( bool ) ) ; } | Adds the specified boolean to self . |
17,210 | public void add ( Character character ) { elements . add ( character == null ? JsonNull . INSTANCE : new JsonPrimitive ( character ) ) ; } | Adds the specified character to self . |
17,211 | public void add ( Number number ) { elements . add ( number == null ? JsonNull . INSTANCE : new JsonPrimitive ( number ) ) ; } | Adds the specified number to self . |
17,212 | public void add ( String string ) { elements . add ( string == null ? JsonNull . INSTANCE : new JsonPrimitive ( string ) ) ; } | Adds the specified string to self . |
17,213 | public void add ( JsonElement element ) { if ( element == null ) { element = JsonNull . INSTANCE ; } elements . add ( element ) ; } | Adds the specified element to self . |
17,214 | private static int parseDotted ( String javaVersion ) { try { String [ ] parts = javaVersion . split ( "[._]" ) ; int firstVer = Integer . parseInt ( parts [ 0 ] ) ; if ( firstVer == 1 && parts . length > 1 ) { return Integer . parseInt ( parts [ 1 ] ) ; } else { return firstVer ; } } catch ( NumberFormatException e ) { return - 1 ; } } | Parses both legacy 1 . 8 style and newer 9 . 0 . 4 style |
17,215 | protected String parseAzToGetRegion ( String availabilityZone ) { if ( ! availabilityZone . isEmpty ( ) ) { String possibleRegion = availabilityZone . substring ( 0 , availabilityZone . length ( ) - 1 ) ; if ( availabilityZoneVsRegion . containsValue ( possibleRegion ) ) { return possibleRegion ; } } return null ; } | Tries to determine what region we re in based on the provided availability zone . |
17,216 | private boolean fetchRegistry ( ) { boolean success ; Stopwatch tracer = fetchRegistryTimer . start ( ) ; try { if ( serverConfig . shouldDisableDeltaForRemoteRegions ( ) || ( getApplications ( ) == null ) || ( getApplications ( ) . getRegisteredApplications ( ) . size ( ) == 0 ) ) { logger . info ( "Disable delta property : {}" , serverConfig . shouldDisableDeltaForRemoteRegions ( ) ) ; logger . info ( "Application is null : {}" , getApplications ( ) == null ) ; logger . info ( "Registered Applications size is zero : {}" , getApplications ( ) . getRegisteredApplications ( ) . isEmpty ( ) ) ; success = storeFullRegistry ( ) ; } else { success = fetchAndStoreDelta ( ) ; } logTotalInstances ( ) ; } catch ( Throwable e ) { logger . error ( "Unable to fetch registry information from the remote registry {}" , this . remoteRegionURL , e ) ; return false ; } finally { if ( tracer != null ) { tracer . stop ( ) ; } } return success ; } | Fetch the registry information from the remote region . |
17,217 | private void updateDelta ( Applications delta ) { int deltaCount = 0 ; for ( Application app : delta . getRegisteredApplications ( ) ) { for ( InstanceInfo instance : app . getInstances ( ) ) { ++ deltaCount ; if ( ActionType . ADDED . equals ( instance . getActionType ( ) ) ) { Application existingApp = getApplications ( ) . getRegisteredApplications ( instance . getAppName ( ) ) ; if ( existingApp == null ) { getApplications ( ) . addApplication ( app ) ; } logger . debug ( "Added instance {} to the existing apps " , instance . getId ( ) ) ; getApplications ( ) . getRegisteredApplications ( instance . getAppName ( ) ) . addInstance ( instance ) ; } else if ( ActionType . MODIFIED . equals ( instance . getActionType ( ) ) ) { Application existingApp = getApplications ( ) . getRegisteredApplications ( instance . getAppName ( ) ) ; if ( existingApp == null ) { getApplications ( ) . addApplication ( app ) ; } logger . debug ( "Modified instance {} to the existing apps " , instance . getId ( ) ) ; getApplications ( ) . getRegisteredApplications ( instance . getAppName ( ) ) . addInstance ( instance ) ; } else if ( ActionType . DELETED . equals ( instance . getActionType ( ) ) ) { Application existingApp = getApplications ( ) . getRegisteredApplications ( instance . getAppName ( ) ) ; if ( existingApp == null ) { getApplications ( ) . addApplication ( app ) ; } logger . debug ( "Deleted instance {} to the existing apps " , instance . getId ( ) ) ; getApplications ( ) . getRegisteredApplications ( instance . getAppName ( ) ) . removeInstance ( instance ) ; } } } logger . debug ( "The total number of instances fetched by the delta processor : {}" , deltaCount ) ; } | Updates the delta information fetches from the eureka server into the local cache . |
17,218 | private void closeResponse ( ClientResponse response ) { if ( response != null ) { try { response . close ( ) ; } catch ( Throwable th ) { logger . error ( "Cannot release response resource :" , th ) ; } } } | Close HTTP response object and its respective resources . |
17,219 | public boolean storeFullRegistry ( ) { long currentGeneration = fetchRegistryGeneration . get ( ) ; Applications apps = fetchRemoteRegistry ( false ) ; if ( apps == null ) { logger . error ( "The application is null for some reason. Not storing this information" ) ; } else if ( fetchRegistryGeneration . compareAndSet ( currentGeneration , currentGeneration + 1 ) ) { applications . set ( apps ) ; applicationsDelta . set ( apps ) ; logger . info ( "Successfully updated registry with the latest content" ) ; return true ; } else { logger . warn ( "Not updating applications as another thread is updating it already" ) ; } return false ; } | Gets the full registry information from the eureka server and stores it locally . |
17,220 | private Applications fetchRemoteRegistry ( boolean delta ) { logger . info ( "Getting instance registry info from the eureka server : {} , delta : {}" , this . remoteRegionURL , delta ) ; if ( shouldUseExperimentalTransport ( ) ) { try { EurekaHttpResponse < Applications > httpResponse = delta ? eurekaHttpClient . getDelta ( ) : eurekaHttpClient . getApplications ( ) ; int httpStatus = httpResponse . getStatusCode ( ) ; if ( httpStatus >= 200 && httpStatus < 300 ) { logger . debug ( "Got the data successfully : {}" , httpStatus ) ; return httpResponse . getEntity ( ) ; } logger . warn ( "Cannot get the data from {} : {}" , this . remoteRegionURL , httpStatus ) ; } catch ( Throwable t ) { logger . error ( "Can't get a response from {}" , this . remoteRegionURL , t ) ; } } else { ClientResponse response = null ; try { String urlPath = delta ? "apps/delta" : "apps/" ; response = discoveryApacheClient . resource ( this . remoteRegionURL + urlPath ) . accept ( MediaType . APPLICATION_JSON_TYPE ) . get ( ClientResponse . class ) ; int httpStatus = response . getStatus ( ) ; if ( httpStatus >= 200 && httpStatus < 300 ) { logger . debug ( "Got the data successfully : {}" , httpStatus ) ; return response . getEntity ( Applications . class ) ; } logger . warn ( "Cannot get the data from {} : {}" , this . remoteRegionURL , httpStatus ) ; } catch ( Throwable t ) { logger . error ( "Can't get a response from {}" , this . remoteRegionURL , t ) ; } finally { closeResponse ( response ) ; } } return null ; } | Fetch registry information from the remote region . |
17,221 | private boolean reconcileAndLogDifference ( Applications delta , String reconcileHashCode ) throws Throwable { logger . warn ( "The Reconcile hashcodes do not match, client : {}, server : {}. Getting the full registry" , reconcileHashCode , delta . getAppsHashCode ( ) ) ; long currentGeneration = fetchRegistryGeneration . get ( ) ; Applications apps = this . fetchRemoteRegistry ( false ) ; if ( apps == null ) { logger . error ( "The application is null for some reason. Not storing this information" ) ; return false ; } if ( fetchRegistryGeneration . compareAndSet ( currentGeneration , currentGeneration + 1 ) ) { applications . set ( apps ) ; applicationsDelta . set ( apps ) ; logger . warn ( "The Reconcile hashcodes after complete sync up, client : {}, server : {}." , getApplications ( ) . getReconcileHashCode ( ) , delta . getAppsHashCode ( ) ) ; return true ; } else { logger . warn ( "Not setting the applications map as another thread has advanced the update generation" ) ; return true ; } } | Reconciles the delta information fetched to see if the hashcodes match . |
17,222 | private void logTotalInstances ( ) { int totInstances = 0 ; for ( Application application : getApplications ( ) . getRegisteredApplications ( ) ) { totInstances += application . getInstancesAsIsFromEureka ( ) . size ( ) ; } logger . debug ( "The total number of all instances in the client now is {}" , totInstances ) ; } | Logs the total number of non - filtered instances stored locally . |
17,223 | public static List < String > getDiscoveryServiceUrls ( EurekaClientConfig clientConfig , String zone , ServiceUrlRandomizer randomizer ) { boolean shouldUseDns = clientConfig . shouldUseDnsForFetchingServiceUrls ( ) ; if ( shouldUseDns ) { return getServiceUrlsFromDNS ( clientConfig , zone , clientConfig . shouldPreferSameZoneEureka ( ) , randomizer ) ; } return getServiceUrlsFromConfig ( clientConfig , zone , clientConfig . shouldPreferSameZoneEureka ( ) ) ; } | Get the list of all eureka service urls for the eureka client to talk to . |
17,224 | public static String getRegion ( EurekaClientConfig clientConfig ) { String region = clientConfig . getRegion ( ) ; if ( region == null ) { region = DEFAULT_REGION ; } region = region . trim ( ) . toLowerCase ( ) ; return region ; } | Get the region that this particular instance is in . |
17,225 | private static int getZoneOffset ( String myZone , boolean preferSameZone , String [ ] availZones ) { for ( int i = 0 ; i < availZones . length ; i ++ ) { if ( myZone != null && ( availZones [ i ] . equalsIgnoreCase ( myZone . trim ( ) ) == preferSameZone ) ) { return i ; } } logger . warn ( "DISCOVERY: Could not pick a zone based on preferred zone settings. My zone - {}," + " preferSameZone - {}. Defaulting to {}" , myZone , preferSameZone , availZones [ 0 ] ) ; return 0 ; } | Gets the zone to pick up for this instance . |
17,226 | private static boolean isSupportedCharset ( MediaType mediaType ) { Map < String , String > parameters = mediaType . getParameters ( ) ; if ( parameters == null || parameters . isEmpty ( ) ) { return true ; } String charset = parameters . get ( "charset" ) ; return charset == null || "UTF-8" . equalsIgnoreCase ( charset ) || "ISO-8859-1" . equalsIgnoreCase ( charset ) ; } | As content is cached we expect both ends use UTF - 8 always . If no content charset encoding is explicitly defined UTF - 8 is assumed as a default . As legacy clients may use ISO 8859 - 1 we accept it as well although result may be unspecified if characters out of ASCII 0 - 127 range are used . |
17,227 | public void shutdown ( ) { try { DefaultMonitorRegistry . getInstance ( ) . unregister ( Monitors . newObjectMonitor ( this ) ) ; } catch ( Throwable t ) { logger . error ( "Cannot shutdown monitor registry" , t ) ; } try { peerEurekaNodes . shutdown ( ) ; } catch ( Throwable t ) { logger . error ( "Cannot shutdown ReplicaAwareInstanceRegistry" , t ) ; } numberOfReplicationsLastMin . stop ( ) ; super . shutdown ( ) ; } | Perform all cleanup and shutdown operations . |
17,228 | public int syncUp ( ) { int count = 0 ; for ( int i = 0 ; ( ( i < serverConfig . getRegistrySyncRetries ( ) ) && ( count == 0 ) ) ; i ++ ) { if ( i > 0 ) { try { Thread . sleep ( serverConfig . getRegistrySyncRetryWaitMs ( ) ) ; } catch ( InterruptedException e ) { logger . warn ( "Interrupted during registry transfer.." ) ; break ; } } Applications apps = eurekaClient . getApplications ( ) ; for ( Application app : apps . getRegisteredApplications ( ) ) { for ( InstanceInfo instance : app . getInstances ( ) ) { try { if ( isRegisterable ( instance ) ) { register ( instance , instance . getLeaseInfo ( ) . getDurationInSecs ( ) , true ) ; count ++ ; } } catch ( Throwable t ) { logger . error ( "During DS init copy" , t ) ; } } } } return count ; } | Populates the registry information from a peer eureka node . This operation fails over to other nodes until the list is exhausted if the communication fails . |
17,229 | @ com . netflix . servo . annotations . Monitor ( name = "isBelowRenewThreshold" , description = "0 = false, 1 = true" , type = com . netflix . servo . annotations . DataSourceType . GAUGE ) public int isBelowRenewThresold ( ) { if ( ( getNumOfRenewsInLastMin ( ) <= numberOfRenewsPerMinThreshold ) && ( ( this . startupTime > 0 ) && ( System . currentTimeMillis ( ) > this . startupTime + ( serverConfig . getWaitTimeInMsWhenSyncEmpty ( ) ) ) ) ) { return 1 ; } else { return 0 ; } } | Checks if the number of renewals is lesser than threshold . |
17,230 | public boolean isRegisterable ( InstanceInfo instanceInfo ) { DataCenterInfo datacenterInfo = instanceInfo . getDataCenterInfo ( ) ; String serverRegion = clientConfig . getRegion ( ) ; if ( AmazonInfo . class . isInstance ( datacenterInfo ) ) { AmazonInfo info = AmazonInfo . class . cast ( instanceInfo . getDataCenterInfo ( ) ) ; String availabilityZone = info . get ( MetaDataKey . availabilityZone ) ; if ( availabilityZone == null && US_EAST_1 . equalsIgnoreCase ( serverRegion ) ) { return true ; } else if ( ( availabilityZone != null ) && ( availabilityZone . contains ( serverRegion ) ) ) { return true ; } } return true ; } | Checks if an instance is registerable in this region . Instances from other regions are rejected . |
17,231 | private void replicateToPeers ( Action action , String appName , String id , InstanceInfo info , InstanceStatus newStatus , boolean isReplication ) { Stopwatch tracer = action . getTimer ( ) . start ( ) ; try { if ( isReplication ) { numberOfReplicationsLastMin . increment ( ) ; } if ( peerEurekaNodes == Collections . EMPTY_LIST || isReplication ) { return ; } for ( final PeerEurekaNode node : peerEurekaNodes . getPeerEurekaNodes ( ) ) { if ( peerEurekaNodes . isThisMyUrl ( node . getServiceUrl ( ) ) ) { continue ; } replicateInstanceActionsToPeers ( action , appName , id , info , newStatus , node ) ; } } finally { tracer . stop ( ) ; } } | Replicates all eureka actions to peer eureka nodes except for replication traffic to this node . |
17,232 | private void replicateInstanceActionsToPeers ( Action action , String appName , String id , InstanceInfo info , InstanceStatus newStatus , PeerEurekaNode node ) { try { InstanceInfo infoFromRegistry = null ; CurrentRequestVersion . set ( Version . V2 ) ; switch ( action ) { case Cancel : node . cancel ( appName , id ) ; break ; case Heartbeat : InstanceStatus overriddenStatus = overriddenInstanceStatusMap . get ( id ) ; infoFromRegistry = getInstanceByAppAndId ( appName , id , false ) ; node . heartbeat ( appName , id , infoFromRegistry , overriddenStatus , false ) ; break ; case Register : node . register ( info ) ; break ; case StatusUpdate : infoFromRegistry = getInstanceByAppAndId ( appName , id , false ) ; node . statusUpdate ( appName , id , newStatus , infoFromRegistry ) ; break ; case DeleteStatusOverride : infoFromRegistry = getInstanceByAppAndId ( appName , id , false ) ; node . deleteStatusOverride ( appName , id , infoFromRegistry ) ; break ; } } catch ( Throwable t ) { logger . error ( "Cannot replicate information to {} for action {}" , node . getServiceUrl ( ) , action . name ( ) , t ) ; } } | Replicates all instance changes to peer eureka nodes except for replication traffic to this node . |
17,233 | private void replicateASGInfoToReplicaNodes ( final String asgName , final ASGStatus newStatus , final PeerEurekaNode node ) { CurrentRequestVersion . set ( Version . V2 ) ; try { node . statusUpdate ( asgName , newStatus ) ; } catch ( Throwable e ) { logger . error ( "Cannot replicate ASG status information to {}" , node . getServiceUrl ( ) , e ) ; } } | Replicates all ASG status changes to peer eureka nodes except for replication traffic to this node . |
17,234 | public void clearRegistry ( ) { overriddenInstanceStatusMap . clear ( ) ; recentCanceledQueue . clear ( ) ; recentRegisteredQueue . clear ( ) ; recentlyChangedQueue . clear ( ) ; registry . clear ( ) ; } | Completely clear the registry . |
17,235 | public boolean cancel ( String appName , String id , boolean isReplication ) { return internalCancel ( appName , id , isReplication ) ; } | Cancels the registration of an instance . |
17,236 | public boolean renew ( String appName , String id , boolean isReplication ) { RENEW . increment ( isReplication ) ; Map < String , Lease < InstanceInfo > > gMap = registry . get ( appName ) ; Lease < InstanceInfo > leaseToRenew = null ; if ( gMap != null ) { leaseToRenew = gMap . get ( id ) ; } if ( leaseToRenew == null ) { RENEW_NOT_FOUND . increment ( isReplication ) ; logger . warn ( "DS: Registry: lease doesn't exist, registering resource: {} - {}" , appName , id ) ; return false ; } else { InstanceInfo instanceInfo = leaseToRenew . getHolder ( ) ; if ( instanceInfo != null ) { InstanceStatus overriddenInstanceStatus = this . getOverriddenInstanceStatus ( instanceInfo , leaseToRenew , isReplication ) ; if ( overriddenInstanceStatus == InstanceStatus . UNKNOWN ) { logger . info ( "Instance status UNKNOWN possibly due to deleted override for instance {}" + "; re-register required" , instanceInfo . getId ( ) ) ; RENEW_NOT_FOUND . increment ( isReplication ) ; return false ; } if ( ! instanceInfo . getStatus ( ) . equals ( overriddenInstanceStatus ) ) { logger . info ( "The instance status {} is different from overridden instance status {} for instance {}. " + "Hence setting the status to overridden status" , instanceInfo . getStatus ( ) . name ( ) , instanceInfo . getOverriddenStatus ( ) . name ( ) , instanceInfo . getId ( ) ) ; instanceInfo . setStatusWithoutDirty ( overriddenInstanceStatus ) ; } } renewsLastMin . increment ( ) ; leaseToRenew . renew ( ) ; return true ; } } | Marks the given instance of the given app name as renewed and also marks whether it originated from replication . |
17,237 | public void storeOverriddenStatusIfRequired ( String appName , String id , InstanceStatus overriddenStatus ) { InstanceStatus instanceStatus = overriddenInstanceStatusMap . get ( id ) ; if ( ( instanceStatus == null ) || ( ! overriddenStatus . equals ( instanceStatus ) ) ) { logger . info ( "Adding overridden status for instance id {} and the value is {}" , id , overriddenStatus . name ( ) ) ; overriddenInstanceStatusMap . put ( id , overriddenStatus ) ; InstanceInfo instanceInfo = this . getInstanceByAppAndId ( appName , id , false ) ; instanceInfo . setOverriddenStatus ( overriddenStatus ) ; logger . info ( "Set the overridden status for instance (appname:{}, id:{}} and the value is {} " , appName , id , overriddenStatus . name ( ) ) ; } } | Stores overridden status if it is not already there . This happens during a reconciliation process during renewal requests . |
17,238 | 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 ( ) ; 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 . setStatusWithoutDirty ( newStatus ) ; long replicaDirtyTimestamp = 0 ; if ( lastDirtyTimestamp != null ) { replicaDirtyTimestamp = Long . valueOf ( lastDirtyTimestamp ) ; } 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 ( ) ; } } | Removes status override for a give instance . |
17,239 | public Application getApplication ( String appName ) { boolean disableTransparentFallback = serverConfig . disableTransparentFallbackToOtherRegion ( ) ; return this . getApplication ( appName , ! disableTransparentFallback ) ; } | Returns the given app that is in this instance only falling back to other regions transparently only if specified in this client configuration . |
17,240 | 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 ; } | Get application information . |
17,241 | @ com . netflix . servo . annotations . Monitor ( name = "numOfRenewsInLastMin" , description = "Number of total heartbeats received in the last minute" , type = DataSourceType . GAUGE ) public long getNumOfRenewsInLastMin ( ) { return renewsLastMin . getCount ( ) ; } | Servo route ; do not call . |
17,242 | @ com . netflix . servo . annotations . Monitor ( name = "numOfRenewsPerMinThreshold" , type = DataSourceType . GAUGE ) public int getNumOfRenewsPerMinThreshold ( ) { return numberOfRenewsPerMinThreshold ; } | Gets the threshold for the renewals per minute . |
17,243 | public List < Pair < Long , String > > getLastNRegisteredInstances ( ) { List < Pair < Long , String > > list = new ArrayList < Pair < Long , String > > ( ) ; synchronized ( recentRegisteredQueue ) { for ( Pair < Long , String > aRecentRegisteredQueue : recentRegisteredQueue ) { list . add ( aRecentRegisteredQueue ) ; } } Collections . reverse ( list ) ; return list ; } | Get the N instances that are most recently registered . |
17,244 | public List < Pair < Long , String > > getLastNCanceledInstances ( ) { List < Pair < Long , String > > list = new ArrayList < Pair < Long , String > > ( ) ; synchronized ( recentCanceledQueue ) { for ( Pair < Long , String > aRecentCanceledQueue : recentCanceledQueue ) { list . add ( aRecentCanceledQueue ) ; } } Collections . reverse ( list ) ; return list ; } | Get the N instances that have most recently canceled . |
17,245 | private void handleEIPBinding ( ) throws InterruptedException { int retries = serverConfig . getEIPBindRebindRetries ( ) ; for ( int i = 0 ; i < retries ; i ++ ) { try { if ( isEIPBound ( ) ) { break ; } else { bindEIP ( ) ; } } catch ( Throwable e ) { logger . error ( "Cannot bind to EIP" , e ) ; Thread . sleep ( EIP_BIND_SLEEP_TIME_MS ) ; } } timer . schedule ( new EIPBindingTask ( ) , serverConfig . getEIPBindingRetryIntervalMsWhenUnbound ( ) ) ; } | Handles EIP binding process in AWS Cloud . |
17,246 | public boolean isEIPBound ( ) { InstanceInfo myInfo = applicationInfoManager . getInfo ( ) ; String myInstanceId = ( ( AmazonInfo ) myInfo . getDataCenterInfo ( ) ) . get ( MetaDataKey . instanceId ) ; String myZone = ( ( AmazonInfo ) myInfo . getDataCenterInfo ( ) ) . get ( MetaDataKey . availabilityZone ) ; String myPublicIP = ( ( AmazonInfo ) myInfo . getDataCenterInfo ( ) ) . get ( MetaDataKey . publicIpv4 ) ; Collection < String > candidateEIPs = getCandidateEIPs ( myInstanceId , myZone ) ; for ( String eipEntry : candidateEIPs ) { if ( eipEntry . equals ( myPublicIP ) ) { logger . info ( "My instance {} seems to be already associated with the public ip {}" , myInstanceId , myPublicIP ) ; return true ; } } return false ; } | Checks if an EIP is already bound to the instance . |
17,247 | public void bindEIP ( ) { InstanceInfo myInfo = applicationInfoManager . getInfo ( ) ; String myInstanceId = ( ( AmazonInfo ) myInfo . getDataCenterInfo ( ) ) . get ( MetaDataKey . instanceId ) ; String myZone = ( ( AmazonInfo ) myInfo . getDataCenterInfo ( ) ) . get ( MetaDataKey . availabilityZone ) ; Collection < String > candidateEIPs = getCandidateEIPs ( myInstanceId , myZone ) ; AmazonEC2 ec2Service = getEC2Service ( ) ; boolean isMyinstanceAssociatedWithEIP = false ; Address selectedEIP = null ; for ( String eipEntry : candidateEIPs ) { try { String associatedInstanceId ; DescribeAddressesRequest describeAddressRequest = new DescribeAddressesRequest ( ) . withPublicIps ( eipEntry ) ; DescribeAddressesResult result = ec2Service . describeAddresses ( describeAddressRequest ) ; if ( ( result . getAddresses ( ) != null ) && ( ! result . getAddresses ( ) . isEmpty ( ) ) ) { Address eipAddress = result . getAddresses ( ) . get ( 0 ) ; associatedInstanceId = eipAddress . getInstanceId ( ) ; if ( ( ( associatedInstanceId == null ) || ( associatedInstanceId . isEmpty ( ) ) ) ) { if ( selectedEIP == null ) { selectedEIP = eipAddress ; } } else if ( isMyinstanceAssociatedWithEIP = ( associatedInstanceId . equals ( myInstanceId ) ) ) { selectedEIP = eipAddress ; break ; } else { logger . warn ( "The selected EIP {} is associated with another instance {} according to AWS," + " hence skipping this" , eipEntry , associatedInstanceId ) ; } } } catch ( Throwable t ) { logger . error ( "Failed to bind elastic IP: {} to {}" , eipEntry , myInstanceId , t ) ; } } if ( null != selectedEIP ) { String publicIp = selectedEIP . getPublicIp ( ) ; if ( ! isMyinstanceAssociatedWithEIP ) { AssociateAddressRequest associateAddressRequest = new AssociateAddressRequest ( ) . withInstanceId ( myInstanceId ) ; String domain = selectedEIP . getDomain ( ) ; if ( "vpc" . equals ( domain ) ) { associateAddressRequest . setAllocationId ( selectedEIP . getAllocationId ( ) ) ; } else { associateAddressRequest . setPublicIp ( publicIp ) ; } ec2Service . associateAddress ( associateAddressRequest ) ; logger . info ( "\n\n\nAssociated {} running in zone: {} to elastic IP: {}" , myInstanceId , myZone , publicIp ) ; } logger . info ( "My instance {} seems to be already associated with the EIP {}" , myInstanceId , publicIp ) ; } else { logger . info ( "No EIP is free to be associated with this instance. Candidate EIPs are: {}" , candidateEIPs ) ; } } | Checks if an EIP is bound and optionally binds the EIP . |
17,248 | public void unbindEIP ( ) throws Exception { InstanceInfo myInfo = applicationInfoManager . getInfo ( ) ; String myPublicIP = null ; if ( myInfo != null && myInfo . getDataCenterInfo ( ) . getName ( ) == Name . Amazon ) { myPublicIP = ( ( AmazonInfo ) myInfo . getDataCenterInfo ( ) ) . get ( MetaDataKey . publicIpv4 ) ; if ( myPublicIP == null ) { logger . info ( "Instance is not associated with an EIP. Will not try to unbind" ) ; return ; } try { AmazonEC2 ec2Service = getEC2Service ( ) ; DescribeAddressesRequest describeAddressRequest = new DescribeAddressesRequest ( ) . withPublicIps ( myPublicIP ) ; DescribeAddressesResult result = ec2Service . describeAddresses ( describeAddressRequest ) ; if ( ( result . getAddresses ( ) != null ) && ( ! result . getAddresses ( ) . isEmpty ( ) ) ) { Address eipAddress = result . getAddresses ( ) . get ( 0 ) ; DisassociateAddressRequest dissociateRequest = new DisassociateAddressRequest ( ) ; String domain = eipAddress . getDomain ( ) ; if ( "vpc" . equals ( domain ) ) { dissociateRequest . setAssociationId ( eipAddress . getAssociationId ( ) ) ; } else { dissociateRequest . setPublicIp ( eipAddress . getPublicIp ( ) ) ; } ec2Service . disassociateAddress ( dissociateRequest ) ; logger . info ( "Dissociated the EIP {} from this instance" , myPublicIP ) ; } } catch ( Throwable e ) { throw new RuntimeException ( "Cannot dissociate address from this instance" , e ) ; } } } | Unbind the EIP that this instance is associated with . |
17,249 | public Collection < String > getCandidateEIPs ( String myInstanceId , String myZone ) { if ( myZone == null ) { myZone = "us-east-1d" ; } Collection < String > eipCandidates = clientConfig . shouldUseDnsForFetchingServiceUrls ( ) ? getEIPsForZoneFromDNS ( myZone ) : getEIPsForZoneFromConfig ( myZone ) ; if ( eipCandidates == null || eipCandidates . size ( ) == 0 ) { throw new RuntimeException ( "Could not get any elastic ips from the EIP pool for zone :" + myZone ) ; } return eipCandidates ; } | Get the list of EIPs in the order of preference depending on instance zone . |
17,250 | private Collection < String > getEIPsForZoneFromConfig ( String myZone ) { List < String > ec2Urls = clientConfig . getEurekaServerServiceUrls ( myZone ) ; return getEIPsFromServiceUrls ( ec2Urls ) ; } | Get the list of EIPs from the configuration . |
17,251 | private Collection < String > getEIPsFromServiceUrls ( List < String > ec2Urls ) { List < String > returnedUrls = new ArrayList < String > ( ) ; String region = clientConfig . getRegion ( ) ; String regionPhrase = "" ; if ( ! US_EAST_1 . equals ( region ) ) { regionPhrase = "." + region ; } for ( String cname : ec2Urls ) { int beginIndex = cname . indexOf ( "ec2-" ) ; if ( - 1 < beginIndex ) { int endIndex = cname . indexOf ( regionPhrase + ".compute" ) ; String eipStr = cname . substring ( beginIndex + 4 , endIndex ) ; String eip = eipStr . replaceAll ( "\\-" , "." ) ; returnedUrls . add ( eip ) ; } } return returnedUrls ; } | Get the list of EIPs from the ec2 urls . |
17,252 | private Collection < String > getEIPsForZoneFromDNS ( String myZone ) { List < String > ec2Urls = EndpointUtils . getServiceUrlsFromDNS ( clientConfig , myZone , true , new EndpointUtils . InstanceInfoBasedUrlRandomizer ( applicationInfoManager . getInfo ( ) ) ) ; return getEIPsFromServiceUrls ( ec2Urls ) ; } | Get the list of EIPS from the DNS . |
17,253 | private AmazonEC2 getEC2Service ( ) { String aWSAccessId = serverConfig . getAWSAccessId ( ) ; String aWSSecretKey = serverConfig . getAWSSecretKey ( ) ; AmazonEC2 ec2Service ; if ( null != aWSAccessId && ! "" . equals ( aWSAccessId ) && null != aWSSecretKey && ! "" . equals ( aWSSecretKey ) ) { ec2Service = new AmazonEC2Client ( new BasicAWSCredentials ( aWSAccessId , aWSSecretKey ) ) ; } else { ec2Service = new AmazonEC2Client ( new InstanceProfileCredentialsProvider ( ) ) ; } String region = clientConfig . getRegion ( ) ; region = region . trim ( ) . toLowerCase ( ) ; ec2Service . setEndpoint ( "ec2." + region + ".amazonaws.com" ) ; return ec2Service ; } | Gets the EC2 service object to call AWS APIs . |
17,254 | public void addInstance ( InstanceInfo i ) { instancesMap . put ( i . getId ( ) , i ) ; synchronized ( instances ) { instances . remove ( i ) ; instances . add ( i ) ; isDirty = true ; } } | Add the given instance info the list . |
17,255 | private static void failFastOnInitCheck ( EurekaClientConfig clientConfig , String msg ) { if ( "true" . equals ( clientConfig . getExperimental ( "clientTransportFailFastOnInit" ) ) ) { throw new RuntimeException ( msg ) ; } } | potential future feature guarding with experimental flag for now |
17,256 | public void contextInitialized ( ServletContextEvent event ) { try { initEurekaEnvironment ( ) ; initEurekaServerContext ( ) ; ServletContext sc = event . getServletContext ( ) ; sc . setAttribute ( EurekaServerContext . class . getName ( ) , serverContext ) ; } catch ( Throwable e ) { logger . error ( "Cannot bootstrap eureka server :" , e ) ; throw new RuntimeException ( "Cannot bootstrap eureka server :" , e ) ; } } | Initializes Eureka including syncing up with other Eureka peers and publishing the registry . |
17,257 | protected void initEurekaServerContext ( ) throws Exception { EurekaServerConfig eurekaServerConfig = new DefaultEurekaServerConfig ( ) ; JsonXStream . getInstance ( ) . registerConverter ( new V1AwareInstanceInfoConverter ( ) , XStream . PRIORITY_VERY_HIGH ) ; XmlXStream . getInstance ( ) . registerConverter ( new V1AwareInstanceInfoConverter ( ) , XStream . PRIORITY_VERY_HIGH ) ; logger . info ( "Initializing the eureka client..." ) ; logger . info ( eurekaServerConfig . getJsonCodecName ( ) ) ; ServerCodecs serverCodecs = new DefaultServerCodecs ( eurekaServerConfig ) ; ApplicationInfoManager applicationInfoManager = null ; if ( eurekaClient == null ) { EurekaInstanceConfig instanceConfig = isCloud ( ConfigurationManager . getDeploymentContext ( ) ) ? new CloudInstanceConfig ( ) : new MyDataCenterInstanceConfig ( ) ; applicationInfoManager = new ApplicationInfoManager ( instanceConfig , new EurekaConfigBasedInstanceInfoProvider ( instanceConfig ) . get ( ) ) ; EurekaClientConfig eurekaClientConfig = new DefaultEurekaClientConfig ( ) ; eurekaClient = new DiscoveryClient ( applicationInfoManager , eurekaClientConfig ) ; } else { applicationInfoManager = eurekaClient . getApplicationInfoManager ( ) ; } PeerAwareInstanceRegistry registry ; if ( isAws ( applicationInfoManager . getInfo ( ) ) ) { registry = new AwsInstanceRegistry ( eurekaServerConfig , eurekaClient . getEurekaClientConfig ( ) , serverCodecs , eurekaClient ) ; awsBinder = new AwsBinderDelegate ( eurekaServerConfig , eurekaClient . getEurekaClientConfig ( ) , registry , applicationInfoManager ) ; awsBinder . start ( ) ; } else { registry = new PeerAwareInstanceRegistryImpl ( eurekaServerConfig , eurekaClient . getEurekaClientConfig ( ) , serverCodecs , eurekaClient ) ; } PeerEurekaNodes peerEurekaNodes = getPeerEurekaNodes ( registry , eurekaServerConfig , eurekaClient . getEurekaClientConfig ( ) , serverCodecs , applicationInfoManager ) ; serverContext = new DefaultEurekaServerContext ( eurekaServerConfig , serverCodecs , registry , peerEurekaNodes , applicationInfoManager ) ; EurekaServerContextHolder . initialize ( serverContext ) ; serverContext . initialize ( ) ; logger . info ( "Initialized server context" ) ; int registryCount = registry . syncUp ( ) ; registry . openForTraffic ( applicationInfoManager , registryCount ) ; EurekaMonitors . registerAllStats ( ) ; } | init hook for server context . Override for custom logic . |
17,258 | public void contextDestroyed ( ServletContextEvent event ) { try { logger . info ( "{} Shutting down Eureka Server.." , new Date ( ) ) ; ServletContext sc = event . getServletContext ( ) ; sc . removeAttribute ( EurekaServerContext . class . getName ( ) ) ; destroyEurekaServerContext ( ) ; destroyEurekaEnvironment ( ) ; } catch ( Throwable e ) { logger . error ( "Error shutting down eureka" , e ) ; } logger . info ( "{} Eureka Service is now shutdown..." , new Date ( ) ) ; } | Handles Eureka cleanup including shutting down all monitors and yielding all EIPs . |
17,259 | protected List < String > resolvePeerUrls ( ) { InstanceInfo myInfo = applicationInfoManager . getInfo ( ) ; String zone = InstanceInfo . getZone ( clientConfig . getAvailabilityZones ( clientConfig . getRegion ( ) ) , myInfo ) ; List < String > replicaUrls = EndpointUtils . getDiscoveryServiceUrls ( clientConfig , zone , new EndpointUtils . InstanceInfoBasedUrlRandomizer ( myInfo ) ) ; int idx = 0 ; while ( idx < replicaUrls . size ( ) ) { if ( isThisMyUrl ( replicaUrls . get ( idx ) ) ) { replicaUrls . remove ( idx ) ; } else { idx ++ ; } } return replicaUrls ; } | Resolve peer URLs . |
17,260 | public boolean isThisMyUrl ( String url ) { final String myUrlConfigured = serverConfig . getMyUrl ( ) ; if ( myUrlConfigured != null ) { return myUrlConfigured . equals ( url ) ; } return isInstanceURL ( url , applicationInfoManager . getInfo ( ) ) ; } | Checks if the given service url contains the current host which is trying to replicate . Only after the EIP binding is done the host has a chance to identify itself in the list of replica nodes and needs to take itself out of replication traffic . |
17,261 | public boolean isInstanceURL ( String url , InstanceInfo instance ) { String hostName = hostFromUrl ( url ) ; String myInfoComparator = instance . getHostName ( ) ; if ( clientConfig . getTransportConfig ( ) . applicationsResolverUseIp ( ) ) { myInfoComparator = instance . getIPAddr ( ) ; } return hostName != null && hostName . equals ( myInfoComparator ) ; } | Checks if the given service url matches the supplied instance |
17,262 | public static String join ( String ... values ) { if ( values == null || values . length == 0 ) { return null ; } StringBuilder sb = new StringBuilder ( ) ; for ( String value : values ) { sb . append ( ',' ) . append ( value ) ; } return sb . substring ( 1 ) ; } | Join all values separating them with a comma . |
17,263 | public static String resolve ( String originalHost ) { String currentHost = originalHost ; if ( isLocalOrIp ( currentHost ) ) { return originalHost ; } try { String targetHost = null ; do { Attributes attrs = getDirContext ( ) . getAttributes ( currentHost , new String [ ] { A_RECORD_TYPE , CNAME_RECORD_TYPE } ) ; Attribute attr = attrs . get ( A_RECORD_TYPE ) ; if ( attr != null ) { targetHost = attr . get ( ) . toString ( ) ; } attr = attrs . get ( CNAME_RECORD_TYPE ) ; if ( attr != null ) { currentHost = attr . get ( ) . toString ( ) ; } else { targetHost = currentHost ; } } while ( targetHost == null ) ; return targetHost ; } catch ( NamingException e ) { logger . warn ( "Cannot resolve eureka server address {}; returning original value {}" , currentHost , originalHost , e ) ; return originalHost ; } } | Resolve host name to the bottom A - Record or the latest available CNAME |
17,264 | public static List < String > resolveARecord ( String rootDomainName ) { if ( isLocalOrIp ( rootDomainName ) ) { return null ; } try { Attributes attrs = getDirContext ( ) . getAttributes ( rootDomainName , new String [ ] { A_RECORD_TYPE , CNAME_RECORD_TYPE } ) ; Attribute aRecord = attrs . get ( A_RECORD_TYPE ) ; Attribute cRecord = attrs . get ( CNAME_RECORD_TYPE ) ; if ( aRecord != null && cRecord == null ) { List < String > result = new ArrayList < > ( ) ; NamingEnumeration < String > entries = ( NamingEnumeration < String > ) aRecord . getAll ( ) ; while ( entries . hasMore ( ) ) { result . add ( entries . next ( ) ) ; } return result ; } } catch ( Exception e ) { logger . warn ( "Cannot load A-record for eureka server address {}" , rootDomainName , e ) ; return null ; } return null ; } | Look into A - record at a specific DNS address . |
17,265 | @ Path ( "{asgName}/status" ) public Response statusUpdate ( @ PathParam ( "asgName" ) String asgName , @ QueryParam ( "value" ) String newStatus , @ HeaderParam ( PeerEurekaNode . HEADER_REPLICATION ) String isReplication ) { if ( awsAsgUtil == null ) { return Response . status ( 400 ) . build ( ) ; } try { logger . info ( "Trying to update ASG Status for ASG {} to {}" , asgName , newStatus ) ; ASGStatus asgStatus = ASGStatus . valueOf ( newStatus . toUpperCase ( ) ) ; awsAsgUtil . setStatus ( asgName , ( ! ASGStatus . DISABLED . equals ( asgStatus ) ) ) ; registry . statusUpdate ( asgName , asgStatus , Boolean . valueOf ( isReplication ) ) ; logger . debug ( "Updated ASG Status for ASG {} to {}" , asgName , asgStatus ) ; } catch ( Throwable e ) { logger . error ( "Cannot update the status {} for the ASG {}" , newStatus , asgName , e ) ; return Response . serverError ( ) . build ( ) ; } return Response . ok ( ) . build ( ) ; } | Changes the status information of the ASG . |
17,266 | private boolean autoDetectEc2 ( AmazonInfoConfig amazonInfoConfig ) { try { URL url = AmazonInfo . MetaDataKey . instanceId . getURL ( null , null ) ; String id = AmazonInfoUtils . readEc2MetadataUrl ( AmazonInfo . MetaDataKey . instanceId , url , amazonInfoConfig . getConnectTimeout ( ) , amazonInfoConfig . getReadTimeout ( ) ) ; if ( id != null ) { logger . info ( "Auto detected EC2 deployment environment, instanceId = {}" , id ) ; return true ; } else { logger . info ( "Auto detected non-EC2 deployment environment, instanceId from metadata url is null" ) ; return false ; } } catch ( SocketTimeoutException e ) { logger . info ( "Auto detected non-EC2 deployment environment, connection to ec2 instance metadata url failed." ) ; } catch ( Exception e ) { logger . warn ( "Failed to auto-detect whether we are in EC2 due to unexpected exception" , e ) ; } return false ; } | best effort try to determine if we are in ec2 by trying to read the instanceId from metadata url |
17,267 | @ Path ( "batch" ) public Response batchReplication ( ReplicationList replicationList ) { try { ReplicationListResponse batchResponse = new ReplicationListResponse ( ) ; for ( ReplicationInstance instanceInfo : replicationList . getReplicationList ( ) ) { try { batchResponse . addResponse ( dispatch ( instanceInfo ) ) ; } catch ( Exception e ) { batchResponse . addResponse ( new ReplicationInstanceResponse ( Status . INTERNAL_SERVER_ERROR . getStatusCode ( ) , null ) ) ; logger . error ( "{} request processing failed for batch item {}/{}" , instanceInfo . getAction ( ) , instanceInfo . getAppName ( ) , instanceInfo . getId ( ) , e ) ; } } return Response . ok ( batchResponse ) . build ( ) ; } catch ( Throwable e ) { logger . error ( "Cannot execute batch Request" , e ) ; return Response . status ( Status . INTERNAL_SERVER_ERROR ) . build ( ) ; } } | Process batched replication events from peer eureka nodes . |
17,268 | public static < T extends EurekaEndpoint > List < T > randomize ( List < T > list ) { List < T > randomList = new ArrayList < > ( list ) ; if ( randomList . size ( ) < 2 ) { return randomList ; } Random random = new Random ( LOCAL_IPV4_ADDRESS . hashCode ( ) ) ; int last = randomList . size ( ) - 1 ; for ( int i = 0 ; i < last ; i ++ ) { int pos = random . nextInt ( randomList . size ( ) - i ) ; if ( pos != i ) { Collections . swap ( randomList , i , pos ) ; } } return randomList ; } | Randomize server list using local IPv4 address hash as a seed . |
17,269 | public static ObjectReader init ( ObjectReader reader ) { return reader . withAttribute ( ATTR_STRING_CACHE , new DeserializerStringCache ( new HashMap < CharBuffer , String > ( 2048 ) , new LinkedHashMap < CharBuffer , String > ( 4096 , 0.75f , true ) { protected boolean removeEldestEntry ( Entry < CharBuffer , String > eldest ) { return size ( ) > LRU_LIMIT ; } } ) ) ; } | adds a new DeserializerStringCache to the passed - in ObjectReader |
17,270 | public static ObjectReader init ( ObjectReader reader , DeserializationContext context ) { return withCache ( context , cache -> { if ( cache == null ) throw new IllegalStateException ( ) ; return reader . withAttribute ( ATTR_STRING_CACHE , cache ) ; } ) ; } | adds an existing DeserializerStringCache from the DeserializationContext to an ObjectReader |
17,271 | public static DeserializerStringCache from ( DeserializationContext context ) { return withCache ( context , cache -> { if ( cache == null ) { cache = new DeserializerStringCache ( new HashMap < CharBuffer , String > ( ) , new HashMap < CharBuffer , String > ( ) ) ; } return cache ; } ) ; } | extracts a DeserializerStringCache from the DeserializationContext |
17,272 | public static void clear ( ObjectReader reader , final CacheScope scope ) { withCache ( reader , cache -> { if ( scope == CacheScope . GLOBAL_SCOPE ) { if ( debugLogEnabled ) logger . debug ( "clearing global-level cache with size {}" , cache . globalCache . size ( ) ) ; cache . globalCache . clear ( ) ; } if ( debugLogEnabled ) logger . debug ( "clearing app-level serialization cache with size {}" , cache . applicationCache . size ( ) ) ; cache . applicationCache . clear ( ) ; return null ; } ) ; } | clears cache entries in the given scope from the specified ObjectReader . Always clears app - scoped entries . |
17,273 | public static void clear ( DeserializationContext context , CacheScope scope ) { withCache ( context , cache -> { if ( scope == CacheScope . GLOBAL_SCOPE ) { if ( debugLogEnabled ) logger . debug ( "clearing global-level serialization cache with size {}" , cache . globalCache . size ( ) ) ; cache . globalCache . clear ( ) ; } if ( debugLogEnabled ) logger . debug ( "clearing app-level serialization cache with size {}" , cache . applicationCache . size ( ) ) ; cache . applicationCache . clear ( ) ; return null ; } ) ; } | clears cache entries in the given scope from the specified DeserializationContext . Always clears app - scoped entries . |
17,274 | public String apply ( final JsonParser jp ) throws IOException { return apply ( jp , CacheScope . APPLICATION_SCOPE , null ) ; } | returns a String read from the JsonParser argument s current position . The returned value may be interned at the app scope to reduce heap consumption |
17,275 | public String apply ( final JsonParser jp , CacheScope cacheScope , Supplier < String > source ) throws IOException { return apply ( CharBuffer . wrap ( jp , source ) , cacheScope ) ; } | returns a String read from the JsonParser argument s current position . The returned value may be interned at the given cacheScope to reduce heap consumption |
17,276 | public String apply ( CharBuffer charValue , CacheScope cacheScope ) { int keyLength = charValue . length ( ) ; if ( ( lengthLimit < 0 || keyLength <= lengthLimit ) ) { Map < CharBuffer , String > cache = ( cacheScope == CacheScope . GLOBAL_SCOPE ) ? globalCache : applicationCache ; String value = cache . get ( charValue ) ; if ( value == null ) { value = charValue . consume ( ( k , v ) -> { cache . put ( k , v ) ; } ) ; } else { } return value ; } return charValue . toString ( ) ; } | returns a object of type T that may be interned at the specified scope to reduce heap consumption |
17,277 | public String apply ( final String stringValue , CacheScope cacheScope ) { if ( stringValue != null && ( lengthLimit < 0 || stringValue . length ( ) <= lengthLimit ) ) { return ( String ) ( cacheScope == CacheScope . GLOBAL_SCOPE ? globalCache : applicationCache ) . computeIfAbsent ( CharBuffer . wrap ( stringValue ) , s -> { logger . trace ( " (string) writing new interned value {} into {} cache scope" , stringValue , cacheScope ) ; return stringValue ; } ) ; } return stringValue ; } | returns a String that may be interned at the given scope to reduce heap consumption |
17,278 | @ Path ( "{id}" ) public InstanceResource getInstanceInfo ( @ PathParam ( "id" ) String id ) { return new InstanceResource ( this , id , serverConfig , registry ) ; } | Gets information about a particular instance of an application . |
17,279 | public byte [ ] getGZIP ( Key key ) { Value payload = getValue ( key , shouldUseReadOnlyResponseCache ) ; if ( payload == null ) { return null ; } return payload . getGzipped ( ) ; } | Get the compressed information about the applications . |
17,280 | public void invalidate ( Key ... keys ) { for ( Key key : keys ) { logger . debug ( "Invalidating the response cache key : {} {} {} {}, {}" , key . getEntityType ( ) , key . getName ( ) , key . getVersion ( ) , key . getType ( ) , key . getEurekaAccept ( ) ) ; readWriteCacheMap . invalidate ( key ) ; Collection < Key > keysWithRegions = regionSpecificKeys . get ( key ) ; if ( null != keysWithRegions && ! keysWithRegions . isEmpty ( ) ) { for ( Key keysWithRegion : keysWithRegions ) { logger . debug ( "Invalidating the response cache key : {} {} {} {} {}" , key . getEntityType ( ) , key . getName ( ) , key . getVersion ( ) , key . getType ( ) , key . getEurekaAccept ( ) ) ; readWriteCacheMap . invalidate ( keysWithRegion ) ; } } } } | Invalidate the cache information given the list of keys . |
17,281 | private String getPayLoad ( Key key , Applications apps ) { EncoderWrapper encoderWrapper = serverCodecs . getEncoder ( key . getType ( ) , key . getEurekaAccept ( ) ) ; String result ; try { result = encoderWrapper . encode ( apps ) ; } catch ( Exception e ) { logger . error ( "Failed to encode the payload for all apps" , e ) ; return "" ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "New application cache entry {} with apps hashcode {}" , key . toStringCompact ( ) , apps . getAppsHashCode ( ) ) ; } return result ; } | Generate pay load with both JSON and XML formats for all applications . |
17,282 | private String getPayLoad ( Key key , Application app ) { if ( app == null ) { return EMPTY_PAYLOAD ; } EncoderWrapper encoderWrapper = serverCodecs . getEncoder ( key . getType ( ) , key . getEurekaAccept ( ) ) ; try { return encoderWrapper . encode ( app ) ; } catch ( Exception e ) { logger . error ( "Failed to encode the payload for application {}" , app . getName ( ) , e ) ; return "" ; } } | Generate pay load with both JSON and XML formats for a given application . |
17,283 | public void cancel ( final String appName , final String id ) throws Exception { long expiryTime = System . currentTimeMillis ( ) + maxProcessingDelayMs ; batchingDispatcher . process ( taskId ( "cancel" , appName , id ) , new InstanceReplicationTask ( targetHost , Action . Cancel , appName , id ) { public EurekaHttpResponse < Void > execute ( ) { return replicationClient . cancel ( appName , id ) ; } public void handleFailure ( int statusCode , Object responseEntity ) throws Throwable { super . handleFailure ( statusCode , responseEntity ) ; if ( statusCode == 404 ) { logger . warn ( "{}: missing entry." , getTaskName ( ) ) ; } } } , expiryTime ) ; } | Send the cancellation information of an instance to the node represented by this class . |
17,284 | public void heartbeat ( final String appName , final String id , final InstanceInfo info , final InstanceStatus overriddenStatus , boolean primeConnection ) throws Throwable { if ( primeConnection ) { replicationClient . sendHeartBeat ( appName , id , info , overriddenStatus ) ; return ; } ReplicationTask replicationTask = new InstanceReplicationTask ( targetHost , Action . Heartbeat , info , overriddenStatus , false ) { public EurekaHttpResponse < InstanceInfo > execute ( ) throws Throwable { return replicationClient . sendHeartBeat ( appName , id , info , overriddenStatus ) ; } public void handleFailure ( int statusCode , Object responseEntity ) throws Throwable { super . handleFailure ( statusCode , responseEntity ) ; if ( statusCode == 404 ) { logger . warn ( "{}: missing entry." , getTaskName ( ) ) ; if ( info != null ) { logger . warn ( "{}: cannot find instance id {} and hence replicating the instance with status {}" , getTaskName ( ) , info . getId ( ) , info . getStatus ( ) ) ; register ( info ) ; } } else if ( config . shouldSyncWhenTimestampDiffers ( ) ) { InstanceInfo peerInstanceInfo = ( InstanceInfo ) responseEntity ; if ( peerInstanceInfo != null ) { syncInstancesIfTimestampDiffers ( appName , id , info , peerInstanceInfo ) ; } } } } ; long expiryTime = System . currentTimeMillis ( ) + getLeaseRenewalOf ( info ) ; batchingDispatcher . process ( taskId ( "heartbeat" , info ) , replicationTask , expiryTime ) ; } | Send the heartbeat information of an instance to the node represented by this class . If the instance does not exist the node the instance registration information is sent again to the peer node . |
17,285 | public void statusUpdate ( final String asgName , final ASGStatus newStatus ) { long expiryTime = System . currentTimeMillis ( ) + maxProcessingDelayMs ; nonBatchingDispatcher . process ( asgName , new AsgReplicationTask ( targetHost , Action . StatusUpdate , asgName , newStatus ) { public EurekaHttpResponse < ? > execute ( ) { return replicationClient . statusUpdate ( asgName , newStatus ) ; } } , expiryTime ) ; } | Send the status information of of the ASG represented by the instance . |
17,286 | public void deleteStatusOverride ( final String appName , final String id , final InstanceInfo info ) { long expiryTime = System . currentTimeMillis ( ) + maxProcessingDelayMs ; batchingDispatcher . process ( taskId ( "deleteStatusOverride" , appName , id ) , new InstanceReplicationTask ( targetHost , Action . DeleteStatusOverride , info , null , false ) { public EurekaHttpResponse < Void > execute ( ) { return replicationClient . deleteStatusOverride ( appName , id , info ) ; } } , expiryTime ) ; } | Delete instance status override . |
17,287 | 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 ) ; if ( ! isSuccess ) { logger . warn ( "Not Found (Renew): {} - {}" , app . getName ( ) , id ) ; return Response . status ( Status . NOT_FOUND ) . build ( ) ; } Response response ; if ( lastDirtyTimestamp != null && serverConfig . shouldSyncWhenTimestampDiffers ( ) ) { response = this . validateDirtyTimestamp ( Long . valueOf ( lastDirtyTimestamp ) , isFromReplicaNode ) ; if ( response . getStatus ( ) == Response . Status . NOT_FOUND . getStatusCode ( ) && ( overriddenStatus != null ) && ! ( InstanceStatus . UNKNOWN . name ( ) . equals ( overriddenStatus ) ) && isFromReplicaNode ) { registry . storeOverriddenStatusIfRequired ( app . getAppName ( ) , id , InstanceStatus . valueOf ( overriddenStatus ) ) ; } } else { response = Response . ok ( ) . build ( ) ; } logger . debug ( "Found (Renew): {} - {}; reply status={}" , app . getName ( ) , id , response . getStatus ( ) ) ; return response ; } | A put request for renewing lease from a client instance . |
17,288 | public Response cancelLease ( @ HeaderParam ( PeerEurekaNode . HEADER_REPLICATION ) String isReplication ) { try { boolean isSuccess = registry . cancel ( app . getName ( ) , id , "true" . equals ( isReplication ) ) ; if ( isSuccess ) { logger . debug ( "Found (Cancel): {} - {}" , app . getName ( ) , id ) ; return Response . ok ( ) . build ( ) ; } else { logger . info ( "Not Found (Cancel): {} - {}" , app . getName ( ) , id ) ; return Response . status ( Status . NOT_FOUND ) . build ( ) ; } } catch ( Throwable e ) { logger . error ( "Error (cancel): {} - {}" , app . getName ( ) , id , e ) ; return Response . serverError ( ) . build ( ) ; } } | Handles cancellation of leases for this particular instance . |
17,289 | public static String getPrivateIp ( InstanceInfo instanceInfo ) { String defaultPrivateIp = null ; if ( instanceInfo . getDataCenterInfo ( ) instanceof AmazonInfo ) { defaultPrivateIp = ( ( AmazonInfo ) instanceInfo . getDataCenterInfo ( ) ) . get ( AmazonInfo . MetaDataKey . localIpv4 ) ; } if ( isNullOrEmpty ( defaultPrivateIp ) ) { defaultPrivateIp = instanceInfo . getIPAddr ( ) ; } return defaultPrivateIp ; } | return the privateIp address of the given InstanceInfo record . The record could be for the local server or a remote server . |
17,290 | public boolean isASGEnabled ( InstanceInfo instanceInfo ) { CacheKey cacheKey = new CacheKey ( getAccountId ( instanceInfo , accountId ) , instanceInfo . getASGName ( ) ) ; Boolean result = asgCache . getIfPresent ( cacheKey ) ; if ( result != null ) { return result ; } else { if ( ! serverConfig . shouldUseAwsAsgApi ( ) ) { logger . info ( ( "'{}' is not cached at the moment and won't be fetched because querying AWS ASGs " + "has been disabled via the config, returning the fallback value." ) , cacheKey ) ; return true ; } logger . info ( "Cache value for asg {} does not exist yet, async refreshing." , cacheKey . asgName ) ; asgCache . refresh ( cacheKey ) ; return true ; } } | Return the status of the ASG whether is enabled or disabled for service . The value is picked up from the cache except the very first time . |
17,291 | public void setStatus ( String asgName , boolean enabled ) { String asgAccountId = getASGAccount ( asgName ) ; asgCache . put ( new CacheKey ( asgAccountId , asgName ) , enabled ) ; } | Sets the status of the ASG . |
17,292 | private boolean isAddToLoadBalancerSuspended ( String asgAccountId , String asgName ) { AutoScalingGroup asg ; if ( asgAccountId == null || asgAccountId . equals ( accountId ) ) { asg = retrieveAutoScalingGroup ( asgName ) ; } else { asg = retrieveAutoScalingGroupCrossAccount ( asgAccountId , asgName ) ; } if ( asg == null ) { logger . warn ( "The ASG information for {} could not be found. So returning false." , asgName ) ; return false ; } return isAddToLoadBalancerSuspended ( asg ) ; } | Check if the ASG is disabled . The amazon flag AddToLoadBalancer is queried to figure out if it is or not . |
17,293 | private boolean isAddToLoadBalancerSuspended ( AutoScalingGroup asg ) { List < SuspendedProcess > suspendedProcesses = asg . getSuspendedProcesses ( ) ; for ( SuspendedProcess process : suspendedProcesses ) { if ( PROP_ADD_TO_LOAD_BALANCER . equals ( process . getProcessName ( ) ) ) { return true ; } } return false ; } | Checks if the load balancer addition is disabled or not . |
17,294 | private AutoScalingGroup retrieveAutoScalingGroup ( String asgName ) { if ( Strings . isNullOrEmpty ( asgName ) ) { logger . warn ( "null asgName specified, not attempting to retrieve AutoScalingGroup from AWS" ) ; return null ; } DescribeAutoScalingGroupsRequest request = new DescribeAutoScalingGroupsRequest ( ) . withAutoScalingGroupNames ( asgName ) ; DescribeAutoScalingGroupsResult result = awsClient . describeAutoScalingGroups ( request ) ; List < AutoScalingGroup > asgs = result . getAutoScalingGroups ( ) ; if ( asgs . isEmpty ( ) ) { return null ; } else { return asgs . get ( 0 ) ; } } | Queries AWS to get the autoscaling information given the asgName . |
17,295 | private Boolean isASGEnabledinAWS ( String asgAccountid , String asgName ) { try { Stopwatch t = this . loadASGInfoTimer . start ( ) ; boolean returnValue = ! isAddToLoadBalancerSuspended ( asgAccountid , asgName ) ; t . stop ( ) ; return returnValue ; } catch ( Throwable e ) { logger . error ( "Could not get ASG information from AWS: " , e ) ; } return Boolean . TRUE ; } | Queries AWS to see if the load balancer flag is suspended . |
17,296 | @ com . netflix . servo . annotations . Monitor ( name = "numOfElementsinASGCache" , description = "Number of elements in the ASG Cache" , type = DataSourceType . GAUGE ) public long getNumberofElementsinASGCache ( ) { return asgCache . size ( ) ; } | Gets the number of elements in the ASG cache . |
17,297 | @ com . netflix . servo . annotations . Monitor ( name = "numOfASGQueries" , description = "Number of queries made to AWS to retrieve ASG information" , type = DataSourceType . COUNTER ) public long getNumberofASGQueries ( ) { return asgCache . stats ( ) . loadCount ( ) ; } | Gets the number of ASG queries done in the period . |
17,298 | @ com . netflix . servo . annotations . Monitor ( name = "numOfASGQueryFailures" , description = "Number of queries made to AWS to retrieve ASG information and that failed" , type = DataSourceType . COUNTER ) public long getNumberofASGQueryFailures ( ) { return asgCache . stats ( ) . loadExceptionCount ( ) ; } | Gets the number of ASG queries that failed because of some reason . |
17,299 | private TimerTask getASGUpdateTask ( ) { return new TimerTask ( ) { public void run ( ) { try { if ( ! serverConfig . shouldUseAwsAsgApi ( ) ) { return ; } Set < CacheKey > cacheKeys = getCacheKeys ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Trying to refresh the keys for {}" , Arrays . toString ( cacheKeys . toArray ( ) ) ) ; } for ( CacheKey key : cacheKeys ) { try { asgCache . refresh ( key ) ; } catch ( Throwable e ) { logger . error ( "Error updating the ASG cache for {}" , key , e ) ; } } } catch ( Throwable e ) { logger . error ( "Error updating the ASG cache" , e ) ; } } } ; } | Gets the task that updates the ASG information periodically . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.