# https://raw.githubusercontent.com/dgraph-io/dgraph/master/contrib/config/kubernetes/dgraph-ha/dgraph-ha.yaml

# This StatefulSet runs 3 Dgraph Zero.
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: dgraph-zero
  namespace: hm-dgraph
spec:
  serviceName: "dgraph-zero"
  replicas: 3
  selector:
    matchLabels:
      app: dgraph-zero
  template:
    metadata:
      labels:
        app: dgraph-zero
    spec:
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 100
              podAffinityTerm:
                labelSelector:
                  matchExpressions:
                    - key: app
                      operator: In
                      values:
                        - dgraph-zero
                topologyKey: kubernetes.io/hostname
      containers:
        - name: zero
          image: dgraph/dgraph:latest
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 5080
              name: grpc-zero
            - containerPort: 6080
              name: http-zero
          volumeMounts:
            - name: datadir
              mountPath: /dgraph
          env:
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
          command:
            - bash
            - "-c"
            - |
              set -ex
              [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
              ordinal=${BASH_REMATCH[1]}
              idx=$(($ordinal + 1))
              if [[ $ordinal -eq 0 ]]; then
                exec dgraph zero --my=$(hostname -f):5080 --raft="idx=$idx" --replicas 3
              else
                exec dgraph zero --my=$(hostname -f):5080 --peer dgraph-zero-0.dgraph-zero.${POD_NAMESPACE}:5080 --raft="idx=$idx" --replicas 3
              fi
          livenessProbe:
            httpGet:
              path: /health
              port: 6080
            initialDelaySeconds: 15
            periodSeconds: 10
            timeoutSeconds: 5
            failureThreshold: 6
            successThreshold: 1
          readinessProbe:
            httpGet:
              path: /health
              port: 6080
            initialDelaySeconds: 15
            periodSeconds: 10
            timeoutSeconds: 5
            failureThreshold: 6
            successThreshold: 1
      terminationGracePeriodSeconds: 60
      volumes:
        - name: datadir
          persistentVolumeClaim:
            claimName: datadir
  updateStrategy:
    type: RollingUpdate
  volumeClaimTemplates:
    - metadata:
        name: datadir
        annotations:
          volume.alpha.kubernetes.io/storage-class: anything
      spec:
        accessModes:
          - "ReadWriteOnce"
        resources:
          requests:
            storage: 5Gi
