# Copyright 2021 The Selkies Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

kind: CronJob
apiVersion: batch/v1beta1
metadata:
  name: image-puller-subscription-reaper
  namespace: pod-broker-system
  labels:
    k8s-app: image-puller-subscription-reaper
spec:
  # UTC time,
  schedule: "0 0 * * *"
  startingDeadlineSeconds: 3600
  concurrencyPolicy: Replace
  successfulJobsHistoryLimit: 0
  jobTemplate:
    spec:
      activeDeadlineSeconds: 1800
      template:
        spec:
          serviceAccount: pod-broker
          restartPolicy: OnFailure
          containers:
            ###
            # per-node gcr topic subscription reaper script
            ###
            - image: gcr.io/cloud-solutions-images/kube-pod-broker-controller:latest
              name: subscription-reaper
              command: ["/bin/bash"]
              args:
                - "-ec"
                - |
                  SUBSCRIPTIONS=$(gcloud pubsub subscriptions list --format='value(name)')
                  NODES=$(kubectl get node -o jsonpath='{..metadata.name}')
                  REGION=$(kubectl get node -o jsonpath='{.items[0].metadata.labels.topology\.kubernetes\.io/region}')
                  
                  for sub in $SUBSCRIPTIONS; do  
                    if [[ "$sub" =~ pod-broker-image-puller && "$sub" =~ ${REGION} ]]; then
                      submatch=$(echo $sub | cut -d'/' -f4 | sed 's/pod-broker-image-puller-//g')
                      if [[ ! "$NODES" =~ $submatch ]]; then
                        echo "deleting stale node subscription: $sub"
                        gcloud pubsub subscriptions delete $sub
                      fi
                    fi
                    
                    if [[ "$sub" =~ pod-broker-image-finder && "$sub" =~ ${REGION} ]]; then
                      submatch=$(echo $sub | cut -d'/' -f4 | sed 's/pod-broker-image-finder-//g')
                      if [[ ! "$NODES" =~ $submatch ]]; then
                        echo "deleting stale node subscription: $sub"
                        gcloud pubsub subscriptions delete $sub
                      fi
                    fi
                  done
              resources:
                requests:
                  cpu: 10m
