# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "superset.name" -}}
{{- default .Chart.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 "superset.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 chart name and version as used by the chart label.
*/}}
{{- define "superset.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}
 # deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "superset.fullname" . }}
  labels:
    app: {{ include "superset.name" . }}
    chart: {{ include "superset.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app: {{ include "superset.name" . }}
      release: {{ .Release.Name }}
  template:
    metadata:
      name: {{ include "superset.fullname" . }}
      labels:
        app: {{ include "superset.name" . }}
        chart: {{ include "superset.chart" . }}
        release: {{ .Release.Name }}
        heritage: {{ .Release.Service }}
      annotations:
        checksum/secrets: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }}
        {{- with .Values.deploymentAnnotations }}
        {{- . | toYaml | nindent 8 }}
        {{- end }}
    spec:
      securityContext:
        runAsUser: 1000
        fsGroup: 1000
      volumes:
        - name: superset-configs
          secret:
            secretName: {{ include "superset.fullname" . }}
        - name: storage-volume
          {{- if .Values.persistence.enabled }}
          persistentVolumeClaim:
            claimName: {{ .Values.persistence.existingClaim | default (include "superset.fullname" .) }}
          {{- else }}
          emptyDir: {}
          {{- end }}
      {{- if .Values.image.pullSecrets }}
      imagePullSecrets:
{{ toYaml .Values.image.pullSecrets | indent 8 }}
      {{- end }}
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          command: ["/usr/bin/env"]
          args:
          - bash
          - /home/superset/init_superset.sh
          {{- range .Values.extraArguments }}
          - {{ . }}
          {{- end }}
          volumeMounts:
            - name: superset-configs
              mountPath: /home/superset
            - name: storage-volume
              mountPath: /var/lib/superset
          ports:
            - name: http
              containerPort: 8088
              protocol: TCP
          {{- if .Values.extraEnv }}
          env:
            {{- range $key, $value := .Values.extraEnv }}
            - name: "{{ $key }}"
              value: "{{ $value }}"
            {{- end }}
          {{- end }}
          {{- if .Values.extraEnvFromSecret }}
          envFrom:
            - secretRef:
                name: {{ .Values.extraEnvFromSecret }}
          {{- end }}
          {{- with .Values.resources }}
          resources:
            {{- . | toYaml | nindent 12 }}
          {{- end }}
          {{- with .Values.livenessProbe }}
          livenessProbe:
            {{- . | toYaml | nindent 12 }}
          {{- end }}
          {{- with .Values.readinessProbe }}
          readinessProbe:
            {{- . | toYaml | nindent 12 }}
          {{- end }}
      {{- with .Values.nodeSelector }}
      nodeSelector:
        {{- . | toYaml | nindent 8 }}
      {{- end }}
      {{- with .Values.affinity }}
      affinity:
        {{- . | toYaml | nindent 8 }}
      {{- end }}
      {{- with .Values.tolerations }}
      tolerations:
        {{- . | toYaml | nindent 8 }}
      {{- end }}
 # ingress.yaml
{{- if .Values.ingress.enabled -}}
{{- $fullName := include "superset.fullname" . -}}
{{- $ingressPath := .Values.ingress.path -}}
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: {{ $fullName }}
  labels:
    app: {{ include "superset.name" . }}
    chart: {{ include "superset.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
  {{- with .Values.ingress.annotations }}
  annotations:
    {{- . | toYaml | nindent 4 }}
  {{- end }}
spec:
  {{- if .Values.ingress.tls }}
  tls:
    {{- range .Values.ingress.tls }}
    - hosts:
        {{- range .hosts }}
        - {{ . }}
        {{- end }}
      secretName: {{ .secretName }}
    {{- end }}
  {{- end }}
  rules:
    {{- range .Values.ingress.hosts }}
    - host: {{ . }}
      http:
        paths:
          - path: {{ $ingressPath }}
            backend:
              serviceName: {{ $fullName }}
              servicePort: http
    {{- end }}
{{- end }}
 # pvc.yaml
{{- if .Values.persistence.enabled -}}
{{- if not .Values.persistence.existingClaim -}}
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: {{ include "superset.fullname" . }}
  labels:
    app: {{ include "superset.name" . }}
    chart: {{ include "superset.chart" . }}
    release: {{ .Release.Name }}
spec:
  accessModes:
    {{- .Values.persistence.accessModes | toYaml | nindent 4 }}
  {{- if .Values.persistence.storageClass }}
  {{- if (eq "-" .Values.persistence.storageClass) }}
  storageClassName: ""
  {{- else }}
  storageClassName: "{{ .Values.persistence.storageClass }}"
  {{- end }}
  {{- end }}
  resources:
    requests:
      storage: "{{ .Values.persistence.size }}"
{{- end }}
{{- end }}
 # secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: {{ include "superset.fullname" . }}
  labels:
    app: {{ include "superset.name" . }}
    chart: {{ include "superset.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
type: Opaque
data:
  init_superset.sh: {{ .Values.initFile | b64enc | quote }}
  superset_config.py: {{ .Values.configFile | b64enc | quote }}
  {{- range $key, $value := .Values.extraConfigFiles }}
  {{ $key }}: {{ $value | b64enc | quote }}
  {{- end }}
 # svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ include "superset.fullname" . }}
  labels:
    app: {{ include "superset.name" . }}
    chart: {{ include "superset.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
  {{- if .Values.service.annotations }}
  annotations:
    {{- .Values.service.annotations | toYaml | nindent 4 }}
  {{- end }}
spec:
  {{- if (or (eq .Values.service.type "ClusterIP") (empty .Values.service.type)) }}
  type: ClusterIP
  {{- if .Values.service.clusterIP }}
  clusterIP: {{ .Values.service.clusterIP }}
  {{- end }}
  {{- else if eq .Values.service.type "LoadBalancer" }}
  type: {{ .Values.service.type }}
  {{- if .Values.service.loadBalancerIP }}
  loadBalancerIP: {{ .Values.service.loadBalancerIP }}
  {{- end }}
  {{- if .Values.service.loadBalancerSourceRanges }}
  loadBalancerSourceRanges:
  {{- .Values.service.loadBalancerSourceRanges | toYaml | nindent 4 }}
  {{- end }}
  {{- else }}
  type: {{ .Values.service.type }}
  {{- end }}
  {{- if .Values.service.externalIPs }}
  externalIPs:
    {{- .Values.service.externalIPs | toYaml | nindent 4 }}
  {{- end }}
  ports:
    - name: http
      port: {{ .Values.service.port }}
      targetPort: 8088
      protocol: TCP
      {{- if (and (eq .Values.service.type "NodePort") (not (empty .Values.service.nodePort))) }}
      nodePort: {{.Values.service.nodePort}}
      {{- end }}
  selector:
    app: {{ include "superset.name" . }}
    release: {{ .Release.Name }}

# Default values for superset.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
replicaCount: 1

## Set default image, imageTag, and imagePullPolicy.
image:
  repository: "amancevice/superset"
  tag: "0.36.0"
  pullPolicy: "IfNotPresent"
  pullSecrets: []

initFile: |-
  if [ "$1" == "development-mode" ]; then
    /usr/local/bin/superset-init --username admin --firstname admin --lastname user --email admin@fab.org --password admin
    superset run
  elif [ "$1" == "production-mode" ]; then
    superset db upgrade
    superset init
    gunicorn \
        -w 10 \
        -k gevent \
        --timeout 300 \
        -b  0.0.0.0:8088 \
        --limit-request-line 0 \
        --limit-request-field_size 0 \
        "superset.app:create_app()"
  else
    echo "You need to specify which mode to start in by setting production-mode"
    echo "or development-mode in extraArguments."
    exit 1
  fi

configFile: |-
  #---------------------------------------------------------
  # Superset specific config
  #---------------------------------------------------------
  ROW_LIMIT = 5000
  SUPERSET_WORKERS = 2

  SUPERSET_WEBSERVER_PORT = 8088
  #---------------------------------------------------------

  #---------------------------------------------------------
  # Flask App Builder configuration
  #---------------------------------------------------------
  # Your App secret key
  SECRET_KEY = '\2\1thisismyscretkey\1\2\e\y\y\h'

  # The SQLAlchemy connection string to your database backend
  # This connection defines the path to the database that stores your
  # superset metadata (slices, connections, tables, dashboards, ...).
  # Note that the connection information to connect to the datasources
  # you want to explore are managed directly in the web UI
  SQLALCHEMY_DATABASE_URI = 'sqlite:////var/lib/superset/superset.db'


  # Flask-WTF flag for CSRF
  WTF_CSRF_ENABLED = True
  # Add endpoints that need to be exempt from CSRF protection
  WTF_CSRF_EXEMPT_LIST = []

  # Set this API key to enable Mapbox visualizations
  MAPBOX_API_KEY = ''

## Extra confiuguration files and their content to be made available next to the config file
extraConfigFiles: {}
  ## custom_sso_security_manager.py: |-
  ##   from superset.security import SupersetSecurityManager
  ##   ...

## Extra environment variables that will be passed onto deployment pod
##
extraEnv: {}

## Extra arguments that will be passed to init_superset.sh
## For the sample initFile this is development-mode or production-mode
extraArguments:
- production-mode

## The name of a secret in the same kubernetes namespace which contain values to be added to the environment
## This can be useful for secret keys, etc
##
extraEnvFromSecret: ""

## Deployment level annotations
## Useful for passing other third party annotations to interact with eg. kube2iam.
deploymentAnnotations: {}

persistence:

  ## If true, superset server will create/use a Persistent Volume Claim
    ## If false, use emptyDir
    ##
  enabled: false

  ## superset data Persistent Volume access modes
  ## Must match those of existing PV or dynamic provisioner
  ## Ref: http://kubernetes.io/docs/user-guide/persistent-volumes/
  ##
  accessModes:
    - ReadWriteOnce

  ## superset data Persistent Volume size
  ##
  size: 8Gi

  ## superset server data Persistent Volume Storage Class
  ## If defined, storageClassName: <storageClass>
  ## If set to "-", storageClassName: "", which disables dynamic provisioning
  ## If undefined (the default) or set to null, no storageClassName spec is
  ##   set, choosing the default provisioner.  (gp2 on AWS, standard on
  ##   GKE, AWS & OpenStack)
  ##
  # storageClass: "-"

  ## Superset data Persistent Volume existing claim name
  ## Requires server.persistence.enabled: true
  ## If defined, PVC must be created manually before volume will be bound
  existingClaim: ""

## Expose the superset service to be accessed from outside the cluster (LoadBalancer service).
## or access it from within the cluster (ClusterIP service). Set the service type and the port to serve it.
## ref: http://kubernetes.io/docs/user-guide/services/
##
service:
  type: ClusterIP
  port: 9000

  ## service annotations
  annotations: {}
    # service.beta.kubernetes.io/aws-load-balancer-internal: "true"
    # external-dns.alpha.kubernetes.io/hostname: "superset.domain.com"

  ## loadbalancer source ranges. only used when service.type is "LoadBalancer"
  loadBalancerSourceRanges: []
  # - 172.31.0.0/16


ingress:
  ## If true, superset Ingress will be created
  ##
  enabled: false

  ## superset Ingress annotations
  annotations: {}
  # kubernetes.io/ingress.class: nginx
  # kubernetes.io/tls-acme: 'true'

  ## superset Ingress hostnames
  ## Must be provided if Ingress is enabled
  ##
  hosts:
    - superset.domain.com

  ## superset Ingress path
  ## Optional, allows specifying paths for more flexibility
  ## E.g. Traefik ingress likes paths
  ##
  path: /

  ## superset Ingress TLS configuration
  ## Secrets must be manually created in the namespace
  ##
  tls: []
  #   - secretName: superset-server-tls
  #     hosts:
  #       - superset.domain.com

## Node labels for pod assignment
## Ref: https://kubernetes.io/docs/user-guide/node-selection/
##
nodeSelector: {}

## Tolerations
## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#taints-and-tolerations-beta-feature
tolerations: []

## Affinity and anti-affinity
## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity
affinity: {}

## Configure resource requests and limits
## ref: http://kubernetes.io/docs/user-guide/compute-resources/
##
resources: {}
#  requests:
#    cpu: 50m
#    memory: 256Mi
#  limits:
#    cpu: 500m
#    memory: 750Mi

## Configure liveness/readiness params
## ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/
##
livenessProbe:
  httpGet:
    path: /health
    port: http
  initialDelaySeconds: 80
  timeoutSeconds: 5
  periodSeconds: 10
  failureThreshold: 2
readinessProbe:
  httpGet:
    path: /health
    port: http
  initialDelaySeconds: 30
  timeoutSeconds: 5
  periodSeconds: 10
  failureThreshold: 2
