본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

ScaledJob 명세 (ScaledJob specification)

원문 보기 위키 갱신

KEDA가 Job을 스케일링하는 데 사용하는 ScaledJob 커스텀 리소스의 전체 필드를 설명하는 참조 페이지예요. 각 프로퍼티가 무엇을 의미하고 기본값이 무엇인지 하나씩 정리해 볼게요.

출처: 문서

본문

개요 (Overview)

이 명세는 KEDA가 Job을 스케일링할 때 사용하는 트리거와 스케일링 동작을 정의하는 ScaledJob 커스텀 리소스 정의를 설명해요. .spec.ScaleTargetRef 섹션은 scaledjob_types.go에 정의된 Job에 대한 참조를 담고 있어요.

apiVersion: keda.sh/v1alpha1
kind: ScaledJob
metadata:
  name: {scaled-job-name}
  labels:
    my-label: {my-label-value}                # Optional. ScaledJob labels are applied to child Jobs
  annotations:
    autoscaling.keda.sh/paused: true          # Optional. Use to pause autoscaling of Jobs
    my-annotation: {my-annotation-value}      # Optional. ScaledJob annotations are applied to child Jobs
spec:
  jobTargetRef:
    parallelism: 1                            # [max number of desired pods](https://kubernetes.io/docs/concepts/workloads/controllers/job/#controlling-parallelism)
    completions: 1                            # [desired number of successfully finished pods](https://kubernetes.io/docs/concepts/workloads/controllers/job/#controlling-parallelism)
    activeDeadlineSeconds: 600                #  Specifies the duration in seconds relative to the startTime that the job may be active before the system tries to terminate it; value must be positive integer
    backoffLimit: 6                           # Specifies the number of retries before marking this job failed. Defaults to 6
    template:
      # describes the job's [pod template](https://kubernetes.io/docs/concepts/workloads/controllers/job)
  pollingInterval: 30                         # Optional. Default: 30 seconds
  successfulJobsHistoryLimit: 5               # Optional. Default: 100. How many completed jobs should be kept.
  failedJobsHistoryLimit: 5                   # Optional. Default: 100. How many failed jobs should be kept.
  envSourceContainerName: {container-name}    # Optional. Default: .spec.JobTargetRef.template.spec.containers[0]
  minReplicaCount: 10                         # Optional. Default: 0
  maxReplicaCount: 100                        # Optional. Default: 100
  rolloutStrategy: gradual                    # Deprecated: Use rollout.strategy instead (see below).
  rollout:
    strategy: gradual                         # Optional. Default: default. Which Rollout Strategy KEDA will use.
    propagationPolicy: foreground             # Optional. Default: background. Kubernetes propagation policy for cleaning up existing jobs during rollout.
  scalingStrategy:
    strategy: "custom"                        # Optional. Default: default. Which Scaling Strategy to use.
    customScalingQueueLengthDeduction: 1      # Optional. A parameter to optimize custom ScalingStrategy.
    customScalingRunningJobPercentage: "0.5"  # Optional. A parameter to optimize custom ScalingStrategy.
    pendingPodConditions:                     # Optional. A parameter to calculate pending job count per the specified pod conditions
      - "Ready"
      - "PodScheduled"
      - "AnyOtherCustomPodCondition"
    multipleScalersCalculation : "max" # Optional. Default: max. Specifies how to calculate the target metrics when multiple scalers are defined.
  triggers:
  # {list of triggers to create jobs}

지원되는 모든 트리거는 여기에서 찾을 수 있어요.

jobTargetRef

jobTargetRef:
    parallelism: 1              # Optional. Max number of desired instances ([docs](https://kubernetes.io/docs/concepts/workloads/controllers/job/#controlling-parallelism))
    completions: 1              # Optional. Desired number of successfully finished instances ([docs](https://kubernetes.io/docs/concepts/workloads/controllers/job/#controlling-parallelism))
    activeDeadlineSeconds: 600  # Optional. Specifies the duration in seconds relative to the startTime that the job may be active before the system tries to terminate it; value must be positive integer
    backoffLimit: 6             # Optional. Specifies the number of retries before marking this job failed. Defaults to 6

jobTargetRef는 batch/v1 JobSpec 객체예요. 각 필드에 대한 자세한 내용은 Kubernetes API를 참고해 주세요. template 필드는 필수예요.

pollingInterval

pollingInterval: 30  # Optional. Default: 30 seconds

각 트리거를 확인하는 주기예요. 기본적으로 KEDA는 모든 ScaledJob에서 30초마다 각 트리거 소스를 확인해요.

successfulJobsHistoryLimit, failedJobsHistoryLimit

successfulJobsHistoryLimit: 5  # Optional. Default: 100. How many completed jobs should be kept.
  failedJobsHistoryLimit: 5      # Optional. Default: 100. How many failed jobs should be kept.

successfulJobsHistoryLimit와 failedJobsHistoryLimit 필드는 선택 사항이에요. 완료된 Job과 실패한 Job을 각각 몇 개까지 보관할지를 지정해요. 기본값은 100이에요. 이 개념은 Job History Limits와 유사해서, 여러분 Job의 결과가 무엇인지 파악하는 데 도움을 줘요.

실제 Job 수는 짧은 시간 안에 이 한도를 초과할 수 있어요. 하지만 정리 기간(cleanup period)에 해소될 거예요. 현재 정리 기간은 폴링 간격(Polling interval)과 같아요.

envSourceContainerName

envSourceContainerName: {container-name}  # Optional. Default: .spec.JobTargetRef.template.spec.containers[0]

이 선택 속성은 KEDA가 시크릿 등을 담고 있는 환경 프로퍼티를 가져오려는 Job 내 컨테이너 이름을 지정해요. 정의하지 않으면 KEDA는 첫 번째 컨테이너, 즉 .spec.JobTargetRef.template.spec.containers[0]에서 환경 프로퍼티를 가져오려고 해요.

minReplicaCount

minReplicaCount: 10 # Optional. Default: 0

기본적으로 생성되는 최소 Job 수예요. 새 Job의 부트스트래핑 시간을 피하는 데 유용해요. minReplicaCount가 maxReplicaCount보다 크면 minReplicaCount는 maxReplicaCount로 설정돼요.

새 메시지는 maxReplicaCount가 허용하는 한도 안에서 새 Job을 만들 수 있어요. 그렇게 해서 minReplicaCount만큼의 Job이 항상 실행되는 상태를 맞춰요. 예를 들어 minReplicaCount를 2로 설정하면 2개의 Job이 영구적으로 실행돼요. targetValue 1을 사용할 때 새 메시지 3개가 보내지면, 그 중 2개는 이미 실행 중인 Job에서 처리되고, minReplicaCount(2)가 요구하는 목표 상태를 맞추기 위해 새 Job이 추가로 생성돼요.

maxReplicaCount

maxReplicaCount: 100 # Optional. Default: 100

단일 폴링 기간 내에 생성되는 최대 파드 수예요. 실행 중인 Job이 있으면 그 수만큼 차감돼요. 다음 표는 스케일링 로직의 예시예요.

| | Queue Length | Max Replica Count | Target Average Value | Running Job Count | Number of the Scale | | 10 | 3 | 1 | 0 | 3 | | 10 | 3 | 2 | 0 | 3 | | 10 | 3 | 1 | 1 | 2 | | 10 | 100 | 1 | 0 | 10 | | 4 | 3 | 5 | 0 | 1 |

  • Queue Length: 큐에 있는 항목 수예요.
  • Target Average Value: 하나의 Job이 소비할 메시지 수예요. scaler 쪽에서 정의돼요. 예: Azure Storage Queue scaler의 queueLength.
  • Running Job Count: 실행 중인 Job 수예요.
  • Number of the Scale: 생성되는 Job 수예요.

rollout

rollout:
    strategy: gradual                         # Optional. Default: default. Which Rollout Strategy KEDA will use.
    propagationPolicy: foreground             # Optional. Default: background. Kubernetes propagation policy for cleaning up existing jobs during

선택 속성 rollout.strategy는 기존 ScaledJob을 업데이트할 때 KEDA가 사용할 롤아웃 전략을 지정해요. 가능한 값은 default 또는 gradual이에요.

default 롤아웃 전략을 사용하면 ScaledJob이 업데이트될 때마다 KEDA가 기존 Job을 종료시켜요. 그런 다음 최신 스펙으로 이 Job들을 다시 만들어요. 이 종료가 발생하는 순서는 rollout.propagationPolicy 속성으로 설정할 수 있어요. 기본적으로 kubernetes background 전파가 사용돼요. 동작을 바꾸려면 propagationPolicy를 foreground로 설정해 주세요. 자세한 내용은 Kubernetes 문서를 참고하세요.

gradual 롤아웃 전략에서는 ScaledJob이 업데이트될 때마다 KEDA가 기존 Job을 삭제하지 않아요. 최신 스펙으로 새 Job만 생성돼요.

scalingStrategy

scalingStrategy:
  strategy: "default"                 # Optional. Default: default. Which Scaling Strategy to use.

Scaling Strategy를 선택하세요. 가능한 값은 default, custom, accurate, eager예요. 기본값은 default예요.

💡 참고: maxScale은 실행 중인 Job 수가 아니에요. 다음과 같이 계산돼요.

maxScale = min(scaledJob.MaxReplicaCount(), divideWithCeil(queueLength, targetAverageValue))

즉 MaxReplicaCount를 초과하지 않는 한 queueLength를 targetAverageValue로 나눈 값을 사용한다는 뜻이에요.

RunningJobCount는 현재 실행 중이거나 아직 끝나지 않은 Job의 수를 나타내요. 다음과 같이 계산돼요.

if !e.isJobFinished(&job) {
 	runningJobs++
}

PendingJobCount는 pending 상태의 Job 수를 알려 주는 지표예요. Pending Job은 두 가지 방법으로 계산할 수 있어요.

  • 기본 동작 - 아직 끝나지 않았고 기본 파드가 실행 중이지 않거나 아직 완료되지 않은 Job
  • pendingPodConditions 설정 - 아직 끝나지 않았고 기본 파드의 지정된 모든 파드 조건이 kubernetes에 의해 true로 표시된 Job

다음과 같이 계산돼요.

if !e.isJobFinished(&job) {
  if len(scaledJob.Spec.ScalingStrategy.PendingPodConditions) > 0 {
      if !e.areAllPendingPodConditionsFulfilled(&job, scaledJob.Spec.ScalingStrategy.PendingPodConditions) {
          pendingJobs++
      }
  } else {
      if !e.isAnyPodRunningOrCompleted(&job) {
          pendingJobs++
      }
  }
}

default

이 로직은 V1에서의 Job과 동일해요. 스케일 수는 다음과 같이 계산돼요.

스케일 수

maxScale - runningJobCount

custom

기본 스케일 로직을 커스터마이즈할 수 있어요. 다음 파라미터를 설정해야 해요. 설정하지 않으면 전략은 default가 돼요.

customScalingQueueLengthDeduction: 1      # Optional. A parameter to optimize custom ScalingStrategy.
customScalingRunningJobPercentage: "0.5"  # Optional. A parameter to optimize custom ScalingStrategy.

스케일 수

min(maxScale-int64(*s.CustomScalingQueueLengthDeduction)-int64(float64(runningJobCount)*(*s.CustomScalingRunningJobPercentage)), maxReplicaCount)

accurate

scaler가 잠긴 메시지 수를 포함하지 않는 queueLength(큐 항목 수)를 반환하는 경우 이 전략을 권장해요. Azure Storage Queue가 한 예시예요. 앱이 메시지를 소비하면 메시지를 삭제하는 방식이라면 이 전략을 사용할 수 있어요.

if (maxScale + runningJobCount) > maxReplicaCount {
		return maxReplicaCount - runningJobCount
	}
	return maxScale - pendingJobCount

자세한 내용은 이 PR을 참고할 수 있어요.

eager

기본 전략을 채택하면 미묘한 문제가 생기기 쉬워요. runningJobCount와 maxReplicaCount 사이에 사용 가능한 슬롯이 있음에도, 메시지가 Job을 생성해 소비되어야 하는데 큐에 남아 있는 경우가 있어요. eager 전략이 이 문제를 해결해 줘요. maxReplicaCount까지 사용 가능한 모든 슬롯을 활용해 대기 중인 메시지가 가능한 한 빨리 처리되도록 보장해요.

예를 들어 클러스터에 아래와 같이 ScaledJob을 구성했다고 가정해 볼게요.

###
  # A job that runs for a minimum of 3 hours.
  ###
  pollingInterval: 10 # Optional. Default: 30 seconds
  maxReplicaCount: 10 # Optional. Default: 100
  triggers:
    - type: rabbitmq
      metadata:
        queueName: woker_queue
        hostFromEnv: RABBITMQ_URL
        mode: QueueLength
        value: "1"

Rabbitmq에 메시지 3개를 보내고 pollingInterval보다 충분히 길게 기다린 뒤, 다시 3개를 보낸다고 해요. 기본 스케일링 전략을 사용하면 메트릭 변경이 다음 표와 같이 나타나요.

| | | | initial | incoming 3 messages | after poll | incoming 3 messages | after poll | | queueLength | 0 | 3 | 3 | 6 | 6 | | runningJobs | 0 | 0 | 3 | 3 | 3 |

eager로 바꾸면 결과는 다음과 같아져요.

| | | | initial | incoming 3 messages | after poll | incoming 3 messages | after poll | | queueLength | 0 | 3 | 3 | 6 | 6 | | runningJobs | 0 | 0 | 3 | 3 | 6 |

최종 상태에서 차이를 확인할 수 있어요. 자세한 내용은 이 원본 이슈를 참고하셔도 좋아요.

scalingStrategy:
    multipleScalersCalculation : "max" # Optional. Default: max. Specifies how to calculate the target metrics (`queueLength` and `maxScale`) when multiple scalers are defined.

트리거가 여러 개일 때의 동작을 선택하세요. 가능한 값은 max, min, avg, sum이고 기본값은 max예요.

  • max: queueLength가 최대인 scaler의 메트릭을 사용해요. (기본값)
  • min: queueLength가 최소인 scaler의 메트릭을 사용해요.
  • avg: 모든 활성 scaler의 메트릭을 합산하고 활성 scaler 수로 나눠요.
  • sum: 모든 활성 scaler의 메트릭을 합산해요.

multipleScalersCalculation

scalingStrategy:
    multipleScalersCalculation : "max" # Optional. Default: max. Specifies how to calculate the target metrics (`queueLength` and `maxScale`) when multiple scalers are defined.

트리거가 여러 개일 때의 동작을 선택하세요. 가능한 값은 max, min, avg, sum이고 기본값은 max예요.

  • max: queueLength가 최대인 scaler의 메트릭을 사용해요. (기본값)
  • min: queueLength가 최소인 scaler의 메트릭을 사용해요.
  • avg: 모든 활성 scaler의 메트릭을 합산하고 활성 scaler 수로 나눠요.
  • sum: 모든 활성 scaler의 메트릭을 합산해요.

더 알아보기 (Learn more)

ScaledJob은 이벤트 기반으로 Job을 생성·스케일링하는 강력한 도구예요. 각 필드의 기본값을 기억해 두면 원하는 스케일링 전략(custom, accurate, eager 등)을 조합해서 엄청나게 유연하게 활용할 수 있어요.