# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "sysdig.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 "sysdig.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 "sysdig.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

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

{{/*
Return the proper Sysdig Agent image name
*/}}
{{- define "sysdig.image" -}}
{{- $registryName := .Values.image.registry -}}
{{- $repositoryName := .Values.image.repository -}}
{{- $tag := .Values.image.tag | toString -}}
{{/*
Helm 2.11 supports the assignment of a value to a variable defined in a different scope,
but Helm 2.9 and 2.10 doesn't support it, so we need to implement this if-else logic.
Also, we can't use a single if because lazy evaluation is not an option
*/}}
{{- if .Values.image.overrideValue }}
    {{- printf .Values.image.overrideValue -}}
{{- else -}}
    {{- if .Values.slim.enabled }}
    {{- $repositoryName = printf "%s-%s" .Values.image.repository "slim" -}}
    {{- end -}}
    {{- if .Values.global }}
        {{- if .Values.global.imageRegistry }}
            {{- printf "%s/%s:%s" .Values.global.imageRegistry $repositoryName $tag -}}
        {{- else -}}
            {{- printf "%s/%s:%s" $registryName $repositoryName $tag -}}
        {{- end -}}
    {{- else -}}
        {{- printf "%s/%s:%s" $registryName $repositoryName $tag -}}
    {{- end -}}
{{- end -}}
{{- end -}}

{{/*
Return the proper Sysdig Agent image name for module building
*/}}
{{- define "sysdig.image.kmodule" -}}
{{- $registryName := .Values.image.registry -}}
{{- $repositoryName := .Values.slim.kmoduleImage.repository -}}
{{- $tag := .Values.image.tag | toString -}}
{{/*
Helm 2.11 supports the assignment of a value to a variable defined in a different scope,
but Helm 2.9 and 2.10 doesn't support it, so we need to implement this if-else logic.
Also, we can't use a single if because lazy evaluation is not an option
*/}}
{{- if .Values.global }}
    {{- if .Values.global.imageRegistry }}
        {{- printf "%s/%s:%s" .Values.global.imageRegistry $repositoryName $tag -}}
    {{- else -}}
        {{- printf "%s/%s:%s" $registryName $repositoryName $tag -}}
    {{- end -}}
{{- else -}}
    {{- printf "%s/%s:%s" $registryName $repositoryName $tag -}}
{{- end -}}
{{- end -}}

{{/*
Common labels
*/}}
{{- define "sysdig.labels" -}}
app.kubernetes.io/name: {{ include "sysdig.name" . }}
helm.sh/chart: {{ include "sysdig.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end -}}
 # auditsink.yaml
{{- if and .Values.auditLog.enabled .Values.auditLog.dynamicBackend.enabled }}
apiVersion: auditregistration.k8s.io/v1alpha1
kind: AuditSink
metadata:
  name: {{ template "sysdig.fullname" . }}
  labels:
{{ include "sysdig.labels" . | indent 4 }}
spec:
  policy:
    level: RequestResponse
    stages:
      - ResponseComplete
      - ResponseStarted
  webhook:
    throttle:
      qps: 10
      burst: 15
    clientConfig:
      service:
        namespace: {{ .Release.Namespace }}
        name: {{ template "sysdig.fullname" . }}
        port: {{ .Values.auditLog.auditServerPort }}
        path: /k8s_audit
{{- end }}
 # clusterrole.yaml
{{- if .Values.rbac.create }}
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: {{ template "sysdig.fullname" .}}
  labels:
{{ include "sysdig.labels" . | indent 4 }}
rules:
  - apiGroups:
      - ""
    resources:
      - pods
      - replicationcontrollers
      - services
      - events
      - limitranges
      - namespaces
      - nodes
      - resourcequotas
      - persistentvolumes
      - persistentvolumeclaims
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - apps
    resources:
      - daemonsets
      - deployments
      - replicasets
      - statefulsets
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - autoscaling
    resources:
      - horizontalpodautoscalers
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - batch
    resources:
      - cronjobs
      - jobs
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - extensions
    resources:
      - daemonsets
      - deployments
      - ingresses
      - replicasets
    verbs:
      - get
      - list
      - watch
{{- end }}
 # clusterrolebinding.yaml
{{- if .Values.rbac.create }}
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: {{ template "sysdig.fullname" .}}
  labels:
{{ include "sysdig.labels" . | indent 4 }}
subjects:
  - kind: ServiceAccount
    name: {{ template "sysdig.serviceAccountName" .}}
    namespace: {{ .Release.Namespace }}
roleRef:
  kind: ClusterRole
  name: {{ template "sysdig.fullname" .}}
  apiGroup: rbac.authorization.k8s.io
{{- end }}
 # configmap-custom-app-checks.yaml
{{- if .Values.customAppChecks }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "sysdig.fullname" . }}-custom-app-checks
  labels:
{{ include "sysdig.labels" . | indent 4 }}
data:
{{- range $file, $content :=  .Values.customAppChecks }}
  {{ $file }}: |-
{{ $content | indent 4}}
{{- end }}
{{- end }}
 # configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "sysdig.fullname" . }}
  labels:
{{ include "sysdig.labels" . | indent 4 }}
data:
  dragent.yaml: |
    new_k8s: true
{{- if or .Values.secure.enabled .Values.auditLog.enabled }}
    security:
{{- if .Values.auditLog.enabled }}
      k8s_audit_server_url: {{ .Values.auditLog.auditServerUrl }}
      k8s_audit_server_port: {{ .Values.auditLog.auditServerPort }}
{{- end }}
{{- if .Values.secure.enabled }}
      enabled: true
    commandlines_capture:
      enabled: true
    memdump:
      enabled: true
{{- end }}
{{- end }}
{{- if .Values.sysdig.settings }}
{{ toYaml .Values.sysdig.settings | indent 4 }}
{{- end }}
 # daemonset.yaml
{{- if .Values.sysdig.accessKey }}
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: {{ template "sysdig.fullname" . }}
  labels:
{{ include "sysdig.labels" . | indent 4 }}
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "sysdig.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
      name: {{ template "sysdig.fullname" .}}
      labels:
{{ include "sysdig.labels" . | indent 8 }}
      {{- if .Values.daemonset.annotations }}
      annotations:
{{ toYaml .Values.daemonset.annotations | indent 8 }}
      {{- end }}
    spec:
      serviceAccountName: {{ template "sysdig.serviceAccountName" .}}
{{- if .Values.priorityClassName }}
      priorityClassName: "{{ .Values.priorityClassName }}"
{{- end }}
      tolerations:
{{ toYaml .Values.tolerations | indent 8 }}
      hostNetwork: true
      dnsPolicy: ClusterFirstWithHostNet
      hostPID: true
      terminationGracePeriodSeconds: 5
      {{- if .Values.daemonset.affinity }}
      affinity:
{{ toYaml .Values.daemonset.affinity | indent 8 }}
      {{- end }}
      {{- if .Values.image.pullSecrets }}
      imagePullSecrets:
{{ toYaml .Values.image.pullSecrets | indent 8 }}
      {{- end }}
      {{- if .Values.slim.enabled }}
      initContainers:
        - name: sysdig-agent-kmodule
          image: {{ template "sysdig.image.kmodule" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          {{- if .Values.image.pullSecrets }}
          imagePullSecrets:
{{ toYaml .Values.image.pullSecrets | indent 12 }}
          {{- end }}
          securityContext:
            capabilities:
              drop:
                - ALL
            privileged: true
            runAsNonRoot: false
            runAsUser: 0
            readOnlyRootFilesystem: false
            allowPrivilegeEscalation: true
          resources:
{{ toYaml .Values.slim.resources | indent 12 }}
          volumeMounts:
            - mountPath: /etc/modprobe.d
              name: modprobe-d
              readOnly: true
            - mountPath: /host/boot
              name: boot-vol
              readOnly: true
            - mountPath: /host/lib/modules
              name: modules-vol
              readOnly: true
            - mountPath: /host/usr
              name: usr-vol
              readOnly: true
      {{- end }}
      containers:
        - name: {{ .Chart.Name }}
          image: {{ template "sysdig.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          resources:
{{ toYaml .Values.resources | indent 12 }}
          securityContext:
            capabilities:
              drop:
                - ALL
            privileged: true
            runAsNonRoot: false
            runAsUser: 0
            readOnlyRootFilesystem: false
            allowPrivilegeEscalation: true
          env:
            {{- if .Values.ebpf.enabled }}
            - name: SYSDIG_BPF_PROBE
              value:
            {{- end }}
            {{- if .Values.proxy.httpProxy }}
            - name: http_proxy
              value: {{ .Values.proxy.httpProxy }}
            {{- end }}
            {{- if .Values.proxy.httpsProxy }}
            - name: https_proxy
              value: {{ .Values.proxy.httpsProxy }}
            {{- end }}
            {{- if .Values.proxy.noProxy }}
            - name: no_proxy
              value: {{ .Values.proxy.noProxy }}
            {{- end }}
            {{- if .Values.timezone }}
            - name: TZ
              value: {{ .Values.timezone }}
            {{- end }}
            {{- range $key, $value := .Values.daemonset.env }}
            - name: "{{ $key }}"
              value: "{{ $value }}"
            {{- end }}
          readinessProbe:
            exec:
              command: [ "test", "-e", "/opt/draios/logs/running" ]
            initialDelaySeconds: 10
          livenessProbe:
            exec:
              command: [ "test", "-e", "/opt/draios/logs/running" ]
            initialDelaySeconds: 10
          volumeMounts:
            {{- if not .Values.slim.enabled }}
            - mountPath: /etc/modprobe.d
              name: modprobe-d
              readOnly: true
            {{- end }}
            - mountPath: /host/dev
              name: dev-vol
              readOnly: false
            - mountPath: /host/proc
              name: proc-vol
              readOnly: true
            {{- if not .Values.slim.enabled }}
            - mountPath: /host/boot
              name: boot-vol
              readOnly: true
            - mountPath: /host/lib/modules
              name: modules-vol
              readOnly: true
            - mountPath: /host/usr
              name: usr-vol
              readOnly: true
            {{- end }}
            - mountPath: /host/run
              name: run-vol
            - mountPath: /host/var/run
              name: varrun-vol
            - mountPath: /dev/shm
              name: dshm
            - mountPath: /opt/draios/etc/kubernetes/config
              name: sysdig-agent-config
            - mountPath: /opt/draios/etc/kubernetes/secrets
              name: sysdig-agent-secrets
            {{- if (and .Values.ebpf.enabled .Values.ebpf.settings.mountEtcVolume) }}
            - mountPath: /host/etc
              name: etc-fs
              readOnly: true
            {{- end }}
            {{- if .Values.customAppChecks }}
            - mountPath: /opt/draios/lib/python/checks.custom.d
              name: custom-app-checks-volume
            {{- end }}
            - mountPath: /host/etc/os-release
              name: osrel
              readOnly: true
      volumes:
        - name: modprobe-d
          hostPath:
            path: /etc/modprobe.d
        - name: osrel
          hostPath:
            path: /etc/os-release
            type: FileOrCreate
        - name: dshm
          emptyDir:
            medium: Memory
        - name: dev-vol
          hostPath:
            path: /dev
        - name: proc-vol
          hostPath:
            path: /proc
        - name: boot-vol
          hostPath:
            path: /boot
        - name: modules-vol
          hostPath:
            path: /lib/modules
        - name: usr-vol
          hostPath:
            path: /usr
        - name: run-vol
          hostPath:
            path: /run
        - name: varrun-vol
          hostPath:
            path: /var/run
        {{- if (and .Values.ebpf.enabled .Values.ebpf.settings.mountEtcVolume) }}
        - name: etc-fs
          hostPath:
            path: /etc
        {{- end }}
        - name: sysdig-agent-config
          configMap:
            name: {{ template "sysdig.fullname" . }}
            optional: true
        - name: sysdig-agent-secrets
          secret:
            secretName: {{ template "sysdig.fullname" . }}
        {{- if .Values.customAppChecks }}
        - name: custom-app-checks-volume
          configMap:
            name: {{ template "sysdig.fullname" . }}-custom-app-checks
        {{- end }}
  updateStrategy:
{{ toYaml .Values.daemonset.updateStrategy | indent 4 }}
{{- end }}
 # secrets.yaml
{{- if .Values.sysdig.accessKey }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ template "sysdig.fullname" . }}
  labels:
{{ include "sysdig.labels" . | indent 4 }}
type: Opaque
data:
 access-key : {{ required "A valid .Values.sysdig.accessKey is required" .Values.sysdig.accessKey | b64enc | quote }}
{{- end }}
 # securitycontextconstraint.yaml
{{- if .Values.scc.create }}
apiVersion: security.openshift.io/v1
kind: SecurityContextConstraints
metadata:
  annotations:
    kubernetes.io/description: |
      This provides the minimum requirements to the Sysdig agent to run in the Openshift.
  name: {{ template "sysdig.fullname" . }}
  labels:
{{ include "sysdig.labels" . | indent 4 }}
allowHostDirVolumePlugin: true
allowHostIPC: false
allowHostNetwork: true
allowHostPID: true
allowHostPorts: false
allowPrivilegeEscalation: true
allowPrivilegedContainer: true
allowedCapabilities: []
allowedUnsafeSysctls: []
defaultAddCapabilities: []
fsGroup:
  type: RunAsAny
groups: []
priority: 0
readOnlyRootFilesystem: false
requiredDropCapabilities: []
runAsUser:
  type: RunAsAny
seLinuxContext:
  type: RunAsAny
seccompProfiles:
- '*'
supplementalGroups:
  type: RunAsAny
users:
- system:serviceaccount:{{ .Release.Namespace }}:{{ template "sysdig.serviceAccountName" .}}
volumes:
- hostPath
- emptyDir
- secret
- configMap
{{- end -}}
 # service.yaml
{{- if .Values.auditLog.enabled }}
apiVersion: v1
kind: Service
metadata:
  name: {{ template "sysdig.fullname" . }}
  labels:
{{ include "sysdig.labels" . | indent 4 }}
spec:
  selector:
    app.kubernetes.io/name: {{ include "sysdig.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
  ports:
  - protocol: TCP
    port: {{ .Values.auditLog.auditServerPort }}
{{- end }}
 # serviceaccount.yaml
{{- if .Values.serviceAccount.create }}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ template "sysdig.serviceAccountName" .}}
  labels:
{{ include "sysdig.labels" . | indent 4 }}
{{- end }}

# Default values for Sysdig Monitor and Secure Helm package.

image:
  # This is a hack to support RELATED_IMAGE_<identifier> feature in Helm based
  # Operators
  #
  # As long as I don't want to people to use this, I will keep it undocumented
  overrideValue:

  registry: docker.io
  repository: sysdig/agent
  tag: 10.0.0
  # Specify a imagePullPolicy
  # Defaults to 'Always' if image tag is 'latest', else set to 'IfNotPresent'
  # ref: http://kubernetes.io/docs/user-guide/images/#pre-pulling-images
  pullPolicy: IfNotPresent
  # Optionally specify an array of imagePullSecrets.
  # Secrets must be manually created in the namespace.
  # ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
  #
  # pullSecrets:
  #   - name: myRegistrKeySecretName

resources:
  # Although resources needed are subjective on the actual workload we provide
  # a sane defaults ones. If you have more questions or concerns, please refer
  # to Sysdig Support for more info about it
  requests:
    cpu: 600m
    memory: 512Mi
  limits:
    cpu: 2000m
    memory: 1536Mi

rbac:
  # true here enables creation of rbac resources
  create: true

serviceAccount:
  # Create and use serviceAccount resources
  create: true
  # Use this value as serviceAccountName
  name:

daemonset:
  # Perform rolling updates by default in the DaemonSet agent
  # ref: https://kubernetes.io/docs/tasks/manage-daemon/update-daemon-set/
  updateStrategy:
    # You can also customize maxUnavailable, maxSurge or minReadySeconds if you
    # need it
    type: RollingUpdate
  ## Extra environment variables that will be pass onto deployment pods
  env: {}
  # Allow the DaemonSet to schedule using affinity rules
  # Ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: kubernetes.io/arch
            operator: In
            values:
              - amd64
          - key: kubernetes.io/os
            operator: In
            values:
              - linux
  # Allow the DaemonSet to set annotations
  annotations: {}

# If is behind a proxy you can set the proxy server
proxy:
  httpProxy:
  httpsProxy:
  noProxy:

# Set daemonset timezone
timezone:

# Set daemonset priorityClassName
priorityClassName:

ebpf:
  # Enable eBPF support for Sysdig Agent
  enabled: false

  settings:
    # Needed to correctly detect the kernel version for the eBPF program
    # Set to false if not running on Google COS
    mountEtcVolume: true

slim:
  # Uses a slim version of the Sysdig Agent
  enabled: false
  # When using slim the kernel module is built in other container, which
  # contains the toolchain required to build the kernel module.
  kmoduleImage:
    repository: sysdig/agent-kmodule

  resources:
    # Resources required by the kernel module builder image. These are some
    # a sane defaults ones, but you can tweak or ask Sysdig Support for more
    # info about this
    requests:
      cpu: 1000m
      memory: 348Mi
    limits:
      memory: 512Mi

sysdig:
  # Required: You need your Sysdig Monitor access key before running agents.
  accessKey: ""

  settings: {}
    ### Agent tags
    # tags: linux:ubuntu,dept:dev,local:nyc
    #### Sysdig Software related config ####
    # Sysdig collector address
    # collector: 192.168.1.1
    # Collector TCP port
    # collector_port: 6666
    # Whether collector accepts ssl
    # ssl: true
    # collector certificate validation
    # ssl_verify_certificate: true
    #######################################
    # k8s_cluster_name: production

secure:
  # true here enables Sysdig Secure: container run-time security & forensics
  enabled: true

auditLog:
  # true here activates the K8s Audit Log feature for Sysdig Secure
  enabled: false
  auditServerUrl: 0.0.0.0
  auditServerPort: 7765

  dynamicBackend:
    # true here configures an AuditSink who will receive the K8s audit logs
    enabled: false

scc:
  create: false

customAppChecks: {}
  # Allow passing custom app checks for Sysdig Agent.
  # Example:
  #
  # sample.py: |-
  #   from checks import AgentCheck
  #
  #   class MyCustomCheck(AgentCheck):
  #       def check(self, instance):
  #           self.gauge("testhelm", 1)

# Allow sysdig to run on Kubernetes 1.6 masters.
tolerations:
  - effect: NoSchedule
    key: node-role.kubernetes.io/master
