utils.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 staticpod
  14. import (
  15. "bytes"
  16. "fmt"
  17. "io/ioutil"
  18. "net"
  19. "net/url"
  20. "os"
  21. "sort"
  22. "strings"
  23. "github.com/pkg/errors"
  24. "k8s.io/api/core/v1"
  25. "k8s.io/apimachinery/pkg/api/resource"
  26. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  27. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  28. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  29. "k8s.io/kubernetes/cmd/kubeadm/app/util"
  30. )
  31. const (
  32. // kubeControllerManagerAddressArg represents the address argument of the kube-controller-manager configuration.
  33. kubeControllerManagerAddressArg = "address"
  34. // kubeSchedulerAddressArg represents the address argument of the kube-scheduler configuration.
  35. kubeSchedulerAddressArg = "address"
  36. // etcdListenClientURLsArg represents the listen-client-urls argument of the etcd configuration.
  37. etcdListenClientURLsArg = "listen-client-urls"
  38. )
  39. // ComponentPod returns a Pod object from the container and volume specifications
  40. func ComponentPod(container v1.Container, volumes map[string]v1.Volume) v1.Pod {
  41. return v1.Pod{
  42. TypeMeta: metav1.TypeMeta{
  43. APIVersion: "v1",
  44. Kind: "Pod",
  45. },
  46. ObjectMeta: metav1.ObjectMeta{
  47. Name: container.Name,
  48. Namespace: metav1.NamespaceSystem,
  49. // The component and tier labels are useful for quickly identifying the control plane Pods when doing a .List()
  50. // against Pods in the kube-system namespace. Can for example be used together with the WaitForPodsWithLabel function
  51. Labels: map[string]string{"component": container.Name, "tier": "control-plane"},
  52. },
  53. Spec: v1.PodSpec{
  54. Containers: []v1.Container{container},
  55. PriorityClassName: "system-cluster-critical",
  56. HostNetwork: true,
  57. Volumes: VolumeMapToSlice(volumes),
  58. },
  59. }
  60. }
  61. // ComponentResources returns the v1.ResourceRequirements object needed for allocating a specified amount of the CPU
  62. func ComponentResources(cpu string) v1.ResourceRequirements {
  63. return v1.ResourceRequirements{
  64. Requests: v1.ResourceList{
  65. v1.ResourceName(v1.ResourceCPU): resource.MustParse(cpu),
  66. },
  67. }
  68. }
  69. // EtcdProbe is a helper function for building a shell-based, etcdctl v1.Probe object to healthcheck etcd
  70. func EtcdProbe(cfg *kubeadmapi.Etcd, port int, certsDir string, CACertName string, CertName string, KeyName string) *v1.Probe {
  71. tlsFlags := fmt.Sprintf("--cacert=%[1]s/%[2]s --cert=%[1]s/%[3]s --key=%[1]s/%[4]s", certsDir, CACertName, CertName, KeyName)
  72. // etcd pod is alive if a linearizable get succeeds.
  73. cmd := fmt.Sprintf("ETCDCTL_API=3 etcdctl --endpoints=https://[%s]:%d %s get foo", GetEtcdProbeAddress(cfg), port, tlsFlags)
  74. return &v1.Probe{
  75. Handler: v1.Handler{
  76. Exec: &v1.ExecAction{
  77. Command: []string{"/bin/sh", "-ec", cmd},
  78. },
  79. },
  80. InitialDelaySeconds: 15,
  81. TimeoutSeconds: 15,
  82. FailureThreshold: 8,
  83. }
  84. }
  85. // NewVolume creates a v1.Volume with a hostPath mount to the specified location
  86. func NewVolume(name, path string, pathType *v1.HostPathType) v1.Volume {
  87. return v1.Volume{
  88. Name: name,
  89. VolumeSource: v1.VolumeSource{
  90. HostPath: &v1.HostPathVolumeSource{
  91. Path: path,
  92. Type: pathType,
  93. },
  94. },
  95. }
  96. }
  97. // NewVolumeMount creates a v1.VolumeMount to the specified location
  98. func NewVolumeMount(name, path string, readOnly bool) v1.VolumeMount {
  99. return v1.VolumeMount{
  100. Name: name,
  101. MountPath: path,
  102. ReadOnly: readOnly,
  103. }
  104. }
  105. // VolumeMapToSlice returns a slice of volumes from a map's values
  106. func VolumeMapToSlice(volumes map[string]v1.Volume) []v1.Volume {
  107. v := make([]v1.Volume, 0, len(volumes))
  108. for _, vol := range volumes {
  109. v = append(v, vol)
  110. }
  111. sort.Slice(v, func(i, j int) bool {
  112. return strings.Compare(v[i].Name, v[j].Name) == -1
  113. })
  114. return v
  115. }
  116. // VolumeMountMapToSlice returns a slice of volumes from a map's values
  117. func VolumeMountMapToSlice(volumeMounts map[string]v1.VolumeMount) []v1.VolumeMount {
  118. v := make([]v1.VolumeMount, 0, len(volumeMounts))
  119. for _, volMount := range volumeMounts {
  120. v = append(v, volMount)
  121. }
  122. sort.Slice(v, func(i, j int) bool {
  123. return strings.Compare(v[i].Name, v[j].Name) == -1
  124. })
  125. return v
  126. }
  127. // GetExtraParameters builds a list of flag arguments two string-string maps, one with default, base commands and one with overrides
  128. func GetExtraParameters(overrides map[string]string, defaults map[string]string) []string {
  129. var command []string
  130. for k, v := range overrides {
  131. if len(v) > 0 {
  132. command = append(command, fmt.Sprintf("--%s=%s", k, v))
  133. }
  134. }
  135. for k, v := range defaults {
  136. if _, overrideExists := overrides[k]; !overrideExists {
  137. command = append(command, fmt.Sprintf("--%s=%s", k, v))
  138. }
  139. }
  140. return command
  141. }
  142. // WriteStaticPodToDisk writes a static pod file to disk
  143. func WriteStaticPodToDisk(componentName, manifestDir string, pod v1.Pod) error {
  144. // creates target folder if not already exists
  145. if err := os.MkdirAll(manifestDir, 0700); err != nil {
  146. return errors.Wrapf(err, "failed to create directory %q", manifestDir)
  147. }
  148. // writes the pod to disk
  149. serialized, err := util.MarshalToYaml(&pod, v1.SchemeGroupVersion)
  150. if err != nil {
  151. return errors.Wrapf(err, "failed to marshal manifest for %q to YAML", componentName)
  152. }
  153. filename := kubeadmconstants.GetStaticPodFilepath(componentName, manifestDir)
  154. if err := ioutil.WriteFile(filename, serialized, 0600); err != nil {
  155. return errors.Wrapf(err, "failed to write static pod manifest file for %q (%q)", componentName, filename)
  156. }
  157. return nil
  158. }
  159. // ReadStaticPodFromDisk reads a static pod file from disk
  160. func ReadStaticPodFromDisk(manifestPath string) (*v1.Pod, error) {
  161. buf, err := ioutil.ReadFile(manifestPath)
  162. if err != nil {
  163. return &v1.Pod{}, errors.Wrapf(err, "failed to read manifest for %q", manifestPath)
  164. }
  165. obj, err := util.UnmarshalFromYaml(buf, v1.SchemeGroupVersion)
  166. if err != nil {
  167. return &v1.Pod{}, errors.Errorf("failed to unmarshal manifest for %q from YAML: %v", manifestPath, err)
  168. }
  169. pod := obj.(*v1.Pod)
  170. return pod, nil
  171. }
  172. // GetAPIServerProbeAddress returns the probe address for the API server
  173. func GetAPIServerProbeAddress(endpoint *kubeadmapi.APIEndpoint) string {
  174. // In the case of a self-hosted deployment, the initial host on which kubeadm --init is run,
  175. // will generate a DaemonSet with a nodeSelector such that all nodes with the label
  176. // node-role.kubernetes.io/master='' will have the API server deployed to it. Since the init
  177. // is run only once on an initial host, the API advertise address will be invalid for any
  178. // future hosts that do not have the same address. Furthermore, since liveness and readiness
  179. // probes do not support the Downward API we cannot dynamically set the advertise address to
  180. // the node's IP. The only option then is to use localhost.
  181. if endpoint != nil && endpoint.AdvertiseAddress != "" {
  182. return endpoint.AdvertiseAddress
  183. }
  184. return "127.0.0.1"
  185. }
  186. // GetControllerManagerProbeAddress returns the kubernetes controller manager probe address
  187. func GetControllerManagerProbeAddress(cfg *kubeadmapi.ClusterConfiguration) string {
  188. if addr, exists := cfg.ControllerManager.ExtraArgs[kubeControllerManagerAddressArg]; exists {
  189. return addr
  190. }
  191. return "127.0.0.1"
  192. }
  193. // GetSchedulerProbeAddress returns the kubernetes scheduler probe address
  194. func GetSchedulerProbeAddress(cfg *kubeadmapi.ClusterConfiguration) string {
  195. if addr, exists := cfg.Scheduler.ExtraArgs[kubeSchedulerAddressArg]; exists {
  196. return addr
  197. }
  198. return "127.0.0.1"
  199. }
  200. // GetEtcdProbeAddress returns the etcd probe address
  201. func GetEtcdProbeAddress(cfg *kubeadmapi.Etcd) string {
  202. if cfg.Local != nil && cfg.Local.ExtraArgs != nil {
  203. if arg, exists := cfg.Local.ExtraArgs[etcdListenClientURLsArg]; exists {
  204. // Use the first url in the listen-client-urls if multiple url's are specified.
  205. if strings.ContainsAny(arg, ",") {
  206. arg = strings.Split(arg, ",")[0]
  207. }
  208. parsedURL, err := url.Parse(arg)
  209. if err != nil || parsedURL.Hostname() == "" {
  210. return "127.0.0.1"
  211. }
  212. // Return the IP if the URL contains an address instead of a name.
  213. if ip := net.ParseIP(parsedURL.Hostname()); ip != nil {
  214. // etcdctl doesn't support auto-converting zero addresses into loopback addresses
  215. if ip.Equal(net.IPv4zero) {
  216. return "127.0.0.1"
  217. }
  218. if ip.Equal(net.IPv6zero) {
  219. return net.IPv6loopback.String()
  220. }
  221. return ip.String()
  222. }
  223. // Use the local resolver to try resolving the name within the URL.
  224. // If the name can not be resolved, return an IPv4 loopback address.
  225. // Otherwise, select the first valid IPv4 address.
  226. // If the name does not resolve to an IPv4 address, select the first valid IPv6 address.
  227. addrs, err := net.LookupIP(parsedURL.Hostname())
  228. if err != nil {
  229. return "127.0.0.1"
  230. }
  231. var ip net.IP
  232. for _, addr := range addrs {
  233. if addr.To4() != nil {
  234. ip = addr
  235. break
  236. }
  237. if addr.To16() != nil && ip == nil {
  238. ip = addr
  239. }
  240. }
  241. return ip.String()
  242. }
  243. }
  244. return "127.0.0.1"
  245. }
  246. // ManifestFilesAreEqual compares 2 files. It returns true if their contents are equal, false otherwise
  247. func ManifestFilesAreEqual(path1, path2 string) (bool, error) {
  248. content1, err := ioutil.ReadFile(path1)
  249. if err != nil {
  250. return false, err
  251. }
  252. content2, err := ioutil.ReadFile(path2)
  253. if err != nil {
  254. return false, err
  255. }
  256. return bytes.Equal(content1, content2), nil
  257. }