Skip to content

Commit

Permalink
feat: handle pod exec error
Browse files Browse the repository at this point in the history
  • Loading branch information
linfan committed Nov 29, 2021
1 parent 18020c1 commit 22dffb0
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
8 changes: 7 additions & 1 deletion pkg/kt/cluster/kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
16 changes: 16 additions & 0 deletions pkg/kt/util/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package util
import (
"fmt"
"math/rand"
"regexp"
"strings"
"time"
)
Expand Down Expand Up @@ -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 ""
}
6 changes: 6 additions & 0 deletions pkg/kt/util/strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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."))
}

0 comments on commit 22dffb0

Please # to comment.