# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "xray.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
The xray-analysis name
*/}}
{{- define "xray-analysis.name" -}}
{{- default .Chart.Name .Values.analysis.name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
The xray-indexer name
*/}}
{{- define "xray-indexer.name" -}}
{{- default .Chart.Name .Values.indexer.name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
The xray-persist name
*/}}
{{- define "xray-persist.name" -}}
{{- default .Chart.Name .Values.persist.name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
The xray-server name
*/}}
{{- define "xray-server.name" -}}
{{- default .Chart.Name .Values.server.name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "xray.fullname" -}}
{{- if .Values.fullnameOverride -}}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "xray-analysis.fullname" -}}
{{- if .Values.analysis.fullnameOverride -}}
{{- .Values.analysis.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.analysis.name -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "xray-indexer.fullname" -}}
{{- if .Values.indexer.fullnameOverride -}}
{{- .Values.indexer.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.indexer.name -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "xray-persist.fullname" -}}
{{- if .Values.persist.fullnameOverride -}}
{{- .Values.persist.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.persist.name -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "xray-server.fullname" -}}
{{- if .Values.server.fullnameOverride -}}
{{- .Values.server.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.server.name -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}

{{/*
Create the name of the service account to use
*/}}
{{- define "xray.serviceAccountName" -}}
{{- if .Values.serviceAccount.create -}}
{{ default (include "xray.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
{{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "xray.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}} # ingress.yaml
{{- if .Values.ingress.enabled -}}
{{- $serviceName := include "xray-server.fullname" . -}}
{{- $servicePort := .Values.server.externalPort -}}
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: {{ template "xray.fullname" . }}
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
  annotations:
    {{- range $key, $value := .Values.ingress.annotations }}
      {{ $key }}: {{ $value | quote }}
    {{- end }}
spec:
  backend:
    serviceName: {{ $serviceName }}
    servicePort: {{ $servicePort }}
{{- if .Values.ingress.hosts }}
  rules:
  {{- range $host := .Values.ingress.hosts }}
  - host: {{ $host }}
    http:
      paths:
        - path: /
          backend:
            serviceName: {{ $serviceName }}
            servicePort: {{ $servicePort }}
  {{- end -}}
{{- end -}}
  {{- if .Values.ingress.tls }}
  tls:
{{ toYaml .Values.ingress.tls | indent 4 }}
  {{- end -}}
{{- end -}}
 # rabbitmq-ha-configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "xray.fullname" . }}-rabbitmq-ha
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
data:
  enabled_plugins: |
    [
      rabbitmq_consistent_hash_exchange,
      rabbitmq_federation,
      rabbitmq_federation_management,
      rabbitmq_management,
      rabbitmq_peer_discovery_k8s,
      rabbitmq_shovel,
      rabbitmq_shovel_management
    ].

  rabbitmq.conf: |
    ## RabbitMQ configuration
    ## Ref: https://github.com/rabbitmq/rabbitmq-server/blob/master/docs/rabbitmq.conf.example

    ## Clustering
    cluster_formation.peer_discovery_backend  = rabbit_peer_discovery_k8s
    cluster_formation.k8s.host = kubernetes.default.svc.cluster.local
    cluster_formation.k8s.address_type = hostname
    cluster_formation.node_cleanup.interval = 10
    cluster_formation.node_cleanup.only_log_warning = false
    cluster_partition_handling = autoheal

    ## The default "guest" user is only permitted to access the server
    ## via a loopback interface (e.g. localhost)
    loopback_users.guest = false

    ## Memory-based Flow Control threshold
    vm_memory_high_watermark.absolute = {{ index .Values "rabbitmq-ha" "rabbitmqMemoryHighWatermark" }}

    management.load_definitions = /etc/rabbitmq/definitions.json
  definitions.json: |
    {
      "users": [
        {
          "name": "{{ index .Values "rabbitmq-ha" "rabbitmqUsername" }}",
          "password": "{{ index .Values "rabbitmq-ha" "rabbitmqPassword" }}",
          "tags": "administrator"
        }
      ],
      "permissions": [
        {
          "configure": ".*",
          "read": ".*",
          "user": "{{ index .Values "rabbitmq-ha" "rabbitmqUsername" }}",
          "vhost": "/",
          "write": ".*"
        }
      ],
      "policies": [
        {
          "apply-to": "all",
          "definition": {
            "ha-mode": "all",
            "ha-sync-mode": "automatic"
          },
          "name": "ha-all",
          "pattern": ".",
          "priority": 0,
          "vhost": "/"
        }
      ],
      "vhosts": [
        {
          "name": "/"
        }
      ]
    }
 # xray-analysis-deployment.yaml
apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {{ template "xray-analysis.fullname" . }}
  labels:
    app: {{ template "xray-analysis.name" . }}
    chart: {{ template "xray.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
    component: {{ .Values.analysis.name }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app: {{ template "xray.name" . }}
      release: {{ .Release.Name }}
      component: {{ .Values.analysis.name }}
  template:
    metadata:
      labels:
        app: {{ template "xray.name" . }}
        release: {{ .Release.Name }}
        component: {{ .Values.analysis.name }}
    spec:
    {{- if .Values.imagePullSecrets }}
      imagePullSecrets:
      - name: {{ .Values.imagePullSecrets }}
    {{- end }}
      serviceAccountName: {{ template "xray.serviceAccountName" . }}
      securityContext:
        runAsUser: {{ .Values.common.xrayUserId }}
        fsGroup: {{ .Values.common.xrayGroupId }}
      initContainers:
      - name: init-wait
        image: {{ .Values.initContainerImage | quote }}
        env:
        {{- if .Values.mongodb.enabled }}
        - name: MONGODB_USER
          value: {{ .Values.mongodb.mongodbUsername }}
        - name: MONGODB_DATABASE
          value: {{ .Values.mongodb.mongodbDatabase }}
        - name: MONGODB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-mongodb
              key: mongodb-password
        {{- else }}
        - name: MONGODB_URL
          value: {{ .Values.global.mongoUrl }}
        {{- end }}
        {{- if .Values.postgresql.enabled }}
        - name: POSTGRES_USER
          value: {{ .Values.postgresql.postgresUser }}
        - name: POSTGRESS_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-postgresql
              key: postgres-password
        - name: POSTGRESS_DB
          value: {{ .Values.postgresql.postgresDatabase }}
        {{- else }}
        - name: POSTGRESS_URL
          value: {{ .Values.global.postgresqlUrl }}
        {{- end }}
        - name: RABBITMQ_USER
          value: {{ index .Values "rabbitmq-ha" "rabbitmqUsername" }}
        - name: RABBITMQ_ERLANG_COOKIE
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-rabbitmq-ha
              key: rabbitmq-erlang-cookie
        - name: RABBITMQ_DEFAULT_PASS
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-rabbitmq-ha
              key: rabbitmq-password
        command:
        - '/bin/sh'
        - '-c'
        - >
          cp -fv /scripts/setup.sh {{ .Values.common.xrayConfigPath }};
          chmod +x {{ .Values.common.xrayConfigPath }}/setup.sh;
          {{ .Values.common.xrayConfigPath }}/setup.sh;
        volumeMounts:
        - name: data-volume
          mountPath: "{{ .Values.common.xrayConfigPath }}"
        - name: setup
          mountPath: "/scripts"
      containers:
      - name: {{ .Values.analysis.name }}
        image: {{ .Values.analysis.image }}:{{ default .Chart.AppVersion .Values.common.xrayVersion }}
        imagePullPolicy: {{ .Values.imagePullPolicy }}
        env:
        - name: XRAYCONFIGPATH
          value: "{{ .Values.common.xrayConfigPath }}"
        - name: XRAY_MASTER_KEY
          valueFrom:
            secretKeyRef:
              name: {{ template "xray.fullname" . }}-master-key
              key: master-key
        - name: XRAY_HA_NODE_ID
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        ports:
        - containerPort: {{ .Values.analysis.internalPort }}
        volumeMounts:
        - name: data-volume
          mountPath: "{{ .Values.common.xrayConfigPath }}"
        securityContext:
          allowPrivilegeEscalation: false
        resources:
{{ toYaml .Values.analysis.resources | indent 10 }}
        readinessProbe:
          httpGet:
            path: /debug/pprof/
            port: {{ .Values.analysis.internalPort }}
          initialDelaySeconds: 60
          periodSeconds: 10
          failureThreshold: 10
        livenessProbe:
          httpGet:
            path: /debug/pprof/
            port: {{ .Values.analysis.internalPort }}
          initialDelaySeconds: 90
          periodSeconds: 10
      volumes:
      - name: data-volume
        emptyDir:
          sizeLimit: {{ .Values.analysis.storage.sizeLimit }}
      - name: config-volume
        emptyDir:
          sizeLimit: 1Gi
      - name: setup
        configMap:
          name: {{ template "xray.fullname" . }}-setup
 # xray-analysis-svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ template "xray-analysis.fullname" . }}
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    component: {{ .Values.analysis.name }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
spec:
  type: {{ .Values.analysis.service.type }}
  ports:
  - port: {{ .Values.analysis.internalPort }}
    protocol: TCP
    name: http
    targetPort: {{ .Values.analysis.externalPort }}
  selector:
    app: {{ template "xray.name" . }}
    component: {{ .Values.analysis.name }}
    release: {{ .Release.Name }} # xray-indexer-deployment.yaml
apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {{ template "xray-indexer.fullname" . }}
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
    component: {{ .Values.indexer.name }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app: {{ template "xray.name" . }}
      release: {{ .Release.Name }}
      component: {{ .Values.indexer.name }}
  template:
    metadata:
      labels:
        app: {{ template "xray.name" . }}
        release: {{ .Release.Name }}
        component: {{ .Values.indexer.name }}
    spec:
    {{- if .Values.imagePullSecrets }}
      imagePullSecrets:
      - name: {{ .Values.imagePullSecrets }}
    {{- end }}
      serviceAccountName: {{ template "xray.serviceAccountName" . }}
      securityContext:
        runAsUser: {{ .Values.common.xrayUserId }}
        fsGroup: {{ .Values.common.xrayGroupId }}
      initContainers:
      - name: init-wait
        image: {{ .Values.initContainerImage | quote }}
        env:
        {{- if .Values.mongodb.enabled }}
        - name: MONGODB_USER
          value: {{ .Values.mongodb.mongodbUsername }}
        - name: MONGODB_DATABASE
          value: {{ .Values.mongodb.mongodbDatabase }}
        - name: MONGODB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-mongodb
              key: mongodb-password
        {{- else }}
        - name: MONGODB_URL
          value: {{ .Values.global.mongoUrl }}
        {{- end }}
        {{- if .Values.postgresql.enabled }}
        - name: POSTGRES_USER
          value: {{ .Values.postgresql.postgresUser }}
        - name: POSTGRESS_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-postgresql
              key: postgres-password
        - name: POSTGRESS_DB
          value: {{ .Values.postgresql.postgresDatabase }}
        {{- else }}
        - name: POSTGRESS_URL
          value: {{ .Values.global.postgresqlUrl }}
        {{- end }}
        - name: RABBITMQ_USER
          value: {{ index .Values "rabbitmq-ha" "rabbitmqUsername" }}
        - name: RABBITMQ_ERLANG_COOKIE
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-rabbitmq-ha
              key: rabbitmq-erlang-cookie
        - name: RABBITMQ_DEFAULT_PASS
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-rabbitmq-ha
              key: rabbitmq-password
        command:
        - '/bin/sh'
        - '-c'
        - >
          cp -fv /scripts/setup.sh {{ .Values.common.xrayConfigPath }};
          chmod +x {{ .Values.common.xrayConfigPath }}/setup.sh;
          {{ .Values.common.xrayConfigPath }}/setup.sh;
        volumeMounts:
        - name: data-volume
          mountPath: "{{ .Values.common.xrayConfigPath }}"
        - name: setup
          mountPath: "/scripts"
      containers:
      - name: {{ .Values.indexer.name }}
        image: {{ .Values.indexer.image }}:{{ default .Chart.AppVersion .Values.common.xrayVersion }}
        imagePullPolicy: {{ .Values.imagePullPolicy }}
        env:
        - name: XRAYCONFIGPATH
          value: "{{ .Values.common.xrayConfigPath }}"
        - name: XRAY_MASTER_KEY
          valueFrom:
            secretKeyRef:
              name: {{ template "xray.fullname" . }}-master-key
              key: master-key
        - name: XRAY_HA_NODE_ID
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        ports:
        - containerPort: {{ .Values.indexer.internalPort }}
        volumeMounts:
        - name: data-volume
          mountPath: "{{ .Values.common.xrayConfigPath }}"
        securityContext:
          allowPrivilegeEscalation: false
        resources:
{{ toYaml .Values.indexer.resources | indent 10 }}
        readinessProbe:
          httpGet:
            path: /debug/pprof/
            port: {{ .Values.indexer.internalPort }}
          initialDelaySeconds: 60
          periodSeconds: 10
          failureThreshold: 10
        livenessProbe:
          httpGet:
            path: /debug/pprof/
            port: {{ .Values.indexer.internalPort }}
          initialDelaySeconds: 90
          periodSeconds: 10
      volumes:
      - name: data-volume
        emptyDir:
          sizeLimit: {{ .Values.indexer.storage.sizeLimit }}
      - name: config-volume
        emptyDir:
          sizeLimit: 1Gi
      - name: setup
        configMap:
          name: {{ template "xray.fullname" . }}-setup
 # xray-indexer-svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ template "xray-indexer.fullname" . }}
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    component: {{ .Values.indexer.name }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
spec:
  type: {{ .Values.indexer.service.type }}
  ports:
  - port: {{ .Values.indexer.internalPort }}
    protocol: TCP
    name: http
    targetPort: {{ .Values.indexer.externalPort }}
  selector:
    app: {{ template "xray.name" . }}
    component: {{ .Values.indexer.name }}
    release: {{ .Release.Name }} # xray-master-key.yaml
apiVersion: v1
kind: Secret
metadata:
  name: {{ template "xray.fullname" . }}-master-key
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
type: Opaque
data:
  master-key: {{ .Values.common.masterKey | b64enc | quote }}

 # xray-persist-deployment.yaml
apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {{ template "xray-persist.fullname" . }}
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
    component: {{ .Values.persist.name }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app: {{ template "xray.name" . }}
      release: {{ .Release.Name }}
      component: {{ .Values.persist.name }}
  template:
    metadata:
      labels:
        app: {{ template "xray.name" . }}
        release: {{ .Release.Name }}
        component: {{ .Values.persist.name }}
    spec:
    {{- if .Values.imagePullSecrets }}
      imagePullSecrets:
      - name: {{ .Values.imagePullSecrets }}
    {{- end }}
      serviceAccountName: {{ template "xray.serviceAccountName" . }}
      securityContext:
        runAsUser: {{ .Values.common.xrayUserId }}
        fsGroup: {{ .Values.common.xrayGroupId }}
      initContainers:
      - name: init-wait
        image: {{ .Values.initContainerImage | quote }}
        env:
        {{- if .Values.mongodb.enabled }}
        - name: MONGODB_USER
          value: {{ .Values.mongodb.mongodbUsername }}
        - name: MONGODB_DATABASE
          value: {{ .Values.mongodb.mongodbDatabase }}
        - name: MONGODB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-mongodb
              key: mongodb-password
        {{- else }}
        - name: MONGODB_URL
          value: {{ .Values.global.mongoUrl }}
        {{- end }}
        {{- if .Values.postgresql.enabled }}
        - name: POSTGRES_USER
          value: {{ .Values.postgresql.postgresUser }}
        - name: POSTGRESS_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-postgresql
              key: postgres-password
        - name: POSTGRESS_DB
          value: {{ .Values.postgresql.postgresDatabase }}
        {{- else }}
        - name: POSTGRESS_URL
          value: {{ .Values.global.postgresqlUrl }}
        {{- end }}
        - name: RABBITMQ_USER
          value: {{ index .Values "rabbitmq-ha" "rabbitmqUsername" }}
        - name: RABBITMQ_ERLANG_COOKIE
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-rabbitmq-ha
              key: rabbitmq-erlang-cookie
        - name: RABBITMQ_DEFAULT_PASS
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-rabbitmq-ha
              key: rabbitmq-password
        command:
        - '/bin/sh'
        - '-c'
        - >
          cp -fv /scripts/setup.sh {{ .Values.common.xrayConfigPath }};
          chmod +x {{ .Values.common.xrayConfigPath }}/setup.sh;
          {{ .Values.common.xrayConfigPath }}/setup.sh;
        volumeMounts:
        - name: data-volume
          mountPath: "{{ .Values.common.xrayConfigPath }}"
        - name: setup
          mountPath: "/scripts"
      containers:
      - name: {{ .Values.persist.name }}
        image: {{ .Values.persist.image }}:{{ default .Chart.AppVersion .Values.common.xrayVersion }}
        imagePullPolicy: {{ .Values.imagePullPolicy }}
        env:
        - name: XRAYCONFIGPATH
          value: "{{ .Values.common.xrayConfigPath }}"
        - name: XRAY_MASTER_KEY
          valueFrom:
            secretKeyRef:
              name: {{ template "xray.fullname" . }}-master-key
              key: master-key
        - name: XRAY_HA_NODE_ID
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        ports:
        - containerPort: {{ .Values.persist.internalPort }}
        volumeMounts:
        - name: data-volume
          mountPath: "{{ .Values.common.xrayConfigPath }}"
        securityContext:
          allowPrivilegeEscalation: false
        resources:
{{ toYaml .Values.persist.resources | indent 10 }}
        readinessProbe:
          httpGet:
            path: /debug/pprof/
            port: {{ .Values.persist.internalPort }}
          initialDelaySeconds: 60
          periodSeconds: 10
          failureThreshold: 10
        livenessProbe:
          httpGet:
            path: /debug/pprof/
            port: {{ .Values.persist.internalPort }}
          initialDelaySeconds: 90
          periodSeconds: 10
      volumes:
      - name: data-volume
        emptyDir:
          sizeLimit: {{ .Values.persist.storage.sizeLimit }}
      - name: config-volume
        emptyDir:
          sizeLimit: 1Gi
      - name: setup
        configMap:
          name: {{ template "xray.fullname" . }}-setup
 # xray-persist-svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ template "xray-persist.fullname" . }}
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    component: {{ .Values.persist.name }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
spec:
  type: {{ .Values.indexer.service.type }}
  ports:
  - port: {{ .Values.persist.internalPort }}
    protocol: TCP
    name: http
    targetPort: {{ .Values.persist.externalPort }}
  selector:
    app: {{ template "xray.name" . }}
    component: {{ .Values.persist.name }}
    release: {{ .Release.Name }} # xray-role.yaml
{{- if .Values.rbac.create }}
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    release: {{ .Release.Name | quote }}
    heritage: {{ .Release.Service | quote }}
  name: {{ template "xray.fullname" . }}
rules:
{{ toYaml .Values.rbac.role.rules }}
{{- end }}
 # xray-rolebinding.yaml
{{- if .Values.rbac.create }}
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    release: {{ .Release.Name | quote }}
    heritage: {{ .Release.Service | quote }}
  name: {{ template "xray.fullname" . }}
subjects:
- kind: ServiceAccount
  name: {{ template "xray.serviceAccountName" . }}
roleRef:
  kind: Role
  apiGroup: rbac.authorization.k8s.io
  name: {{ template "xray.fullname" . }}
{{- end }}
 # xray-server-deployment.yaml
apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {{ template "xray-server.fullname" . }}
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
    component: {{ .Values.server.name }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app: {{ template "xray.name" . }}
      release: {{ .Release.Name }}
      component: {{ .Values.server.name }}
  template:
    metadata:
      labels:
        app: {{ template "xray.name" . }}
        release: {{ .Release.Name }}
        component: {{ .Values.server.name }}
    spec:
    {{- if .Values.imagePullSecrets }}
      imagePullSecrets:
      - name: {{ .Values.imagePullSecrets }}
    {{- end }}
      serviceAccountName: {{ template "xray.serviceAccountName" . }}
      securityContext:
        runAsUser: {{ .Values.common.xrayUserId }}
        fsGroup: {{ .Values.common.xrayGroupId }}
      initContainers:
      - name: init-wait
        image: {{ .Values.initContainerImage | quote }}
        env:
        {{- if .Values.mongodb.enabled }}
        - name: MONGODB_USER
          value: {{ .Values.mongodb.mongodbUsername }}
        - name: MONGODB_DATABASE
          value: {{ .Values.mongodb.mongodbDatabase }}
        - name: MONGODB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-mongodb
              key: mongodb-password
        {{- else }}
        - name: MONGODB_URL
          value: {{ .Values.global.mongoUrl }}
        {{- end }}
        {{- if .Values.postgresql.enabled }}
        - name: POSTGRES_USER
          value: {{ .Values.postgresql.postgresUser }}
        - name: POSTGRESS_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-postgresql
              key: postgres-password
        - name: POSTGRESS_DB
          value: {{ .Values.postgresql.postgresDatabase }}
        {{- else }}
        - name: POSTGRESS_URL
          value: {{ .Values.global.postgresqlUrl }}
        {{- end }}
        - name: RABBITMQ_USER
          value: {{ index .Values "rabbitmq-ha" "rabbitmqUsername" }}
        - name: RABBITMQ_ERLANG_COOKIE
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-rabbitmq-ha
              key: rabbitmq-erlang-cookie
        - name: RABBITMQ_DEFAULT_PASS
          valueFrom:
            secretKeyRef:
              name: {{ .Release.Name }}-rabbitmq-ha
              key: rabbitmq-password
        command:
        - '/bin/sh'
        - '-c'
        - >
          cp -fv /scripts/setup.sh {{ .Values.common.xrayConfigPath }};
          chmod +x {{ .Values.common.xrayConfigPath }}/setup.sh;
          {{ .Values.common.xrayConfigPath }}/setup.sh;
        volumeMounts:
        - name: data-volume
          mountPath: "{{ .Values.common.xrayConfigPath }}"
        - name: setup
          mountPath: "/scripts"
      containers:
      - name: {{ .Values.server.name }}
        image: {{ .Values.server.image }}:{{ default .Chart.AppVersion .Values.common.xrayVersion }}
        imagePullPolicy: {{ .Values.imagePullPolicy }}
        env:
        - name: XRAYCONFIGPATH
          value: "{{ .Values.common.xrayConfigPath }}"
        - name: XRAY_MASTER_KEY
          valueFrom:
            secretKeyRef:
              name: {{ template "xray.fullname" . }}-master-key
              key: master-key
        - name: XRAY_HA_NODE_ID
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        ports:
        - containerPort: {{ .Values.server.internalPort }}
        volumeMounts:
        - name: data-volume
          mountPath: "{{ .Values.common.xrayConfigPath }}"
        securityContext:
          allowPrivilegeEscalation: false
        resources:
{{ toYaml .Values.server.resources | indent 10 }}
        readinessProbe:
          httpGet:
            path: /
            port: {{ .Values.server.internalPort }}
          initialDelaySeconds: 60
          periodSeconds: 10
          failureThreshold: 10
        livenessProbe:
          httpGet:
            path: /
            port: {{ .Values.server.internalPort }}
          initialDelaySeconds: 90
          periodSeconds: 10
      volumes:
      - name: data-volume
        emptyDir:
          sizeLimit: {{ .Values.server.storage.sizeLimit }}
      - name: config-volume
        emptyDir:
          sizeLimit: 1Gi
      - name: setup
        configMap:
          name: {{ template "xray.fullname" . }}-setup
 # xray-server-svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ template "xray-server.fullname" . }}
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    component: {{ .Values.server.name }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
spec:
  type: {{ .Values.server.service.type }}
{{- if .Values.server.loadBalancerSourceRanges }}
  loadBalancerSourceRanges:
{{ toYaml .Values.server.loadBalancerSourceRanges | indent 4 }}
{{- end }}
  ports:
  - port: {{ .Values.server.externalPort }}
    protocol: TCP
    name: http
    targetPort: {{ .Values.server.internalPort }}
  selector:
    app: {{ template "xray.name" . }}
    component: {{ .Values.server.name }}
    release: {{ .Release.Name }} # xray-serviceaccount.yaml
{{- if .Values.serviceAccount.create }}
apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    release: {{ .Release.Name | quote }}
    heritage: {{ .Release.Service | quote }}
  name: {{ template "xray.serviceAccountName" . }}
{{- end }}
 # xray-setup-conf.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "xray.fullname" . }}-setup
  labels:
    app: {{ template "xray.name" . }}
    chart: {{ template "xray.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
data:
  setup.sh: |
    #!/bin/sh
    # Setup script for Xray microservice

    SCRIPTS_DIR=/scripts
    XRAYCONFIGPATH={{ .Values.common.xrayConfigPath }}
    XRAY_CONFIG_DIR=${XRAYCONFIGPATH}/config
    XRAY_CONFIG_FILE=${XRAY_CONFIG_DIR}/xray_config.yaml

    echo "Creating directories"
    mkdir -pv ${XRAY_CONFIG_DIR}

    # Wait for DBs to be ready
    echo "Waiting for DBs..."
    {{- if .Values.mongodb.enabled }}
    until nc -z -w 2 {{ .Release.Name }}-postgresql {{ .Values.postgresql.service.port }} && echo postgresql ok; do
      sleep 2;
    done;
    {{- end }}
    {{- if .Values.postgresql.enabled }}
    until nc -z -w 2 {{ .Release.Name }}-mongodb 27017 && echo mongodb ok; do
      sleep 2;
    done;
    {{- end }}
    until nc -z -w 2 {{ .Release.Name }}-rabbitmq-ha {{ index .Values "rabbitmq-ha" "rabbitmqNodePort" }} && echo rabbitmq ok; do
      sleep 2;
    done;

    # Prepare Xray config
    echo "Preparing Xray config (${XRAY_CONFIG_FILE})"
    if [ -f ${XRAY_CONFIG_FILE} ]; then
      echo "Config exist. Backing it up..."
      cp -vf ${XRAY_CONFIG_FILE} ${XRAY_CONFIG_FILE}-$(date +%Y%m%d-%H%M%S)
    fi

    # Creating Mongodb URL
    {{- if .Values.mongodb.enabled }}
    MONGODB_URL="mongodb://${MONGODB_USER}:${MONGODB_PASSWORD}@{{ .Release.Name }}-mongodb:27017/?authSource=${MONGODB_DATABASE}\&authMechanism=SCRAM-SHA-1"
    {{- else }}
    MONGODB_URL="${MONGODB_URL}"
    {{- end }}

    # Creating PostgreSQL URL
    {{- if .Values.postgresql.enabled }}
    POSTGRESS_URL="postgres://${POSTGRES_USER}:${POSTGRESS_PASSWORD}@{{ .Release.Name }}-postgresql:{{ .Values.postgresql.service.port }}/${POSTGRESS_DB}?sslmode=disable"
    {{- else }}
    POSTGRESS_URL="${POSTGRESS_URL}"
    {{- end }}

    # Creating Rabbitmq-Ha URL
    RABBITMQ_URL="amqp://${RABBITMQ_USER}:${RABBITMQ_DEFAULT_PASS}@{{ .Release.Name }}-rabbitmq-ha:{{ index .Values "rabbitmq-ha" "rabbitmqNodePort" }}/"
    cp -vf ${SCRIPTS_DIR}/xray_config.yaml ${XRAY_CONFIG_FILE}

    # Preparing xray_config.yaml
    sed -i "s RABBITMQ_URL ${RABBITMQ_URL} " ${XRAY_CONFIG_FILE}
    sed -i "s MONGODB_URL ${MONGODB_URL} " ${XRAY_CONFIG_FILE}
    sed -i "s POSTGRESS_URL ${POSTGRESS_URL} " ${XRAY_CONFIG_FILE}

  xray_config.yaml: |
    # Generated Xray config
    ---
        ver:            1.0
        XrayServerPort: "{{ .Values.server.internalPort }}"
        mqBaseUrl:      "RABBITMQ_URL"
        mongoUrl:       "MONGODB_URL"
        postgresqlUrl:  "POSTGRESS_URL"
        stdOutEnabled:  {{ .Values.common.stdOutEnabled }}
        skipEntLicCheckForCloud: true
    # End generated config


# Default values for Xray HA.
# This is a YAML-formatted file.
# Beware when changing values here. You should know what you are doing!
# Access the values with {{ .Values.key.subkey }}

# Common
replicaCount: 1
imagePullPolicy: IfNotPresent
initContainerImage: "alpine:3.6"
imagePullSecrets:

## Role Based Access
## Ref: https://kubernetes.io/docs/admin/authorization/rbac/
rbac:
  create: true
  role:
    ## Rules to create. It follows the role specification
    rules:
    - apiGroups:
      - ''
      resources:
      - services
      - endpoints
      - pods
      verbs:
      - get
      - watch
      - list

ingress:
  enabled: false
  # Used to create an Ingress record.
  hosts:
    - xray.domain.example
  annotations:
  # kubernetes.io/ingress.class: nginx
  # kubernetes.io/tls-acme: "true"
  tls:
  # Secrets must be manually created in the namespace.
  # - secretName: chart-example-tls
  #   hosts:
  #     - xray.domain.example

## Service Account
## Ref: https://kubernetes.io/docs/admin/service-accounts-admin/
##
serviceAccount:
  create: true
  ## The name of the ServiceAccount to use.
  ## If not set and create is true, a name is generated using the fullname template
  name:

# PostgreSQL
## Configuration values for the postgresql dependency
## ref: https://github.com/kubernetes/charts/blob/master/stable/postgresql/README.md
##
postgresql:
  enabled: true
  postgresDatabase: "xraydb"
  postgresUser: "xray"
  postgresPassword:
  service:
    port: 5432
  persistence:
    enabled: true
    size: 50Gi
    existingClaim:
  resources:
    requests:
      memory: "1Gi"
      cpu: "250m"
    limits:
      memory: "2Gi"
      cpu: "1"

## Configuration values for the mongodb dependency
## ref: https://github.com/kubernetes/charts/blob/master/stable/mongodb/README.md
##
mongodb:
  enabled: true
  image:
    tag: 3.6.3
    pullPolicy: IfNotPresent
  persistence:
    size: 50Gi
  # resources:
  #  requests:
  #    memory: "12Gi"
  #    cpu: "200m"
  #  limits:
  #    memory: "12Gi"
  #    cpu: "2"
  ## Make sure the --wiredTigerCacheSizeGB is no more than half the memory limit!
  ## This is critical to protect against OOMKill by Kubernetes!
  mongodbExtraFlags:
  - "--wiredTigerCacheSizeGB=1"
  mongodbRootPassword:
  mongodbUsername: xray
  mongodbPassword:
  mongodbDatabase: xray
#  livenessProbe:
#    initialDelaySeconds: 60
#    periodSeconds: 10
#  readinessProbe:
#    initialDelaySeconds: 30
#    periodSeconds: 30

# RabbitMQ HA
## Configuration values for the rabbitmq-ha dependency
## ref: https://github.com/kubernetes/charts/blob/master/stable/rabbitmq-ha/README.md
##
rabbitmq-ha:
  replicaCount: 1
  rabbitmqUsername: "guest"
  rabbitmqPassword:
  customConfigMap: true
  rabbitmqErlangCookie: XRAYRABBITMQCLUSTER
  rabbitmqMemoryHighWatermark: 500MB
  rabbitmqNodePort: 5672
  # resources:
  #  requests:
  #    memory: "250Mi"
  #    cpu: "100m"
  #  limits:
  #    memory: "550Mi"
  #    cpu: "200m"
  persistentVolume:
    enabled: true
    size: 20Gi
  rbac:
    create: true

common:
  ## Note that by default we use appVersion to get image tag
  # xrayVersion: 2.3.0
  xrayConfigPath: /var/opt/jfrog/xray/data
  xrayUserId: 1035
  xrayGroupId: 1035
  stdOutEnabled: true
  ## Xray requires a unique master key
  ## You can generate one with the command:
  ## 'openssl rand -hex 32'
  ## Pass it to helm with '--set common.masterKey=${MASTER_KEY}'
  ## IMPORTANT: You should NOT use the example masterKey for a production deployment!
  masterKey: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF

# For setting up external services, must pass the connection URL for them
global:
  mongoUrl:
  postgresqlUrl:


analysis:
  name: xray-analysis
  image: docker.bintray.io/jfrog/xray-analysis
  internalPort: 7000
  externalPort: 7000
  service:
    type: ClusterIP
  ## Container storage limit
  storage:
    sizeLimit: 10Gi
  resources: {}
  #  requests:
  #    memory: "1Gi"
  #    cpu: "100m"
  #  limits:
  #    memory: "2Gi"
  #    cpu: "1"

indexer:
  name: xray-indexer
  image: docker.bintray.io/jfrog/xray-indexer
  internalPort: 7002
  externalPort: 7002
  service:
    type: ClusterIP
  ## Container storage limit
  storage:
    sizeLimit: 10Gi
  resources: {}
  #  requests:
  #    memory: "1Gi"
  #    cpu: "100m"
  #  limits:
  #    memory: "2Gi"
  #    cpu: "1"

persist:
  name: xray-persist
  image: docker.bintray.io/jfrog/xray-persist
  internalPort: 7003
  externalPort: 7003
  service:
    type: ClusterIP
  ## Container storage limit
  storage:
    sizeLimit: 10Gi
  resources: {}
  #  requests:
  #    memory: "1Gi"
  #    cpu: "100m"
  #  limits:
  #    memory: "2Gi"
  #    cpu: "1"

server:
  name: xray-server
  image: docker.bintray.io/jfrog/xray-server
  internalPort: 8000
  externalPort: 80
  service:
    type: LoadBalancer
    name: xray
  ## Container storage limit
  storage:
    sizeLimit: 10Gi
  # Whitelist IPs allowed to LoadBalancer type services
  # Example: loadBalancerSourceRanges={82.82.190.51/32,141.141.8.8/32}
  loadBalancerSourceRanges: []
  resources: {}
  #  requests:
  #    memory: "1Gi"
  #    cpu: "100m"
  #  limits:
  #    memory: "2Gi"
  #    cpu: "1"
