Socle V004 – Configuration

Socle V004 - Configuration

04 – Configuration

Version : 4.0.0 Date : 2025-01-25

1. Introduction

Le Socle V4 utilise une configuration centralisée via SocleConfiguration qui charge les paramètres depuis application.yml et les variables d’environnement.

Priorité de configuration

1. Variables d'environnement (priorité maximale)
2. application.yml
3. Valeurs par défaut dans le code

2. Fichier application.yml

2.1 Configuration minimale

socle:
  app_name: ${APP_NAME:my-app}
  env_name: ${ENV_NAME:DEV}
  exec_id: ${EXEC_ID:${socle.app_name}-${random.uuid}}
  region: ${REGION:local}
  version: ${APP_VERSION:4.0.0}

spring:
  application:
    name: ${socle.app_name}

server:
  port: ${HTTP_PORT:8080}

logging:
  config: classpath:log4j2.xml

2.2 Configuration complète

socle:
  # === Identification ===
  app_name: ${APP_NAME:socle-v4}
  env_name: ${ENV_NAME:DEV}
  exec_id: ${EXEC_ID:${socle.app_name}-${random.uuid}}
  region: ${REGION:local}
  version: ${APP_VERSION:4.0.0}

  # === HTTP Server ===
  http:
    enabled: ${HTTP_ENABLED:true}
    port: ${HTTP_PORT:8080}
    context-path: ${CONTEXT_PATH:/}

  # === KvBus ===
  kvbus:
    mode: ${KVBUS_MODE:in_memory}
    redis:
      host: ${REDIS_HOST:localhost}
      port: ${REDIS_PORT:6379}
      password: ${REDIS_PASSWORD:}
      database: ${REDIS_DATABASE:0}
      prefix: ${REDIS_PREFIX:socle}

  # === Supervisor ===
  supervisor:
    heartbeat-interval-ms: ${SUPERVISOR_HEARTBEAT_MS:10000}
    unhealthy-threshold: ${SUPERVISOR_UNHEALTHY_THRESHOLD:3}
    check-interval-ms: ${SUPERVISOR_CHECK_INTERVAL_MS:5000}
    stale-timeout-ms: ${SUPERVISOR_STALE_TIMEOUT_MS:60000}

  # === StatusDashboard (V4) ===
  status_dashboard:
    enabled: ${STATUS_DASHBOARD_ENABLED:true}
    port: ${STATUS_DASHBOARD_PORT:9374}
    refresh_interval: ${STATUS_DASHBOARD_REFRESH:5}

  # === Scheduler ===
  scheduler:
    enabled: ${SCHEDULER_ENABLED:true}
    thread-pool-size: ${SCHEDULER_POOL_SIZE:4}

  # === Admin API ===
  admin:
    enabled: ${ADMIN_ENABLED:true}
    auth:
      enabled: ${ADMIN_AUTH_ENABLED:false}
      username: ${ADMIN_USERNAME:admin}
      password: ${ADMIN_PASSWORD:admin}

  # === TechDB (V4) ===
  techdb:
    enabled: ${TECHDB_ENABLED:true}
    url: jdbc:h2:file:${TECHDB_PATH:./data/socle-techdb};MODE=PostgreSQL;DB_CLOSE_DELAY=-1
    username: socle
    password: ${TECHDB_PASSWORD:socle}
    console:
      enabled: ${H2_CONSOLE_ENABLED:false}
      path: /h2-console

  # === Logging (V4) ===
  logging:
    forwarder:
      enabled: ${LOG_FORWARDER_ENABLED:false}
      transport-mode: ${LOG_TRANSPORT_MODE:http}
      log-hub-url: ${LOG_HUB_URL:}
      nats-url: ${NATS_URL:}
      batch-size: ${LOG_BATCH_SIZE:100}
      flush-interval-ms: ${LOG_FLUSH_INTERVAL_MS:5000}

  # === Auth Client (V4) ===
  auth:
    enabled: ${AUTH_ENABLED:false}
    server-url: ${AUTH_SERVER_URL:}
    source-name: ${SOURCE_NAME:${socle.app_name}}
    api-key: ${API_KEY:}

  # === Worker Registry (V4) ===
  worker-registry:
    enabled: ${WORKER_REGISTRY_ENABLED:false}
    server-url: ${WORKER_REGISTRY_URL:}
    heartbeat-interval-ms: ${REGISTRY_HEARTBEAT_MS:30000}

spring:
  application:
    name: ${socle.app_name}

server:
  port: ${socle.http.port}

logging:
  config: classpath:log4j2.xml

3. Variables d’environnement

3.1 Variables essentielles

Variable Description Défaut Obligatoire
APP_NAME Nom de l’application socle-v4 Recommandé
ENV_NAME Environnement (DEV/STAGING/PROD) DEV Recommandé
REGION Région géographique local Recommandé
HTTP_PORT Port HTTP 8080 Non

3.2 Variables KvBus

Variable Description Défaut
KVBUS_MODE Mode (in_memory/redis) in_memory
REDIS_HOST Hôte Redis localhost
REDIS_PORT Port Redis 6379
REDIS_PASSWORD Mot de passe Redis
REDIS_DATABASE Database Redis 0
REDIS_PREFIX Préfixe des clés socle

3.3 Variables Supervisor et Dashboard

Variable Description Défaut
SUPERVISOR_HEARTBEAT_MS Intervalle heartbeat attendu 10000 (10s)
SUPERVISOR_UNHEALTHY_THRESHOLD Heartbeats manqués avant UNHEALTHY 3
SUPERVISOR_CHECK_INTERVAL_MS Fréquence de vérification 5000 (5s)
SUPERVISOR_STALE_TIMEOUT_MS Timeout avant STALE 60000 (1min)
STATUS_DASHBOARD_ENABLED Activer le dashboard true
STATUS_DASHBOARD_PORT Port du dashboard 9374
STATUS_DASHBOARD_REFRESH Rafraîchissement (secondes) 5

3.4 Variables V4

Variable Description Défaut
TECHDB_ENABLED Activer H2 TechDB true
TECHDB_PATH Chemin fichier H2 ./data/socle-techdb
H2_CONSOLE_ENABLED Console H2 web false
LOG_FORWARDER_ENABLED Activer LogForwarder false
LOG_TRANSPORT_MODE Mode transport logs http
AUTH_ENABLED Activer auth JWT false
WORKER_REGISTRY_ENABLED Activer registry false

4. Classe SocleConfiguration

package eu.lmvi.socle.config;

@Configuration
@ConfigurationProperties(prefix = "socle")
public class SocleConfiguration {

    // === Identification ===
    private String app_name = "socle-v4";
    private String env_name = "DEV";
    private String exec_id;
    private String region = "local";
    private String version = "4.0.0";

    // === HTTP ===
    private HttpConfig http = new HttpConfig();

    // === KvBus ===
    private KvBusConfig kvbus = new KvBusConfig();

    // === Supervisor ===
    private SupervisorConfig supervisor = new SupervisorConfig();

    // === TechDB (V4) ===
    private TechDbConfig techdb = new TechDbConfig();

    // === Logging (V4) ===
    private LoggingConfig logging = new LoggingConfig();

    // === Auth (V4) ===
    private AuthConfig auth = new AuthConfig();

    // === Worker Registry (V4) ===
    private WorkerRegistryConfig workerRegistry = new WorkerRegistryConfig();

    // Getters / Setters...

    @PostConstruct
    public void init() {
        if (exec_id == null || exec_id.isEmpty()) {
            exec_id = app_name + "-" + UUID.randomUUID().toString().substring(0, 8);
        }
    }
}

4.1 Sous-configurations

public static class HttpConfig {
    private boolean enabled = true;
    private int port = 8080;
    private String contextPath = "/";
}

public static class KvBusConfig {
    private String mode = "in_memory";
    private RedisConfig redis = new RedisConfig();
}

public static class TechDbConfig {
    private boolean enabled = true;
    private String url = "jdbc:h2:file:./data/socle-techdb";
    private String username = "socle";
    private String password = "socle";
    private ConsoleConfig console = new ConsoleConfig();
}

public static class LoggingConfig {
    private ForwarderConfig forwarder = new ForwarderConfig();
}

public static class AuthConfig {
    private boolean enabled = false;
    private String serverUrl;
    private String sourceName;
    private String apiKey;
}

public static class WorkerRegistryConfig {
    private boolean enabled = false;
    private String serverUrl;
    private long heartbeatIntervalMs = 30000;
}

5. Accès à la configuration

5.1 Injection

@Service
public class MonService {

    @Autowired
    private SocleConfiguration config;

    public void doSomething() {
        String appName = config.getApp_name();
        String region = config.getRegion();
        boolean techDbEnabled = config.getTechdb().isEnabled();
    }
}

5.2 Dans un Worker

public class MonWorker implements Worker {

    private final SocleConfiguration config;

    public MonWorker(SocleConfiguration config) {
        this.config = config;
    }

    @Override
    public void doWork() {
        log.info("Running in region: {}", config.getRegion());
    }
}

6. Profils Spring

6.1 Activation

# Via variable d'environnement
export SPRING_PROFILES_ACTIVE=prod

# Via ligne de commande
java -jar app.jar --spring.profiles.active=prod

6.2 Fichiers par profil

src/main/resources/
├── application.yml           # Configuration de base
├── application-dev.yml       # Overrides DEV
├── application-staging.yml   # Overrides STAGING
└── application-prod.yml      # Overrides PROD

6.3 Exemple application-prod.yml

socle:
  env_name: PROD
  techdb:
    console:
      enabled: false
  logging:
    forwarder:
      enabled: true
  auth:
    enabled: true
  worker-registry:
    enabled: true

logging:
  config: classpath:log4j2-prod.xml

7. Configuration Docker

7.1 Dockerfile

FROM eclipse-temurin:21-jre

WORKDIR /app

COPY target/socle-v004-4.0.0.jar app.jar

# Variables par défaut (peuvent être overridées)
ENV APP_NAME=socle-v4
ENV ENV_NAME=PROD
ENV HTTP_PORT=8080
ENV TECHDB_PATH=/app/data/techdb

EXPOSE 8080

ENTRYPOINT ["java", "-jar", "app.jar"]

7.2 docker-compose.yml

version: '3.8'

services:
  socle-app:
    image: socle-v4:latest
    environment:
      - APP_NAME=my-service
      - ENV_NAME=PROD
      - REGION=MTQ
      - KVBUS_MODE=redis
      - REDIS_HOST=redis
      - LOG_FORWARDER_ENABLED=true
      - LOG_HUB_URL=http://loghub:8080/api/ingest-logs
    ports:
      - "8080:8080"
    volumes:
      - ./data:/app/data
    depends_on:
      - redis

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

8. Configuration Kubernetes

8.1 ConfigMap

apiVersion: v1
kind: ConfigMap
metadata:
  name: socle-config
data:
  APP_NAME: "my-service"
  ENV_NAME: "PROD"
  REGION: "MTQ"
  KVBUS_MODE: "redis"
  LOG_FORWARDER_ENABLED: "true"

8.2 Secret

apiVersion: v1
kind: Secret
metadata:
  name: socle-secrets
type: Opaque
stringData:
  REDIS_PASSWORD: "secret-password"
  API_KEY: "my-api-key"
  TECHDB_PASSWORD: "techdb-password"

8.3 Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: socle-app
spec:
  replicas: 2
  template:
    spec:
      containers:
        - name: socle
          image: socle-v4:latest
          envFrom:
            - configMapRef:
                name: socle-config
            - secretRef:
                name: socle-secrets
          ports:
            - containerPort: 8080

9. Validation de configuration

9.1 Validation au démarrage

@Component
public class ConfigurationValidator implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private SocleConfiguration config;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        validateRequired();
        validateConsistency();
    }

    private void validateRequired() {
        if (config.getApp_name() == null || config.getApp_name().isEmpty()) {
            throw new IllegalStateException("APP_NAME is required");
        }
    }

    private void validateConsistency() {
        if (config.getAuth().isEnabled() && config.getAuth().getApiKey() == null) {
            throw new IllegalStateException("API_KEY required when AUTH_ENABLED=true");
        }
    }
}

9.2 Endpoint de configuration

GET /admin/config

Retourne la configuration actuelle (sans les secrets).

10. Bonnes pratiques

DO

  • Utiliser les variables d’environnement pour les valeurs spécifiques à l’environnement
  • Définir des valeurs par défaut sensées
  • Utiliser des profils Spring pour les environnements
  • Valider la configuration au démarrage
  • Ne jamais committer de secrets

DON’T

  • Ne pas hardcoder de valeurs dans le code
  • Ne pas mettre de mots de passe dans application.yml
  • Ne pas utiliser de valeurs par défaut dangereuses en prod

11. Références

Commentaires

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *