Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Table of Contents

Motivation

The proposal to introduce autoscaling for Flink (FLIP-271) has garnered significant interest due to its potential to greatly enhance the usability of Flink. The primary objective is to enable users to effortlessly enable the autoscaler for their Flink jobs without the need for intricate parallelism configurations. However, the current implementation of the flink-autoscaler is tightly integrated with Kubernetes and resides within the flink-kubernetes-operator repository.

There are compelling reasons to extend the usage of the flink-autoscaler to Flink jobs running on YARN as well:

  1. With the recent merge of the Externalized Declarative Resource Management (FLIP-291, FLINK-31316), in-place scaling is now supported across all types of Flink jobs. This development has made scaling Flink on YARN a straightforward process.

  2. Several discussions within the Flink user community, as observed in the mail list , have emphasized the necessity of flink-autoscaler supporting Flink on YARN.

Hence, this FLIP is centered around the crucial task of decoupling the autoscaler functionality from Kubernetes.
By achieving this decoupling, we aim to empower Flink users to leverage the benefits of autoscaling irrespective of their chosen deployment platform, whether it be Kubernetes or YARN.

Core Idea


  1. JobAutoScaler and JobAutoScalerImpl: These components will define the general autoscaling strategy for Flink jobs and are essential for the implementation of the autoscaler module.

  2. Interfaces: The FLIP outlines the necessity of defining

...

  1. a few interfaces -

...

  1. AutoScalerEventHandler, AutoScalerStateStore and AutoScalerStateStoreFactory .
    The

...

  1. AutoScalerEventHandler  interface handles event-based operations, while the AutoScalerStateStore  interface is responsible for accessing and persisting the autoscaler's state.

  2. Dependencies: The autoscaler module should not rely on any Kubernetes-related dependencies such as fabric8, flink-kubernetes-operator, or flink-kubernetes.
    Instead, it can rely on Apache Flink project dependencies to gather metrics and make scaling decisions based on JobVertexID , Configuration , MetricGroup , and other relevant classes.

  3. Optional Goal: As a nice-to-have feature, the FLIP proposes moving the flink-autoscaler module to the Apache Flink repository, thereby making it an integral part of the Flink project.
    Please note that, Initially autoscaler module will be part of flink-kubernetes-operator repository during this FLIP, and we can move the autoscaler module to apache flink in the last step of this FLIP.


Note:
Independent flink-kubernetes-operator-autoscaler  module is not necessary. Moving classes to flink-kubernetes-operator  will reduce complexity. We can discuss it in the mail list.

...

  • In the POC version, flink-kubernetes-operator-autoscaler  defines KubernetesAutoScalerHandler  KubernetesAutoScalerEventHandler, KubernetesAutoScalerStateStore and KubernetesAutoScalerStateStore Factory.
  • If flink-kubernetes-operator-autoscaler  as an independent module, it must depend on flink-kubernetes-operator  module.
  • flink-kubernetes-operator  cannot depend on flink-kubernetes-operator-autoscaler , so it's more difficult to load these classes than remove the flink-kubernetes-operator-autoscaler  module.

...

The proposed interface retains similarity to the existing JobAutoScaler , although with modified method parameters. Instead of using Kubernetes-related classes, the parameters will be replaced with
JobAutoScalerContext<KEY, INFO>  and KEY jobKey . To enhance clarity, it is suggested to rename the generic parameter KEY  to JOB_KEY . The autoscaler will treat Flink jobs with the same jobKey as identical.

...

Code Block
/** The general Autoscaler instance. */
public interface JobAutoScaler<KEY, INFO> {

    /** Called as part of the reconciliation loop. Returns true if this call led to scaling. */
    boolean scale(JobAutoScalerContext<KEY, INFO> context);

    /** Called when the customjob resource is deleted. */
    void cleanup(KEY jobKeyJobAutoScalerContext<KEY, INFO> context);
}

2. JobAutoScalerContext

...



    /** Get the current parallelism overrides for the job. */
    Map<String, String> getParallelismOverrides(JobAutoScalerContext<KEY, INFO> context);
}

2. JobAutoScalerContext

The JobAutoScalerContext  encapsulates essential information required for scaling Flink jobs, including jobKey, jobId, stateStore, and INFO extraJobInfo.
Currently, in the existing code or for Kubernetes jobs, the jobKey is defined as io.javaoperatorsdk.operator.processing.event.ResourceID .
However, there is a possibility to define the jobKey for Flink jobs running on YARN in the future.

Regarding the INFO extraJobInfo, it is worth noting that the flink-autoscaler itself does not utilize this information. Instead, it is employed by certain implementations of the

...

AutoScalerEventHandler.
The entire JobAutoScalerContext, comprising all relevant details, will be passed to these implementations when the autoscaler invokes their respective callbacks.


Code Block
/**
 * The job autoscaler context.
 *
 * @param <KEY>
 * @param <INFO>
 */
@AllArgsConstructor
public class JobAutoScalerContext<KEY, INFO> {

    // The identifier of each flink job.
    @Getter private final KEY jobKey;

    @Getter private final JobID jobID;

    @Getter private final long jobVersion;

    // Whether the job is really running, the STARTING or CANCELING aren't running.
    @Getter private final boolean isRunning;

    @Getter private final Configuration conf;

    @Getter private final MetricGroup metricGroup;

    private final SupplierWithException<RestClusterClient<String>, Exception> restClientSupplier;

    @Getter private final Duration flinkClientTimeout;

    @Getter private final AutoScalerStateStoreAutoScalerStateStoreFactory stateStorestateStoreFactory;

    /**
     * The flink-autoscaler doesn't use the extraJobInfo, it is only used in some implements of AutoScalerHandler. This
     * whole context will be passed to these implements when the autoscaler callbacks them.
     */
    @Getter @Nullable private final INFO extraJobInfo;

    public RestClusterClient<String> getRestClusterClient() throws Exception {
        return restClientSupplier.get();
    }
}

3. AutoScalerHandler


    public Optional<AutoScalerStateStore> getStateStore() {
        return stateStoreFactory.get();
    }

    public AutoScalerStateStore getOrCreateStateStore() {
        return stateStoreFactory.getOrCreate();
    }
}


3. AutoScalerEventHandler

AutoScalerEventHandler  will be called by auto scaler when some cases need to be handle, such as: scaling error, report scaling result and update flink job based on the recommended parallelism.

For current code or kubernetes job, most of handlers will record event, all of handlers needs the AbstractFlinkResource AutoScalerHandler will be called by auto scaler when some cases need to be handle, such as: scaling error, report scaling result and update flink job based on the recommended parallelism.
For current code or kubernetes job, most of handlers will record event, all of handlers needs the `AbstractFlinkResource<?, ?>` , it's saved at `INFO extraJobInfo` INFO extraJobInfo  of JobAutoScalerContext .
The `AutoScalerHandler` AutoScalerEventHandler  object is shared for all flink jobs, it doesn't have the job information. However, it needs the `AbstractFlinkResource<?, ?>` AbstractFlinkResource  of every job, that's why adding the `INFO extraJobInfo` INFO extraJobInfo  to the JobAutoScalerContext .


Code Block
/**
 * Handler all events during scaling.
 *
 * @param <KEY>
 * @param <INFO>
 */
public interface AutoScalerHandler<KEYAutoScalerEventHandler<KEY, INFO> {

    void handlerScalingError(handlerScalingFailure(
            JobAutoScalerContext<KEY, INFO> context, String errorMessage);


            FailureReason failureReason,
        void handlerScalingReport(JobAutoScalerContext<KEY, INFO> context, String scalingReportMessageerrorMessage);

    void handlerIneffectiveScalinghandlerScalingReport(JobAutoScalerContext<KEY, INFO> context, String messagescalingReportMessage);

    void handlerRecommendedParallelism(
            JobAutoScalerContext<KEY, INFO> context,
 Map<String,   String> recommendedParallelism);

    /** The reason of autoscaler failure. */
    enum FailureReason {
        HashMap<String, String> recommendedParallelism);
}

4. AutoScalerStateStore

...

ScalingException(true),
        IneffectiveScaling(false);

        // true indicates that the current reason is an unexpected error. False indicates that the
        // current reason is that the strategy causes this scaling to fail.
        private final boolean isError;

        FailureReason(boolean isError) {
            this.isError = isError;
        }

        public boolean isError() {
            return isError;
        }
    }
}


4. AutoScalerStateStore

AutoScalerStateStore  is responsible for persist and access state during scaling.

For current code or kubernetes job, the state is persisted to ConfigMap. So the KubernetesAutoScalerStateStore  needs to fetch ConfigMap before scaling, and persist the ConfigMap after scaling.
For other jobs(yarn or standalone), I implement a HeapedAutoScalerStateStore , it means the state will be lost after autoscaler restart. Of course, we can implement MySQLAutoScalerStateStore  to persist the store in the future.


Code Block
/** It will be used store state during scaling. */
public interface AutoScalerStateStore {

    Optional<String> get(String key);

    // Put the state to state store, please flush the state store to prevent the state lost.
    void put(String key, String value);

    void remove(String key);

    void flush();

    /**
     * The state store cannot be used if the state store isn't valid. Please create a new state
     * store by {@link AutoScalerStateStoreFactory}.
     */
    boolean isValid();
}


Currently, the AutoScalerStateStore is maintained by AutoscalerInfoManager to reduce the access with kubernetes. If the state store isn't vaild, AutoscalerInfoManager will get or create a new AutoScalerStateStore.


Proposed Changes

  1. Ensure new autoscaler module keeps the general auto scaling strategy.
    It includes JobAutoScalerImpl , ScalingMetricCollector , AutoScalerInfo, ScalingExecutor  etc.
    kubernetes related dependencies should be removed from these classes and use JobAutoScalerContext , AutoScalerHandler  and AutoScalerStateStore  instead.

  2. Using the `RestClusterClient<String>` instead of org.apache.flink.kubernetes.operator.service.FlinkService 

    The FlinkService is related to kubernetes, so we shouldn't use it.The RestClusterClient is general flink client, it supports all flink types, including: kubernetes, yarn, standalone.
    The RestClusterClient<String> is included in JobAutoScalerContext.


  3. Implement the default and kubernetes classes for AutoScalerHandler
    The default AutoScalerHandler could be the LoggedAutoScalerHandler. It just log the event when any method is called.



For current code in kubernetes, most of handlers will record event, all of handlers needs the AbstractFlinkResource , it's saved at INFO extraJobInfo  of JobAutoScalerContext .
The AutoScalerHandler  object is shared for all flink jobs, it doesn't have the job information. However, it needs the AbstractFlinkResource of every job, that's why adding the INFO extraJobInfo  to the JobAutoScalerContext . 


Code Block
/** The kubernetes auto scaler event handler. */
public class KubernetesAutoScalerEventHandler<CR extends AbstractFlinkResource<?, ?>>
Code Block
public interface AutoScalerStateStore {

    Optional<String> get(String key);

    // Put the state to state store, please flush the state store to prevent the state lost.
    void put(String key, String value);

    void remove(String key);

    void flush();
}

Proposed Changes

...

The FlinkService is related to kubernetes, so we shouldn't use it.The RestClusterClient is general flink client, it supports all flink types, including: kubernetes, yarn, standalone.
The RestClusterClient<String> is included in JobAutoScalerContext.

...

For current code in kubernetes, most of handlers will record event, all of handlers needs the `AbstractFlinkResource<?, ?>`, it's saved at `INFO extraJobInfo` of JobAutoScalerContext.
The AutoScalerHandler  object is shared for all flink jobs, it doesn't have the job information. However, it needs the `AbstractFlinkResource<?, ?>` of every job, that's why adding the INFO extraJobInfo  to the JobAutoScalerContext. 

Code Block
/**
 * The kubenetes auto scaler handler.
 *
 * @param <CR>
 */
public class KubernetesAutoScalerHandler<CR extends AbstractFlinkResource<?, ?>>
        implements AutoScalerHandler<ResourceID, CR> {

    private final KubernetesClient kubernetesClient;

    private final EventRecorder eventRecorder;

    public KubernetesAutoScalerHandler(
            KubernetesClient kubernetesClient, EventRecorder eventRecorder) {
        this.kubernetesClient = kubernetesClient;
        this.eventRecorder = eventRecorder;
    }

    @Override
    public void handlerScalingError(
            JobAutoScalerContext<ResourceID, CR> context, String errorMessage) {
        eventRecorder.triggerEvent(
                context.getExtraJobInfo(),
                EventRecorder.Type.Warning,
                EventRecorder.Reason.AutoscalerError,
                EventRecorder.Component.Operator,
                errorMessage);
    }

    @Override
    public void handlerScalingReport(
            JobAutoScalerContext<ResourceID, CR> context, String scalingReportMessage) {
        eventRecorder.triggerEvent(
                context.getExtraJobInfo(),
                EventRecorder.Type.Normal,
                EventRecorder.Reason.ScalingReport,
                EventRecorder.Component.Operator,
        implements AutoScalerEventHandler<ResourceID, CR> {

    private scalingReportMessage,
static final Logger LOG =
            "ScalingExecutor"LoggerFactory.getLogger(KubernetesAutoScalerEventHandler.class);

    }private final KubernetesClient kubernetesClient;

     @Overrideprivate final EventRecorder eventRecorder;

    public void handlerIneffectiveScalingKubernetesAutoScalerEventHandler(
            JobAutoScalerContext<ResourceID, CR> contextKubernetesClient kubernetesClient, StringEventRecorder messageeventRecorder) {
        eventRecorderthis.triggerEvent(
kubernetesClient = kubernetesClient;
        this.eventRecorder = eventRecorder;
    context.getExtraJobInfo(),}

    @Override
    public void handlerScalingFailure(
        EventRecorder.Type.Normal,
      JobAutoScalerContext<ResourceID, CR> context,
              EventRecorder.Reason.IneffectiveScalingFailureReason failureReason,
            String    EventRecorder.Component.Operator,errorMessage) {
        eventRecorder.triggerEvent(
        message);
    }

    @Override
 context.getExtraJobInfo(),
   public void handlerRecommendedParallelism(
            JobAutoScalerContext<ResourceID, CR> contextfailureReason.isError() ? EventRecorder.Type.Warning : EventRecorder.Type.Normal,
            HashMap<String, String> recommendedParallelism) {
    failureReason.toString(),
                AbstractFlinkResource<?errorMessage,
  ?> resource = context.getExtraJobInfo();
        var flinkConf = ConfigurationEventRecorder.fromMap(resource.getSpec().getFlinkConfiguration())Component.Operator);
    }

    flinkConf.set(PARALLELISM_OVERRIDES, recommendedParallelism);@Override
    public    resource.getSpec().setFlinkConfiguration(flinkConf.toMap());

void handlerScalingReport(
         KubernetesClientUtils.applyToStoredCr(
   JobAutoScalerContext<ResourceID, CR> context, String scalingReportMessage) {
        kubernetesClient,eventRecorder.triggerEvent(
                resourcecontext.getExtraJobInfo(),
                EventRecorder.Type.Normal,
       stored ->
        EventRecorder.Reason.ScalingReport,
                stored.getSpec()EventRecorder.Component.Operator,
                scalingReportMessage,
                .setFlinkConfiguration(resource.getSpec().getFlinkConfiguration()))"ScalingExecutor");
    }
}

    @Override
    public void handlerRecommendedParallelism(
            JobAutoScalerContext<ResourceID, CR> context,
            Map<String, String> recommendedParallelism) {}
}


Alternative implementation: Create an AutoScalerEventHandler Alternative implementation: Create an AutoScalerHandler for the current job each time JobAutoScaler#scale is called, it means we change the AutoScalerHandler AutoScalerEventHandler to a finer granularity. If so, we can:

  • Adding the AutoScalerHandler AutoScalerEventHandler into the JobAutoScalerContext
  • And adding the JobAutoScalerContext  into the AutoScalerHandlerAutoScalerEventHandler
  • All hander methods don't need the JobAutoScalerContext, because it has includes the JobAutoScalerContext

...

For current code or kubernetes job, the state is persisted to ConfigMap. So the KubernetesAutoScalerStateStore needs to fetch ConfigMap before scaling, and persist the ConfigMap after scaling.the ConfigMap after scaling.

Code Block
/** The kubernetes auto scaler state store, it's based on the config map. */
public class KubernetesAutoScalerStateStore implements AutoScalerStateStore {

    private static final Logger LOG = LoggerFactory.getLogger(KubernetesAutoScalerStateStore.class);

    private final KubernetesClient kubernetesClient;

    private ConfigMap configMap;

    public KubernetesAutoScalerStateStore(KubernetesClient kubernetesClient, ConfigMap configMap) {
Code Block
/** The kubernetes auto scaler state store. */
public class KubernetesAutoScalerStateStore implements AutoScalerStateStore {

    private static final Logger LOG = LoggerFactory.getLogger(KubernetesAutoScalerStateStore.class);

    private static final String LABEL_COMPONENT_AUTOSCALER = "autoscaler";

    private final KubernetesClient kubernetesClient;

    private final ConfigMap configMap;

    public KubernetesAutoScalerStateStore(
            AbstractFlinkResource<?, ?> cr, KubernetesClient kubernetesClient) {
        this.kubernetesClient = kubernetesClient;
        this.configMap = getConfigMap(cr, kubernetesClient);
    }

    public static ConfigMap getConfigMap(
            AbstractFlinkResource<?, ?> cr, KubernetesClient kubeClient) {

        var objectMeta = new ObjectMeta();
        objectMeta.setName("autoscaler-" + cr.getMetadata().getName());
        objectMeta.setNamespace(cr.getMetadata().getNamespace());

        return getScalingInfoConfigMapFromKube(objectMeta, kubeClient)
                .orElseGet(
                        () -> {
                            LOG.info("Creating scaling info config map");

                            objectMeta.setLabels(
                                    Map.of(
                                            Constants.LABEL_COMPONENT_KEY,
                                            LABEL_COMPONENT_AUTOSCALER,
                                            Constants.LABEL_APP_KEY,
                                            cr.getMetadata().getName()));
                            var cm = new ConfigMap();
                            cm.setMetadata(objectMeta);
                            cm.addOwnerReference(cr);
                            cm.setData(new HashMap<>());
                            return kubeClient.resource(cm).create();
                      this.kubernetesClient = })kubernetesClient;
    }

    privatethis.configMap static Optional<ConfigMap> getScalingInfoConfigMapFromKube(= configMap;
    }

    @Override
    ObjectMetapublic objectMeta, KubernetesClient kubeClientOptional<String> get(String key) {
        return Optional.ofNullable(configMap.getData().get(key));
    }

    @Override
    public void put(String key, String value) {
           kubeClientconfigMap.getData().put(key, value);
    }

    @Override
    public void remove(String key) {
        configMap.configMapsgetData().remove(key);
    }

    @Override
    public            .inNamespace(objectMeta.getNamespace())void flush() {
        try {
            configMap =  kubernetesClient.withNameresource(objectMetaconfigMap).getNameupdate());
        } catch (Exception e) {
            LOG.geterror());
    }

         @Override
    public Optional<String> get(String key) {
        return Optional.ofNullable(configMap.getData().get(key)); "Error while updating autoscaler info configmap, invalidating to clear the cache",
    }

       @Override
    public void put(String key, String valuee);
 {
        configMap.getData().put(key, value);
  configMap = }null;

     @Override
    public void remove(String key)throw {e;
        configMap.getData().remove(key);  }
    }

    @Override
    public voidboolean flushisValid() {
        return kubernetesClient.resource(configMap).update()configMap != null;
    }
}



POC

I have finished the POC for FLIP-334, here is the POC branch. This branch has 3 commits:, here is the POC branch. This branch has 3 commits:

  • The first commit: Create the flink-autoscaler module, and move non-kubernetes related autoscaler classes to flink-autoscaler module.
  • The second commit: Add the general interface for autoscaler.
  • The third The first commit: Remove some test classes of autoscaler due to they depend on k8s, I didn't support the unit test in this POC.(For the final PR, I will do it)
  • The second last commit: Decoupling the autosclaer and kubernetes (this commit is core change, it includes all changes about this FLIP)
  • The third commit: Rename the module name from flink-kebernetes-operator-autosclaer  to flink-autoscaler

...

  • .


The flink-autoscaler module doesn't depend on any kubernetes dependencies in this POC. I have tested, it works well with kubernetes.
You can run the flink-kubernetes-operator locally based on the flink-kubernetes-operator-docs and run the autoscaling example.

...