# PostgreSQL StatefulSet for main database
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
  namespace: ez-api-test-dev
  labels:
    app.kubernetes.io/name: ez-api-test-dev
    app.kubernetes.io/component: postgres
spec:
  serviceName: postgres
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  # 有状态服务使用 OrderedReady 策略，确保按顺序部署和终止
  podManagementPolicy: OrderedReady
  # 使用 RollingUpdate 策略，partition=0 表示全部更新
  updateStrategy:
    type: RollingUpdate
    rollingUpdate:
      partition: 0
  template:
    metadata:
      labels:
        app: postgres
        app.kubernetes.io/name: ez-api-test-dev
        app.kubernetes.io/component: postgres
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: postgres
          image: postgres:15-alpine
          ports:
            - containerPort: 5432
              name: postgres
          env:
            - name: POSTGRES_USER
              valueFrom:
                secretKeyRef:
                  name: ez-api-secrets
                  key: POSTGRES_USER
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: ez-api-secrets
                  key: POSTGRES_PASSWORD
            - name: POSTGRES_DB
              valueFrom:
                configMapKeyRef:
                  name: ez-api-config
                  key: POSTGRES_DB
            - name: PGDATA
              value: /var/lib/postgresql/data/pgdata
          volumeMounts:
            - name: postgres-data
              mountPath: /var/lib/postgresql/data
          resources:
            requests:
              memory: "256Mi"
              cpu: "100m"
            limits:
              memory: "1Gi"
              cpu: "500m"
          livenessProbe:
            exec:
              command:
                - pg_isready
                - -U
                - postgres
            initialDelaySeconds: 30
            periodSeconds: 10
            timeoutSeconds: 5
            failureThreshold: 6
          readinessProbe:
            exec:
              command:
                - pg_isready
                - -U
                - postgres
            initialDelaySeconds: 5
            periodSeconds: 5
            timeoutSeconds: 5
            failureThreshold: 3
  volumeClaimTemplates:
    - metadata:
        name: postgres-data
      spec:
        accessModes: ["ReadWriteOnce"]
        # 根据集群配置修改 storageClassName
        # storageClassName: "standard"
        resources:
          requests:
            storage: 50Gi
---
# PostgreSQL Service (Headless for StatefulSet)
apiVersion: v1
kind: Service
metadata:
  name: postgres
  namespace: ez-api-test-dev
  labels:
    app.kubernetes.io/name: ez-api-test-dev
    app.kubernetes.io/component: postgres
spec:
  ports:
    - port: 5432
      targetPort: 5432
      name: postgres
  clusterIP: None  # Headless service for StatefulSet
  selector:
    app: postgres
