You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by gy...@apache.org on 2023/07/14 11:42:14 UTC

[flink-kubernetes-operator] branch main updated: [FLINK-32317] Enrich metadata in CR error field

This is an automated email from the ASF dual-hosted git repository.

gyfora pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/flink-kubernetes-operator.git


The following commit(s) were added to refs/heads/main by this push:
     new 371a2e6b [FLINK-32317] Enrich metadata in CR error field
371a2e6b is described below

commit 371a2e6bbb8008c8ffccfff8fc338fb39bda19e2
Author: darenwkt <10...@users.noreply.github.com>
AuthorDate: Fri Jul 14 12:42:09 2023 +0100

    [FLINK-32317] Enrich metadata in CR error field
---
 .../shortcodes/generated/dynamic_section.html      |   6 ++
 .../kubernetes_operator_config_configuration.html  |   6 ++
 .../config/FlinkOperatorConfiguration.java         |   5 +
 .../config/KubernetesOperatorConfigOptions.java    |   9 ++
 .../utils/FlinkResourceExceptionUtils.java         |  77 ++++++++++++---
 .../utils/FlinkResourceExceptionUtilsTest.java     | 104 ++++++++++++++++++++-
 .../flink-kubernetes-operator/conf/flink-conf.yaml |   1 +
 7 files changed, 192 insertions(+), 16 deletions(-)

diff --git a/docs/layouts/shortcodes/generated/dynamic_section.html b/docs/layouts/shortcodes/generated/dynamic_section.html
index 327dc129..45ecc3f3 100644
--- a/docs/layouts/shortcodes/generated/dynamic_section.html
+++ b/docs/layouts/shortcodes/generated/dynamic_section.html
@@ -50,6 +50,12 @@
             <td>Boolean</td>
             <td>Whether to enable rolling back failed deployment upgrades.</td>
         </tr>
+        <tr>
+            <td><h5>kubernetes.operator.exception.label.mapper</h5></td>
+            <td style="word-wrap: break-word;"></td>
+            <td>Map</td>
+            <td>Key-Value pair where key is the REGEX to filter through the exception messages and value is the string to be included in CR status error label field if the REGEX matches. Expected format: headerKey1:headerValue1,headerKey2:headerValue2.</td>
+        </tr>
         <tr>
             <td><h5>kubernetes.operator.jm-deployment-recovery.enabled</h5></td>
             <td style="word-wrap: break-word;">true</td>
diff --git a/docs/layouts/shortcodes/generated/kubernetes_operator_config_configuration.html b/docs/layouts/shortcodes/generated/kubernetes_operator_config_configuration.html
index 3c678c2d..b3604b80 100644
--- a/docs/layouts/shortcodes/generated/kubernetes_operator_config_configuration.html
+++ b/docs/layouts/shortcodes/generated/kubernetes_operator_config_configuration.html
@@ -86,6 +86,12 @@
             <td>Integer</td>
             <td>Maximum length of each exception field including stack trace to be included in CR status error field.</td>
         </tr>
+        <tr>
+            <td><h5>kubernetes.operator.exception.label.mapper</h5></td>
+            <td style="word-wrap: break-word;"></td>
+            <td>Map</td>
+            <td>Key-Value pair where key is the REGEX to filter through the exception messages and value is the string to be included in CR status error label field if the REGEX matches. Expected format: headerKey1:headerValue1,headerKey2:headerValue2.</td>
+        </tr>
         <tr>
             <td><h5>kubernetes.operator.exception.stacktrace.enabled</h5></td>
             <td style="word-wrap: break-word;">false</td>
diff --git a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/config/FlinkOperatorConfiguration.java b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/config/FlinkOperatorConfiguration.java
index f32e57d8..d4ed1e79 100644
--- a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/config/FlinkOperatorConfiguration.java
+++ b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/config/FlinkOperatorConfiguration.java
@@ -32,6 +32,7 @@ import org.apache.commons.lang3.StringUtils;
 import java.time.Duration;
 import java.util.Arrays;
 import java.util.HashSet;
+import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
 
@@ -66,6 +67,7 @@ public class FlinkOperatorConfiguration {
     int exceptionStackTraceLengthThreshold;
     int exceptionFieldLengthThreshold;
     int exceptionThrowableCountThreshold;
+    Map<String, String> exceptionLabelMapper;
     String labelSelector;
     LeaderElectionConfiguration leaderElectionConfiguration;
     DeletionPropagation deletionPropagation;
@@ -122,6 +124,8 @@ public class FlinkOperatorConfiguration {
                 operatorConfig.get(
                         KubernetesOperatorConfigOptions
                                 .OPERATOR_EXCEPTION_THROWABLE_LIST_MAX_COUNT);
+        Map<String, String> exceptionLabelMapper =
+                operatorConfig.get(KubernetesOperatorConfigOptions.OPERATOR_EXCEPTION_LABEL_MAPPER);
 
         String flinkServiceHostOverride = null;
         if (getEnv(ENV_KUBERNETES_SERVICE_HOST).isEmpty()) {
@@ -200,6 +204,7 @@ public class FlinkOperatorConfiguration {
                 exceptionStackTraceLengthThreshold,
                 exceptionFieldLengthThreshold,
                 exceptionThrowableCountThreshold,
+                exceptionLabelMapper,
                 labelSelector,
                 getLeaderElectionConfig(operatorConfig),
                 deletionPropagation);
diff --git a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/config/KubernetesOperatorConfigOptions.java b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/config/KubernetesOperatorConfigOptions.java
index 921ca841..7cec45e2 100644
--- a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/config/KubernetesOperatorConfigOptions.java
+++ b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/config/KubernetesOperatorConfigOptions.java
@@ -29,6 +29,7 @@ import io.javaoperatorsdk.operator.api.config.LeaderElectionConfiguration;
 import io.javaoperatorsdk.operator.api.reconciler.Constants;
 
 import java.time.Duration;
+import java.util.HashMap;
 import java.util.Map;
 
 /** This class holds configuration constants used by flink operator. */
@@ -259,6 +260,14 @@ public class KubernetesOperatorConfigOptions {
                     .withDescription(
                             "Maximum number of throwable to be included in CR status error field.");
 
+    @Documentation.Section(SECTION_DYNAMIC)
+    public static final ConfigOption<Map<String, String>> OPERATOR_EXCEPTION_LABEL_MAPPER =
+            operatorConfig("exception.label.mapper")
+                    .mapType()
+                    .defaultValue(new HashMap<>())
+                    .withDescription(
+                            "Key-Value pair where key is the REGEX to filter through the exception messages and value is the string to be included in CR status error label field if the REGEX matches. Expected format: headerKey1:headerValue1,headerKey2:headerValue2.");
+
     @Documentation.Section(SECTION_ADVANCED)
     public static final ConfigOption<Duration> OPERATOR_SAVEPOINT_HISTORY_MAX_AGE_THRESHOLD =
             ConfigOptions.key(OPERATOR_SAVEPOINT_HISTORY_MAX_AGE.key() + ".threshold")
diff --git a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/utils/FlinkResourceExceptionUtils.java b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/utils/FlinkResourceExceptionUtils.java
index 78b26414..8c925879 100644
--- a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/utils/FlinkResourceExceptionUtils.java
+++ b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/utils/FlinkResourceExceptionUtils.java
@@ -29,14 +29,18 @@ import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import org.apache.commons.lang3.exception.ExceptionUtils;
 
+import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.Map;
 import java.util.Optional;
+import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 
 /** Flink Resource Exception utilities. */
 public final class FlinkResourceExceptionUtils {
 
     private static final ObjectMapper objectMapper = new ObjectMapper();
+    public static final String LABELS = "labels";
 
     public static <R extends AbstractFlinkResource> void updateFlinkResourceException(
             Throwable throwable, R resource, FlinkOperatorConfiguration conf) {
@@ -45,6 +49,7 @@ public final class FlinkResourceExceptionUtils {
         int stackTraceLengthThreshold = conf.getExceptionStackTraceLengthThreshold();
         int lengthThreshold = conf.getExceptionFieldLengthThreshold();
         int throwableCountThreshold = conf.getExceptionThrowableCountThreshold();
+        Map<String, String> labelMapper = conf.getExceptionLabelMapper();
 
         Preconditions.checkNotNull(stackTraceEnabled);
 
@@ -54,7 +59,8 @@ public final class FlinkResourceExceptionUtils {
                         stackTraceEnabled,
                         stackTraceLengthThreshold,
                         lengthThreshold,
-                        throwableCountThreshold);
+                        throwableCountThreshold,
+                        labelMapper);
 
         try {
             ((AbstractFlinkResource<?, ?>) resource)
@@ -76,10 +82,16 @@ public final class FlinkResourceExceptionUtils {
             boolean isStackTraceEnabled,
             int stackTraceLengthThreshold,
             int lengthThreshold,
-            int throwableCountThreshold) {
+            int throwableCountThreshold,
+            Map<String, String> labelMapper) {
+
         FlinkResourceException flinkResourceException =
                 convertToFlinkResourceException(
-                        throwable, isStackTraceEnabled, stackTraceLengthThreshold, lengthThreshold);
+                        throwable,
+                        isStackTraceEnabled,
+                        stackTraceLengthThreshold,
+                        lengthThreshold,
+                        labelMapper);
 
         flinkResourceException.setThrowableList(
                 ExceptionUtils.getThrowableList(throwable.getCause()).stream()
@@ -90,7 +102,8 @@ public final class FlinkResourceExceptionUtils {
                                                 t,
                                                 false,
                                                 stackTraceLengthThreshold,
-                                                lengthThreshold))
+                                                lengthThreshold,
+                                                labelMapper))
                         .collect(Collectors.toList()));
 
         return flinkResourceException;
@@ -100,7 +113,8 @@ public final class FlinkResourceExceptionUtils {
             Throwable throwable,
             boolean stackTraceEnabled,
             int stackTraceLengthThreshold,
-            int lengthThreshold) {
+            int lengthThreshold,
+            Map<String, String> labelMapper) {
         FlinkResourceException flinkResourceException = FlinkResourceException.builder().build();
 
         getSubstringWithMaxLength(throwable.getClass().getName(), lengthThreshold)
@@ -109,11 +123,12 @@ public final class FlinkResourceExceptionUtils {
                 .ifPresent(flinkResourceException::setMessage);
 
         if (stackTraceEnabled) {
-            getSubstringWithMaxLength(ExceptionUtils.getStackTrace(throwable), lengthThreshold)
+            getSubstringWithMaxLength(
+                            ExceptionUtils.getStackTrace(throwable), stackTraceLengthThreshold)
                     .ifPresent(flinkResourceException::setStackTrace);
         }
 
-        enrichMetadata(throwable, flinkResourceException, lengthThreshold);
+        enrichMetadata(throwable, flinkResourceException, lengthThreshold, labelMapper);
 
         return flinkResourceException;
     }
@@ -129,12 +144,18 @@ public final class FlinkResourceExceptionUtils {
     private static void enrichMetadata(
             Throwable throwable,
             FlinkResourceException flinkResourceException,
-            int lengthThreshold) {
+            int lengthThreshold,
+            Map<String, String> labelMapper) {
+        if (flinkResourceException.getAdditionalMetadata() == null) {
+            flinkResourceException.setAdditionalMetadata(new HashMap<>());
+        }
+
         if (throwable instanceof RestClientException) {
-            flinkResourceException.setAdditionalMetadata(
-                    Map.of(
+            flinkResourceException
+                    .getAdditionalMetadata()
+                    .put(
                             "httpResponseCode",
-                            ((RestClientException) throwable).getHttpResponseStatus().code()));
+                            ((RestClientException) throwable).getHttpResponseStatus().code());
         }
 
         if (throwable instanceof DeploymentFailedException) {
@@ -142,13 +163,43 @@ public final class FlinkResourceExceptionUtils {
                             ((DeploymentFailedException) throwable).getReason(), lengthThreshold)
                     .ifPresent(
                             reason ->
-                                    flinkResourceException.setAdditionalMetadata(
-                                            Map.of("reason", reason)));
+                                    flinkResourceException
+                                            .getAdditionalMetadata()
+                                            .put("reason", reason));
         }
 
+        labelMapper
+                .entrySet()
+                .forEach(
+                        (entry) -> {
+                            Pattern pattern = Pattern.compile(entry.getKey());
+
+                            org.apache.flink.util.ExceptionUtils.findThrowable(
+                                            throwable,
+                                            t ->
+                                                    pattern.matcher(
+                                                                    Optional.ofNullable(
+                                                                                    t.getMessage())
+                                                                            .orElse(""))
+                                                            .find())
+                                    .ifPresent(
+                                            (t) -> {
+                                                enrichMetadataWithLabelMapper(
+                                                        flinkResourceException, entry.getValue());
+                                            });
+                        });
+
         // This section can be extended to enrich more metadata in the future.
     }
 
+    private static void enrichMetadataWithLabelMapper(
+            FlinkResourceException flinkResourceException, String value) {
+        if (!flinkResourceException.getAdditionalMetadata().containsKey(LABELS)) {
+            flinkResourceException.getAdditionalMetadata().put(LABELS, new ArrayList<String>());
+        }
+        ((ArrayList) flinkResourceException.getAdditionalMetadata().get(LABELS)).add(value);
+    }
+
     private static String convertToJson(FlinkResourceException flinkResourceException)
             throws JsonProcessingException {
         return objectMapper.writeValueAsString(flinkResourceException);
diff --git a/flink-kubernetes-operator/src/test/java/org/apache/flink/kubernetes/operator/utils/FlinkResourceExceptionUtilsTest.java b/flink-kubernetes-operator/src/test/java/org/apache/flink/kubernetes/operator/utils/FlinkResourceExceptionUtilsTest.java
index 13ca0861..f66f84b7 100644
--- a/flink-kubernetes-operator/src/test/java/org/apache/flink/kubernetes/operator/utils/FlinkResourceExceptionUtilsTest.java
+++ b/flink-kubernetes-operator/src/test/java/org/apache/flink/kubernetes/operator/utils/FlinkResourceExceptionUtilsTest.java
@@ -36,10 +36,17 @@ import org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseSt
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
 
+import java.util.ArrayList;
 import java.util.List;
+import java.util.Map;
 import java.util.Optional;
+import java.util.stream.Stream;
 
+import static org.apache.flink.kubernetes.operator.utils.FlinkResourceExceptionUtils.LABELS;
 import static org.apache.flink.kubernetes.operator.utils.FlinkResourceExceptionUtils.getSubstringWithMaxLength;
 import static org.apache.flink.kubernetes.operator.utils.FlinkResourceExceptionUtils.updateFlinkResourceException;
 import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -70,6 +77,9 @@ public class FlinkResourceExceptionUtilsTest {
         assertEquals(
                 KubernetesOperatorConfigOptions.OPERATOR_EXCEPTION_FIELD_MAX_LENGTH.defaultValue(),
                 configManager.getOperatorConfiguration().getExceptionFieldLengthThreshold());
+        assertEquals(
+                KubernetesOperatorConfigOptions.OPERATOR_EXCEPTION_LABEL_MAPPER.defaultValue(),
+                configManager.getOperatorConfiguration().getExceptionLabelMapper());
 
         testUpdateFlinkResourceException(configManager);
 
@@ -80,6 +90,7 @@ public class FlinkResourceExceptionUtilsTest {
         testConfig.set(
                 KubernetesOperatorConfigOptions.OPERATOR_EXCEPTION_THROWABLE_LIST_MAX_COUNT, 0);
         testConfig.set(KubernetesOperatorConfigOptions.OPERATOR_EXCEPTION_FIELD_MAX_LENGTH, 0);
+        testConfig.set(KubernetesOperatorConfigOptions.OPERATOR_EXCEPTION_LABEL_MAPPER, Map.of());
 
         configManager.updateDefaultConfig(testConfig);
         testUpdateFlinkResourceException(configManager);
@@ -89,6 +100,9 @@ public class FlinkResourceExceptionUtilsTest {
         testConfig.set(
                 KubernetesOperatorConfigOptions.OPERATOR_EXCEPTION_THROWABLE_LIST_MAX_COUNT, 100);
         testConfig.set(KubernetesOperatorConfigOptions.OPERATOR_EXCEPTION_FIELD_MAX_LENGTH, 100);
+        testConfig.set(
+                KubernetesOperatorConfigOptions.OPERATOR_EXCEPTION_LABEL_MAPPER,
+                Map.of("rest client .*", "rest exception found"));
 
         configManager.updateDefaultConfig(testConfig);
         testUpdateFlinkResourceException(configManager);
@@ -115,7 +129,6 @@ public class FlinkResourceExceptionUtilsTest {
             FlinkResourceException flinkResourceException =
                     new ObjectMapper().readValue(errorJson, FlinkResourceException.class);
 
-            assertNull(flinkResourceException.getAdditionalMetadata());
             assertEquals(
                     getSubstringWithMaxLength(
                                     "reconciliation exception message",
@@ -139,6 +152,22 @@ public class FlinkResourceExceptionUtilsTest {
                                     .getOperatorConfiguration()
                                     .getExceptionThrowableCountThreshold());
 
+            configManager
+                    .getOperatorConfiguration()
+                    .getExceptionLabelMapper()
+                    .forEach(
+                            (key, value) -> {
+                                assertTrue(
+                                        flinkResourceException.getAdditionalMetadata().get(LABELS)
+                                                instanceof ArrayList);
+                                assertTrue(
+                                        ((ArrayList<?>)
+                                                        flinkResourceException
+                                                                .getAdditionalMetadata()
+                                                                .get(LABELS))
+                                                .contains(value));
+                            });
+
             flinkResourceException
                     .getThrowableList()
                     .forEach(
@@ -184,7 +213,76 @@ public class FlinkResourceExceptionUtilsTest {
         }
     }
 
-    private ReconciliationException getTestException() {
+    private static Stream<Arguments> labelMapperProvider() {
+        return Stream.of(
+                Arguments.of(Map.of(), List.of(), getTestException()),
+                Arguments.of(
+                        Map.of("test rest client", "rest exception found"),
+                        List.of(),
+                        getTestException()),
+                Arguments.of(
+                        Map.of("rest client .*", "rest exception found"),
+                        List.of("rest exception found"),
+                        getTestException()),
+                Arguments.of(
+                        Map.of(
+                                "rest client .*",
+                                "rest exception found",
+                                ".*missing.*",
+                                "job manager is missing"),
+                        List.of("rest exception found", "job manager is missing"),
+                        getTestException()),
+                Arguments.of(
+                        Map.of("test rest client", "rest exception found"),
+                        List.of(),
+                        new Exception()));
+    }
+
+    @ParameterizedTest
+    @MethodSource("labelMapperProvider")
+    public void testUpdateFlinkResourceExceptionWithLabelMapper(
+            Map<String, String> labelMapper,
+            List<String> expectedLabelMapperMetadata,
+            Exception testException)
+            throws JsonProcessingException {
+        Configuration testConfig = new Configuration();
+        FlinkConfigManager configManager = new FlinkConfigManager(testConfig);
+
+        testConfig.set(
+                KubernetesOperatorConfigOptions.OPERATOR_EXCEPTION_LABEL_MAPPER, labelMapper);
+        configManager.updateDefaultConfig(testConfig);
+
+        List<AbstractFlinkResource> resources = getTestResources();
+        for (AbstractFlinkResource resource : resources) {
+            updateFlinkResourceException(
+                    testException, resource, configManager.getOperatorConfiguration());
+
+            String errorJson =
+                    Optional.ofNullable(resource)
+                            .map(r -> (CommonStatus) r.getStatus())
+                            .map(CommonStatus::getError)
+                            .orElseThrow(RuntimeException::new);
+
+            FlinkResourceException flinkResourceException =
+                    new ObjectMapper().readValue(errorJson, FlinkResourceException.class);
+
+            if (flinkResourceException.getAdditionalMetadata().get(LABELS) != null) {
+                assertTrue(
+                        flinkResourceException.getAdditionalMetadata().get(LABELS) instanceof List);
+                List<String> labelMapperList =
+                        (ArrayList) flinkResourceException.getAdditionalMetadata().get(LABELS);
+
+                expectedLabelMapperMetadata.forEach(
+                        (value) -> {
+                            assertTrue(labelMapperList.contains(value));
+                        });
+
+                assertEquals(expectedLabelMapperMetadata.size(), labelMapperList.size());
+            }
+        }
+    }
+
+    private static ReconciliationException getTestException() {
         return new ReconciliationException(
                 "reconciliation exception message",
                 new MissingJobManagerException(
@@ -197,7 +295,7 @@ public class FlinkResourceExceptionUtilsTest {
                                 new HttpResponseStatus(400, "http response status"))));
     }
 
-    private List<AbstractFlinkResource> getTestResources() {
+    private static List<AbstractFlinkResource> getTestResources() {
         return List.of(new FlinkSessionJob(), new FlinkDeployment());
     }
 }
diff --git a/helm/flink-kubernetes-operator/conf/flink-conf.yaml b/helm/flink-kubernetes-operator/conf/flink-conf.yaml
index a396305b..b94cc937 100644
--- a/helm/flink-kubernetes-operator/conf/flink-conf.yaml
+++ b/helm/flink-kubernetes-operator/conf/flink-conf.yaml
@@ -43,6 +43,7 @@ parallelism.default: 1
 # kubernetes.operator.exception.stacktrace.max.length: 2048
 # kubernetes.operator.exception.field.max.length: 2048
 # kubernetes.operator.exception.throwable.list.max.count: 2
+# kubernetes.operator.exception.label.mapper: Job has already been submitted:duplicatedJobFound,Server returned HTTP response code:httpResponseCodeFound
 # kubernetes.operator.leader-election.enabled: false
 # kubernetes.operator.leader-election.lease-name: flink-operator-lease