Kubernetes, масштабирование cronjob pod на другой узел

У нас есть единственное задание cronjob kubernetes, задача которого - обнаружить недавно загруженный файл и выполнить с ним некоторые операции. Эта операция выполняется каждую минуту и ​​может занять 10 минут.

На данный момент он работает и создает новые модули для заданий по мере обнаружения новых файлов. Однако мы бы хотели, чтобы под, созданный cronjob, порождался на другом узле. На этом этапе все мои поды создаются в одном узле, что может привести к сбою моего экземпляра EC2 в худшем случае, когда много новых файлов и моя система использует нашу память.

Я использую файловую систему EFS для обмена файлами между моими разными узлами, поэтому все узлы могут читать загруженные файлы.

Как мне разрешить создание новых модулей на разных узлах с помощью kubernetes cronjobs?


person user3454396    schedule 11.04.2020    source источник


Ответы (1)


Вы можете использовать Inter pod antiAffinity в разделе шаблона модуля cronjob. Сходство между модулями и анти-сродство позволяют вам ограничивать, какие узлы ваш модуль может быть запланирован на основе меток на модулях, которые уже запущены на узле, а не на основе на этикетках на узлах. Правила имеют форму «этот модуль должен (или, в случае анти-аффинности, не должен) запускаться в X, если этот X уже работает с одним или несколькими модулями, соответствующими правилу Y».

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: test
spec:
  schedule: "*/5 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          affinity:
            podAntiAffinity:
              requiredDuringSchedulingIgnoredDuringExecution:
              - labelSelector:
                  matchExpressions:
                  - key: app
                    operator: In
                    values:
                    - web-store
                topologyKey: "kubernetes.io/hostname"
          containers:
            - name: hello
              image: bash
              command: ["echo",  "Hello world"]
          restartPolicy: OnFailure

Необходимые документы API

kubectl explain cronjob.spec.jobTemplate.spec.template.spec.affinity.podAntiAffinity
KIND:     CronJob
VERSION:  batch/v1beta1

RESOURCE: podAntiAffinity <Object>

DESCRIPTION:
     Describes pod anti-affinity scheduling rules (e.g. avoid putting this pod
     in the same node, zone, etc. as some other pod(s)).

     Pod anti affinity is a group of inter pod anti affinity scheduling rules.

FIELDS:
   preferredDuringSchedulingIgnoredDuringExecution  <[]Object>
     The scheduler will prefer to schedule pods to nodes that satisfy the
     anti-affinity expressions specified by this field, but it may choose a node
     that violates one or more of the expressions. The node that is most
     preferred is the one with the greatest sum of weights, i.e. for each node
     that meets all of the scheduling requirements (resource request,
     requiredDuringScheduling anti-affinity expressions, etc.), compute a sum by
     iterating through the elements of this field and adding "weight" to the sum
     if the node has pods which matches the corresponding podAffinityTerm; the
     node(s) with the highest sum are the most preferred.

   requiredDuringSchedulingIgnoredDuringExecution   <[]Object>
     If the anti-affinity requirements specified by this field are not met at
     scheduling time, the pod will not be scheduled onto the node. If the
     anti-affinity requirements specified by this field cease to be met at some
     point during pod execution (e.g. due to a pod label update), the system may
     or may not try to eventually evict the pod from its node. When there are
     multiple elements, the lists of nodes corresponding to each podAffinityTerm
     are intersected, i.e. all terms must be satisfied.

Примечание. Анти-сродство Pod требует, чтобы узлы были последовательно помечены, другими словами, каждый узел в кластере должен иметь соответствующую метку, соответствующую топологическому ключу. Если у некоторых или всех узлов отсутствует указанная метка topologyKey, это может привести к непредвиденному поведению.

person Arghya Sadhu    schedule 11.04.2020