---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mongo
  annotations:
    keel.sh/policy: force
    keel.sh/trigger: poll
    keel.sh/pollSchedule: "@midnight"
spec:
  revisionHistoryLimit: 0
  serviceName: mongo
  selector:
    matchLabels:
      app: mongo
  replicas: 1
  template:
    metadata:
      labels:
        app: mongo
    spec:
      securityContext:
        fsGroup: 999
      containers:
      - name: mongo
        image: mongo:5
        command:
         - mongod
         - --quiet
         - --replSet
         - rs0
         - --bind_ip_all
        ports:
        - name: mongo
          containerPort: 27017
        securityContext:
          readOnlyRootFilesystem: true
          runAsNonRoot: true
          runAsUser: 999
        volumeMounts:
        - name: tmp
          mountPath: /tmp
        - name: mongo-data
          mountPath: /data/db
      - name: exporter
        image: percona/mongodb_exporter:0.30.0
        args:
          - --compatible-mode
          - --mongodb.direct-connect=false
        ports:
        - name: mongo-exporter
          containerPort: 9216
        securityContext:
          readOnlyRootFilesystem: true
          runAsNonRoot: true
          runAsUser: 65535
        env:
        - name: MONGODB_URI
          value: mongodb://mongo
      # Make sure MongoDB instances run on storage{1..3} nodes, as close
      # as possible to Longhorn instances
      tolerations:
      - key: dedicated
        operator: Equal
        value: storage
        effect: NoSchedule
      nodeSelector:
        dedicated: storage
      volumes:
      - name: tmp
        emptyDir: {}
  volumeClaimTemplates:
  - metadata:
      name: mongo-data
    spec:
      storageClassName: longhorn
      accessModes:
        - ReadWriteOnce
      resources:
        requests:
          storage: 10Gi
---
apiVersion: v1
kind: Service
metadata:
  name: mongo-exporter
  annotations:
    prometheus.io/scrape: 'true'
spec:
  ports:
    - protocol: TCP
      port: 9216
  selector:
    app: mongo
---
apiVersion: batch/v1
kind: Job
metadata:
  name: mongo-rs0-init
spec:
  template:
    spec:
      containers:
      - name: mongo-rs0-init
        image: mongo
        command: ["mongo", "--eval", "rs.initiate();", "mongodb://mongo-0.mongo"]
      restartPolicy: OnFailure
  backoffLimit: 4