-
Notifications
You must be signed in to change notification settings - Fork 306
/
check.go
401 lines (373 loc) · 11.7 KB
/
check.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
// Copyright 2020 PingCAP, Inc.
//
// 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package command
import (
"fmt"
"path"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/joomcode/errorx"
"github.com/pingcap/errors"
"github.com/pingcap/tiup/pkg/cliutil"
"github.com/pingcap/tiup/pkg/cliutil/prepare"
"github.com/pingcap/tiup/pkg/cluster/clusterutil"
"github.com/pingcap/tiup/pkg/cluster/meta"
operator "github.com/pingcap/tiup/pkg/cluster/operation"
"github.com/pingcap/tiup/pkg/cluster/task"
"github.com/pingcap/tiup/pkg/logger"
"github.com/pingcap/tiup/pkg/logger/log"
"github.com/pingcap/tiup/pkg/utils"
"github.com/spf13/cobra"
)
type checkOptions struct {
user string // username to login to the SSH server
identityFile string // path to the private key file
usePassword bool // use password instead of identity file for ssh connection
opr *operator.CheckOptions
applyFix bool // try to apply fixes of failed checks
}
func newCheckCmd() *cobra.Command {
opt := checkOptions{
opr: &operator.CheckOptions{},
identityFile: path.Join(utils.UserHome(), ".ssh", "id_rsa"),
}
cmd := &cobra.Command{
Use: "check <topology.yml>",
Short: "Perform preflight checks for the cluster.",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return cmd.Help()
}
logger.EnableAuditLog()
var topo meta.DMTopologySpecification
if err := clusterutil.ParseTopologyYaml(args[0], &topo); err != nil {
return err
}
// use a dummy cluster name, the real cluster name is set during deploy
if err := prepare.CheckClusterPortConflict("nonexist-dummy-dm-cluster", &topo); err != nil {
return err
}
if err := prepare.CheckClusterDirConflict("nonexist-dummy-dm-cluster", &topo); err != nil {
return err
}
sshConnProps, err := cliutil.ReadIdentityFileOrPassword(opt.identityFile, opt.usePassword)
if err != nil {
return err
}
return checkSystemInfo(sshConnProps, &topo, &opt)
},
}
cmd.Flags().StringVar(&opt.user, "user", utils.CurrentUser(), "The user name to login via SSH. The user must has root (or sudo) privilege.")
cmd.Flags().StringVarP(&opt.identityFile, "identity_file", "i", opt.identityFile, "The path of the SSH identity file. If specified, public key authentication will be used.")
cmd.Flags().BoolVarP(&opt.usePassword, "password", "p", false, "Use password of target hosts. If specified, password authentication will be used.")
cmd.Flags().BoolVar(&opt.opr.EnableCPU, "enable-cpu", false, "Enable CPU thread count check")
cmd.Flags().BoolVar(&opt.opr.EnableMem, "enable-mem", false, "Enable memory size check")
cmd.Flags().BoolVar(&opt.opr.EnableDisk, "enable-disk", false, "Enable disk IO (fio) check")
cmd.Flags().BoolVar(&opt.applyFix, "apply", false, "Try to fix failed checks")
return cmd
}
// checkSystemInfo performs series of checks and tests of the deploy server
func checkSystemInfo(s *cliutil.SSHConnectionProps, topo *meta.DMTopologySpecification, opt *checkOptions) error {
var (
collectTasks []*task.StepDisplay
checkSysTasks []*task.StepDisplay
cleanTasks []*task.StepDisplay
applyFixTasks []*task.StepDisplay
downloadTasks []*task.StepDisplay
)
insightVer := meta.ComponentVersion(meta.ComponentCheckCollector, "")
uniqueHosts := map[string]int{} // host -> ssh-port
uniqueArchList := make(map[string]struct{}) // map["os-arch"]{}
topo.IterInstance(func(inst meta.Instance) {
archKey := fmt.Sprintf("%s-%s", inst.OS(), inst.Arch())
if _, found := uniqueArchList[archKey]; !found {
uniqueArchList[archKey] = struct{}{}
t0 := task.NewBuilder().
Download(
meta.ComponentCheckCollector,
inst.OS(),
inst.Arch(),
insightVer,
).
BuildAsStep(fmt.Sprintf(" - Downloading check tools for %s/%s", inst.OS(), inst.Arch()))
downloadTasks = append(downloadTasks, t0)
}
if _, found := uniqueHosts[inst.GetHost()]; !found {
uniqueHosts[inst.GetHost()] = inst.GetSSHPort()
// build system info collecting tasks
t1 := task.NewBuilder().
RootSSH(
inst.GetHost(),
inst.GetSSHPort(),
opt.user,
s.Password,
s.IdentityFile,
s.IdentityFilePassphrase,
gOpt.SSHTimeout,
).
Mkdir(opt.user, inst.GetHost(), filepath.Join(task.CheckToolsPathDir, "bin")).
CopyComponent(
meta.ComponentCheckCollector,
inst.OS(),
inst.Arch(),
insightVer,
inst.GetHost(),
task.CheckToolsPathDir,
).
Shell(
inst.GetHost(),
filepath.Join(task.CheckToolsPathDir, "bin", "insight"),
false,
).
BuildAsStep(fmt.Sprintf(" - Getting system info of %s:%d", inst.GetHost(), inst.GetSSHPort()))
collectTasks = append(collectTasks, t1)
// if the data dir set in topology is relative, and the home dir of deploy user
// and the user run the check command is on different partitions, the disk detection
// may be using incorrect partition for validations.
for _, dataDir := range clusterutil.MultiDirAbs(opt.user, inst.DataDir()) {
// build checking tasks
t2 := task.NewBuilder().
CheckSys(
inst.GetHost(),
dataDir,
task.CheckTypeSystemInfo,
topo,
opt.opr,
).
CheckSys(
inst.GetHost(),
dataDir,
task.CheckTypePartitions,
topo,
opt.opr,
).
Shell(
inst.GetHost(),
"ss -lnt",
false,
).
CheckSys(
inst.GetHost(),
dataDir,
task.CheckTypePort,
topo,
opt.opr,
).
Shell(
inst.GetHost(),
"cat /etc/security/limits.conf",
false,
).
CheckSys(
inst.GetHost(),
dataDir,
task.CheckTypeSystemLimits,
topo,
opt.opr,
).
Shell(
inst.GetHost(),
"sysctl -a",
true,
).
CheckSys(
inst.GetHost(),
dataDir,
task.CheckTypeSystemConfig,
topo,
opt.opr,
).
CheckSys(
inst.GetHost(),
dataDir,
task.CheckTypeService,
topo,
opt.opr,
).
CheckSys(
inst.GetHost(),
dataDir,
task.CheckTypePackage,
topo,
opt.opr,
).
CheckSys(
inst.GetHost(),
dataDir,
task.CheckTypeFIO,
topo,
opt.opr,
).
BuildAsStep(fmt.Sprintf(" - Checking node %s", inst.GetHost()))
checkSysTasks = append(checkSysTasks, t2)
}
t3 := task.NewBuilder().
RootSSH(
inst.GetHost(),
inst.GetSSHPort(),
opt.user,
s.Password,
s.IdentityFile,
s.IdentityFilePassphrase,
gOpt.SSHTimeout,
).
Rmdir(inst.GetHost(), task.CheckToolsPathDir).
BuildAsStep(fmt.Sprintf(" - Cleanup check files on %s:%d", inst.GetHost(), inst.GetSSHPort()))
cleanTasks = append(cleanTasks, t3)
}
})
t := task.NewBuilder().
ParallelStep("+ Download necessary tools", downloadTasks...).
ParallelStep("+ Collect basic system information", collectTasks...).
ParallelStep("+ Check system requirements", checkSysTasks...).
ParallelStep("+ Cleanup check files", cleanTasks...).
Build()
ctx := task.NewContext()
if err := t.Execute(ctx); err != nil {
if errorx.Cast(err) != nil {
// FIXME: Map possible task errors and give suggestions.
return err
}
return errors.Trace(err)
}
var checkResultTable [][]string
// FIXME: add fix result to output
checkResultTable = [][]string{
// Header
{"Node", "Check", "Result", "Message"},
}
for host := range uniqueHosts {
tf := task.NewBuilder().
RootSSH(
host,
uniqueHosts[host],
opt.user,
s.Password,
s.IdentityFile,
s.IdentityFilePassphrase,
gOpt.SSHTimeout,
)
resLines, err := handleCheckResults(ctx, host, opt, tf)
if err != nil {
continue
}
applyFixTasks = append(applyFixTasks, tf.BuildAsStep(fmt.Sprintf(" - Applying changes on %s", host)))
checkResultTable = append(checkResultTable, resLines...)
}
// print check results *before* trying to applying checks
// FIXME: add fix result to output, and display the table after fixing
cliutil.PrintTable(checkResultTable, true)
if opt.applyFix {
tc := task.NewBuilder().
ParallelStep("+ Try to apply changes to fix failed checks", applyFixTasks...).
Build()
if err := tc.Execute(ctx); err != nil {
if errorx.Cast(err) != nil {
// FIXME: Map possible task errors and give suggestions.
return err
}
return errors.Trace(err)
}
}
return nil
}
// handleCheckResults parses the result of checks
func handleCheckResults(ctx *task.Context, host string, opt *checkOptions, t *task.Builder) ([][]string, error) {
results, _ := ctx.GetCheckResults(host)
if len(results) < 1 {
return nil, fmt.Errorf("no check results found for %s", host)
}
lines := make([][]string, 0)
//log.Infof("Check results of %s: (only errors and important info are displayed)", color.HiCyanString(host))
for _, r := range results {
var line []string
if r.Err != nil {
if r.IsWarning() {
line = []string{host, r.Name, color.YellowString("Warn"), r.Error()}
} else {
line = []string{host, r.Name, color.HiRedString("Fail"), r.Error()}
}
if !opt.applyFix {
lines = append(lines, line)
continue
}
msg, err := fixFailedChecks(ctx, host, r, t)
if err != nil {
log.Debugf("%s: fail to apply fix to %s (%s)", host, r.Name, err)
}
if msg != "" {
// show auto fixing info
line[len(line)-1] = msg
}
} else if r.Msg != "" {
line = []string{host, r.Name, color.GreenString("Pass"), r.Msg}
}
// show errors and messages only, ignore empty lines
if len(line) > 0 {
lines = append(lines, line)
}
}
return lines, nil
}
// fixFailedChecks tries to automatically apply changes to fix failed checks
func fixFailedChecks(ctx *task.Context, host string, res *operator.CheckResult, t *task.Builder) (string, error) {
msg := ""
switch res.Name {
case operator.CheckNameSysService:
if strings.Contains(res.Msg, "not found") {
return "", nil
}
fields := strings.Fields(res.Msg)
if len(fields) < 2 {
return "", fmt.Errorf("can not perform action of service, %s", res.Msg)
}
t.SystemCtl(host, fields[1], fields[0])
msg = fmt.Sprintf("will try to '%s'", color.HiBlueString(res.Msg))
case operator.CheckNameSysctl:
fields := strings.Fields(res.Msg)
if len(fields) < 3 {
return "", fmt.Errorf("can not set kernel parameter, %s", res.Msg)
}
t.Sysctl(host, fields[0], fields[2])
msg = fmt.Sprintf("will try to set '%s'", color.HiBlueString(res.Msg))
case operator.CheckNameLimits:
fields := strings.Fields(res.Msg)
if len(fields) < 4 {
return "", fmt.Errorf("can not set limits, %s", res.Msg)
}
t.Limit(host, fields[0], fields[1], fields[2], fields[3])
msg = fmt.Sprintf("will try to set '%s'", color.HiBlueString(res.Msg))
case operator.CheckNameSELinux:
t.Shell(host,
fmt.Sprintf(
"sed -i 's/SELINUX=enforcing/SELINUX=no/g' %s && %s",
"/etc/selinux/config",
"setenforce 0",
),
true)
msg = fmt.Sprintf("will try to %s, reboot might be needed", color.HiBlueString("disable SELinux"))
case operator.CheckNameOSVer,
operator.CheckNameCPUThreads,
operator.CheckNameDisks,
operator.CheckNameEpoll,
operator.CheckNameMem,
operator.CheckNameCommand,
operator.CheckNameFio:
// don't show unsupported message for checks that are impossible to fix by us
return "", nil
default:
msg = fmt.Sprintf("%s, auto fixing not supported", res)
}
return msg, nil
}