Skip to content

Commit

Permalink
Get or create join tocken on get-join-token (#202)
Browse files Browse the repository at this point in the history
* get or create join tocken

* improve grab token function
  • Loading branch information
louiseschmidtgen authored Mar 5, 2024
1 parent 61310ce commit e46dddf
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/k8s/pkg/k8sd/api/cluster_tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func postClusterJoinTokens(m *microcluster.MicroCluster, s *state.State, r *http
if req.Worker {
token, err = createWorkerToken(s)
} else {
token, err = m.NewJoinToken(hostname)
token, err = getOrCreateJoinToken(m, hostname)
}
if err != nil {
return response.InternalError(fmt.Errorf("failed to create token: %w", err))
Expand All @@ -40,6 +40,28 @@ func postClusterJoinTokens(m *microcluster.MicroCluster, s *state.State, r *http
return response.SyncResponse(true, &apiv1.TokensResponse{EncodedToken: token})
}

func getOrCreateJoinToken(m *microcluster.MicroCluster, tokenName string) (string, error) {
// grab token if it exists and return it
records, err := m.ListJoinTokens()
if err != nil {
fmt.Println("Failed to get existing tokens. Trying to create a new token.")
} else {
for _, record := range records {
if record.Name == tokenName {
return record.Token, nil
}
}
fmt.Println("No token exists yet. Creating a new token.")
}

// if token does not exist, create a new one
token, err := m.NewJoinToken(tokenName)
if err != nil {
return "", fmt.Errorf("failed to generate a new microcluster join token: %w", err)
}
return token, nil
}

func createWorkerToken(s *state.State) (string, error) {
var token string
if err := s.Database.Transaction(s.Context, func(ctx context.Context, tx *sql.Tx) error {
Expand Down

0 comments on commit e46dddf

Please sign in to comment.