Если вы видите что-то необычное, просто сообщите мне. Skip to main content

Cluster Autoscaler: как он работает и решение частых проблем

Что такое Cluster Autosc

Kubernetes представляет несколько механизмов для масштабирования нагрузки. Три главные механизмы это : VPA, HPA, CA.

CA автоматически подбирает количество нод в кластере под требования. Когда число подов, которые находятся в очереди назначения или при остутствии возможности назначить, показывает что ресурсов не хватает в кластере, CA добавляет новые ноды в кластер. Он так же может уменьшить количество нод если они не до конца используются долгое время.

TheОбычно Cluster Autoscaler isустанавливается typicallyкак installed as aобъект Deployment objectв inкластере. aОн cluster.работает Itтолько scalesодной oneрепликой replicaи atиспользует aвыборный time,механизм andдля usesтого. leaderчтобы electionбыть toуверенным, ensureчто highон availability.

полностью

HowКак работает Cluster Autoscaler

Для простоты, мы объясним процесс Cluster Autoscaler Worksв

Forрежиме simplicity,масштабирования. we’llКогда explainчисло theназначенных Clusterподов Autoscalerв processкластере inувеличивается, aуказывая scaleна outнедостаток scenario. When the number of pending (unschedulable) pods in the cluster increases, indicating a lack of resources,ресурсов, CA automaticallyавтоматически startsзапускает newновые nodes.ноды.

ThisЭто occursпроявляется inв fourчетырех steps:шагах:

  1. CA checksпроверяет forназначенные pendingподы, pods,время scanning at an interval ofпроверки 10 secondsсекунд(для (configurableнастройки usingможно theуказать флаг --scan-interval)
  2. flag)
  3. Если есть назначенные поды, CA запускаем новые ноды для масштабирования кластера, в рамках конфигурации кластера. CA встраивается в облачную платформу, например AWS или Azure, используя их возможности масштабирования для того, чтобы можно было управлять vm.
  4. K8s регистрирует новые vm в качестве нод, позволяя K8s запускать поды на свежих ресурсах.
  5. IfK8s thereпланировщик areзапускает pendingназначенные pods,поды CAна spinsновые upноды. new nodes to scale out the cluster, within the constraints configured by the administrator. CA integrates with public cloud platforms such as AWS and Azure, using their autoscaling capabilities to add more virtual machines.
  6. Kubernetes registers the new virtual machines as nodes in the control plane, allowing the Kubernetes scheduler to run pods on them.
  7. The Kubernetes scheduler assigns the pending pods to the newew nodes.

Cluster Autoscaler

DiagnosingОбнаружение Issuesпроблем withс Cluster Autoscaler

ClusterCA Autoscalerполезный isмеханизм, aно usefulон mechanism,может butработать itне canтак, sometimesкак workожидает differentlyадминистратор. thanВот expected.первшые Hereшаги, areчтобы theнайти primaryпроблему waysс to diagnose an issue with CA:CA.

LogsЛогирование onна control plane nodesнодах

KubernetesПлан controlуправления planeK8s nodesсоздает createлоги logsактивности ofCA Clusterпо Autoscalerследующему activity in the following path:пути: /var/log/cluster-autoscaler.log

Events on control plane nodesСобытия

The kube-system/cluster-autoscaler-status ConfigMap emitsпроизводят theследующие following events:события:

  • ScaledUpGroup—thisScaledUpGroup event- meansэто событие говорит, CA increasedувеличивает theразмер sizeгруппы ofнод(предоставляется theпрошлый nodeи groupтекущий (provides previous size and current size)размеры)
  • ScaleDownEmpty—thisScaleDownEmpty event- meansэто событие означение, что CA removedубирает aноду, nodeкоторая thatне didимеет notподов(системные haveподы anyпри userэтом podsне running on it (only system pods)рассматриваюца)
  • ScaleDown—thisScaleDown event- meansэто событие создается, когда CA removedубирает aноду, nodeкоторая thatимеет hadзапущенные userподы. podsСобытие runningсодержит onимена it.всех Theподов, eventкоторые willбудет includeперезазначены theна namesдругие ofноды allв podsрезультате that are rescheduled as a result.действия.

EventsСобытия on nodesнод

  • ScaleDown—thisTriggeredScaleUp event- meansэто cобытие говорит, что CA isувеличивает scalingкластер, downтак theкак node.появились Thereподы canв be multiple events, indicating different stages of the scale-down operation.очереди.
  • ScaleDownFailed—thisNotTriggerScaleUp event- meansсобытие говорит, что CA triedне toможет removeувеличить theколичество nodeнод butв did not succeed. It provides the resulting error message.группе.
  • ScaleDown

    Events- onэто pods

    событие
      значит,
    • TriggeredScaleUp—this event meansчто CA scaledпробует upперенести theподы clusterс toноды, enableчтобы thisзатем podосвободить toноду schedule.
    • и
    • NotTriggerScaleUp—thisудалить eventиз means CA was not able to scale up a node group to allow this pod to schedule.
    • ScaleDown—this event means CA tried to evict this pod from a node, in order to drain it and then scale it down.кластера.

    Cluster Autoscaler: Troubleshootingработа forс Specificопределенными Error Scenariosошибками

    HereПредлагаем areнесколько specificопределенных errorситуаций, scenariosкоторые thatмогут canповяится occurпри withработе theCA Clusterи Autoscalerвозможные andрешения howэтих to perform initial troubleshooting.проблем.

    TheseЭта instructionsинструкция willпозволит allowвыяснить youпростые toошибки debugработы simpleCA, errorно scenarios,для butболее forсложных moreпроблем, complexвключающие errorsмножество involvingдвигающихся multipleчастей movingв partsкластере, inвозможно theпридется cluster,автоматизировать youинструментарий mightрешения need automated troubleshooting tools.проблем.

    NodesНоды withс Lowнедостаточной Utilizationнагрузой areне Notудалются Scaledиз Downкластера.

    HereВот areпричины reasonsпо whyкоторы CA mightне failможет toуменьшить scaleколичество downнод, aи node,что andможно whatс youэтим can do about them.сделать.

    REASONПричина CLUSTER DOESN’T SCALE DOWNпроблемы WHATЧто YOUможно CAN DOсделать
    PodВ specsописании indicateпода itесть shouldуказание, notчто beего evictedнельзя fromперенести theна node.другую ноду. IdentifyПроверьте the missingотсутсвующий ConfigMap andи createсоздайте itего, inили theиспользуйте namespace, or mount another, existing ConfigMap.другой.
    NodeГруппа groupнод alreadyуже hasимеет theминимальное minimum size.значение. ReduceСократите minimumминимальное sizeзначение inв CAнастройках configuration.CA.
    TheНода nodeимеет hasдирективу “scale-down disabled” annotation.. RemoveУберите theдирективу annotationс from the node.ноды.
    CA isожидает waitingвремени forсогласно theодному durationиз specifiedуказанных inследующих one of these flags:флагов: --scale-down-unneeded-time --scale-down-delay-after-add flag, --scale-down-delay-after-failure, --scale-down-delay-after-delete, --scan-interval ReduceСократите theвремя timeуказанное specifiedво inсоответсвующем theфлаге, relevantили flag,дождись orуказанного wait the specified time after the relevant event.времени.
    FailedНеудачна attemptяпопытка toудаления remove the node ноды(CA willбудет wait anotherждать 5 minutesминут beforeпееред tryingповторной again).попыткой) WaitПодождите 5 minutesминут andи seeпроверьте ifрешилась theли issueпроблема. is resolved..

    PendingПоды Nodesв Existсостоянии Butpenind, Clusterно Doesновые Notноды Scaleне Upсоздаются.

    HereНиже areприведены reasonsпричины whyпочему CA mightможет failне toувеличивать scaleколичество upнод theв cluster,кластере, andи whatчто youс canэтим doможно about them.сделать.

    REASON CLUSTER DOESN’T SCALE UPПричина WHATЧто YOUможно CAN DOсделать
    ExistingСоздаваемый podsпод haveимеет highзапросы resourceпревыщающие requests,характеристики which won’t be satisfied by new nodes.ноды. EnableДать возможность CA toдобавлять addбольшие largeноды, nodes,или orсократить reduceтребования resourceресурсов requestsдля by pods.пода.
    AllВсе suitableподходящие nodeгруппы groupsнод areимеют atмаксимально maximumразрешенное size.значение. IncreaseУвеличьте theмаксимальное maximumзначение sizeнеобходимой of the relevant node group.группы.
    ExistingНовый podsпод areне notназначается ableно toновые schedule on new nodes due to selectors or other settings.ноды. ModifyИзменити podописание manifestsпода, toчтобы enableпредоставить someвозможность podsподу toназначаться scheduleна onопределенной theгруппе new nodes. Learn more in our guide to node affinity.нод.

    NoVolumeZoneConflict error—this indicatesпоказывает, that aчто StatefulSet needsтребует toзапуск runв inтой theже sameзоне zoneчто withи a PersistentVolume (PersistentVolume(PV), butно thatэта zoneзона hasуже alreadyимеет reachedдоступный itsлимит scaling.| limit.начиная Fromс Kubernetes 1.1313, onwards,вы youможете canразделить runгруппу separateнод nodeна groupsзоны perи zoneиспользовать and use theфлаг --balance-similar-node-groups flagдля to keep them balanced across zones. балансировки.|

    Cluster Autoscaler Stopsпрекратил Workingработать

    IfЕсли CA appearsне toработает, haveпройдитесь stoppedпо working,следующим followшагам, theseчтобы stepsпонять to debug the problem:проблему.

    1. CheckПроверьте ifчто CA isзапущен. running—youЭто canможно checkпроверить theпо latestпоследнему eventsсобытию, emittedкоторое byгенерируется theв kube-system/cluster-autoscaler-status ConfigMap. ThisОно shouldне beдолжно no more thanпревышать 3 minutes.минуты.
    2. CheckПроверьте ifесли clusterкластер andи nodeгруппы groupsнод areнаходятся inв healthyздоровом state—thisсостоянии, shouldэто beтак reportedже byможно theнайти ConfigMap.в configMap
    3. CheckПроверьте ifналичие thereнеготовых areнод - если какие-то ноды оказываются unready nodesпроверьте (CAчисло versionresoureceUnready. 1.24Если andкакие-то later)—ifноды someпомечены, nodesпроблема, appearскорей unready,всего, checkв theтом, resourceUnreadyчто count.не Ifбыло anyустановленно nodesнеобходимое are marked as resourceUnready, the problem is likely with a device driver failing to install a required hardware resource.ПО.
    4. IfЕсли both cluster andсостояние CA areи healthy,кластера check:здоровое,
      • Nodes with low utilization—if these nodes are not being scheduled, see the Nodes with Low Utilization section above. ju* Pending pods that do not trigger a scale up—see the Pending Nodes Exist section above.
    проверьте:
    • Control plane CA logs—couldlogs indicate- whatмогут isуказать theна problemпроблему, preventingкоторая CAможет fromне scalingдавать upмасштабировать or down, why it cannot remove a pod, or what was the scale-up plan.кластер.
    • CA eventsсобытия on theдля pod object—couldобъекта provide cluesможет whyдать понимание почему CA couldне notпереназначает reschedule the pod.поды.
    • Cloud provider resources quota—if thereесли areесть failedнеудачные attemptsпопытки toдобавить addноду, nodes,проблема theможет problemбыть couldв beквотах resourceресурсов quotaу with the public cloud provider.провайдера.
    • Networking issues—if theесли cloudпровайдер providerпытается isсоздать managingноду, toно createона nodesне butподключается theyк areкластеру, notэто connectingможет toговорить theо cluster,проблеме thisс could indicate a networking issue.сетью.