idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
35,300
|
static MetricDescriptor . ValueType createValueType ( Type type ) { if ( type == Type . CUMULATIVE_DOUBLE || type == Type . GAUGE_DOUBLE ) { return MetricDescriptor . ValueType . DOUBLE ; } else if ( type == Type . GAUGE_INT64 || type == Type . CUMULATIVE_INT64 ) { return MetricDescriptor . ValueType . INT64 ; } else if ( type == Type . GAUGE_DISTRIBUTION || type == Type . CUMULATIVE_DISTRIBUTION ) { return MetricDescriptor . ValueType . DISTRIBUTION ; } return MetricDescriptor . ValueType . UNRECOGNIZED ; }
|
Convert a OpenCensus Type to a StackDriver ValueType
|
35,301
|
static Metric createMetric ( io . opencensus . metrics . export . MetricDescriptor metricDescriptor , List < LabelValue > labelValues , String domain , Map < LabelKey , LabelValue > constantLabels ) { Metric . Builder builder = Metric . newBuilder ( ) ; builder . setType ( generateType ( metricDescriptor . getName ( ) , domain ) ) ; Map < String , String > stringTagMap = Maps . newHashMap ( ) ; List < LabelKey > labelKeys = metricDescriptor . getLabelKeys ( ) ; for ( int i = 0 ; i < labelValues . size ( ) ; i ++ ) { String value = labelValues . get ( i ) . getValue ( ) ; if ( value == null ) { continue ; } stringTagMap . put ( labelKeys . get ( i ) . getKey ( ) , value ) ; } for ( Map . Entry < LabelKey , LabelValue > constantLabel : constantLabels . entrySet ( ) ) { String constantLabelKey = constantLabel . getKey ( ) . getKey ( ) ; String constantLabelValue = constantLabel . getValue ( ) . getValue ( ) ; constantLabelValue = constantLabelValue == null ? "" : constantLabelValue ; stringTagMap . put ( constantLabelKey , constantLabelValue ) ; } builder . putAllLabels ( stringTagMap ) ; return builder . build ( ) ; }
|
Create a Metric using the LabelKeys and LabelValues .
|
35,302
|
static TypedValue createTypedValue ( Value value ) { return value . match ( typedValueDoubleFunction , typedValueLongFunction , typedValueDistributionFunction , typedValueSummaryFunction , Functions . < TypedValue > throwIllegalArgumentException ( ) ) ; }
|
Note TypedValue is A single strongly - typed value i . e only one field should be set .
|
35,303
|
static Distribution createDistribution ( io . opencensus . metrics . export . Distribution distribution ) { Distribution . Builder builder = Distribution . newBuilder ( ) . setBucketOptions ( createBucketOptions ( distribution . getBucketOptions ( ) ) ) . setCount ( distribution . getCount ( ) ) . setMean ( distribution . getCount ( ) == 0 ? 0 : distribution . getSum ( ) / distribution . getCount ( ) ) . setSumOfSquaredDeviation ( distribution . getSumOfSquaredDeviations ( ) ) ; setBucketCountsAndExemplars ( distribution . getBuckets ( ) , builder ) ; return builder . build ( ) ; }
|
Convert a OpenCensus Distribution to a StackDriver Distribution
|
35,304
|
static Timestamp convertTimestamp ( io . opencensus . common . Timestamp censusTimestamp ) { if ( censusTimestamp . getSeconds ( ) < 0 ) { return Timestamp . newBuilder ( ) . build ( ) ; } return Timestamp . newBuilder ( ) . setSeconds ( censusTimestamp . getSeconds ( ) ) . setNanos ( censusTimestamp . getNanos ( ) ) . build ( ) ; }
|
Convert a OpenCensus Timestamp to a StackDriver Timestamp
|
35,305
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public TagContext tagContextCreation ( Data data ) { return TagsBenchmarksUtil . createTagContext ( data . tagger . emptyBuilder ( ) , data . numTags ) ; }
|
Create a tag context .
|
35,306
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Scope scopeTagContext ( Data data ) { Scope scope = data . tagger . withTagContext ( data . tagContext ) ; scope . close ( ) ; return scope ; }
|
Open and close a tag context scope .
|
35,307
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public TagContext getCurrentTagContext ( Data data ) { return data . tagger . getCurrentTagContext ( ) ; }
|
Get the current tag context .
|
35,308
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public byte [ ] serializeTagContext ( Data data ) throws Exception { return data . serializer . toByteArray ( data . tagContext ) ; }
|
Serialize a tag context .
|
35,309
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public TagContext deserializeTagContext ( Data data ) throws Exception { return data . serializer . fromByteArray ( data . serializedTagContext ) ; }
|
Deserialize a tag context .
|
35,310
|
private static ViewData createInternal ( View view , Map < List < TagValue > , AggregationData > aggregationMap , AggregationWindowData window , Timestamp start , Timestamp end ) { @ SuppressWarnings ( "nullness" ) Map < List < TagValue > , AggregationData > map = aggregationMap ; return new AutoValue_ViewData ( view , map , window , start , end ) ; }
|
constructor does not have the
|
35,311
|
static Endpoint produceLocalEndpoint ( String serviceName ) { Endpoint . Builder builder = Endpoint . newBuilder ( ) . serviceName ( serviceName ) ; try { Enumeration < NetworkInterface > nics = NetworkInterface . getNetworkInterfaces ( ) ; if ( nics == null ) { return builder . build ( ) ; } while ( nics . hasMoreElements ( ) ) { NetworkInterface nic = nics . nextElement ( ) ; Enumeration < InetAddress > addresses = nic . getInetAddresses ( ) ; while ( addresses . hasMoreElements ( ) ) { InetAddress address = addresses . nextElement ( ) ; if ( address . isSiteLocalAddress ( ) ) { builder . ip ( address ) ; break ; } } } } catch ( Exception e ) { if ( logger . isLoggable ( Level . FINE ) ) { logger . log ( Level . FINE , "error reading nics" , e ) ; } } return builder . build ( ) ; }
|
Logic borrowed from brave . internal . Platform . produceLocalEndpoint
|
35,312
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public AttributeValue [ ] createAttributeValues ( Data data ) { return getAttributeValues ( data . size , data . attributeType ) ; }
|
Create attribute values .
|
35,313
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Map < String , AttributeValue > createAttributeMap ( Data data ) { Map < String , AttributeValue > attributeMap = new HashMap < > ( data . size ) ; for ( int i = 0 ; i < data . size ; i ++ ) { attributeMap . put ( data . attributeKeys [ i ] , data . attributeValues [ i ] ) ; } return attributeMap ; }
|
Create an AttributeMap .
|
35,314
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Annotation createAnnotation ( Data data ) { return Annotation . fromDescriptionAndAttributes ( ANNOTATION_DESCRIPTION , data . attributeMap ) ; }
|
Create an Annotation .
|
35,315
|
static MetricFamilySamples createMetricFamilySamples ( Metric metric , String namespace ) { MetricDescriptor metricDescriptor = metric . getMetricDescriptor ( ) ; String name = getNamespacedName ( metricDescriptor . getName ( ) , namespace ) ; Type type = getType ( metricDescriptor . getType ( ) ) ; List < String > labelNames = convertToLabelNames ( metricDescriptor . getLabelKeys ( ) ) ; List < Sample > samples = Lists . newArrayList ( ) ; for ( io . opencensus . metrics . export . TimeSeries timeSeries : metric . getTimeSeriesList ( ) ) { for ( io . opencensus . metrics . export . Point point : timeSeries . getPoints ( ) ) { samples . addAll ( getSamples ( name , labelNames , timeSeries . getLabelValues ( ) , point . getValue ( ) ) ) ; } } return new MetricFamilySamples ( name , type , metricDescriptor . getDescription ( ) , samples ) ; }
|
Converts a Metric to a Prometheus MetricFamilySamples .
|
35,316
|
static MetricFamilySamples createDescribableMetricFamilySamples ( MetricDescriptor metricDescriptor , String namespace ) { String name = getNamespacedName ( metricDescriptor . getName ( ) , namespace ) ; Type type = getType ( metricDescriptor . getType ( ) ) ; List < String > labelNames = convertToLabelNames ( metricDescriptor . getLabelKeys ( ) ) ; if ( containsDisallowedLeLabelForHistogram ( labelNames , type ) ) { throw new IllegalStateException ( "Prometheus Histogram cannot have a label named 'le', " + "because it is a reserved label for bucket boundaries. " + "Please remove this key from your view." ) ; } if ( containsDisallowedQuantileLabelForSummary ( labelNames , type ) ) { throw new IllegalStateException ( "Prometheus Summary cannot have a label named 'quantile', " + "because it is a reserved label. Please remove this key from your view." ) ; } return new MetricFamilySamples ( name , type , metricDescriptor . getDescription ( ) , Collections . < Sample > emptyList ( ) ) ; }
|
Used only for Prometheus metric registry should not contain any actual samples .
|
35,317
|
static List < String > convertToLabelNames ( List < LabelKey > labelKeys ) { final List < String > labelNames = new ArrayList < String > ( labelKeys . size ( ) ) ; for ( LabelKey labelKey : labelKeys ) { labelNames . add ( Collector . sanitizeMetricName ( labelKey . getKey ( ) ) ) ; } return labelNames ; }
|
Converts the list of label keys to a list of string label names . Also sanitizes the label keys .
|
35,318
|
static TraceConfig getCurrentTraceConfig ( io . opencensus . trace . config . TraceConfig traceConfig ) { TraceParams traceParams = traceConfig . getActiveTraceParams ( ) ; return toTraceConfigProto ( traceParams ) ; }
|
Creates a TraceConfig proto message with current TraceParams .
|
35,319
|
static TraceParams getUpdatedTraceParams ( UpdatedLibraryConfig config , io . opencensus . trace . config . TraceConfig traceConfig ) { TraceParams currentParams = traceConfig . getActiveTraceParams ( ) ; TraceConfig traceConfigProto = config . getConfig ( ) ; return fromTraceConfigProto ( traceConfigProto , currentParams ) ; }
|
TraceParams then applies the updated TraceParams .
|
35,320
|
@ SuppressWarnings ( "nullness" ) public static void createAndRegister ( ElasticsearchTraceConfiguration elasticsearchTraceConfiguration ) throws MalformedURLException { synchronized ( monitor ) { Preconditions . checkState ( handler == null , "Elasticsearch exporter already registered." ) ; Preconditions . checkArgument ( elasticsearchTraceConfiguration != null , "Elasticsearch " + "configuration not set." ) ; Preconditions . checkArgument ( elasticsearchTraceConfiguration . getElasticsearchIndex ( ) != null , "Elasticsearch index not specified" ) ; Preconditions . checkArgument ( elasticsearchTraceConfiguration . getElasticsearchType ( ) != null , "Elasticsearch type not specified" ) ; Preconditions . checkArgument ( elasticsearchTraceConfiguration . getElasticsearchUrl ( ) != null , "Elasticsearch URL not specified" ) ; handler = new ElasticsearchTraceHandler ( elasticsearchTraceConfiguration ) ; register ( Tracing . getExportComponent ( ) . getSpanExporter ( ) , handler ) ; } }
|
Creates and registers the ElasticsearchTraceExporter to the OpenCensus .
|
35,321
|
public boolean isEnabled ( String featurePath ) { checkArgument ( ! Strings . isNullOrEmpty ( featurePath ) ) ; return config . getConfig ( featurePath ) . getBoolean ( "enabled" ) ; }
|
Checks whether a feature is enabled in the effective configuration .
|
35,322
|
synchronized void sendInitialMessage ( Node node ) { io . opencensus . proto . trace . v1 . TraceConfig currentTraceConfigProto = TraceProtoUtils . getCurrentTraceConfig ( traceConfig ) ; CurrentLibraryConfig firstConfig = CurrentLibraryConfig . newBuilder ( ) . setNode ( node ) . setConfig ( currentTraceConfigProto ) . build ( ) ; sendCurrentConfig ( firstConfig ) ; }
|
subsequent updated library configs unless the stream is interrupted .
|
35,323
|
private synchronized void sendCurrentConfig ( ) { io . opencensus . proto . trace . v1 . TraceConfig currentTraceConfigProto = TraceProtoUtils . getCurrentTraceConfig ( traceConfig ) ; CurrentLibraryConfig currentLibraryConfig = CurrentLibraryConfig . newBuilder ( ) . setConfig ( currentTraceConfigProto ) . build ( ) ; sendCurrentConfig ( currentLibraryConfig ) ; }
|
Follow up after applying the updated library config .
|
35,324
|
private synchronized void sendCurrentConfig ( CurrentLibraryConfig currentLibraryConfig ) { if ( isCompleted ( ) || currentConfigObserver == null ) { return ; } try { currentConfigObserver . onNext ( currentLibraryConfig ) ; } catch ( Exception e ) { onComplete ( e ) ; } }
|
Sends current config to Agent if the stream is still connected otherwise do nothing .
|
35,325
|
public static void main ( String [ ] args ) throws IOException , InterruptedException { View view = View . create ( Name . create ( "task_latency_distribution" ) , "The distribution of the task latencies." , LATENCY_MS , Aggregation . Distribution . create ( LATENCY_BOUNDARIES ) , Collections . < TagKey > emptyList ( ) ) ; ViewManager viewManager = Stats . getViewManager ( ) ; viewManager . registerView ( view ) ; StackdriverStatsExporter . createAndRegister ( ) ; Random rand = new Random ( ) ; for ( int i = 0 ; i < 100 ; i ++ ) { long ms = ( long ) ( TimeUnit . MILLISECONDS . convert ( 5 , TimeUnit . SECONDS ) * rand . nextDouble ( ) ) ; System . out . println ( String . format ( "Latency %d: %d" , i , ms ) ) ; STATS_RECORDER . newMeasureMap ( ) . put ( LATENCY_MS , ms ) . record ( ) ; } System . out . println ( String . format ( "Sleeping %d seconds before shutdown to ensure all records are flushed." , EXPORT_INTERVAL ) ) ; Thread . sleep ( TimeUnit . MILLISECONDS . convert ( EXPORT_INTERVAL , TimeUnit . SECONDS ) ) ; }
|
Main launcher for the Stackdriver example .
|
35,326
|
synchronized void onExport ( ExportTraceServiceRequest request ) { if ( isCompleted ( ) || exportRequestObserver == null ) { return ; } try { exportRequestObserver . onNext ( request ) ; } catch ( Exception e ) { onComplete ( e ) ; } }
|
Sends the export request to Agent if the stream is still connected otherwise do nothing .
|
35,327
|
public static Duration create ( long seconds , int nanos ) { if ( seconds < - MAX_SECONDS ) { throw new IllegalArgumentException ( "'seconds' is less than minimum (" + - MAX_SECONDS + "): " + seconds ) ; } if ( seconds > MAX_SECONDS ) { throw new IllegalArgumentException ( "'seconds' is greater than maximum (" + MAX_SECONDS + "): " + seconds ) ; } if ( nanos < - MAX_NANOS ) { throw new IllegalArgumentException ( "'nanos' is less than minimum (" + - MAX_NANOS + "): " + nanos ) ; } if ( nanos > MAX_NANOS ) { throw new IllegalArgumentException ( "'nanos' is greater than maximum (" + MAX_NANOS + "): " + nanos ) ; } if ( ( seconds < 0 && nanos > 0 ) || ( seconds > 0 && nanos < 0 ) ) { throw new IllegalArgumentException ( "'seconds' and 'nanos' have inconsistent sign: seconds=" + seconds + ", nanos=" + nanos ) ; } return new AutoValue_Duration ( seconds , nanos ) ; }
|
Creates a new time duration from given seconds and nanoseconds .
|
35,328
|
static Node getNodeInfo ( String serviceName ) { String jvmName = ManagementFactory . getRuntimeMXBean ( ) . getName ( ) ; Timestamp censusTimestamp = Timestamp . fromMillis ( System . currentTimeMillis ( ) ) ; return Node . newBuilder ( ) . setIdentifier ( getProcessIdentifier ( jvmName , censusTimestamp ) ) . setLibraryInfo ( getLibraryInfo ( OpenCensusLibraryInformation . VERSION ) ) . setServiceInfo ( getServiceInfo ( serviceName ) ) . build ( ) ; }
|
Creates a Node with information from the OpenCensus library and environment variables .
|
35,329
|
static LibraryInfo getLibraryInfo ( String currentOcJavaVersion ) { return LibraryInfo . newBuilder ( ) . setLanguage ( Language . JAVA ) . setCoreLibraryVersion ( currentOcJavaVersion ) . setExporterVersion ( OC_AGENT_EXPORTER_VERSION ) . build ( ) ; }
|
Creates library info with the given OpenCensus Java version .
|
35,330
|
static ServiceInfo getServiceInfo ( String serviceName ) { return ServiceInfo . newBuilder ( ) . setName ( serviceName ) . build ( ) ; }
|
Creates service info with the given service name .
|
35,331
|
public HttpRequestContext handleStart ( C carrier , Q request ) { checkNotNull ( carrier , "carrier" ) ; checkNotNull ( request , "request" ) ; SpanBuilder spanBuilder = null ; String spanName = getSpanName ( request , extractor ) ; SpanContext spanContext = null ; try { spanContext = textFormat . extract ( carrier , getter ) ; } catch ( SpanContextParseException e ) { } if ( spanContext == null || publicEndpoint ) { spanBuilder = tracer . spanBuilder ( spanName ) ; } else { spanBuilder = tracer . spanBuilderWithRemoteParent ( spanName , spanContext ) ; } Span span = spanBuilder . setSpanKind ( Kind . SERVER ) . startSpan ( ) ; if ( publicEndpoint && spanContext != null ) { span . addLink ( Link . fromSpanContext ( spanContext , Type . PARENT_LINKED_SPAN ) ) ; } if ( span . getOptions ( ) . contains ( Options . RECORD_EVENTS ) ) { addSpanRequestAttributes ( span , request , extractor ) ; } return getNewContext ( span , tagger . getCurrentTagContext ( ) ) ; }
|
Instrument an incoming request before it is handled .
|
35,332
|
private Map < String , StatsSnapshot > getStatsSnapshots ( boolean isReceived ) { SortedMap < String , StatsSnapshot > map = Maps . newTreeMap ( ) ; if ( isReceived ) { getStatsSnapshots ( map , SERVER_RPC_CUMULATIVE_VIEWS ) ; getStatsSnapshots ( map , SERVER_RPC_MINUTE_VIEWS ) ; getStatsSnapshots ( map , SERVER_RPC_HOUR_VIEWS ) ; } else { getStatsSnapshots ( map , CLIENT_RPC_CUMULATIVE_VIEWS ) ; getStatsSnapshots ( map , CLIENT_RPC_MINUTE_VIEWS ) ; getStatsSnapshots ( map , CLIENT_RPC_HOUR_VIEWS ) ; } return map ; }
|
Gets stats snapshot for each method .
|
35,333
|
private static double getDurationInSecs ( ViewData . AggregationWindowData . CumulativeData cumulativeData ) { return toDoubleSeconds ( cumulativeData . getEnd ( ) . subtractTimestamp ( cumulativeData . getStart ( ) ) ) ; }
|
Calculates the duration of the given CumulativeData in seconds .
|
35,334
|
public static void main ( String [ ] args ) throws InterruptedException { TagContextBuilder tagContextBuilder = tagger . currentBuilder ( ) . put ( FRONTEND_KEY , TagValue . create ( "mobile-ios9.3.5" ) ) ; SpanBuilder spanBuilder = tracer . spanBuilder ( "my.org/ProcessVideo" ) . setRecordEvents ( true ) . setSampler ( Samplers . alwaysSample ( ) ) ; viewManager . registerView ( VIDEO_SIZE_VIEW ) ; LoggingTraceExporter . register ( ) ; try ( Scope scopedTags = tagContextBuilder . buildScoped ( ) ; Scope scopedSpan = spanBuilder . startScopedSpan ( ) ) { tracer . getCurrentSpan ( ) . addAnnotation ( "Start processing video." ) ; Thread . sleep ( new Random ( ) . nextInt ( 10 ) + 1 ) ; statsRecorder . newMeasureMap ( ) . put ( VIDEO_SIZE , 25 * MiB ) . record ( ) ; tracer . getCurrentSpan ( ) . addAnnotation ( "Finished processing video." ) ; } catch ( Exception e ) { tracer . getCurrentSpan ( ) . addAnnotation ( "Exception thrown when processing video." ) ; tracer . getCurrentSpan ( ) . setStatus ( Status . UNKNOWN ) ; logger . severe ( e . getMessage ( ) ) ; } logger . info ( "Wait longer than the reporting duration..." ) ; Thread . sleep ( 5100 ) ; ViewData viewData = viewManager . getView ( VIDEO_SIZE_VIEW_NAME ) ; logger . info ( String . format ( "Recorded stats for %s:\n %s" , VIDEO_SIZE_VIEW_NAME . asString ( ) , viewData ) ) ; }
|
Main launcher for the QuickStart example .
|
35,335
|
public static TagKey [ ] createTagKeys ( int size , String name ) { TagKey [ ] keys = new TagKey [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { keys [ i ] = TagKey . create ( name + i ) ; } return keys ; }
|
Creates an array of TagKeys of size with name prefix .
|
35,336
|
public static TagValue [ ] createTagValues ( int size , String name ) { TagValue [ ] values = new TagValue [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { values [ i ] = TagValue . create ( name + i ) ; } return values ; }
|
Creates an array of TagValues of size with name prefix .
|
35,337
|
public static TagContext createTagContext ( TagContextBuilder tagsBuilder , int numTags ) { for ( int i = 0 ; i < numTags ; i ++ ) { tagsBuilder . put ( TAG_KEYS . get ( i ) , TAG_VALUES . get ( i ) , UNLIMITED_PROPAGATION ) ; } return tagsBuilder . build ( ) ; }
|
Adds numTags tags to tagsBuilder and returns the associated tag context .
|
35,338
|
private static DisruptorEventQueue create ( ) { Disruptor < DisruptorEvent > disruptor = new Disruptor < > ( DisruptorEventFactory . INSTANCE , DISRUPTOR_BUFFER_SIZE , new DaemonThreadFactory ( "OpenCensus.Disruptor" ) , ProducerType . MULTI , new SleepingWaitStrategy ( 0 , 1000 * 1000 ) ) ; disruptor . handleEventsWith ( new DisruptorEventHandler [ ] { DisruptorEventHandler . INSTANCE } ) ; disruptor . start ( ) ; final RingBuffer < DisruptorEvent > ringBuffer = disruptor . getRingBuffer ( ) ; DisruptorEnqueuer enqueuer = new DisruptorEnqueuer ( ) { public void enqueue ( Entry entry ) { long sequence = ringBuffer . next ( ) ; try { DisruptorEvent event = ringBuffer . get ( sequence ) ; event . setEntry ( entry ) ; } finally { ringBuffer . publish ( sequence ) ; } } } ; return new DisruptorEventQueue ( disruptor , enqueuer ) ; }
|
Creates a new EventQueue . Private to prevent creation of non - singleton instance .
|
35,339
|
public void shutdown ( ) { enqueuer = new DisruptorEnqueuer ( ) { final AtomicBoolean logged = new AtomicBoolean ( false ) ; public void enqueue ( Entry entry ) { if ( ! logged . getAndSet ( true ) ) { logger . log ( Level . INFO , "Attempted to enqueue entry after Disruptor shutdown." ) ; } } } ; disruptor . shutdown ( ) ; }
|
Shuts down the underlying disruptor .
|
35,340
|
public final Span getCurrentSpan ( ) { Span currentSpan = CurrentSpanUtils . getCurrentSpan ( ) ; return currentSpan != null ? currentSpan : BlankSpan . INSTANCE ; }
|
Gets the current Span from the current Context .
|
35,341
|
public static void unregister ( ) { synchronized ( monitor ) { checkState ( handler != null , "Zipkin exporter is not registered." ) ; unregister ( Tracing . getExportComponent ( ) . getSpanExporter ( ) ) ; handler = null ; } }
|
Unregisters the Zipkin Trace exporter from the OpenCensus library .
|
35,342
|
static Span getCurrentSpan ( ) { SpanContext currentSpanContext = CURRENT_SPAN . get ( ) ; return currentSpanContext != null ? currentSpanContext . span : null ; }
|
Get the current span out of the thread context .
|
35,343
|
static void setCurrentSpan ( Span span ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "Setting current span " + span ) ; } push ( span , false ) ; }
|
Set the current span in the thread context
|
35,344
|
static void close ( SpanFunction spanFunction ) { SpanContext current = CURRENT_SPAN . get ( ) ; while ( current != null ) { spanFunction . apply ( current . span ) ; current = removeCurrentSpanInternal ( current . parent ) ; if ( current == null || ! current . autoClose ) { return ; } } }
|
will be applied on the closed Span .
|
35,345
|
static void push ( Span span , boolean autoClose ) { if ( isCurrent ( span ) ) { return ; } setSpanContextInternal ( new SpanContext ( span , autoClose ) ) ; }
|
Push a span into the thread context with the option to have it auto close if any child spans are themselves closed . Use autoClose = true if you start a new span with a parent that wasn t already in thread context .
|
35,346
|
public static void main ( String ... args ) { try { setupOpenCensusAndPrometheusExporter ( ) ; } catch ( IOException e ) { System . err . println ( "Failed to create and register OpenCensus Prometheus Stats exporter " + e ) ; return ; } BufferedReader stdin = new BufferedReader ( new InputStreamReader ( System . in ) ) ; while ( true ) { try { readEvaluateProcessLine ( stdin ) ; } catch ( IOException e ) { System . err . println ( "EOF bye " + e ) ; return ; } catch ( Exception e ) { recordTaggedStat ( KEY_METHOD , "repl" , M_ERRORS , new Long ( 1 ) ) ; return ; } } }
|
Main launcher for the Repl example .
|
35,347
|
public String get ( String key ) { for ( Entry entry : getEntries ( ) ) { if ( entry . getKey ( ) . equals ( key ) ) { return entry . getValue ( ) ; } } return null ; }
|
Returns the value to which the specified key is mapped or null if this map contains no mapping for the key .
|
35,348
|
private static boolean validateValue ( String value ) { if ( value . length ( ) > VALUE_MAX_SIZE || value . charAt ( value . length ( ) - 1 ) == ' ' ) { return false ; } for ( int i = 0 ; i < value . length ( ) ; i ++ ) { char c = value . charAt ( i ) ; if ( c == ',' || c == '=' || c < ' ' || c > '~' ) { return false ; } } return true ; }
|
0x20 to 0x7E ) except comma and = .
|
35,349
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public TagContext timeNestedTagContext ( Data data ) { return TagsBenchmarksUtil . createTagContext ( data . tagger . toBuilder ( data . baseTagContext ) , data . numTags ) ; }
|
Build nested tag context .
|
35,350
|
public static void createAndRegister ( final String thriftEndpoint , final String serviceName ) { synchronized ( monitor ) { checkState ( handler == null , "Jaeger exporter is already registered." ) ; final SpanExporter . Handler newHandler = newHandler ( thriftEndpoint , serviceName ) ; JaegerTraceExporter . handler = newHandler ; register ( Tracing . getExportComponent ( ) . getSpanExporter ( ) , newHandler ) ; } }
|
Creates and registers the Jaeger Trace exporter to the OpenCensus library . Only one Jaeger exporter can be registered at any point .
|
35,351
|
public static void createWithSender ( final ThriftSender sender , final String serviceName ) { synchronized ( monitor ) { checkState ( handler == null , "Jaeger exporter is already registered." ) ; final SpanExporter . Handler newHandler = newHandlerWithSender ( sender , serviceName ) ; JaegerTraceExporter . handler = newHandler ; register ( Tracing . getExportComponent ( ) . getSpanExporter ( ) , newHandler ) ; } }
|
Creates and registers the Jaeger Trace exporter to the OpenCensus library using the provided HttpSender . Only one Jaeger exporter can be registered at any point .
|
35,352
|
private static void performWork ( Span parent ) { SpanBuilder spanBuilder = tracer . spanBuilderWithExplicitParent ( "internal_work" , parent ) . setRecordEvents ( true ) . setSampler ( Samplers . alwaysSample ( ) ) ; try ( Scope scope = spanBuilder . startScopedSpan ( ) ) { Span span = tracer . getCurrentSpan ( ) ; span . putAttribute ( "my_attribute" , AttributeValue . stringAttributeValue ( "blue" ) ) ; span . addAnnotation ( "Performing work." ) ; sleepFor ( 20 ) ; span . addAnnotation ( "Done work." ) ; } }
|
A helper function that performs some work in its own Span .
|
35,353
|
@ SuppressWarnings ( "deprecation" ) private static void emitTraceParamsTable ( TraceParams params , PrintWriter out ) { out . write ( "<b class=\"title\">Active tracing parameters:</b><br>\n" + "<table class=\"small\" rules=\"all\">\n" + " <tr>\n" + " <td class=\"col_headR\">Name</td>\n" + " <td class=\"col_head\">Value</td>\n" + " </tr>\n" ) ; out . printf ( " <tr>%n <td>Sampler</td>%n <td>%s</td>%n </tr>%n" , params . getSampler ( ) . getDescription ( ) ) ; out . printf ( " <tr>%n <td>MaxNumberOfAttributes</td>%n <td>%d</td>%n </tr>%n" , params . getMaxNumberOfAttributes ( ) ) ; out . printf ( " <tr>%n <td>MaxNumberOfAnnotations</td>%n <td>%d</td>%n </tr>%n" , params . getMaxNumberOfAnnotations ( ) ) ; out . printf ( " <tr>%n <td>MaxNumberOfNetworkEvents</td>%n <td>%d</td>%n </tr>%n" , params . getMaxNumberOfNetworkEvents ( ) ) ; out . printf ( " <tr>%n <td>MaxNumberOfLinks</td>%n <td>%d</td>%n </tr>%n" , params . getMaxNumberOfLinks ( ) ) ; out . write ( "</table>\n" ) ; }
|
Prints a table to a PrintWriter that shows existing trace parameters .
|
35,354
|
@ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span putAttribute ( Data data ) { data . span . putAttribute ( ATTRIBUTE_KEY , AttributeValue . stringAttributeValue ( ATTRIBUTE_VALUE ) ) ; return data . span ; }
|
This benchmark attempts to measure performance of adding an attribute to the span .
|
35,355
|
@ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span addAnnotation ( Data data ) { data . span . addAnnotation ( ANNOTATION_DESCRIPTION ) ; return data . span ; }
|
This benchmark attempts to measure performance of adding an annotation to the span .
|
35,356
|
@ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span addMessageEvent ( Data data ) { data . span . addMessageEvent ( io . opencensus . trace . MessageEvent . builder ( Type . RECEIVED , 1 ) . setUncompressedMessageSize ( 3 ) . build ( ) ) ; return data . span ; }
|
This benchmark attempts to measure performance of adding a network event to the span .
|
35,357
|
@ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span addLink ( Data data ) { data . span . addLink ( Link . fromSpanContext ( data . linkedSpan . getContext ( ) , Link . Type . PARENT_LINKED_SPAN ) ) ; return data . span ; }
|
This benchmark attempts to measure performance of adding a link to the span .
|
35,358
|
static OcAgentMetricsServiceExportRpcHandler create ( MetricsServiceStub stub ) { OcAgentMetricsServiceExportRpcHandler exportRpcHandler = new OcAgentMetricsServiceExportRpcHandler ( ) ; ExportResponseObserver exportResponseObserver = new ExportResponseObserver ( exportRpcHandler ) ; try { StreamObserver < ExportMetricsServiceRequest > exportRequestObserver = stub . export ( exportResponseObserver ) ; exportRpcHandler . setExportRequestObserver ( exportRequestObserver ) ; } catch ( StatusRuntimeException e ) { exportRpcHandler . onComplete ( e ) ; } return exportRpcHandler ; }
|
given MetricsServiceStub .
|
35,359
|
public static Timestamp create ( long seconds , int nanos ) { if ( seconds < - MAX_SECONDS ) { throw new IllegalArgumentException ( "'seconds' is less than minimum (" + - MAX_SECONDS + "): " + seconds ) ; } if ( seconds > MAX_SECONDS ) { throw new IllegalArgumentException ( "'seconds' is greater than maximum (" + MAX_SECONDS + "): " + seconds ) ; } if ( nanos < 0 ) { throw new IllegalArgumentException ( "'nanos' is less than zero: " + nanos ) ; } if ( nanos > MAX_NANOS ) { throw new IllegalArgumentException ( "'nanos' is greater than maximum (" + MAX_NANOS + "): " + nanos ) ; } return new AutoValue_Timestamp ( seconds , nanos ) ; }
|
Creates a new timestamp from given seconds and nanoseconds .
|
35,360
|
public static Timestamp fromMillis ( long epochMilli ) { long secs = floorDiv ( epochMilli , MILLIS_PER_SECOND ) ; int mos = ( int ) floorMod ( epochMilli , MILLIS_PER_SECOND ) ; return create ( secs , ( int ) ( mos * NANOS_PER_MILLI ) ) ; }
|
Creates a new timestamp from the given milliseconds .
|
35,361
|
private Timestamp plus ( long secondsToAdd , long nanosToAdd ) { if ( ( secondsToAdd | nanosToAdd ) == 0 ) { return this ; } long epochSec = TimeUtils . checkedAdd ( getSeconds ( ) , secondsToAdd ) ; epochSec = TimeUtils . checkedAdd ( epochSec , nanosToAdd / NANOS_PER_SECOND ) ; nanosToAdd = nanosToAdd % NANOS_PER_SECOND ; long nanoAdjustment = getNanos ( ) + nanosToAdd ; return ofEpochSecond ( epochSec , nanoAdjustment ) ; }
|
Returns a Timestamp with the specified duration added .
|
35,362
|
private static long floorDiv ( long x , long y ) { return BigDecimal . valueOf ( x ) . divide ( BigDecimal . valueOf ( y ) , 0 , RoundingMode . FLOOR ) . longValue ( ) ; }
|
Returns the result of dividing x by y rounded using floor .
|
35,363
|
private static Map < String , String > initializeAwsIdentityDocument ( ) { InputStream stream = null ; try { stream = openStream ( AWS_INSTANCE_IDENTITY_DOCUMENT_URI ) ; String awsIdentityDocument = slurp ( new InputStreamReader ( stream , Charset . forName ( "UTF-8" ) ) ) ; return parseAwsIdentityDocument ( awsIdentityDocument ) ; } catch ( IOException e ) { } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( IOException e ) { } } } return Collections . emptyMap ( ) ; }
|
This method should only be called once .
|
35,364
|
private static Set < View > filterExportedViews ( Collection < View > allViews ) { Set < View > views = Sets . newHashSet ( ) ; for ( View view : allViews ) { if ( view . getWindow ( ) instanceof View . AggregationWindow . Cumulative ) { views . add ( view ) ; } } return Collections . unmodifiableSet ( views ) ; }
|
Returns the subset of the given views that should be exported
|
35,365
|
synchronized void record ( TagContext tags , MeasureMapInternal stats , Timestamp timestamp ) { Iterator < Measurement > iterator = stats . iterator ( ) ; Map < String , AttachmentValue > attachments = stats . getAttachments ( ) ; while ( iterator . hasNext ( ) ) { Measurement measurement = iterator . next ( ) ; Measure measure = measurement . getMeasure ( ) ; if ( ! measure . equals ( registeredMeasures . get ( measure . getName ( ) ) ) ) { continue ; } Collection < MutableViewData > viewDataCollection = mutableMap . get ( measure . getName ( ) ) ; for ( MutableViewData viewData : viewDataCollection ) { viewData . record ( tags , RecordUtils . getDoubleValueFromMeasurement ( measurement ) , timestamp , attachments ) ; } } }
|
Records stats with a set of tags .
|
35,366
|
synchronized void clearStats ( ) { for ( Entry < String , Collection < MutableViewData > > entry : mutableMap . asMap ( ) . entrySet ( ) ) { for ( MutableViewData mutableViewData : entry . getValue ( ) ) { mutableViewData . clearStats ( ) ; } } }
|
Clear stats for all the current MutableViewData
|
35,367
|
synchronized void resumeStatsCollection ( Timestamp now ) { for ( Entry < String , Collection < MutableViewData > > entry : mutableMap . asMap ( ) . entrySet ( ) ) { for ( MutableViewData mutableViewData : entry . getValue ( ) ) { mutableViewData . resumeStatsCollection ( now ) ; } } }
|
Resume stats collection for all MutableViewData .
|
35,368
|
static ProcessIdentifier getProcessIdentifier ( String jvmName , Timestamp censusTimestamp ) { String hostname ; int pid ; int delimiterIndex = jvmName . indexOf ( '@' ) ; if ( delimiterIndex < 1 ) { try { hostname = InetAddress . getLocalHost ( ) . getHostName ( ) ; } catch ( UnknownHostException e ) { hostname = "localhost" ; } pid = new SecureRandom ( ) . nextInt ( ) ; } else { hostname = jvmName . substring ( delimiterIndex + 1 , jvmName . length ( ) ) ; try { pid = Integer . parseInt ( jvmName . substring ( 0 , delimiterIndex ) ) ; } catch ( NumberFormatException e ) { pid = new SecureRandom ( ) . nextInt ( ) ; } } return ProcessIdentifier . newBuilder ( ) . setHostName ( hostname ) . setPid ( pid ) . setStartTimestamp ( MetricsProtoUtils . toTimestampProto ( censusTimestamp ) ) . build ( ) ; }
|
Creates process identifier with the given JVM name and start time .
|
35,369
|
public static void main ( String [ ] args ) throws InterruptedException { configureAlwaysSample ( ) ; registerAllViews ( ) ; LongGauge gauge = registerGauge ( ) ; String endPoint = getStringOrDefaultFromArgs ( args , 0 , DEFAULT_ENDPOINT ) ; registerAgentExporters ( endPoint ) ; try ( Scope scope = tracer . spanBuilder ( "root" ) . startScopedSpan ( ) ) { int iteration = 1 ; while ( true ) { doWork ( iteration , random . nextInt ( 10 ) , gauge ) ; iteration ++ ; Thread . sleep ( 5000 ) ; } } catch ( InterruptedException e ) { logger . info ( "Thread interrupted, exiting in 5 seconds." ) ; Thread . sleep ( 5000 ) ; } }
|
Main launcher of the example .
|
35,370
|
public State get ( ) { InternalState internalState = currentInternalState . get ( ) ; while ( ! internalState . isRead ) { currentInternalState . compareAndSet ( internalState , internalState . state == State . ENABLED ? InternalState . ENABLED_READ : InternalState . DISABLED_READ ) ; internalState = currentInternalState . get ( ) ; } return internalState . state ; }
|
Returns the current state and updates the status as being read .
|
35,371
|
public boolean set ( State state ) { while ( true ) { InternalState internalState = currentInternalState . get ( ) ; checkState ( ! internalState . isRead , "State was already read, cannot set state." ) ; if ( state == internalState . state ) { return false ; } else { if ( ! currentInternalState . compareAndSet ( internalState , state == State . ENABLED ? InternalState . ENABLED_NOT_READ : InternalState . DISABLED_NOT_READ ) ) { continue ; } return true ; } } }
|
Sets current state to the given state . Returns true if the current state is changed false otherwise .
|
35,372
|
private static int encodeTag ( Tag tag , StringBuilder stringBuilder ) { String key = tag . getKey ( ) . getName ( ) ; String value = tag . getValue ( ) . asString ( ) ; int charsOfTag = key . length ( ) + value . length ( ) ; checkArgument ( charsOfTag <= TAG_SERIALIZED_SIZE_LIMIT , "Serialized size of tag " + tag + " exceeds limit " + TAG_SERIALIZED_SIZE_LIMIT ) ; stringBuilder . append ( key ) . append ( TAG_KEY_VALUE_DELIMITER ) . append ( value ) ; return charsOfTag ; }
|
Encodes the tag to the given string builder and returns the length of encoded key - value pair .
|
35,373
|
private static void decodeTag ( String stringTag , Map < TagKey , TagValueWithMetadata > tags ) { String keyWithValue ; int firstPropertyIndex = stringTag . indexOf ( TAG_PROPERTIES_DELIMITER ) ; if ( firstPropertyIndex != - 1 ) { keyWithValue = stringTag . substring ( 0 , firstPropertyIndex ) ; } else { keyWithValue = stringTag ; } List < String > keyValuePair = TAG_KEY_VALUE_SPLITTER . splitToList ( keyWithValue ) ; checkArgument ( keyValuePair . size ( ) == 2 , "Malformed tag " + stringTag ) ; TagKey key = TagKey . create ( keyValuePair . get ( 0 ) . trim ( ) ) ; TagValue value = TagValue . create ( keyValuePair . get ( 1 ) . trim ( ) ) ; TagValueWithMetadata valueWithMetadata = TagValueWithMetadata . create ( value , METADATA_UNLIMITED_PROPAGATION ) ; tags . put ( key , valueWithMetadata ) ; }
|
The format of encoded string tag is name1 = value1 ; properties1 = p1 ; properties2 = p2 .
|
35,374
|
private static void emitSpans ( PrintWriter out , Formatter formatter , Collection < SpanData > spans ) { out . write ( "<pre>\n" ) ; formatter . format ( "%-23s %18s%n" , "When" , "Elapsed(s)" ) ; out . write ( "-------------------------------------------\n" ) ; for ( SpanData span : spans ) { tracer . getCurrentSpan ( ) . addAnnotation ( "Render span." , ImmutableMap . < String , AttributeValue > builder ( ) . put ( "SpanId" , AttributeValue . stringAttributeValue ( BaseEncoding . base16 ( ) . lowerCase ( ) . encode ( span . getContext ( ) . getSpanId ( ) . getBytes ( ) ) ) ) . build ( ) ) ; emitSingleSpan ( formatter , span ) ; } out . write ( "</pre>\n" ) ; }
|
Emits the list of SampledRequets with a header .
|
35,375
|
private void emitSummaryTable ( PrintWriter out , Formatter formatter ) throws UnsupportedEncodingException { if ( runningSpanStore == null || sampledSpanStore == null ) { return ; } RunningSpanStore . Summary runningSpanStoreSummary = runningSpanStore . getSummary ( ) ; SampledSpanStore . Summary sampledSpanStoreSummary = sampledSpanStore . getSummary ( ) ; out . write ( "<table style='border-spacing: 0;\n" ) ; out . write ( "border-left:1px solid #3D3D3D;border-right:1px solid #3D3D3D;'>\n" ) ; emitSummaryTableHeader ( out , formatter ) ; Set < String > spanNames = new TreeSet < > ( runningSpanStoreSummary . getPerSpanNameSummary ( ) . keySet ( ) ) ; spanNames . addAll ( sampledSpanStoreSummary . getPerSpanNameSummary ( ) . keySet ( ) ) ; boolean zebraColor = true ; for ( String spanName : spanNames ) { out . write ( "<tr class=\"border\">\n" ) ; if ( ! zebraColor ) { out . write ( "<tr class=\"border\">\n" ) ; } else { formatter . format ( "<tr class=\"border\" style=\"background: %s\">%n" , ZEBRA_STRIPE_COLOR ) ; } zebraColor = ! zebraColor ; formatter . format ( "<td>%s</td>%n" , htmlEscaper ( ) . escape ( spanName ) ) ; out . write ( "<td class=\"borderRL\"> </td>" ) ; RunningSpanStore . PerSpanNameSummary runningSpanStorePerSpanNameSummary = runningSpanStoreSummary . getPerSpanNameSummary ( ) . get ( spanName ) ; emitSingleCell ( out , formatter , spanName , runningSpanStorePerSpanNameSummary == null ? 0 : runningSpanStorePerSpanNameSummary . getNumRunningSpans ( ) , RequestType . RUNNING , 0 ) ; SampledSpanStore . PerSpanNameSummary sampledSpanStorePerSpanNameSummary = sampledSpanStoreSummary . getPerSpanNameSummary ( ) . get ( spanName ) ; out . write ( "<td class=\"borderLC\"> </td>" ) ; Map < LatencyBucketBoundaries , Integer > latencyBucketsSummaries = sampledSpanStorePerSpanNameSummary != null ? sampledSpanStorePerSpanNameSummary . getNumbersOfLatencySampledSpans ( ) : null ; int subtype = 0 ; for ( LatencyBucketBoundaries latencyBucketsBoundaries : LatencyBucketBoundaries . values ( ) ) { if ( latencyBucketsSummaries != null ) { int numSamples = latencyBucketsSummaries . containsKey ( latencyBucketsBoundaries ) ? latencyBucketsSummaries . get ( latencyBucketsBoundaries ) : 0 ; emitSingleCell ( out , formatter , spanName , numSamples , RequestType . FINISHED , subtype ++ ) ; } else { emitSingleCell ( out , formatter , spanName , - 1 , RequestType . FINISHED , subtype ++ ) ; } } out . write ( "<td class=\"borderRL\"> </td>" ) ; if ( sampledSpanStorePerSpanNameSummary != null ) { Map < CanonicalCode , Integer > errorBucketsSummaries = sampledSpanStorePerSpanNameSummary . getNumbersOfErrorSampledSpans ( ) ; int numErrorSamples = 0 ; for ( Map . Entry < CanonicalCode , Integer > it : errorBucketsSummaries . entrySet ( ) ) { numErrorSamples += it . getValue ( ) ; } emitSingleCell ( out , formatter , spanName , numErrorSamples , RequestType . FAILED , 0 ) ; } else { emitSingleCell ( out , formatter , spanName , - 1 , RequestType . FAILED , 0 ) ; } out . write ( "</tr>\n" ) ; } out . write ( "</table>" ) ; }
|
Emits the summary table with links to all samples .
|
35,376
|
public static int getVarInt ( byte [ ] src , int offset , int [ ] dst ) { int result = 0 ; int shift = 0 ; int b ; do { if ( shift >= 32 ) { throw new IndexOutOfBoundsException ( "varint too long" ) ; } b = src [ offset ++ ] ; result |= ( b & 0x7F ) << shift ; shift += 7 ; } while ( ( b & 0x80 ) != 0 ) ; dst [ 0 ] = result ; return offset ; }
|
Reads a varint from src places its values into the first element of dst and returns the offset in to src of the first byte after the varint .
|
35,377
|
public static int getVarInt ( ByteBuffer src ) { int tmp ; if ( ( tmp = src . get ( ) ) >= 0 ) { return tmp ; } int result = tmp & 0x7f ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 7 ; } else { result |= ( tmp & 0x7f ) << 7 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 14 ; } else { result |= ( tmp & 0x7f ) << 14 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 21 ; } else { result |= ( tmp & 0x7f ) << 21 ; result |= ( tmp = src . get ( ) ) << 28 ; while ( tmp < 0 ) { tmp = src . get ( ) ; } } } } return result ; }
|
Reads a varint from the current position of the given ByteBuffer and returns the decoded value as 32 bit integer .
|
35,378
|
public static void putVarInt ( int v , ByteBuffer sink ) { while ( true ) { int bits = v & 0x7f ; v >>>= 7 ; if ( v == 0 ) { sink . put ( ( byte ) bits ) ; return ; } sink . put ( ( byte ) ( bits | 0x80 ) ) ; } }
|
Encodes an integer in a variable - length encoding 7 bits per byte to a ByteBuffer sink .
|
35,379
|
public static int getVarInt ( InputStream inputStream ) throws IOException { int result = 0 ; int shift = 0 ; int b ; do { if ( shift >= 32 ) { throw new IndexOutOfBoundsException ( "varint too long" ) ; } b = inputStream . read ( ) ; result |= ( b & 0x7F ) << shift ; shift += 7 ; } while ( ( b & 0x80 ) != 0 ) ; return result ; }
|
Reads a varint from the given InputStream and returns the decoded value as an int .
|
35,380
|
public static void putVarInt ( int v , OutputStream outputStream ) throws IOException { byte [ ] bytes = new byte [ varIntSize ( v ) ] ; putVarInt ( v , bytes , 0 ) ; outputStream . write ( bytes ) ; }
|
Encodes an integer in a variable - length encoding 7 bits per byte and writes it to the given OutputStream .
|
35,381
|
public static long getVarLong ( ByteBuffer src ) { long tmp ; if ( ( tmp = src . get ( ) ) >= 0 ) { return tmp ; } long result = tmp & 0x7f ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 7 ; } else { result |= ( tmp & 0x7f ) << 7 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 14 ; } else { result |= ( tmp & 0x7f ) << 14 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 21 ; } else { result |= ( tmp & 0x7f ) << 21 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 28 ; } else { result |= ( tmp & 0x7f ) << 28 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 35 ; } else { result |= ( tmp & 0x7f ) << 35 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 42 ; } else { result |= ( tmp & 0x7f ) << 42 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 49 ; } else { result |= ( tmp & 0x7f ) << 49 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 56 ; } else { result |= ( tmp & 0x7f ) << 56 ; result |= ( ( long ) src . get ( ) ) << 63 ; } } } } } } } } return result ; }
|
Reads an up to 64 bit long varint from the current position of the given ByteBuffer and returns the decoded value as long .
|
35,382
|
public static void putVarLong ( long v , ByteBuffer sink ) { while ( true ) { int bits = ( ( int ) v ) & 0x7f ; v >>>= 7 ; if ( v == 0 ) { sink . put ( ( byte ) bits ) ; return ; } sink . put ( ( byte ) ( bits | 0x80 ) ) ; } }
|
Encodes a long integer in a variable - length encoding 7 bits per byte to a ByteBuffer sink .
|
35,383
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span createRootSpan ( Data data ) { Span span = data . tracer . spanBuilderWithExplicitParent ( "RootSpan" , null ) . setRecordEvents ( data . recorded ) . setSampler ( data . sampled ? Samplers . alwaysSample ( ) : Samplers . neverSample ( ) ) . startSpan ( ) ; span . end ( ) ; return span ; }
|
Create a root span .
|
35,384
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Link createLink ( Data data ) { return Link . fromSpanContext ( SpanContext . create ( TraceId . fromBytes ( new byte [ ] { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 0 } ) , SpanId . fromBytes ( new byte [ ] { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 0 } ) , TraceOptions . DEFAULT , TRACESTATE_DEFAULT ) , Link . Type . PARENT_LINKED_SPAN ) ; }
|
Create a link .
|
35,385
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public MessageEvent createMessageEvent ( Data data ) { return MessageEvent . builder ( MessageEvent . Type . SENT , MESSAGE_ID ) . build ( ) ; }
|
Create a message event .
|
35,386
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span getCurrentSpan ( Data data ) { return data . tracer . getCurrentSpan ( ) ; }
|
Get current trace span .
|
35,387
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public byte [ ] encodeSpanBinary ( Data data ) { return data . propagation . getBinaryFormat ( ) . toByteArray ( data . spanToEncode . getContext ( ) ) ; }
|
Encode a span using binary format .
|
35,388
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public SpanContext decodeSpanBinary ( Data data ) throws SpanContextParseException { return data . propagation . getBinaryFormat ( ) . fromByteArray ( data . spanToDecodeBinary ) ; }
|
Decode a span using binary format .
|
35,389
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public String encodeSpanText ( Data data ) { return encodeSpanContextText ( data . propagation . getTraceContextFormat ( ) , data . spanToEncode . getContext ( ) ) ; }
|
Encode a span using text format .
|
35,390
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public SpanContext decodeSpanText ( Data data ) throws SpanContextParseException { return data . propagation . getTraceContextFormat ( ) . extract ( data . spanToDecodeText , textGetter ) ; }
|
Decode a span using text format .
|
35,391
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span setStatus ( Data data ) { data . spanToSet . setStatus ( STATUS_OK ) ; return data . spanToSet ; }
|
Set status on a span .
|
35,392
|
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span endSpan ( Data data ) { data . spanToEnd . end ( ) ; return data . spanToEnd ; }
|
End a span .
|
35,393
|
public static void createAndRegisterWithCredentialsAndProjectId ( Credentials credentials , String projectId ) throws IOException { StackdriverTraceExporter . createAndRegister ( StackdriverTraceConfiguration . builder ( ) . setCredentials ( credentials ) . setProjectId ( projectId ) . build ( ) ) ; }
|
Creates and registers the Stackdriver Trace exporter to the OpenCensus library for an explicit project ID and using explicit credentials . Only one Stackdriver exporter can be registered at any point .
|
35,394
|
public static void createAndRegisterWithProjectId ( String projectId ) throws IOException { StackdriverTraceExporter . createAndRegister ( StackdriverTraceConfiguration . builder ( ) . setCredentials ( GoogleCredentials . getApplicationDefault ( ) ) . setProjectId ( projectId ) . build ( ) ) ; }
|
Creates and registers the Stackdriver Trace exporter to the OpenCensus library for an explicit project ID . Only one Stackdriver exporter can be registered at any point .
|
35,395
|
static List < DataPoint > adapt ( Metric metric ) { MetricDescriptor metricDescriptor = metric . getMetricDescriptor ( ) ; MetricType metricType = getType ( metricDescriptor . getType ( ) ) ; if ( metricType == null ) { return Collections . emptyList ( ) ; } DataPoint . Builder shared = DataPoint . newBuilder ( ) ; shared . setMetric ( metricDescriptor . getName ( ) ) ; shared . setMetricType ( metricType ) ; ArrayList < DataPoint > datapoints = Lists . newArrayList ( ) ; for ( TimeSeries timeSeries : metric . getTimeSeriesList ( ) ) { DataPoint . Builder builder = shared . clone ( ) ; builder . addAllDimensions ( createDimensions ( metricDescriptor . getLabelKeys ( ) , timeSeries . getLabelValues ( ) ) ) ; List < Point > points = timeSeries . getPoints ( ) ; datapoints . ensureCapacity ( datapoints . size ( ) + points . size ( ) ) ; for ( Point point : points ) { datapoints . add ( builder . setValue ( createDatum ( point . getValue ( ) ) ) . build ( ) ) ; } } return datapoints ; }
|
Converts the given Metric into datapoints that can be sent to SignalFx .
|
35,396
|
@ SuppressWarnings ( "unused" ) public void setSmtpAuth ( String userName , String password ) { setSmtpUsername ( userName ) ; setSmtpPassword ( password ) ; }
|
Make API match Mailer plugin
|
35,397
|
private Object readResolve ( ) throws ObjectStreamException { if ( triggerScript != null && secureTriggerScript == null ) { this . secureTriggerScript = new SecureGroovyScript ( triggerScript , false , null ) ; this . secureTriggerScript . configuring ( ApprovalContext . create ( ) ) ; triggerScript = null ; } return this ; }
|
Called when object has been deserialized from a stream .
|
35,398
|
private String renderTemplate ( Run < ? , ? > build , FilePath workspace , TaskListener listener , InputStream templateStream ) throws IOException { String result ; final Map < String , Object > binding = new HashMap < > ( ) ; ExtendedEmailPublisherDescriptor descriptor = Jenkins . getActiveInstance ( ) . getDescriptorByType ( ExtendedEmailPublisherDescriptor . class ) ; binding . put ( "build" , build ) ; binding . put ( "listener" , listener ) ; binding . put ( "it" , new ScriptContentBuildWrapper ( build ) ) ; binding . put ( "rooturl" , descriptor . getHudsonUrl ( ) ) ; binding . put ( "project" , build . getParent ( ) ) ; binding . put ( "workspace" , workspace ) ; try { String text = IOUtils . toString ( templateStream ) ; boolean approvedScript = false ; if ( templateStream instanceof UserProvidedContentInputStream && ! AbstractEvalContent . isApprovedScript ( text , GroovyLanguage . get ( ) ) ) { approvedScript = false ; ScriptApproval . get ( ) . configuring ( text , GroovyLanguage . get ( ) , ApprovalContext . create ( ) . withItem ( build . getParent ( ) ) ) ; } else { approvedScript = true ; } GroovyShell shell = createEngine ( descriptor , Collections . < String , Object > emptyMap ( ) , ! approvedScript ) ; SimpleTemplateEngine engine = new SimpleTemplateEngine ( shell ) ; Template tmpl ; synchronized ( templateCache ) { Reference < Template > templateR = templateCache . get ( text ) ; tmpl = templateR == null ? null : templateR . get ( ) ; if ( tmpl == null ) { tmpl = engine . createTemplate ( text ) ; templateCache . put ( text , new SoftReference < > ( tmpl ) ) ; } } final Template tmplR = tmpl ; if ( approvedScript ) { result = tmplR . make ( binding ) . toString ( ) ; } else { StaticProxyInstanceWhitelist whitelist = new StaticProxyInstanceWhitelist ( build , "templates-instances.whitelist" ) ; result = GroovySandbox . runInSandbox ( new Callable < String > ( ) { public String call ( ) throws Exception { return tmplR . make ( binding ) . toString ( ) ; } } , new ProxyWhitelist ( Whitelist . all ( ) , new TaskListenerInstanceWhitelist ( listener ) , new PrintStreamInstanceWhitelist ( listener . getLogger ( ) ) , new EmailExtScriptTokenMacroWhitelist ( ) , whitelist ) ) ; } } catch ( Exception e ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; e . printStackTrace ( pw ) ; result = "Exception raised during template rendering: " + e . getMessage ( ) + "\n\n" + sw . toString ( ) ; } return result ; }
|
Renders the template using a SimpleTemplateEngine
|
35,399
|
private String executeScript ( Run < ? , ? > build , FilePath workspace , TaskListener listener , InputStream scriptStream ) throws IOException { String result = "" ; Map binding = new HashMap < > ( ) ; ExtendedEmailPublisherDescriptor descriptor = Jenkins . getActiveInstance ( ) . getDescriptorByType ( ExtendedEmailPublisherDescriptor . class ) ; Item parent = build . getParent ( ) ; binding . put ( "build" , build ) ; binding . put ( "it" , new ScriptContentBuildWrapper ( build ) ) ; binding . put ( "project" , parent ) ; binding . put ( "rooturl" , descriptor . getHudsonUrl ( ) ) ; binding . put ( "workspace" , workspace ) ; PrintStream logger = listener . getLogger ( ) ; binding . put ( "logger" , logger ) ; String scriptContent = IOUtils . toString ( scriptStream , descriptor . getCharset ( ) ) ; if ( scriptStream instanceof UserProvidedContentInputStream ) { ScriptApproval . get ( ) . configuring ( scriptContent , GroovyLanguage . get ( ) , ApprovalContext . create ( ) . withItem ( parent ) ) ; } if ( scriptStream instanceof UserProvidedContentInputStream && ! AbstractEvalContent . isApprovedScript ( scriptContent , GroovyLanguage . get ( ) ) ) { GroovyShell shell = createEngine ( descriptor , binding , true ) ; Object res = GroovySandbox . run ( shell , scriptContent , new ProxyWhitelist ( Whitelist . all ( ) , new PrintStreamInstanceWhitelist ( logger ) , new EmailExtScriptTokenMacroWhitelist ( ) ) ) ; if ( res != null ) { result = res . toString ( ) ; } } else { if ( scriptStream instanceof UserProvidedContentInputStream ) { ScriptApproval . get ( ) . using ( scriptContent , GroovyLanguage . get ( ) ) ; } GroovyShell shell = createEngine ( descriptor , binding , false ) ; Script script = shell . parse ( scriptContent ) ; Object res = script . run ( ) ; if ( res != null ) { result = res . toString ( ) ; } } return result ; }
|
Executes a script and returns the last value as a String
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.