Skip to content

Commit

Permalink
Merge pull request #2 from msfidelis/refactor
Browse files Browse the repository at this point in the history
Refactor
  • Loading branch information
msfidelis authored Sep 7, 2022
2 parents 6576964 + bf239c6 commit c96c8e4
Show file tree
Hide file tree
Showing 16 changed files with 623 additions and 254 deletions.
7 changes: 0 additions & 7 deletions bmr-grpc-service/pkg/tracer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,13 @@ import (

"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/jaeger"
stdout "go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.7.0"
)

func InitTracer() *sdktrace.TracerProvider {
exporter, err := stdout.New(stdout.WithPrettyPrint())
if err != nil {
fmt.Println("Failed to init tracer", err)
}

exp, err := jaeger.New(
jaeger.WithCollectorEndpoint(
jaeger.WithEndpoint(
Expand All @@ -34,7 +28,6 @@ func InitTracer() *sdktrace.TracerProvider {
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp),
sdktrace.WithSampler(sdktrace.AlwaysSample()),
sdktrace.WithBatcher(exporter),
sdktrace.WithResource(resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceNameKey.String("bmr-grpc-service"),
Expand Down
7 changes: 0 additions & 7 deletions calories-grpc-service/pkg/tracer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,13 @@ import (

"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/jaeger"
stdout "go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.7.0"
)

func InitTracer() *sdktrace.TracerProvider {
exporter, err := stdout.New(stdout.WithPrettyPrint())
if err != nil {
fmt.Println("Failed to init tracer", err)
}

exp, err := jaeger.New(
jaeger.WithCollectorEndpoint(
jaeger.WithEndpoint(
Expand All @@ -33,7 +27,6 @@ func InitTracer() *sdktrace.TracerProvider {
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp),
sdktrace.WithSampler(sdktrace.AlwaysSample()),
sdktrace.WithBatcher(exporter),
sdktrace.WithResource(resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceNameKey.String("calories-grpc-service"),
Expand Down
153 changes: 30 additions & 123 deletions health-api/controllers/calculator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package calculator

import (
"net/http"
"os"

"github.com/gin-gonic/gin"
"github.com/msfidelis/health-api/pkg/logger"
Expand All @@ -11,9 +10,7 @@ import (
"github.com/msfidelis/health-api/pkg/services/recommendations"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"

"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"go.opentelemetry.io/otel/attribute"
)

Expand Down Expand Up @@ -107,169 +104,81 @@ func Post(c *gin.Context) {

// BMR
ctxBMR, spanBMR := tr.Start(c.Request.Context(), "BMR Service Call")

bmrEndpoint := os.Getenv("BMR_SERVICE_ENDPOINT")

log.Info().
Str("Service", "bmr").
Str("BMR_SERVICE_ENDPOINT", bmrEndpoint).
Msg("Creating remote connection with gRPC Endpoint for BMR Service")
defer spanBMR.End()

spanBMR.SetAttributes(
attribute.String("Service", "bmr"),
attribute.String("BMR_SERVICE_ENDPOINT", bmrEndpoint),
attribute.String("Service", "BMR"),
)

var conn *grpc.ClientConn
conn, err := grpc.Dial(
bmrEndpoint,
grpc.WithInsecure(),
grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor()),
grpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor()),
)
resBMR, err := bmr.Call(ctxBMR, request.Gender, request.Weight, request.Height, request.ActivityIntensity, tr)

if err != nil {
log.Error().
Str("Service", "bmr").
Str("Error", err.Error()).
Msg("Failed to create gRPC Connection with BMR Service")
Msg("Error to consume gRPC Service")

spanBMR.SetAttributes(
attribute.String("Service", "bmr"),
attribute.String("Error", err.Error()),
attribute.String("Message", "Failed to create gRPC Connection with BMR Service"),
)
}
defer conn.Close()

bmrClient := bmr.NewBMRServiceClient(conn)

spanBMR.SetAttributes(
attribute.String("grpc.request.Gender", request.Gender),
attribute.Float64("grpc.request.Weight", request.Weight),
attribute.Float64("grpc.request.Height", request.Height),
attribute.String("grpc.request.ActivityIntensity", request.ActivityIntensity),
)

resBMR, err := bmrClient.SayHello(ctxBMR, &bmr.Message{
Gender: request.Gender,
Weight: request.Weight,
Height: request.Height,
Activity: request.ActivityIntensity,
})

spanBMR.SetAttributes(
attribute.Float64("grpc.response.BMR", resBMR.Bmr),
attribute.Float64("grpc.response.Necessity", resBMR.Necessity),
attribute.String("grpc.response.Unity", "kcal"),
)

defer spanBMR.End()
c.JSON(http.StatusInternalServerError, gin.H{
"message": "Error to create gRPC Connection with BMR Service",
"error": err.Error(),
})
}

// IMC
ctxIMC, spanIMC := tr.Start(c.Request.Context(), "IMC Service Call")
imcEndpoint := os.Getenv("IMC_SERVICE_ENDPOINT")
defer spanIMC.End()

log.Info().
Str("Service", "imc").
Str("IMC_SERVICE_ENDPOINT", imcEndpoint).
Msg("Creating remote connection with gRPC Endpoint for IMC Service")

spanIMC.SetAttributes(
attribute.String("Service", "imc"),
attribute.String("IMC_SERVICE_ENDPOINT", imcEndpoint),
)

var connIMC *grpc.ClientConn
connIMC, errIMC := grpc.Dial(
imcEndpoint,
grpc.WithInsecure(),
grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor()),
grpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor()),
)
resIMC, err := imc.Call(ctxIMC, request.Weight, request.Height, tr)

if errIMC != nil {
if err != nil {
log.Error().
Str("Service", "imc").
Str("Error", err.Error()).
Msg("Failed to create gRPC Connection with IMC Service")
Msg("Error to consume gRPC Service")

spanIMC.SetAttributes(
attribute.String("Service", "imc"),
spanBMR.SetAttributes(
attribute.String("Error", err.Error()),
attribute.String("Message", "Failed to create gRPC Connection with IMC Service"),
)
}
defer connIMC.Close()

imcClient := imc.NewIMCServiceClient(connIMC)

spanIMC.SetAttributes(
attribute.Float64("grpc.request.Weight", request.Weight),
attribute.Float64("grpc.request.Height", request.Height),
)

resIMC, err := imcClient.SayHello(ctxIMC, &imc.Message{
Weight: request.Weight,
Height: request.Height,
})

spanIMC.SetAttributes(
attribute.Float64("grpc.response.Imc", resIMC.Imc),
attribute.String("grpc.response.Class", resIMC.Class),
)

defer spanIMC.End()
c.JSON(http.StatusInternalServerError, gin.H{
"message": "Error to create gRPC Connection with IMC Service",
"error": err.Error(),
})
}

// Recommendations
ctxRecommendations, spanRecommendations := tr.Start(c.Request.Context(), "Recommendations Service Call")
recommendationsEndpoint := os.Getenv("RECOMMENDATIONS_SERVICE_ENDPOINT")

log.Info().
Str("Service", "recommendations").
Str("RECOMMENDATIONS_SERVICE_ENDPOINT", recommendationsEndpoint).
Msg("Creating remote connection with gRPC Endpoint for Recommendation Service")

spanRecommendations.SetAttributes(
attribute.String("Service", "recommendations"),
attribute.String("RECOMMENDATIONS_SERVICE_ENDPOINT", recommendationsEndpoint),
)
defer spanRecommendations.End()

var connRecommendations *grpc.ClientConn
connRecommendations, errRecommendations := grpc.Dial(
recommendationsEndpoint,
grpc.WithInsecure(),
grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor()),
grpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor()),
)
resRecommendations, err := recommendations.Call(ctxRecommendations, request.Weight, request.Height, resBMR.Necessity, tr)

if errRecommendations != nil {
if err != nil {
log.Error().
Str("Service", "recommendations").
Str("Service", "imc").
Str("Error", err.Error()).
Msg("Failed to create gRPC Connection with Recommendations Service")
Msg("Error to consume gRPC Service")

spanRecommendations.SetAttributes(
attribute.String("Service", "recommendations"),
spanBMR.SetAttributes(
attribute.String("Error", err.Error()),
attribute.String("Message", "Failed to create gRPC Connection with Recommendations Service"),
)
}
defer connRecommendations.Close()

recommendationsClient := recommendations.NewRecomendationsServiceClient(connRecommendations)

spanRecommendations.SetAttributes(
attribute.String("grpc.request.Gender", request.Gender),
attribute.Float64("grpc.request.Weight", request.Weight),
attribute.Float64("grpc.request.Calories", resBMR.Necessity),
)

resRecommendations, err := recommendationsClient.SayHello(ctxRecommendations, &recommendations.Message{
Weight: request.Weight,
Height: request.Height,
Calories: resBMR.Necessity,
})
c.JSON(http.StatusInternalServerError, gin.H{
"message": "Error to create gRPC Connection with IMC Service",
"error": err.Error(),
})
}

spanRecommendations.SetAttributes(
attribute.Int64("grpc.response.Protein", resRecommendations.ProteinsValue),
Expand All @@ -279,8 +188,6 @@ func Post(c *gin.Context) {
attribute.Float64("grpc.response.Calories.Loss", resRecommendations.CaloriesToLoss),
)

defer spanRecommendations.End()

_, spanResponse := tr.Start(c.Request.Context(), "HTTP Response")

// BMR Response
Expand Down
4 changes: 0 additions & 4 deletions health-api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,6 @@ import (
// Jaeger
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"

// "go.opentelemetry.io/otel/attribute"

// oteltrace "go.opentelemetry.io/otel/trace"

swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"

Expand Down
98 changes: 97 additions & 1 deletion health-api/pkg/services/bmr/main.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,101 @@
package bmr

func Call() {
import (
context "context"
"fmt"
"os"
"time"

"github.com/msfidelis/health-api/pkg/logger"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
)

func Call(ctx context.Context, gender string, weight float64, height float64, activity_intensity string, tracer trace.Tracer) (*Response, error) {

var backoffSchedule = []time.Duration{
1 * time.Second,
3 * time.Second,
10 * time.Second,
}

var resGrpc *Response
var err error

log := logger.Instance()
bmrEndpoint := os.Getenv("BMR_SERVICE_ENDPOINT")

for i, backoff := range backoffSchedule {

ctxCall, spanCall := tracer.Start(ctx, fmt.Sprintf("BMR call attempt %v", i+1))
defer spanCall.End()

var conn *grpc.ClientConn
conn, err = grpc.Dial(
bmrEndpoint,
grpc.WithInsecure(),
grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor()),
grpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor()),
)

if err != nil {
log.Error().
Str("Service", "bmr").
Str("Error", err.Error()).
Msg("Failed to create gRPC Connection with BMR Service")

spanCall.SetAttributes(
attribute.String("Service", "BMR"),
attribute.String("gRPC connection error", err.Error()),
)
}
defer conn.Close()

grpcClient := NewBMRServiceClient(conn)

resGrpc, err = grpcClient.SayHello(ctxCall, &Message{
Gender: gender,
Weight: weight,
Height: height,
Activity: activity_intensity,
})

if err != nil {
log.Error().
Str("Service", "bmr").
Str("Error", err.Error()).
Msg("Failed to communicate with BMR Service")

spanCall.SetAttributes(
attribute.String("Service", "BMR"),
attribute.String("gRPC call error", err.Error()),
)
}

if err == nil {
break
}

log.Info().
Str("Service", "bmr").
Int("Retry", i+1).
Str("Backoff", fmt.Sprintf("%s", backoff)).
Msg("Failed to communicate with BMR Service")

spanCall.SetAttributes(
attribute.String("Service", "BMR"),
attribute.Int("Attempts", i+1),
)

time.Sleep(backoff)
}

if err != nil {
return nil, err
}

return resGrpc, nil

}
Loading

0 comments on commit c96c8e4

Please sign in to comment.