checks.go 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  1. /*
  2. Copyright 2016 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 preflight
  14. import (
  15. "bufio"
  16. "bytes"
  17. "crypto/tls"
  18. "crypto/x509"
  19. "encoding/json"
  20. "fmt"
  21. "io"
  22. "io/ioutil"
  23. "net"
  24. "net/http"
  25. "net/url"
  26. "os"
  27. "path/filepath"
  28. "runtime"
  29. "strings"
  30. "time"
  31. "github.com/PuerkitoBio/purell"
  32. "github.com/pkg/errors"
  33. netutil "k8s.io/apimachinery/pkg/util/net"
  34. "k8s.io/apimachinery/pkg/util/sets"
  35. versionutil "k8s.io/apimachinery/pkg/util/version"
  36. kubeadmversion "k8s.io/component-base/version"
  37. "k8s.io/klog"
  38. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  39. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  40. "k8s.io/kubernetes/cmd/kubeadm/app/images"
  41. "k8s.io/kubernetes/cmd/kubeadm/app/util/initsystem"
  42. utilruntime "k8s.io/kubernetes/cmd/kubeadm/app/util/runtime"
  43. system "k8s.io/system-validators/validators"
  44. utilsexec "k8s.io/utils/exec"
  45. utilsnet "k8s.io/utils/net"
  46. )
  47. const (
  48. bridgenf = "/proc/sys/net/bridge/bridge-nf-call-iptables"
  49. bridgenf6 = "/proc/sys/net/bridge/bridge-nf-call-ip6tables"
  50. ipv4Forward = "/proc/sys/net/ipv4/ip_forward"
  51. ipv6DefaultForwarding = "/proc/sys/net/ipv6/conf/default/forwarding"
  52. externalEtcdRequestTimeout = time.Duration(10 * time.Second)
  53. externalEtcdRequestRetries = 3
  54. externalEtcdRequestInterval = time.Duration(5 * time.Second)
  55. )
  56. var (
  57. minExternalEtcdVersion = versionutil.MustParseSemantic(kubeadmconstants.MinExternalEtcdVersion)
  58. )
  59. // Error defines struct for communicating error messages generated by preflight checks
  60. type Error struct {
  61. Msg string
  62. }
  63. // Error implements the standard error interface
  64. func (e *Error) Error() string {
  65. return fmt.Sprintf("[preflight] Some fatal errors occurred:\n%s%s", e.Msg, "[preflight] If you know what you are doing, you can make a check non-fatal with `--ignore-preflight-errors=...`")
  66. }
  67. // Preflight identifies this error as a preflight error
  68. func (e *Error) Preflight() bool {
  69. return true
  70. }
  71. // Checker validates the state of the system to ensure kubeadm will be
  72. // successful as often as possible.
  73. type Checker interface {
  74. Check() (warnings, errorList []error)
  75. Name() string
  76. }
  77. // ContainerRuntimeCheck verifies the container runtime.
  78. type ContainerRuntimeCheck struct {
  79. runtime utilruntime.ContainerRuntime
  80. }
  81. // Name returns label for RuntimeCheck.
  82. func (ContainerRuntimeCheck) Name() string {
  83. return "CRI"
  84. }
  85. // Check validates the container runtime
  86. func (crc ContainerRuntimeCheck) Check() (warnings, errorList []error) {
  87. klog.V(1).Infoln("validating the container runtime")
  88. if err := crc.runtime.IsRunning(); err != nil {
  89. errorList = append(errorList, err)
  90. }
  91. return warnings, errorList
  92. }
  93. // ServiceCheck verifies that the given service is enabled and active. If we do not
  94. // detect a supported init system however, all checks are skipped and a warning is
  95. // returned.
  96. type ServiceCheck struct {
  97. Service string
  98. CheckIfActive bool
  99. Label string
  100. }
  101. // Name returns label for ServiceCheck. If not provided, will return based on the service parameter
  102. func (sc ServiceCheck) Name() string {
  103. if sc.Label != "" {
  104. return sc.Label
  105. }
  106. return fmt.Sprintf("Service-%s", strings.Title(sc.Service))
  107. }
  108. // Check validates if the service is enabled and active.
  109. func (sc ServiceCheck) Check() (warnings, errorList []error) {
  110. klog.V(1).Infoln("validating if the service is enabled and active")
  111. initSystem, err := initsystem.GetInitSystem()
  112. if err != nil {
  113. return []error{err}, nil
  114. }
  115. if !initSystem.ServiceExists(sc.Service) {
  116. return []error{errors.Errorf("%s service does not exist", sc.Service)}, nil
  117. }
  118. if !initSystem.ServiceIsEnabled(sc.Service) {
  119. warnings = append(warnings,
  120. errors.Errorf("%s service is not enabled, please run '%s'",
  121. sc.Service, initSystem.EnableCommand(sc.Service)))
  122. }
  123. if sc.CheckIfActive && !initSystem.ServiceIsActive(sc.Service) {
  124. errorList = append(errorList,
  125. errors.Errorf("%s service is not active, please run 'systemctl start %s.service'",
  126. sc.Service, sc.Service))
  127. }
  128. return warnings, errorList
  129. }
  130. // FirewalldCheck checks if firewalld is enabled or active. If it is, warn the user that there may be problems
  131. // if no actions are taken.
  132. type FirewalldCheck struct {
  133. ports []int
  134. }
  135. // Name returns label for FirewalldCheck.
  136. func (FirewalldCheck) Name() string {
  137. return "Firewalld"
  138. }
  139. // Check validates if the firewall is enabled and active.
  140. func (fc FirewalldCheck) Check() (warnings, errorList []error) {
  141. klog.V(1).Infoln("validating if the firewall is enabled and active")
  142. initSystem, err := initsystem.GetInitSystem()
  143. if err != nil {
  144. return []error{err}, nil
  145. }
  146. if !initSystem.ServiceExists("firewalld") {
  147. return nil, nil
  148. }
  149. if initSystem.ServiceIsActive("firewalld") {
  150. err := errors.Errorf("firewalld is active, please ensure ports %v are open or your cluster may not function correctly",
  151. fc.ports)
  152. return []error{err}, nil
  153. }
  154. return nil, nil
  155. }
  156. // PortOpenCheck ensures the given port is available for use.
  157. type PortOpenCheck struct {
  158. port int
  159. label string
  160. }
  161. // Name returns name for PortOpenCheck. If not known, will return "PortXXXX" based on port number
  162. func (poc PortOpenCheck) Name() string {
  163. if poc.label != "" {
  164. return poc.label
  165. }
  166. return fmt.Sprintf("Port-%d", poc.port)
  167. }
  168. // Check validates if the particular port is available.
  169. func (poc PortOpenCheck) Check() (warnings, errorList []error) {
  170. klog.V(1).Infof("validating availability of port %d", poc.port)
  171. ln, err := net.Listen("tcp", fmt.Sprintf(":%d", poc.port))
  172. if err != nil {
  173. errorList = []error{errors.Errorf("Port %d is in use", poc.port)}
  174. }
  175. if ln != nil {
  176. if err = ln.Close(); err != nil {
  177. warnings = append(warnings,
  178. errors.Errorf("when closing port %d, encountered %v", poc.port, err))
  179. }
  180. }
  181. return warnings, errorList
  182. }
  183. // IsPrivilegedUserCheck verifies user is privileged (linux - root, windows - Administrator)
  184. type IsPrivilegedUserCheck struct{}
  185. // Name returns name for IsPrivilegedUserCheck
  186. func (IsPrivilegedUserCheck) Name() string {
  187. return "IsPrivilegedUser"
  188. }
  189. // IsDockerSystemdCheck verifies if Docker is setup to use systemd as the cgroup driver.
  190. type IsDockerSystemdCheck struct{}
  191. // Name returns name for IsDockerSystemdCheck
  192. func (IsDockerSystemdCheck) Name() string {
  193. return "IsDockerSystemdCheck"
  194. }
  195. // DirAvailableCheck checks if the given directory either does not exist, or is empty.
  196. type DirAvailableCheck struct {
  197. Path string
  198. Label string
  199. }
  200. // Name returns label for individual DirAvailableChecks. If not known, will return based on path.
  201. func (dac DirAvailableCheck) Name() string {
  202. if dac.Label != "" {
  203. return dac.Label
  204. }
  205. return fmt.Sprintf("DirAvailable-%s", strings.Replace(dac.Path, "/", "-", -1))
  206. }
  207. // Check validates if a directory does not exist or empty.
  208. func (dac DirAvailableCheck) Check() (warnings, errorList []error) {
  209. klog.V(1).Infof("validating the existence and emptiness of directory %s", dac.Path)
  210. // If it doesn't exist we are good:
  211. if _, err := os.Stat(dac.Path); os.IsNotExist(err) {
  212. return nil, nil
  213. }
  214. f, err := os.Open(dac.Path)
  215. if err != nil {
  216. return nil, []error{errors.Wrapf(err, "unable to check if %s is empty", dac.Path)}
  217. }
  218. defer f.Close()
  219. _, err = f.Readdirnames(1)
  220. if err != io.EOF {
  221. return nil, []error{errors.Errorf("%s is not empty", dac.Path)}
  222. }
  223. return nil, nil
  224. }
  225. // FileAvailableCheck checks that the given file does not already exist.
  226. type FileAvailableCheck struct {
  227. Path string
  228. Label string
  229. }
  230. // Name returns label for individual FileAvailableChecks. If not known, will return based on path.
  231. func (fac FileAvailableCheck) Name() string {
  232. if fac.Label != "" {
  233. return fac.Label
  234. }
  235. return fmt.Sprintf("FileAvailable-%s", strings.Replace(fac.Path, "/", "-", -1))
  236. }
  237. // Check validates if the given file does not already exist.
  238. func (fac FileAvailableCheck) Check() (warnings, errorList []error) {
  239. klog.V(1).Infof("validating the existence of file %s", fac.Path)
  240. if _, err := os.Stat(fac.Path); err == nil {
  241. return nil, []error{errors.Errorf("%s already exists", fac.Path)}
  242. }
  243. return nil, nil
  244. }
  245. // FileExistingCheck checks that the given file does not already exist.
  246. type FileExistingCheck struct {
  247. Path string
  248. Label string
  249. }
  250. // Name returns label for individual FileExistingChecks. If not known, will return based on path.
  251. func (fac FileExistingCheck) Name() string {
  252. if fac.Label != "" {
  253. return fac.Label
  254. }
  255. return fmt.Sprintf("FileExisting-%s", strings.Replace(fac.Path, "/", "-", -1))
  256. }
  257. // Check validates if the given file already exists.
  258. func (fac FileExistingCheck) Check() (warnings, errorList []error) {
  259. klog.V(1).Infof("validating the existence of file %s", fac.Path)
  260. if _, err := os.Stat(fac.Path); err != nil {
  261. return nil, []error{errors.Errorf("%s doesn't exist", fac.Path)}
  262. }
  263. return nil, nil
  264. }
  265. // FileContentCheck checks that the given file contains the string Content.
  266. type FileContentCheck struct {
  267. Path string
  268. Content []byte
  269. Label string
  270. }
  271. // Name returns label for individual FileContentChecks. If not known, will return based on path.
  272. func (fcc FileContentCheck) Name() string {
  273. if fcc.Label != "" {
  274. return fcc.Label
  275. }
  276. return fmt.Sprintf("FileContent-%s", strings.Replace(fcc.Path, "/", "-", -1))
  277. }
  278. // Check validates if the given file contains the given content.
  279. func (fcc FileContentCheck) Check() (warnings, errorList []error) {
  280. klog.V(1).Infof("validating the contents of file %s", fcc.Path)
  281. f, err := os.Open(fcc.Path)
  282. if err != nil {
  283. return nil, []error{errors.Errorf("%s does not exist", fcc.Path)}
  284. }
  285. lr := io.LimitReader(f, int64(len(fcc.Content)))
  286. defer f.Close()
  287. buf := &bytes.Buffer{}
  288. _, err = io.Copy(buf, lr)
  289. if err != nil {
  290. return nil, []error{errors.Errorf("%s could not be read", fcc.Path)}
  291. }
  292. if !bytes.Equal(buf.Bytes(), fcc.Content) {
  293. return nil, []error{errors.Errorf("%s contents are not set to %s", fcc.Path, fcc.Content)}
  294. }
  295. return nil, []error{}
  296. }
  297. // InPathCheck checks if the given executable is present in $PATH
  298. type InPathCheck struct {
  299. executable string
  300. mandatory bool
  301. exec utilsexec.Interface
  302. label string
  303. suggestion string
  304. }
  305. // Name returns label for individual InPathCheck. If not known, will return based on path.
  306. func (ipc InPathCheck) Name() string {
  307. if ipc.label != "" {
  308. return ipc.label
  309. }
  310. return fmt.Sprintf("FileExisting-%s", strings.Replace(ipc.executable, "/", "-", -1))
  311. }
  312. // Check validates if the given executable is present in the path.
  313. func (ipc InPathCheck) Check() (warnings, errs []error) {
  314. klog.V(1).Infof("validating the presence of executable %s", ipc.executable)
  315. _, err := ipc.exec.LookPath(ipc.executable)
  316. if err != nil {
  317. if ipc.mandatory {
  318. // Return as an error:
  319. return nil, []error{errors.Errorf("%s not found in system path", ipc.executable)}
  320. }
  321. // Return as a warning:
  322. warningMessage := fmt.Sprintf("%s not found in system path", ipc.executable)
  323. if ipc.suggestion != "" {
  324. warningMessage += fmt.Sprintf("\nSuggestion: %s", ipc.suggestion)
  325. }
  326. return []error{errors.New(warningMessage)}, nil
  327. }
  328. return nil, nil
  329. }
  330. // HostnameCheck checks if hostname match dns sub domain regex.
  331. // If hostname doesn't match this regex, kubelet will not launch static pods like kube-apiserver/kube-controller-manager and so on.
  332. type HostnameCheck struct {
  333. nodeName string
  334. }
  335. // Name will return Hostname as name for HostnameCheck
  336. func (HostnameCheck) Name() string {
  337. return "Hostname"
  338. }
  339. // Check validates if hostname match dns sub domain regex.
  340. func (hc HostnameCheck) Check() (warnings, errorList []error) {
  341. klog.V(1).Infoln("checking whether the given node name is reachable using net.LookupHost")
  342. addr, err := net.LookupHost(hc.nodeName)
  343. if addr == nil {
  344. warnings = append(warnings, errors.Errorf("hostname \"%s\" could not be reached", hc.nodeName))
  345. }
  346. if err != nil {
  347. warnings = append(warnings, errors.Wrapf(err, "hostname \"%s\"", hc.nodeName))
  348. }
  349. return warnings, errorList
  350. }
  351. // HTTPProxyCheck checks if https connection to specific host is going
  352. // to be done directly or over proxy. If proxy detected, it will return warning.
  353. type HTTPProxyCheck struct {
  354. Proto string
  355. Host string
  356. }
  357. // Name returns HTTPProxy as name for HTTPProxyCheck
  358. func (hst HTTPProxyCheck) Name() string {
  359. return "HTTPProxy"
  360. }
  361. // Check validates http connectivity type, direct or via proxy.
  362. func (hst HTTPProxyCheck) Check() (warnings, errorList []error) {
  363. klog.V(1).Infoln("validating if the connectivity type is via proxy or direct")
  364. u := &url.URL{Scheme: hst.Proto, Host: hst.Host}
  365. if utilsnet.IsIPv6String(hst.Host) {
  366. u.Host = net.JoinHostPort(hst.Host, "1234")
  367. }
  368. req, err := http.NewRequest("GET", u.String(), nil)
  369. if err != nil {
  370. return nil, []error{err}
  371. }
  372. proxy, err := netutil.SetOldTransportDefaults(&http.Transport{}).Proxy(req)
  373. if err != nil {
  374. return nil, []error{err}
  375. }
  376. if proxy != nil {
  377. return []error{errors.Errorf("Connection to %q uses proxy %q. If that is not intended, adjust your proxy settings", u, proxy)}, nil
  378. }
  379. return nil, nil
  380. }
  381. // HTTPProxyCIDRCheck checks if https connection to specific subnet is going
  382. // to be done directly or over proxy. If proxy detected, it will return warning.
  383. // Similar to HTTPProxyCheck above, but operates with subnets and uses API
  384. // machinery transport defaults to simulate kube-apiserver accessing cluster
  385. // services and pods.
  386. type HTTPProxyCIDRCheck struct {
  387. Proto string
  388. CIDR string
  389. }
  390. // Name will return HTTPProxyCIDR as name for HTTPProxyCIDRCheck
  391. func (HTTPProxyCIDRCheck) Name() string {
  392. return "HTTPProxyCIDR"
  393. }
  394. // Check validates http connectivity to first IP address in the CIDR.
  395. // If it is not directly connected and goes via proxy it will produce warning.
  396. func (subnet HTTPProxyCIDRCheck) Check() (warnings, errorList []error) {
  397. klog.V(1).Infoln("validating http connectivity to first IP address in the CIDR")
  398. if len(subnet.CIDR) == 0 {
  399. return nil, nil
  400. }
  401. _, cidr, err := net.ParseCIDR(subnet.CIDR)
  402. if err != nil {
  403. return nil, []error{errors.Wrapf(err, "error parsing CIDR %q", subnet.CIDR)}
  404. }
  405. testIP, err := utilsnet.GetIndexedIP(cidr, 1)
  406. if err != nil {
  407. return nil, []error{errors.Wrapf(err, "unable to get first IP address from the given CIDR (%s)", cidr.String())}
  408. }
  409. testIPstring := testIP.String()
  410. if len(testIP) == net.IPv6len {
  411. testIPstring = fmt.Sprintf("[%s]:1234", testIP)
  412. }
  413. url := fmt.Sprintf("%s://%s/", subnet.Proto, testIPstring)
  414. req, err := http.NewRequest("GET", url, nil)
  415. if err != nil {
  416. return nil, []error{err}
  417. }
  418. // Utilize same transport defaults as it will be used by API server
  419. proxy, err := netutil.SetOldTransportDefaults(&http.Transport{}).Proxy(req)
  420. if err != nil {
  421. return nil, []error{err}
  422. }
  423. if proxy != nil {
  424. return []error{errors.Errorf("connection to %q uses proxy %q. This may lead to malfunctional cluster setup. Make sure that Pod and Services IP ranges specified correctly as exceptions in proxy configuration", subnet.CIDR, proxy)}, nil
  425. }
  426. return nil, nil
  427. }
  428. // SystemVerificationCheck defines struct used for running the system verification node check in test/e2e_node/system
  429. type SystemVerificationCheck struct {
  430. IsDocker bool
  431. }
  432. // Name will return SystemVerification as name for SystemVerificationCheck
  433. func (SystemVerificationCheck) Name() string {
  434. return "SystemVerification"
  435. }
  436. // Check runs all individual checks
  437. func (sysver SystemVerificationCheck) Check() (warnings, errorList []error) {
  438. klog.V(1).Infoln("running all checks")
  439. // Create a buffered writer and choose a quite large value (1M) and suppose the output from the system verification test won't exceed the limit
  440. // Run the system verification check, but write to out buffered writer instead of stdout
  441. bufw := bufio.NewWriterSize(os.Stdout, 1*1024*1024)
  442. reporter := &system.StreamReporter{WriteStream: bufw}
  443. var errs []error
  444. var warns []error
  445. // All the common validators we'd like to run:
  446. var validators = []system.Validator{
  447. &system.KernelValidator{Reporter: reporter}}
  448. // run the docker validator only with docker runtime
  449. if sysver.IsDocker {
  450. validators = append(validators, &system.DockerValidator{Reporter: reporter})
  451. }
  452. if runtime.GOOS == "linux" {
  453. //add linux validators
  454. validators = append(validators,
  455. &system.OSValidator{Reporter: reporter},
  456. &system.CgroupsValidator{Reporter: reporter})
  457. }
  458. // Run all validators
  459. for _, v := range validators {
  460. warn, err := v.Validate(system.DefaultSysSpec)
  461. if err != nil {
  462. errs = append(errs, err...)
  463. }
  464. if warn != nil {
  465. warns = append(warns, warn...)
  466. }
  467. }
  468. if len(errs) != 0 {
  469. // Only print the output from the system verification check if the check failed
  470. fmt.Println("[preflight] The system verification failed. Printing the output from the verification:")
  471. bufw.Flush()
  472. return warns, errs
  473. }
  474. return warns, nil
  475. }
  476. // KubernetesVersionCheck validates Kubernetes and kubeadm versions
  477. type KubernetesVersionCheck struct {
  478. KubeadmVersion string
  479. KubernetesVersion string
  480. }
  481. // Name will return KubernetesVersion as name for KubernetesVersionCheck
  482. func (KubernetesVersionCheck) Name() string {
  483. return "KubernetesVersion"
  484. }
  485. // Check validates Kubernetes and kubeadm versions
  486. func (kubever KubernetesVersionCheck) Check() (warnings, errorList []error) {
  487. klog.V(1).Infoln("validating Kubernetes and kubeadm version")
  488. // Skip this check for "super-custom builds", where apimachinery/the overall codebase version is not set.
  489. if strings.HasPrefix(kubever.KubeadmVersion, "v0.0.0") {
  490. return nil, nil
  491. }
  492. kadmVersion, err := versionutil.ParseSemantic(kubever.KubeadmVersion)
  493. if err != nil {
  494. return nil, []error{errors.Wrapf(err, "couldn't parse kubeadm version %q", kubever.KubeadmVersion)}
  495. }
  496. k8sVersion, err := versionutil.ParseSemantic(kubever.KubernetesVersion)
  497. if err != nil {
  498. return nil, []error{errors.Wrapf(err, "couldn't parse Kubernetes version %q", kubever.KubernetesVersion)}
  499. }
  500. // Checks if k8sVersion greater or equal than the first unsupported versions by current version of kubeadm,
  501. // that is major.minor+1 (all patch and pre-releases versions included)
  502. // NB. in semver patches number is a numeric, while prerelease is a string where numeric identifiers always have lower precedence than non-numeric identifiers.
  503. // thus setting the value to x.y.0-0 we are defining the very first patch - prereleases within x.y minor release.
  504. firstUnsupportedVersion := versionutil.MustParseSemantic(fmt.Sprintf("%d.%d.%s", kadmVersion.Major(), kadmVersion.Minor()+1, "0-0"))
  505. if k8sVersion.AtLeast(firstUnsupportedVersion) {
  506. return []error{errors.Errorf("Kubernetes version is greater than kubeadm version. Please consider to upgrade kubeadm. Kubernetes version: %s. Kubeadm version: %d.%d.x", k8sVersion, kadmVersion.Components()[0], kadmVersion.Components()[1])}, nil
  507. }
  508. return nil, nil
  509. }
  510. // KubeletVersionCheck validates installed kubelet version
  511. type KubeletVersionCheck struct {
  512. KubernetesVersion string
  513. exec utilsexec.Interface
  514. }
  515. // Name will return KubeletVersion as name for KubeletVersionCheck
  516. func (KubeletVersionCheck) Name() string {
  517. return "KubeletVersion"
  518. }
  519. // Check validates kubelet version. It should be not less than minimal supported version
  520. func (kubever KubeletVersionCheck) Check() (warnings, errorList []error) {
  521. klog.V(1).Infoln("validating kubelet version")
  522. kubeletVersion, err := GetKubeletVersion(kubever.exec)
  523. if err != nil {
  524. return nil, []error{errors.Wrap(err, "couldn't get kubelet version")}
  525. }
  526. if kubeletVersion.LessThan(kubeadmconstants.MinimumKubeletVersion) {
  527. return nil, []error{errors.Errorf("Kubelet version %q is lower than kubeadm can support. Please upgrade kubelet", kubeletVersion)}
  528. }
  529. if kubever.KubernetesVersion != "" {
  530. k8sVersion, err := versionutil.ParseSemantic(kubever.KubernetesVersion)
  531. if err != nil {
  532. return nil, []error{errors.Wrapf(err, "couldn't parse Kubernetes version %q", kubever.KubernetesVersion)}
  533. }
  534. if kubeletVersion.Major() > k8sVersion.Major() || kubeletVersion.Minor() > k8sVersion.Minor() {
  535. return nil, []error{errors.Errorf("the kubelet version is higher than the control plane version. This is not a supported version skew and may lead to a malfunctional cluster. Kubelet version: %q Control plane version: %q", kubeletVersion, k8sVersion)}
  536. }
  537. }
  538. return nil, nil
  539. }
  540. // SwapCheck warns if swap is enabled
  541. type SwapCheck struct{}
  542. // Name will return Swap as name for SwapCheck
  543. func (SwapCheck) Name() string {
  544. return "Swap"
  545. }
  546. // Check validates whether swap is enabled or not
  547. func (swc SwapCheck) Check() (warnings, errorList []error) {
  548. klog.V(1).Infoln("validating whether swap is enabled or not")
  549. f, err := os.Open("/proc/swaps")
  550. if err != nil {
  551. // /proc/swaps not available, thus no reasons to warn
  552. return nil, nil
  553. }
  554. defer f.Close()
  555. var buf []string
  556. scanner := bufio.NewScanner(f)
  557. for scanner.Scan() {
  558. buf = append(buf, scanner.Text())
  559. }
  560. if err := scanner.Err(); err != nil {
  561. return nil, []error{errors.Wrap(err, "error parsing /proc/swaps")}
  562. }
  563. if len(buf) > 1 {
  564. return nil, []error{errors.New("running with swap on is not supported. Please disable swap")}
  565. }
  566. return nil, nil
  567. }
  568. type etcdVersionResponse struct {
  569. Etcdserver string `json:"etcdserver"`
  570. Etcdcluster string `json:"etcdcluster"`
  571. }
  572. // ExternalEtcdVersionCheck checks if version of external etcd meets the demand of kubeadm
  573. type ExternalEtcdVersionCheck struct {
  574. Etcd kubeadmapi.Etcd
  575. }
  576. // Name will return ExternalEtcdVersion as name for ExternalEtcdVersionCheck
  577. func (ExternalEtcdVersionCheck) Name() string {
  578. return "ExternalEtcdVersion"
  579. }
  580. // Check validates external etcd version
  581. // TODO: Use the official etcd Golang client for this instead?
  582. func (evc ExternalEtcdVersionCheck) Check() (warnings, errorList []error) {
  583. klog.V(1).Infoln("validating the external etcd version")
  584. // Return quickly if the user isn't using external etcd
  585. if evc.Etcd.External.Endpoints == nil {
  586. return nil, nil
  587. }
  588. var config *tls.Config
  589. var err error
  590. if config, err = evc.configRootCAs(config); err != nil {
  591. errorList = append(errorList, err)
  592. return nil, errorList
  593. }
  594. if config, err = evc.configCertAndKey(config); err != nil {
  595. errorList = append(errorList, err)
  596. return nil, errorList
  597. }
  598. client := evc.getHTTPClient(config)
  599. for _, endpoint := range evc.Etcd.External.Endpoints {
  600. if _, err := url.Parse(endpoint); err != nil {
  601. errorList = append(errorList, errors.Wrapf(err, "failed to parse external etcd endpoint %s", endpoint))
  602. continue
  603. }
  604. resp := etcdVersionResponse{}
  605. var err error
  606. versionURL := fmt.Sprintf("%s/%s", endpoint, "version")
  607. if tmpVersionURL, err := purell.NormalizeURLString(versionURL, purell.FlagRemoveDuplicateSlashes); err != nil {
  608. errorList = append(errorList, errors.Wrapf(err, "failed to normalize external etcd version url %s", versionURL))
  609. continue
  610. } else {
  611. versionURL = tmpVersionURL
  612. }
  613. if err = getEtcdVersionResponse(client, versionURL, &resp); err != nil {
  614. errorList = append(errorList, err)
  615. continue
  616. }
  617. etcdVersion, err := versionutil.ParseSemantic(resp.Etcdserver)
  618. if err != nil {
  619. errorList = append(errorList, errors.Wrapf(err, "couldn't parse external etcd version %q", resp.Etcdserver))
  620. continue
  621. }
  622. if etcdVersion.LessThan(minExternalEtcdVersion) {
  623. errorList = append(errorList, errors.Errorf("this version of kubeadm only supports external etcd version >= %s. Current version: %s", kubeadmconstants.MinExternalEtcdVersion, resp.Etcdserver))
  624. continue
  625. }
  626. }
  627. return nil, errorList
  628. }
  629. // configRootCAs configures and returns a reference to tls.Config instance if CAFile is provided
  630. func (evc ExternalEtcdVersionCheck) configRootCAs(config *tls.Config) (*tls.Config, error) {
  631. var CACertPool *x509.CertPool
  632. if evc.Etcd.External.CAFile != "" {
  633. CACert, err := ioutil.ReadFile(evc.Etcd.External.CAFile)
  634. if err != nil {
  635. return nil, errors.Wrapf(err, "couldn't load external etcd's server certificate %s", evc.Etcd.External.CAFile)
  636. }
  637. CACertPool = x509.NewCertPool()
  638. CACertPool.AppendCertsFromPEM(CACert)
  639. }
  640. if CACertPool != nil {
  641. if config == nil {
  642. config = &tls.Config{}
  643. }
  644. config.RootCAs = CACertPool
  645. }
  646. return config, nil
  647. }
  648. // configCertAndKey configures and returns a reference to tls.Config instance if CertFile and KeyFile pair is provided
  649. func (evc ExternalEtcdVersionCheck) configCertAndKey(config *tls.Config) (*tls.Config, error) {
  650. var cert tls.Certificate
  651. if evc.Etcd.External.CertFile != "" && evc.Etcd.External.KeyFile != "" {
  652. var err error
  653. cert, err = tls.LoadX509KeyPair(evc.Etcd.External.CertFile, evc.Etcd.External.KeyFile)
  654. if err != nil {
  655. return nil, errors.Wrapf(err, "couldn't load external etcd's certificate and key pair %s, %s", evc.Etcd.External.CertFile, evc.Etcd.External.KeyFile)
  656. }
  657. if config == nil {
  658. config = &tls.Config{}
  659. }
  660. config.Certificates = []tls.Certificate{cert}
  661. }
  662. return config, nil
  663. }
  664. func (evc ExternalEtcdVersionCheck) getHTTPClient(config *tls.Config) *http.Client {
  665. if config != nil {
  666. transport := netutil.SetOldTransportDefaults(&http.Transport{
  667. TLSClientConfig: config,
  668. })
  669. return &http.Client{
  670. Transport: transport,
  671. Timeout: externalEtcdRequestTimeout,
  672. }
  673. }
  674. return &http.Client{Timeout: externalEtcdRequestTimeout, Transport: netutil.SetOldTransportDefaults(&http.Transport{})}
  675. }
  676. func getEtcdVersionResponse(client *http.Client, url string, target interface{}) error {
  677. loopCount := externalEtcdRequestRetries + 1
  678. var err error
  679. var stopRetry bool
  680. for loopCount > 0 {
  681. if loopCount <= externalEtcdRequestRetries {
  682. time.Sleep(externalEtcdRequestInterval)
  683. }
  684. stopRetry, err = func() (stopRetry bool, err error) {
  685. r, err := client.Get(url)
  686. if err != nil {
  687. loopCount--
  688. return false, err
  689. }
  690. defer r.Body.Close()
  691. if r != nil && r.StatusCode >= 500 && r.StatusCode <= 599 {
  692. loopCount--
  693. return false, errors.Errorf("server responded with non-successful status: %s", r.Status)
  694. }
  695. return true, json.NewDecoder(r.Body).Decode(target)
  696. }()
  697. if stopRetry {
  698. break
  699. }
  700. }
  701. return err
  702. }
  703. // ImagePullCheck will pull container images used by kubeadm
  704. type ImagePullCheck struct {
  705. runtime utilruntime.ContainerRuntime
  706. imageList []string
  707. }
  708. // Name returns the label for ImagePullCheck
  709. func (ImagePullCheck) Name() string {
  710. return "ImagePull"
  711. }
  712. // Check pulls images required by kubeadm. This is a mutating check
  713. func (ipc ImagePullCheck) Check() (warnings, errorList []error) {
  714. for _, image := range ipc.imageList {
  715. ret, err := ipc.runtime.ImageExists(image)
  716. if ret && err == nil {
  717. klog.V(1).Infof("image exists: %s", image)
  718. continue
  719. }
  720. if err != nil {
  721. errorList = append(errorList, errors.Wrapf(err, "failed to check if image %s exists", image))
  722. }
  723. klog.V(1).Infof("pulling %s", image)
  724. if err := ipc.runtime.PullImage(image); err != nil {
  725. errorList = append(errorList, errors.Wrapf(err, "failed to pull image %s", image))
  726. }
  727. }
  728. return warnings, errorList
  729. }
  730. // NumCPUCheck checks if current number of CPUs is not less than required
  731. type NumCPUCheck struct {
  732. NumCPU int
  733. }
  734. // Name returns the label for NumCPUCheck
  735. func (NumCPUCheck) Name() string {
  736. return "NumCPU"
  737. }
  738. // Check number of CPUs required by kubeadm
  739. func (ncc NumCPUCheck) Check() (warnings, errorList []error) {
  740. numCPU := runtime.NumCPU()
  741. if numCPU < ncc.NumCPU {
  742. errorList = append(errorList, errors.Errorf("the number of available CPUs %d is less than the required %d", numCPU, ncc.NumCPU))
  743. }
  744. return warnings, errorList
  745. }
  746. // RunInitNodeChecks executes all individual, applicable to control-plane node checks.
  747. // The boolean flag 'isSecondaryControlPlane' controls whether we are running checks in a --join-control-plane scenario.
  748. // The boolean flag 'downloadCerts' controls whether we should skip checks on certificates because we are downloading them.
  749. // If the flag is set to true we should skip checks already executed by RunJoinNodeChecks.
  750. func RunInitNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.InitConfiguration, ignorePreflightErrors sets.String, isSecondaryControlPlane bool, downloadCerts bool) error {
  751. if !isSecondaryControlPlane {
  752. // First, check if we're root separately from the other preflight checks and fail fast
  753. if err := RunRootCheckOnly(ignorePreflightErrors); err != nil {
  754. return err
  755. }
  756. }
  757. manifestsDir := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ManifestsSubDirName)
  758. checks := []Checker{
  759. NumCPUCheck{NumCPU: kubeadmconstants.ControlPlaneNumCPU},
  760. KubernetesVersionCheck{KubernetesVersion: cfg.KubernetesVersion, KubeadmVersion: kubeadmversion.Get().GitVersion},
  761. FirewalldCheck{ports: []int{int(cfg.LocalAPIEndpoint.BindPort), kubeadmconstants.KubeletPort}},
  762. PortOpenCheck{port: int(cfg.LocalAPIEndpoint.BindPort)},
  763. PortOpenCheck{port: kubeadmconstants.KubeSchedulerPort},
  764. PortOpenCheck{port: kubeadmconstants.KubeControllerManagerPort},
  765. FileAvailableCheck{Path: kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.KubeAPIServer, manifestsDir)},
  766. FileAvailableCheck{Path: kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.KubeControllerManager, manifestsDir)},
  767. FileAvailableCheck{Path: kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.KubeScheduler, manifestsDir)},
  768. FileAvailableCheck{Path: kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.Etcd, manifestsDir)},
  769. HTTPProxyCheck{Proto: "https", Host: cfg.LocalAPIEndpoint.AdvertiseAddress},
  770. }
  771. cidrs := strings.Split(cfg.Networking.ServiceSubnet, ",")
  772. for _, cidr := range cidrs {
  773. checks = append(checks, HTTPProxyCIDRCheck{Proto: "https", CIDR: cidr})
  774. }
  775. cidrs = strings.Split(cfg.Networking.PodSubnet, ",")
  776. for _, cidr := range cidrs {
  777. checks = append(checks, HTTPProxyCIDRCheck{Proto: "https", CIDR: cidr})
  778. }
  779. if !isSecondaryControlPlane {
  780. checks = addCommonChecks(execer, cfg.KubernetesVersion, &cfg.NodeRegistration, checks)
  781. // Check if Bridge-netfilter and IPv6 relevant flags are set
  782. if ip := net.ParseIP(cfg.LocalAPIEndpoint.AdvertiseAddress); ip != nil {
  783. if utilsnet.IsIPv6(ip) {
  784. checks = append(checks,
  785. FileContentCheck{Path: bridgenf6, Content: []byte{'1'}},
  786. FileContentCheck{Path: ipv6DefaultForwarding, Content: []byte{'1'}},
  787. )
  788. }
  789. }
  790. // if using an external etcd
  791. if cfg.Etcd.External != nil {
  792. // Check external etcd version before creating the cluster
  793. checks = append(checks, ExternalEtcdVersionCheck{Etcd: cfg.Etcd})
  794. }
  795. }
  796. if cfg.Etcd.Local != nil {
  797. // Only do etcd related checks when required to install a local etcd
  798. checks = append(checks,
  799. PortOpenCheck{port: kubeadmconstants.EtcdListenClientPort},
  800. PortOpenCheck{port: kubeadmconstants.EtcdListenPeerPort},
  801. DirAvailableCheck{Path: cfg.Etcd.Local.DataDir},
  802. )
  803. }
  804. if cfg.Etcd.External != nil && !(isSecondaryControlPlane && downloadCerts) {
  805. // Only check etcd certificates when using an external etcd and not joining with automatic download of certs
  806. if cfg.Etcd.External.CAFile != "" {
  807. checks = append(checks, FileExistingCheck{Path: cfg.Etcd.External.CAFile, Label: "ExternalEtcdClientCertificates"})
  808. }
  809. if cfg.Etcd.External.CertFile != "" {
  810. checks = append(checks, FileExistingCheck{Path: cfg.Etcd.External.CertFile, Label: "ExternalEtcdClientCertificates"})
  811. }
  812. if cfg.Etcd.External.KeyFile != "" {
  813. checks = append(checks, FileExistingCheck{Path: cfg.Etcd.External.KeyFile, Label: "ExternalEtcdClientCertificates"})
  814. }
  815. }
  816. return RunChecks(checks, os.Stderr, ignorePreflightErrors)
  817. }
  818. // RunJoinNodeChecks executes all individual, applicable to node checks.
  819. func RunJoinNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.JoinConfiguration, ignorePreflightErrors sets.String) error {
  820. // First, check if we're root separately from the other preflight checks and fail fast
  821. if err := RunRootCheckOnly(ignorePreflightErrors); err != nil {
  822. return err
  823. }
  824. checks := []Checker{
  825. DirAvailableCheck{Path: filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ManifestsSubDirName)},
  826. FileAvailableCheck{Path: filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.KubeletKubeConfigFileName)},
  827. FileAvailableCheck{Path: filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.KubeletBootstrapKubeConfigFileName)},
  828. }
  829. checks = addCommonChecks(execer, "", &cfg.NodeRegistration, checks)
  830. if cfg.ControlPlane == nil {
  831. checks = append(checks, FileAvailableCheck{Path: cfg.CACertPath})
  832. }
  833. addIPv6Checks := false
  834. if cfg.Discovery.BootstrapToken != nil {
  835. ipstr, _, err := net.SplitHostPort(cfg.Discovery.BootstrapToken.APIServerEndpoint)
  836. if err == nil {
  837. checks = append(checks,
  838. HTTPProxyCheck{Proto: "https", Host: ipstr},
  839. )
  840. if ip := net.ParseIP(ipstr); ip != nil {
  841. if utilsnet.IsIPv6(ip) {
  842. addIPv6Checks = true
  843. }
  844. }
  845. }
  846. }
  847. if addIPv6Checks {
  848. checks = append(checks,
  849. FileContentCheck{Path: bridgenf6, Content: []byte{'1'}},
  850. FileContentCheck{Path: ipv6DefaultForwarding, Content: []byte{'1'}},
  851. )
  852. }
  853. return RunChecks(checks, os.Stderr, ignorePreflightErrors)
  854. }
  855. // addCommonChecks is a helper function to duplicate checks that are common between both the
  856. // kubeadm init and join commands
  857. func addCommonChecks(execer utilsexec.Interface, k8sVersion string, nodeReg *kubeadmapi.NodeRegistrationOptions, checks []Checker) []Checker {
  858. containerRuntime, err := utilruntime.NewContainerRuntime(execer, nodeReg.CRISocket)
  859. isDocker := false
  860. if err != nil {
  861. fmt.Printf("[preflight] WARNING: Couldn't create the interface used for talking to the container runtime: %v\n", err)
  862. } else {
  863. checks = append(checks, ContainerRuntimeCheck{runtime: containerRuntime})
  864. if containerRuntime.IsDocker() {
  865. isDocker = true
  866. checks = append(checks, ServiceCheck{Service: "docker", CheckIfActive: true})
  867. // Linux only
  868. // TODO: support other CRIs for this check eventually
  869. // https://github.com/kubernetes/kubeadm/issues/874
  870. checks = append(checks, IsDockerSystemdCheck{})
  871. }
  872. }
  873. // non-windows checks
  874. if runtime.GOOS == "linux" {
  875. if !isDocker {
  876. checks = append(checks, InPathCheck{executable: "crictl", mandatory: true, exec: execer})
  877. }
  878. checks = append(checks,
  879. FileContentCheck{Path: bridgenf, Content: []byte{'1'}},
  880. FileContentCheck{Path: ipv4Forward, Content: []byte{'1'}},
  881. SwapCheck{},
  882. InPathCheck{executable: "conntrack", mandatory: true, exec: execer},
  883. InPathCheck{executable: "ip", mandatory: true, exec: execer},
  884. InPathCheck{executable: "iptables", mandatory: true, exec: execer},
  885. InPathCheck{executable: "mount", mandatory: true, exec: execer},
  886. InPathCheck{executable: "nsenter", mandatory: true, exec: execer},
  887. InPathCheck{executable: "ebtables", mandatory: false, exec: execer},
  888. InPathCheck{executable: "ethtool", mandatory: false, exec: execer},
  889. InPathCheck{executable: "socat", mandatory: false, exec: execer},
  890. InPathCheck{executable: "tc", mandatory: false, exec: execer},
  891. InPathCheck{executable: "touch", mandatory: false, exec: execer})
  892. }
  893. checks = append(checks,
  894. SystemVerificationCheck{IsDocker: isDocker},
  895. HostnameCheck{nodeName: nodeReg.Name},
  896. KubeletVersionCheck{KubernetesVersion: k8sVersion, exec: execer},
  897. ServiceCheck{Service: "kubelet", CheckIfActive: false},
  898. PortOpenCheck{port: kubeadmconstants.KubeletPort})
  899. return checks
  900. }
  901. // RunRootCheckOnly initializes checks slice of structs and call RunChecks
  902. func RunRootCheckOnly(ignorePreflightErrors sets.String) error {
  903. checks := []Checker{
  904. IsPrivilegedUserCheck{},
  905. }
  906. return RunChecks(checks, os.Stderr, ignorePreflightErrors)
  907. }
  908. // RunPullImagesCheck will pull images kubeadm needs if they are not found on the system
  909. func RunPullImagesCheck(execer utilsexec.Interface, cfg *kubeadmapi.InitConfiguration, ignorePreflightErrors sets.String) error {
  910. containerRuntime, err := utilruntime.NewContainerRuntime(utilsexec.New(), cfg.NodeRegistration.CRISocket)
  911. if err != nil {
  912. return err
  913. }
  914. checks := []Checker{
  915. ImagePullCheck{runtime: containerRuntime, imageList: images.GetControlPlaneImages(&cfg.ClusterConfiguration)},
  916. }
  917. return RunChecks(checks, os.Stderr, ignorePreflightErrors)
  918. }
  919. // RunChecks runs each check, displays it's warnings/errors, and once all
  920. // are processed will exit if any errors occurred.
  921. func RunChecks(checks []Checker, ww io.Writer, ignorePreflightErrors sets.String) error {
  922. var errsBuffer bytes.Buffer
  923. for _, c := range checks {
  924. name := c.Name()
  925. warnings, errs := c.Check()
  926. if setHasItemOrAll(ignorePreflightErrors, name) {
  927. // Decrease severity of errors to warnings for this check
  928. warnings = append(warnings, errs...)
  929. errs = []error{}
  930. }
  931. for _, w := range warnings {
  932. io.WriteString(ww, fmt.Sprintf("\t[WARNING %s]: %v\n", name, w))
  933. }
  934. for _, i := range errs {
  935. errsBuffer.WriteString(fmt.Sprintf("\t[ERROR %s]: %v\n", name, i.Error()))
  936. }
  937. }
  938. if errsBuffer.Len() > 0 {
  939. return &Error{Msg: errsBuffer.String()}
  940. }
  941. return nil
  942. }
  943. // setHasItemOrAll is helper function that return true if item is present in the set (case insensitive) or special key 'all' is present
  944. func setHasItemOrAll(s sets.String, item string) bool {
  945. if s.Has("all") || s.Has(strings.ToLower(item)) {
  946. return true
  947. }
  948. return false
  949. }