-
Notifications
You must be signed in to change notification settings - Fork 553
/
start.go
1075 lines (1007 loc) · 28.4 KB
/
start.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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 Redpanda Data, Inc.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.md
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0
//go:build linux
// +build linux
package redpanda
import (
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/redpanda-data/redpanda/src/go/rpk/pkg/cli/cmd/common"
"github.com/redpanda-data/redpanda/src/go/rpk/pkg/cloud"
"github.com/redpanda-data/redpanda/src/go/rpk/pkg/config"
"github.com/redpanda-data/redpanda/src/go/rpk/pkg/net"
vos "github.com/redpanda-data/redpanda/src/go/rpk/pkg/os"
rp "github.com/redpanda-data/redpanda/src/go/rpk/pkg/redpanda"
"github.com/redpanda-data/redpanda/src/go/rpk/pkg/tuners"
"github.com/redpanda-data/redpanda/src/go/rpk/pkg/tuners/factory"
"github.com/redpanda-data/redpanda/src/go/rpk/pkg/tuners/hwloc"
"github.com/redpanda-data/redpanda/src/go/rpk/pkg/tuners/iotune"
log "github.com/sirupsen/logrus"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
type prestartConfig struct {
tuneEnabled bool
checkEnabled bool
}
type seastarFlags struct {
memory string
lockMemory bool
reserveMemory string
hugepages string
cpuSet string
ioPropertiesFile string
ioProperties string
smp int
threadAffinity bool
numIoQueues int
maxIoRequests int
mbind bool
overprovisioned bool
unsafeBypassFsync bool
}
const (
configFlag = "config"
memoryFlag = "memory"
lockMemoryFlag = "lock-memory"
reserveMemoryFlag = "reserve-memory"
hugepagesFlag = "hugepages"
cpuSetFlag = "cpuset"
ioPropertiesFileFlag = "io-properties-file"
ioPropertiesFlag = "io-properties"
wellKnownIOFlag = "well-known-io"
smpFlag = "smp"
threadAffinityFlag = "thread-affinity"
numIoQueuesFlag = "num-io-queues"
maxIoRequestsFlag = "max-io-requests"
mbindFlag = "mbind"
overprovisionedFlag = "overprovisioned"
unsafeBypassFsyncFlag = "unsafe-bypass-fsync"
nodeIDFlag = "node-id"
setConfigFlag = "set"
modeFlag = "mode"
checkFlag = "check"
)
func updateConfigWithFlags(conf *config.Config, flags *pflag.FlagSet) {
if flags.Changed(lockMemoryFlag) {
conf.Rpk.EnableMemoryLocking, _ = flags.GetBool(lockMemoryFlag)
}
if flags.Changed(wellKnownIOFlag) {
conf.Rpk.WellKnownIo, _ = flags.GetString(wellKnownIOFlag)
}
if flags.Changed(overprovisionedFlag) {
conf.Rpk.Overprovisioned, _ = flags.GetBool(overprovisionedFlag)
}
if flags.Changed(nodeIDFlag) {
conf.Redpanda.ID = new(int)
*conf.Redpanda.ID, _ = flags.GetInt(nodeIDFlag)
}
}
func parseConfigKvs(args []string) ([]string, []string) {
setFlag := fmt.Sprintf("--%s", setConfigFlag)
kvs := []string{}
i := 0
for i < len(args)-1 {
if args[i] == setFlag {
kvs = append(kvs, args[i+1])
args = append(args[:i], args[i+2:]...)
continue
}
i++
}
return kvs, args
}
func NewStartCommand(fs afero.Fs, launcher rp.Launcher) *cobra.Command {
prestartCfg := prestartConfig{}
var (
configFile string
nodeID int
seeds []string
kafkaAddr []string
proxyAddr []string
schemaRegAddr []string
rpcAddr string
advertisedKafka []string
advertisedProxy []string
advertisedRPC string
installDirFlag string
timeout time.Duration
wellKnownIo string
mode string
)
sFlags := seastarFlags{}
command := &cobra.Command{
Use: "start",
Short: "Start redpanda",
FParseErrWhitelist: cobra.FParseErrWhitelist{
// Allow unknown flags so that arbitrary flags can be passed
// through to redpanda/seastar without the need to pass '--'
// (POSIX standard)
UnknownFlags: true,
},
RunE: func(cmd *cobra.Command, args []string) error {
// --set flags have to be parsed by hand because pflag (the
// underlying flag-parsing lib used by cobra) uses a CSV parser
// for list flags, and since JSON often contains commas, it
// blows up when there's a JSON object.
configKvs, filteredArgs := parseConfigKvs(os.Args)
p := config.ParamsFromCommand(cmd)
cfg, err := p.Load(fs)
if err != nil {
return fmt.Errorf("unable to load config file: %s", err)
}
// We set fields in the raw file without writing rpk specific env
// or flag overrides. This command itself has all redpanda specific
// flags installed, and handles redpanda specific env vars itself.
// The magic `--set` flag is what modifies any redpanda.yaml fields.
// Thus, we can ignore any env / flags that would come from rpk
// configuration itself.
cfg = cfg.FileOrDefaults()
if cfg.Redpanda.DeveloperMode && len(mode) == 0 {
mode = "dev-container"
}
switch mode {
case "dev-container":
fmt.Fprintln(os.Stderr, "WARNING: This is a setup for development purposes only; in this mode your clusters may run unrealistically fast and data can be corrupted any time your computer shuts down uncleanly.")
setContainerModeFlags(cmd)
setContainerModeCfgFields(cfg)
case "help":
fmt.Println(helpMode)
return nil
case "":
// do nothing.
default:
return fmt.Errorf("unrecognized mode %q; use --mode help for more info", mode)
}
if len(configKvs) > 0 {
if err = setConfig(cfg, configKvs); err != nil {
return err
}
}
updateConfigWithFlags(cfg, cmd.Flags())
if len(seeds) == 0 {
// If --seeds wasn't passed, fall back to the
// env var.
envSeeds := os.Getenv("REDPANDA_SEEDS")
if envSeeds != "" {
seeds = strings.Split(
envSeeds,
",",
)
}
}
seedServers, err := parseSeeds(seeds)
if err != nil {
return err
}
if len(seedServers) != 0 {
cfg.Redpanda.SeedServers = seedServers
}
kafkaAddr = stringSliceOr(
kafkaAddr,
strings.Split(
os.Getenv("REDPANDA_KAFKA_ADDRESS"),
",",
),
)
kafkaAPI, err := parseNamedAuthNAddresses(
kafkaAddr,
config.DefaultKafkaPort,
)
if err != nil {
return err
}
if len(kafkaAPI) > 0 {
cfg.Redpanda.KafkaAPI = kafkaAPI
}
proxyAddr = stringSliceOr(
proxyAddr,
strings.Split(
os.Getenv("REDPANDA_PANDAPROXY_ADDRESS"),
",",
),
)
proxyAPI, err := parseNamedAuthNAddresses(
proxyAddr,
config.DefaultProxyPort,
)
if err != nil {
return err
}
if len(proxyAPI) > 0 {
if cfg.Pandaproxy == nil {
cfg.Pandaproxy = config.DevDefault().Pandaproxy
}
cfg.Pandaproxy.PandaproxyAPI = proxyAPI
}
schemaRegAddr = stringSliceOr(
schemaRegAddr,
strings.Split(
os.Getenv("REDPANDA_SCHEMA_REGISTRY_ADDRESS"),
",",
),
)
schemaRegAPI, err := parseNamedAuthNAddresses(
schemaRegAddr,
config.DefaultSchemaRegPort,
)
if err != nil {
return err
}
if len(schemaRegAPI) > 0 {
if cfg.SchemaRegistry == nil {
cfg.SchemaRegistry = config.DevDefault().SchemaRegistry
}
cfg.SchemaRegistry.SchemaRegistryAPI = schemaRegAPI
}
rpcAddr = stringOr(
rpcAddr,
os.Getenv("REDPANDA_RPC_ADDRESS"),
)
rpcServer, err := parseAddress(
rpcAddr,
config.DevDefault().Redpanda.RPCServer.Port,
)
if err != nil {
return err
}
if rpcServer != nil {
cfg.Redpanda.RPCServer = *rpcServer
}
advertisedKafka = stringSliceOr(
advertisedKafka,
strings.Split(
os.Getenv("REDPANDA_ADVERTISE_KAFKA_ADDRESS"),
",",
),
)
advKafkaAPI, err := parseNamedAddresses(
advertisedKafka,
config.DefaultKafkaPort,
)
if err != nil {
return err
}
if len(advKafkaAPI) > 0 {
cfg.Redpanda.AdvertisedKafkaAPI = advKafkaAPI
}
advertisedProxy = stringSliceOr(
advertisedProxy,
strings.Split(
os.Getenv("REDPANDA_ADVERTISE_PANDAPROXY_ADDRESS"),
",",
),
)
advProxyAPI, err := parseNamedAddresses(
advertisedProxy,
config.DefaultProxyPort,
)
if err != nil {
return err
}
if len(advProxyAPI) > 0 {
if cfg.Pandaproxy == nil {
cfg.Pandaproxy = config.DevDefault().Pandaproxy
}
cfg.Pandaproxy.AdvertisedPandaproxyAPI = advProxyAPI
}
advertisedRPC = stringOr(
advertisedRPC,
os.Getenv("REDPANDA_ADVERTISE_RPC_ADDRESS"),
)
advRPCApi, err := parseAddress(
advertisedRPC,
config.DevDefault().Redpanda.RPCServer.Port,
)
if err != nil {
return err
}
if advRPCApi != nil {
cfg.Redpanda.AdvertisedRPCAPI = advRPCApi
}
installDirectory, err := getOrFindInstallDir(fs, installDirFlag)
if err != nil {
return err
}
rpArgs, err := buildRedpandaFlags(
fs,
cfg,
filteredArgs,
sFlags,
cmd.Flags(),
!prestartCfg.checkEnabled,
)
if err != nil {
return err
}
if cfg.Redpanda.Directory == "" {
cfg.Redpanda.Directory = config.DevDefault().Redpanda.Directory
}
err = prestart(fs, rpArgs, cfg, prestartCfg, timeout)
if err != nil {
return err
}
err = cfg.Write(fs)
if err != nil {
return err
}
rpArgs.ExtraArgs = args
fmt.Println(common.FeedbackMsg)
fmt.Println("Starting redpanda...")
return launcher.Start(installDirectory, rpArgs)
},
}
command.Flags().StringVar(
&configFile,
configFlag,
"",
"Redpanda config file, if not set the file will be searched for"+
" in the default locations.",
)
command.Flags().IntVar(
&nodeID,
nodeIDFlag,
-1,
"The node ID. Must be an integer and must be unique within a cluster. If unset, Redpanda will assign one automatically")
command.Flags().MarkHidden(nodeIDFlag)
command.Flags().StringSliceVarP(
&seeds,
"seeds",
"s",
[]string{},
"A comma-separated list of seed node addresses"+
" (<host>[:<port>]) to connect to",
)
command.Flags().StringSliceVar(
&kafkaAddr,
"kafka-addr",
[]string{},
"A comma-separated list of Kafka listener addresses to bind to (<name>://<host>:<port>)",
)
command.Flags().StringSliceVar(
&proxyAddr,
"pandaproxy-addr",
[]string{},
"A comma-separated list of Pandaproxy listener addresses to bind to (<name>://<host>:<port>)",
)
command.Flags().StringSliceVar(
&schemaRegAddr,
"schema-registry-addr",
[]string{},
"A comma-separated list of Schema Registry listener addresses to bind to (<name>://<host>:<port>)",
)
command.Flags().StringVar(
&rpcAddr,
"rpc-addr",
"",
"The RPC address to bind to (<host>:<port>)",
)
command.Flags().StringSliceVar(
&advertisedKafka,
"advertise-kafka-addr",
[]string{},
"A comma-separated list of Kafka addresses to advertise (<name>://<host>:<port>)",
)
command.Flags().StringSliceVar(
&advertisedProxy,
"advertise-pandaproxy-addr",
[]string{},
"A comma-separated list of Pandaproxy addresses to advertise (<name>://<host>:<port>)",
)
command.Flags().StringVar(
&advertisedRPC,
"advertise-rpc-addr",
"",
"The advertised RPC address (<host>:<port>)",
)
command.Flags().StringVar(&sFlags.memory,
memoryFlag, "", "Amount of memory for redpanda to use, "+
"if not specified redpanda will use all available memory")
command.Flags().BoolVar(&sFlags.lockMemory,
lockMemoryFlag, false, "If set, will prevent redpanda from swapping")
command.Flags().StringVar(&sFlags.cpuSet, cpuSetFlag, "",
"Set of CPUs for redpanda to use in cpuset(7) format, "+
"if not specified redpanda will use all available CPUs")
command.Flags().StringVar(&installDirFlag,
"install-dir", "",
"Directory where redpanda has been installed")
command.Flags().BoolVar(&prestartCfg.tuneEnabled, "tune", false,
"When present will enable tuning before starting redpanda")
command.Flags().BoolVar(&prestartCfg.checkEnabled, checkFlag, true,
"When set to false will disable system checking before starting redpanda")
command.Flags().IntVar(&sFlags.smp, smpFlag, 0, "Restrict redpanda to"+
" the given number of CPUs. This option does not mandate a"+
" specific placement of CPUs. See --cpuset if you need to do so.")
command.Flags().StringVar(&sFlags.reserveMemory, reserveMemoryFlag, "",
"Memory reserved for the OS (if --memory isn't specified)")
command.Flags().StringVar(&sFlags.hugepages, hugepagesFlag, "",
"Path to accessible hugetlbfs mount (typically /dev/hugepages/something)")
command.Flags().BoolVar(&sFlags.threadAffinity, threadAffinityFlag, true,
"Pin threads to their cpus (disable for overprovisioning)")
command.Flags().IntVar(&sFlags.numIoQueues, numIoQueuesFlag, 0,
"Number of IO queues. Each IO unit will be responsible for a fraction "+
"of the IO requests. Defaults to the number of threads")
command.Flags().IntVar(&sFlags.maxIoRequests, maxIoRequestsFlag, 0,
"Maximum amount of concurrent requests to be sent to the disk. "+
"Defaults to 128 times the number of IO queues")
command.Flags().StringVar(&sFlags.ioPropertiesFile, ioPropertiesFileFlag, "",
"Path to a YAML file describing the characteristics of the I/O Subsystem")
command.Flags().StringVar(&sFlags.ioProperties, ioPropertiesFlag, "",
"A YAML string describing the characteristics of the I/O Subsystem")
command.Flags().StringVar(
&wellKnownIo,
wellKnownIOFlag,
"",
"The cloud vendor and VM type, in the format <vendor>:<vm type>:<storage type>")
command.Flags().BoolVar(&sFlags.mbind, mbindFlag, true, "Enable mbind")
command.Flags().BoolVar(
&sFlags.overprovisioned,
overprovisionedFlag,
false,
"Enable overprovisioning",
)
command.Flags().BoolVar(&sFlags.unsafeBypassFsync, unsafeBypassFsyncFlag, false, "Enable unsafe-bypass-fsync")
command.Flags().StringVar(
&mode,
modeFlag,
"",
"Mode sets well-known configuration properties for development or test environments; use --mode help for more info",
)
command.Flags().DurationVar(
&timeout,
"timeout",
10000*time.Millisecond,
"The maximum time to wait for the checks and tune processes to complete. "+
"The value passed is a sequence of decimal numbers, each with optional "+
"fraction and a unit suffix, such as '300ms', '1.5s' or '2h45m'. "+
"Valid time units are 'ns', 'us' (or 'µs'), 'ms', 's', 'm', 'h'",
)
for flag := range flagsMap(sFlags) {
command.Flag(flag).Hidden = true
}
return command
}
func flagsMap(sFlags seastarFlags) map[string]interface{} {
return map[string]interface{}{
memoryFlag: sFlags.memory,
lockMemoryFlag: sFlags.lockMemory,
reserveMemoryFlag: sFlags.reserveMemory,
ioPropertiesFileFlag: sFlags.ioPropertiesFile,
ioPropertiesFlag: sFlags.ioProperties,
cpuSetFlag: sFlags.cpuSet,
smpFlag: sFlags.smp,
hugepagesFlag: sFlags.hugepages,
threadAffinityFlag: sFlags.threadAffinity,
numIoQueuesFlag: sFlags.numIoQueues,
maxIoRequestsFlag: sFlags.maxIoRequests,
mbindFlag: sFlags.mbind,
overprovisionedFlag: sFlags.overprovisioned,
unsafeBypassFsyncFlag: sFlags.unsafeBypassFsync,
}
}
func prestart(
fs afero.Fs,
args *rp.RedpandaArgs,
conf *config.Config,
prestartCfg prestartConfig,
timeout time.Duration,
) error {
if prestartCfg.checkEnabled {
err := check(fs, conf, timeout, checkFailedActions(args))
if err != nil {
return err
}
fmt.Println("System check - PASSED")
}
if prestartCfg.tuneEnabled {
cpuset := fmt.Sprint(args.SeastarFlags[cpuSetFlag])
err := tuneAll(fs, cpuset, conf, timeout)
if err != nil {
return err
}
fmt.Println("System tune - PASSED")
}
return nil
}
func buildRedpandaFlags(
fs afero.Fs,
conf *config.Config,
args []string,
sFlags seastarFlags,
flags *pflag.FlagSet,
skipChecks bool,
) (*rp.RedpandaArgs, error) {
wellKnownIOSet := conf.Rpk.WellKnownIo != ""
ioPropsSet := flags.Changed(ioPropertiesFileFlag) || flags.Changed(ioPropertiesFlag)
if wellKnownIOSet && ioPropsSet {
return nil, errors.New(
"--well-known-io or (rpk.well_known_io) and" +
" --io-properties (or --io-properties-file)" +
" can't be set at the same time",
)
}
if !ioPropsSet {
// If --io-properties-file and --io-properties weren't set, try
// finding an IO props file in the default location.
sFlags.ioPropertiesFile = rp.GetIOConfigPath(
filepath.Dir(conf.FileLocation()),
)
if exists, _ := afero.Exists(fs, sFlags.ioPropertiesFile); !exists {
sFlags.ioPropertiesFile = ""
}
// Otherwise, try to deduce the IO props.
if sFlags.ioPropertiesFile == "" {
ioProps, err := resolveWellKnownIo(conf, skipChecks)
if err != nil {
log.Warn(err)
} else if ioProps != nil {
yaml, err := iotune.ToYaml(*ioProps)
if err != nil {
return nil, err
}
sFlags.ioProperties = fmt.Sprintf("'%s'", yaml)
}
}
}
flagsMap := flagsMap(sFlags)
for flag := range flagsMap {
if !flags.Changed(flag) {
delete(flagsMap, flag)
}
}
flagsMap = flagsFromConf(conf, flagsMap, flags)
finalFlags := mergeMaps(
parseFlags(conf.Rpk.AdditionalStartFlags),
extraFlags(flags, args),
)
for n, v := range flagsMap {
if _, alreadyPresent := finalFlags[n]; alreadyPresent {
return nil, fmt.Errorf(
"Configuration conflict. Flag '--%s'"+
" is also present in"+
" 'rpk.additional_start_flags' in"+
" configuration file '%s'. Please"+
" remove it and pass '--%s' directly"+
" to `rpk start`.",
n,
conf.FileLocation(),
n,
)
}
finalFlags[n] = fmt.Sprint(v)
}
return &rp.RedpandaArgs{
ConfigFilePath: conf.FileLocation(),
SeastarFlags: finalFlags,
}, nil
}
func flagsFromConf(
conf *config.Config, flagsMap map[string]interface{}, flags *pflag.FlagSet,
) map[string]interface{} {
flagsMap[overprovisionedFlag] = conf.Rpk.Overprovisioned
flagsMap[lockMemoryFlag] = conf.Rpk.EnableMemoryLocking
// Setting SMP to 0 doesn't make sense.
if !flags.Changed(smpFlag) && conf.Rpk.SMP != nil && *conf.Rpk.SMP != 0 {
flagsMap[smpFlag] = *conf.Rpk.SMP
}
return flagsMap
}
func mergeFlags(
current map[string]interface{}, overrides []string,
) map[string]interface{} {
overridesMap := map[string]string{}
for _, o := range overrides {
pattern := regexp.MustCompile(`[\s=]+`)
parts := pattern.Split(o, 2)
flagName := strings.ReplaceAll(parts[0], "--", "")
if len(parts) == 2 {
overridesMap[flagName] = parts[1]
} else {
overridesMap[flagName] = ""
}
}
for k, v := range overridesMap {
current[k] = v
}
return current
}
func setConfig(cfg *config.Config, configKvs []string) error {
for _, rawKv := range configKvs {
parts := strings.SplitN(rawKv, "=", 2)
if len(parts) < 2 {
return fmt.Errorf(
"key-value pair '%s' is not formatted as expected (k=v)",
rawKv,
)
}
err := cfg.Set(parts[0], parts[1], "")
if err != nil {
return err
}
}
return nil
}
func resolveWellKnownIo(
conf *config.Config, skipChecks bool,
) (*iotune.IoProperties, error) {
var ioProps *iotune.IoProperties
if conf.Rpk.WellKnownIo != "" {
wellKnownIoTokens := strings.Split(conf.Rpk.WellKnownIo, ":")
if len(wellKnownIoTokens) != 3 {
err := errors.New(
"--well-known-io should have the format '<vendor>:<vm type>:<storage type>'",
)
return nil, err
}
ioProps, err := iotune.DataFor(
conf.Redpanda.Directory,
wellKnownIoTokens[0],
wellKnownIoTokens[1],
wellKnownIoTokens[2],
)
if err != nil {
// Log the error to let the user know that the data wasn't found
return nil, err
}
return ioProps, nil
}
// Skip detecting the cloud vendor if skipChecks is true
if skipChecks {
return nil, nil
}
log.Info("Detecting the current cloud vendor and VM")
vendor, err := cloud.AvailableVendor()
if err != nil {
return nil, errors.New("Could not detect the current cloud vendor")
}
ioProps, err = iotune.DataForVendor(conf.Redpanda.Directory, vendor)
if err != nil {
// Log the error to let the user know that the data wasn't found
return nil, err
}
return ioProps, nil
}
func tuneAll(
fs afero.Fs, cpuSet string, conf *config.Config, timeout time.Duration,
) error {
params := &factory.TunerParams{}
tunerFactory := factory.NewDirectExecutorTunersFactory(fs, *conf, timeout)
hw := hwloc.NewHwLocCmd(vos.NewProc(), timeout)
if cpuSet == "" {
cpuMask, err := hw.All()
if err != nil {
return err
}
params.CPUMask = cpuMask
} else {
cpuMask, err := hwloc.TranslateToHwLocCPUSet(cpuSet)
if err != nil {
return err
}
params.CPUMask = cpuMask
}
err := factory.FillTunerParamsWithValuesFromConfig(params, conf)
if err != nil {
return err
}
availableTuners := factory.AvailableTuners()
for _, tunerName := range availableTuners {
enabled := factory.IsTunerEnabled(tunerName, conf.Rpk)
tuner := tunerFactory.CreateTuner(tunerName, params)
supported, reason := tuner.CheckIfSupported()
if !enabled {
fmt.Printf("Skipping disabled tuner %s\n", tunerName)
continue
}
if !supported {
log.Debugf("Tuner '%s' is not supported - %s", tunerName, reason)
continue
}
log.Debugf("Tuner parameters %+v", params)
result := tuner.Tune()
if result.IsFailed() {
return result.Error()
}
}
return nil
}
type checkFailedAction func(*tuners.CheckResult)
func checkFailedActions(
args *rp.RedpandaArgs,
) map[tuners.CheckerID]checkFailedAction {
return map[tuners.CheckerID]checkFailedAction{
tuners.SwapChecker: func(*tuners.CheckResult) {
// Do not set --lock-memory flag when swap is disabled
args.SeastarFlags[lockMemoryFlag] = "false"
},
}
}
func check(
fs afero.Fs,
conf *config.Config,
timeout time.Duration,
checkFailedActions map[tuners.CheckerID]checkFailedAction,
) error {
results, err := tuners.Check(fs, conf, timeout)
if err != nil {
return err
}
for _, result := range results {
if !result.IsOk {
if action, exists := checkFailedActions[result.CheckerID]; exists {
action(&result)
}
msg := fmt.Sprintf("System check '%s' failed. Required: %v, Current %v",
result.Desc, result.Required, result.Current)
if result.Severity == tuners.Fatal {
return fmt.Errorf(msg)
}
fmt.Println(msg)
}
}
return nil
}
func parseFlags(flags []string) map[string]string {
parsed := map[string]string{}
for i := 0; i < len(flags); i++ {
f := flags[i]
isFlag := strings.HasPrefix(f, "-")
trimmed := strings.Trim(f, " -")
// Filter out elements that aren't flags or are empty.
if !isFlag || trimmed == "" {
continue
}
// Check if it's in name=value format
// Split only into 2 tokens, since some flags can have multiple '='
// in them, like --logger-log-level=archival=debug:cloud_storage=debug
parts := strings.SplitN(trimmed, "=", 2)
if len(parts) >= 2 {
name := strings.Trim(parts[0], " ")
value := strings.Trim(parts[1], " ")
parsed[name] = value
continue
}
// Otherwise, it can be a boolean flag (i.e. -v) or in
// name<space>value format
if i == len(flags)-1 {
// We've reached the last element, so it's a single flag
parsed[trimmed] = ""
continue
}
// Check if the next element starts with a hyphen
// If it does, it's another flag, and the current element is a
// boolean flag
next := flags[i+1]
if strings.HasPrefix(next, "-") {
parsed[trimmed] = ""
continue
}
// Otherwise, the current element is the name of the flag and
// the next one is its value
parsed[trimmed] = next
i += 1
}
return parsed
}
func parseSeeds(seeds []string) ([]config.SeedServer, error) {
seedServers := []config.SeedServer{}
defaultPort := config.DevDefault().Redpanda.RPCServer.Port
for _, s := range seeds {
addr, err := parseAddress(s, defaultPort)
if err != nil {
return seedServers, fmt.Errorf(
"Couldn't parse seed '%s': %v",
s,
err,
)
}
if addr == nil {
return seedServers, fmt.Errorf(
"Couldn't parse seed '%s': empty address",
s,
)
}
seedServers = append(
seedServers,
config.SeedServer{Host: *addr},
)
}
return seedServers, nil
}
func parseAddress(addr string, defaultPort int) (*config.SocketAddress, error) {
named, err := parseNamedAddress(addr, defaultPort)
if err != nil {
return nil, err
}
if named == nil {
return nil, nil
}
return &config.SocketAddress{
Address: named.Address,
Port: named.Port,
}, nil
}
func parseNamedAddresses(
addrs []string, defaultPort int,
) ([]config.NamedSocketAddress, error) {
as := make([]config.NamedSocketAddress, 0, len(addrs))
for _, addr := range addrs {
a, err := parseNamedAddress(addr, defaultPort)
if err != nil {
return nil, err
}
if a != nil {
as = append(as, *a)
}
}
return as, nil
}
func parseNamedAddress(
addr string, defaultPort int,
) (*config.NamedSocketAddress, error) {
if addr == "" {
return nil, nil
}
scheme, hostport, err := net.ParseHostMaybeScheme(addr)
if err != nil {
return nil, err
}
host, port := net.SplitHostPortDefault(hostport, defaultPort)
return &config.NamedSocketAddress{
Address: host,
Port: port,
Name: scheme,
}, nil
}
func parseNamedAuthNAddresses(
addrs []string, defaultPort int,
) ([]config.NamedAuthNSocketAddress, error) {
as := make([]config.NamedAuthNSocketAddress, 0, len(addrs))
for _, addr := range addrs {
a, err := parseNamedAuthNAddress(addr, defaultPort)
if err != nil {
return nil, err
}
if a != nil {
as = append(as, *a)
}
}
return as, nil
}
func parseNamedAuthNAddress(
addrAuthn string, defaultPort int,
) (*config.NamedAuthNSocketAddress, error) {
if addrAuthn == "" {
return nil, nil
}
addr, authn, err := splitAddressAuthN(addrAuthn)
if err != nil {
return nil, err
}
scheme, hostport, err := net.ParseHostMaybeScheme(addr)
if err != nil {
return nil, err
}
host, port := net.SplitHostPortDefault(hostport, defaultPort)
return &config.NamedAuthNSocketAddress{
Address: host,
Port: port,
Name: scheme,
AuthN: authn,
}, nil
}
func splitAddressAuthN(str string) (addr string, authn *string, err error) {
bits := strings.Split(str, "|")
if len(bits) > 2 {
err = fmt.Errorf(`invalid format for listener, at most one "|" can be present: %q`, str)
return
}
addr = bits[0]
if len(bits) == 2 {
authn = &bits[1]
}
return
}
func stringOr(a, b string) string {
if a != "" {
return a
}
return b
}
func stringSliceOr(a, b []string) []string {
if len(a) != 0 {
return a
}
return b
}
// Returns the set of unknown flags passed.
func extraFlags(flags *pflag.FlagSet, args []string) map[string]string {
allFlagsMap := parseFlags(args)
extra := map[string]string{}
for k, v := range allFlagsMap {
var f *pflag.Flag
if len(k) == 1 {
f = flags.ShorthandLookup(k)
} else {
f = flags.Lookup(k)
}
// It isn't a "known" flag, so it must be an extra one.