// StartSpan starts a new span with a given parent context, operation name, tags and
// optional parent span. It returns a context with the created span.
186492
func StartSpan(
	parentCtx context.Context,
	opName string,
	tags opentracing.Tags,
	reference ...opentracing.SpanContext,
) context.Context {
	var ref opentracing.SpanContext
	if len(reference) > 0 {
		ref = reference[0]
	}
	span := opentracing.StartSpan(opName, opentracing.ChildOf(ref), tags)
	return opentracing.ContextWithSpan(parentCtx, span)
}
208984
func (t *Tracing) StartSpan(operationName string, opts ...opentracing.StartSpanOption) opentracing.Span {
	return t.tracer.StartSpan(operationName, opts...)
}
1046935
func Parent(sc model.SpanContext) SpanOption {
	return func(t *Tracer, s *spanImpl) {
		if sc.Err != nil {
			// encountered an extraction error
			switch t.extractFailurePolicy {
			case ExtractFailurePolicyRestart:
			case ExtractFailurePolicyError:
				panic(s.SpanContext.Err)
			case ExtractFailurePolicyTagAndRestart:
				s.Tags["error.extract"] = sc.Err.Error()
			default:
				panic(ErrInvalidExtractFailurePolicy)
			}
			/* don't use provided SpanContext, but restart trace */
			return
		}
		s.SpanContext = sc
	}
}
444607
func (t *Tracer) StartSpan(name string, options ...SpanOption) Span {
	if atomic.LoadInt32(&t.noop) == 1 {
		return &noopSpan{}
	}
	s := &spanImpl{
		SpanModel: model.SpanModel{
			Kind:          model.Undetermined,
			Name:          name,
			LocalEndpoint: t.localEndpoint,
			Annotations:   make([]model.Annotation, 0),
			Tags:          make(map[string]string),
		},
		flushOnFinish: true,
		tracer:        t,
	}

	// add default tracer tags to span
	for k, v := range t.defaultTags {
		s.Tag(k, v)
	}

	// handle provided functional options
	for _, option := range options {
		option(t, s)
	}

	if s.TraceID.Empty() {
		// create root span
		s.SpanContext.TraceID = t.generate.TraceID()
		s.SpanContext.ID = t.generate.SpanID(s.SpanContext.TraceID)
	} else {
		// valid parent context found
		if t.sharedSpans && s.Kind == model.Server {
			// join span
			s.Shared = true
		} else {
			// regular child span
			parentID := s.SpanContext.ID
			s.SpanContext.ParentID = &parentID
			s.SpanContext.ID = t.generate.SpanID(model.TraceID{})
		}
	}

	if !s.SpanContext.Debug && s.Sampled == nil {
		// deferred sampled context found, invoke sampler
		sampled := t.sampler(s.SpanContext.TraceID.Low)
		s.SpanContext.Sampled = &sampled
		if sampled {
			s.mustCollect = 1
		}
	} else {
		if s.SpanContext.Debug || *s.Sampled {
			s.mustCollect = 1
		}
	}

	if t.unsampledNoop && s.mustCollect == 0 {
		// trace not being sampled and noop requested
		return &noopSpan{
			SpanContext: s.SpanContext,
		}
	}

	// add start time
	if s.Timestamp.IsZero() {
		s.Timestamp = time.Now()
	}

	return s
}
143834
func (EventReceiver) SpanStart(ctx context.Context, eventName, query string) context.Context {
	span, ctx := ot.StartSpanFromContext(ctx, eventName)
	otext.DBStatement.Set(span, query)
	otext.DBType.Set(span, "sql")
	return ctx
}
800859
func (ns *NamedStopwatch) Start(name string) {
	if ns == nil {
		return // if we're not using stopwatches we just do nothing
	}
	ns.Lock()
	defer ns.Unlock()

	ns.start(name)
}
831279
func (c *Counter) AddSpans(ctx context.Context, spans []*trace.Span, next trace.Sink) error {
	atomic.AddInt64(&c.TotalSpans, int64(len(spans)))
	atomic.AddInt64(&c.TotalProcessCalls, 1)
	atomic.AddInt64(&c.CallsInFlight, 1)
	start := time.Now()
	err := next.AddSpans(ctx, spans)
	atomic.AddInt64(&c.TotalProcessTimeNs, time.Since(start).Nanoseconds())
	atomic.AddInt64(&c.CallsInFlight, -1)
	if err != nil && spanfilter.IsInvalid(err) {
		atomic.AddInt64(&c.TotalProcessErrors, 1)
		atomic.AddInt64(&c.ProcessErrorSpans, int64(len(spans)))
		c.logErrMsg(ctx, err, "Unable to process spans")
	}
	return err
}
40560
func FinishSpans() {
	store.spans.Range(func(_, v interface{}) bool {
		v.(opentracing.Span).Finish()
		return true
	})
}
297282
func NewSpanContext(traceID TraceID, spanID, parentID SpanID, sampled bool, baggage map[string]string) SpanContext {
	flags := byte(0)
	if sampled {
		flags = flagSampled
	}
	return SpanContext{
		traceID:  traceID,
		spanID:   spanID,
		parentID: parentID,
		flags:    flags,
		baggage:  baggage}
}
209105
func NewSpan(ctx context.Context, tracer opentracing.Tracer, name string) (context.Context, opentracing.Span) {
	span := opentracing.SpanFromContext(ctx)
	spanCtx := span.Context()
	span = tracer.StartSpan(name, opentracing.ChildOf(spanCtx))
	ctx = opentracing.ContextWithSpan(ctx, span)
	return ctx, span
}
1323160
func (ts *traceState) CreateSpan(desc string) (report ReportFunc) {
	ts.mu.Lock()
	defer ts.mu.Unlock()

	index := len(ts.spans)
	ts.spans = append(ts.spans, &span{desc: desc, start: time.Now()})

	report = func(err error) { ts.report(index, err) }
	return
}
489577
func StartSpanFromHeaders(headers tasks.Headers, operationName string) opentracing.Span {
	// Try to extract the span context from the carrier.
	spanContext, err := opentracing.GlobalTracer().Extract(opentracing.TextMap, headers)

	// Create a new span from the span context if found or start a new trace with the function name.
	// For clarity add the machinery component tag.
	span := opentracing.StartSpan(
		operationName,
		ConsumerOption(spanContext),
		MachineryTag,
	)

	// Log any error but don't fail
	if err != nil {
		span.LogFields(opentracing_log.Error(err))
	}

	return span
}
22351
func (t *Trace) contextAsParent() *spanContext {

	c := &spanContext{}
	c.Init()
	c.baggageItems["traceid"] = strconv.FormatInt(t.TraceID, 10)
	c.baggageItems["parentid"] = strconv.FormatInt(t.SpanID, 10)
	c.baggageItems[ResourceKey] = t.Resource
	return c
}
317800
func (t *Tracer) StartSpan(
	operationName string,
	options ...opentracing.StartSpanOption,
) opentracing.Span {
	sso := opentracing.StartSpanOptions{}
	for _, o := range options {
		o.Apply(&sso)
	}
	return t.startSpanWithOptions(operationName, sso)
}
1106188
func (n *Node) start(nsMap map[string]client.MessageSet) error {
	n.l.Infoln("adaptor Starting...")

	s, err := n.c.Connect()
	if err != nil {
		return err
	}
	if closer, ok := s.(client.Closer); ok {
		defer func() {
			n.l.Debugln("closing session...")
			closer.Close()
			n.l.Debugln("session closed...")
		}()
	}
	readFunc := n.reader.Read(nsMap, func(check string) bool { return n.nsFilter.MatchString(check) })
	msgChan, err := readFunc(s, n.done)
	if err != nil {
		return err
	}
	var logOffset int64
	for msg := range msgChan {
		if n.clog != nil {
			d, _ := mejson.Marshal(msg.Msg.Data().AsMap())
			b, _ := json.Marshal(d)
			o, err := n.clog.Append(
				commitlog.NewLogFromEntry(
					commitlog.LogEntry{
						Key:       []byte(msg.Msg.Namespace()),
						Mode:      msg.Mode,
						Op:        msg.Msg.OP(),
						Timestamp: uint64(msg.Timestamp),
						Value:     b,
					}))
			if err != nil {
				return err
			}
			logOffset = o
			n.l.With("offset", logOffset).Debugln("attaching offset to message")
		}
		n.pipe.Send(msg.Msg, offset.Offset{
			Namespace: msg.Msg.Namespace(),
			LogOffset: uint64(logOffset),
			Timestamp: time.Now().Unix(),
		})
	}

	n.l.Infoln("adaptor Start finished...")
	return nil
}
737610
func (f *ItemFlagger) AddSpans(ctx context.Context, spans []*trace.Span, next trace.Sink) error {
	return next.AddSpans(ctx, spans)
}
77873
func (r *LoggableSpanRecorder) RecordSpan(span RawSpan) {
	// short circuit if theres nothing to write to
	if !writer.WriterGroup.Active() {
		return
	}

	sl := make([]SpanLog, len(span.Logs))
	for i := range span.Logs {
		sl[i].Timestamp = span.Logs[i].Timestamp
		sf := make([]SpanField, len(span.Logs[i].Fields))
		sl[i].Field = sf
		for j := range span.Logs[i].Fields {
			sf[j].Key = span.Logs[i].Fields[j].Key()
			sf[j].Value = fmt.Sprint(span.Logs[i].Fields[j].Value())
		}
	}

	tags := make(map[string]interface{}, len(span.Tags))
	for k, v := range span.Tags {
		switch vt := v.(type) {
		case bool, string, int, int8, int16, int32, int64, uint, uint8, uint16, uint64:
			tags[k] = v
		case []byte:
			base64.StdEncoding.EncodeToString(vt)
		default:
			tags[k] = fmt.Sprint(v)
		}
	}

	spanlog := &LoggableSpan{
		TraceID:      span.Context.TraceID,
		SpanID:       span.Context.SpanID,
		ParentSpanID: span.ParentSpanID,
		Operation:    span.Operation,
		Start:        span.Start,
		Duration:     span.Duration,
		Tags:         tags,
		Logs:         sl,
	}

	var buf bytes.Buffer
	encoder := json.NewEncoder(&buf)
	encoder.SetEscapeHTML(false)
	err := encoder.Encode(spanlog)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR FORMATTING SPAN ENTRY: %s\n", err)
		return
	}

	writer.WriterGroup.Write(buf.Bytes())
}