idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
21,200
static Method getMethod ( Class < ? > cls , String name ) throws NoSuchMethodException { NoSuchMethodException firstExc = null ; for ( Class < ? > c = cls ; c != null ; c = c . getSuperclass ( ) ) { try { return c . getDeclaredMethod ( name ) ; } catch ( NoSuchMethodException e ) { if ( firstExc == null ) { firstExc = e ; } } } throw firstExc ; }
Search for a method in the class and all superclasses .
21,201
static Method getGaugeMethod ( Registry registry , Id id , Object obj , String method ) { try { final Method m = Utils . getMethod ( obj . getClass ( ) , method ) ; try { final Number n = ( Number ) m . invoke ( obj ) ; REGISTRY_LOGGER . debug ( "registering gauge {}, using method [{}], with initial value {}" , id , m , n ) ; return m ; } catch ( Exception e ) { final String msg = "exception thrown invoking method [" + m + "], skipping registration of gauge " + id ; registry . propagate ( msg , e ) ; } } catch ( NoSuchMethodException e ) { final String mname = obj . getClass ( ) . getName ( ) + "." + method ; final String msg = "invalid method [" + mname + "], skipping registration of gauge " + id ; registry . propagate ( msg , e ) ; } return null ; }
Return a method supplying a value for a gauge .
21,202
public static Id normalize ( Id id ) { return ( new DefaultId ( id . name ( ) ) ) . withTags ( id . tags ( ) ) . normalize ( ) ; }
Returns a new id with the tag list sorted by key and with no duplicate keys .
21,203
public static Measurement first ( Iterable < Measurement > ms , Predicate < Measurement > p ) { Iterator < Measurement > it = filter ( ms , p ) . iterator ( ) ; return it . hasNext ( ) ? it . next ( ) : null ; }
Returns the first measurement that matches the predicate .
21,204
public static < T > List < T > toList ( Iterable < T > iter ) { List < T > buf = new ArrayList < > ( ) ; for ( T v : iter ) { buf . add ( v ) ; } return buf ; }
Returns a list with a copy of the data from the iterable .
21,205
public static < T > List < T > toList ( Iterator < T > iter ) { List < T > buf = new ArrayList < > ( ) ; while ( iter . hasNext ( ) ) { buf . add ( iter . next ( ) ) ; } return buf ; }
Returns a list with the data from the iterator .
21,206
@ SuppressWarnings ( "PMD.UnusedLocalVariable" ) public static < T > int size ( Iterable < T > iter ) { if ( iter instanceof ArrayTagSet ) { return ( ( ArrayTagSet ) iter ) . size ( ) ; } else if ( iter instanceof Collection < ? > ) { return ( ( Collection < ? > ) iter ) . size ( ) ; } else { int size = 0 ; for ( T v : iter ) { ++ size ; } return size ; } }
Returns the size of an iterable . This method should only be used with fixed size collections . It will attempt to find an efficient method to get the size before falling back to a traversal of the iterable .
21,207
static Iterable < Tag > toIterable ( String [ ] tags ) { if ( tags . length % 2 == 1 ) { throw new IllegalArgumentException ( "size must be even, it is a set of key=value pairs" ) ; } ArrayList < Tag > ts = new ArrayList < > ( tags . length / 2 ) ; for ( int i = 0 ; i < tags . length ; i += 2 ) { ts . add ( new BasicTag ( tags [ i ] , tags [ i + 1 ] ) ) ; } return ts ; }
Returns an iterable of tags based on a string array .
21,208
public static void propagateTypeError ( Registry registry , Id id , Class < ? > desiredClass , Class < ? > actualClass ) { final String dType = desiredClass . getName ( ) ; final String aType = actualClass . getName ( ) ; final String msg = String . format ( "cannot access '%s' as a %s, it already exists as a %s" , id , dType , aType ) ; registry . propagate ( new IllegalStateException ( msg ) ) ; }
Propagate a type error exception . Used in situations where an existing id has already been registered but with a different class .
21,209
public static void addToRootLogger ( Registry registry , String name , boolean ignoreExceptions ) { final Appender appender = new SpectatorAppender ( registry , name , null , null , ignoreExceptions ) ; appender . start ( ) ; LoggerContext context = ( LoggerContext ) LogManager . getContext ( false ) ; Configuration config = context . getConfiguration ( ) ; addToRootLogger ( appender ) ; config . addListener ( reconfigurable -> addToRootLogger ( appender ) ) ; }
Add the spectator appender to the root logger . This method is intended to be called once as part of the applications initialization process .
21,210
public static SpectatorAppender createAppender ( @ PluginAttribute ( "name" ) String name , @ PluginAttribute ( "ignoreExceptions" ) boolean ignoreExceptions , @ PluginElement ( "Layout" ) Layout < ? extends Serializable > layout , @ PluginElement ( "Filters" ) Filter filter ) { if ( name == null ) { LOGGER . error ( "no name provided for SpectatorAppender" ) ; return null ; } return new SpectatorAppender ( Spectator . globalRegistry ( ) , name , filter , layout , ignoreExceptions ) ; }
Create a new instance of the appender using the global spectator registry .
21,211
public static LongTaskTimer get ( Registry registry , Id id ) { ConcurrentMap < Id , Object > state = registry . state ( ) ; Object obj = Utils . computeIfAbsent ( state , id , i -> { LongTaskTimer timer = new LongTaskTimer ( registry , id ) ; PolledMeter . using ( registry ) . withId ( id ) . withTag ( Statistic . activeTasks ) . monitorValue ( timer , LongTaskTimer :: activeTasks ) ; PolledMeter . using ( registry ) . withId ( id ) . withTag ( Statistic . duration ) . monitorValue ( timer , t -> t . duration ( ) / NANOS_PER_SECOND ) ; return timer ; } ) ; if ( ! ( obj instanceof LongTaskTimer ) ) { Utils . propagateTypeError ( registry , id , LongTaskTimer . class , obj . getClass ( ) ) ; obj = new LongTaskTimer ( new NoopRegistry ( ) , id ) ; } return ( LongTaskTimer ) obj ; }
Creates a timer for tracking long running tasks .
21,212
void refresh ( ) { try { HttpResponse res = client . get ( uri ) . withConnectTimeout ( connectTimeout ) . withReadTimeout ( readTimeout ) . addHeader ( "If-None-Match" , etag ) . send ( ) . decompress ( ) ; if ( res . status ( ) == 304 ) { LOGGER . debug ( "no modification to subscriptions" ) ; } else if ( res . status ( ) != 200 ) { LOGGER . warn ( "failed to update subscriptions, received status {}" , res . status ( ) ) ; } else { etag = res . header ( "ETag" ) ; payload = filterByStep ( mapper . readValue ( res . entity ( ) , Subscriptions . class ) ) ; } } catch ( Exception e ) { LOGGER . warn ( "failed to update subscriptions (uri={})" , uri , e ) ; } if ( payload != null ) { long now = clock . wallTime ( ) ; payload . update ( subscriptions , now , now + configTTL ) ; } }
Refresh the subscriptions from the server .
21,213
@ SuppressWarnings ( "PMD.AvoidCatchingThrowable" ) static String mkString ( Object obj ) { if ( obj == null ) { return "null" ; } try { return obj . toString ( ) + " (type is " + obj . getClass ( ) + ")" ; } catch ( Throwable t ) { return t . getClass ( ) . toString ( ) + ": " + t . getMessage ( ) + " (type is " + obj . getClass ( ) + ")" ; } }
Convert object to string and checking if it fails .
21,214
static GcType getGcType ( String name ) { GcType t = KNOWN_COLLECTOR_NAMES . get ( name ) ; return ( t == null ) ? GcType . UNKNOWN : t ; }
Determine the type old or young based on the name of the collector .
21,215
static long getTotalUsage ( Map < String , MemoryUsage > usages ) { long sum = 0L ; for ( Map . Entry < String , MemoryUsage > e : usages . entrySet ( ) ) { sum += e . getValue ( ) . getUsed ( ) ; } return sum ; }
Compute the total usage across all pools .
21,216
static long getTotalMaxUsage ( Map < String , MemoryUsage > usages ) { long sum = 0L ; for ( Map . Entry < String , MemoryUsage > e : usages . entrySet ( ) ) { long max = e . getValue ( ) . getMax ( ) ; if ( max > 0 ) { sum += e . getValue ( ) . getMax ( ) ; } } return sum ; }
Compute the max usage across all pools .
21,217
static long getPromotionSize ( GcInfo info ) { long totalBefore = getTotalUsage ( info . getMemoryUsageBeforeGc ( ) ) ; long totalAfter = getTotalUsage ( info . getMemoryUsageAfterGc ( ) ) ; return totalAfter - totalBefore ; }
Compute the amount of data promoted during a GC event .
21,218
void addAndGet ( long amount ) { for ( int i = 0 ; i < ServoPollers . NUM_POLLERS ; ++ i ) { getCurrent ( i ) . addAndGet ( amount ) ; } }
Add to the current bucket .
21,219
AtomicLong getCurrent ( int pollerIndex ) { rollCount ( pollerIndex , clock . now ( ) ) ; return data [ 2 * pollerIndex + CURRENT ] ; }
Get the AtomicLong for the current bucket .
21,220
Long poll ( int pollerIndex ) { final long now = clock . now ( ) ; final long step = ServoPollers . POLLING_INTERVALS [ pollerIndex ] ; rollCount ( pollerIndex , now ) ; final int prevPos = 2 * pollerIndex + PREVIOUS ; final long value = data [ prevPos ] . get ( ) ; final long last = lastPollTime [ pollerIndex ] . getAndSet ( now ) ; final long missed = ( now - last ) / step - 1 ; if ( last / step == now / step ) { return value ; } else if ( last > 0L && missed > 0L ) { return null ; } else { return value ; } }
Get the value for the last completed interval .
21,221
static String substitute ( String pattern , Map < String , String > vars ) { String value = pattern ; for ( Map . Entry < String , String > entry : vars . entrySet ( ) ) { String raw = entry . getValue ( ) ; String v = Introspector . decapitalize ( raw ) ; value = value . replace ( "{raw:" + entry . getKey ( ) + "}" , raw ) ; value = value . replace ( "{" + entry . getKey ( ) + "}" , v ) ; } return value ; }
Substitute named variables in the pattern string with the corresponding values in the variables map .
21,222
@ SuppressWarnings ( "PMD" ) static Double eval ( String expr , Map < String , ? extends Number > vars ) { Deque < Double > stack = new ArrayDeque < > ( ) ; String [ ] parts = expr . split ( "[,\\s]+" ) ; for ( String part : parts ) { switch ( part ) { case ":add" : binaryOp ( stack , ( a , b ) -> a + b ) ; break ; case ":sub" : binaryOp ( stack , ( a , b ) -> a - b ) ; break ; case ":mul" : binaryOp ( stack , ( a , b ) -> a * b ) ; break ; case ":div" : binaryOp ( stack , ( a , b ) -> a / b ) ; break ; case ":if-changed" : ifChanged ( stack ) ; break ; default : if ( part . startsWith ( "{" ) && part . endsWith ( "}" ) ) { Number v = vars . get ( part . substring ( 1 , part . length ( ) - 1 ) ) ; if ( v == null ) v = Double . NaN ; stack . addFirst ( v . doubleValue ( ) ) ; } else { stack . addFirst ( Double . parseDouble ( part ) ) ; } break ; } } return stack . removeFirst ( ) ; }
Evaluate a simple stack expression for the value .
21,223
public void stop ( ) { if ( scheduler != null ) { scheduler . shutdown ( ) ; scheduler = null ; logger . info ( "flushing metrics before stopping the registry" ) ; collectData ( ) ; logger . info ( "stopped collecting metrics every {} reporting to {}" , frequency , uri ) ; } else { logger . warn ( "registry stopped, but was never started" ) ; } }
Stop the scheduler reporting data .
21,224
MonitorConfig toMonitorConfig ( Id id , Tag stat ) { MonitorConfig . Builder builder = new MonitorConfig . Builder ( id . name ( ) ) ; if ( stat != null ) { builder . withTag ( stat . key ( ) , stat . value ( ) ) ; } for ( Tag t : id . tags ( ) ) { builder . withTag ( t . key ( ) , t . value ( ) ) ; } return builder . build ( ) ; }
Converts a spectator id into a MonitorConfig that can be used by servo .
21,225
public static void logClientRequest ( Logger logger , HttpLogEntry entry ) { log ( logger , CLIENT , entry ) ; }
Log a client request .
21,226
public static void logServerRequest ( Logger logger , HttpLogEntry entry ) { log ( logger , SERVER , entry ) ; }
Log a request received by a server .
21,227
public HttpLogEntry withRequestUri ( String uri , String path ) { this . requestUri = uri ; this . path = path ; return this ; }
Set the URI for the actual http request .
21,228
public HttpLogEntry withRequestHeader ( String name , String value ) { requestHeaders . add ( new Header ( name , value ) ) ; return this ; }
Add a header that was on the request .
21,229
public HttpLogEntry withResponseHeader ( String name , String value ) { responseHeaders . add ( new Header ( name , value ) ) ; return this ; }
Add a header that was on the response .
21,230
public long getLatency ( ) { if ( latency >= 0L ) { return latency ; } else if ( events . size ( ) >= 2 ) { return events . get ( events . size ( ) - 1 ) . timestamp ( ) - events . get ( 0 ) . timestamp ( ) ; } else { return - 1 ; } }
Return the latency for the request . If not explicitly set it will be calculated from the events .
21,231
public long getOverallLatency ( ) { if ( maxAttempts <= 1 || originalStart < 0 ) { return getLatency ( ) ; } else if ( events . isEmpty ( ) ) { return - 1 ; } else { return events . get ( events . size ( ) - 1 ) . timestamp ( ) - originalStart ; } }
Return the overall latency for a group of requests including all retries .
21,232
public String getStartTime ( ) { return events . isEmpty ( ) ? "unknown" : isoDate . format ( new Date ( events . get ( 0 ) . timestamp ( ) ) ) ; }
Return the starting time for the request .
21,233
public String getTimeline ( ) { StringBuilder builder = new StringBuilder ( ) ; for ( Event event : events ) { builder . append ( event . name ( ) ) . append ( ":" ) . append ( event . timestamp ( ) ) . append ( ";" ) ; } return builder . toString ( ) ; }
Return a time line based on marked events .
21,234
public HttpRequestBuilder addHeader ( String name , String value ) { reqHeaders . put ( name , value ) ; entry . withRequestHeader ( name , value ) ; return this ; }
Add a header to the request . Note the content type will be set automatically when providing the content payload and should not be set here .
21,235
public HttpRequestBuilder withContent ( String type , String content ) { return withContent ( type , content . getBytes ( StandardCharsets . UTF_8 ) ) ; }
Set the request body .
21,236
public HttpRequestBuilder compress ( int level ) throws IOException { addHeader ( "Content-Encoding" , "gzip" ) ; entity = HttpUtils . gzip ( entity , level ) ; return this ; }
Compress the request body using the specified compression level . The content must have already been set on the builder .
21,237
public HttpRequestBuilder withRetries ( int n ) { Preconditions . checkArg ( n >= 0 , "number of retries must be >= 0" ) ; this . numAttempts = n + 1 ; entry . withMaxAttempts ( numAttempts ) ; return this ; }
How many times to retry if the intial attempt fails?
21,238
public static long [ ] asArray ( ) { long [ ] values = new long [ BUCKET_VALUES . length ] ; System . arraycopy ( BUCKET_VALUES , 0 , values , 0 , BUCKET_VALUES . length ) ; return values ; }
Returns a copy of the bucket values array .
21,239
public static < T > T [ ] map ( Class < T > c , Function < Long , T > f ) { @ SuppressWarnings ( "unchecked" ) T [ ] values = ( T [ ] ) Array . newInstance ( c , BUCKET_VALUES . length ) ; for ( int i = 0 ; i < BUCKET_VALUES . length ; ++ i ) { values [ i ] = f . apply ( BUCKET_VALUES [ i ] ) ; } return values ; }
Map the bucket values to a new array of a different type .
21,240
public static void percentiles ( long [ ] counts , double [ ] pcts , double [ ] results ) { Preconditions . checkArg ( counts . length == BUCKET_VALUES . length , "counts is not the same size as buckets array" ) ; Preconditions . checkArg ( pcts . length > 0 , "pct array cannot be empty" ) ; Preconditions . checkArg ( pcts . length == results . length , "pcts is not the same size as results array" ) ; long total = 0L ; for ( long c : counts ) { total += c ; } int pctIdx = 0 ; long prev = 0 ; double prevP = 0.0 ; long prevB = 0 ; for ( int i = 0 ; i < BUCKET_VALUES . length ; ++ i ) { long next = prev + counts [ i ] ; double nextP = 100.0 * next / total ; long nextB = BUCKET_VALUES [ i ] ; while ( pctIdx < pcts . length && nextP >= pcts [ pctIdx ] ) { double f = ( pcts [ pctIdx ] - prevP ) / ( nextP - prevP ) ; results [ pctIdx ] = f * ( nextB - prevB ) + prevB ; ++ pctIdx ; } if ( pctIdx >= pcts . length ) break ; prev = next ; prevP = nextP ; prevB = nextB ; } double nextP = 100.0 ; long nextB = Long . MAX_VALUE ; while ( pctIdx < pcts . length ) { double f = ( pcts [ pctIdx ] - prevP ) / ( nextP - prevP ) ; results [ pctIdx ] = f * ( nextB - prevB ) + prevB ; ++ pctIdx ; } }
Compute a set of percentiles based on the counts for the buckets .
21,241
public static double percentile ( long [ ] counts , double p ) { double [ ] pcts = new double [ ] { p } ; double [ ] results = new double [ 1 ] ; percentiles ( counts , pcts , results ) ; return results [ 0 ] ; }
Compute a percentile based on the counts for the buckets .
21,242
long getInitialDelay ( long stepSize ) { long now = clock ( ) . wallTime ( ) ; long stepBoundary = now / stepSize * stepSize ; long offset = stepSize / 10 ; long delay = now - stepBoundary ; if ( delay < offset ) { return delay + offset ; } else if ( delay > stepSize - offset ) { return stepSize - offset ; } else { return delay ; } }
Avoid collecting right on boundaries to minimize transitions on step longs during a collection . Randomly distribute across the middle of the step interval .
21,243
public void stop ( ) { if ( scheduler != null ) { scheduler . shutdown ( ) ; scheduler = null ; logger . info ( "stopped collecting metrics every {}ms reporting to {}" , step , uri ) ; } else { logger . warn ( "registry stopped, but was never started" ) ; } }
Stop the scheduler reporting Atlas data .
21,244
void collectData ( ) { if ( config . lwcEnabled ( ) ) { try { handleSubscriptions ( ) ; } catch ( Exception e ) { logger . warn ( "failed to handle subscriptions" , e ) ; } } else { logger . debug ( "lwc is disabled, skipping subscriptions" ) ; } if ( config . enabled ( ) ) { try { for ( List < Measurement > batch : getBatches ( ) ) { PublishPayload p = new PublishPayload ( commonTags , batch ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "publish payload: {}" , jsonMapper . writeValueAsString ( p ) ) ; } HttpResponse res = client . post ( uri ) . withConnectTimeout ( connectTimeout ) . withReadTimeout ( readTimeout ) . withContent ( "application/x-jackson-smile" , smileMapper . writeValueAsBytes ( p ) ) . send ( ) ; Instant date = res . dateHeader ( "Date" ) ; recordClockSkew ( ( date == null ) ? 0L : date . toEpochMilli ( ) ) ; } } catch ( Exception e ) { logger . warn ( "failed to send metrics (uri={})" , uri , e ) ; } } else { logger . debug ( "publishing is disabled, skipping collection" ) ; } removeExpiredMeters ( ) ; }
Collect data and send to Atlas .
21,245
private void recordClockSkew ( long responseTimestamp ) { if ( responseTimestamp == 0L ) { logger . debug ( "no date timestamp on response, cannot record skew" ) ; } else { final long delta = clock ( ) . wallTime ( ) - responseTimestamp ; if ( delta >= 0L ) { timer ( CLOCK_SKEW_TIMER , "id" , "fast" ) . record ( delta , TimeUnit . MILLISECONDS ) ; } else { timer ( CLOCK_SKEW_TIMER , "id" , "slow" ) . record ( - delta , TimeUnit . MILLISECONDS ) ; } logger . debug ( "clock skew between client and server: {}ms" , delta ) ; } }
Record the difference between the date response time and the local time on the server . This is used to get a rough idea of the amount of skew in the environment . Ideally it should be fairly small . The date header will only have seconds so we expect to regularly have differences of up to 1 second . Note that it is a rough estimate and could be elevated because of unrelated problems like GC or network delays .
21,246
List < List < Measurement > > getBatches ( ) { List < List < Measurement > > batches = new ArrayList < > ( ) ; List < Measurement > ms = getMeasurements ( ) . collect ( Collectors . toList ( ) ) ; for ( int i = 0 ; i < ms . size ( ) ; i += batchSize ) { List < Measurement > batch = ms . subList ( i , Math . min ( ms . size ( ) , i + batchSize ) ) ; batches . add ( batch ) ; } return batches ; }
Get a list of all measurements and break them into batches .
21,247
public static AsciiSet control ( ) { final boolean [ ] members = new boolean [ 128 ] ; for ( char c = 0 ; c < members . length ; ++ c ) { members [ c ] = Character . isISOControl ( c ) ; } return new AsciiSet ( members ) ; }
Returns a set that matches ascii control characters .
21,248
private static String toPattern ( boolean [ ] members ) { StringBuilder buf = new StringBuilder ( ) ; if ( members [ '-' ] ) { buf . append ( '-' ) ; } boolean previous = false ; char s = 0 ; for ( int i = 0 ; i < members . length ; ++ i ) { if ( members [ i ] && ! previous ) { s = ( char ) i ; } else if ( ! members [ i ] && previous ) { final char e = ( char ) ( i - 1 ) ; append ( buf , s , e ) ; } previous = members [ i ] ; } if ( previous ) { final char e = ( char ) ( members . length - 1 ) ; append ( buf , s , e ) ; } return buf . toString ( ) ; }
Converts the members array to a pattern string . Used to provide a user friendly toString implementation for the set .
21,249
public boolean containsAll ( CharSequence str ) { final int n = str . length ( ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( ! contains ( str . charAt ( i ) ) ) { return false ; } } return true ; }
Returns true if all characters in the string are contained within the set .
21,250
public String replaceNonMembers ( String input , char replacement ) { if ( ! contains ( replacement ) ) { throw new IllegalArgumentException ( replacement + " is not a member of " + pattern ) ; } return containsAll ( input ) ? input : replaceNonMembersImpl ( input , replacement ) ; }
Replace all characters in the input string with the replacement character .
21,251
public AsciiSet union ( AsciiSet set ) { final boolean [ ] unionMembers = new boolean [ 128 ] ; for ( int i = 0 ; i < unionMembers . length ; ++ i ) { unionMembers [ i ] = members [ i ] || set . members [ i ] ; } return new AsciiSet ( unionMembers ) ; }
Returns a new set that will match characters either in the this set or in the set that is provided .
21,252
public AsciiSet intersection ( AsciiSet set ) { final boolean [ ] intersectionMembers = new boolean [ 128 ] ; for ( int i = 0 ; i < intersectionMembers . length ; ++ i ) { intersectionMembers [ i ] = members [ i ] && set . members [ i ] ; } return new AsciiSet ( intersectionMembers ) ; }
Returns a new set that will match characters iff they are included this set and in the set that is provided .
21,253
public AsciiSet diff ( AsciiSet set ) { final boolean [ ] diffMembers = new boolean [ 128 ] ; for ( int i = 0 ; i < diffMembers . length ; ++ i ) { diffMembers [ i ] = members [ i ] && ! set . members [ i ] ; } return new AsciiSet ( diffMembers ) ; }
Returns a new set that will match characters iff they are included this set and not in the set that is provided .
21,254
public AsciiSet invert ( ) { final boolean [ ] invertMembers = new boolean [ 128 ] ; for ( int i = 0 ; i < invertMembers . length ; ++ i ) { invertMembers [ i ] = ! members [ i ] ; } return new AsciiSet ( invertMembers ) ; }
Returns a new set that will match characters that are not included this set .
21,255
public Optional < Character > character ( ) { char c = 0 ; int count = 0 ; for ( int i = 0 ; i < members . length ; ++ i ) { if ( members [ i ] ) { c = ( char ) i ; ++ count ; } } return ( count == 1 ) ? Optional . of ( c ) : Optional . empty ( ) ; }
If this set matches a single character then return an optional with that character . Otherwise return an empty optional .
21,256
public static PrototypeMeasurementFilterSpecification loadFromPath ( String path ) throws IOException { byte [ ] jsonData = Files . readAllBytes ( Paths . get ( path ) ) ; ObjectMapper objectMapper = new ObjectMapper ( ) ; return objectMapper . readValue ( jsonData , PrototypeMeasurementFilterSpecification . class ) ; }
Loads a specification from a file .
21,257
public static Registry run ( String type , String test ) { Registry registry = createRegistry ( type ) ; TESTS . get ( test ) . accept ( registry ) ; return registry ; }
Run a test for a given type of registry .
21,258
@ SuppressWarnings ( "PMD" ) public static void main ( String [ ] args ) { if ( args . length < 2 ) { System . out . println ( "Usage: perf <registry> <test>" ) ; System . exit ( 1 ) ; } Registry registry = run ( args [ 0 ] , args [ 1 ] ) ; GraphLayout igraph = GraphLayout . parseInstance ( registry ) ; System . out . println ( igraph . toFootprint ( ) ) ; }
Run a test and output the memory footprint of the registry .
21,259
public static Map < String , String > extractFrom ( Function < String , String > env ) { Map < String , String > headers = new LinkedHashMap < > ( ) ; addHeader ( headers , env , NetflixHeader . ASG , NETFLIX_ASG ) ; addHeader ( headers , env , NetflixHeader . Node , NETFLIX_NODE ) ; addHeader ( headers , env , NetflixHeader . Zone , NETFLIX_ZONE ) ; return headers ; }
Extract common Netflix headers from the specified function for retrieving the value of an environment variable .
21,260
public Evaluator sync ( Map < String , List < Subscription > > subs ) { Set < String > removed = subscriptions . keySet ( ) ; removed . removeAll ( subs . keySet ( ) ) ; removed . forEach ( this :: removeGroupSubscriptions ) ; subs . forEach ( this :: addGroupSubscriptions ) ; return this ; }
Synchronize the internal set of subscriptions with the map that is passed in .
21,261
public Evaluator addGroupSubscriptions ( String group , List < Subscription > subs ) { List < Subscription > oldSubs = subscriptions . put ( group , subs ) ; if ( oldSubs == null ) { LOGGER . debug ( "added group {} with {} subscriptions" , group , subs . size ( ) ) ; } else { LOGGER . debug ( "updated group {}, {} subscriptions before, {} subscriptions now" , group , oldSubs . size ( ) , subs . size ( ) ) ; } return this ; }
Add subscriptions for a given group .
21,262
public Evaluator removeGroupSubscriptions ( String group ) { List < Subscription > oldSubs = subscriptions . remove ( group ) ; if ( oldSubs != null ) { LOGGER . debug ( "removed group {} with {} subscriptions" , group , oldSubs . size ( ) ) ; } return this ; }
Remove subscriptions for a given group .
21,263
public EvalPayload eval ( String group , long timestamp , List < TagsValuePair > vs ) { List < Subscription > subs = subscriptions . getOrDefault ( group , Collections . emptyList ( ) ) ; List < EvalPayload . Metric > metrics = new ArrayList < > ( ) ; for ( Subscription s : subs ) { DataExpr expr = s . dataExpr ( ) ; for ( TagsValuePair pair : expr . eval ( vs ) ) { EvalPayload . Metric m = new EvalPayload . Metric ( s . getId ( ) , pair . tags ( ) , pair . value ( ) ) ; metrics . add ( m ) ; } } return new EvalPayload ( timestamp , metrics ) ; }
Evaluate expressions for all subscriptions associated with the specified group using the provided data .
21,264
public static void update ( Registry registry ) { Iterator < Map . Entry < Id , Object > > iter = registry . state ( ) . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry < Id , Object > entry = iter . next ( ) ; if ( entry . getValue ( ) instanceof AbstractMeterState ) { AbstractMeterState tuple = ( AbstractMeterState ) entry . getValue ( ) ; tuple . doUpdate ( registry ) ; if ( tuple . hasExpired ( ) ) { iter . remove ( ) ; } } } }
Force the polling of all meters associated with the registry .
21,265
public IncludeExcludePatterns metricToPatterns ( String metric ) { IncludeExcludePatterns foundPatterns = metricNameToPatterns . get ( metric ) ; if ( foundPatterns != null ) { return foundPatterns ; } foundPatterns = new IncludeExcludePatterns ( ) ; for ( MeterFilterPattern meterPattern : includePatterns ) { if ( meterPattern . namePattern . matcher ( metric ) . matches ( ) ) { foundPatterns . include . addAll ( meterPattern . values ) ; } } for ( MeterFilterPattern meterPattern : excludePatterns ) { if ( meterPattern . namePattern . matcher ( metric ) . matches ( ) ) { foundPatterns . exclude . addAll ( meterPattern . values ) ; } } metricNameToPatterns . put ( metric , foundPatterns ) ; return foundPatterns ; }
Find the IncludeExcludePatterns for filtering a given metric .
21,266
public static PrototypeMeasurementFilter loadFromPath ( String path ) throws IOException { PrototypeMeasurementFilterSpecification spec = PrototypeMeasurementFilterSpecification . loadFromPath ( path ) ; return new PrototypeMeasurementFilter ( spec ) ; }
Factory method building a filter from a specification file .
21,267
public HttpRequestBuilder addHeader ( String name , String value ) { if ( value != null ) { reqHeaders . put ( name , value ) ; } return this ; }
Add a header to the request . Note the content type will be set automatically when providing the content payload and should not be set here . If the value is null then the header will get ignored .
21,268
static Matcher optimize ( Matcher matcher ) { Matcher m = matcher ; Matcher opt = optimizeSinglePass ( m ) ; for ( int i = 0 ; ! m . equals ( opt ) && i < MAX_ITERATIONS ; ++ i ) { m = opt ; opt = optimizeSinglePass ( m ) ; } return opt ; }
Return a new instance of the matcher that has been optimized .
21,269
static Matcher mergeNext ( Matcher matcher ) { if ( matcher instanceof SeqMatcher ) { List < Matcher > matchers = matcher . < SeqMatcher > as ( ) . matchers ( ) ; List < Matcher > ms = new ArrayList < > ( ) ; for ( int i = 0 ; i < matchers . size ( ) ; ++ i ) { Matcher m = matchers . get ( i ) ; if ( m instanceof GreedyMatcher ) { List < Matcher > after = matchers . subList ( i + 1 , matchers . size ( ) ) ; ms . add ( m . < GreedyMatcher > as ( ) . mergeNext ( SeqMatcher . create ( after ) ) ) ; break ; } else { ms . add ( m ) ; } } return SeqMatcher . create ( ms ) ; } return matcher ; }
For greedy matchers go ahead and include the next portion of the match so it can be checked as we go along . Since there is no support for capturing the value we can stop as soon as it is detected there would be a match rather than finding the largest possible match .
21,270
static Matcher removeTrueInSequence ( Matcher matcher ) { if ( matcher instanceof SeqMatcher ) { List < Matcher > matchers = matcher . < SeqMatcher > as ( ) . matchers ( ) ; List < Matcher > ms = new ArrayList < > ( ) ; for ( Matcher m : matchers ) { if ( ! ( m instanceof TrueMatcher ) ) { ms . add ( m ) ; } } return SeqMatcher . create ( ms ) ; } return matcher ; }
The true matcher is sometimes used as a placeholder while parsing . For sequences it isn t needed and it is faster to leave them out .
21,271
static Matcher sequenceWithFalseIsFalse ( Matcher matcher ) { if ( matcher instanceof SeqMatcher ) { for ( Matcher m : matcher . < SeqMatcher > as ( ) . matchers ( ) ) { if ( m instanceof FalseMatcher ) { return FalseMatcher . INSTANCE ; } } } return matcher ; }
If a sequence contains an explicit false matcher then the whole sequence will never match and can be treated as false .
21,272
static Matcher sequenceWithStuffAfterEndIsFalse ( Matcher matcher ) { if ( matcher instanceof SeqMatcher ) { boolean end = false ; for ( Matcher m : matcher . < SeqMatcher > as ( ) . matchers ( ) ) { if ( m instanceof EndMatcher ) { end = true ; } else if ( end && ! m . alwaysMatches ( ) ) { return FalseMatcher . INSTANCE ; } } } return matcher ; }
If a sequence contains content after an end anchor then it will never be able to match and can be treated as false .
21,273
static Matcher convertEmptyCharClassToFalse ( Matcher matcher ) { if ( matcher instanceof CharClassMatcher ) { return matcher . < CharClassMatcher > as ( ) . set ( ) . isEmpty ( ) ? FalseMatcher . INSTANCE : matcher ; } return matcher ; }
If a character class is empty then it will not match anything and can be treated as false .
21,274
static Matcher inlineMatchAnyPrecedingOr ( Matcher matcher ) { if ( matcher instanceof ZeroOrMoreMatcher ) { ZeroOrMoreMatcher zm = matcher . as ( ) ; if ( zm . repeated ( ) instanceof AnyMatcher && zm . next ( ) instanceof OrMatcher ) { List < Matcher > matchers = zm . next ( ) . < OrMatcher > as ( ) . matchers ( ) ; List < Matcher > ms = new ArrayList < > ( ) ; for ( Matcher m : matchers ) { ms . add ( new ZeroOrMoreMatcher ( AnyMatcher . INSTANCE , m ) ) ; } return OrMatcher . create ( ms ) ; } } return matcher ; }
If the matcher preceding an OR clause is a repeated any match move into each branch of the OR clause . This allows for other optimizations such as conversion to an indexOf to take effect for each branch .
21,275
static Matcher startsWithCharSeq ( Matcher matcher ) { if ( matcher instanceof SeqMatcher ) { List < Matcher > matchers = matcher . < SeqMatcher > as ( ) . matchers ( ) ; if ( matchers . size ( ) >= 2 && matchers . get ( 0 ) instanceof StartMatcher && matchers . get ( 1 ) instanceof CharSeqMatcher ) { List < Matcher > ms = new ArrayList < > ( ) ; ms . add ( new StartsWithMatcher ( matchers . get ( 1 ) . < CharSeqMatcher > as ( ) . pattern ( ) ) ) ; ms . addAll ( matchers . subList ( 2 , matchers . size ( ) ) ) ; return SeqMatcher . create ( ms ) ; } } return matcher ; }
If the matcher has a start anchored character sequence then replace it with a StartsWithMatcher . In a tight loop this is much faster than a running with a sequence of two matchers .
21,276
static Matcher combineCharSeqAfterStartsWith ( Matcher matcher ) { if ( matcher instanceof SeqMatcher ) { List < Matcher > matchers = matcher . < SeqMatcher > as ( ) . matchers ( ) ; if ( matchers . size ( ) >= 2 && matchers . get ( 0 ) instanceof StartsWithMatcher && matchers . get ( 1 ) instanceof CharSeqMatcher ) { List < Matcher > ms = new ArrayList < > ( ) ; String prefix = matchers . get ( 0 ) . < StartsWithMatcher > as ( ) . pattern ( ) + matchers . get ( 1 ) . < CharSeqMatcher > as ( ) . pattern ( ) ; ms . add ( new StartsWithMatcher ( prefix ) ) ; ms . addAll ( matchers . subList ( 2 , matchers . size ( ) ) ) ; return SeqMatcher . create ( ms ) ; } else { return matcher ; } } return matcher ; }
If a char sequence is adjacent to a starts with matcher then append the sequence to the prefix pattern of the starts with matcher .
21,277
static Matcher combineCharSeqAfterIndexOf ( Matcher matcher ) { if ( matcher instanceof IndexOfMatcher ) { IndexOfMatcher m = matcher . as ( ) ; Matcher next = PatternUtils . head ( m . next ( ) ) ; if ( next instanceof CharSeqMatcher ) { String pattern = m . pattern ( ) + next . < CharSeqMatcher > as ( ) . pattern ( ) ; return new IndexOfMatcher ( pattern , PatternUtils . tail ( m . next ( ) ) ) ; } } return matcher ; }
If a char sequence is adjacent to an index of matcher then append the sequence to the pattern of the index of matcher .
21,278
static Matcher combineAdjacentCharSeqs ( Matcher matcher ) { if ( matcher instanceof SeqMatcher ) { List < Matcher > matchers = matcher . < SeqMatcher > as ( ) . matchers ( ) ; List < Matcher > ms = new ArrayList < > ( ) ; CharSeqMatcher cs1 = null ; for ( Matcher m : matchers ) { if ( m instanceof CharSeqMatcher ) { if ( cs1 == null ) { cs1 = m . as ( ) ; } else { CharSeqMatcher cs2 = m . as ( ) ; cs1 = new CharSeqMatcher ( cs1 . pattern ( ) + cs2 . pattern ( ) ) ; } } else { if ( cs1 != null ) { ms . add ( cs1 ) ; cs1 = null ; } ms . add ( m ) ; } } if ( cs1 != null ) { ms . add ( cs1 ) ; } return SeqMatcher . create ( ms ) ; } return matcher ; }
If a char sequence is adjacent to another char sequence then concatenate the sequences .
21,279
static Matcher removeRepeatedStart ( Matcher matcher ) { if ( matcher instanceof ZeroOrMoreMatcher ) { ZeroOrMoreMatcher zm = matcher . as ( ) ; if ( zm . repeated ( ) instanceof StartMatcher ) { return zm . next ( ) ; } } return matcher ; }
Zero or more start anchors is the same as not being anchored by the start .
21,280
static Matcher combineAdjacentStart ( Matcher matcher ) { if ( matcher instanceof SeqMatcher ) { List < Matcher > matchers = matcher . < SeqMatcher > as ( ) . matchers ( ) ; if ( ! matchers . isEmpty ( ) && matchers . get ( 0 ) instanceof StartMatcher ) { List < Matcher > ms = new ArrayList < > ( ) ; ms . add ( StartMatcher . INSTANCE ) ; int pos = 0 ; for ( Matcher m : matchers ) { if ( m instanceof StartMatcher ) { ++ pos ; } else { break ; } } ms . addAll ( matchers . subList ( pos , matchers . size ( ) ) ) ; return SeqMatcher . create ( ms ) ; } } return matcher ; }
Multiple adjacent start anchors can be reduced to a single start anchor .
21,281
public Predicate < Measurement > getDefaultMeasurementFilter ( ) throws IOException { if ( defaultMeasurementFilter != null ) { return defaultMeasurementFilter ; } if ( ! prototypeFilterPath . isEmpty ( ) ) { defaultMeasurementFilter = PrototypeMeasurementFilter . loadFromPath ( prototypeFilterPath ) ; } else { defaultMeasurementFilter = ALL_MEASUREMENTS_FILTER ; } return defaultMeasurementFilter ; }
The default measurement filter is configured through properties .
21,282
Map < String , MetricValues > encodeRegistry ( Registry sourceRegistry , Predicate < Measurement > filter ) { Map < String , MetricValues > metricMap = new HashMap < > ( ) ; for ( Meter meter : sourceRegistry ) { String kind = knownMeterKinds . computeIfAbsent ( meter . id ( ) , k -> meterToKind ( sourceRegistry , meter ) ) ; for ( Measurement measurement : meter . measure ( ) ) { if ( ! filter . test ( measurement ) ) { continue ; } if ( Double . isNaN ( measurement . value ( ) ) ) { continue ; } String meterName = measurement . id ( ) . name ( ) ; MetricValues have = metricMap . get ( meterName ) ; if ( have == null ) { metricMap . put ( meterName , new MetricValues ( kind , measurement ) ) ; } else { have . addMeasurement ( measurement ) ; } } } return metricMap ; }
Internal API for encoding a registry that can be encoded as JSON . This is a helper function for the REST endpoint and to test against .
21,283
public static String meterToKind ( Registry registry , Meter meter ) { String kind ; if ( meter instanceof Timer ) { kind = "Timer" ; } else if ( meter instanceof Counter ) { kind = "Counter" ; } else if ( meter instanceof Gauge ) { kind = "Gauge" ; } else if ( meter instanceof DistributionSummary ) { kind = "DistributionSummary" ; } else { kind = meter . getClass ( ) . getSimpleName ( ) ; } return kind ; }
Determine the type of a meter for reporting purposes .
21,284
public String header ( String k ) { List < String > vs = headers . get ( k ) ; return ( vs == null || vs . isEmpty ( ) ) ? null : vs . get ( 0 ) ; }
Return the value for the first occurrence of a given header or null if not found .
21,285
public Instant dateHeader ( String k ) { String d = header ( k ) ; return ( d == null ) ? null : parseDate ( d ) ; }
Return the value for a date header . The return value will be null if the header does not exist or if it cannot be parsed correctly as a date .
21,286
public HttpResponse decompress ( ) throws IOException { String enc = header ( "Content-Encoding" ) ; return ( enc != null && enc . contains ( "gzip" ) ) ? unzip ( ) : this ; }
Return a copy of the response with the entity decompressed .
21,287
static Config loadConfig ( String userResources ) { Config config = ConfigFactory . load ( "agent" ) ; if ( userResources != null && ! "" . equals ( userResources ) ) { for ( String userResource : userResources . split ( "[,\\s]+" ) ) { if ( userResource . startsWith ( "file:" ) ) { File file = new File ( userResource . substring ( "file:" . length ( ) ) ) ; LOGGER . info ( "loading configuration from file: {}" , file ) ; Config user = ConfigFactory . parseFile ( file ) ; config = user . withFallback ( config ) ; } else { LOGGER . info ( "loading configuration from resource: {}" , userResource ) ; Config user = ConfigFactory . parseResourcesAnySyntax ( userResource ) ; config = user . withFallback ( config ) ; } } } return config . resolve ( ) . getConfig ( "netflix.spectator.agent" ) ; }
Helper to load config files specified by the user .
21,288
public static void premain ( String arg , Instrumentation instrumentation ) throws Exception { Config config = loadConfig ( arg ) ; LOGGER . debug ( "loaded configuration: {}" , config . root ( ) . render ( ) ) ; createDependencyProperties ( config ) ; AtlasRegistry registry = new AtlasRegistry ( Clock . SYSTEM , new AgentAtlasConfig ( config ) ) ; Spectator . globalRegistry ( ) . add ( registry ) ; GcLogger gcLogger = new GcLogger ( ) ; if ( config . getBoolean ( "collection.gc" ) ) { gcLogger . start ( null ) ; } if ( config . getBoolean ( "collection.jvm" ) ) { Jmx . registerStandardMXBeans ( registry ) ; } if ( config . getBoolean ( "collection.jmx" ) ) { for ( Config cfg : config . getConfigList ( "jmx.mappings" ) ) { Jmx . registerMappingsFromConfig ( registry , cfg ) ; } } registry . start ( ) ; Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( registry :: stop , "spectator-agent-shutdown" ) ) ; }
Entry point for the agent .
21,289
static JmxMeasurementConfig from ( Config config ) { String name = config . getString ( "name" ) ; Map < String , String > tags = config . getConfigList ( "tags" ) . stream ( ) . collect ( Collectors . toMap ( c -> c . getString ( "key" ) , c -> c . getString ( "value" ) ) ) ; String value = config . getString ( "value" ) ; boolean counter = config . hasPath ( "counter" ) && config . getBoolean ( "counter" ) ; return new JmxMeasurementConfig ( name , tags , value , counter ) ; }
Create from a Typesafe Config object .
21,290
static byte [ ] gzip ( byte [ ] data , int level ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( data . length ) ; try ( GzipLevelOutputStream out = new GzipLevelOutputStream ( baos ) ) { out . setLevel ( level ) ; out . write ( data ) ; } return baos . toByteArray ( ) ; }
Compress a byte array using GZIP with the given compression level .
21,291
@ SuppressWarnings ( "PMD.AssignmentInOperand" ) static byte [ ] gunzip ( byte [ ] data ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( data . length * 10 ) ; try ( InputStream in = new GZIPInputStream ( new ByteArrayInputStream ( data ) ) ) { byte [ ] buffer = new byte [ 4096 ] ; int length ; while ( ( length = in . read ( buffer ) ) > 0 ) { baos . write ( buffer , 0 , length ) ; } } return baos . toByteArray ( ) ; }
Decompress a GZIP compressed byte array .
21,292
public static Config createConfig ( Config config ) { try { CompositeConfig cc = new DefaultCompositeConfig ( true ) ; cc . addConfig ( "ATLAS" , loadPropFiles ( ) ) ; cc . addConfig ( "ENVIRONMENT" , EnvironmentConfig . INSTANCE ) ; cc . addConfig ( "SYS" , SystemConfig . INSTANCE ) ; if ( config != null ) { LOGGER . debug ( "found injected config, adding as override layer" ) ; cc . addConfig ( "INJECTED" , config ) ; } else { LOGGER . debug ( "no injected config found" ) ; } return cc ; } catch ( ConfigException e ) { throw new IllegalStateException ( "failed to load atlas config" , e ) ; } }
Create a config to be used in the Netflix Cloud .
21,293
public static Map < String , String > commonTags ( ) { final Map < String , String > commonTags = new HashMap < > ( ) ; put ( commonTags , "nf.app" , Env . app ( ) ) ; put ( commonTags , "nf.cluster" , Env . cluster ( ) ) ; put ( commonTags , "nf.asg" , Env . asg ( ) ) ; put ( commonTags , "nf.stack" , Env . stack ( ) ) ; put ( commonTags , "nf.zone" , Env . zone ( ) ) ; put ( commonTags , "nf.vmtype" , Env . vmtype ( ) ) ; put ( commonTags , "nf.node" , Env . instanceId ( ) ) ; put ( commonTags , "nf.region" , Env . region ( ) ) ; put ( commonTags , "nf.account" , Env . accountId ( ) ) ; put ( commonTags , "nf.task" , Env . task ( ) ) ; put ( commonTags , "nf.job" , Env . job ( ) ) ; return commonTags ; }
Infrastructure tags that are common across all metrics . Used for deduplication and for providing a scope for the metrics produced .
21,294
public static SparkNameFunction fromConfig ( Config config , String key , Registry registry ) { return fromPatternList ( config . getConfigList ( key ) , registry ) ; }
Create a name function based on a config .
21,295
public String sequence ( ) { return dN == asg . length ( ) ? null : substr ( asg , dN + 1 , asg . length ( ) ) ; }
If the server group has a sequence number then return it . Otherwise return null .
21,296
public synchronized void start ( GcEventListener listener ) { if ( notifListener != null ) { LOGGER . warn ( "logger already started" ) ; return ; } eventListener = listener ; notifListener = new GcNotificationListener ( ) ; for ( GarbageCollectorMXBean mbean : ManagementFactory . getGarbageCollectorMXBeans ( ) ) { if ( mbean instanceof NotificationEmitter ) { final NotificationEmitter emitter = ( NotificationEmitter ) mbean ; emitter . addNotificationListener ( notifListener , null , null ) ; } } }
Start collecting data about GC events .
21,297
public synchronized void stop ( ) { Preconditions . checkState ( notifListener != null , "logger has not been started" ) ; for ( GarbageCollectorMXBean mbean : ManagementFactory . getGarbageCollectorMXBeans ( ) ) { if ( mbean instanceof NotificationEmitter ) { final NotificationEmitter emitter = ( NotificationEmitter ) mbean ; try { emitter . removeNotificationListener ( notifListener ) ; } catch ( ListenerNotFoundException e ) { LOGGER . warn ( "could not remove gc listener" , e ) ; } } } notifListener = null ; }
Stop collecting GC events .
21,298
public List < GcEvent > getLogs ( ) { final List < GcEvent > logs = new ArrayList < > ( ) ; for ( CircularBuffer < GcEvent > buffer : gcLogs . values ( ) ) { logs . addAll ( buffer . toList ( ) ) ; } Collections . sort ( logs , GcEvent . REVERSE_TIME_ORDER ) ; return logs ; }
Return the current set of GC events in the in - memory log .
21,299
private boolean isStatusSet ( ExecutionAttributes attrs ) { Boolean s = attrs . getAttribute ( STATUS_IS_SET ) ; return s != null && s ; }
For network errors there will not be a response so the status will not have been set . This method looks for a flag in the attributes to see if we need to close off the log entry for the attempt .