fix operator crashing on first startup (#28997)

This commit is contained in:
Hugo Shaka 2023-07-12 11:53:45 -04:00 committed by GitHub
parent 860931461b
commit b5c11a29a7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -236,12 +236,21 @@ func CreateAndBootstrapBot(ctx context.Context, opts Options) (*Bot, *proto.Feat
// See https://github.com/gravitational/teleport/issues/13091
func createOrReplaceBot(ctx context.Context, opts Options, authClient auth.ClientI) (string, error) {
var token string
// We remove the bot and its role. If this is the first operator to run,
// this throws a "NotFound" error.
// We need to check if the bot exists first and cannot just attempt to delete
// it because DeleteBot() returns an aggregate, which breaks the
// ToGRPC/FromGRPC status code translation. We end up with the wrong error
// type and cannot check if `trace.IsNotFound()`
botRoleName := fmt.Sprintf("bot-%s", opts.Name)
if err := authClient.DeleteBot(ctx, opts.Name); err != nil && !trace.IsNotFound(err) {
exists, err := botExists(ctx, opts, authClient)
if err != nil {
return "", trace.Wrap(err)
}
if exists {
err := authClient.DeleteBot(ctx, opts.Name)
if err != nil {
return "", trace.Wrap(err)
}
}
if err := authClient.DeleteRole(ctx, botRoleName); err != nil && !trace.IsNotFound(err) {
return "", trace.Wrap(err)
}
@ -256,3 +265,16 @@ func createOrReplaceBot(ctx context.Context, opts Options, authClient auth.Clien
return token, nil
}
func botExists(ctx context.Context, opts Options, authClient auth.ClientI) (bool, error) {
botUsers, err := authClient.GetBotUsers(ctx)
if err != nil {
return false, trace.Wrap(err)
}
for _, botUser := range botUsers {
if botUser.GetName() == fmt.Sprintf("bot-%s", opts.Name) {
return true, nil
}
}
return false, nil
}