apiVersion: v1
kind: Namespace
metadata:
  name: db-es
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: elasticsearch
  namespace: db-es
spec:
  serviceName: elasticsearch
  replicas: 1
  selector:
    matchLabels:
      app: elasticsearch
  template:
    metadata:
      labels:
        app: elasticsearch
    spec:
      volumes:
        - name: shared-data
          emptyDir: {}
      securityContext:
        fsGroup: 1000
      initContainers:
        - name: fix-permissions
          image: hub.yizhisec.com/hybridscope/v2/es-init-helper:alpine-3.22.2
          imagePullPolicy: IfNotPresent
          command:
            - /bin/sh
            - -c
          args: 
            - | 
              #/bin/sh
              cp -rf /data/plugins/* /app/shared/
              chown -R 1000:1000 /usr/share/elasticsearch/data           
          volumeMounts:
            - name: es-data
              mountPath: /usr/share/elasticsearch/data
            - name: shared-data
              mountPath: /app/shared
          securityContext:
            runAsUser: 0
      containers:
        - name: elasticsearch
          image: hub.yizhisec.com/external/elasticsearch:7.17.28
          imagePullPolicy: IfNotPresent
          env:
            - name: discovery.type
              value: single-node
            - name: ES_JAVA_OPTS
              value: "-Xms%dg -Xmx%dg"
            - name: node.name
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
          ports:
            - containerPort: 9200
              name: http
            - containerPort: 9300
              name: transport
          volumeMounts:
            - name: es-data
              mountPath: /usr/share/elasticsearch/data
            - name: shared-data
              mountPath: /usr/share/elasticsearch/plugins
          resources:
            requests:
              memory: "%dGi"
              cpu: "%d"
            limits:
              memory: "%dGi"
              cpu: "%d"
  volumeClaimTemplates:
    - metadata:
        name: es-data
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: longhorn
        resources:
          requests:
            storage: %s
---
apiVersion: v1
kind: Service
metadata:
  name: es-service
  namespace: db-es
spec:
  type: ClusterIP
  selector:
    app: elasticsearch
  ports:
    - name: http
      protocol: TCP
      port: 9200
      targetPort: http
    - name: transport
      protocol: TCP
      port: 9300
      targetPort: transport
---
apiVersion: batch/v1
kind: Job
metadata:
  name: es-init-job
  namespace: db-es
spec:
  template:
    spec:
      containers:
        - name: es-init
          image: hub.yizhisec.com/hybridscope/v2/es-init-helper:alpine-3.22.2
          imagePullPolicy: IfNotPresent
          command:
            - /bin/sh
            - /data/create_index.sh
      restartPolicy: Never
  backoffLimit: 2