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 <gsamfira@cloudbasesolutions.com>
This commit is contained in:
Gabriel Adrian Samfira 2023-01-27 16:27:25 +02:00
parent 8f56f51598
commit 4d071b7d10
2 changed files with 27 additions and 7 deletions

View file

@ -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,

View file

@ -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
}