token.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package node
  14. import (
  15. "context"
  16. "github.com/pkg/errors"
  17. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  18. clientset "k8s.io/client-go/kubernetes"
  19. bootstraputil "k8s.io/cluster-bootstrap/token/util"
  20. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  21. "k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient"
  22. )
  23. // TODO(mattmoyer): Move CreateNewTokens, UpdateOrCreateTokens out of this package to client-go for a generic abstraction and client for a Bootstrap Token
  24. // CreateNewTokens tries to create a token and fails if one with the same ID already exists
  25. func CreateNewTokens(client clientset.Interface, tokens []kubeadmapi.BootstrapToken) error {
  26. return UpdateOrCreateTokens(client, true, tokens)
  27. }
  28. // UpdateOrCreateTokens attempts to update a token with the given ID, or create if it does not already exist.
  29. func UpdateOrCreateTokens(client clientset.Interface, failIfExists bool, tokens []kubeadmapi.BootstrapToken) error {
  30. for _, token := range tokens {
  31. secretName := bootstraputil.BootstrapTokenSecretName(token.Token.ID)
  32. secret, err := client.CoreV1().Secrets(metav1.NamespaceSystem).Get(context.TODO(), secretName, metav1.GetOptions{})
  33. if secret != nil && err == nil && failIfExists {
  34. return errors.Errorf("a token with id %q already exists", token.Token.ID)
  35. }
  36. updatedOrNewSecret := token.ToSecret()
  37. // Try to create or update the token with an exponential backoff
  38. err = apiclient.TryRunCommand(func() error {
  39. if err := apiclient.CreateOrUpdateSecret(client, updatedOrNewSecret); err != nil {
  40. return errors.Wrapf(err, "failed to create or update bootstrap token with name %s", secretName)
  41. }
  42. return nil
  43. }, 5)
  44. if err != nil {
  45. return err
  46. }
  47. }
  48. return nil
  49. }