Руководство по разворачиванию SOBERIS в Kubernetes

SOBERIS представляет собой многокомпонентную систему, развернутую в кластере Kubernetes с использованием Helm чартов. Данное руководство описывает пошаговую установку всех компонентов системы в Kubernetes.
Системные требования
Kubernetes кластер
  • Kubernetes версии 1.24+
  • Helm версии 3.0+
  • kubectl для управления кластером
  • Минимум 3 узла для обеспечения высокой доступности
  • Поддержка LoadBalancer или Ingress Controller
Ресурсы кластера- Минимум 16 ГБ оперативной памяти на кластер
  • Минимум 100 ГБ дискового пространства для persistent volumes
  • Минимум 4 CPU ядра на кластер
  • Storage Class для динамического создания persistent volumes
Доступ к образам
  • Docker образы SOBERIS предоставляются после оплаты лицензии
  • Helm чарт и templates предоставляются после оплаты лицензии
  • Настроенные imagePullSecrets (при использовании private registry)
Быстрый старт
# Для быстрого развертывания системы с настройками по умолчанию:

```bash
# Создание namespace с метками
kubectl create namespace soberis
kubectl label namespace soberis name=soberis app=soberis-infrastructure --overwrite

# Установка SOBERIS
helm install soberis .\helm\soberis -n soberis --wait --timeout=15m

# Проверка статуса
kubectl get pods -n soberis
```

Для остановки системы:

```bash
# Удаление релиза
helm uninstall soberis -n soberis --wait --timeout=15m

# Удаление namespace
kubectl delete namespace soberis --wait --timeout=15m
```
Шаг 1. Подготовка кластера
1.1. Проверка статуса кластера
```bash
# Проверка подключения к кластеру
kubectl cluster-info

# Проверка узлов кластера
kubectl get nodes

# Проверка доступных storage classes
kubectl get storageclass
```
1.2. Создание namespace
```bash
# Создание namespace для SOBERIS
kubectl create namespace soberis

# Добавление меток для namespace
kubectl label namespace soberis name=soberis app=soberis-infrastructure --overwrite

# Установка namespace по умолчанию
kubectl config set-context --current --namespace=soberis
```
1.3. Настройка RBAC (при необходимости)
```bash
# Создание service account для Helm
kubectl create serviceaccount helm-deploy -n soberis

# Создание cluster role binding
kubectl create clusterrolebinding helm-deploy-cluster-admin \
  --clusterrole=cluster-admin \
  --serviceaccount=soberis:helm-deploy
```
Шаг 2. Получение и подготовка Helm чарта
2.1. Получение чарта SOBERIS
```bash
# После оплаты лицензии вы получите:
# - Архив с Helm чартом
# - Docker образы системы
# - Инструкции по развертыванию

# Распаковка полученного архива
tar -xzf soberis-helm-chart.tar.gz
cd soberis-helm

# Или клонирование предоставленного репозитория
git clone <предоставленный-repository-url>
cd soberis/helm/soberis
```
2.2. Проверка структуры чарта
```bash
# Проверка структуры чарта
helm show chart .

# Просмотр значений по умолчанию
helm show values . > default-values.yaml
```
Шаг 3. Настройка конфигурации
3.1. Создание файла custom-values.yaml
# Global configuration shared across all components
global:
  # Kubernetes namespace where all resources will be deployed
  namespace: soberis
  # MongoDB configuration settings
  mongodb:
    image:
      # Docker repository for MongoDB container image
      repository: mongo
      # MongoDB version tag
      tag: "8.0"
      # Image pull policy (IfNotPresent, Always, Never)
      pullPolicy: IfNotPresent
  # Redis configuration settings
  redis:
    image:
      # Docker repository for Redis container image
      repository: redis
      # Redis version tag
      tag: "7.2"
      # Image pull policy (IfNotPresent, Always, Never)
      pullPolicy: IfNotPresent

# MongoDB configuration for sharded cluster deployment
mongodb:
  # Configuration server settings
  config:
    # Number of config server replicas
    replicas: 3
    # Port for MongoDB config server
    port: 27017
    # Resource allocation for config servers
    resources:
      requests:
        # Minimum memory required
        memory: "512Mi"
        # Minimum CPU required
        cpu: "250m"
      limits:
        # Maximum memory allowed
        memory: "1Gi"
        # Maximum CPU allowed
        cpu: "500m"
    # Persistent storage configuration
    storage:
      # Storage size for config server
      size: "10Gi"
    # Health check probe configuration
    healthCheck:
      readiness:
        # Delay before first readiness check
        initialDelaySeconds: 10
        # Interval between readiness checks
        periodSeconds: 10
        # Timeout for readiness probe
        timeoutSeconds: 5
        # Number of failures before marking as not ready
        failureThreshold: 6
      liveness:
        # Delay before first liveness check
        initialDelaySeconds: 30
        # Interval between liveness checks
        periodSeconds: 30
        # Timeout for liveness probe
        timeoutSeconds: 5
        # Number of failures before restart
        failureThreshold: 3

  # First shard configuration
  shard1:
    # Number of replica set members in shard1
    replicas: 3
    # Port for shard1 MongoDB instances
    port: 27017
    # Resource allocation for shard1
    resources:
      requests:
        # Minimum memory required for shard1
        memory: "1Gi"
        # Minimum CPU required for shard1
        cpu: "500m"
      limits:
        # Maximum memory allowed for shard1
        memory: "2Gi"
        # Maximum CPU allowed for shard1
        cpu: "1000m"
    # Persistent storage configuration for shard1
    storage:
      # Storage size for each shard1 replica
      size: "50Gi"
    # Health check probe configuration for shard1
    healthCheck:
      readiness:
        # Delay before first readiness check
        initialDelaySeconds: 10
        # Interval between readiness checks
        periodSeconds: 10
        # Timeout for readiness probe
        timeoutSeconds: 5
        # Number of failures before marking as not ready
        failureThreshold: 6
      liveness:
        # Delay before first liveness check
        initialDelaySeconds: 30
        # Interval between liveness checks
        periodSeconds: 30
        # Timeout for liveness probe
        timeoutSeconds: 5
        # Number of failures before restart
        failureThreshold: 3

  # Second shard configuration
  shard2:
    # Number of replica set members in shard2
    replicas: 3
    # Port for shard2 MongoDB instances
    port: 27017
    # Resource allocation for shard2
    resources:
      requests:
        # Minimum memory required for shard2
        memory: "1Gi"
        # Minimum CPU required for shard2
        cpu: "500m"
      limits:
        # Maximum memory allowed for shard2
        memory: "2Gi"
        # Maximum CPU allowed for shard2
        cpu: "1000m"
    # Persistent storage configuration for shard2
    storage:
      # Storage size for each shard2 replica
      size: "50Gi"
    # Health check probe configuration for shard2
    healthCheck:
      readiness:
        # Delay before first readiness check
        initialDelaySeconds: 10
        # Interval between readiness checks
        periodSeconds: 10
        # Timeout for readiness probe
        timeoutSeconds: 5
        # Number of failures before marking as not ready
        failureThreshold: 6
      liveness:
        # Delay before first liveness check
        initialDelaySeconds: 30
        # Interval between liveness checks
        periodSeconds: 30
        # Timeout for liveness probe
        timeoutSeconds: 5
        # Number of failures before restart
        failureThreshold: 3

  # MongoDB router (mongos) configuration
  router:
    # Number of mongos router replicas
    replicas: 2
    # Port for mongos router instances
    port: 27017
    # Resource allocation for routers
    resources:
      requests:
        # Minimum memory required for routers
        memory: "512Mi"
        # Minimum CPU required for routers
        cpu: "250m"
      limits:
        # Maximum memory allowed for routers
        memory: "1Gi"
        # Maximum CPU allowed for routers
        cpu: "500m"
    # Service configuration for router access
    service:
      # Service type for external access
      type: NodePort
      # NodePort for external MongoDB access
      nodePort: 30017
    # Health check probe configuration for routers
    healthCheck:
      readiness:
        # Delay before first readiness check
        initialDelaySeconds: 10
        # Interval between readiness checks
        periodSeconds: 10
        # Timeout for readiness probe
        timeoutSeconds: 5
        # Number of failures before marking as not ready
        failureThreshold: 6
      liveness:
        # Delay before first liveness check
        initialDelaySeconds: 30
        # Interval between liveness checks
        periodSeconds: 30
        # Timeout for liveness probe
        timeoutSeconds: 5
        # Number of failures before restart
        failureThreshold: 3

  # MongoDB initialization job configuration
  init:
    # Resource allocation for MongoDB init container
    resources:
      requests:
        # Minimum memory required for init job
        memory: "256Mi"
        # Minimum CPU required for init job
        cpu: "100m"
      limits:
        # Maximum memory allowed for init job
        memory: "512Mi"
        # Maximum CPU allowed for init job
        cpu: "200m"
  
  # MongoDB transaction parameters configuration
  transaction:
    # Transaction lifetime limit in seconds (MongoDB parameter)
    lifetimeLimitSeconds: 60
    # Maximum time transaction waits for lock in milliseconds
    maxLockRequestTimeoutMs: 5000

# Redis cluster configuration
redis:
  # Redis cluster settings
  cluster:
    # Enable Redis cluster mode
    enabled: true
    # Number of master nodes in cluster
    masters: 3
    # Number of slave nodes in cluster
    slaves: 3
    # Number of replicas per master
    replicas: 1
  
  # Redis master node configuration
  master:
    # Resource allocation for master nodes
    resources:
      requests:
        # Minimum memory required for masters
        memory: "256Mi"
        # Minimum CPU required for masters
        cpu: "100m"
      limits:
        # Maximum memory allowed for masters
        memory: "512Mi"
        # Maximum CPU allowed for masters
        cpu: "250m"
    # Persistent storage configuration for masters
    storage:
      # Storage size for each master node
      size: "5Gi"
    # Port configuration for master nodes
    ports:
      # Redis protocol port
      redis: 6379
      # Cluster bus port for inter-node communication
      bus: 16379
    # Service configuration for master nodes
    service:
      # Service type for internal cluster access
      type: ClusterIP
    # Health check probe configuration for masters
    healthCheck:
      readiness:
        # Delay before first readiness check
        initialDelaySeconds: 10
        # Interval between readiness checks
        periodSeconds: 5
        # Timeout for readiness probe
        timeoutSeconds: 3
      liveness:
        # Delay before first liveness check
        initialDelaySeconds: 30
        # Interval between liveness checks
        periodSeconds: 10
        # Timeout for liveness probe
        timeoutSeconds: 5
  
  # Redis slave node configuration
  slave:
    # Resource allocation for slave nodes
    resources:
      requests:
        # Minimum memory required for slaves
        memory: "256Mi"
        # Minimum CPU required for slaves
        cpu: "100m"
      limits:
        # Maximum memory allowed for slaves
        memory: "512Mi"
        # Maximum CPU allowed for slaves
        cpu: "250m"
    # Persistent storage configuration for slaves
    storage:
      # Storage size for each slave node
      size: "5Gi"
    # Port configuration for slave nodes
    ports:
      # Redis protocol port
      redis: 6379
      # Cluster bus port for inter-node communication
      bus: 16379
    # Service configuration for slave nodes
    service:
      # Service type for internal cluster access
      type: ClusterIP
    # Health check probe configuration for slaves
    healthCheck:
      readiness:
        # Delay before first readiness check
        initialDelaySeconds: 10
        # Interval between readiness checks
        periodSeconds: 5
        # Timeout for readiness probe
        timeoutSeconds: 3
      liveness:
        # Delay before first liveness check
        initialDelaySeconds: 30
        # Interval between liveness checks
        periodSeconds: 10
        # Timeout for liveness probe
        timeoutSeconds: 5

  # Redis configuration parameters
  config:
    # Enable Redis cluster mode
    clusterEnabled: true
    # Enable append-only file persistence
    appendOnly: true
    # Cluster node timeout in milliseconds
    nodeTimeout: 5000
    # Announce IP address to other cluster nodes
    announceIp: true
  
  # Redis initialization job configuration
  init:
    # Resource allocation for Redis init container
    resources:
      requests:
        # Minimum memory required for init job
        memory: "128Mi"
        # Minimum CPU required for init job
        cpu: "100m"
      limits:
        # Maximum memory allowed for init job
        memory: "256Mi"
        # Maximum CPU allowed for init job
        cpu: "200m"

# Keycloak identity and access management configuration
keycloak:
  # Keycloak container image settings
  image:
    # Docker repository for Keycloak container image
    repository: quay.io/keycloak/keycloak
    # Keycloak version tag
    tag: "26.2"
    # Image pull policy (IfNotPresent, Always, Never)
    pullPolicy: IfNotPresent
  
  # PostgreSQL database configuration for Keycloak
  database:
    image:
      # Docker repository for PostgreSQL container image
      repository: postgres
      # PostgreSQL version tag
      tag: "17.5"
      # Image pull policy (IfNotPresent, Always, Never)
      pullPolicy: IfNotPresent
    # Database name for Keycloak
    name: keycloak
    # Database username for Keycloak
    user: keycloak
    # Database password for Keycloak
    password: keycloak
    # Persistent storage configuration for database
    storage:
      # Storage size for PostgreSQL data
      size: "10Gi"
    # Resource allocation for PostgreSQL
    resources:
      requests:
        # Minimum memory required for database
        memory: "256Mi"
        # Minimum CPU required for database
        cpu: "100m"
      limits:
        # Maximum memory allowed for database
        memory: "512Mi"
        # Maximum CPU allowed for database
        cpu: "250m"
  
  # Resource allocation for Keycloak service
  resources:
    requests:
      # Minimum memory required for Keycloak
      memory: "512Mi"
      # Minimum CPU required for Keycloak
      cpu: "250m"
    limits:
      # Maximum memory allowed for Keycloak
      memory: "1Gi"
      # Maximum CPU allowed for Keycloak
      cpu: "500m"
  
  # Keycloak admin user configuration
  admin:
    # Admin username for Keycloak console
    username: admin
    # Admin password for Keycloak console
    password: admin
  
  # Keycloak realm configuration
  realm:
    # Name of the realm to create
    name: soberis
    # Enable the realm
    enabled: true
    # Default locale for the realm
    defaultLocale: ru
    # Supported locales in the realm
    supportedLocales: ru
    # Enable internationalization
    i18nEnabled: true
    # Comma-separated list of roles to create
    roles: "update_schema,import_schema,export_schema,read_specification,clear_cache,read_metrics,update_log_ttl,api_keys_management"
  
  # Default user to create in the realm
  defaultUser:
    # Username for the default user
    username: admin_user
    # Password for the default user
    password: admin_user
    # Enable the user account
    enabled: true
    # Mark email as verified
    emailVerified: true
  
  # OAuth2 client configuration for frontend
  client:
    # Client ID for the frontend application
    id: frontend
    # Enable the client
    enabled: true
    # Public client (no client secret required)
    public: true
    # Valid redirect URIs for OAuth2 flows
    redirectUris: "http://localhost/*,https://localhost/*"
    # Valid web origins for CORS
    webOrigins: "http://localhost,https://localhost"
  
  # Keycloak hostname configuration
  hostname:
    # Enforce strict hostname validation
    strict: false
    # Enforce HTTPS only
    strictHttps: false
    # Frontend URL for Keycloak
    url: "https://localhost"
    # Admin console URL for Keycloak
    adminUrl: "https://localhost"
  
  # Kubernetes service configuration for Keycloak
  service:
    # Service type for internal access
    type: ClusterIP
    # Port for Keycloak HTTP service
    port: 8080
    # NodePort for external access (if type is NodePort)
    nodePort: 30180

# Soberis application configuration
soberis:
  # Container image settings for Soberis
  image:
    # Docker repository for Soberis container image
    repository: soberis
    # Soberis version tag
    tag: "latest"
    # Image pull policy (IfNotPresent, Always, Never)
    pullPolicy: IfNotPresent
  
  # Number of Soberis application replicas
  replicas: 3
  
  # Resource allocation for Soberis application
  resources:
    requests:
      # Minimum memory required for Soberis
      memory: "1Gi"
      # Minimum CPU required for Soberis
      cpu: "500m"
    limits:
      # Maximum memory allowed for Soberis
      memory: "2Gi"
      # Maximum CPU allowed for Soberis
      cpu: "1000m"
  
  # Port configuration for Soberis application
  ports:
    # Main API port for Soberis
    api: 8588
    # Metrics and health check port
    metrics: 8888
  
  # Kubernetes service configuration for Soberis
  service:
    # Service type for external access
    type: NodePort
    # NodePort for external API access
    nodePort: 30588
  
  # Health check probe configuration for Soberis
  healthChecks:
    # Liveness probe to check if container is running
    livenessProbe:
      httpGet:
        # Health check endpoint path
        path: /actuator/health/liveness
        # Port for health check
        port: 8888
      # Delay before first liveness check
      initialDelaySeconds: 30
      # Interval between liveness checks
      periodSeconds: 10
      # Timeout for liveness probe
      timeoutSeconds: 5
      # Number of failures before restart
      failureThreshold: 3
    
    # Readiness probe to check if container is ready to serve traffic
    readinessProbe:
      httpGet:
        # Readiness check endpoint path
        path: /actuator/health/readiness
        # Port for readiness check
        port: 8888
      # Delay before first readiness check
      initialDelaySeconds: 15
      # Interval between readiness checks
      periodSeconds: 5
      # Timeout for readiness probe
      timeoutSeconds: 3
      # Number of failures before marking as not ready
      failureThreshold: 3
    
    # Startup probe to check if container has started successfully
    startupProbe:
      httpGet:
        # Startup check endpoint path
        path: /actuator/health
        # Port for startup check
        port: 8888
      # Delay before first startup check
      initialDelaySeconds: 10
      # Interval between startup checks
      periodSeconds: 10
      # Timeout for startup probe
      timeoutSeconds: 5
      # Number of failures before considering startup failed
      failureThreshold: 30  
  
  # Environment variables for Soberis application
  environment:
    # Spring Boot active profiles
    springProfilesActive: docker
    # License key for Soberis (empty for trial)
    licenseKey: ""
    # Enable API token validation
    apiTokenValidationEnabled: true
    # URL pattern for multi-instance deployment
    instanceUrlPattern: "http://soberis-{instance}:8588"
  
  # MongoDB connection configuration for Soberis
  mongodb:
    # MongoDB connection URI
    uri: "mongodb://mongodb-router-service:27017/"
    # Main application database name
    database: "sbrs_data_db"
    # Event log database name
    eventLogDatabase: "sbrs_event_log_db"
    # Service log database name
    serviceLogDatabase: "sbrs_service_log_db"
    # Server log database name
    serverLogDatabase: "sbrs_server_log_db"
  
  # Redis cluster connection configuration for Soberis
  redis:
    # Comma-separated list of Redis cluster nodes
    clusterNodes: "redis-master1:6379,redis-master2:6379,redis-master3:6379,redis-slave1:6379,redis-slave2:6379,redis-slave3:6379"
    # Maximum number of redirects in cluster
    maxRedirects: 5
    # Socket timeout in milliseconds
    timeout: 30000
    # Connection timeout in milliseconds
    connectTimeout: 15000
    # Maximum number of active connections in pool
    poolMaxActive: 20
    # Maximum number of idle connections in pool
    poolMaxIdle: 8
    # Minimum number of idle connections in pool
    poolMinIdle: 2
    # Maximum wait time for connection in milliseconds
    poolMaxWait: 15000
    # Cluster topology refresh period in milliseconds
    clusterRefreshPeriod: 30000
    # Enable adaptive cluster topology refresh
    adaptiveRefresh: true
    # Triggers for adaptive refresh
    refreshTriggers: "MOVED_REDIRECT,ASK_REDIRECT"
  
  # OAuth2 configuration for Soberis authentication
  oauth2:
    # OAuth2 issuer URI for token validation
    issuerUri: "https://localhost/realms/soberis"
    # JWK Set URI for public key retrieval
    jwkSetUri: "http://keycloak:8080/realms/soberis/protocol/openid-connect/certs"
  
  # Transaction management configuration
  transaction:
    # Application transaction timeout in milliseconds (5 minutes)
    defaultTimeoutMs: 300000
    # Redis TTL buffer in milliseconds
    redisTtlBufferMs: 5000
    # Transaction proxy connection timeout in milliseconds
    proxyConnectionTimeoutMs: 5000
    # Transaction proxy read timeout in milliseconds
    proxyReadTimeoutMs: 10000

# Nginx reverse proxy and web server configuration
nginx:
  # Nginx container image settings
  image:
    # Docker repository for Nginx container image
    repository: nginx
    # Nginx version tag
    tag: "latest"
    # Image pull policy (IfNotPresent, Always, Never)
    pullPolicy: IfNotPresent
  
  # Number of Nginx replicas
  replicas: 2
  
  # Resource allocation for Nginx
  resources:
    requests:
      # Minimum memory required for Nginx
      memory: "256Mi"
      # Minimum CPU required for Nginx
      cpu: "100m"
    limits:
      # Maximum memory allowed for Nginx
      memory: "512Mi"
      # Maximum CPU allowed for Nginx
      cpu: "250m"
  
  # Port configuration for Nginx
  ports:
    # HTTP port for web traffic
    http: 80
    # HTTPS port for secure web traffic
    https: 443
  
  # Kubernetes service configuration for Nginx
  service:
    # Service type for external access
    type: LoadBalancer 
    # NodePort for HTTP traffic
    httpNodePort: 30080 
    # NodePort for HTTPS traffic
    httpsNodePort: 30443 
    # Base HTTP port for additional services
    baseHttpPort: 30090  
    # Base HTTPS port for additional services
    baseHttpsPort: 30453 
  
  # Frontend application configuration for Nginx
  frontend:
    # Keycloak server URL for authentication
    keycloakUrl: "https://localhost"
    # Base URL for HTTP client requests
    httpClientBaseUrl: "https://localhost"
    # Specification server URL
    specificationServerUrl: "https://localhost"
  
  # Backend load balancing configuration for Nginx
  backend:
    # Default weight for backend servers
    defaultWeight: 1
    # Maximum number of failed attempts before marking server as unavailable
    maxFails: 3
    # Time to wait before retrying failed server
    failTimeout: "30s"
    # Number of keepalive connections to upstream servers
    keepalive: 32
    # Maximum number of requests per keepalive connection
    keepaliveRequests: 100
    # Timeout for keepalive connections
    keepaliveTimeout: "60s"
  
  # Nginx server configuration
  server:
    # Server name for virtual host
    name: "localhost"
    # DNS resolver for upstream name resolution
    resolver: "10.96.0.10"
    # Cache validity time for DNS resolution
    resolverValid: "30s"
    # Network allowed to access status page
    statusAllowNetwork: "10.0.0.0/8"
    # Maximum number of simultaneous connections per worker
    workerConnections: 1024
    # Timeout for keep-alive connections
    keepaliveTimeout: 65
    # Maximum size of types hash table
    typesHashMaxSize: 2048
  
  # Gzip compression configuration for Nginx
  gzip:
    # Enable gzip compression
    enabled: "on"
    # Compression level (1-9, higher = better compression, more CPU)
    compLevel: 6
    # Minimum response size to compress
    minLength: 1000
  
  # Proxy configuration for Nginx
  proxy:
    # Size of buffer for reading response header
    bufferSize: "128k"
    # Number of buffers for reading response
    buffersNum: 4
    # Size of buffers for reading response
    buffersSize: "256k"
    # Size of buffers for busy connections
    busyBuffersSize: "256k"
    # Timeout for reading response from upstream
    readTimeout: "60s"
    # Timeout for establishing connection to upstream
    connectTimeout: "30s"
    # Timeout for sending request to upstream
    sendTimeout: "60s"
    # Number of tries for next upstream server
    nextUpstreamTries: 2
    # Timeout for next upstream attempts
    nextUpstreamTimeout: "100s"
  
  # Specific proxy settings for SBRS backend
  sbrs:
    # Timeout for reading response from SBRS backend
    proxyReadTimeout: "120s"
    # Timeout for establishing connection to SBRS backend
    proxyConnectTimeout: "30s"
    # Timeout for sending request to SBRS backend
    proxySendTimeout: "120s"
  
  # CORS (Cross-Origin Resource Sharing) configuration
  cors:
    # Allowed origins for CORS requests
    allowedOrigins: "https://localhost,http://localhost"
    # Allowed HTTP methods for CORS requests
    allowedMethods: "GET, POST, OPTIONS, PUT, DELETE"
    # Allowed headers for CORS requests
    allowedHeaders: "Authorization, Content-Type, Accept, X-Requested-With, Origin, Accept-Language, Connection, Sec-Fetch-Dest, Sec-Fetch-Mode, Sec-Fetch-Site, Sec-Fetch-Storage-Access, User-Agent, sec-ch-ua, sec-ch-ua-mobile, sec-ch-ua-platform, Cache-Control, Pragma"
    # Allow credentials in CORS requests
    allowCredentials: true
    # Maximum age for CORS preflight cache
    maxAge: 86400

  # SSL/TLS configuration for HTTPS
  ssl:
    # Enable SSL/TLS encryption
    enabled: true
    # Path to SSL certificate file
    certPath: "/shared/ssl/server.crt"
    # Path to SSL private key file
    keyPath: "/shared/ssl/server.key"
    # Country code for certificate
    country: "RU"
    # State/Province for certificate
    state: "Moscow"
    # City for certificate
    city: "Moscow"
    # Organization name for certificate
    org: "Soberis"
    # Organizational unit for certificate
    orgUnit: "IT"
    # Common name for certificate (domain name)
    commonName: "localhost"
    # Email address for certificate
    email: "admin@subdsoberis.ru"
    # Certificate validity period in days
    days: 365
    # RSA key size for certificate
    keySize: 2048
    # SSL cipher suite configuration for security
    cipherSuite: "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA"
    # SSL session cache configuration
    sessionCache: "shared:SSL:10m"
    # SSL session timeout
    sessionTimeout: "10m"
  
  # Static file serving configuration
  staticFiles:
    # Cache expiration time for static files
    cacheExpires: "1y"
  
  # Health check configuration for Nginx
  healthcheck:
    # URL for health check endpoint
    url: "http://localhost:80/"
3.2. Настройка доменного имени
# Если у вас есть доменное имя, замените `localhost` на ваш домен:

```yaml
# В custom-values.yaml
nginx:
  server:
    name: "soberis.yourdomain.com"
  frontend:
    keycloakUrl: "https://soberis.yourdomain.com"
    httpClientBaseUrl: "https://soberis.yourdomain.com"
    specificationServerUrl: "https://soberis.yourdomain.com"

keycloak:
  realm:
    url: "https://soberis.yourdomain.com"
    adminUrl: "https://soberis.yourdomain.com"

soberis:
  oauth2:
    issuerUri: "https://soberis.yourdomain.com/realms/soberis"
```
3.3. Настройка SSL сертификатов
```yaml
# Для production среды настройте SSL
nginx:
  ssl:
    enabled: true
    commonName: "soberis.yourdomain.com"
    # Или используйте существующие сертификаты
    # existingSecret: "soberis-tls"
```
Шаг 4. Создание секретов
4.1. Секрет для private registry (при необходимости)
```bash
# Создание секрета для доступа к private registry
kubectl create secret docker-registry soberis-registry-secret \
  --docker-server=your-registry.com \
  --docker-username=your-username \
  --docker-password=your-password \
  --docker-email=your-email@example.com \
  -n soberis
```
4.2. Секрет для лицензионного ключа
```bash
# Создание секрета с лицензионным ключом
kubectl create secret generic soberis-license \
  --from-literal=license-key="ВАШ_ЛИЦЕНЗИОННЫЙ_КЛЮЧ" \
  -n soberis
```
Шаг 5. Развертывание системы
5.1. Проверка чарта перед установкой
```bash
# Проверка синтаксиса чарта
helm lint .

# Симуляция установки (dry-run)
helm install soberis . --dry-run --debug -f custom-values.yaml

# Генерация манифестов для проверки
helm template soberis . -f custom-values.yaml > manifests.yaml
```
5.2. Установка системы
```bash
# Установка SOBERIS с ожиданием готовности всех компонентов
helm install soberis . -f custom-values.yaml -n soberis --wait --timeout=15m

# Альтернативный вариант установки без custom values
helm install soberis .\helm\soberis -n soberis --wait --timeout=15m

# Просмотр статуса установки
helm status soberis -n soberis

# Мониторинг процесса развертывания
kubectl get pods -n soberis -w
```
5.3. Последовательность инициализации
Система автоматически управляет последовательностью запуска:
1. Базы данных: PostgreSQL для Keycloak, MongoDB кластер, Redis кластер
2. Инициализация: Jobs для настройки MongoDB и Redis кластеров
3. Keycloak: Сервер аутентификации и авторизации
4. Backend: API сервисы SOBERIS (3 реплики)
5. Frontend: Веб-интерфейс Nginx (2 реплики)
Шаг 6. Проверка установки
6.1. Проверка статуса pods
```bash
# Проверка всех pods
kubectl get pods -n soberis

# Детальная информация о pods
kubectl describe pods -n soberis

# Проверка логов
kubectl logs -f deployment/soberis -n soberis
```
6.2. Проверка сервисов
```bash
# Просмотр всех сервисов
kubectl get services -n soberis

# Получение внешнего IP LoadBalancer
kubectl get service nginx-service -n soberis

# Проверка endpoints
kubectl get endpoints -n soberis
```
6.3. Доступ к приложению
После успешного развертывания откройте в браузере:

```bash
# Получение внешнего адреса
export EXTERNAL_IP=$(kubectl get service nginx-service -n soberis -o jsonpath='{.status.loadBalancer.ingress[0].ip}')

# Или для NodePort
export NODE_IP=$(kubectl get nodes -o jsonpath='{.items[0].status.addresses[?(@.type=="ExternalIP")].address}')
export NODE_PORT=$(kubectl get service nginx-service -n soberis -o jsonpath='{.spec.ports[0].nodePort}')
```

- HTTPS: `https://$EXTERNAL_IP` или `https://$NODE_IP:$NODE_PORT`
- HTTP: `http://$EXTERNAL_IP` или `http://$NODE_IP:$NODE_PORT`
6.4. Учетные данные по умолчанию
Для входа в систему используйте:
- Логин: `admin_user`
- Пароль: `admin_user`

Примечание: Управление пользователями осуществляется через административную панель Keycloak. Подробная инструкция по настройке пользователей предоставляется вместе с лицензией.
Шаг 7. Настройка Ingress (опционально)
7.1. Создание Ingress для внешнего доступа
```yaml
# ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: soberis-ingress
  namespace: soberis
  annotations:
    kubernetes.io/ingress.class: "nginx"
    cert-manager.io/cluster-issuer: "letsencrypt-prod"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
  tls:
  - hosts:
    - soberis.yourdomain.com
    secretName: soberis-tls
  rules:
  - host: soberis.yourdomain.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: nginx-service
            port:
              number: 80
```
7.2. Применение Ingress
```bash
# Применение конфигурации Ingress
kubectl apply -f ingress.yaml

# Проверка статуса Ingress
kubectl get ingress -n soberis
```
Шаг 8. Мониторинг и логи
8.1. Просмотр логов системы
```bash
# Логи backend сервисов
kubectl logs -f deployment/soberis -n soberis

# Логи frontend
kubectl logs -f deployment/nginx -n soberis

# Логи Keycloak
kubectl logs -f deployment/keycloak -n soberis

# Логи MongoDB
kubectl logs -f statefulset/mongodb-config -n soberis

# Логи Redis
kubectl logs -f statefulset/redis-master1 -n soberis
```
8.2. Мониторинг ресурсов
```bash
# Использование ресурсов pods
kubectl top pods -n soberis

# Использование ресурсов nodes
kubectl top nodes

# События в namespace
kubectl get events -n soberis --sort-by='.lastTimestamp'
```
Шаг 9. Обновление системы
9.1. Обновление Helm релиза
```bash
# Обновление значений конфигурации
helm upgrade soberis . -f custom-values.yaml -n soberis

# Обновление с новой версией образов
helm upgrade soberis . --set soberis.image.tag=2.0.170 -n soberis

# Откат к предыдущей версии
helm rollback soberis 1 -n soberis
```
9.2. Обновление образов
```bash
# Обновление образа SOBERIS backend
kubectl set image deployment/soberis soberis=your-registry/soberis:2.0.170 -n soberis

# Обновление образа frontend
kubectl set image deployment/nginx nginx=your-registry/soberis-frontend:2.0.170 -n soberis

# Проверка статуса rolling update
kubectl rollout status deployment/soberis -n soberis
```
Полезные команды
# Управление релизом
```bash
# Список всех релизов
helm list -n soberis

# Просмотр истории релиза
helm history soberis -n soberis

# Полное удаление релиза с ожиданием завершения
helm uninstall soberis -n soberis --wait --timeout=15m

# Удаление всех ресурсов включая PVC и namespace
kubectl delete namespace soberis --wait --timeout=15m
```

# Диагностика проблем
```bash
# Описание проблемного pod
kubectl describe pod <pod-name> -n soberis

# Подключение к контейнеру для отладки
kubectl exec -it <pod-name> -n soberis -- /bin/bash

# Проверка persistent volumes
kubectl get pv,pvc -n soberis

# Проверка сетевых политик
kubectl get networkpolicy -n soberis
```

# Резервное копирование
```bash
# Экспорт текущей конфигурации
helm get values soberis -n soberis > backup-values.yaml

# Создание снапшота persistent volumes
kubectl get pvc -n soberis -o yaml > pvc-backup.yaml

# Бэкап данных MongoDB (пример)
kubectl exec -it mongodb-router-0 -n soberis -- mongodump --out /backup
```
Рекомендации для production
# Безопасность
- Используйте TLS сертификаты от доверенного CA
- Настройте Network Policies для изоляции трафика
- Регулярно обновляйте образы и зависимости
- Используйте secrets для хранения паролей и ключей

# Производительность
- Настройте resource limits и requests для всех компонентов
- Используйте быстрые storage classes (SSD) для баз данных
- Настройте HPA (Horizontal Pod Autoscaler) для автомасштабирования
- Мониторинг производительности с помощью Prometheus/Grafana

# Высокая доступность
- Разверните кластер на нескольких availability zones
- Используйте минимум 3 реплики для критичных компонентов
- Настройте pod anti-affinity rules
- Регулярно тестируйте процедуры восстановления

# Мониторинг
- Настройте централизованный сбор логов (ELK, Fluentd)
- Мониторинг метрик с помощью Prometheus
- Настройте алерты для критичных событий
- Регулярные health checks для всех компонентов
Примечания
- При первом запуске инициализация может занять 10-15 минут (при первом запуске дождитесь остановки init-контейнеров)
- Для production среды рекомендуется использовать managed services для баз данных
- Регулярно создавайте резервные копии данных MongoDB и PostgreSQL
- Система автоматически создает самоподписанные SSL сертификаты для разработки