{{- if and (eq .Values.datastore "kubernetes") .Values.typha.enabled -}}
# This manifest creates a Service, which will be backed by Calico's Typha daemon.
# Typha sits in between Felix and the API server, reducing Calico's load on the API server.

apiVersion: v1
kind: Service
metadata:
  name: calico-typha
  namespace: kube-system
  labels:
    k8s-app: calico-typha
spec:
  ports:
    - port: 5473
      protocol: TCP
      targetPort: calico-typha
      name: calico-typha
  selector:
    k8s-app: calico-typha

---

# This manifest creates a Deployment of Typha to back the above service.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: calico-typha
  namespace: kube-system
  labels:
    k8s-app: calico-typha
spec:
  # Number of Typha replicas. To enable Typha, set this to a non-zero value *and* set the
  # typha_service_name variable in the calico-config ConfigMap above.
  #
  # We recommend using Typha if you have more than 50 nodes. Above 100 nodes it is essential
  # (when using the Kubernetes datastore). Use one replica for every 100-200 nodes. In
  # production, we recommend running at least 3 replicas to reduce the impact of rolling upgrade.
  replicas: 1
  revisionHistoryLimit: 2
  selector:
    matchLabels:
      k8s-app: calico-typha
  strategy:
    rollingUpdate:
      # 100% surge allows a complete up-level set of typha instances to start and become ready,
      # which in turn allows all the back-level typha instances to start shutting down. This
      # means that connections tend to bounce directly from a back-level instance to an up-level
      # instance.
      maxSurge: 100%
      # In case the cluster is unable to schedule extra surge instances, allow at most one instance
      # to shut down to make room. You can set this to 0 if you're sure there'll always be enough room to
      # schedule extra typha instances during an upgrade (because setting it to 0 blocks shutdown until
      # up-level typha instances are online and ready).
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      labels:
        k8s-app: calico-typha
      annotations:
        cluster-autoscaler.kubernetes.io/safe-to-evict: 'true'
    spec:
      nodeSelector:
        kubernetes.io/os: linux
      hostNetwork: true
      # Typha supports graceful shut down, disconnecting clients slowly during the grace period.
      # The TYPHA_SHUTDOWNTIMEOUTSECS env var should be kept in sync with this value.
      terminationGracePeriodSeconds: 300
      tolerations:
        # Mark the pod as a critical add-on for rescheduling.
        - key: CriticalAddonsOnly
          operator: Exists
      # Since Calico can't network a pod until Typha is up, we need to run Typha itself
      # as a host-networked pod.
      serviceAccountName: calico-node
      priorityClassName: system-cluster-critical
      # fsGroup allows using projected serviceaccount tokens as described here kubernetes/kubernetes#82573
      securityContext:
        fsGroup: 65534
      containers:
      - image: {{ .Values.typha.image }}:{{.Values.version }}
        imagePullPolicy: {{.Values.imagePullPolicy}}
        name: calico-typha
        ports:
        - containerPort: 5473
          name: calico-typha
          protocol: TCP
        envFrom:
        - configMapRef:
            # Allow KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT to be overridden for eBPF mode.
            name: kubernetes-services-endpoint
            optional: true
        env:
{{- if .Values.bpf }}
          # Overrides for kubernetes API server host/port. Needed in BPF mode.
          - name: KUBERNETES_SERVICE_HOST
            valueFrom:
              configMapKeyRef:
                name: calico-config
                key: kubernetes_service_host
          - name: KUBERNETES_SERVICE_PORT
            valueFrom:
              configMapKeyRef:
                name: calico-config
                key: kubernetes_service_port
{{- end }}
          # Enable "info" logging by default. Can be set to "debug" to increase verbosity.
          - name: TYPHA_LOGSEVERITYSCREEN
            value: "info"
          # Disable logging to file and syslog since those don't make sense in Kubernetes.
          - name: TYPHA_LOGFILEPATH
            value: "none"
          - name: TYPHA_LOGSEVERITYSYS
            value: "none"
          # Monitor the Kubernetes API to find the number of running instances and rebalance
          # connections.
          - name: TYPHA_CONNECTIONREBALANCINGMODE
            value: "kubernetes"
          - name: TYPHA_DATASTORETYPE
            value: "kubernetes"
          - name: TYPHA_HEALTHENABLED
            value: "true"
          # Set this to the same value as terminationGracePeriodSeconds; it tells Typha how much time
          # it has to shut down.
          - name: TYPHA_SHUTDOWNTIMEOUTSECS
            value: "300"
{{- if eq .Values.ipam "host-local" }}
          # Configure route aggregation based on pod CIDR.
          - name: USE_POD_CIDR
            value: "true"
{{- end }}
          # Uncomment these lines to enable prometheus metrics. Since Typha is host-networked,
          # this opens a port on the host, which may need to be secured.
          #- name: TYPHA_PROMETHEUSMETRICSENABLED
          #  value: "true"
          #- name: TYPHA_PROMETHEUSMETRICSPORT
          #  value: "9093"
{{- if .Values.typha.env }}
{{ toYaml .Values.typha.env | indent 10 }}
{{- end }}
        livenessProbe:
          httpGet:
            path: /liveness
            port: 9098
            host: localhost
          periodSeconds: 30
          initialDelaySeconds: 30
          timeoutSeconds: 10
        securityContext:
          runAsNonRoot: true
          allowPrivilegeEscalation: false
        readinessProbe:
          httpGet:
            path: /readiness
            port: 9098
            host: localhost
          periodSeconds: 10
          timeoutSeconds: 10

---

# This manifest creates a Pod Disruption Budget for Typha to allow K8s Cluster Autoscaler to evict

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: calico-typha
  namespace: kube-system
  labels:
    k8s-app: calico-typha
spec:
  maxUnavailable: 1
  selector:
    matchLabels:
      k8s-app: calico-typha
{{- end -}}
