Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.DS_Store
**/.env
21 changes: 21 additions & 0 deletions learning-otel-go/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Configurações do servidor
PORT=8080
ENV=development

# Configurações do banco de dados
DB_HOST=localhost
DB_PORT=5432
DB_USER=admin
DB_PASS=admin123
DB_NAME=golearn_db

# Configurações de logs
LOG_LEVEL=info

# OpenTelemetry
# Para usar o OpenTelemetry Collector (recomendado):
OTEL_EXPORTER_OTLP_ENDPOINT=localhost:4317
# O OpenTelemetry Collector encaminhará traces para Jaeger e métricas para seus destinos configurados

# Segurança
API_KEY=sua_chave_secreta_aqui
28 changes: 28 additions & 0 deletions learning-otel-go/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
The MIT License (MIT)

Original Work
Copyright (c) 2016 Matthias Kadenbach
https://github.com/mattes/migrate

Modified Work
Copyright (c) 2018 Dale Hui
https://github.com/golang-migrate/migrate


Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
165 changes: 165 additions & 0 deletions learning-otel-go/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
# API de Tarefas com OpenTelemetry em Go

Este projeto é um exemplo prático de como implementar telemetria usando OpenTelemetry em uma aplicação Go. A aplicação consiste em uma API de gerenciamento de tarefas (todo list) com uma arquitetura em camadas e persistência em PostgreSQL.

## Estrutura do Projeto

O projeto segue uma arquitetura em camadas:

```
todo-api/
├── cmd/
│ └── migrate/ # Ferramenta para migrações do banco de dados
├── db/
│ └── migrations/ # Migrações SQL
├── internal/
│ ├── config/ # Configurações da aplicação
│ ├── core/
│ │ └── task/ # Domínio e regras de negócio
│ ├── handler/ # Handlers HTTP
│ ├── router/ # Configuração de rotas
│ └── telemetry/ # Configuração OpenTelemetry
└── main.go # Ponto de entrada da aplicação
```

## Tecnologias Utilizadas

### Bibliotecas Principais
- **gorilla/mux**: Router HTTP
- **lib/pq**: Driver PostgreSQL para Go
- **golang-migrate/migrate**: Migrações de banco de dados
- **google/uuid**: Geração de identificadores únicos
- **joho/godotenv**: Carregamento de variáveis de ambiente

### OpenTelemetry
- **go.opentelemetry.io/otel**: API principal do OpenTelemetry
- **go.opentelemetry.io/otel/trace**: API de traces
- **go.opentelemetry.io/otel/sdk**: Implementação do SDK
- **go.opentelemetry.io/otel/exporters/otlp**: Exportadores para OTLP
- **go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc**: Exportador gRPC

## Funcionalidades

A API implementa operações CRUD para tarefas:

- **GET /tasks**: Lista todas as tarefas
- **POST /task**: Cria uma nova tarefa
- **PUT /task/{id}**: Atualiza uma tarefa existente
- **DELETE /task/{id}**: Remove uma tarefa
- **GET /health**: Endpoint de verificação de saúde

## Implementação do OpenTelemetry

A telemetria foi implementada em várias camadas da aplicação:

### 1. Inicialização (internal/telemetry/tracing.go)

Configuração do provedor de traces, exportador OTLP e propagadores:

```go
func InitTracer(serviceName string, collectorURL string) (func(context.Context) error, error) {
// Configuração do tracer, exportador e propagadores
// ...
}
```

### 2. Middleware HTTP (internal/telemetry/middleware.go)

Instrumenta todas as requisições HTTP:

```go
func TracingMiddleware(next http.Handler) http.Handler {
// Criação de spans para cada requisição HTTP
// Propagação de contexto
// Captura de status code e headers
// ...
}
```

### 3. Camada de Serviço (internal/core/task/service.go)

Cada método de serviço cria spans próprios:

```go
func (s *TaskService) CreateTask(title, description string, concluded bool) error {
// Criação de span específico para esta operação
// Adição de atributos e metadados
// ...
}
```

### 4. Repositório (internal/core/task/pg_repository.go)

Operações de banco de dados também são rastreadas:

```go
func (r *PgTaskRepository) GetAll() ([]Task, error) {
// Span para operação de banco
// Atributos como tipo de operação SQL
// Métricas como número de linhas retornadas
// ...
}
```

## Configuração do Ambiente

O projeto usa Docker Compose para configurar:

1. **PostgreSQL**: Banco de dados para armazenar as tarefas
2. **Jaeger**: Backend para visualização de traces

```yaml
version: '3.8'
services:
postgres:
# Configuração do PostgreSQL

jaeger:
# Configuração do Jaeger All-in-One
# Expõe UI na porta 16686
```

## Como Executar

1. Clone o repositório
```
git clone <repository-url>
cd todo-api
```

2. Inicie os serviços
```
docker-compose up -d
```

3. Execute as migrações
```
go run cmd/migrate/main.go
```

4. Inicie a aplicação
```
go run main.go
```

5. Visualize os traces em http://localhost:16686
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Vc chegou a adicionar um swagger na API pra facilitar a geração dos tracings?


## Observabilidade

A implementação de OpenTelemetry permite:

- **Rastreamento distribuído**: Acompanhe operações em todos os componentes
- **Métricas detalhadas**: Número de requisições, duração, erros
- **Diagnóstico de problemas**: Identifique gargalos de performance
- **Correlação de eventos**: Associe cada operação a um identificador único

## Benefícios do OpenTelemetry

- **Padrão aberto**: Não há lock-in de fornecedor
- **Instrumentação consistente**: Mesmo padrão em diferentes linguagens
- **Extensibilidade**: Suporte a múltiplos backends (Jaeger, Zipkin, etc.)
- **Baixo overhead**: Impacto mínimo na performance

## Contribuindo

Contribuições são bem-vindas! Este projeto serve como referência para implementação de telemetria em aplicações Go.
29 changes: 29 additions & 0 deletions learning-otel-go/cmd/migrate/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// cmd/migrate/main.go
package main

import (
"fmt"
"log"
"todo-api/internal/config"

"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
)

func main() {
cfg := config.LoadConfig()

dbURL := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=disable", cfg.Database.User, cfg.Database.Password, cfg.Database.Host, cfg.Database.Port, cfg.Database.Name)

m, err := migrate.New("file://db/migrations", dbURL)
if err != nil {
log.Fatal(err)
}

if err := m.Up(); err != nil && err != migrate.ErrNoChange {
log.Fatal(err)
}

log.Println("Migrations aplicadas com sucesso!")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE IF EXISTS tasks;
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
CREATE TABLE tasks (
id UUID PRIMARY KEY,
title TEXT NOT NULL,
description TEXT NOT NULL,
concluded BOOLEAN NOT NULL DEFAULT FALSE
);
54 changes: 54 additions & 0 deletions learning-otel-go/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
services:
postgres:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acho que aqui pode deixar só o Postgres, o resto já tem lá no docker-compose global

https://github.com/douglasjunior/learning-open-telemetry/blob/main/docker/docker-compose.yml

image: postgres:latest
container_name: golearn_postgres
environment:
POSTGRES_USER: admin
POSTGRES_PASSWORD: admin123
POSTGRES_DB: golearn_db
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
restart: unless-stopped
networks:
- otel-network

otel-collector:
image: otel/opentelemetry-collector:latest
container_name: otel-collector
command: ["--config=/etc/otel-collector-config.yaml"]
volumes:
- ./otel-collector-config.yaml:/etc/otel-collector-config.yaml
ports:
- "4319:4317" # OTLP gRPC - mapeando para 4319 externamente
- "4320:4318" # OTLP HTTP - mapeando para 4320 externamente
depends_on:
- jaeger
networks:
- otel-network

jaeger:
image: jaegertracing/all-in-one:latest
container_name: jaeger
ports:
- "6831:6831/udp"
- "6832:6832/udp"
- "5778:5778"
- "16686:16686"
- "14250:14250"
- "14268:14268"
- "14269:14269"
- "4317:4317" # OTLP gRPC nativo do Jaeger
environment:
- COLLECTOR_OTLP_ENABLED=true
restart: unless-stopped
networks:
- otel-network

volumes:
postgres_data:

networks:
otel-network:
driver: bridge
36 changes: 36 additions & 0 deletions learning-otel-go/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
module todo-api

go 1.24.2

require (
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/golang-migrate/migrate/v4 v4.18.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/mux v1.8.1 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.1 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/lib/pq v1.10.9 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/otel v1.35.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.35.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0 // indirect
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.35.0 // indirect
go.opentelemetry.io/otel/metric v1.35.0 // indirect
go.opentelemetry.io/otel/sdk v1.35.0 // indirect
go.opentelemetry.io/otel/sdk/metric v1.35.0 // indirect
go.opentelemetry.io/otel/trace v1.35.0 // indirect
go.opentelemetry.io/proto/otlp v1.5.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/net v0.35.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/text v0.22.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a // indirect
google.golang.org/grpc v1.71.0 // indirect
google.golang.org/protobuf v1.36.5 // indirect
)
Loading