local.go 11 KB

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