Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Dockerfile, Docker Compose, and Enhanced (Colored) Logging with Timezone Support for Wuzapi API #70

Open
wants to merge 19 commits into
base: main
Choose a base branch
from

Conversation

guilhermejansen
Copy link

Descrição (Português)

Esta Pull Request introduz as seguintes melhorias e configurações para a API Wuzapi:

Dockerfile:

  • Etapa de Build:
    • Utiliza a imagem golang:1.23-alpine3.20 para compilar o binário da API, instalando as dependências necessárias (como gcc, musl-dev e gcompat).
  • Imagem Final:
    • Baseada na imagem alpine:3.20, instala os pacotes essenciais para a execução da aplicação, incluindo tzdata para suporte a timezones.
    • Define a variável de ambiente TZ como "America/Sao_Paulo".
    • Copia os artefatos compilados, pastas de estáticos, migrações, arquivos e demais recursos.
    • Ajusta as permissões e define os volumes para persistência dos dados.
    • Configura o ENTRYPOINT para iniciar o binário com as flags --logtype=console --color=true, garantindo que os logs sejam exibidos em formato de console colorido.

Docker Compose:

  • Define dois serviços:
    • wuzapi-server:
      • Constrói a imagem a partir do Dockerfile acima.
      • Mapeia a porta 8080.
      • Define as variáveis de ambiente necessárias (incluindo o fuso horário).
      • Monta os volumes para persistência dos dados.
    • db:
      • Utiliza a imagem oficial postgres:15 e configura o banco de dados com as variáveis de ambiente apropriadas.
  • Configura a rede e os volumes necessários para a comunicação entre os serviços e a persistência dos dados.

Aprimoramentos no Código (main.go):

  • Migrações Condicionais:
    • Antes de executar as migrações, o código verifica se já existe pelo menos um usuário no banco de dados.
    • Se houver usuários, as migrações são puladas; caso contrário, o script SQL de migração é executado e um usuário padrão é inserido.
  • Configuração de Logs:
    • Utiliza o zerolog para registrar as mensagens, com suporte à saída em JSON ou em console.
    • Quando o modo console está ativado com a flag --color=true, os logs são exibidos com cores diferenciadas para cada nível (DEBUG, INFO, WARN, ERROR, etc.) e com timestamps formatados conforme o fuso horário definido.
  • Timezone:
    • O código lê a variável de ambiente TZ e ajusta time.Local de acordo, garantindo que os logs e operações de tempo usem o fuso horário correto.

Description (English)

This Pull Request introduces the following improvements and configurations for the Wuzapi API:

Dockerfile:

  • Build Stage:
    • Uses the golang:1.23-alpine3.20 image to compile the API binary, installing the necessary build dependencies (such as gcc, musl-dev, and gcompat).
  • Final Image:
    • Based on the alpine:3.20 image, installs the essential packages for running the application, including tzdata for timezone support.
    • Sets the environment variable TZ to "America/Sao_Paulo".
    • Copies the compiled binary, static assets, migrations, files, and other necessary resources.
    • Adjusts file permissions and defines volumes for data persistence.
    • Configures the ENTRYPOINT to run the binary with the flags --logtype=console --color=true, ensuring that logs are displayed in a colored console format.

Docker Compose:

  • Defines two services:
    • wuzapi-server:
      • Builds the image using the Dockerfile above.
      • Maps port 8080.
      • Sets the necessary environment variables (including the timezone).
      • Mounts volumes for data persistence.
    • db:
      • Uses the official postgres:15 image and configures the database with the appropriate environment variables.
  • Configures the network and volumes required for inter-service communication and data persistence.

Code Enhancements (main.go):

  • Conditional Migrations:
    • Before executing migrations, the code checks if at least one user exists in the database.
    • If users exist, migrations are skipped; otherwise, the SQL migration script is executed and a default user is inserted.
  • Logging Configuration:
    • Uses zerolog for logging, supporting both JSON and console output.
    • When console mode is enabled with the flag --color=true, logs are displayed with different colors for each log level (DEBUG, INFO, WARN, ERROR, etc.) and timestamps formatted according to the configured timezone.
  • Timezone:
    • The code reads the TZ environment variable and sets time.Local accordingly, ensuring that log timestamps and time-based operations use the correct timezone.

Instruções / Final Instructions

  1. Build da Imagem / Build the Image:

    docker-compose build --no-cache wuzapi-server
  2. Subir os Serviços / Start the Services:

    docker-compose up wuzapi-server
  3. Verificar os Logs / Check the Logs:

    • Os logs serão exibidos no console em formato colorido (quando --color=true) e os timestamps estarão formatados conforme o timezone configurado.
    • Logs in console mode will be displayed with colors for each log level (if --color=true), and timestamps will be formatted according to the configured timezone.

Arquivos Completos / Complete Files

Dockerfile

# =========================
# Build Stage: Compile the API
# =========================
FROM golang:1.23-alpine3.20 AS builder

# Atualiza o apk e instala dependências para compilar
RUN apk update && apk add --no-cache gcc musl-dev gcompat

WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download

COPY . .
ENV CGO_ENABLED=1
RUN go build -o wuzapi

# =========================
# Final Image: Running the API
# =========================
FROM alpine:3.20

# Atualiza o apk e instala os pacotes necessários, incluindo tzdata para suporte a timezones
RUN apk update && apk add --no-cache \
    ca-certificates \
    netcat-openbsd \
    postgresql-client \
    openssl \
    curl \
    ffmpeg \
    tzdata

# Define o fuso horário para America/Sao_Paulo
ENV TZ="America/Sao_Paulo"

WORKDIR /app

# Copia os arquivos compilados e recursos da etapa de build
COPY --from=builder /app/wuzapi         /app/
COPY --from=builder /app/static         /app/static/
COPY --from=builder /app/migrations     /app/migrations/
COPY --from=builder /app/files          /app/files/
COPY --from=builder /app/repository     /app/repository/
COPY --from=builder /app/dbdata         /app/dbdata/
COPY --from=builder /app/wuzapi.service /app/wuzapi.service

# Ajusta as permissões
RUN chmod +x /app/wuzapi
RUN chmod -R 755 /app
RUN chown -R root:root /app

# Define volumes para persistência de dados
VOLUME [ "/app/dbdata", "/app/files" ]

# ENTRYPOINT: Executa o binário com flags para logs em console colorido
ENTRYPOINT ["/app/wuzapi", "--logtype=console", "--color=true"]

docker-compose.yml

version: "3.8"

services:
  wuzapi-server:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8080:8080"
    environment:
      - WUZAPI_ADMIN_TOKEN=H4Zbhw72PBKdTIgS
      - DB_USER=wuzapi
      - DB_PASSWORD=wuzapi
      - DB_NAME=wuzapi
      - DB_HOST=db
      - DB_PORT=5432
      - TZ=America/Sao_Paulo
    volumes:
      - ./dbdata:/app/dbdata
      - ./files:/app/files
    depends_on:
      - db
    networks:
      - wuzapi-network

  db:
    image: postgres:15
    environment:
      POSTGRES_USER: wuzapi
      POSTGRES_PASSWORD: wuzapi
      POSTGRES_DB: wuzapi
    ports:
      - "5432:5432"
    volumes:
      - db_data:/var/lib/postgresql/data
    networks:
      - wuzapi-network

networks:
  wuzapi-network:
    driver: bridge

volumes:
  dbdata:
  files:
  db_data:

guilhermejansen and others added 19 commits September 23, 2024 20:19
This commit updates the go.sum file to include new dependencies and their respective versions. Notable changes include the addition of several packages such as , , and updates to existing packages like  and . These changes ensure that the project is using the latest compatible versions of its dependencies.
…k management functions

This commit modifies existing database queries in the  file to use PostgreSQL's parameterized query syntax (using , , etc.) instead of the previous  syntax. Additionally, it introduces new functions for managing webhooks, including , , and , enhancing the API's capabilities for user webhook management.
…ging

Updated the callHookFile function to create a final payload that includes the file parameter. Enhanced logging to provide more detailed information about the payload being sent and the response received, improving traceability and debugging capabilities.
This commit updates the database connection from SQLite to PostgreSQL using the sqlx library. It introduces environment variable loading for database credentials and implements database migrations using the golang-migrate package. Additionally, logging has been improved to provide clearer error messages in both English and Portuguese.
This commit introduces two new routes for managing webhooks: a DELETE method to remove a webhook and a PUT method to update an existing webhook. These additions enhance the webhook functionality and provide more flexibility for users interacting with the API.
…fication

This commit introduces new endpoints for user management under , allowing for listing, adding, and deleting users. Additionally, it enhances the webhook functionality with endpoints for setting, updating, and deleting webhooks, along with detailed descriptions and response examples for each operation. The API specification is now more comprehensive, providing clearer guidance for developers integrating with the API.
…ling

Refactored the database interactions in  to utilize the  package for enhanced query capabilities. Updated SQL statements to use positional parameters and improved error handling for JSON marshaling when calling webhooks. Additionally, increased the HTTP client timeout from 5 to 30 seconds to enhance reliability during network operations.
adjust update removing comma
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants