local.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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 etcd
  14. import (
  15. "fmt"
  16. "path/filepath"
  17. "strings"
  18. "time"
  19. "github.com/pkg/errors"
  20. "k8s.io/klog"
  21. "k8s.io/api/core/v1"
  22. clientset "k8s.io/client-go/kubernetes"
  23. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  24. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  25. "k8s.io/kubernetes/cmd/kubeadm/app/images"
  26. kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
  27. etcdutil "k8s.io/kubernetes/cmd/kubeadm/app/util/etcd"
  28. staticpodutil "k8s.io/kubernetes/cmd/kubeadm/app/util/staticpod"
  29. )
  30. const (
  31. etcdVolumeName = "etcd-data"
  32. certsVolumeName = "etcd-certs"
  33. etcdHealthyCheckInterval = 5 * time.Second
  34. etcdHealthyCheckRetries = 8
  35. )
  36. // CreateLocalEtcdStaticPodManifestFile will write local etcd static pod manifest file.
  37. // This function is used by init - when the etcd cluster is empty - or by kubeadm
  38. // upgrade - when the etcd cluster is already up and running (and the --initial-cluster flag have no impact)
  39. func CreateLocalEtcdStaticPodManifestFile(manifestDir string, nodeName string, cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint) error {
  40. if cfg.Etcd.External != nil {
  41. return errors.New("etcd static pod manifest cannot be generated for cluster using external etcd")
  42. }
  43. // gets etcd StaticPodSpec
  44. spec := GetEtcdPodSpec(cfg, endpoint, nodeName, []etcdutil.Member{})
  45. // writes etcd StaticPod to disk
  46. if err := staticpodutil.WriteStaticPodToDisk(kubeadmconstants.Etcd, manifestDir, spec); err != nil {
  47. return err
  48. }
  49. klog.V(1).Infof("[etcd] wrote Static Pod manifest for a local etcd member to %q\n", kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.Etcd, manifestDir))
  50. return nil
  51. }
  52. // CheckLocalEtcdClusterStatus verifies health state of local/stacked etcd cluster before installing a new etcd member
  53. func CheckLocalEtcdClusterStatus(client clientset.Interface, cfg *kubeadmapi.ClusterConfiguration) error {
  54. klog.V(1).Info("[etcd] Checking etcd cluster health")
  55. // creates an etcd client that connects to all the local/stacked etcd members
  56. klog.V(1).Info("creating etcd client that connects to etcd pods")
  57. etcdClient, err := etcdutil.NewFromCluster(client, cfg.CertificatesDir)
  58. if err != nil {
  59. return err
  60. }
  61. // Checking health state
  62. _, err = etcdClient.GetClusterStatus()
  63. if err != nil {
  64. return errors.Wrap(err, "etcd cluster is not healthy")
  65. }
  66. return nil
  67. }
  68. // RemoveStackedEtcdMemberFromCluster will remove a local etcd member from etcd cluster,
  69. // when reset the control plane node.
  70. func RemoveStackedEtcdMemberFromCluster(client clientset.Interface, cfg *kubeadmapi.InitConfiguration) error {
  71. // creates an etcd client that connects to all the local/stacked etcd members
  72. klog.V(1).Info("[etcd] creating etcd client that connects to etcd pods")
  73. etcdClient, err := etcdutil.NewFromCluster(client, cfg.CertificatesDir)
  74. if err != nil {
  75. return err
  76. }
  77. // notifies the other members of the etcd cluster about the removing member
  78. etcdPeerAddress := etcdutil.GetPeerURL(&cfg.LocalAPIEndpoint)
  79. klog.V(2).Infof("[etcd] get the member id from peer: %s", etcdPeerAddress)
  80. id, err := etcdClient.GetMemberID(etcdPeerAddress)
  81. if err != nil {
  82. return err
  83. }
  84. klog.V(1).Infof("[etcd] removing etcd member: %s, id: %d", etcdPeerAddress, id)
  85. members, err := etcdClient.RemoveMember(id)
  86. if err != nil {
  87. return err
  88. }
  89. klog.V(1).Infof("[etcd] Updated etcd member list: %v", members)
  90. return nil
  91. }
  92. // CreateStackedEtcdStaticPodManifestFile will write local etcd static pod manifest file
  93. // for an additional etcd member that is joining an existing local/stacked etcd cluster.
  94. // Other members of the etcd cluster will be notified of the joining node in beforehand as well.
  95. func CreateStackedEtcdStaticPodManifestFile(client clientset.Interface, manifestDir string, nodeName string, cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint) error {
  96. // creates an etcd client that connects to all the local/stacked etcd members
  97. klog.V(1).Info("creating etcd client that connects to etcd pods")
  98. etcdClient, err := etcdutil.NewFromCluster(client, cfg.CertificatesDir)
  99. if err != nil {
  100. return err
  101. }
  102. // notifies the other members of the etcd cluster about the joining member
  103. etcdPeerAddress := etcdutil.GetPeerURL(endpoint)
  104. klog.V(1).Infof("Adding etcd member: %s", etcdPeerAddress)
  105. initialCluster, err := etcdClient.AddMember(nodeName, etcdPeerAddress)
  106. if err != nil {
  107. return err
  108. }
  109. fmt.Println("[etcd] Announced new etcd member joining to the existing etcd cluster")
  110. klog.V(1).Infof("Updated etcd member list: %v", initialCluster)
  111. klog.V(1).Info("Creating local etcd static pod manifest file")
  112. // gets etcd StaticPodSpec, actualized for the current InitConfiguration and the new list of etcd members
  113. spec := GetEtcdPodSpec(cfg, endpoint, nodeName, initialCluster)
  114. // writes etcd StaticPod to disk
  115. if err := staticpodutil.WriteStaticPodToDisk(kubeadmconstants.Etcd, manifestDir, spec); err != nil {
  116. return err
  117. }
  118. fmt.Printf("[etcd] Wrote Static Pod manifest for a local etcd member to %q\n", kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.Etcd, manifestDir))
  119. fmt.Printf("[etcd] Waiting for the new etcd member to join the cluster. This can take up to %v\n", etcdHealthyCheckInterval*etcdHealthyCheckRetries)
  120. if _, err := etcdClient.WaitForClusterAvailable(etcdHealthyCheckRetries, etcdHealthyCheckInterval); err != nil {
  121. return err
  122. }
  123. return nil
  124. }
  125. // GetEtcdPodSpec returns the etcd static Pod actualized to the context of the current configuration
  126. // NB. GetEtcdPodSpec methods holds the information about how kubeadm creates etcd static pod manifests.
  127. func GetEtcdPodSpec(cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, nodeName string, initialCluster []etcdutil.Member) v1.Pod {
  128. pathType := v1.HostPathDirectoryOrCreate
  129. etcdMounts := map[string]v1.Volume{
  130. etcdVolumeName: staticpodutil.NewVolume(etcdVolumeName, cfg.Etcd.Local.DataDir, &pathType),
  131. certsVolumeName: staticpodutil.NewVolume(certsVolumeName, cfg.CertificatesDir+"/etcd", &pathType),
  132. }
  133. return staticpodutil.ComponentPod(v1.Container{
  134. Name: kubeadmconstants.Etcd,
  135. Command: getEtcdCommand(cfg, endpoint, nodeName, initialCluster),
  136. Image: images.GetEtcdImage(cfg),
  137. ImagePullPolicy: v1.PullIfNotPresent,
  138. // Mount the etcd datadir path read-write so etcd can store data in a more persistent manner
  139. VolumeMounts: []v1.VolumeMount{
  140. staticpodutil.NewVolumeMount(etcdVolumeName, cfg.Etcd.Local.DataDir, false),
  141. staticpodutil.NewVolumeMount(certsVolumeName, cfg.CertificatesDir+"/etcd", false),
  142. },
  143. LivenessProbe: staticpodutil.EtcdProbe(
  144. &cfg.Etcd, kubeadmconstants.EtcdListenClientPort, cfg.CertificatesDir,
  145. kubeadmconstants.EtcdCACertName, kubeadmconstants.EtcdHealthcheckClientCertName, kubeadmconstants.EtcdHealthcheckClientKeyName,
  146. ),
  147. }, etcdMounts)
  148. }
  149. // getEtcdCommand builds the right etcd command from the given config object
  150. func getEtcdCommand(cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, nodeName string, initialCluster []etcdutil.Member) []string {
  151. defaultArguments := map[string]string{
  152. "name": nodeName,
  153. "listen-client-urls": fmt.Sprintf("%s,%s", etcdutil.GetClientURLByIP("127.0.0.1"), etcdutil.GetClientURL(endpoint)),
  154. "advertise-client-urls": etcdutil.GetClientURL(endpoint),
  155. "listen-peer-urls": etcdutil.GetPeerURL(endpoint),
  156. "initial-advertise-peer-urls": etcdutil.GetPeerURL(endpoint),
  157. "data-dir": cfg.Etcd.Local.DataDir,
  158. "cert-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdServerCertName),
  159. "key-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdServerKeyName),
  160. "trusted-ca-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdCACertName),
  161. "client-cert-auth": "true",
  162. "peer-cert-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdPeerCertName),
  163. "peer-key-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdPeerKeyName),
  164. "peer-trusted-ca-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdCACertName),
  165. "peer-client-cert-auth": "true",
  166. "snapshot-count": "10000",
  167. }
  168. if len(initialCluster) == 0 {
  169. defaultArguments["initial-cluster"] = fmt.Sprintf("%s=%s", nodeName, etcdutil.GetPeerURL(endpoint))
  170. } else {
  171. // NB. the joining etcd member should be part of the initialCluster list
  172. endpoints := []string{}
  173. for _, member := range initialCluster {
  174. endpoints = append(endpoints, fmt.Sprintf("%s=%s", member.Name, member.PeerURL))
  175. }
  176. defaultArguments["initial-cluster"] = strings.Join(endpoints, ",")
  177. defaultArguments["initial-cluster-state"] = "existing"
  178. }
  179. command := []string{"etcd"}
  180. command = append(command, kubeadmutil.BuildArgumentListFromMap(defaultArguments, cfg.Etcd.Local.ExtraArgs)...)
  181. return command
  182. }