k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/cmd/kubeadm/app/phases/bootstraptoken/node/token.go (about) 1 /* 2 Copyright 2017 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package node 18 19 import ( 20 "context" 21 22 "github.com/pkg/errors" 23 24 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 25 "k8s.io/apimachinery/pkg/util/wait" 26 clientset "k8s.io/client-go/kubernetes" 27 bootstraputil "k8s.io/cluster-bootstrap/token/util" 28 29 bootstraptokenv1 "k8s.io/kubernetes/cmd/kubeadm/app/apis/bootstraptoken/v1" 30 kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" 31 kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants" 32 "k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient" 33 ) 34 35 // CreateNewTokens tries to create a token and fails if one with the same ID already exists 36 func CreateNewTokens(client clientset.Interface, tokens []bootstraptokenv1.BootstrapToken) error { 37 return UpdateOrCreateTokens(client, true, tokens) 38 } 39 40 // UpdateOrCreateTokens attempts to update a token with the given ID, or create if it does not already exist. 41 func UpdateOrCreateTokens(client clientset.Interface, failIfExists bool, tokens []bootstraptokenv1.BootstrapToken) error { 42 43 for _, token := range tokens { 44 45 secretName := bootstraputil.BootstrapTokenSecretName(token.Token.ID) 46 secret, err := client.CoreV1().Secrets(metav1.NamespaceSystem).Get(context.TODO(), secretName, metav1.GetOptions{}) 47 if secret != nil && err == nil && failIfExists { 48 return errors.Errorf("a token with id %q already exists", token.Token.ID) 49 } 50 51 updatedOrNewSecret := bootstraptokenv1.BootstrapTokenToSecret(&token) 52 53 var lastError error 54 err = wait.PollUntilContextTimeout( 55 context.Background(), 56 kubeadmconstants.KubernetesAPICallRetryInterval, 57 kubeadmapi.GetActiveTimeouts().KubernetesAPICall.Duration, 58 true, func(_ context.Context) (bool, error) { 59 if err := apiclient.CreateOrUpdateSecret(client, updatedOrNewSecret); err != nil { 60 lastError = errors.Wrapf(err, "failed to create or update bootstrap token with name %s", secretName) 61 return false, nil 62 } 63 return true, nil 64 }) 65 if err != nil { 66 return lastError 67 } 68 } 69 return nil 70 }