idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
9,400
public FragmentBuilder getFragmentBuilder ( ) { FragmentBuilder builder = builders . get ( ) ; if ( builder == null ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Creating new FragmentBuilder" ) ; } builder = new FragmentBuilder ( ) ; builders . set ( builder ) ; int currentCount = threadCounter . incrementAndGet ( ) ; int builderCount = builder . incrementThreadCount ( ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Associate Thread with FragmentBuilder(1): Total Thread Count = " + currentCount + " : Fragment Thread Count = " + builderCount ) ; synchronized ( threadNames ) { threadNames . add ( Thread . currentThread ( ) . getName ( ) ) ; } } } return builder ; }
This method returns the appropriate fragment builder for the current thread .
9,401
public void setFragmentBuilder ( FragmentBuilder builder ) { FragmentBuilder currentBuilder = builders . get ( ) ; if ( currentBuilder == null && builder != null ) { int currentCount = threadCounter . incrementAndGet ( ) ; int builderCount = builder . incrementThreadCount ( ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Associate Thread with FragmentBuilder(2): Total Thread Count = " + currentCount + " : Fragment Thread Count = " + builderCount ) ; synchronized ( threadNames ) { threadNames . add ( Thread . currentThread ( ) . getName ( ) ) ; } } } else if ( currentBuilder != null && builder == null ) { int currentCount = threadCounter . decrementAndGet ( ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Disassociate Thread from FragmentBuilder(2): Total Thread Count = " + currentCount ) ; synchronized ( threadNames ) { threadNames . remove ( Thread . currentThread ( ) . getName ( ) ) ; } } } else if ( currentBuilder != builder ) { int oldCount = currentBuilder . decrementThreadCount ( ) ; int newCount = builder . incrementThreadCount ( ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "WARNING: Overwriting thread's fragment builder: old=[" + currentBuilder + " count=" + oldCount + "] now=[" + builder + " count=" + newCount + "]" ) ; } } builders . set ( builder ) ; }
This method sets the builder for this thread of execution .
9,402
public void clear ( ) { int currentCount = threadCounter . decrementAndGet ( ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Clear: Disassociate Thread from FragmentBuilder(1): current thread count=" + currentCount ) ; synchronized ( threadNames ) { threadNames . remove ( Thread . currentThread ( ) . getName ( ) ) ; } } FragmentBuilder currentBuilder = builders . get ( ) ; if ( currentBuilder != null ) { currentBuilder . decrementThreadCount ( ) ; } builders . remove ( ) ; }
This method clears the trace fragment builder for the current thread of execution .
9,403
protected static List < Trace > internalQuery ( ElasticsearchClient client , String tenantId , Criteria criteria ) { List < Trace > ret = new ArrayList < Trace > ( ) ; String index = client . getIndex ( tenantId ) ; try { RefreshRequestBuilder refreshRequestBuilder = client . getClient ( ) . admin ( ) . indices ( ) . prepareRefresh ( index ) ; client . getClient ( ) . admin ( ) . indices ( ) . refresh ( refreshRequestBuilder . request ( ) ) . actionGet ( ) ; BoolQueryBuilder query = ElasticsearchUtil . buildQuery ( criteria , ElasticsearchUtil . TRANSACTION_FIELD , Trace . class ) ; SearchRequestBuilder request = client . getClient ( ) . prepareSearch ( index ) . setTypes ( TRACE_TYPE ) . setSearchType ( SearchType . DFS_QUERY_THEN_FETCH ) . setTimeout ( TimeValue . timeValueMillis ( criteria . getTimeout ( ) ) ) . setSize ( criteria . getMaxResponseSize ( ) ) . setQuery ( query ) . addSort ( ElasticsearchUtil . TIMESTAMP_FIELD , SortOrder . ASC ) ; FilterBuilder filter = ElasticsearchUtil . buildFilter ( criteria ) ; if ( filter != null ) { request . setPostFilter ( filter ) ; } SearchResponse response = request . execute ( ) . actionGet ( ) ; if ( response . isTimedOut ( ) ) { msgLog . warnQueryTimedOut ( ) ; } for ( SearchHit searchHitFields : response . getHits ( ) ) { try { ret . add ( mapper . readValue ( searchHitFields . getSourceAsString ( ) , Trace . class ) ) ; } catch ( Exception e ) { msgLog . errorFailedToParse ( e ) ; } } if ( msgLog . isTraceEnabled ( ) ) { msgLog . tracef ( "Query traces with criteria[%s] is: %s" , criteria , ret ) ; } } catch ( org . elasticsearch . indices . IndexMissingException ime ) { if ( msgLog . isTraceEnabled ( ) ) { msgLog . tracef ( "No index found, so unable to retrieve traces" ) ; } } catch ( org . elasticsearch . action . search . SearchPhaseExecutionException spee ) { if ( msgLog . isTraceEnabled ( ) ) { msgLog . tracef ( "Failed to get fragments" , spee ) ; } } return ret ; }
This method performs the query .
9,404
public static void decodeProperties ( Set < PropertyCriteria > properties , String encoded ) { if ( encoded != null && ! encoded . trim ( ) . isEmpty ( ) ) { StringTokenizer st = new StringTokenizer ( encoded , "," ) ; while ( st . hasMoreTokens ( ) ) { String token = st . nextToken ( ) ; String [ ] parts = token . split ( "[|]" ) ; if ( parts . length >= 2 ) { String name = parts [ 0 ] . trim ( ) ; String value = parts [ 1 ] . trim ( ) ; Operator op = Operator . HAS ; if ( parts . length > 2 ) { op = Operator . valueOf ( parts [ 2 ] . trim ( ) ) ; } log . tracef ( "Extracted property name [%s] value [%s] operator [%s]" , name , value , op ) ; properties . add ( new PropertyCriteria ( name , value , op ) ) ; } } } }
This method processes a comma separated list of properties defined as a name|value pair .
9,405
public static void decodeCorrelationIdentifiers ( Set < CorrelationIdentifier > correlations , String encoded ) { if ( encoded != null && ! encoded . trim ( ) . isEmpty ( ) ) { StringTokenizer st = new StringTokenizer ( encoded , "," ) ; while ( st . hasMoreTokens ( ) ) { String token = st . nextToken ( ) ; String [ ] parts = token . split ( "[|]" ) ; if ( parts . length == 2 ) { String scope = parts [ 0 ] . trim ( ) ; String value = parts [ 1 ] . trim ( ) ; log . tracef ( "Extracted correlation identifier scope [%s] value [%s]" , scope , value ) ; CorrelationIdentifier cid = new CorrelationIdentifier ( ) ; cid . setScope ( Scope . valueOf ( scope ) ) ; cid . setValue ( value ) ; correlations . add ( cid ) ; } } } }
This method processes a comma separated list of correlation identifiers defined as a scope|value pair .
9,406
public static Reference findPrimaryReference ( List < Reference > references ) { List < Reference > followsFrom = references . stream ( ) . filter ( ref -> References . FOLLOWS_FROM . equals ( ref . getReferenceType ( ) ) && ref . getReferredTo ( ) instanceof APMSpan ) . collect ( Collectors . toList ( ) ) ; List < Reference > childOfSpan = references . stream ( ) . filter ( ref -> References . CHILD_OF . equals ( ref . getReferenceType ( ) ) && ref . getReferredTo ( ) instanceof APMSpan ) . collect ( Collectors . toList ( ) ) ; List < Reference > extractedTraceState = references . stream ( ) . filter ( ref -> ref . getReferredTo ( ) instanceof APMSpanBuilder ) . collect ( Collectors . toList ( ) ) ; if ( ! extractedTraceState . isEmpty ( ) ) { if ( extractedTraceState . size ( ) == 1 ) { return extractedTraceState . get ( 0 ) ; } return null ; } if ( ! childOfSpan . isEmpty ( ) ) { if ( childOfSpan . size ( ) == 1 ) { return childOfSpan . get ( 0 ) ; } return null ; } if ( followsFrom . size ( ) == 1 ) { return followsFrom . get ( 0 ) ; } return null ; }
This method identifies the primary parent reference that should be used to link the associated span to an existing trace instance .
9,407
protected void initTopLevelState ( APMSpan topSpan , TraceRecorder recorder , ContextSampler sampler ) { nodeBuilder = new NodeBuilder ( ) ; traceContext = new TraceContext ( topSpan , nodeBuilder , recorder , sampler ) ; }
This method initialises the node builder and trace context for a top level trace fragment .
9,408
protected void initFromExtractedTraceState ( APMSpanBuilder builder , TraceRecorder recorder , Reference ref , ContextSampler sampler ) { APMSpanBuilder parentBuilder = ( APMSpanBuilder ) ref . getReferredTo ( ) ; initTopLevelState ( this , recorder , sampler ) ; if ( parentBuilder . state ( ) . containsKey ( Constants . HAWKULAR_APM_ID ) ) { setInteractionId ( parentBuilder . state ( ) . get ( Constants . HAWKULAR_APM_ID ) . toString ( ) ) ; traceContext . initTraceState ( parentBuilder . state ( ) ) ; } getNodeBuilder ( ) . setNodeType ( NodeType . Consumer ) ; processRemainingReferences ( builder , ref ) ; }
This method initialises the span based on extracted trace state .
9,409
protected void initChildOf ( APMSpanBuilder builder , Reference ref ) { APMSpan parent = ( APMSpan ) ref . getReferredTo ( ) ; if ( parent . getNodeBuilder ( ) != null ) { nodeBuilder = new NodeBuilder ( parent . getNodeBuilder ( ) ) ; traceContext = parent . traceContext ; if ( parent . getTags ( ) . containsKey ( Constants . PROP_TRANSACTION_NAME ) && traceContext . getTransaction ( ) == null ) { traceContext . setTransaction ( parent . getTags ( ) . get ( Constants . PROP_TRANSACTION_NAME ) . toString ( ) ) ; } } processRemainingReferences ( builder , ref ) ; }
This method initialises the span based on a child - of relationship .
9,410
protected void initFollowsFrom ( APMSpanBuilder builder , TraceRecorder recorder , Reference ref , ContextSampler sampler ) { APMSpan referenced = ( APMSpan ) ref . getReferredTo ( ) ; initTopLevelState ( referenced . getTraceContext ( ) . getTopSpan ( ) , recorder , sampler ) ; String nodeId = referenced . getNodePath ( ) ; getNodeBuilder ( ) . addCorrelationId ( new CorrelationIdentifier ( Scope . CausedBy , nodeId ) ) ; traceContext . initTraceState ( referenced . state ( ) ) ; makeInternalLink ( builder ) ; }
This method initialises the span based on a follows - from relationship .
9,411
protected void processNoPrimaryReference ( APMSpanBuilder builder , TraceRecorder recorder , ContextSampler sampler ) { initTopLevelState ( this , recorder , sampler ) ; Set < String > traceIds = builder . references . stream ( ) . map ( ref -> { if ( ref . getReferredTo ( ) instanceof APMSpan ) { return ( ( APMSpan ) ref . getReferredTo ( ) ) . getTraceContext ( ) . getTraceId ( ) ; } else if ( ref . getReferredTo ( ) instanceof APMSpanBuilder ) { return ( ( APMSpanBuilder ) ref . getReferredTo ( ) ) . state ( ) . get ( Constants . HAWKULAR_APM_TRACEID ) . toString ( ) ; } log . warning ( "Reference refers to an unsupported SpanContext implementation: " + ref . getReferredTo ( ) ) ; return null ; } ) . collect ( Collectors . toSet ( ) ) ; if ( traceIds . size ( ) > 0 ) { if ( traceIds . size ( ) > 1 ) { log . warning ( "References should all belong to the same 'trace' instance" ) ; } if ( builder . references . get ( 0 ) . getReferredTo ( ) instanceof APMSpan ) { traceContext . initTraceState ( ( ( APMSpan ) builder . references . get ( 0 ) . getReferredTo ( ) ) . state ( ) ) ; } } processRemainingReferences ( builder , null ) ; makeInternalLink ( builder ) ; }
This method initialises the span based on there being no primary reference .
9,412
protected void processRemainingReferences ( APMSpanBuilder builder , Reference primaryRef ) { for ( Reference ref : builder . references ) { if ( primaryRef == ref ) { continue ; } if ( ref . getReferredTo ( ) instanceof APMSpan ) { APMSpan referenced = ( APMSpan ) ref . getReferredTo ( ) ; String nodeId = referenced . getNodePath ( ) ; getNodeBuilder ( ) . addCorrelationId ( new CorrelationIdentifier ( Scope . CausedBy , nodeId ) ) ; } else if ( ref . getReferredTo ( ) instanceof APMSpanBuilder && ( ( APMSpanBuilder ) ref . getReferredTo ( ) ) . state ( ) . containsKey ( Constants . HAWKULAR_APM_ID ) ) { getNodeBuilder ( ) . addCorrelationId ( new CorrelationIdentifier ( Scope . Interaction , ( ( APMSpanBuilder ) ref . getReferredTo ( ) ) . state ( ) . get ( Constants . HAWKULAR_APM_ID ) . toString ( ) ) ) ; } } }
This method processes the remaining references by creating appropriate correlation ids against the current node .
9,413
public void init ( String txn , TransactionConfig btc ) { if ( log . isLoggable ( Level . FINE ) ) { log . fine ( "ProcessManager: initialise btxn '" + txn + "' config=" + btc + " processors=" + btc . getProcessors ( ) . size ( ) ) ; } if ( btc . getProcessors ( ) != null && ! btc . getProcessors ( ) . isEmpty ( ) ) { List < ProcessorWrapper > procs = new ArrayList < ProcessorWrapper > ( ) ; for ( int i = 0 ; i < btc . getProcessors ( ) . size ( ) ; i ++ ) { procs . add ( new ProcessorWrapper ( btc . getProcessors ( ) . get ( i ) ) ) ; } synchronized ( processors ) { processors . put ( txn , procs ) ; } } else { synchronized ( processors ) { processors . remove ( txn ) ; } } }
This method initialises the processors associated with the supplied transaction configuration .
9,414
public void process ( Trace trace , Node node , Direction direction , Map < String , ? > headers , Object ... values ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "ProcessManager: process trace=" + trace + " node=" + node + " direction=" + direction + " headers=" + headers + " values=" + values + " : available processors=" + processors ) ; } if ( trace . getTransaction ( ) != null ) { List < ProcessorWrapper > procs = null ; synchronized ( processors ) { procs = processors . get ( trace . getTransaction ( ) ) ; } if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "ProcessManager: trace name=" + trace . getTransaction ( ) + " processors=" + procs ) ; } if ( procs != null ) { for ( int i = 0 ; i < procs . size ( ) ; i ++ ) { procs . get ( i ) . process ( trace , node , direction , headers , values ) ; } } } }
This method processes the supplied information against the configured processor details for the trace .
9,415
public static String toUnique ( Span span ) { String id = span . getId ( ) ; if ( span . clientSpan ( ) ) { id = getClientId ( span . getId ( ) ) ; } return id ; }
Utility method to get unique id of the span . Note that method does not change the span id .
9,416
protected void doPublish ( String tenantId , List < T > items , String subscriber , int retryCount , long delay ) throws Exception { String data = mapper . writeValueAsString ( items ) ; TextMessage tm = session . createTextMessage ( data ) ; if ( tenantId != null ) { tm . setStringProperty ( "tenant" , tenantId ) ; } if ( subscriber != null ) { tm . setStringProperty ( "subscriber" , subscriber ) ; } tm . setIntProperty ( "retryCount" , retryCount ) ; if ( delay > 0 ) { tm . setLongProperty ( "_AMQ_SCHED_DELIVERY" , System . currentTimeMillis ( ) + delay ) ; } if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Publish: " + tm ) ; } producer . send ( tm ) ; }
This method publishes the supplied items .
9,417
protected void init ( ) { Properties props = new Properties ( ) ; props . put ( "bootstrap.servers" , PropertyUtil . getProperty ( PropertyUtil . HAWKULAR_APM_URI_PUBLISHER , PropertyUtil . getProperty ( PropertyUtil . HAWKULAR_APM_URI ) ) . substring ( PropertyUtil . KAFKA_PREFIX . length ( ) ) ) ; props . put ( "acks" , "all" ) ; props . put ( "retries" , PropertyUtil . getPropertyAsInteger ( PropertyUtil . HAWKULAR_APM_KAFKA_PRODUCER_RETRIES , 3 ) ) ; props . put ( "batch.size" , 16384 ) ; props . put ( "linger.ms" , 1 ) ; props . put ( "buffer.memory" , 33554432 ) ; props . put ( "key.serializer" , "org.apache.kafka.common.serialization.StringSerializer" ) ; props . put ( "value.serializer" , "org.apache.kafka.common.serialization.StringSerializer" ) ; producer = new KafkaProducer < > ( props ) ; }
This method initialises the publisher .
9,418
public Criteria addProperty ( String name , String value , Operator operator ) { properties . add ( new PropertyCriteria ( name , value , operator ) ) ; return this ; }
This method adds a new property criteria .
9,419
public boolean transactionWide ( ) { return ! ( ! properties . isEmpty ( ) || ! correlationIds . isEmpty ( ) || hostName != null || uri != null || operation != null ) ; }
This method determines if the specified criteria are relevant to all fragments within an end to end transaction .
9,420
public Criteria deriveTransactionWide ( ) { Criteria ret = new Criteria ( ) ; ret . setStartTime ( startTime ) ; ret . setEndTime ( endTime ) ; ret . setProperties ( getProperties ( ) . stream ( ) . filter ( p -> p . getName ( ) . equals ( Constants . PROP_PRINCIPAL ) ) . collect ( Collectors . toSet ( ) ) ) ; ret . setTransaction ( transaction ) ; return ret ; }
This method returns the transaction wide version of the current criteria .
9,421
public static CollectorConfiguration getConfiguration ( String type ) { return loadConfig ( PropertyUtil . getProperty ( HAWKULAR_APM_CONFIG , DEFAULT_URI ) , type ) ; }
This method returns the collector configuration .
9,422
protected static CollectorConfiguration loadConfig ( String uri , String type ) { final CollectorConfiguration config = new CollectorConfiguration ( ) ; if ( type == null ) { type = DEFAULT_TYPE ; } uri += java . io . File . separator + type ; File f = new File ( uri ) ; if ( ! f . isAbsolute ( ) ) { if ( f . exists ( ) ) { uri = f . getAbsolutePath ( ) ; } else if ( System . getProperties ( ) . containsKey ( "jboss.server.config.dir" ) ) { uri = System . getProperty ( "jboss.server.config.dir" ) + java . io . File . separatorChar + uri ; } else { try { URL url = Thread . currentThread ( ) . getContextClassLoader ( ) . getResource ( uri ) ; if ( url != null ) { uri = url . getPath ( ) ; } else { log . severe ( "Failed to get absolute path for uri '" + uri + "'" ) ; } } catch ( Exception e ) { log . log ( Level . SEVERE , "Failed to get absolute path for uri '" + uri + "'" , e ) ; uri = null ; } } } if ( uri != null ) { String [ ] uriParts = uri . split ( Matcher . quoteReplacement ( File . separator ) ) ; int startIndex = 0 ; if ( uriParts [ 0 ] . equals ( "file:" ) ) { startIndex ++ ; } try { Path path = getPath ( startIndex , uriParts ) ; Files . walkFileTree ( path , new FileVisitor < Path > ( ) { public FileVisitResult postVisitDirectory ( Path path , IOException exc ) throws IOException { return FileVisitResult . CONTINUE ; } public FileVisitResult preVisitDirectory ( Path path , BasicFileAttributes attrs ) throws IOException { return FileVisitResult . CONTINUE ; } public FileVisitResult visitFile ( Path path , BasicFileAttributes attrs ) throws IOException { if ( path . toString ( ) . endsWith ( ".json" ) ) { String json = new String ( Files . readAllBytes ( path ) ) ; CollectorConfiguration childConfig = mapper . readValue ( json , CollectorConfiguration . class ) ; if ( childConfig != null ) { config . merge ( childConfig , false ) ; } } return FileVisitResult . CONTINUE ; } public FileVisitResult visitFileFailed ( Path path , IOException exc ) throws IOException { return FileVisitResult . CONTINUE ; } } ) ; } catch ( Throwable e ) { log . log ( Level . SEVERE , "Failed to load configuration" , e ) ; } } return config ; }
This method loads the configuration from the supplied URI .
9,423
protected void process ( String tenantId , List < S > items , int retryCount ) throws Exception { ProcessingUnit < S , T > pu = new ProcessingUnit < S , T > ( ) ; pu . setProcessor ( getProcessor ( ) ) ; pu . setRetrySubscriber ( retrySubscriber ) ; pu . setRetryCount ( retryCount ) ; pu . setResultHandler ( ( tid , events ) -> getPublisher ( ) . publish ( tid , events , getPublisher ( ) . getInitialRetryCount ( ) , getProcessor ( ) . getDeliveryDelay ( events ) ) ) ; pu . setRetryHandler ( ( tid , events ) -> getRetryPublisher ( ) . retry ( tid , events , pu . getRetrySubscriber ( ) , pu . getRetryCount ( ) - 1 , getProcessor ( ) . getRetryDelay ( events , pu . getRetryCount ( ) - 1 ) ) ) ; pu . handle ( tenantId , items ) ; }
This method processes the received list of items .
9,424
public static List < SourceInfo > getSourceInfo ( String tenantId , List < Trace > items ) throws RetryAttemptException { List < SourceInfo > sourceInfoList = new ArrayList < SourceInfo > ( ) ; int curpos = 0 ; for ( int i = 0 ; i < items . size ( ) ; i ++ ) { Trace trace = items . get ( i ) ; StringBuffer nodeId = new StringBuffer ( trace . getFragmentId ( ) ) ; for ( int j = 0 ; j < trace . getNodes ( ) . size ( ) ; j ++ ) { Node node = trace . getNodes ( ) . get ( j ) ; int len = nodeId . length ( ) ; initialiseSourceInfo ( sourceInfoList , tenantId , trace , nodeId , j , node ) ; nodeId . delete ( len , nodeId . length ( ) ) ; } EndpointRef ep = EndpointUtil . getSourceEndpoint ( trace ) ; for ( int j = curpos ; j < sourceInfoList . size ( ) ; j ++ ) { SourceInfo si = sourceInfoList . get ( j ) ; si . setEndpoint ( ep ) ; } curpos = sourceInfoList . size ( ) ; } return sourceInfoList ; }
This method gets the source information associated with the supplied traces .
9,425
protected static void initialiseSourceInfo ( List < SourceInfo > sourceInfoList , String tenantId , Trace trace , StringBuffer parentNodeId , int pos , Node node ) { SourceInfo si = new SourceInfo ( ) ; parentNodeId . append ( ':' ) ; parentNodeId . append ( pos ) ; si . setId ( parentNodeId . toString ( ) ) ; si . setTimestamp ( node . getTimestamp ( ) ) ; si . setDuration ( node . getDuration ( ) ) ; si . setTraceId ( trace . getTraceId ( ) ) ; si . setFragmentId ( trace . getFragmentId ( ) ) ; si . setHostName ( trace . getHostName ( ) ) ; si . setHostAddress ( trace . getHostAddress ( ) ) ; si . setMultipleConsumers ( true ) ; si . setProperties ( node . getProperties ( ) ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Adding source information for node id=" + si . getId ( ) + " si=" + si ) ; } sourceInfoList . add ( si ) ; if ( node . getClass ( ) == Producer . class ) { List < CorrelationIdentifier > cids = node . findCorrelationIds ( Scope . Interaction , Scope . ControlFlow ) ; if ( ! cids . isEmpty ( ) ) { for ( int i = 0 ; i < cids . size ( ) ; i ++ ) { CorrelationIdentifier cid = cids . get ( i ) ; SourceInfo copy = new SourceInfo ( si ) ; copy . setId ( cid . getValue ( ) ) ; copy . setMultipleConsumers ( ( ( Producer ) node ) . multipleConsumers ( ) ) ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Extra source information for scope=" + cid . getScope ( ) + " id=" + copy . getId ( ) + " si=" + copy ) ; } sourceInfoList . add ( copy ) ; } } } if ( node instanceof ContainerNode ) { int nodeIdLen = parentNodeId . length ( ) ; for ( int j = 0 ; j < ( ( ContainerNode ) node ) . getNodes ( ) . size ( ) ; j ++ ) { initialiseSourceInfo ( sourceInfoList , tenantId , trace , parentNodeId , j , ( ( ContainerNode ) node ) . getNodes ( ) . get ( j ) ) ; parentNodeId . delete ( nodeIdLen , parentNodeId . length ( ) ) ; } } }
This method initialises an individual node within a trace .
9,426
protected static Span findRootOrServerSpan ( String tenantId , Span span , SpanCache spanCache ) { while ( span != null && ! span . serverSpan ( ) && ! span . topLevelSpan ( ) ) { span = spanCache . get ( tenantId , span . getParentId ( ) ) ; } return span ; }
This method identifies the root or enclosing server span that contains the supplied client span .
9,427
public static SourceInfo getSourceInfo ( String tenantId , Span serverSpan , SpanCache spanCache ) { String clientSpanId = SpanUniqueIdGenerator . getClientId ( serverSpan . getId ( ) ) ; if ( spanCache != null && clientSpanId != null ) { Span clientSpan = spanCache . get ( tenantId , clientSpanId ) ; Span rootOrServerSpan = findRootOrServerSpan ( tenantId , clientSpan , spanCache ) ; if ( rootOrServerSpan != null ) { SourceInfo si = new SourceInfo ( ) ; if ( clientSpan . getDuration ( ) != null ) { si . setDuration ( clientSpan . getDuration ( ) ) ; } if ( clientSpan . getTimestamp ( ) != null ) { si . setTimestamp ( clientSpan . getTimestamp ( ) ) ; } si . setTraceId ( clientSpan . getTraceId ( ) ) ; si . setFragmentId ( clientSpan . getId ( ) ) ; si . getProperties ( ) . addAll ( clientSpan . binaryAnnotationMapping ( ) . getProperties ( ) ) ; si . setHostAddress ( clientSpan . ipv4 ( ) ) ; if ( clientSpan . service ( ) != null ) { si . getProperties ( ) . add ( new Property ( Constants . PROP_SERVICE_NAME , clientSpan . service ( ) ) ) ; } si . setId ( clientSpan . getId ( ) ) ; si . setMultipleConsumers ( false ) ; URL url = rootOrServerSpan . url ( ) ; si . setEndpoint ( new EndpointRef ( ( url != null ? url . getPath ( ) : null ) , SpanDeriverUtil . deriveOperation ( rootOrServerSpan ) , ! rootOrServerSpan . serverSpan ( ) ) ) ; return si ; } } return null ; }
This method attempts to derive the Source Information for the supplied server span . If the information is not available then a null will be returned which can be used to trigger a retry attempt if appropriate .
9,428
public static ProcessorActionHandler getHandler ( ProcessorAction action ) { ProcessorActionHandler ret = null ; Class < ? extends ProcessorActionHandler > cls = handlers . get ( action . getClass ( ) ) ; if ( cls != null ) { try { Constructor < ? extends ProcessorActionHandler > con = cls . getConstructor ( ProcessorAction . class ) ; ret = con . newInstance ( action ) ; } catch ( Exception e ) { log . log ( Level . SEVERE , "Failed to instantiate handler for action '" + action + "'" , e ) ; } } return ret ; }
This method returns an action handler for the supplied action .
9,429
protected static boolean processConfig ( ) { CollectorConfiguration config = configService . getCollector ( null , null , null , null ) ; if ( config != null ) { try { updateInstrumentation ( config ) ; } catch ( Exception e ) { log . severe ( "Failed to update instrumentation rules: " + e ) ; } } return config != null ; }
This method attempts to retrieve and process the instrumentation information contained within the collector configuration .
9,430
public static void updateInstrumentation ( CollectorConfiguration config ) throws Exception { List < String > scripts = new ArrayList < String > ( ) ; List < String > scriptNames = new ArrayList < String > ( ) ; Map < String , Instrumentation > instrumentTypes = config . getInstrumentation ( ) ; for ( Map . Entry < String , Instrumentation > stringInstrumentationEntry : instrumentTypes . entrySet ( ) ) { Instrumentation types = stringInstrumentationEntry . getValue ( ) ; String rules = ruleTransformer . transform ( stringInstrumentationEntry . getKey ( ) , types , config . getProperty ( "version." + stringInstrumentationEntry . getKey ( ) , null ) ) ; if ( log . isLoggable ( Level . FINER ) ) { log . finer ( "Update instrumentation script name=" + stringInstrumentationEntry . getKey ( ) + " rules=" + rules ) ; } if ( rules != null ) { scriptNames . add ( stringInstrumentationEntry . getKey ( ) ) ; scripts . add ( rules ) ; } } PrintWriter writer = new PrintWriter ( new StringWriter ( ) ) ; transformer . installScript ( scripts , scriptNames , writer ) ; writer . close ( ) ; }
This method updates the instrumentation instructions .
9,431
public Node build ( ) { ContainerNode ret = null ; if ( nodeType == NodeType . Component ) { ret = new Component ( ) ; ( ( Component ) ret ) . setComponentType ( componentType ) ; } else if ( nodeType == NodeType . Consumer ) { ret = new Consumer ( ) ; ( ( Consumer ) ret ) . setEndpointType ( endpointType ) ; } else if ( nodeType == NodeType . Producer ) { ret = new Producer ( ) ; ( ( Producer ) ret ) . setEndpointType ( endpointType ) ; } ret . setCorrelationIds ( correlationIds ) ; ret . setOperation ( operation ) ; ret . setProperties ( properties ) ; ret . setUri ( uri ) ; ret . setDuration ( duration ) ; ret . setTimestamp ( timestamp ) ; for ( int i = 0 ; i < nodes . size ( ) ; i ++ ) { ret . getNodes ( ) . add ( nodes . get ( i ) . build ( ) ) ; } NodeUtil . rewriteURI ( ret ) ; return ret ; }
This method builds the node hierarchy .
9,432
public void endProcessingNode ( ) { if ( nodeCount . decrementAndGet ( ) == 0 && recorder != null ) { Node node = rootNode . build ( ) ; trace . setTimestamp ( node . getTimestamp ( ) ) ; trace . setTransaction ( getTransaction ( ) ) ; trace . getNodes ( ) . add ( node ) ; if ( checkForSamplingProperties ( node ) ) { reportingLevel = ReportingLevel . All ; } boolean sampled = sampler . isSampled ( trace , reportingLevel ) ; if ( sampled && reportingLevel == null ) { reportingLevel = ReportingLevel . All ; } if ( sampled ) { recorder . record ( trace ) ; } } }
This method indicates the end of processing a node within the trace instance . Once all nodes for a trace have completed being processed the trace will be reported .
9,433
public EndpointRef getSourceEndpoint ( ) { return new EndpointRef ( TagUtil . getUriPath ( topSpan . getTags ( ) ) , topSpan . getOperationName ( ) , false ) ; }
This method returns the source endpoint for the root trace fragment generated by the service invocation .
9,434
public void initTraceState ( Map < String , Object > state ) { Object traceId = state . get ( Constants . HAWKULAR_APM_TRACEID ) ; Object transaction = state . get ( Constants . HAWKULAR_APM_TXN ) ; Object level = state . get ( Constants . HAWKULAR_APM_LEVEL ) ; if ( traceId != null ) { setTraceId ( traceId . toString ( ) ) ; } else { log . severe ( "Trace id has not been propagated" ) ; } if ( transaction != null ) { setTransaction ( transaction . toString ( ) ) ; } if ( level != null ) { setReportingLevel ( ReportingLevel . valueOf ( level . toString ( ) ) ) ; } }
Initialise the trace state from the supplied state .
9,435
private static boolean checkForSamplingProperties ( Node node ) { Set < Property > samplingProperties = node instanceof ContainerNode ? ( ( ContainerNode ) node ) . getPropertiesIncludingDescendants ( Tags . SAMPLING_PRIORITY . getKey ( ) ) : node . getProperties ( Tags . SAMPLING_PRIORITY . getKey ( ) ) ; for ( Property prop : samplingProperties ) { int priority = 0 ; try { priority = Integer . parseInt ( prop . getValue ( ) ) ; } catch ( NumberFormatException ex ) { } if ( priority > 0 ) { return true ; } } return false ; }
This method is looking for sampling tag in nodes properties to override current sampling .
9,436
public static String encodeEndpoint ( String uri , String operation ) { StringBuilder buf = new StringBuilder ( ) ; if ( uri != null && ! uri . trim ( ) . isEmpty ( ) ) { buf . append ( uri ) ; } if ( operation != null && ! operation . trim ( ) . isEmpty ( ) ) { buf . append ( '[' ) ; buf . append ( operation ) ; buf . append ( ']' ) ; } return buf . toString ( ) ; }
This method converts the supplied URI and optional operation into an endpoint descriptor .
9,437
public static String decodeEndpointURI ( String endpoint ) { int ind = endpoint . indexOf ( '[' ) ; if ( ind == 0 ) { return null ; } else if ( ind != - 1 ) { return endpoint . substring ( 0 , ind ) ; } return endpoint ; }
This method returns the URI part of the supplied endpoint .
9,438
public static String decodeEndpointOperation ( String endpoint , boolean stripped ) { int ind = endpoint . indexOf ( '[' ) ; if ( ind != - 1 ) { if ( stripped ) { return endpoint . substring ( ind + 1 , endpoint . length ( ) - 1 ) ; } return endpoint . substring ( ind ) ; } return null ; }
This method returns the operation part of the supplied endpoint .
9,439
public static String encodeClientURI ( String uri ) { if ( uri == null ) { return Constants . URI_CLIENT_PREFIX ; } return Constants . URI_CLIENT_PREFIX + uri ; }
This method provides a client based encoding of an URI . This is required to identify the client node invoking a service using a particular URI .
9,440
public static String decodeClientURI ( String clientUri ) { return clientUri . startsWith ( Constants . URI_CLIENT_PREFIX ) ? clientUri . substring ( Constants . URI_CLIENT_PREFIX . length ( ) ) : clientUri ; }
This method provides a decoding of a client based URI .
9,441
public static EndpointRef getSourceEndpoint ( Trace fragment ) { Node rootNode = fragment . getNodes ( ) . isEmpty ( ) ? null : fragment . getNodes ( ) . get ( 0 ) ; if ( rootNode == null ) { return null ; } return new EndpointRef ( rootNode . getUri ( ) , rootNode . getOperation ( ) , fragment . initialFragment ( ) && rootNode instanceof Producer ) ; }
This method determines the source URI that should be attributed to the supplied fragment . If the top level fragment just contains a Producer then prefix with client to distinguish it from the same endpoint for the service .
9,442
protected void submitTraces ( ) { if ( ! traces . isEmpty ( ) ) { List < Trace > toSend = traces ; traces = new ArrayList < > ( batchSize + 1 ) ; executor . execute ( new Runnable ( ) { public void run ( ) { try { tracePublisher . publish ( tenantId , toSend ) ; } catch ( Exception e ) { log . log ( Level . SEVERE , "Failed to publish traces" , e ) ; } } } ) ; } }
This method submits the current list of traces
9,443
public static List < HttpCode > getHttpStatusCodes ( List < BinaryAnnotation > binaryAnnotations ) { if ( binaryAnnotations == null ) { return Collections . emptyList ( ) ; } List < HttpCode > httpCodes = new ArrayList < > ( ) ; for ( BinaryAnnotation binaryAnnotation : binaryAnnotations ) { if ( Constants . ZIPKIN_BIN_ANNOTATION_HTTP_STATUS_CODE . equals ( binaryAnnotation . getKey ( ) ) && binaryAnnotation . getValue ( ) != null ) { String strHttpCode = binaryAnnotation . getValue ( ) ; Integer httpCode = toInt ( strHttpCode . trim ( ) ) ; if ( httpCode != null ) { String description = EnglishReasonPhraseCatalog . INSTANCE . getReason ( httpCode , Locale . ENGLISH ) ; httpCodes . add ( new HttpCode ( httpCode , description ) ) ; } } } return httpCodes ; }
Method returns list of http status codes .
9,444
public static List < HttpCode > getClientOrServerErrors ( List < HttpCode > httpCodes ) { return httpCodes . stream ( ) . filter ( x -> x . isClientOrServerError ( ) ) . collect ( Collectors . toList ( ) ) ; }
Method returns only client or sever http errors .
9,445
public static String getHttpMethod ( Span span ) { if ( isHttp ( span ) ) { BinaryAnnotation ba = span . getBinaryAnnotation ( "http.method" ) ; String httpMethod = null ; if ( ba != null ) { httpMethod = ba . getValue ( ) . toUpperCase ( ) ; } else if ( span . getName ( ) != null ) { httpMethod = span . getName ( ) . toUpperCase ( ) ; } if ( HTTP_METHODS . contains ( httpMethod ) ) { return httpMethod ; } } return null ; }
Derives HTTP operation from Span s binary annotations .
9,446
private static Integer toInt ( String str ) { Integer num = null ; try { num = Integer . parseInt ( str ) ; } catch ( NumberFormatException ex ) { log . severe ( String . format ( "failed to convert str: %s to integer" , str ) ) ; } return num ; }
Converts string to a number .
9,447
public static String serialize ( Object value ) { if ( value instanceof String ) { return ( String ) value ; } else if ( value instanceof byte [ ] ) { return new String ( ( byte [ ] ) value ) ; } }
This method converts the supplied object to a string .
9,448
public Set < Property > allProperties ( ) { Set < Property > properties = new HashSet < Property > ( ) ; for ( Node n : nodes ) { n . includeProperties ( properties ) ; } return Collections . unmodifiableSet ( properties ) ; }
This method returns all properties contained in the node hierarchy that can be used to search for the trace .
9,449
public long calculateDuration ( ) { if ( ! nodes . isEmpty ( ) ) { long endTime = 0 ; for ( int i = 0 ; i < getNodes ( ) . size ( ) ; i ++ ) { Node node = getNodes ( ) . get ( i ) ; long nodeEndTime = node . overallEndTime ( ) ; if ( nodeEndTime > endTime ) { endTime = nodeEndTime ; } } return endTime - getNodes ( ) . get ( 0 ) . getTimestamp ( ) ; } return 0L ; }
This method returns the duration of the trace fragment .
9,450
public Set < Node > getCorrelatedNodes ( CorrelationIdentifier cid ) { Set < Node > ret = new HashSet < Node > ( ) ; for ( Node n : getNodes ( ) ) { n . findCorrelatedNodes ( cid , ret ) ; } return ret ; }
This method locates any node within the trace that is associated with the supplied correlation id .
9,451
protected void initNode ( ) { ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( TransportClient . class . getClassLoader ( ) ) ; final Properties properties = new Properties ( ) ; try { InputStream stream = null ; if ( System . getProperties ( ) . containsKey ( "jboss.server.config.dir" ) ) { File file = new File ( System . getProperty ( "jboss.server.config.dir" ) + File . separatorChar + HAWKULAR_ELASTICSEARCH_PROPERTIES ) ; stream = new FileInputStream ( file ) ; } else { stream = this . getClass ( ) . getResourceAsStream ( File . separatorChar + HAWKULAR_ELASTICSEARCH_PROPERTIES ) ; } properties . load ( stream ) ; stream . close ( ) ; } catch ( IOException e ) { log . log ( Level . SEVERE , "Failed to load elasticsearch properties" , e ) ; } node = NodeBuilder . nodeBuilder ( ) . settings ( ImmutableSettings . settingsBuilder ( ) . put ( properties ) ) . node ( ) ; node . start ( ) ; client = node . client ( ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( cl ) ; } if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Initialized Elasticsearch node=" + node + " client=" + client ) ; } }
This method initializes the node .
9,452
public void close ( ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Close Elasticsearch node=" + node + " client=" + client ) ; } if ( client != null ) { client . close ( ) ; client = null ; } if ( node != null ) { node . stop ( ) ; node = null ; } }
This method closes the elasticsearch node .
9,453
public < T > T cast ( Object obj , Class < T > clz ) { if ( ! clz . isAssignableFrom ( obj . getClass ( ) ) ) { return null ; } return clz . cast ( obj ) ; }
This method casts the supplied object to the nominated class . If the object cannot be cast to the provided type then a null will be returned .
9,454
public String formatSQL ( Object obj , Object expr ) { String sql = null ; if ( expr instanceof String ) { sql = ( String ) expr ; if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "SQL retrieved from state = " + sql ) ; } } else if ( obj != null ) { sql = toString ( obj ) ; if ( sql != null ) { if ( sql . startsWith ( "prep" ) ) { sql = sql . replaceFirst ( "prep[0-9]*: " , "" ) ; } sql = sql . replaceAll ( "X'.*'" , BINARY_SQL_MARKER ) ; } if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "SQL derived from context = " + sql ) ; } } return sql ; }
This method attempts to return a SQL statement . If an expression is supplied and is string it will be used . Otherwise the method will attempt to derive an expression from the supplied object .
9,455
protected FaultDescriptor getFaultDescriptor ( Object fault ) { for ( int i = 0 ; i < faultDescriptors . size ( ) ; i ++ ) { if ( faultDescriptors . get ( i ) . isValid ( fault ) ) { return faultDescriptors . get ( i ) ; } } return null ; }
This method attempts to locate a descriptor for the fault .
9,456
public String faultName ( Object fault ) { FaultDescriptor fd = getFaultDescriptor ( fault ) ; if ( fd != null ) { return fd . getName ( fault ) ; } return fault . getClass ( ) . getSimpleName ( ) ; }
This method gets the name of the supplied fault .
9,457
public String faultDescription ( Object fault ) { FaultDescriptor fd = getFaultDescriptor ( fault ) ; if ( fd != null ) { return fd . getDescription ( fault ) ; } return fault . toString ( ) ; }
This method gets the description of the supplied fault .
9,458
public String removeAfter ( String original , String marker ) { int index = original . indexOf ( marker ) ; if ( index != - 1 ) { return original . substring ( 0 , index ) ; } return original ; }
This method removes the end part of a string beginning at a specified marker .
9,459
public Map < String , String > getHeaders ( String type , Object target ) { HeadersAccessor accessor = getHeadersAccessor ( type ) ; if ( accessor != null ) { Map < String , String > ret = accessor . getHeaders ( target ) ; return ret ; } return null ; }
This method attempts to provide headers for the supplied target object .
9,460
public static BinaryAnnotationMappingDeriver getInstance ( String path ) { if ( instance == null ) { synchronized ( LOCK ) { if ( instance == null ) { instance = path == null ? new BinaryAnnotationMappingDeriver ( ) : new BinaryAnnotationMappingDeriver ( path ) ; } } } return instance ; }
Returns instance of mapping deriver .
9,461
public MappingResult mappingResult ( List < BinaryAnnotation > binaryAnnotations ) { if ( binaryAnnotations == null ) { return new MappingResult ( ) ; } List < String > componentTypes = new ArrayList < > ( ) ; List < String > endpointTypes = new ArrayList < > ( ) ; MappingResult . Builder mappingBuilder = MappingResult . builder ( ) ; for ( BinaryAnnotation binaryAnnotation : binaryAnnotations ) { if ( binaryAnnotation . getKey ( ) == null ) { continue ; } BinaryAnnotationMapping mapping = mappingStorage . getKeyBasedMappings ( ) . get ( binaryAnnotation . getKey ( ) ) ; if ( mapping != null && mapping . isIgnore ( ) ) { continue ; } if ( mapping == null || mapping . getProperty ( ) == null ) { mappingBuilder . addProperty ( new Property ( binaryAnnotation . getKey ( ) , binaryAnnotation . getValue ( ) , AnnotationTypeUtil . toPropertyType ( binaryAnnotation . getType ( ) ) ) ) ; } if ( mapping != null ) { if ( mapping . getComponentType ( ) != null ) { componentTypes . add ( mapping . getComponentType ( ) ) ; } if ( mapping . getEndpointType ( ) != null ) { endpointTypes . add ( mapping . getEndpointType ( ) ) ; } if ( mapping . getProperty ( ) != null && ! mapping . getProperty ( ) . isExclude ( ) ) { String key = mapping . getProperty ( ) . getKey ( ) != null ? mapping . getProperty ( ) . getKey ( ) : binaryAnnotation . getKey ( ) ; mappingBuilder . addProperty ( new Property ( key , binaryAnnotation . getValue ( ) , AnnotationTypeUtil . toPropertyType ( binaryAnnotation . getType ( ) ) ) ) ; } } } if ( ! componentTypes . isEmpty ( ) ) { mappingBuilder . withComponentType ( componentTypes . get ( 0 ) ) ; } if ( ! endpointTypes . isEmpty ( ) ) { mappingBuilder . withEndpointType ( endpointTypes . get ( 0 ) ) ; } return mappingBuilder . build ( ) ; }
Creates a mapping result from supplied binary annotations .
9,462
protected void deriveNodeDetails ( Trace trace , List < Node > nodes , List < NodeDetails > rts , boolean initial , Set < Property > commonProperties ) { for ( int i = 0 ; i < nodes . size ( ) ; i ++ ) { Node n = nodes . get ( i ) ; boolean ignoreNode = false ; boolean ignoreChildNodes = false ; if ( n . getClass ( ) == Consumer . class && ( ( Consumer ) n ) . getEndpointType ( ) == null ) { ignoreNode = true ; } else if ( n . getClass ( ) == Producer . class && ( ( Producer ) n ) . getEndpointType ( ) == null ) { ignoreNode = true ; ignoreChildNodes = true ; } if ( ! ignoreNode ) { NodeDetails nd = new NodeDetails ( ) ; nd . setId ( UUID . randomUUID ( ) . toString ( ) ) ; nd . setTraceId ( trace . getTraceId ( ) ) ; nd . setFragmentId ( trace . getFragmentId ( ) ) ; nd . setTransaction ( trace . getTransaction ( ) ) ; nd . setCorrelationIds ( n . getCorrelationIds ( ) ) ; nd . setElapsed ( n . getDuration ( ) ) ; nd . setActual ( calculateActualTime ( n ) ) ; if ( n . getType ( ) == NodeType . Component ) { nd . setComponentType ( ( ( Component ) n ) . getComponentType ( ) ) ; } else { nd . setComponentType ( n . getType ( ) . name ( ) ) ; } if ( trace . getHostName ( ) != null && ! trace . getHostName ( ) . trim ( ) . isEmpty ( ) ) { nd . setHostName ( trace . getHostName ( ) ) ; } if ( initial ) { nd . setProperties ( trace . allProperties ( ) ) ; nd . setInitial ( true ) ; } else { nd . getProperties ( ) . addAll ( n . getProperties ( ) ) ; nd . getProperties ( ) . addAll ( commonProperties ) ; } nd . setTimestamp ( n . getTimestamp ( ) ) ; nd . setType ( n . getType ( ) ) ; nd . setUri ( n . getUri ( ) ) ; nd . setOperation ( n . getOperation ( ) ) ; rts . add ( nd ) ; } initial = false ; if ( ! ignoreChildNodes && n . interactionNode ( ) ) { deriveNodeDetails ( trace , ( ( InteractionNode ) n ) . getNodes ( ) , rts , initial , commonProperties ) ; } } }
This method recursively derives the node details metrics for the supplied nodes .
9,463
protected Set < Property > obtainCommonProperties ( Trace trace ) { Set < Property > commonProperties = trace . getProperties ( Constants . PROP_SERVICE_NAME ) ; commonProperties . addAll ( trace . getProperties ( Constants . PROP_BUILD_STAMP ) ) ; commonProperties . addAll ( trace . getProperties ( Constants . PROP_PRINCIPAL ) ) ; return commonProperties ; }
Obtain any properties from the trace that should be applied to all derived NodeDetails .
9,464
protected long calculateActualTime ( Node n ) { long childElapsed = 0 ; if ( n . containerNode ( ) ) { long startTime = n . getTimestamp ( ) + n . getDuration ( ) ; long endTime = n . getTimestamp ( ) ; for ( int i = 0 ; i < ( ( ContainerNode ) n ) . getNodes ( ) . size ( ) ; i ++ ) { Node child = ( ( ContainerNode ) n ) . getNodes ( ) . get ( i ) ; if ( child . getTimestamp ( ) < startTime ) { startTime = child . getTimestamp ( ) ; } if ( endTime < ( child . getTimestamp ( ) + child . getDuration ( ) ) ) { endTime = child . getTimestamp ( ) + child . getDuration ( ) ; } childElapsed += child . getDuration ( ) ; } if ( childElapsed > n . getDuration ( ) ) { childElapsed = endTime - startTime ; if ( childElapsed < 0 || childElapsed > n . getDuration ( ) ) { childElapsed = 0 ; } } else if ( endTime > n . getTimestamp ( ) + n . getDuration ( ) ) { childElapsed = 0 ; } } return n . getDuration ( ) - childElapsed ; }
This method calculates the actual time associated with the supplied node .
9,465
public boolean process ( Trace trace , Node node , Direction direction , Map < String , ? > headers , Object [ ] values ) { if ( predicate != null ) { return predicate . test ( trace , node , direction , headers , values ) ; } return true ; }
This method processes the supplied information to extract the relevant details .
9,466
public boolean isVersionValid ( String version ) { if ( fromVersion != null && version != null ) { if ( version . compareTo ( fromVersion ) < 0 ) { return false ; } } if ( toVersion != null ) { if ( version == null || version . compareTo ( toVersion ) >= 0 ) { return false ; } } return true ; }
This method determines if the rule is valid for the supplied version . If the supplied version is null then it is assumed to represent latest version and therefore any rule with a toVersion set will not be valid .
9,467
public void finest ( String mesg , Throwable t ) { log ( Level . FINEST , mesg , t ) ; }
This method logs a message at the FINEST level .
9,468
public void finer ( String mesg , Throwable t ) { log ( Level . FINER , mesg , t ) ; }
This method logs a message at the FINER level .
9,469
public void fine ( String mesg , Throwable t ) { log ( Level . FINE , mesg , t ) ; }
This method logs a message at the FINE level .
9,470
public void info ( String mesg , Throwable t ) { log ( Level . INFO , mesg , t ) ; }
This method logs a message at the INFO level .
9,471
public void warning ( String mesg , Throwable t ) { log ( Level . WARNING , mesg , t ) ; }
This method logs a message at the WARNING level .
9,472
public void severe ( String mesg , Throwable t ) { log ( Level . SEVERE , mesg , t ) ; }
This method logs a message at the SEVERE level .
9,473
public void log ( Level mesgLevel , String mesg , Throwable t ) { if ( mesgLevel . ordinal ( ) >= level . ordinal ( ) ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( mesgLevel . name ( ) ) ; builder . append ( ": [" ) ; builder . append ( simpleClassName != null ? simpleClassName : className ) ; builder . append ( "] [" ) ; builder . append ( Thread . currentThread ( ) ) ; builder . append ( "] " ) ; builder . append ( mesg ) ; if ( mesgLevel == Level . SEVERE ) { if ( julLogger != null ) { julLogger . log ( java . util . logging . Level . SEVERE , builder . toString ( ) , t ) ; } else { System . err . println ( builder . toString ( ) ) ; } } else { if ( julLogger != null ) { julLogger . info ( builder . toString ( ) ) ; } else { System . out . println ( builder . toString ( ) ) ; } } if ( t != null ) { t . printStackTrace ( ) ; } } }
This method logs a message at the supplied message level with an optional exception .
9,474
public static String deriveOperation ( Span span ) { if ( SpanHttpDeriverUtil . isHttp ( span ) ) { return SpanHttpDeriverUtil . getHttpMethod ( span ) ; } return span . getName ( ) ; }
Derives an operation from supplied span .
9,475
public boolean isCompleteExceptIgnoredNodes ( ) { synchronized ( nodeStack ) { if ( nodeStack . isEmpty ( ) && retainedNodes . isEmpty ( ) ) { return true ; } else { for ( int i = 0 ; i < nodeStack . size ( ) ; i ++ ) { if ( ! ignoredNodes . contains ( nodeStack . get ( i ) ) ) { return false ; } } for ( int i = 0 ; i < retainedNodes . size ( ) ; i ++ ) { if ( ! ignoredNodes . contains ( retainedNodes . get ( i ) ) ) { return false ; } } return true ; } } }
This method determines if the fragment is complete with the exception of ignored nodes .
9,476
public void pushNode ( Node node ) { initNode ( node ) ; inStream = null ; synchronized ( nodeStack ) { poppedNodes . clear ( ) ; if ( suppress ) { suppressedNodeStack . push ( node ) ; return ; } if ( nodeStack . isEmpty ( ) ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Pushing top level node: " + node + " for txn: " + trace ) ; } trace . getNodes ( ) . add ( node ) ; } else { Node parent = nodeStack . peek ( ) ; if ( parent instanceof ContainerNode ) { if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( "Add node: " + node + " to parent: " + parent + " in txn: " + trace ) ; } ( ( ContainerNode ) parent ) . getNodes ( ) . add ( node ) ; } else { log . severe ( "Attempt to add node '" + node + "' under non-container node '" + parent + "'" ) ; } } nodeStack . push ( node ) ; } }
This method pushes a new node into the trace fragment hierarchy .
9,477
public Node popNode ( Class < ? extends Node > cls , String uri ) { synchronized ( nodeStack ) { if ( suppress ) { if ( ! suppressedNodeStack . isEmpty ( ) ) { Node suppressed = popNode ( suppressedNodeStack , cls , uri ) ; if ( suppressed != null ) { return suppressed ; } } else { suppress = false ; } } return popNode ( nodeStack , cls , uri ) ; } }
This method pops the latest node from the trace fragment hierarchy .
9,478
protected Node popNode ( Stack < Node > stack , Class < ? extends Node > cls , String uri ) { Node top = stack . isEmpty ( ) ? null : stack . peek ( ) ; if ( top != null ) { if ( nodeMatches ( top , cls , uri ) ) { Node node = stack . pop ( ) ; poppedNodes . push ( node ) ; return node ; } else { for ( int i = stack . size ( ) - 2 ; i >= 0 ; i -- ) { if ( nodeMatches ( stack . get ( i ) , cls , uri ) ) { Node node = stack . remove ( i ) ; poppedNodes . push ( node ) ; return node ; } } } } return null ; }
This method pops a node of the defined class and optional uri from the stack . If the uri is not defined then the latest node of the approach class will be chosen .
9,479
protected boolean nodeMatches ( Node node , Class < ? extends Node > cls , String uri ) { if ( node . getClass ( ) == cls ) { return uri == null || NodeUtil . isOriginalURI ( node , uri ) ; } return false ; }
This method determines whether the supplied node matches the specified class and optional URI .
9,480
public void retainNode ( String id ) { synchronized ( retainedNodes ) { Node current = getCurrentNode ( ) ; if ( current != null ) { retainedNodes . put ( id , current ) ; } } }
This method indicates that the current node for this thread of execution should be retained temporarily pending further changes .
9,481
public void addUncompletedCorrelationId ( String id , Node node , int position ) { NodePlaceholder placeholder = new NodePlaceholder ( ) ; placeholder . setNode ( node ) ; placeholder . setPosition ( position ) ; uncompletedCorrelationIdsNodeMap . put ( id , placeholder ) ; }
This method associates a parent node and child position with a correlation id .
9,482
public int getUncompletedCorrelationIdPosition ( String id ) { if ( uncompletedCorrelationIdsNodeMap . containsKey ( id ) ) { return uncompletedCorrelationIdsNodeMap . get ( id ) . getPosition ( ) ; } return - 1 ; }
This method returns the child position associated with the supplied correlation id .
9,483
public Node removeUncompletedCorrelationId ( String id ) { NodePlaceholder placeholder = uncompletedCorrelationIdsNodeMap . remove ( id ) ; if ( placeholder != null ) { return placeholder . getNode ( ) ; } return null ; }
This method removes the uncompleted correlation id and its associated information .
9,484
public void writeInData ( int hashCode , byte [ ] b , int offset , int len ) { if ( inStream != null && ( hashCode == - 1 || hashCode == inHashCode ) ) { inStream . write ( b , offset , len ) ; } }
This method writes data to the in buffer .
9,485
public byte [ ] getInData ( int hashCode ) { if ( inStream != null && ( hashCode == - 1 || hashCode == inHashCode ) ) { try { inStream . close ( ) ; } catch ( IOException e ) { log . severe ( "Failed to close in data stream: " + e ) ; } byte [ ] b = inStream . toByteArray ( ) ; inStream = null ; return b ; } return null ; }
This method returns the data associated with the in buffer and resets the buffer to be inactive .
9,486
public void writeOutData ( int hashCode , byte [ ] b , int offset , int len ) { if ( outStream != null && ( hashCode == - 1 || hashCode == outHashCode ) ) { outStream . write ( b , offset , len ) ; } }
This method writes data to the out buffer .
9,487
public byte [ ] getOutData ( int hashCode ) { if ( outStream != null && ( hashCode == - 1 || hashCode == outHashCode ) ) { try { outStream . close ( ) ; } catch ( IOException e ) { log . severe ( "Failed to close out data stream: " + e ) ; } byte [ ] b = outStream . toByteArray ( ) ; outStream = null ; return b ; } return null ; }
This method returns the data associated with the out buffer and resets the buffer to be inactive .
9,488
public void setState ( Object context , String name , Object value ) { StateInformation si = stateInformation . get ( name ) ; if ( si == null ) { si = new StateInformation ( ) ; stateInformation . put ( name , si ) ; } si . set ( context , value ) ; }
This method stores state information associated with the name and optional context .
9,489
public Object getState ( Object context , String name ) { StateInformation si = stateInformation . get ( name ) ; if ( si == null ) { return null ; } return si . get ( context ) ; }
This method returns the state associated with the name and optional context .
9,490
public static String getUriPath ( String value ) { try { URL url = new URL ( value ) ; return url . getPath ( ) ; } catch ( MalformedURLException e ) { return value ; } }
This method extracts the path component of a URL . If the supplied value is not a valid URL format then it will simply return the supplied value .
9,491
public static String getUriPath ( Map < String , Object > tags ) { for ( Map . Entry < String , Object > entry : tags . entrySet ( ) ) { if ( isUriKey ( entry . getKey ( ) ) ) { return getUriPath ( entry . getValue ( ) . toString ( ) ) ; } } return null ; }
This method returns the URI value from a set of supplied tags by first identifying which tag relates to a URI and then returning its path value .
9,492
public static void rewriteURI ( Node node , String uri ) { node . getProperties ( ) . add ( new Property ( APM_ORIGINAL_URI , node . getUri ( ) ) ) ; node . setUri ( uri ) ; }
This method rewrites the URI associated with the supplied node and stores the original in the node s details .
9,493
public static boolean isOriginalURI ( Node node , String uri ) { if ( node . getUri ( ) . equals ( uri ) ) { return true ; } if ( node . hasProperty ( APM_ORIGINAL_URI ) ) { return node . getProperties ( APM_ORIGINAL_URI ) . iterator ( ) . next ( ) . getValue ( ) . equals ( uri ) ; } return false ; }
This method determines whether the supplied URI matches the original URI on the node .
9,494
protected Object getDataValue ( Trace trace , Node node , Direction direction , Map < String , ? > headers , Object [ ] values ) { if ( source == DataSource . Content ) { return values [ index ] ; } else if ( source == DataSource . Header ) { return headers . get ( key ) ; } return null ; }
This method returns the data value associated with the requested data source and key ..
9,495
protected void includeProperties ( Set < Property > allProperties ) { super . includeProperties ( allProperties ) ; nodes . forEach ( n -> n . includeProperties ( allProperties ) ) ; }
This method adds the properties for this node to the supplied set .
9,496
protected long overallEndTime ( ) { long ret = super . overallEndTime ( ) ; for ( Node child : nodes ) { long childEndTime = child . overallEndTime ( ) ; if ( childEndTime > ret ) { ret = childEndTime ; } } return ret ; }
This method determines the overall end time of this node .
9,497
protected Collection < CommunicationSummaryStatistics > doGetCommunicationSummaryStatistics ( String tenantId , Criteria criteria ) { String index = client . getIndex ( tenantId ) ; Map < String , CommunicationSummaryStatistics > stats = new HashMap < > ( ) ; if ( ! criteria . transactionWide ( ) ) { Criteria txnWideCriteria = criteria . deriveTransactionWide ( ) ; buildCommunicationSummaryStatistics ( stats , index , txnWideCriteria , false ) ; } buildCommunicationSummaryStatistics ( stats , index , criteria , true ) ; return stats . values ( ) ; }
This method returns the flat list of communication summary stats .
9,498
private void buildCommunicationSummaryStatistics ( Map < String , CommunicationSummaryStatistics > stats , String index , Criteria criteria , boolean addMetrics ) { if ( ! refresh ( index ) ) { return ; } BoolQueryBuilder query = buildQuery ( criteria , ElasticsearchUtil . TRANSACTION_FIELD , null ) ; query = query . mustNot ( QueryBuilders . matchQuery ( "internal" , "true" ) ) ; StatsBuilder latencyBuilder = AggregationBuilders . stats ( "latency" ) . field ( ElasticsearchUtil . LATENCY_FIELD ) ; TermsBuilder targetBuilder = AggregationBuilders . terms ( "target" ) . field ( ElasticsearchUtil . TARGET_FIELD ) . size ( criteria . getMaxResponseSize ( ) ) . subAggregation ( latencyBuilder ) ; TermsBuilder sourceBuilder = AggregationBuilders . terms ( "source" ) . field ( ElasticsearchUtil . SOURCE_FIELD ) . size ( criteria . getMaxResponseSize ( ) ) . subAggregation ( targetBuilder ) ; SearchRequestBuilder request = getBaseSearchRequestBuilder ( COMMUNICATION_DETAILS_TYPE , index , criteria , query , 0 ) . addAggregation ( sourceBuilder ) ; SearchResponse response = getSearchResponse ( request ) ; for ( Terms . Bucket sourceBucket : response . getAggregations ( ) . < Terms > get ( "source" ) . getBuckets ( ) ) { Terms targets = sourceBucket . getAggregations ( ) . get ( "target" ) ; CommunicationSummaryStatistics css = stats . get ( sourceBucket . getKey ( ) ) ; if ( css == null ) { css = new CommunicationSummaryStatistics ( ) ; css . setId ( sourceBucket . getKey ( ) ) ; css . setUri ( EndpointUtil . decodeEndpointURI ( css . getId ( ) ) ) ; css . setOperation ( EndpointUtil . decodeEndpointOperation ( css . getId ( ) , true ) ) ; stats . put ( css . getId ( ) , css ) ; } if ( addMetrics ) { css . setCount ( sourceBucket . getDocCount ( ) ) ; } for ( Terms . Bucket targetBucket : targets . getBuckets ( ) ) { Stats latency = targetBucket . getAggregations ( ) . get ( "latency" ) ; String linkId = targetBucket . getKey ( ) ; ConnectionStatistics con = css . getOutbound ( ) . get ( linkId ) ; if ( con == null ) { con = new ConnectionStatistics ( ) ; css . getOutbound ( ) . put ( linkId , con ) ; } if ( addMetrics ) { con . setMinimumLatency ( ( long ) latency . getMin ( ) ) ; con . setAverageLatency ( ( long ) latency . getAvg ( ) ) ; con . setMaximumLatency ( ( long ) latency . getMax ( ) ) ; con . setCount ( targetBucket . getDocCount ( ) ) ; } } } addNodeInformation ( stats , index , criteria , addMetrics , false ) ; addNodeInformation ( stats , index , criteria , addMetrics , true ) ; }
This method builds a map of communication summary stats related to the supplied criteria .
9,499
static String getServiceFromBuildName ( String buildName ) { if ( null == buildName || buildName . isEmpty ( ) ) { return buildName ; } return buildName . substring ( 0 , buildName . lastIndexOf ( '-' ) ) ; }
Converts an OpenShift build name into a service name