idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
1,700
public static Managed registerInjector ( final Application application , final Injector injector ) { Preconditions . checkNotNull ( application , "Application instance required" ) ; Preconditions . checkArgument ( ! INJECTORS . containsKey ( application ) , "Injector already registered for application %s" , application . getClass ( ) . getName ( ) ) ; INJECTORS . put ( application , injector ) ; return new Managed ( ) { public void start ( ) throws Exception { } public void stop ( ) throws Exception { INJECTORS . remove ( application ) ; } } ; }
Used internally to register application specific injector .
1,701
@ SuppressWarnings ( "unchecked" ) public static < T > Class < T > getInstanceClass ( final T object ) { final Class cls = object . getClass ( ) ; return cls . getName ( ) . contains ( "$$EnhancerByGuice" ) ? ( Class < T > ) cls . getSuperclass ( ) : cls ; }
Used to get correct object type even if it s guice proxy .
1,702
public void scan ( final ClassVisitor visitor ) { if ( scanned == null ) { performScan ( ) ; } for ( Class < ? > cls : scanned ) { visitor . visit ( cls ) ; } }
Scan configured classpath packages .
1,703
public static < T > List < T > removeTypes ( final List < T > list , final List < Class < ? extends T > > filter ) { final Iterator it = list . iterator ( ) ; while ( it . hasNext ( ) ) { final Class type = it . next ( ) . getClass ( ) ; if ( filter . contains ( type ) ) { it . remove ( ) ; } } return list ; }
Filter list from objects of type present in filter list .
1,704
public ConfigPath findByPath ( final String path ) { return paths . stream ( ) . filter ( it -> it . getPath ( ) . equalsIgnoreCase ( path ) ) . findFirst ( ) . orElse ( null ) ; }
Case insensitive exact match .
1,705
public List < ConfigPath > findAllRootPaths ( ) { return paths . stream ( ) . filter ( it -> ! it . getPath ( ) . contains ( DOT ) ) . collect ( Collectors . toList ( ) ) ; }
For example it would always contain logging metrics and server paths from dropwizard configuration .
1,706
public void hkManage ( final Class < ? > type ) { if ( ! JerseyBinding . isHK2Managed ( type , options . get ( JerseyExtensionsManagedByGuice ) ) ) { throw new WrongContextException ( "HK2 creates service %s which must be managed by guice." , type . getName ( ) ) ; } hkManaged . add ( type ) ; }
Called by specific HK2 lifecycle listener to check if bean is properly instantiated by HK2 .
1,707
public void guiceManage ( final Class < ? > type ) { if ( JerseyBinding . isHK2Managed ( type , options . get ( JerseyExtensionsManagedByGuice ) ) ) { throw new WrongContextException ( "Guice creates service %s which must be managed by HK2." , type . getName ( ) ) ; } guiceManaged . add ( type ) ; }
Called by specific guice provision listener to check if bean is properly instantiated by guice .
1,708
private void checkHkFirstMode ( ) { final boolean guiceyFirstMode = context . option ( JerseyExtensionsManagedByGuice ) ; if ( ! guiceyFirstMode ) { Preconditions . checkState ( context . option ( UseHkBridge ) , "HK2 management for jersey extensions is enabled by default " + "(InstallersOptions.JerseyExtensionsManagedByGuice), but HK2-guice bridge is not " + "enabled. Use GuiceyOptions.UseHkBridge option to enable bridge " + "(extra dependency is required)" ) ; } }
When HK2 management for jersey extensions is enabled by default then guice bridge must be enabled . Without it guice beans could not be used in resources and other jersey extensions . If this is expected then guice support is not needed at all .
1,709
public static void register ( final GuiceyConfigurationHook hook ) { if ( HOOKS . get ( ) == null ) { HOOKS . set ( new LinkedHashSet < > ( ) ) ; } HOOKS . get ( ) . add ( hook ) ; }
Register hook for current thread . Must be called before application initialization otherwise will not be used at all .
1,710
@ SuppressWarnings ( "unchecked" ) public static void configureModules ( final ConfigurationContext context ) { final Options options = new Options ( context . options ( ) ) ; for ( Module mod : context . getEnabledModules ( ) ) { if ( mod instanceof BootstrapAwareModule ) { ( ( BootstrapAwareModule ) mod ) . setBootstrap ( context . getBootstrap ( ) ) ; } if ( mod instanceof ConfigurationAwareModule ) { ( ( ConfigurationAwareModule ) mod ) . setConfiguration ( context . getConfiguration ( ) ) ; } if ( mod instanceof ConfigurationTreeAwareModule ) { ( ( ConfigurationTreeAwareModule ) mod ) . setConfigurationTree ( context . getConfigurationTree ( ) ) ; } if ( mod instanceof EnvironmentAwareModule ) { ( ( EnvironmentAwareModule ) mod ) . setEnvironment ( context . getEnvironment ( ) ) ; } if ( mod instanceof OptionsAwareModule ) { ( ( OptionsAwareModule ) mod ) . setOptions ( options ) ; } } }
Post - process registered modules by injecting bootstrap configuration environment and options objects .
1,711
public void activate ( ) { GuiceBridge . getGuiceBridge ( ) . initializeGuiceBridge ( locator ) ; final GuiceIntoHK2Bridge guiceBridge = locator . getService ( GuiceIntoHK2Bridge . class ) ; guiceBridge . bridgeGuiceInjector ( injector ) ; }
Activate HK2 guice bridge .
1,712
protected boolean isForceSingleton ( final Class < ? > type , final boolean hkManaged ) { return ( ( Boolean ) option ( ForceSingletonForJerseyExtensions ) ) && ! hasScopeAnnotation ( type , hkManaged ) ; }
Singleton binding should not be forced if bean has explicit scope declaration .
1,713
private boolean hasScopeAnnotation ( final Class < ? > type , final boolean hkManaged ) { boolean found = false ; for ( Annotation ann : type . getAnnotations ( ) ) { final Class < ? extends Annotation > annType = ann . annotationType ( ) ; if ( annType . isAnnotationPresent ( Scope . class ) ) { found = true ; break ; } if ( ! hkManaged && annType . isAnnotationPresent ( ScopeAnnotation . class ) ) { found = true ; break ; } } return found ; }
Checks scope annotation presence directly on bean . Base classes are not checked as scope is not inheritable .
1,714
public void registerCommands ( final List < Class < Command > > commands ) { setScope ( ConfigScope . ClasspathScan . getType ( ) ) ; for ( Class < Command > cmd : commands ) { register ( ConfigItem . Command , cmd ) ; } closeScope ( ) ; }
Register commands resolved with classpath scan .
1,715
private void applyPredicatesForRegisteredItems ( final List < PredicateHandler > predicates ) { ImmutableList . builder ( ) . addAll ( getEnabledModules ( ) ) . addAll ( getEnabledBundles ( ) ) . addAll ( getEnabledExtensions ( ) ) . addAll ( getEnabledInstallers ( ) ) . build ( ) . stream ( ) . < ItemInfo > map ( this :: getInfo ) . forEach ( item -> applyDisablePredicates ( predicates , item ) ) ; }
Disable predicate could be registered after some items registration and to make sure that predicate affects all these items - apply to all currenlty registered items .
1,716
@ SuppressWarnings ( "unchecked" ) private < T extends ItemInfoImpl > T getOrCreateInfo ( final ConfigItem type , final Object item ) { final Class < ? > itemType = getType ( item ) ; final T info ; if ( detailsHolder . containsKey ( itemType ) ) { info = ( T ) detailsHolder . get ( itemType ) ; } else { itemsHolder . put ( type , item ) ; info = type . newContainer ( itemType ) ; detailsHolder . put ( itemType , info ) ; } return info ; }
Disabled items may not be actually registered . In order to register disable info in uniform way dummy container is created .
1,717
public final OptionsConfig hideGroups ( final Class < Enum > ... groups ) { hiddenGroups . addAll ( Arrays . asList ( groups ) ) ; return this ; }
Hide option groups from reporting .
1,718
public static void overrideScope ( final Runnable action ) { override . set ( true ) ; try { action . run ( ) ; } finally { override . remove ( ) ; } }
Use to register overriding modules . Such complex approach was used because overriding modules is the only item that require additional parameter during registration . This parameter may be used in disable predicate to differentiate overriding modules from normal modules .
1,719
public final Reporter line ( final String line , final Object ... args ) { counter ++ ; wasEmptyLine = false ; message . append ( TAB ) . append ( String . format ( line , args ) ) . append ( NEWLINE ) ; return this ; }
Prints formatted line .
1,720
public String renderReport ( final ContextTreeConfig config ) { final Set < Class < ? > > scopes = service . getActiveScopes ( ! config . isHideDisables ( ) ) ; final TreeNode root = new TreeNode ( "APPLICATION" ) ; if ( ! config . getHiddenScopes ( ) . contains ( Application . getType ( ) ) ) { renderScopeContent ( config , root , Application . getType ( ) ) ; } renderSpecialScope ( config , scopes , root , "BUNDLES LOOKUP" , BundleLookup ) ; renderSpecialScope ( config , scopes , root , "DROPWIZARD BUNDLES" , DropwizardBundle ) ; renderSpecialScope ( config , scopes , root , "CLASSPATH SCAN" , ClasspathScan ) ; renderSpecialScope ( config , scopes , root , "HOOKS" , Hook ) ; final StringBuilder res = new StringBuilder ( ) . append ( Reporter . NEWLINE ) . append ( Reporter . NEWLINE ) ; root . render ( res ) ; return res . toString ( ) ; }
Renders configuration tree report according to provided config . By default report padded left with one tab . Subtrees are always padded with empty lines for better visibility .
1,721
private void renderBundle ( final ContextTreeConfig config , final TreeNode root , final Class < ? > scope , final Class < Object > bundle ) { final BundleItemInfo info = service . getData ( ) . getInfo ( bundle ) ; if ( isHidden ( config , info , scope ) ) { return ; } final List < String > markers = Lists . newArrayList ( ) ; fillCommonMarkers ( info , markers , scope ) ; final TreeNode node = new TreeNode ( RenderUtils . renderClassLine ( bundle , markers ) ) ; if ( ! isDuplicateRegistration ( info , scope ) ) { renderScopeContent ( config , node , bundle ) ; } if ( node . hasChildren ( ) || ! config . isHideEmptyBundles ( ) || ( ! config . isHideDisables ( ) && markers . contains ( IGNORED ) ) ) { root . child ( node ) ; } }
Renders bundle if allowed .
1,722
@ SuppressWarnings ( "checkstyle:BooleanExpressionComplexity" ) private boolean isHidden ( final ContextTreeConfig config , final ItemInfo info , final Class < ? > scope ) { final boolean hidden = config . getHiddenItems ( ) . contains ( info . getItemType ( ) ) ; final boolean disabled = config . isHideDisables ( ) && isDisabled ( info ) ; final boolean ignored = config . isHideDuplicateRegistrations ( ) && isDuplicateRegistration ( info , scope ) ; final boolean hiddenScope = ! isScopeVisible ( config , null , scope ) || isHiddenBundle ( config , info ) ; final boolean notUsedInstaller = config . isHideNotUsedInstallers ( ) && isNotUsedInstaller ( info ) ; return hidden || disabled || ignored || hiddenScope || notUsedInstaller ; }
Checks element visibility according to config . Universal place to check visibility for either simple config items or bundles and special scopes .
1,723
public static ConfigurationTree build ( final Bootstrap bootstrap , final Configuration configuration , final boolean introspect ) { final List < Class > roots = resolveRootTypes ( new ArrayList < > ( ) , configuration . getClass ( ) ) ; if ( introspect ) { final List < ConfigPath > content = resolvePaths ( bootstrap . getObjectMapper ( ) . getSerializationConfig ( ) , null , new ArrayList < > ( ) , configuration . getClass ( ) , configuration , GenericsResolver . resolve ( configuration . getClass ( ) ) ) ; final List < ConfigPath > uniqueContent = resolveUniqueTypePaths ( content ) ; return new ConfigurationTree ( roots , content , uniqueContent ) ; } else { return new ConfigurationTree ( roots ) ; } }
Analyze configuration object to extract bindable parts .
1,724
public String renderReport ( final OptionsConfig config ) { final StringBuilder res = new StringBuilder ( ) ; render ( config , res ) ; return res . toString ( ) ; }
Renders options report .
1,725
public void count ( final Stat name , final int count ) { Integer value = counters . get ( name ) ; value = value == null ? count : value + count ; counters . put ( name , value ) ; }
Inserts value for first call and sum values for consequent calls .
1,726
public void startHkTimer ( final Stat name ) { timer ( GuiceyTime ) ; if ( ! HKTime . equals ( name ) ) { timer ( HKTime ) ; } timer ( name ) ; }
Special methods for tracking time in HK2 scope . Such complication used to avoid using 3 different trackers in code . HK2 initialization is performed after bundles run and so out of scope of GuiceBundle .
1,727
private List < FeatureInstaller > prepareInstallers ( final List < Class < ? extends FeatureInstaller > > installerClasses ) { final List < FeatureInstaller > installers = Lists . newArrayList ( ) ; final Options options = new Options ( context . options ( ) ) ; for ( Class < ? extends FeatureInstaller > installerClass : installerClasses ) { try { final FeatureInstaller installer = installerClass . newInstance ( ) ; installers . add ( installer ) ; if ( WithOptions . class . isAssignableFrom ( installerClass ) ) { ( ( WithOptions ) installer ) . setOptions ( options ) ; } } catch ( Exception e ) { throw new IllegalStateException ( "Failed to register installer " + installerClass . getName ( ) , e ) ; } } return installers ; }
Instantiate all found installers using default constructor .
1,728
@ SuppressWarnings ( "PMD.PrematureDeclaration" ) private void resolveExtensions ( final ExtensionsHolder holder ) { final Stopwatch timer = context . stat ( ) . timer ( Stat . ExtensionsRecognitionTime ) ; final boolean guiceFirstMode = context . option ( JerseyExtensionsManagedByGuice ) ; final List < Class < ? > > manual = context . getEnabledExtensions ( ) ; for ( Class < ? > type : manual ) { if ( ! processType ( type , holder , guiceFirstMode , false ) ) { throw new IllegalStateException ( "No installer found for extension " + type . getName ( ) + ". Available installers: " + holder . getInstallerTypes ( ) . stream ( ) . map ( FeatureUtils :: getInstallerExtName ) . collect ( Collectors . joining ( ", " ) ) ) ; } } if ( scanner != null ) { scanner . scan ( type -> { if ( manual . contains ( type ) ) { context . getOrRegisterExtension ( type , true ) ; } else { processType ( type , holder , guiceFirstMode , true ) ; } } ) ; } context . lifecycle ( ) . extensionsResolved ( context . getEnabledExtensions ( ) , context . getDisabledExtensions ( ) ) ; timer . stop ( ) ; }
Performs one more classpath scan to search for extensions or simply install manually provided extension classes .
1,729
@ SuppressWarnings ( "unchecked" ) private void bindExtension ( final ExtensionItemInfo item , final FeatureInstaller installer , final ExtensionsHolder holder ) { final Class < ? extends FeatureInstaller > installerClass = installer . getClass ( ) ; final Class < ? > type = item . getType ( ) ; holder . register ( installerClass , type ) ; if ( installer instanceof BindingInstaller ) { ( ( BindingInstaller ) installer ) . install ( binder ( ) , type , item . isLazy ( ) ) ; } else if ( ! item . isLazy ( ) ) { binder ( ) . bind ( type ) ; } }
Bind extension to guice context .
1,730
public static String renderDisabledInstaller ( final Class < FeatureInstaller > type ) { return String . format ( "-%-19s %-38s" , FeatureUtils . getInstallerExtName ( type ) , brackets ( renderClass ( type ) ) ) ; }
Renders disabled installer line . The same as installer line but with - before installer name and without markers .
1,731
public static String renderPackage ( final Class < ? > type ) { return PACKAGE_FORMATTER . abbreviate ( type . isMemberClass ( ) && ! type . isAnonymousClass ( ) ? type . getDeclaringClass ( ) . getName ( ) : type . getPackage ( ) . getName ( ) ) ; }
If provided type is inner class then declaring class will be rendered instead of package .
1,732
public String renderReport ( final DiagnosticConfig config ) { final StringBuilder res = new StringBuilder ( ) ; printCommands ( config , res ) ; printBundles ( config , res ) ; if ( config . isPrintInstallers ( ) ) { printInstallers ( config , res ) ; printDisabledExtensions ( config , res , true ) ; } else { printExtensionsOnly ( config , res ) ; } printModules ( config , res ) ; return res . toString ( ) ; }
Renders diagnostic report according to config .
1,733
private void configureFromBundles ( ) { context . lifecycle ( ) . runPhase ( context . getConfiguration ( ) , context . getConfigurationTree ( ) , context . getEnvironment ( ) ) ; final Stopwatch timer = context . stat ( ) . timer ( BundleTime ) ; final Stopwatch resolutionTimer = context . stat ( ) . timer ( BundleResolutionTime ) ; if ( context . option ( ConfigureFromDropwizardBundles ) ) { context . registerDwBundles ( BundleSupport . findBundles ( context . getBootstrap ( ) , GuiceyBundle . class ) ) ; } context . registerLookupBundles ( bundleLookup . lookup ( ) ) ; resolutionTimer . stop ( ) ; BundleSupport . processBundles ( context ) ; timer . stop ( ) ; }
Apply configuration from registered bundles . If dropwizard bundles support is enabled lookup them too .
1,734
@ SuppressWarnings ( "deprecation" ) private void bindEnvironment ( ) { bind ( Bootstrap . class ) . toInstance ( bootstrap ( ) ) ; bind ( Environment . class ) . toInstance ( environment ( ) ) ; install ( new ConfigBindingModule ( configuration ( ) , configurationTree ( ) , context . option ( BindConfigurationInterfaces ) ) ) ; }
Bind bootstrap configuration and environment objects to be able to use them as injectable .
1,735
public static void enableBundles ( final Class < ? extends GuiceyBundle > ... bundles ) { final String prop = Joiner . on ( ',' ) . join ( toStrings ( Lists . newArrayList ( bundles ) ) ) ; System . setProperty ( BUNDLES_PROPERTY , prop ) ; }
Sets system property value to provided classes . Shortcut is useful to set property from code for example in unit tests .
1,736
public boolean cancel ( boolean ign ) { assert op != null : "No operation" ; op . cancel ( ) ; notifyListeners ( ) ; return op . getState ( ) == OperationState . WRITE_QUEUED ; }
Cancel this operation if possible .
1,737
public Long getCas ( ) { if ( cas == null ) { try { get ( ) ; } catch ( InterruptedException e ) { status = new OperationStatus ( false , "Interrupted" , StatusCode . INTERRUPTED ) ; } catch ( ExecutionException e ) { getLogger ( ) . warn ( "Error getting cas of operation" , e ) ; } } if ( cas == null && status . isSuccess ( ) ) { throw new UnsupportedOperationException ( "This operation doesn't return" + "a cas value." ) ; } return cas ; }
Get the CAS for this operation .
1,738
public OperationStatus getStatus ( ) { if ( status == null ) { try { get ( ) ; } catch ( InterruptedException e ) { status = new OperationStatus ( false , "Interrupted" , StatusCode . INTERRUPTED ) ; } catch ( ExecutionException e ) { getLogger ( ) . warn ( "Error getting status of operation" , e ) ; } } return status ; }
Get the current status of this operation .
1,739
public void set ( T o , OperationStatus s ) { objRef . set ( o ) ; status = s ; }
Set the Operation associated with this OperationFuture .
1,740
public static Logger getLogger ( String name ) { if ( name == null ) { throw new NullPointerException ( "Logger name may not be null." ) ; } init ( ) ; return ( instance . internalGetLogger ( name ) ) ; }
Get a logger by name .
1,741
private Logger internalGetLogger ( String name ) { assert name != null : "Name was null" ; Logger rv = instances . get ( name ) ; if ( rv == null ) { Logger newLogger = null ; try { newLogger = getNewInstance ( name ) ; } catch ( Exception e ) { throw new RuntimeException ( "Problem getting logger" , e ) ; } Logger tmp = instances . putIfAbsent ( name , newLogger ) ; rv = tmp == null ? newLogger : tmp ; } return ( rv ) ; }
Get an instance of Logger from internal mechanisms .
1,742
@ SuppressWarnings ( "unchecked" ) private void getConstructor ( ) { Class < ? extends Logger > c = DefaultLogger . class ; String className = System . getProperty ( "net.spy.log.LoggerImpl" ) ; if ( className != null ) { try { c = ( Class < ? extends Logger > ) Class . forName ( className ) ; } catch ( NoClassDefFoundError e ) { System . err . println ( "Warning: " + className + " not found while initializing" + " net.spy.compat.log.LoggerFactory" ) ; e . printStackTrace ( ) ; c = DefaultLogger . class ; } catch ( ClassNotFoundException e ) { System . err . println ( "Warning: " + className + " not found while initializing" + " net.spy.compat.log.LoggerFactory" ) ; e . printStackTrace ( ) ; c = DefaultLogger . class ; } } try { Class < ? > [ ] args = { String . class } ; instanceConstructor = c . getConstructor ( args ) ; } catch ( NoSuchMethodException e ) { try { Class < ? > [ ] args = { } ; instanceConstructor = c . getConstructor ( args ) ; } catch ( NoSuchMethodException e2 ) { System . err . println ( "Warning: " + className + " has no appropriate constructor, using defaults." ) ; try { Class < ? > [ ] args = { String . class } ; instanceConstructor = DefaultLogger . class . getConstructor ( args ) ; } catch ( NoSuchMethodException e3 ) { throw new NoSuchMethodError ( "There used to be a constructor that " + "takes a single String on " + DefaultLogger . class + ", but I " + "can't find one now." ) ; } } } }
Find the appropriate constructor
1,743
public Throwable getThrowable ( Object [ ] args ) { Throwable rv = null ; if ( args . length > 0 ) { if ( args [ args . length - 1 ] instanceof Throwable ) { rv = ( Throwable ) args [ args . length - 1 ] ; } } return rv ; }
Get the throwable from the last element of this array if it is Throwable else null .
1,744
public void trace ( Object message , Throwable exception ) { log ( Level . TRACE , message , exception ) ; }
Log a message at trace level .
1,745
public void trace ( String message , Object ... args ) { if ( isDebugEnabled ( ) ) { trace ( String . format ( message , args ) , getThrowable ( args ) ) ; } }
Log a formatted message at trace level .
1,746
public void debug ( Object message , Throwable exception ) { log ( Level . DEBUG , message , exception ) ; }
Log a message at debug level .
1,747
public void info ( String message , Object ... args ) { if ( isInfoEnabled ( ) ) { info ( String . format ( message , args ) , getThrowable ( args ) ) ; } }
Log a formatted message at info level .
1,748
public void warn ( Object message , Throwable exception ) { log ( Level . WARN , message , exception ) ; }
Log a message at warning level .
1,749
public void error ( Object message , Throwable exception ) { log ( Level . ERROR , message , exception ) ; }
Log a message at error level .
1,750
public void fatal ( Object message , Throwable exception ) { log ( Level . FATAL , message , exception ) ; }
Log a message at fatal level .
1,751
public void log ( Level level , Object message , Throwable e ) { if ( level == null ) { level = Level . FATAL ; } switch ( level ) { case TRACE : logger . trace ( message . toString ( ) , e ) ; break ; case DEBUG : logger . debug ( message . toString ( ) , e ) ; break ; case INFO : logger . info ( message . toString ( ) , e ) ; break ; case WARN : logger . warn ( message . toString ( ) , e ) ; break ; case ERROR : logger . error ( message . toString ( ) , e ) ; break ; case FATAL : logger . error ( message . toString ( ) , e ) ; break ; default : logger . error ( "Unhandled Logging Level: " + level + " with log message: " + message . toString ( ) , e ) ; } }
Wrapper around SLF4J logger facade .
1,752
public synchronized void authConnection ( MemcachedConnection conn , OperationFactory opFact , AuthDescriptor authDescriptor , MemcachedNode node ) { interruptOldAuth ( node ) ; AuthThread newSASLAuthenticator = new AuthThread ( conn , opFact , authDescriptor , node ) ; nodeMap . put ( node , newSASLAuthenticator ) ; }
Authenticate a new connection . This is typically used by a MemcachedNode in order to authenticate a connection right after it has been established .
1,753
private void parseHeaderFromBuffer ( ) { int magic = header [ 0 ] ; assert magic == RES_MAGIC : "Invalid magic: " + magic ; responseCmd = header [ 1 ] ; assert cmd == DUMMY_OPCODE || responseCmd == cmd : "Unexpected response command value" ; keyLen = decodeShort ( header , 2 ) ; errorCode = decodeShort ( header , 6 ) ; int bytesToRead = decodeInt ( header , 8 ) ; payload = new byte [ bytesToRead ] ; responseOpaque = decodeInt ( header , 12 ) ; responseCas = decodeLong ( header , 16 ) ; assert opaqueIsValid ( ) : "Opaque is not valid" ; }
Parse the header info out of the buffer .
1,754
private void readPayloadFromBuffer ( final ByteBuffer buffer ) throws IOException { int toRead = payload . length - payloadOffset ; int available = buffer . remaining ( ) ; toRead = Math . min ( toRead , available ) ; getLogger ( ) . debug ( "Reading %d payload bytes" , toRead ) ; buffer . get ( payload , payloadOffset , toRead ) ; payloadOffset += toRead ; if ( payloadOffset == payload . length ) { finishedPayload ( payload ) ; } }
Read the payload from the buffer .
1,755
protected OperationStatus getStatusForErrorCode ( int errCode , byte [ ] errPl ) throws IOException { if ( errCode == SUCCESS ) { return STATUS_OK ; } else { StatusCode statusCode = StatusCode . fromBinaryCode ( errCode ) ; errorMsg = errPl . clone ( ) ; switch ( errCode ) { case ERR_NOT_FOUND : return new CASOperationStatus ( false , new String ( errPl ) , CASResponse . NOT_FOUND , statusCode ) ; case ERR_EXISTS : return new CASOperationStatus ( false , new String ( errPl ) , CASResponse . EXISTS , statusCode ) ; case ERR_NOT_STORED : return new CASOperationStatus ( false , new String ( errPl ) , CASResponse . NOT_FOUND , statusCode ) ; case ERR_INTERNAL : handleError ( OperationErrorType . SERVER , new String ( errPl ) ) ; case ERR_2BIG : case ERR_INVAL : case ERR_DELTA_BADVAL : case ERR_NOT_MY_VBUCKET : case ERR_UNKNOWN_COMMAND : case ERR_NO_MEM : case ERR_NOT_SUPPORTED : case ERR_BUSY : case ERR_TEMP_FAIL : return new OperationStatus ( false , new String ( errPl ) , statusCode ) ; default : return null ; } } }
Get the OperationStatus object for the given error code .
1,756
protected void prepareBuffer ( final String key , final long cas , final byte [ ] val , final Object ... extraHeaders ) { int extraLen = 0 ; int extraHeadersLength = extraHeaders . length ; if ( extraHeadersLength > 0 ) { extraLen = calculateExtraLength ( extraHeaders ) ; } final byte [ ] keyBytes = KeyUtil . getKeyBytes ( key ) ; int bufSize = MIN_RECV_PACKET + keyBytes . length + val . length ; ByteBuffer bb = ByteBuffer . allocate ( bufSize + extraLen ) ; assert bb . order ( ) == ByteOrder . BIG_ENDIAN ; bb . put ( REQ_MAGIC ) ; bb . put ( cmd ) ; bb . putShort ( ( short ) keyBytes . length ) ; bb . put ( ( byte ) extraLen ) ; bb . put ( ( byte ) 0 ) ; bb . putShort ( vbucket ) ; bb . putInt ( keyBytes . length + val . length + extraLen ) ; bb . putInt ( opaque ) ; bb . putLong ( cas ) ; if ( extraHeadersLength > 0 ) { addExtraHeaders ( bb , extraHeaders ) ; } bb . put ( keyBytes ) ; bb . put ( val ) ; bb . flip ( ) ; setBuffer ( bb ) ; }
Prepare the buffer for sending .
1,757
private void initReporter ( ) { String reporterType = System . getProperty ( "net.spy.metrics.reporter.type" , DEFAULT_REPORTER_TYPE ) ; String reporterInterval = System . getProperty ( "net.spy.metrics.reporter.interval" , DEFAULT_REPORTER_INTERVAL ) ; String reporterDir = System . getProperty ( "net.spy.metrics.reporter.outdir" , DEFAULT_REPORTER_OUTDIR ) ; if ( reporterType . equals ( "console" ) ) { final ConsoleReporter reporter = ConsoleReporter . forRegistry ( registry ) . convertRatesTo ( TimeUnit . SECONDS ) . convertDurationsTo ( TimeUnit . SECONDS ) . build ( ) ; reporter . start ( Integer . parseInt ( reporterInterval ) , TimeUnit . SECONDS ) ; } else if ( reporterType . equals ( "jmx" ) ) { final JmxReporter reporter = JmxReporter . forRegistry ( registry ) . convertRatesTo ( TimeUnit . SECONDS ) . convertDurationsTo ( TimeUnit . SECONDS ) . build ( ) ; reporter . start ( ) ; } else if ( reporterType . equals ( "csv" ) ) { final CsvReporter reporter = CsvReporter . forRegistry ( registry ) . convertRatesTo ( TimeUnit . SECONDS ) . convertDurationsTo ( TimeUnit . SECONDS ) . build ( new File ( reporterDir ) ) ; reporter . start ( Integer . parseInt ( reporterInterval ) , TimeUnit . SECONDS ) ; } else if ( reporterType . equals ( "slf4j" ) ) { final Slf4jReporter reporter = Slf4jReporter . forRegistry ( registry ) . convertRatesTo ( TimeUnit . SECONDS ) . convertDurationsTo ( TimeUnit . SECONDS ) . outputTo ( LoggerFactory . getLogger ( MetricCollector . class ) ) . build ( ) ; reporter . start ( Integer . parseInt ( reporterInterval ) , TimeUnit . SECONDS ) ; } else { throw new IllegalStateException ( "Unknown Metrics Reporter Type: " + reporterType ) ; } }
Initialize the proper metrics Reporter .
1,758
public ResponseMessage getNextMessage ( long time , TimeUnit timeunit ) { try { Object m = rqueue . poll ( time , timeunit ) ; if ( m == null ) { return null ; } else if ( m instanceof ResponseMessage ) { return ( ResponseMessage ) m ; } else if ( m instanceof TapAck ) { TapAck ack = ( TapAck ) m ; tapAck ( ack . getConn ( ) , ack . getNode ( ) , ack . getOpcode ( ) , ack . getOpaque ( ) , ack . getCallback ( ) ) ; return null ; } else { throw new RuntimeException ( "Unexpected tap message type" ) ; } } catch ( InterruptedException e ) { shutdown ( ) ; return null ; } }
Gets the next tap message from the queue of received tap messages .
1,759
public boolean hasMoreMessages ( ) { if ( ! rqueue . isEmpty ( ) ) { return true ; } else { synchronized ( omap ) { Iterator < TapStream > itr = omap . keySet ( ) . iterator ( ) ; while ( itr . hasNext ( ) ) { TapStream ts = itr . next ( ) ; if ( ts . isCompleted ( ) || ts . isCancelled ( ) || ts . hasErrored ( ) ) { omap . get ( ts ) . shutdown ( ) ; omap . remove ( ts ) ; } } if ( omap . size ( ) > 0 ) { return true ; } } } return false ; }
Decides whether the client has received tap messages or will receive more messages in the future .
1,760
public TapStream tapCustom ( final String id , final RequestMessage message ) throws ConfigurationException , IOException { final TapConnectionProvider conn = new TapConnectionProvider ( addrs ) ; final TapStream ts = new TapStream ( ) ; conn . broadcastOp ( new BroadcastOpFactory ( ) { public Operation newOp ( final MemcachedNode n , final CountDownLatch latch ) { Operation op = conn . getOpFactory ( ) . tapCustom ( id , message , new TapOperation . Callback ( ) { public void receivedStatus ( OperationStatus status ) { } public void gotData ( ResponseMessage tapMessage ) { rqueue . add ( tapMessage ) ; messagesRead ++ ; } public void gotAck ( MemcachedNode node , TapOpcode opcode , int opaque ) { rqueue . add ( new TapAck ( conn , node , opcode , opaque , this ) ) ; } public void complete ( ) { latch . countDown ( ) ; } } ) ; ts . addOp ( ( TapOperation ) op ) ; return op ; } } ) ; synchronized ( omap ) { omap . put ( ts , conn ) ; } return ts ; }
Allows the user to specify a custom tap message .
1,761
public void shutdown ( ) { synchronized ( omap ) { for ( Map . Entry < TapStream , TapConnectionProvider > me : omap . entrySet ( ) ) { me . getValue ( ) . shutdown ( ) ; } } }
Shuts down all tap streams that are currently running .
1,762
public static long fieldToValue ( byte [ ] buffer , int offset , int length ) { long total = 0 ; long val = 0 ; for ( int i = 0 ; i < length ; i ++ ) { val = buffer [ offset + i ] ; if ( val < 0 ) { val = val + 256 ; } total += ( long ) Math . pow ( 256.0 , ( double ) ( length - 1 - i ) ) * val ; } return total ; }
Converts a field in a byte array into a value .
1,763
public static void valueToFieldOffest ( byte [ ] buffer , int offset , int length , long l ) { long divisor ; for ( int i = 0 ; i < length ; i ++ ) { divisor = ( long ) Math . pow ( 256.0 , ( double ) ( length - 1 - i ) ) ; buffer [ offset + i ] = ( byte ) ( l / divisor ) ; l = l % divisor ; } }
Puts a value into a specific location in a byte buffer .
1,764
protected final synchronized void transitionState ( OperationState newState ) { getLogger ( ) . debug ( "Transitioned state from %s to %s" , state , newState ) ; state = newState ; if ( state != OperationState . WRITE_QUEUED && state != OperationState . WRITING ) { cmd = null ; } if ( state == OperationState . COMPLETE ) { callback . complete ( ) ; } }
Transition the state of this operation to the given state .
1,765
public boolean isCompleted ( ) { for ( TapOperation op : ops ) { if ( ! op . getState ( ) . equals ( OperationState . COMPLETE ) ) { return false ; } } return true ; }
Check if all operations in the TapStream are completed .
1,766
public void setFlags ( TapRequestFlag f ) { if ( ! flagList . contains ( f ) ) { if ( ! hasFlags ) { hasFlags = true ; extralength += 4 ; totalbody += 4 ; } if ( f . equals ( TapRequestFlag . BACKFILL ) ) { hasBackfill = true ; totalbody += 8 ; } if ( f . equals ( TapRequestFlag . LIST_VBUCKETS ) || f . equals ( TapRequestFlag . TAKEOVER_VBUCKETS ) ) { hasVBucketList = true ; totalbody += 2 ; } if ( f . equals ( TapRequestFlag . CHECKPOINT ) ) { hasVBucketCheckpoints = true ; totalbody += 2 ; } flagList . add ( f ) ; } }
Sets the flags for the tap stream . These flags decide what kind of tap stream will be received .
1,767
public void setVbucketlist ( short [ ] vbs ) { int oldSize = ( vblist . length + 1 ) * 2 ; int newSize = ( vbs . length + 1 ) * 2 ; totalbody += newSize - oldSize ; vblist = vbs ; }
Sets a list of vbuckets to stream keys from .
1,768
public void setvBucketCheckpoints ( Map < Short , Long > vbchkpnts ) { int oldSize = ( vBucketCheckpoints . size ( ) ) * 10 ; int newSize = ( vbchkpnts . size ( ) ) * 10 ; totalbody += newSize - oldSize ; vBucketCheckpoints = vbchkpnts ; }
Sets a map of vbucket checkpoints .
1,769
public void setName ( String n ) { if ( n . length ( ) > 65535 ) { throw new IllegalArgumentException ( "Tap name too long" ) ; } totalbody += n . length ( ) - name . length ( ) ; keylength = ( short ) n . length ( ) ; name = n ; }
Sets a name for this tap stream . If the tap stream fails this name can be used to try to restart the tap stream from where it last left off .
1,770
public ByteBuffer getBytes ( ) { ByteBuffer bb = ByteBuffer . allocate ( HEADER_LENGTH + getTotalbody ( ) ) ; bb . put ( magic . getMagic ( ) ) ; bb . put ( opcode . getOpcode ( ) ) ; bb . putShort ( keylength ) ; bb . put ( extralength ) ; bb . put ( datatype ) ; bb . putShort ( vbucket ) ; bb . putInt ( totalbody ) ; bb . putInt ( opaque ) ; bb . putLong ( cas ) ; if ( hasFlags ) { int flag = 0 ; for ( int i = 0 ; i < flagList . size ( ) ; i ++ ) { flag |= flagList . get ( i ) . getFlags ( ) ; } bb . putInt ( flag ) ; } bb . put ( name . getBytes ( ) ) ; if ( hasBackfill ) { bb . putLong ( backfilldate ) ; } if ( hasVBucketList ) { bb . putShort ( ( short ) vblist . length ) ; for ( int i = 0 ; i < vblist . length ; i ++ ) { bb . putShort ( vblist [ i ] ) ; } } if ( hasVBucketCheckpoints ) { bb . putShort ( ( short ) vBucketCheckpoints . size ( ) ) ; for ( Short vBucket : vBucketCheckpoints . keySet ( ) ) { bb . putShort ( vBucket ) ; bb . putLong ( vBucketCheckpoints . get ( vBucket ) ) ; } } return ( ByteBuffer ) bb . flip ( ) ; }
Encodes the message into binary .
1,771
protected Future < T > addToListeners ( final GenericCompletionListener < ? extends Future < T > > listener ) { if ( listener == null ) { throw new IllegalArgumentException ( "The listener can't be null." ) ; } synchronized ( this ) { listeners . add ( listener ) ; } if ( isDone ( ) ) { notifyListeners ( ) ; } return this ; }
Add the given listener to the total list of listeners to be notified .
1,772
protected void notifyListener ( final ExecutorService executor , final Future < ? > future , final GenericCompletionListener listener ) { executor . submit ( new Runnable ( ) { public void run ( ) { try { listener . onComplete ( future ) ; } catch ( Throwable t ) { getLogger ( ) . warn ( "Exception thrown wile executing " + listener . getClass ( ) . getName ( ) + ".operationComplete()" , t ) ; } } } ) ; }
Notify a specific listener of completion .
1,773
protected void notifyListeners ( final Future < ? > future ) { final List < GenericCompletionListener < ? extends Future < T > > > copy = new ArrayList < GenericCompletionListener < ? extends Future < T > > > ( ) ; synchronized ( this ) { copy . addAll ( listeners ) ; listeners = new ArrayList < GenericCompletionListener < ? extends Future < T > > > ( ) ; } for ( GenericCompletionListener < ? extends Future < ? super T > > listener : copy ) { notifyListener ( executor ( ) , future , listener ) ; } }
Notify all registered listeners with a special future on completion .
1,774
protected Future < T > removeFromListeners ( GenericCompletionListener < ? extends Future < T > > listener ) { if ( listener == null ) { throw new IllegalArgumentException ( "The listener can't be null." ) ; } if ( ! isDone ( ) ) { synchronized ( this ) { listeners . remove ( listener ) ; } } return this ; }
Remove a listener from the list of registered listeners .
1,775
protected void registerMetrics ( ) { if ( metricType . equals ( MetricType . DEBUG ) || metricType . equals ( MetricType . PERFORMANCE ) ) { metrics . addHistogram ( OVERALL_AVG_BYTES_READ_METRIC ) ; metrics . addHistogram ( OVERALL_AVG_BYTES_WRITE_METRIC ) ; metrics . addHistogram ( OVERALL_AVG_TIME_ON_WIRE_METRIC ) ; metrics . addMeter ( OVERALL_RESPONSE_METRIC ) ; metrics . addMeter ( OVERALL_REQUEST_METRIC ) ; if ( metricType . equals ( MetricType . DEBUG ) ) { metrics . addCounter ( RECON_QUEUE_METRIC ) ; metrics . addCounter ( SHUTD_QUEUE_METRIC ) ; metrics . addMeter ( OVERALL_RESPONSE_RETRY_METRIC ) ; metrics . addMeter ( OVERALL_RESPONSE_SUCC_METRIC ) ; metrics . addMeter ( OVERALL_RESPONSE_FAIL_METRIC ) ; } } }
Register Metrics for collection .
1,776
protected List < MemcachedNode > createConnections ( final Collection < InetSocketAddress > addrs ) throws IOException { List < MemcachedNode > connections = new ArrayList < MemcachedNode > ( addrs . size ( ) ) ; for ( SocketAddress sa : addrs ) { SocketChannel ch = SocketChannel . open ( ) ; ch . configureBlocking ( false ) ; MemcachedNode qa = connectionFactory . createMemcachedNode ( sa , ch , bufSize ) ; qa . setConnection ( this ) ; int ops = 0 ; Socket socket = ch . socket ( ) ; socket . setTcpNoDelay ( ! connectionFactory . useNagleAlgorithm ( ) ) ; socket . setKeepAlive ( connectionFactory . getKeepAlive ( ) ) ; try { if ( ch . connect ( sa ) ) { getLogger ( ) . info ( "Connected to %s immediately" , qa ) ; connected ( qa ) ; } else { getLogger ( ) . info ( "Added %s to connect queue" , qa ) ; ops = SelectionKey . OP_CONNECT ; } selector . wakeup ( ) ; qa . setSk ( ch . register ( selector , ops , qa ) ) ; assert ch . isConnected ( ) || qa . getSk ( ) . interestOps ( ) == SelectionKey . OP_CONNECT : "Not connected, and not wanting to connect" ; } catch ( SocketException e ) { getLogger ( ) . warn ( "Socket error on initial connect" , e ) ; queueReconnect ( qa ) ; } connections . add ( qa ) ; } return connections ; }
Create connections for the given list of addresses .
1,777
private boolean selectorsMakeSense ( ) { for ( MemcachedNode qa : locator . getAll ( ) ) { if ( qa . getSk ( ) != null && qa . getSk ( ) . isValid ( ) ) { if ( qa . getChannel ( ) . isConnected ( ) ) { int sops = qa . getSk ( ) . interestOps ( ) ; int expected = 0 ; if ( qa . hasReadOp ( ) ) { expected |= SelectionKey . OP_READ ; } if ( qa . hasWriteOp ( ) ) { expected |= SelectionKey . OP_WRITE ; } if ( qa . getBytesRemainingToWrite ( ) > 0 ) { expected |= SelectionKey . OP_WRITE ; } assert sops == expected : "Invalid ops: " + qa + ", expected " + expected + ", got " + sops ; } else { int sops = qa . getSk ( ) . interestOps ( ) ; assert sops == SelectionKey . OP_CONNECT : "Not connected, and not watching for connect: " + sops ; } } } getLogger ( ) . debug ( "Checked the selectors." ) ; return true ; }
Make sure that the current selectors make sense .
1,778
public void handleIO ( ) throws IOException { if ( shutDown ) { getLogger ( ) . debug ( "No IO while shut down." ) ; return ; } handleInputQueue ( ) ; getLogger ( ) . debug ( "Done dealing with queue." ) ; long delay = wakeupDelay ; if ( ! reconnectQueue . isEmpty ( ) ) { long now = System . currentTimeMillis ( ) ; long then = reconnectQueue . firstKey ( ) ; delay = Math . max ( then - now , 1 ) ; } getLogger ( ) . debug ( "Selecting with delay of %sms" , delay ) ; assert selectorsMakeSense ( ) : "Selectors don't make sense." ; int selected = selector . select ( delay ) ; if ( shutDown ) { return ; } else if ( selected == 0 && addedQueue . isEmpty ( ) ) { handleWokenUpSelector ( ) ; } else if ( selector . selectedKeys ( ) . isEmpty ( ) ) { handleEmptySelects ( ) ; } else { getLogger ( ) . debug ( "Selected %d, selected %d keys" , selected , selector . selectedKeys ( ) . size ( ) ) ; emptySelects = 0 ; Iterator < SelectionKey > iterator = selector . selectedKeys ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { SelectionKey sk = iterator . next ( ) ; handleIO ( sk ) ; iterator . remove ( ) ; } } handleOperationalTasks ( ) ; }
Handle all IO that flows through the connection .
1,779
private void handleShutdownQueue ( ) throws IOException { for ( MemcachedNode qa : nodesToShutdown ) { if ( ! addedQueue . contains ( qa ) ) { nodesToShutdown . remove ( qa ) ; metrics . decrementCounter ( SHUTD_QUEUE_METRIC ) ; Collection < Operation > notCompletedOperations = qa . destroyInputQueue ( ) ; if ( qa . getChannel ( ) != null ) { qa . getChannel ( ) . close ( ) ; qa . setSk ( null ) ; if ( qa . getBytesRemainingToWrite ( ) > 0 ) { getLogger ( ) . warn ( "Shut down with %d bytes remaining to write" , qa . getBytesRemainingToWrite ( ) ) ; } getLogger ( ) . debug ( "Shut down channel %s" , qa . getChannel ( ) ) ; } redistributeOperations ( notCompletedOperations ) ; } } }
Check if nodes need to be shut down and do so if needed .
1,780
private void checkPotentiallyTimedOutConnection ( ) { boolean stillCheckingTimeouts = true ; while ( stillCheckingTimeouts ) { try { for ( SelectionKey sk : selector . keys ( ) ) { MemcachedNode mn = ( MemcachedNode ) sk . attachment ( ) ; if ( mn . getContinuousTimeout ( ) > timeoutExceptionThreshold ) { getLogger ( ) . warn ( "%s exceeded continuous timeout threshold" , sk ) ; lostConnection ( mn ) ; } } stillCheckingTimeouts = false ; } catch ( ConcurrentModificationException e ) { getLogger ( ) . warn ( "Retrying selector keys after " + "ConcurrentModificationException caught" , e ) ; continue ; } } }
Check if one or more nodes exceeded the timeout Threshold .
1,781
private void handleInputQueue ( ) { if ( ! addedQueue . isEmpty ( ) ) { getLogger ( ) . debug ( "Handling queue" ) ; Collection < MemcachedNode > toAdd = new HashSet < MemcachedNode > ( ) ; Collection < MemcachedNode > todo = new HashSet < MemcachedNode > ( ) ; MemcachedNode qaNode ; while ( ( qaNode = addedQueue . poll ( ) ) != null ) { todo . add ( qaNode ) ; } for ( MemcachedNode node : todo ) { boolean readyForIO = false ; if ( node . isActive ( ) ) { if ( node . getCurrentWriteOp ( ) != null ) { readyForIO = true ; getLogger ( ) . debug ( "Handling queued write %s" , node ) ; } } else { toAdd . add ( node ) ; } node . copyInputQueue ( ) ; if ( readyForIO ) { try { if ( node . getWbuf ( ) . hasRemaining ( ) ) { handleWrites ( node ) ; } } catch ( IOException e ) { getLogger ( ) . warn ( "Exception handling write" , e ) ; lostConnection ( node ) ; } } node . fixupOps ( ) ; } addedQueue . addAll ( toAdd ) ; } }
Handle any requests that have been made against the client .
1,782
private void connected ( final MemcachedNode node ) { assert node . getChannel ( ) . isConnected ( ) : "Not connected." ; int rt = node . getReconnectCount ( ) ; node . connected ( ) ; for ( ConnectionObserver observer : connObservers ) { observer . connectionEstablished ( node . getSocketAddress ( ) , rt ) ; } }
Indicate a successful connect to the given node .
1,783
private void lostConnection ( final MemcachedNode node ) { queueReconnect ( node ) ; for ( ConnectionObserver observer : connObservers ) { observer . connectionLost ( node . getSocketAddress ( ) ) ; } }
Indicate a lost connection to the given node .
1,784
boolean belongsToCluster ( final MemcachedNode node ) { for ( MemcachedNode n : locator . getAll ( ) ) { if ( n . getSocketAddress ( ) . equals ( node . getSocketAddress ( ) ) ) { return true ; } } return false ; }
Makes sure that the given node belongs to the current cluster .
1,785
private void handleIO ( final SelectionKey sk ) { MemcachedNode node = ( MemcachedNode ) sk . attachment ( ) ; try { getLogger ( ) . debug ( "Handling IO for: %s (r=%s, w=%s, c=%s, op=%s)" , sk , sk . isReadable ( ) , sk . isWritable ( ) , sk . isConnectable ( ) , sk . attachment ( ) ) ; if ( sk . isConnectable ( ) && belongsToCluster ( node ) ) { getLogger ( ) . debug ( "Connection state changed for %s" , sk ) ; final SocketChannel channel = node . getChannel ( ) ; if ( channel . finishConnect ( ) ) { finishConnect ( sk , node ) ; } else { assert ! channel . isConnected ( ) : "connected" ; } } else { handleReadsAndWrites ( sk , node ) ; } } catch ( ClosedChannelException e ) { if ( ! shutDown ) { getLogger ( ) . info ( "Closed channel and not shutting down. Queueing" + " reconnect on %s" , node , e ) ; lostConnection ( node ) ; } } catch ( ConnectException e ) { getLogger ( ) . info ( "Reconnecting due to failure to connect to %s" , node , e ) ; queueReconnect ( node ) ; } catch ( OperationException e ) { node . setupForAuth ( ) ; getLogger ( ) . info ( "Reconnection due to exception handling a memcached " + "operation on %s. This may be due to an authentication failure." , node , e ) ; lostConnection ( node ) ; } catch ( Exception e ) { node . setupForAuth ( ) ; getLogger ( ) . info ( "Reconnecting due to exception on %s" , node , e ) ; lostConnection ( node ) ; } node . fixupOps ( ) ; }
Handle IO for a specific selector .
1,786
private void finishConnect ( final SelectionKey sk , final MemcachedNode node ) throws IOException { if ( verifyAliveOnConnect ) { final CountDownLatch latch = new CountDownLatch ( 1 ) ; final OperationFuture < Boolean > rv = new OperationFuture < Boolean > ( "noop" , latch , 2500 , listenerExecutorService ) ; NoopOperation testOp = opFact . noop ( new OperationCallback ( ) { public void receivedStatus ( OperationStatus status ) { rv . set ( status . isSuccess ( ) , status ) ; } public void complete ( ) { latch . countDown ( ) ; } } ) ; testOp . setHandlingNode ( node ) ; testOp . initialize ( ) ; checkState ( ) ; insertOperation ( node , testOp ) ; node . copyInputQueue ( ) ; boolean done = false ; if ( sk . isValid ( ) ) { long timeout = TimeUnit . MILLISECONDS . toNanos ( connectionFactory . getOperationTimeout ( ) ) ; long stop = System . nanoTime ( ) + timeout ; while ( stop > System . nanoTime ( ) ) { handleWrites ( node ) ; handleReads ( node ) ; if ( done = ( latch . getCount ( ) == 0 ) ) { break ; } } } if ( ! done || testOp . isCancelled ( ) || testOp . hasErrored ( ) || testOp . isTimedOut ( ) ) { throw new ConnectException ( "Could not send noop upon connect! " + "This may indicate a running, but not responding memcached " + "instance." ) ; } } connected ( node ) ; addedQueue . offer ( node ) ; if ( node . getWbuf ( ) . hasRemaining ( ) ) { handleWrites ( node ) ; } }
Finish the connect phase and potentially verify its liveness .
1,787
private void handleWrites ( final MemcachedNode node ) throws IOException { node . fillWriteBuffer ( shouldOptimize ) ; boolean canWriteMore = node . getBytesRemainingToWrite ( ) > 0 ; while ( canWriteMore ) { int wrote = node . writeSome ( ) ; metrics . updateHistogram ( OVERALL_AVG_BYTES_WRITE_METRIC , wrote ) ; node . fillWriteBuffer ( shouldOptimize ) ; canWriteMore = wrote > 0 && node . getBytesRemainingToWrite ( ) > 0 ; } }
Handle pending writes for the given node .
1,788
private void handleReads ( final MemcachedNode node ) throws IOException { Operation currentOp = node . getCurrentReadOp ( ) ; if ( currentOp instanceof TapAckOperationImpl ) { node . removeCurrentReadOp ( ) ; return ; } ByteBuffer rbuf = node . getRbuf ( ) ; final SocketChannel channel = node . getChannel ( ) ; int read = channel . read ( rbuf ) ; metrics . updateHistogram ( OVERALL_AVG_BYTES_READ_METRIC , read ) ; if ( read < 0 ) { currentOp = handleReadsWhenChannelEndOfStream ( currentOp , node , rbuf ) ; } while ( read > 0 ) { getLogger ( ) . debug ( "Read %d bytes" , read ) ; rbuf . flip ( ) ; while ( rbuf . remaining ( ) > 0 ) { if ( currentOp == null ) { throw new IllegalStateException ( "No read operation." ) ; } long timeOnWire = System . nanoTime ( ) - currentOp . getWriteCompleteTimestamp ( ) ; metrics . updateHistogram ( OVERALL_AVG_TIME_ON_WIRE_METRIC , ( int ) ( timeOnWire / 1000 ) ) ; metrics . markMeter ( OVERALL_RESPONSE_METRIC ) ; synchronized ( currentOp ) { readBufferAndLogMetrics ( currentOp , rbuf , node ) ; } currentOp = node . getCurrentReadOp ( ) ; } rbuf . clear ( ) ; read = channel . read ( rbuf ) ; node . completedRead ( ) ; } }
Handle pending reads for the given node .
1,789
private void readBufferAndLogMetrics ( final Operation currentOp , final ByteBuffer rbuf , final MemcachedNode node ) throws IOException { currentOp . readFromBuffer ( rbuf ) ; if ( currentOp . getState ( ) == OperationState . COMPLETE ) { getLogger ( ) . debug ( "Completed read op: %s and giving the next %d " + "bytes" , currentOp , rbuf . remaining ( ) ) ; Operation op = node . removeCurrentReadOp ( ) ; assert op == currentOp : "Expected to pop " + currentOp + " got " + op ; if ( op . hasErrored ( ) ) { metrics . markMeter ( OVERALL_RESPONSE_FAIL_METRIC ) ; } else { metrics . markMeter ( OVERALL_RESPONSE_SUCC_METRIC ) ; } } else if ( currentOp . getState ( ) == OperationState . RETRY ) { handleRetryInformation ( currentOp . getErrorMsg ( ) ) ; getLogger ( ) . debug ( "Reschedule read op due to NOT_MY_VBUCKET error: " + "%s " , currentOp ) ; ( ( VBucketAware ) currentOp ) . addNotMyVbucketNode ( currentOp . getHandlingNode ( ) ) ; Operation op = node . removeCurrentReadOp ( ) ; assert op == currentOp : "Expected to pop " + currentOp + " got " + op ; retryOperation ( currentOp ) ; metrics . markMeter ( OVERALL_RESPONSE_RETRY_METRIC ) ; } }
Read from the buffer and add metrics information .
1,790
private Operation handleReadsWhenChannelEndOfStream ( final Operation currentOp , final MemcachedNode node , final ByteBuffer rbuf ) throws IOException { if ( currentOp instanceof TapOperation ) { currentOp . getCallback ( ) . complete ( ) ; ( ( TapOperation ) currentOp ) . streamClosed ( OperationState . COMPLETE ) ; getLogger ( ) . debug ( "Completed read op: %s and giving the next %d bytes" , currentOp , rbuf . remaining ( ) ) ; Operation op = node . removeCurrentReadOp ( ) ; assert op == currentOp : "Expected to pop " + currentOp + " got " + op ; return node . getCurrentReadOp ( ) ; } else { throw new IOException ( "Disconnected unexpected, will reconnect." ) ; } }
Deal with an operation where the channel reached the end of a stream .
1,791
private void potentiallyCloseLeakingChannel ( final SocketChannel ch , final MemcachedNode node ) { if ( ch != null && ! ch . isConnected ( ) && ! ch . isConnectionPending ( ) ) { try { ch . close ( ) ; } catch ( IOException e ) { getLogger ( ) . error ( "Exception closing channel: %s" , node , e ) ; } } }
Make sure channel connections are not leaked and properly close under faulty reconnect cirumstances .
1,792
protected void addOperation ( final String key , final Operation o ) { MemcachedNode placeIn = null ; MemcachedNode primary = locator . getPrimary ( key ) ; if ( primary . isActive ( ) || failureMode == FailureMode . Retry ) { placeIn = primary ; } else if ( failureMode == FailureMode . Cancel ) { o . cancel ( ) ; } else { Iterator < MemcachedNode > i = locator . getSequence ( key ) ; while ( placeIn == null && i . hasNext ( ) ) { MemcachedNode n = i . next ( ) ; if ( n . isActive ( ) ) { placeIn = n ; } } if ( placeIn == null ) { placeIn = primary ; this . getLogger ( ) . warn ( "Could not redistribute to another node, " + "retrying primary node for %s." , key ) ; } } assert o . isCancelled ( ) || placeIn != null : "No node found for key " + key ; if ( placeIn != null ) { addOperation ( placeIn , o ) ; } else { assert o . isCancelled ( ) : "No node found for " + key + " (and not " + "immediately cancelled)" ; } }
Add an operation to a connection identified by the given key .
1,793
public void insertOperation ( final MemcachedNode node , final Operation o ) { o . setHandlingNode ( node ) ; o . initialize ( ) ; node . insertOp ( o ) ; addedQueue . offer ( node ) ; metrics . markMeter ( OVERALL_REQUEST_METRIC ) ; Selector s = selector . wakeup ( ) ; assert s == selector : "Wakeup returned the wrong selector." ; getLogger ( ) . debug ( "Added %s to %s" , o , node ) ; }
Insert an operation on the given node to the beginning of the queue .
1,794
protected void addOperation ( final MemcachedNode node , final Operation o ) { if ( ! node . isAuthenticated ( ) ) { retryOperation ( o ) ; return ; } o . setHandlingNode ( node ) ; o . initialize ( ) ; node . addOp ( o ) ; addedQueue . offer ( node ) ; metrics . markMeter ( OVERALL_REQUEST_METRIC ) ; Selector s = selector . wakeup ( ) ; assert s == selector : "Wakeup returned the wrong selector." ; getLogger ( ) . debug ( "Added %s to %s" , o , node ) ; }
Enqueue an operation on the given node .
1,795
public void addOperations ( final Map < MemcachedNode , Operation > ops ) { for ( Map . Entry < MemcachedNode , Operation > me : ops . entrySet ( ) ) { addOperation ( me . getKey ( ) , me . getValue ( ) ) ; } }
Enqueue the given list of operations on each handling node .
1,796
public CountDownLatch broadcastOperation ( final BroadcastOpFactory of , final Collection < MemcachedNode > nodes ) { final CountDownLatch latch = new CountDownLatch ( nodes . size ( ) ) ; for ( MemcachedNode node : nodes ) { getLogger ( ) . debug ( "broadcast Operation: node = " + node ) ; Operation op = of . newOp ( node , latch ) ; op . initialize ( ) ; node . addOp ( op ) ; op . setHandlingNode ( node ) ; addedQueue . offer ( node ) ; metrics . markMeter ( OVERALL_REQUEST_METRIC ) ; } Selector s = selector . wakeup ( ) ; assert s == selector : "Wakeup returned the wrong selector." ; return latch ; }
Broadcast an operation to a collection of nodes .
1,797
public void shutdown ( ) throws IOException { shutDown = true ; try { Selector s = selector . wakeup ( ) ; assert s == selector : "Wakeup returned the wrong selector." ; for ( MemcachedNode node : locator . getAll ( ) ) { if ( node . getChannel ( ) != null ) { node . getChannel ( ) . close ( ) ; node . setSk ( null ) ; if ( node . getBytesRemainingToWrite ( ) > 0 ) { getLogger ( ) . warn ( "Shut down with %d bytes remaining to write" , node . getBytesRemainingToWrite ( ) ) ; } getLogger ( ) . debug ( "Shut down channel %s" , node . getChannel ( ) ) ; } } selector . close ( ) ; getLogger ( ) . debug ( "Shut down selector %s" , selector ) ; } finally { running = false ; } }
Shut down all connections and do not accept further incoming ops .
1,798
public String connectionsStatus ( ) { StringBuilder connStatus = new StringBuilder ( ) ; connStatus . append ( "Connection Status {" ) ; for ( MemcachedNode node : locator . getAll ( ) ) { connStatus . append ( " " ) . append ( node . getSocketAddress ( ) ) . append ( " active: " ) . append ( node . isActive ( ) ) . append ( ", authed: " ) . append ( node . isAuthenticated ( ) ) . append ( MessageFormat . format ( ", last read: {0} ms ago" , node . lastReadDelta ( ) ) ) ; } connStatus . append ( " }" ) ; return connStatus . toString ( ) ; }
Construct a String containing information about all nodes and their state .
1,799
private static void setTimeout ( final Operation op , final boolean isTimeout ) { Logger logger = LoggerFactory . getLogger ( MemcachedConnection . class ) ; try { if ( op == null || op . isTimedOutUnsent ( ) ) { return ; } MemcachedNode node = op . getHandlingNode ( ) ; if ( node != null ) { node . setContinuousTimeout ( isTimeout ) ; } } catch ( Exception e ) { logger . error ( e . getMessage ( ) ) ; } }
Set the continuous timeout on an operation .