From 22dffb08245f5694a11bded59ce181d9e3a7e602 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=87=91=E6=88=9F?= Date: Tue, 30 Nov 2021 00:24:47 +0800 Subject: [PATCH] feat: handle pod exec error --- pkg/kt/cluster/kubernetes.go | 8 +++++++- pkg/kt/util/strings.go | 16 ++++++++++++++++ pkg/kt/util/strings_test.go | 6 ++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/pkg/kt/cluster/kubernetes.go b/pkg/kt/cluster/kubernetes.go index da096e6f..a2d2ec45 100644 --- a/pkg/kt/cluster/kubernetes.go +++ b/pkg/kt/cluster/kubernetes.go @@ -211,7 +211,13 @@ func (k *Kubernetes) ExecInPod(containerName, podName, namespace string, opts op var stdout, stderr bytes.Buffer log.Debug().Msgf("Execute command %v in %s:%s", cmd, podName, containerName) err := execute("POST", req.URL(), opts.RestConfig, nil, &stdout, &stderr, false) - return strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), err + stdoutMsg := util.RemoveColor(strings.TrimSpace(stdout.String())) + stderrMsg := util.RemoveColor(strings.TrimSpace(stderr.String())) + rawErrMsg := util.ExtractErrorMessage(stderrMsg) + if err == nil && rawErrMsg != "" { + err = fmt.Errorf(rawErrMsg) + } + return stdoutMsg, stderrMsg, err } func (k *Kubernetes) CreateConfigMapWithSshKey(ctx context.Context, labels map[string]string, sshcm string, namespace string, diff --git a/pkg/kt/util/strings.go b/pkg/kt/util/strings.go index e003e534..5d068b29 100644 --- a/pkg/kt/util/strings.go +++ b/pkg/kt/util/strings.go @@ -3,6 +3,7 @@ package util import ( "fmt" "math/rand" + "regexp" "strings" "time" ) @@ -53,3 +54,18 @@ func Append(base string, inc string) string { return fmt.Sprintf("%s,%s", base, inc) } } + +// RemoveColor remove shell color character in text +func RemoveColor(msg string) string { + colorExp := regexp.MustCompile("\033\\[[0-9]+m") + return colorExp.ReplaceAllString(msg, "") +} + +// ExtractErrorMessage extract error from log +func ExtractErrorMessage(msg string) string { + errExp := regexp.MustCompile(" error=\"([^\"]+)\"") + if strings.Contains(msg, " ERR ") && errExp.MatchString(msg) { + return errExp.FindStringSubmatch(msg)[1] + } + return "" +} diff --git a/pkg/kt/util/strings_test.go b/pkg/kt/util/strings_test.go index f0e19261..c9b5dcab 100644 --- a/pkg/kt/util/strings_test.go +++ b/pkg/kt/util/strings_test.go @@ -32,3 +32,9 @@ func TestString2Map(t *testing.T) { }) } } + +func Test_ExtractErrorMessage(t *testing.T) { + require.Equal(t, "specfied header 'kt_version' no match mesh pod header 'vvvv'", + ExtractErrorMessage("4:00PM ERR Update route with add failed error=\"specfied header 'kt_version' no match mesh pod header 'vvvv'\"")) + require.Empty(t, ExtractErrorMessage("4:00PM INFO Route updated.")) +}