From 4d071b7d10d7c1bea12e2821fc3219527faa3dc1 Mon Sep 17 00:00:00 2001 From: Gabriel Adrian Samfira Date: Fri, 27 Jan 2023 16:27:25 +0200 Subject: [PATCH] Return only alpha numeric characters as an ID On some providers the default character set used by shortid may lead to errors when creating runners, due to the fact that underscores are not allowed in their names. Signed-off-by: Gabriel Adrian Samfira --- runner/pool/pool.go | 8 +------- util/util.go | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/runner/pool/pool.go b/runner/pool/pool.go index 9670e1d2..897939b6 100644 --- a/runner/pool/pool.go +++ b/runner/pool/pool.go @@ -33,9 +33,7 @@ import ( "garm/util" "github.com/google/go-github/v48/github" - "github.com/google/uuid" "github.com/pkg/errors" - "github.com/teris-io/shortid" ) var ( @@ -396,11 +394,7 @@ func (r *basePoolManager) AddRunner(ctx context.Context, poolID string) error { return errors.Wrap(err, "fetching pool") } - suffix, err := shortid.Generate() - if err != nil { - suffix = uuid.New().String() - } - name := fmt.Sprintf("%s-%s", pool.GetRunnerPrefix(), suffix) + name := fmt.Sprintf("%s-%s", pool.GetRunnerPrefix(), util.NewID()) createParams := params.CreateInstanceParams{ Name: name, diff --git a/util/util.go b/util/util.go index e7129929..57b9f72b 100644 --- a/util/util.go +++ b/util/util.go @@ -38,8 +38,10 @@ import ( "garm/runner/common" "github.com/google/go-github/v48/github" + "github.com/google/uuid" gorillaHandlers "github.com/gorilla/handlers" "github.com/pkg/errors" + "github.com/teris-io/shortid" "golang.org/x/crypto/bcrypt" "golang.org/x/oauth2" lumberjack "gopkg.in/natefinch/lumberjack.v2" @@ -331,3 +333,27 @@ func NewLoggingMiddleware(writer io.Writer) func(http.Handler) http.Handler { func SanitizeLogEntry(entry string) string { return strings.Replace(strings.Replace(entry, "\n", "", -1), "\r", "", -1) } + +func randomCharacter() string { + for i := 0; i < 5; i++ { + character, err := GetRandomString(1) + if err != nil { + continue + } + return character + } + return "" +} + +func NewID() string { + newID, err := shortid.Generate() + if err != nil { + newID = uuid.New().String() + } else { + // remove underscores and hyphens from short ID. The hypens will remain + // if we are forced to fall back to uuid4. + newID = strings.Replace(newID, "_", randomCharacter(), -1) + newID = strings.Replace(newID, "-", randomCharacter(), -1) + } + return newID +}