utils.go 11 KB

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