/
checks.go
509 lines (433 loc) · 14.5 KB
/
checks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*
* Tencent is pleased to support the open source community by making TKEStack
* available.
*
* Copyright (C) 2012-2019 Tencent. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at
*
* https://opensource.org/licenses/Apache-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package preflight
import (
"bytes"
"fmt"
"strconv"
"strings"
"github.com/pkg/errors"
"tkestack.io/tke/pkg/platform/provider/baremetal/constants"
v1 "tkestack.io/tke/pkg/platform/types/v1"
"tkestack.io/tke/pkg/util/ssh"
)
const (
ipv4Forward = "/proc/sys/net/ipv4/ip_forward"
)
var tools = []string{"sysctl", "swapoff", "sed", "getconf", "ss", "grep", "id", "uname", "modinfo", "ip", "awk", "iptables"}
var kernelParemeter = []string{
"CONFIG_BPF", "CONFIG_BPF_SYSCALL", "CONFIG_NET_CLS_BPF", "CONFIG_BPF_JIT",
"CONFIG_NET_CLS_ACT", "CONFIG_NET_SCH_INGRESS", "CONFIG_CRYPTO_SHA1",
"CONFIG_CRYPTO_USER_API_HASH", "CONFIG_CGROUPS", "CONFIG_CGROUP_BPF",
}
func newCommonChecks(c *v1.Cluster, s ssh.Interface) []Checker {
var checks []Checker
if c.Cluster.Spec.Features.EnableCilium {
checks = append(checks, []Checker{
KernelParameterCheck{Interface: s, KernelParameter: kernelParemeter},
KernelCheck{Interface: s, MinKernelVersion: 4, MinMajorVersion: 11},
PortOpenCheck{Interface: s, port: 4240},
PortOpenCheck{Interface: s, port: 9876},
PortOpenCheck{Interface: s, port: 9890},
PortOpenCheck{Interface: s, port: 9891},
}...)
}
checks = append(checks, []Checker{
IsPrivilegedUserCheck{Interface: s},
CPUArchCeck{Interface: s, Arch: 64},
KernelCheck{Interface: s, MinKernelVersion: 3, MinMajorVersion: 10},
KernelModuleCheck{Interface: s, Module: "iptable_nat"},
FileContentCheck{Interface: s, Path: ipv4Forward, Content: []byte{'1'}},
FileAvailableCheck{Interface: s, Path: constants.KubectlConfigFile},
DirEmptyCheck{Interface: s, Path: constants.CNIConfDIr},
DirAvailableCheck{Interface: s, Path: constants.CNIDataDir},
PortOpenCheck{Interface: s, port: constants.ProxyHealthzPort},
PortOpenCheck{Interface: s, port: constants.ProxyStatusPort},
PortOpenCheck{Interface: s, port: constants.KubeletPort},
}...)
return checks
}
// RunMasterChecks checks for master
func RunMasterChecks(c *v1.Cluster, s ssh.Interface) error {
checks := newCommonChecks(c, s)
checks = append(checks, []Checker{
NumCPUCheck{Interface: s, NumCPU: constants.MinNumCPU},
DirAvailableCheck{Interface: s, Path: constants.EtcdDataDir},
PortOpenCheck{Interface: s, port: 6443}, // kube-apiserver
PortOpenCheck{Interface: s, port: constants.InsecureSchedulerPort},
PortOpenCheck{Interface: s, port: constants.InsecureKubeControllerManagerPort},
PortOpenCheck{Interface: s, port: constants.ProxyHealthzPort},
PortOpenCheck{Interface: s, port: constants.ProxyStatusPort},
PortOpenCheck{Interface: s, port: constants.EtcdListenClientPort},
PortOpenCheck{Interface: s, port: constants.EtcdListenPeerPort},
}...)
for _, tool := range tools {
checks = append(checks, InPathCheck{Interface: s, executable: tool})
}
return RunChecks(checks)
}
// RunNodeChecks checks for node
func RunNodeChecks(c *v1.Cluster, s ssh.Interface) error {
checks := newCommonChecks(c, s)
checks = append(checks, []Checker{}...)
for _, tool := range tools {
checks = append(checks, InPathCheck{Interface: s, executable: tool})
}
return RunChecks(checks)
}
// RunChecks runs each check, displays it's warnings/errors, and once all
// are processed will exit if any errors occurred.
func RunChecks(checks []Checker) error {
var errsBuffer bytes.Buffer
for _, c := range checks {
name := c.Name()
warnings, errs := c.Check()
for _, w := range warnings {
errsBuffer.WriteString(fmt.Sprintf("\t[WARNING %s]: %v\n", name, w))
}
for _, i := range errs {
errsBuffer.WriteString(fmt.Sprintf("\t[ERROR %s]: %v\n", name, i.Error()))
}
}
if errsBuffer.Len() > 0 {
return &Error{Msg: errsBuffer.String()}
}
return nil
}
// Error defines struct for communicating error messages generated by preflight checks
type Error struct {
Msg string
}
// Error implements the standard error interface
func (e *Error) Error() string {
return fmt.Sprintf("[preflight] Some fatal errors occurred:\n%s", e.Msg)
}
// Preflight identifies this error as a preflight error
func (e *Error) Preflight() bool {
return true
}
// Checker validates the state of the system to ensure kubeadm will be
// successful as often as possible.
type Checker interface {
Check() (warnings, errorList []error)
Name() string
}
// NumCPUCheck checks if current number of CPUs is not less than required
type NumCPUCheck struct {
ssh.Interface
NumCPU int
}
// Name returns the label for NumCPUCheck
func (NumCPUCheck) Name() string {
return "NumCPU"
}
// Check number of CPUs required by kubeadm
func (ncc NumCPUCheck) Check() (warnings, errorList []error) {
result, err := ncc.CombinedOutput("getconf _NPROCESSORS_ONLN")
if err != nil {
errorList = append(errorList, err)
return
}
numCPU, err := strconv.Atoi(strings.TrimSpace(string(result)))
if err != nil {
errorList = append(errorList, err)
return
}
if numCPU < ncc.NumCPU {
errorList = append(errorList, errors.Errorf("the number of available CPUs %d is less than the required %d", numCPU, ncc.NumCPU))
}
return warnings, errorList
}
// CPUArchCeck checks cpu arch
type CPUArchCeck struct {
ssh.Interface
Arch int
}
// Name returns the label for CPUArchCeck
func (CPUArchCeck) Name() string {
return "NumCPU"
}
// Check checks cpu arch
func (cac CPUArchCeck) Check() (warnings, errorList []error) {
result, err := cac.CombinedOutput("getconf LONG_BIT")
if err != nil {
errorList = append(errorList, err)
return
}
arch, err := strconv.Atoi(strings.TrimSpace(string(result)))
if err != nil {
errorList = append(errorList, err)
return
}
if arch != cac.Arch {
errorList = append(errorList, errors.Errorf("only support CPU arch %d, but current is %d", cac.Arch, arch))
}
return warnings, errorList
}
// PortOpenCheck ensures the given port is available for use.
type PortOpenCheck struct {
ssh.Interface
port int
label string
}
// Name returns name for PortOpenCheck. If not known, will return "PortXXXX" based on port number
func (poc PortOpenCheck) Name() string {
if poc.label != "" {
return poc.label
}
return fmt.Sprintf("Port-%d", poc.port)
}
// Check validates if the particular port is available.
func (poc PortOpenCheck) Check() (warnings, errorList []error) {
errorList = []error{}
stdout, _, exit, err := poc.Exec(fmt.Sprintf("ss -ntl | grep -w ':%d'", poc.port))
if err != nil {
errorList = append(errorList, err)
return
}
if exit == 0 {
errorList = append(errorList, errors.Errorf("Port %d is in use:%s", poc.port, stdout))
}
return nil, errorList
}
// FileAvailableCheck checks that the given file does not already exist.
type FileAvailableCheck struct {
ssh.Interface
Path string
Label string
}
// Name returns label for individual FileAvailableChecks. If not known, will return based on path.
func (fac FileAvailableCheck) Name() string {
if fac.Label != "" {
return fac.Label
}
return fmt.Sprintf("FileAvailable-%s", strings.Replace(fac.Path, "/", "-", -1))
}
// Check validates if the given file does not already exist.
func (fac FileAvailableCheck) Check() (warnings, errorList []error) {
if ok, err := fac.Exist(fac.Path); err == nil && ok {
errorList = append(errorList, errors.Errorf("%s already exists", fac.Path))
}
return nil, errorList
}
// FileContentCheck checks that the given file contains the string Content.
type FileContentCheck struct {
ssh.Interface
Path string
Content []byte
Label string
}
// Name returns label for individual FileContentChecks. If not known, will return based on path.
func (fcc FileContentCheck) Name() string {
if fcc.Label != "" {
return fcc.Label
}
return fmt.Sprintf("FileContent-%s", strings.Replace(fcc.Path, "/", "-", -1))
}
// Check validates if the given file contains the given content.
func (fcc FileContentCheck) Check() (warnings, errorList []error) {
data, err := fcc.ReadFile(fcc.Path)
if err != nil {
return nil, []error{err}
}
if !bytes.Equal(data[:len(fcc.Content)], fcc.Content) {
return nil, []error{errors.Errorf("%s contents are not set to %s", fcc.Path, fcc.Content)}
}
return nil, []error{}
}
// InPathCheck checks if the given executable is present in $PATH
type InPathCheck struct {
ssh.Interface
executable string
mandatory bool
label string
suggestion string
}
// Name returns label for individual InPathCheck. If not known, will return based on path.
func (ipc InPathCheck) Name() string {
if ipc.label != "" {
return ipc.label
}
return fmt.Sprintf("FileExisting-%s", strings.Replace(ipc.executable, "/", "-", -1))
}
// Check validates if the given executable is present in the path.
func (ipc InPathCheck) Check() (warnings, errs []error) {
_, err := ipc.LookPath(ipc.executable)
if err != nil {
if ipc.mandatory {
// Return as an error:
return nil, []error{errors.Errorf("%s not found in system path", ipc.executable)}
}
// Return as a warning:
warningMessage := fmt.Sprintf("%s not found in system path", ipc.executable)
if ipc.suggestion != "" {
warningMessage += fmt.Sprintf("\nSuggestion: %s", ipc.suggestion)
}
return []error{errors.New(warningMessage)}, nil
}
return nil, nil
}
// IsPrivilegedUserCheck verifies user is privileged (linux - root, windows - Administrator)
type IsPrivilegedUserCheck struct {
ssh.Interface
}
// Name returns name for IsPrivilegedUserCheck
func (IsPrivilegedUserCheck) Name() string {
return "IsPrivilegedUser"
}
// Check validates if an user has elevated (root) privileges.
func (ipuc IsPrivilegedUserCheck) Check() (warnings, errorList []error) {
errorList = []error{}
result, err := ipuc.CombinedOutput("id -u")
if err != nil {
errorList = append(errorList, err)
return
}
uid, err := strconv.Atoi(strings.TrimSpace(string(result)))
if err != nil {
errorList = append(errorList, err)
return
}
if uid != 0 {
errorList = append(errorList, errors.New("user is not running as root"))
}
return nil, errorList
}
// DirAvailableCheck checks if the given directory either does not exist, or is empty.
type DirAvailableCheck struct {
ssh.Interface
Path string
Label string
}
// Name returns label for individual DirAvailableChecks. If not known, will return based on path.
func (dac DirAvailableCheck) Name() string {
if dac.Label != "" {
return dac.Label
}
return fmt.Sprintf("DirAvailable-%s", strings.Replace(dac.Path, "/", "-", -1))
}
// Check validates if a directory does not exist or empty.
func (dac DirAvailableCheck) Check() (warnings, errorList []error) {
if ok, err := dac.Exist(dac.Path); err == nil && ok {
errorList = append(errorList, errors.Errorf("%s already exists", dac.Path))
}
return nil, errorList
}
// DirEmptyCheck checks if the given directory either does not exist, or is empty.
type DirEmptyCheck struct {
ssh.Interface
Path string
Label string
}
// Name returns label for individual DirEmptyCheck. If not known, will return based on path.
func (dmc DirEmptyCheck) Name() string {
if dmc.Label != "" {
return dmc.Label
}
return fmt.Sprintf("DirEmptyCheck-%s", strings.Replace(dmc.Path, "/", "-", -1))
}
// Check validates if a directory is empty.
func (dmc DirEmptyCheck) Check() (warnings, errorList []error) {
if res, err := dmc.ReadDir(dmc.Path); err == nil && len(res) != 0 {
errorList = append(errorList, errors.Errorf("%s not empty dir", dmc.Path))
}
return nil, errorList
}
// Check the kernel version and kernel parameter for Cilium installation.
type KernelParameterCheck struct {
ssh.Interface
KernelParameter []string
}
// Name returns label for KernelCheck
func (kc KernelParameterCheck) Name() string {
return fmt.Sprintf("KernelParameter-%s", kc.KernelParameter)
}
// Check validates kernel version and parameter.
func (kc KernelParameterCheck) Check() (warnings, errorList []error) {
for _, kp := range kc.KernelParameter {
_, _, exit, err := kc.Exec(fmt.Sprintf("cat /boot/config-$(uname -r) | grep '%s='", kp))
if err != nil {
errorList = append(errorList, err)
return
}
if exit != 0 {
errorList = append(errorList, errors.Errorf("Parameter %s is not set", kp))
}
}
return nil, errorList
}
// KernelCheck checks if kernel meet requires
type KernelCheck struct {
ssh.Interface
MinKernelVersion int
MinMajorVersion int
}
// Name returns label for KernelCheck
func (kc KernelCheck) Name() string {
return fmt.Sprintf("KernelCheck-%d-%d", kc.MinKernelVersion, kc.MinMajorVersion)
}
// Check validates kernel version
func (kc KernelCheck) Check() (warnings, errorList []error) {
result, err := kc.CombinedOutput("uname -r")
if err != nil {
errorList = append(errorList, err)
return
}
versionStr := strings.TrimSpace(string(result))
versions := strings.Split(strings.TrimSpace(string(result)), ".")
if len(versions) < 2 {
errorList = append(errorList, errors.Errorf("parse version error:%s", versionStr))
return
}
kernelVersion, err := strconv.Atoi(versions[0])
if err != nil {
errorList = append(errorList, err)
return
}
majorVersion, err := strconv.Atoi(versions[1])
if err != nil {
errorList = append(errorList, err)
return
}
if (kernelVersion < kc.MinKernelVersion) ||
(kernelVersion == kc.MinKernelVersion && majorVersion < kc.MinMajorVersion) {
errorList = append(errorList, errors.Errorf("kernel version(%s) must not lower than %d.%d", versionStr, kc.MinKernelVersion, kc.MinMajorVersion))
}
return nil, errorList
}
// KernelModuleCheck checks that the given kernel module wheather exists
type KernelModuleCheck struct {
ssh.Interface
Module string
Label string
}
// Name returns label for individual FileAvailableChecks. If not known, will return based on path.
func (kmc KernelModuleCheck) Name() string {
if kmc.Label != "" {
return kmc.Label
}
return fmt.Sprintf("KernelModule-%s", strings.Replace(kmc.Module, "/", "-", -1))
}
// Check validates if the given file does not already exist.
func (kmc KernelModuleCheck) Check() (warnings, errorList []error) {
_, _, exit, err := kmc.Execf("modinfo %s", kmc.Module)
if err != nil || exit != 0 {
errorList = append(errorList, errors.Errorf("%s is required", kmc.Module))
}
return nil, errorList
}