Copyright 2017, OpenCensus Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

package zpages

import (
	
	
	
	
	
	
	
	
	

	
	
)

spanNameQueryField is the header for span name.
spanTypeQueryField is the header for type (running = 0, latency = 1, error = 2) to display.
spanSubtypeQueryField is the header for sub-type: * for latency based samples [0, 8] representing the latency buckets, where 0 is the first one; * for error based samples, 0 means all, otherwise the error code;
maxTraceMessageLength is the maximum length of a message in tracez output.
	maxTraceMessageLength = 1024
)

var (
	defaultLatencies = [...]time.Duration{
		10 * time.Microsecond,
		100 * time.Microsecond,
		time.Millisecond,
		10 * time.Millisecond,
		100 * time.Millisecond,
		time.Second,
		10 * time.Second,
		100 * time.Second,
	}
	canonicalCodes = [...]string{
		"OK",
		"CANCELLED",
		"UNKNOWN",
		"INVALID_ARGUMENT",
		"DEADLINE_EXCEEDED",
		"NOT_FOUND",
		"ALREADY_EXISTS",
		"PERMISSION_DENIED",
		"RESOURCE_EXHAUSTED",
		"FAILED_PRECONDITION",
		"ABORTED",
		"OUT_OF_RANGE",
		"UNIMPLEMENTED",
		"INTERNAL",
		"UNAVAILABLE",
		"DATA_LOSS",
		"UNAUTHENTICATED",
	}
)

func ( int32) string {
	if  < 0 || int() >= len(canonicalCodes) {
		return "error code " + strconv.FormatInt(int64(), 10)
	}
	return canonicalCodes[]
}

func ( http.ResponseWriter,  *http.Request) {
	.ParseForm()
	.Header().Set("Content-Type", "text/html; charset=utf-8")
	 := .Form.Get(spanNameQueryField)
	,  := strconv.Atoi(.Form.Get(spanTypeQueryField))
	,  := strconv.Atoi(.Form.Get(spanSubtypeQueryField))
	WriteHTMLTracezPage(, , , )
}
WriteHTMLTracezPage writes an HTML document to w containing locally-sampled trace spans.
func ( io.Writer,  string, ,  int) {
	if  := headerTemplate.Execute(, headerData{Title: "Trace Spans"});  != nil {
		log.Printf("zpages: executing template: %v", )
	}
	WriteHTMLTracezSummary()
	WriteHTMLTracezSpans(, , , )
	if  := footerTemplate.Execute(, nil);  != nil {
		log.Printf("zpages: executing template: %v", )
	}
}
WriteHTMLTracezSummary writes HTML to w containing a summary of locally-sampled trace spans. It includes neither a header nor footer, so you can embed this data in other pages.
func ( io.Writer) {
	if  := summaryTableTemplate.Execute(, getSummaryPageData());  != nil {
		log.Printf("zpages: executing template: %v", )
	}
}
WriteHTMLTracezSpans writes HTML to w containing locally-sampled trace spans. It includes neither a header nor footer, so you can embed this data in other pages.
func ( io.Writer,  string, ,  int) {
	if  == "" {
		return
	}
	if  := tracesTableTemplate.Execute(, traceDataFromSpans(, traceSpans(, , )));  != nil {
		log.Printf("zpages: executing template: %v", )
	}
}
WriteTextTracezSpans writes formatted text to w containing locally-sampled trace spans.
func ( io.Writer,  string, ,  int) {
	 := traceSpans(, , )
	 := traceDataFromSpans(, )
	writeTextTraces(, )
}
WriteTextTracezSummary writes formatted text to w containing a summary of locally-sampled trace spans.
func ( io.Writer) {
	.Write([]byte("Locally sampled spans summary\n\n"))

	 := getSummaryPageData()
	if len(.Rows) == 0 {
		return
	}

	 := tabwriter.NewWriter(, 8, 8, 1, ' ', 0)

	for ,  := range .Header {
		if  != 0 {
			.Write([]byte("\t"))
		}
		.Write([]byte())
	}
	.Write([]byte("\n"))

	 := func( int) {
		if  == 0 {
			.Write([]byte(".\t"))
			return
		}
		fmt.Fprintf(, "%d\t", )
	}
	for ,  := range .Rows {
		.Write([]byte(.Name))
		.Write([]byte("\t"))
		(.Active)
		for ,  := range .Latency {
			()
		}
		(.Errors)
		.Write([]byte("\n"))
	}
	.Flush()
}
traceData contains data for the trace data template.
type traceData struct {
	Name string
	Num  int
	Rows []traceRow
}

type traceRow struct {
	Fields [3]string
	trace.SpanContext
	ParentSpanID trace.SpanID
}

type events []interface{}

func ( events) () int { return len() }
func ( events) (,  int) bool {
	var  time.Time
	switch x := [].(type) {
	case *trace.Annotation:
		 = .Time
	case *trace.MessageEvent:
		 = .Time
	}
	switch x := [].(type) {
	case *trace.Annotation:
		return .Before(.Time)
	case *trace.MessageEvent:
		return .Before(.Time)
	}
	return false
}

func ( events) (,  int) { [], [] = [], [] }

func ( *trace.SpanData) []traceRow {
	 := .StartTime

	, ,  := .Date()
	 := func( time.Time) string {
		return .Format("2006/01/02-15:04:05") + fmt.Sprintf(".%06d", .Nanosecond()/1000)
	}
	 := func( time.Time) string {
		, ,  := .Date()
		if  ==  &&  ==  &&  ==  {
			return .Format("           15:04:05") + fmt.Sprintf(".%06d", .Nanosecond()/1000)
		}
		, ,  = , , 
		return ()
	}

	 := 
	 := func( time.Time) string {
		 := .Sub()
		 = 
There are five cases for duration printing: -1234567890s -1234.123456 .123456 12345.123456 12345678901s
		switch {
		case  < -9999999999:
			return fmt.Sprintf("%11ds", /1e6)
		case  < 0:
			 :=  / 1e6
			 -=  * 1e6
			return fmt.Sprintf("%5d.%06d", , -)
		case  < 1e6:
			return fmt.Sprintf("     .%6d", )
		case  <= 99999999999:
			 :=  / 1e6
			 -=  * 1e6
			return fmt.Sprintf("%5d.%06d", , )
		default:
			return fmt.Sprintf("%11ds", /1e6)
		}
	}

	 := traceRow{Fields: [3]string{(), "", ""}, SpanContext: .SpanContext, ParentSpanID: .ParentSpanID}
	if .EndTime.IsZero() {
		.Fields[1] = "            "
	} else {
		.Fields[1] = (.EndTime)
		 = 
	}
	 := []traceRow{}

	 := func( map[string]interface{}) string {
		if len() == 0 {
			return ""
		}
		var  []string
		for  := range  {
			 = append(, )
		}
		sort.Strings()
		var  []string
		for ,  := range  {
			 := []
			switch .(type) {
			case string:
				 = append(, fmt.Sprintf("%s=%q", , ))
			default:
				 = append(, fmt.Sprintf("%s=%v", , ))
			}
		}
		return "Attributes:{" + strings.Join(, ", ") + "}"
	}

	if .Status != (trace.Status{}) {
		 := fmt.Sprintf("Status{canonicalCode=%s, description=%q}",
			canonicalCodeString(.Status.Code), .Status.Message)
		 = append(, traceRow{Fields: [3]string{"", "", }})
	}

	if len(.Attributes) != 0 {
		 = append(, traceRow{Fields: [3]string{"", "", (.Attributes)}})
	}

	var  events
	for  := range .Annotations {
		 = append(, &.Annotations[])
	}
	for  := range .MessageEvents {
		 = append(, &.MessageEvents[])
	}
	sort.Sort()
	for ,  := range  {
		switch e := .(type) {
		case *trace.Annotation:
			 := .Message
			if len(.Attributes) != 0 {
				 =  + "  " + (.Attributes)
			}
			 := traceRow{Fields: [3]string{
				(.Time),
				(.Time),
				,
			}}
			 = append(, )
		case *trace.MessageEvent:
			 := traceRow{Fields: [3]string{(.Time), (.Time)}}
			switch .EventType {
			case trace.MessageEventTypeSent:
				.Fields[2] = fmt.Sprintf("sent message [%d bytes, %d compressed bytes]", .UncompressedByteSize, .CompressedByteSize)
			case trace.MessageEventTypeRecv:
				.Fields[2] = fmt.Sprintf("received message [%d bytes, %d compressed bytes]", .UncompressedByteSize, .CompressedByteSize)
			}
			 = append(, )
		}
	}
	for  := range  {
		if len([].Fields[2]) > maxTraceMessageLength {
			[].Fields[2] = [].Fields[2][:maxTraceMessageLength]
		}
	}
	return 
}

func ( string, ,  int) []*trace.SpanData {
	 := internal.Trace.(interface {
		( string) []*trace.SpanData
		( string,  int32) []*trace.SpanData
		( string, ,  time.Duration) []*trace.SpanData
	})
	var  []*trace.SpanData
	switch  {
	case 0: // active
		 = .()
	case 1: // latency
		var ,  time.Duration
		 := len(defaultLatencies)
		if  == 0 {
			 = defaultLatencies[0]
		} else if  ==  {
			,  = defaultLatencies[-1], (1<<63)-1
		} else if 0 <  &&  <  {
			,  = defaultLatencies[-1], defaultLatencies[]
		}
		 = .(, , )
	case 2: // error
		 = .(, 0)
	}
	return 
}

func ( string,  []*trace.SpanData) traceData {
	 := traceData{
		Name: ,
		Num:  len(),
	}
	for ,  := range  {
		.Rows = append(.Rows, traceRows()...)
	}
	return 
}

func ( io.Writer,  traceData) {
	 := tabwriter.NewWriter(, 1, 8, 1, ' ', 0)
	fmt.Fprint(, "When\tElapsed(s)\tType\n")
	for ,  := range .Rows {
		.Write([]byte(.Fields[0]))
		.Write([]byte("\t"))
		.Write([]byte(.Fields[1]))
		.Write([]byte("\t"))
		.Write([]byte(.Fields[2]))
		if  := .SpanContext;  != (trace.SpanContext{}) {
			fmt.Fprintf(, "trace_id: %s span_id: %s", .TraceID, .SpanID)
			if .ParentSpanID != (trace.SpanID{}) {
				fmt.Fprintf(, " parent_span_id: %s", .ParentSpanID)
			}
		}
		.Write([]byte("\n"))
	}
	.Flush()
}

type summaryPageData struct {
	Header             []string
	LatencyBucketNames []string
	Links              bool
	TracesEndpoint     string
	Rows               []summaryPageRow
}

type summaryPageRow struct {
	Name    string
	Active  int
	Latency []int
	Errors  int
}

func () summaryPageData {
	 := summaryPageData{
		Links:          true,
		TracesEndpoint: "tracez",
	}
	 := internal.Trace.(interface {
		() map[string]internal.PerMethodSummary
	})
	for ,  := range .() {
		if len(.Header) == 0 {
			.Header = []string{"Name", "Active"}
			for ,  := range .LatencyBuckets {
				 := .MinLatency
				 := fmt.Sprintf(">%v", )
				if  == 100*time.Second {
					 = ">100s"
				}
				.Header = append(.Header, )
				.LatencyBucketNames = append(.LatencyBucketNames, )
			}
			.Header = append(.Header, "Errors")
		}
		 := summaryPageRow{Name: , Active: .Active}
		for ,  := range .LatencyBuckets {
			.Latency = append(.Latency, .Size)
		}
		for ,  := range .ErrorBuckets {
			.Errors += .Size
		}
		.Rows = append(.Rows, )
	}
	sort.Slice(.Rows, func(,  int) bool {
		return .Rows[].Name < .Rows[].Name
	})
	return