0

This question is directly related to following questions. None of them solved this issue :

Distributed tracing with golang http.PostForm

POST data faild using http.NewRequest

How to pass opentracing data using json

SpanContext not found in Extract carrier in microservice

This is my current cinfigurations.

In First microservice (API-Gateway) I have following codes :

func startTracing(service string) (opentracing.Tracer, io.Closer) {
    cfg := &config.Configuration{
        Sampler: &config.SamplerConfig{
            Type:  "const",
            Param: 1,
        },
        Reporter: &config.ReporterConfig{
            LogSpans: true,
        },
    }
    tracer, closer, err := cfg.New(service, config.Logger(jaeger.StdLogger))
    if err != nil {
        panic(fmt.Sprintf("ERROR: cannot init Jaeger: %v\n", err))
    }
    return tracer, closer
}

func main() {

    http.HandleFunc("/getemail", validatemail)
    http.ListenAndServe(":7070", nil)
}

func validatemail(res http.ResponseWriter, req *http.Request) {

    gatewayTracer, gatewayTracerClose := startTracing("Validate Email")

    validateEmailSpan := gatewayTracer.StartSpan("Email address checking")

    // Check method
    if req.Method != "POST" {
        log.Panic("Email form data is not Post")

    }

    email := req.FormValue("email") 

    validEmail := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`) // regex to validate email address

    if validEmail.MatchString(email) {
        httpClient := http.Client{}

        form := url.Values{}
        form.Set("email", email)

        userserviceUrl := "http://user:7071/checkemail"

        checkEmailReq, err := http.NewRequest("POST", userserviceUrl, strings.NewReader(form.Encode()))
        if err != nil {
            log.Println(err)
        }

        ext.SpanKindRPCClient.Set(validateEmailSpan)
        ext.HTTPUrl.Set(validateEmailSpan, userserviceUrl)
        ext.HTTPMethod.Set(validateEmailSpan, "POST")

        validateEmailSpan.Tracer().Inject(
            validateEmailSpan.Context(),
            opentracing.HTTPHeaders,
            opentracing.HTTPHeadersCarrier(req.Header),
        )
        req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

        resp, err := httpClient.Do(checkEmailReq)

        if err != nil {
            log.Println("Couldnt verify email address user service sends an error : ", err)
        }
        defer resp.Body.Close()

    } else {
        log.Println("Wrong email address format")
    }

    defer gatewayTracerClose.Close()
    defer validateEmailSpan.Finish()
}

In my second micro service ( User Service)

func CheckEmail(res http.ResponseWriter, req *http.Request) {

    checkEmailTracer, checkemailtracerClose := startTracing("Registering Service")  // Same startTracing function as API-Gateway

    spanCtx, _ := checkEmailTracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))
    span := checkEmailTracer.StartSpan("format", ext.RPCServerOption(spanCtx))

    defer span.Finish()
    req.ParseForm()

    log.Println("Start from context :", spanCtx)

}

Here output from **Start from context ** : nil

What am I missing here? I am really new for opentracing. Here posted code is taken from opentracing-tutorial - yurishkur.

Sachith Muhandiram
  • 2,819
  • 10
  • 45
  • 94
  • 1
    comparing your code to the tutorial, there are two things I've noticed. First is that you declare `tracer` and `closer` in the handler (that means for each request), whereas in the tutorial it's declared in the `main` method. Second thing is that `ext.RPCServerOption(spanCtx)` should be used when creating span in the gateway, not your target service. – Emin Laletovic Nov 21 '19 at 15:54
  • @eminlala The problem was, I used handler, if I define `tracer/closer` in `main` how am I supposed to pass to `validatemail()` – Sachith Muhandiram Nov 21 '19 at 16:03
  • you could try defining a `Ctrl` struct with a `Tracer` property. In `main` create a `Ctrl` object and assign initialized tracer to it's `Tracer` property. Next, you can define `validatemail` as `func (ctrl *Ctrl) validateemail` and you will have the tracer available inside it. You can check this link: https://gobyexample.com/methods – Emin Laletovic Nov 21 '19 at 16:27
  • @eminlala Thanks, but now I have a problem with `Extract` from secondary service side. In sample, they have started a separate tracer there. – Sachith Muhandiram Nov 21 '19 at 17:01
  • Did you start a separate tracer instance there, because it should be started separately for each service? – Emin Laletovic Nov 22 '19 at 08:30
  • @eminlala yes, I have started a separate tracer as described. And tried to extract. – Sachith Muhandiram Nov 22 '19 at 12:00

0 Answers0