utils.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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/url"
  19. "os"
  20. "sort"
  21. "strings"
  22. "github.com/pkg/errors"
  23. v1 "k8s.io/api/core/v1"
  24. "k8s.io/apimachinery/pkg/api/resource"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/util/intstr"
  27. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  28. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  29. kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
  30. "k8s.io/kubernetes/cmd/kubeadm/app/util/kustomize"
  31. )
  32. const (
  33. // kubeControllerManagerBindAddressArg represents the bind-address argument of the kube-controller-manager configuration.
  34. kubeControllerManagerBindAddressArg = "bind-address"
  35. // kubeSchedulerBindAddressArg represents the bind-address argument of the kube-scheduler configuration.
  36. kubeSchedulerBindAddressArg = "bind-address"
  37. )
  38. // ComponentPod returns a Pod object from the container, volume and annotations specifications
  39. func ComponentPod(container v1.Container, volumes map[string]v1.Volume, annotations map[string]string) v1.Pod {
  40. return v1.Pod{
  41. TypeMeta: metav1.TypeMeta{
  42. APIVersion: "v1",
  43. Kind: "Pod",
  44. },
  45. ObjectMeta: metav1.ObjectMeta{
  46. Name: container.Name,
  47. Namespace: metav1.NamespaceSystem,
  48. // The component and tier labels are useful for quickly identifying the control plane Pods when doing a .List()
  49. // against Pods in the kube-system namespace. Can for example be used together with the WaitForPodsWithLabel function
  50. Labels: map[string]string{"component": container.Name, "tier": kubeadmconstants.ControlPlaneTier},
  51. Annotations: annotations,
  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. // NewVolume creates a v1.Volume with a hostPath mount to the specified location
  70. func NewVolume(name, path string, pathType *v1.HostPathType) v1.Volume {
  71. return v1.Volume{
  72. Name: name,
  73. VolumeSource: v1.VolumeSource{
  74. HostPath: &v1.HostPathVolumeSource{
  75. Path: path,
  76. Type: pathType,
  77. },
  78. },
  79. }
  80. }
  81. // NewVolumeMount creates a v1.VolumeMount to the specified location
  82. func NewVolumeMount(name, path string, readOnly bool) v1.VolumeMount {
  83. return v1.VolumeMount{
  84. Name: name,
  85. MountPath: path,
  86. ReadOnly: readOnly,
  87. }
  88. }
  89. // VolumeMapToSlice returns a slice of volumes from a map's values
  90. func VolumeMapToSlice(volumes map[string]v1.Volume) []v1.Volume {
  91. v := make([]v1.Volume, 0, len(volumes))
  92. for _, vol := range volumes {
  93. v = append(v, vol)
  94. }
  95. sort.Slice(v, func(i, j int) bool {
  96. return strings.Compare(v[i].Name, v[j].Name) == -1
  97. })
  98. return v
  99. }
  100. // VolumeMountMapToSlice returns a slice of volumes from a map's values
  101. func VolumeMountMapToSlice(volumeMounts map[string]v1.VolumeMount) []v1.VolumeMount {
  102. v := make([]v1.VolumeMount, 0, len(volumeMounts))
  103. for _, volMount := range volumeMounts {
  104. v = append(v, volMount)
  105. }
  106. sort.Slice(v, func(i, j int) bool {
  107. return strings.Compare(v[i].Name, v[j].Name) == -1
  108. })
  109. return v
  110. }
  111. // GetExtraParameters builds a list of flag arguments two string-string maps, one with default, base commands and one with overrides
  112. func GetExtraParameters(overrides map[string]string, defaults map[string]string) []string {
  113. var command []string
  114. for k, v := range overrides {
  115. if len(v) > 0 {
  116. command = append(command, fmt.Sprintf("--%s=%s", k, v))
  117. }
  118. }
  119. for k, v := range defaults {
  120. if _, overrideExists := overrides[k]; !overrideExists {
  121. command = append(command, fmt.Sprintf("--%s=%s", k, v))
  122. }
  123. }
  124. return command
  125. }
  126. // KustomizeStaticPod applies patches defined in kustomizeDir to a static Pod manifest
  127. func KustomizeStaticPod(pod *v1.Pod, kustomizeDir string) (*v1.Pod, error) {
  128. // marshal the pod manifest into yaml
  129. serialized, err := kubeadmutil.MarshalToYaml(pod, v1.SchemeGroupVersion)
  130. if err != nil {
  131. return pod, errors.Wrapf(err, "failed to marshal manifest to YAML")
  132. }
  133. km, err := kustomize.GetManager(kustomizeDir)
  134. if err != nil {
  135. return pod, errors.Wrapf(err, "failed to GetPatches from %q", kustomizeDir)
  136. }
  137. kustomized, err := km.Kustomize(serialized)
  138. if err != nil {
  139. return pod, errors.Wrap(err, "failed to kustomize static Pod manifest")
  140. }
  141. // unmarshal kustomized yaml back into a pod manifest
  142. obj, err := kubeadmutil.UnmarshalFromYaml(kustomized, v1.SchemeGroupVersion)
  143. if err != nil {
  144. return pod, errors.Wrap(err, "failed to unmarshal kustomize manifest from YAML")
  145. }
  146. pod2, ok := obj.(*v1.Pod)
  147. if !ok {
  148. return pod, errors.Wrap(err, "kustomized manifest is not a valid Pod object")
  149. }
  150. return pod2, nil
  151. }
  152. // WriteStaticPodToDisk writes a static pod file to disk
  153. func WriteStaticPodToDisk(componentName, manifestDir string, pod v1.Pod) error {
  154. // creates target folder if not already exists
  155. if err := os.MkdirAll(manifestDir, 0700); err != nil {
  156. return errors.Wrapf(err, "failed to create directory %q", manifestDir)
  157. }
  158. // writes the pod to disk
  159. serialized, err := kubeadmutil.MarshalToYaml(&pod, v1.SchemeGroupVersion)
  160. if err != nil {
  161. return errors.Wrapf(err, "failed to marshal manifest for %q to YAML", componentName)
  162. }
  163. filename := kubeadmconstants.GetStaticPodFilepath(componentName, manifestDir)
  164. if err := ioutil.WriteFile(filename, serialized, 0600); err != nil {
  165. return errors.Wrapf(err, "failed to write static pod manifest file for %q (%q)", componentName, filename)
  166. }
  167. return nil
  168. }
  169. // ReadStaticPodFromDisk reads a static pod file from disk
  170. func ReadStaticPodFromDisk(manifestPath string) (*v1.Pod, error) {
  171. buf, err := ioutil.ReadFile(manifestPath)
  172. if err != nil {
  173. return &v1.Pod{}, errors.Wrapf(err, "failed to read manifest for %q", manifestPath)
  174. }
  175. obj, err := kubeadmutil.UnmarshalFromYaml(buf, v1.SchemeGroupVersion)
  176. if err != nil {
  177. return &v1.Pod{}, errors.Errorf("failed to unmarshal manifest for %q from YAML: %v", manifestPath, err)
  178. }
  179. pod := obj.(*v1.Pod)
  180. return pod, nil
  181. }
  182. // LivenessProbe creates a Probe object with a HTTPGet handler
  183. func LivenessProbe(host, path string, port int, scheme v1.URIScheme) *v1.Probe {
  184. return &v1.Probe{
  185. Handler: v1.Handler{
  186. HTTPGet: &v1.HTTPGetAction{
  187. Host: host,
  188. Path: path,
  189. Port: intstr.FromInt(port),
  190. Scheme: scheme,
  191. },
  192. },
  193. InitialDelaySeconds: 15,
  194. TimeoutSeconds: 15,
  195. FailureThreshold: 8,
  196. }
  197. }
  198. // GetAPIServerProbeAddress returns the probe address for the API server
  199. func GetAPIServerProbeAddress(endpoint *kubeadmapi.APIEndpoint) string {
  200. // In the case of a self-hosted deployment, the initial host on which kubeadm --init is run,
  201. // will generate a DaemonSet with a nodeSelector such that all nodes with the label
  202. // node-role.kubernetes.io/master='' will have the API server deployed to it. Since the init
  203. // is run only once on an initial host, the API advertise address will be invalid for any
  204. // future hosts that do not have the same address. Furthermore, since liveness and readiness
  205. // probes do not support the Downward API we cannot dynamically set the advertise address to
  206. // the node's IP. The only option then is to use localhost.
  207. if endpoint != nil && endpoint.AdvertiseAddress != "" {
  208. return getProbeAddress(endpoint.AdvertiseAddress)
  209. }
  210. return "127.0.0.1"
  211. }
  212. // GetControllerManagerProbeAddress returns the kubernetes controller manager probe address
  213. func GetControllerManagerProbeAddress(cfg *kubeadmapi.ClusterConfiguration) string {
  214. if addr, exists := cfg.ControllerManager.ExtraArgs[kubeControllerManagerBindAddressArg]; exists {
  215. return getProbeAddress(addr)
  216. }
  217. return "127.0.0.1"
  218. }
  219. // GetSchedulerProbeAddress returns the kubernetes scheduler probe address
  220. func GetSchedulerProbeAddress(cfg *kubeadmapi.ClusterConfiguration) string {
  221. if addr, exists := cfg.Scheduler.ExtraArgs[kubeSchedulerBindAddressArg]; exists {
  222. return getProbeAddress(addr)
  223. }
  224. return "127.0.0.1"
  225. }
  226. // GetEtcdProbeEndpoint takes a kubeadm Etcd configuration object and attempts to parse
  227. // the first URL in the listen-metrics-urls argument, returning an etcd probe hostname,
  228. // port and scheme
  229. func GetEtcdProbeEndpoint(cfg *kubeadmapi.Etcd, isIPv6 bool) (string, int, v1.URIScheme) {
  230. localhost := "127.0.0.1"
  231. if isIPv6 {
  232. localhost = "::1"
  233. }
  234. if cfg.Local == nil || cfg.Local.ExtraArgs == nil {
  235. return localhost, kubeadmconstants.EtcdMetricsPort, v1.URISchemeHTTP
  236. }
  237. if arg, exists := cfg.Local.ExtraArgs["listen-metrics-urls"]; exists {
  238. // Use the first url in the listen-metrics-urls if multiple URL's are specified.
  239. arg = strings.Split(arg, ",")[0]
  240. parsedURL, err := url.Parse(arg)
  241. if err != nil {
  242. return localhost, kubeadmconstants.EtcdMetricsPort, v1.URISchemeHTTP
  243. }
  244. // Parse scheme
  245. scheme := v1.URISchemeHTTP
  246. if parsedURL.Scheme == "https" {
  247. scheme = v1.URISchemeHTTPS
  248. }
  249. // Parse hostname
  250. hostname := parsedURL.Hostname()
  251. if len(hostname) == 0 {
  252. hostname = localhost
  253. }
  254. // Parse port
  255. port := kubeadmconstants.EtcdMetricsPort
  256. portStr := parsedURL.Port()
  257. if len(portStr) != 0 {
  258. p, err := kubeadmutil.ParsePort(portStr)
  259. if err == nil {
  260. port = p
  261. }
  262. }
  263. return hostname, port, scheme
  264. }
  265. return localhost, kubeadmconstants.EtcdMetricsPort, v1.URISchemeHTTP
  266. }
  267. // ManifestFilesAreEqual compares 2 files. It returns true if their contents are equal, false otherwise
  268. func ManifestFilesAreEqual(path1, path2 string) (bool, error) {
  269. content1, err := ioutil.ReadFile(path1)
  270. if err != nil {
  271. return false, err
  272. }
  273. content2, err := ioutil.ReadFile(path2)
  274. if err != nil {
  275. return false, err
  276. }
  277. return bytes.Equal(content1, content2), nil
  278. }
  279. // getProbeAddress returns a valid probe address.
  280. // Kubeadm uses the bind-address to configure the probe address. It's common to use the
  281. // unspecified address "0.0.0.0" or "::" as bind-address when we want to listen in all interfaces,
  282. // however this address can't be used as probe #86504.
  283. // If the address is an unspecified address getProbeAddress returns empty,
  284. // that means that kubelet will use the PodIP as probe address.
  285. func getProbeAddress(addr string) string {
  286. if addr == "0.0.0.0" || addr == "::" {
  287. return ""
  288. }
  289. return addr
  290. }