/
auto.go
1272 lines (1066 loc) · 36.2 KB
/
auto.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
//
// (C) Copyright 2020-2024 Intel Corporation.
//
// SPDX-License-Identifier: BSD-2-Clause-Patent
//
package control
import (
"context"
"encoding/json"
"fmt"
"math"
"math/bits"
"sort"
"strconv"
"strings"
"github.com/pkg/errors"
"github.com/daos-stack/daos/src/control/common"
"github.com/daos-stack/daos/src/control/lib/hardware"
"github.com/daos-stack/daos/src/control/logging"
"github.com/daos-stack/daos/src/control/server/config"
"github.com/daos-stack/daos/src/control/server/engine"
"github.com/daos-stack/daos/src/control/server/storage"
)
const (
scmMountPrefix = "/mnt/daos"
scmBdevDir = "/dev"
defaultFiPort = 31416
defaultFiPortInterval = 1000
defaultTargetCount = 16
defaultEngineLogFile = "/tmp/daos_engine"
defaultControlLogFile = "/tmp/daos_server.log"
minNrSSDs = 1
minDMABuffer = 1024
numaCoreUsage = 0.8 // fraction of numa cores to use for targets
coresRsvdPerEngine = 2 // number of cores to reserve for system usage per engine
errUnsupNetDevClass = "unsupported net dev class in request: %s"
errInsufNrIfaces = "insufficient matching fabric interfaces, want %d got %d %v"
errInsufNrPMemGroups = "insufficient number of pmem device numa groups %v, want %d got %d"
errInsufNrSSDGroups = "insufficient number of ssd device numa groups %v, want %d got %d"
errInsufNrSSDs = "insufficient number of ssds for numa %d, want %d got %d"
errInvalNrCores = "invalid number of cores-per-numa, want at least 2 got %d"
errInsufNrProvGroups = "none of the provider-ifaces sets match the numa node sets " +
"that meet storage requirements"
)
var errNoNuma = errors.New("zero numa nodes reported on hosts")
type (
// ConGenerateReq contains the inputs for the request.
ConfGenerateReq struct {
// Number of engines to include in generated config.
NrEngines int `json:"NrEngines"`
// Force use of a specific network device class for fabric comms.
NetClass hardware.NetDevClass `json:"-"`
// Force use of a specific fabric provider.
NetProvider string `json:"NetProvider"`
// Generate a config without NVMe.
SCMOnly bool `json:"SCMOnly"`
// Hosts to run the management service.
AccessPoints []string `json:"-"`
// Ports to use for fabric comms (one needed per engine).
FabricPorts []int `json:"-"`
// Generate config with a tmpfs RAM-disk SCM.
UseTmpfsSCM bool `json:"UseTmpfsSCM"`
// Location to persist control-plane metadata, will generate MD-on-SSD config.
ExtMetadataPath string `json:"ExtMetadataPath"`
Log logging.Logger `json:"-"`
}
// ConfGenerateResp contains the generated server config.
ConfGenerateResp struct {
config.Server
}
// ConfGenerateRemoteReq adds connectivity related fields to base request.
ConfGenerateRemoteReq struct {
ConfGenerateReq
HostList []string
Client UnaryInvoker
}
// ConfGenerateRemoteResp wraps the ConfGenerateResp.
ConfGenerateRemoteResp struct {
ConfGenerateResp
}
// ConfGenerateError implements the error interface and contains a set of host-specific
// errors encountered while attempting to generate a configuration.
ConfGenerateError struct {
HostErrorsResp
}
)
// UnmarshalJSON unpacks JSON message into ConfGenerateReq struct.
func (cgr *ConfGenerateReq) UnmarshalJSON(data []byte) error {
type Alias ConfGenerateReq
aux := &struct {
AccessPoints string
FabricPorts string
NetClass string
*Alias
}{
Alias: (*Alias)(cgr),
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
cgr.AccessPoints = strings.Split(aux.AccessPoints, ",")
fabricPorts := strings.Split(aux.FabricPorts, ",")
for _, s := range fabricPorts {
if s == "" {
continue
}
n, err := strconv.Atoi(s)
if err != nil {
return errors.Wrap(err, "fabric ports")
}
cgr.FabricPorts = append(cgr.FabricPorts, n)
}
switch aux.NetClass {
case "ethernet":
cgr.NetClass = hardware.Ether
case "infiniband":
cgr.NetClass = hardware.Infiniband
default:
return errors.Errorf("unrecognized net-class value %s", aux.NetClass)
}
return nil
}
func (cge *ConfGenerateError) Error() string {
return cge.Errors().Error()
}
// GetHostErrors returns the wrapped HostErrorsMap.
func (cge *ConfGenerateError) GetHostErrors() HostErrorsMap {
return cge.HostErrors
}
// IsConfGenerateError returns true if the provided error is a *ConfGenerateError.
func IsConfGenerateError(err error) bool {
_, ok := errors.Cause(err).(*ConfGenerateError)
return ok
}
// DefaultEngineCfg is a standard baseline for the config generate to start from.
func DefaultEngineCfg(idx int) *engine.Config {
return engine.NewConfig().
WithTargetCount(defaultTargetCount).
WithLogFile(fmt.Sprintf("%s.%d.log", defaultEngineLogFile, idx))
}
// ConfGenerate derives an optimal server config file from details of network, storage and CPU
// hardware by evaluating affinity matches for NUMA node combinations.
func ConfGenerate(req ConfGenerateReq, newEngineCfg newEngineCfgFn, hf *HostFabric, hs *HostStorage) (*ConfGenerateResp, error) {
// process host fabric scan results to retrieve network details
nd, err := getNetworkDetails(req, hf)
if err != nil {
return nil, err
}
// process host storage scan results to retrieve storage details
sd, err := getStorageDetails(req, nd.NumaCount, hs)
if err != nil {
return nil, err
}
// evaluate device affinities to enforce locality constraints
nodeSet, err := filterDevicesByAffinity(req, nd, sd)
if err != nil {
return nil, err
}
// populate engine configs with storage and network devices
ecs, err := genEngineConfigs(req, newEngineCfg, nodeSet, nd, sd)
if err != nil {
return nil, err
}
// calculate service and helper thread counts
tc, err := getThreadCounts(req.Log, nodeSet, nd.NumaCoreCount, sd.NumaSSDs)
if err != nil {
return nil, err
}
// populate server config using engine configs
sc, err := genServerConfig(req, ecs, sd.MemInfo, tc)
if err != nil {
return nil, err
}
resp := ConfGenerateResp{Server: *sc}
return &resp, nil
}
// ConfGenerateRemote calls ConfGenerate after validating a homogeneous hardware setup across
// remote hosts. Returns API response or error.
func ConfGenerateRemote(ctx context.Context, req ConfGenerateRemoteReq) (*ConfGenerateRemoteResp, error) {
req.Log.Debugf("ConfGenerateRemote called with request %+v", req)
if len(req.HostList) == 0 {
return nil, errors.New("no hosts specified")
}
if len(req.AccessPoints) == 0 {
return nil, errors.New("no access points specified")
}
ns, err := getNetworkSet(ctx, req)
if err != nil {
return nil, err
}
ss, err := getStorageSet(ctx, req)
if err != nil {
return nil, err
}
resp, err := ConfGenerate(req.ConfGenerateReq, DefaultEngineCfg, ns.HostFabric,
ss.HostStorage)
if err != nil {
return nil, err
}
remResp := ConfGenerateRemoteResp{ConfGenerateResp: *resp}
return &remResp, nil
}
// getNetworkSet retrieves the result of network scan over host list and verifies that there is
// only a single network set in response which indicates that network hardware setup is homogeneous
// across all hosts. Return host errors, network scan results for the host set or error.
func getNetworkSet(ctx context.Context, req ConfGenerateRemoteReq) (*HostFabricSet, error) {
req.Log.Debugf("fetching host fabric info on hosts %v", req.HostList)
scanReq := &NetworkScanReq{
Provider: "all", // explicitly request all providers
}
scanReq.SetHostList(req.HostList)
scanResp, err := NetworkScan(ctx, req.Client, scanReq)
if err != nil {
return nil, err
}
if len(scanResp.GetHostErrors()) > 0 {
return nil, &ConfGenerateError{HostErrorsResp: scanResp.HostErrorsResp}
}
// verify homogeneous network
switch len(scanResp.HostFabrics) {
case 0:
return nil, errors.New("no host responses")
case 1:
// success
default:
// more than one means non-homogeneous hardware
req.Log.Info("Heterogeneous network hardware configurations detected, " +
"cannot proceed. The following sets of hosts have different " +
"network hardware:")
for _, hns := range scanResp.HostFabrics {
req.Log.Info(hns.HostSet.String())
}
return nil, errors.New("network hardware not consistent across hosts")
}
networkSet := scanResp.HostFabrics[scanResp.HostFabrics.Keys()[0]]
req.Log.Debugf("Network hardware is consistent for hosts %s:\n\t%v",
networkSet.HostSet, networkSet.HostFabric.Interfaces)
return networkSet, nil
}
// Return ordered list of keys from int key map.
func intMapKeys(i interface{}) (keys []int) {
m, ok := i.(map[int]interface{})
if !ok {
panic("map doesn't have int key type")
}
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)
return keys
}
// numaNetIfaceMap is an alias for a map of NUMA node ID to optimal fabric network interface.
type numaNetIfaceMap map[int]*HostFabricInterface
func (nnim numaNetIfaceMap) keys() (keys []int) {
for k := range nnim {
keys = append(keys, k)
}
sort.Ints(keys)
return
}
// providerIfaceMap is an alias for a provider-to-numaNetIfaceMap map.
type providerIfaceMap map[string]numaNetIfaceMap
// add network device to bucket corresponding to provider and NUMA binding. Do not add if there is
// an existing entry as the interfaces are processed in descending order of performance (best
// first).
func (pis providerIfaceMap) add(iface *HostFabricInterface) {
nn := int(iface.NumaNode)
if _, exists := pis[iface.Provider]; !exists {
pis[iface.Provider] = make(numaNetIfaceMap)
}
if _, exists := pis[iface.Provider][nn]; exists {
return // already have interface for this NUMA
}
pis[iface.Provider][nn] = iface
}
// parseInterfaces processes network devices in scan result, adding to a provider bucket when the
// network device class matches that requested (ETHER or INFINIBAND.
// Returns when all matching devices have been added to the relevant provider bucket.
func (pim providerIfaceMap) fromFabric(reqClass hardware.NetDevClass, prov string, ifaces []*HostFabricInterface) error {
if pim == nil {
return errors.Errorf("%T receiver is nil", pim)
}
// sort network interfaces by priority to get best available
sort.Slice(ifaces, func(i, j int) bool {
return ifaces[i].Priority < ifaces[j].Priority
})
for _, iface := range ifaces {
if iface.NetDevClass == reqClass && (prov == "" || iface.Provider == prov) {
pim.add(iface)
}
}
return nil
}
type networkDetails struct {
NumaCount int
NumaCoreCount int
ProviderIfaces providerIfaceMap
NumaIfaces numaNetIfaceMap
}
// getNetworkDetails retrieves fabric network interfaces that can be used in server config file.
// Return interfaces mapped first by NUMA then provider and per-NUMA core count.
func getNetworkDetails(req ConfGenerateReq, hf *HostFabric) (*networkDetails, error) {
if hf == nil {
return nil, errors.New("nil HostFabric")
}
switch req.NetClass {
case hardware.Ether, hardware.Infiniband:
default:
return nil, errors.Errorf(errUnsupNetDevClass, req.NetClass.String())
}
provIfaces := make(providerIfaceMap)
if err := provIfaces.fromFabric(req.NetClass, req.NetProvider, hf.Interfaces); err != nil {
return nil, err
}
req.Log.Debugf("numa nodes: %d, numa core count: %d, available interfaces %v", hf.NumaCount,
hf.CoresPerNuma, provIfaces)
return &networkDetails{
NumaCount: int(hf.NumaCount),
NumaCoreCount: int(hf.CoresPerNuma),
ProviderIfaces: provIfaces,
}, nil
}
// getStorageSet retrieves the result of storage scan over host list and verifies that there is
// only a single storage set in response which indicates that storage hardware setup is homogeneous
// across all hosts. Filter NVMe storage scan so only NUMA affinity and PCI address is taking into
// account by supplying NvmeBasic flag in scan request. This enables configuration to work with
// different combinations of SSD models. Return host errors, storage scan results for the host set
// or error.
func getStorageSet(ctx context.Context, req ConfGenerateRemoteReq) (*HostStorageSet, error) {
req.Log.Debugf("fetching host storage info on hosts %v", req.HostList)
scanReq := &StorageScanReq{NvmeBasic: true}
scanReq.SetHostList(req.HostList)
scanResp, err := StorageScan(ctx, req.Client, scanReq)
if err != nil {
return nil, err
}
if len(scanResp.GetHostErrors()) > 0 {
return nil, &ConfGenerateError{HostErrorsResp: scanResp.HostErrorsResp}
}
// verify homogeneous storage
switch len(scanResp.HostStorage) {
case 0:
return nil, errors.New("no host responses")
case 1:
// success
default:
// more than one means non-homogeneous hardware
req.Log.Info("Heterogeneous storage hardware configurations detected, " +
"cannot proceed. The following sets of hosts have different " +
"storage hardware:")
for _, hss := range scanResp.HostStorage {
req.Log.Info(hss.HostSet.String())
}
return nil, errors.New("storage hardware not consistent across hosts")
}
storageSet := scanResp.HostStorage[scanResp.HostStorage.Keys()[0]]
hostStorage := storageSet.HostStorage
req.Log.Debugf("Storage hardware is consistent for hosts %s:\n\t%s\n\t%s\n\t%s",
storageSet.HostSet.String(), hostStorage.ScmNamespaces.Summary(),
hostStorage.NvmeDevices.Summary(), hostStorage.MemInfo.Summary())
return storageSet, nil
}
// numaSCMsMap is an alias for a map of NUMA node ID to slice of string sorted PMem block device
// paths.
type numaSCMsMap map[int]sort.StringSlice
func (npm numaSCMsMap) keys() (keys []int) {
for k := range npm {
keys = append(keys, k)
}
sort.Ints(keys)
return
}
// mapPMems maps NUMA node ID to pmem block device paths, sort paths to attempt selection of
// desired devices if named appropriately in the case that multiple devices exist for a given NUMA
// node.
func (npm numaSCMsMap) fromSCM(nss storage.ScmNamespaces) error {
if npm == nil {
return errors.Errorf("%T receiver is nil", npm)
}
for _, ns := range nss {
nn := int(ns.NumaNode)
npm[nn] = append(npm[nn], fmt.Sprintf("%s/%s", scmBdevDir, ns.BlockDevice))
}
for _, pms := range npm {
pms.Sort()
}
return nil
}
// numSSDsMap is an alias for a map of NUMA node ID to slice of NVMe SSD PCI addresses.
type numaSSDsMap map[int]*hardware.PCIAddressSet
func (nsm numaSSDsMap) keys() (keys []int) {
for k := range nsm {
keys = append(keys, k)
}
sort.Ints(keys)
return
}
// mapSSDs maps NUMA node ID to NVMe SSD PCI address set.
func (nsm numaSSDsMap) fromNVMe(ssds storage.NvmeControllers) error {
if nsm == nil {
return errors.Errorf("%T receiver is nil", nsm)
}
for _, ssd := range ssds {
nn := int(ssd.SocketID)
if _, exists := nsm[nn]; exists {
if err := nsm[nn].AddStrings(ssd.PciAddr); err != nil {
return err
}
continue
}
newAddrSet, err := hardware.NewPCIAddressSetFromString(ssd.PciAddr)
if err != nil {
return err
}
nsm[nn] = newAddrSet
}
return nil
}
type storageDetails struct {
NumaSCMs numaSCMsMap
NumaSSDs numaSSDsMap
MemInfo *common.MemInfo
scmCls storage.Class
}
// getStorageDetails retrieves mappings of NUMA node to PMem and NVMe SSD devices. Returns storage
// details struct or host error response and outer error.
func getStorageDetails(req ConfGenerateReq, numaCount int, hs *HostStorage) (*storageDetails, error) {
if hs == nil {
return nil, errors.New("nil HostStorage")
}
if hs.MemInfo == nil {
return nil, errors.New("nil HostStorage.MemInfo")
}
sd := storageDetails{
NumaSCMs: make(numaSCMsMap),
NumaSSDs: make(numaSSDsMap),
MemInfo: &common.MemInfo{
HugepageSizeKiB: hs.MemInfo.HugepageSizeKiB,
MemTotalKiB: hs.MemInfo.MemTotalKiB,
},
scmCls: storage.ClassDcpm,
}
if sd.MemInfo.HugepageSizeKiB == 0 {
return nil, errors.New("requires nonzero HugepageSizeKiB")
}
if err := sd.NumaSSDs.fromNVMe(hs.NvmeDevices); err != nil {
return nil, errors.Wrap(err, "mapping ssd addresses to numa node")
}
// if tmpfs scm mode is requested, init scm map to init entry for each numa node
if req.UseTmpfsSCM {
if numaCount <= 0 {
return nil, errors.New("requires nonzero numaCount")
}
if sd.MemInfo.MemTotalKiB == 0 {
return nil, errors.New("requires nonzero MemTotalKiB")
}
req.Log.Debugf("using tmpfs for scm, one for each numa node [0-%d]", numaCount-1)
for i := 0; i < numaCount; i++ {
sd.NumaSCMs[i] = sort.StringSlice{""}
}
sd.scmCls = storage.ClassRam
return &sd, nil
}
if err := sd.NumaSCMs.fromSCM(hs.ScmNamespaces); err != nil {
return nil, errors.Wrap(err, "mapping scm block device names to numa node")
}
return &sd, nil
}
// Filters PMem and SSD groups to include only the NUMA IDs that have sufficient number of devices
// with appropriate affinity. Returns error if not enough satisfied NUMA ID groupings for required
// engine count.
func checkNvmeAffinity(req ConfGenerateReq, sd *storageDetails) error {
req.Log.Debugf("numa to pmem mappings: %v", sd.NumaSCMs)
req.Log.Debugf("numa to nvme mappings: %v", sd.NumaSSDs)
if len(sd.NumaSCMs) < req.NrEngines {
return errors.Errorf(errInsufNrPMemGroups, sd.NumaSCMs, req.NrEngines,
len(sd.NumaSCMs))
}
if req.SCMOnly {
req.Log.Debug("nvme disabled, skip validation")
// set empty ssd lists for relevant numa ids
sd.NumaSSDs = make(numaSSDsMap)
for numaID := range sd.NumaSCMs {
sd.NumaSSDs[numaID] = hardware.MustNewPCIAddressSet()
}
return nil
}
var pass, fail []int
for numaID := range sd.NumaSCMs {
if sd.NumaSSDs[numaID].Len() >= minNrSSDs {
pass = append(pass, numaID)
} else {
fail = append(fail, numaID)
}
}
switch {
case len(pass) > 0 && len(fail) > 0:
req.Log.Debugf("ssd requirements met for numa ids %v but not for %v", pass, fail)
case len(pass) > 0:
req.Log.Debugf("ssd requirements met for numa ids %v", pass)
default:
req.Log.Debugf("ssd requirements not met for numa ids %v", fail)
}
if len(pass) < req.NrEngines {
// fail if the number of passing numa id groups is less than required
req.Log.Errorf("ssd-to-numa mapping validation failed, not enough numaID groupings "+
"satisfy SSD requirements (%d per-engine) to meet the number of required "+
"engines (%d)", minNrSSDs, req.NrEngines)
// print first failing numa id details in returned error
for _, numaID := range sd.NumaSCMs.keys() {
if sd.NumaSSDs[numaID].Len() >= minNrSSDs {
continue
}
return errors.Errorf(errInsufNrSSDs, numaID, minNrSSDs,
sd.NumaSSDs[numaID].Len())
}
// unexpected operation, program flow should not reach here
return errors.New("no pmem-to-numa mappings")
}
// truncate storage maps to remove entries that don't meet requirements
for _, idx := range fail {
delete(sd.NumaSCMs, idx)
delete(sd.NumaSSDs, idx)
}
req.Log.Debugf("storage validation passed, scm: %+v, nvme: %+v", sd.NumaSCMs,
sd.NumaSSDs)
return nil
}
// returns all combinations of n size in set
func combinations(set []int, n int) (sss [][]int) {
length := uint(len(set))
if n > len(set) {
n = len(set)
}
// iterate through possible combinations and assign subsets
for ssBits := 1; ssBits < (1 << length); ssBits++ {
if n > 0 && bits.OnesCount(uint(ssBits)) != n {
continue
}
var ss []int
for obj := uint(0); obj < length; obj++ {
// is obj in subset?
if (ssBits>>obj)&1 == 1 {
ss = append(ss, set[obj])
}
}
sss = append(sss, ss)
}
for _, ss := range sss {
sort.Ints(ss)
}
// sort slices by first element
sort.Slice(sss, func(i, j int) bool {
if len(sss[i]) == 0 && len(sss[j]) == 0 {
return false
}
if len(sss[i]) == 0 || len(sss[j]) == 0 {
return len(sss[i]) == 0
}
return sss[i][0] < sss[j][0]
})
return sss
}
// returns true if sub is part of super
func isSubset(sub, super []int) bool {
set := make(map[int]int)
for _, val := range super {
set[val] += 1
}
for _, val := range sub {
if set[val] == 0 {
return false
}
set[val] -= 1
}
return true
}
type rating struct {
prioSum int
provider string
}
func getFabricScores(log logging.Logger, nodeSets [][]int, nd *networkDetails) ([]*rating, error) {
// return combined interface score for each numa node set
scores := make([]*rating, len(nodeSets))
for idx, ns := range nodeSets {
if len(ns) == 0 {
return nil, errors.Errorf("unexpected empty numa node set at index %d", idx)
}
// if a input numa node set is a subset of the node set supported on fabric interfaces
// for a specific provider, record it as a matching provider
var matchingProviders []string
for p, numaIfaces := range nd.ProviderIfaces {
if isSubset(ns, numaIfaces.keys()) {
matchingProviders = append(matchingProviders, p)
}
}
if len(matchingProviders) == 0 {
log.Debugf("no providers with supported fabric ifaces across numa set %v", ns)
continue
}
log.Debugf("providers %v supported across numa set %v", matchingProviders, ns)
// for each matching provider, sum priority scores for each node's first iface
// and select provider with lowest sum priority for this node set
var bestProvider string
var bestScore int = math.MaxInt32
for _, p := range matchingProviders {
var score int
for _, n := range ns {
ni := nd.ProviderIfaces[p][n]
if ni == nil {
return nil, errors.Errorf("nil iface for provider %s, numa %d",
p, n)
}
score += int(ni.Priority)
}
if score < bestScore {
bestScore = score
bestProvider = p
}
}
if bestProvider == "" || bestScore == math.MaxUint32 {
// unexpected, score should have been calculated by this point
return nil, errors.Errorf("fabric score not calculated for numa node set %v",
ns)
}
scores[idx] = &rating{
prioSum: bestScore,
provider: bestProvider,
}
log.Debugf("fabric score for numa node set %v: %+v", ns, *scores[idx])
}
return scores, nil
}
func nodeSetToMap(ns []int) map[int]bool {
nm := make(map[int]bool)
for _, ni := range ns {
nm[ni] = true
}
return nm
}
// Trim device details to fit the number of engines required.
func trimStorageDeviceMaps(nodeSet []int, sd *storageDetails) {
nodesToUse := nodeSetToMap(nodeSet)
for numaID := range sd.NumaSCMs {
if !nodesToUse[numaID] {
delete(sd.NumaSCMs, numaID)
}
}
for numaID := range sd.NumaSSDs {
if !nodesToUse[numaID] {
delete(sd.NumaSSDs, numaID)
}
}
}
// Find min nr ssds across numa node set and first node with that number.
func lowestCommonNrSSDs(nodeSet []int, numaSSDs numaSSDsMap) (int, error) {
nodesToUse := nodeSetToMap(nodeSet)
minNrSSDs := math.MaxUint32
for numaID, ssds := range numaSSDs {
if nodesToUse[numaID] && ssds.Len() < minNrSSDs {
minNrSSDs = ssds.Len()
}
}
if minNrSSDs == math.MaxUint32 {
return 0, errors.New("lowest common number of ssds could not be calculated")
}
return minNrSSDs, nil
}
// Generate scores for interfaces supporting a specific provider across a set of NUMA nodes whose
// length matches engineCount. Score is sum of interface priority values. Choose lowest score.
func chooseEngineAffinity(req ConfGenerateReq, nd *networkDetails, sd *storageDetails) ([]int, error) {
nodes := sd.NumaSCMs.keys()
// retrieve numa node combinations that meet storage requirements for an engine config
nodeSets := combinations(nodes, req.NrEngines)
if len(nodeSets) == 0 {
return nil, errors.New("no numa node sets found in scm map")
}
req.Log.Debugf("numasets for possible engine configs: %v (from superset %v)", nodeSets,
nodes)
fabricScores, err := getFabricScores(req.Log, nodeSets, nd)
if err != nil {
return nil, err
}
// choose the numa node set with the lowest fabric priority score (lower is better), if
// score is equal, choose nodes with max lowest-common number of ssds
var bestNumaSet []int
var bestFabric *rating
for idx, fs := range fabricScores {
switch {
case fs == nil:
continue
case bestFabric == nil:
// first entrant, select winner
case fs.prioSum > bestFabric.prioSum:
// higher score, skip entrant
continue
case fs.prioSum < bestFabric.prioSum:
// new winning score, select winner
default:
// equal lowest score, choose set with max lowest common number of ssds
curBestNrSSDs, err := lowestCommonNrSSDs(bestNumaSet, sd.NumaSSDs)
if err != nil {
return nil, err
}
newBestNrSSDs, err := lowestCommonNrSSDs(nodeSets[idx], sd.NumaSSDs)
if err != nil {
return nil, err
}
if newBestNrSSDs <= curBestNrSSDs {
continue
}
}
bestFabric = fs
bestNumaSet = nodeSets[idx]
}
if len(bestNumaSet) == 0 || bestFabric == nil {
return nil, errors.New(errInsufNrProvGroups)
}
req.Log.Debugf("fabric provider %s chosen on numa nodes %v", bestFabric.provider,
bestNumaSet)
// populate specific fabric interfaces to use for each numa node
nd.NumaIfaces = make(numaNetIfaceMap)
for _, nn := range bestNumaSet {
iface := nd.ProviderIfaces[bestFabric.provider][nn]
if iface != nil {
nd.NumaIfaces[nn] = iface
}
}
nd.ProviderIfaces = nil
// trim any storage device groupings for numa ids that are unsuitable for engine configs
trimStorageDeviceMaps(bestNumaSet, sd)
// sanity check number of satisfied numa id groups matches number of engines required
if len(nd.NumaIfaces) != req.NrEngines {
return nil, errors.Errorf(errInsufNrIfaces, req.NrEngines, len(nd.NumaIfaces),
nd.NumaIfaces)
}
if len(sd.NumaSCMs) != req.NrEngines {
return nil, errors.Errorf(errInsufNrPMemGroups, sd.NumaSCMs, req.NrEngines,
len(sd.NumaSCMs))
}
if len(sd.NumaSSDs) != req.NrEngines {
return nil, errors.Errorf(errInsufNrSSDGroups, sd.NumaSSDs, req.NrEngines,
len(sd.NumaSSDs))
}
sort.Ints(bestNumaSet)
return bestNumaSet, nil
}
func filterDevicesByAffinity(req ConfGenerateReq, nd *networkDetails, sd *storageDetails) ([]int, error) {
// if unset, assign number of engines based on number of NUMA nodes
if req.NrEngines == 0 {
req.NrEngines = nd.NumaCount
}
if req.NrEngines == 0 {
return nil, errNoNuma
}
req.Log.Debugf("attempting to generate config with %d engines", req.NrEngines)
if err := checkNvmeAffinity(req, sd); err != nil {
return nil, err
}
nodeSet, err := chooseEngineAffinity(req, nd, sd)
if err != nil {
return nil, err
}
if len(nodeSet) == 0 {
return nil, errors.New("generated config should have at least one engine")
}
return nodeSet, nil
}
func correctSSDCounts(log logging.Logger, sd *storageDetails) error {
// calculate ssd count lowest value across numa nodes
minSSDsInCfg, err := lowestCommonNrSSDs(sd.NumaSSDs.keys(), sd.NumaSSDs)
if err != nil {
return err
}
log.Debugf("selecting %d ssds per engine (lowest value across engines)", minSSDsInCfg)
// second pass to apply corrections
for numaID := range sd.NumaSSDs {
ssds := sd.NumaSSDs[numaID]
if ssds.Len() > minSSDsInCfg {
log.Debugf("larger number of SSDs (%d) on NUMA-%d than the lowest common "+
"number across all relevant NUMA nodes (%d), configuration is "+
"not balanced", ssds.Len(), numaID, minSSDsInCfg)
if ssds.HasVMD() {
// Not currently possible to restrict the number of backing devices
// used behind a VMD so refuse to generate config.
return FaultConfigVMDImbalance
}
// restrict ssds used so that number is equal across engines
log.Debugf("only using %d SSDs from NUMA-%d from an available %d",
minSSDsInCfg, numaID, ssds.Len())
ssdAddrs := ssds.Strings()[:minSSDsInCfg]
sd.NumaSSDs[numaID] = hardware.MustNewPCIAddressSet(ssdAddrs...)
}
}
return nil
}
func getSCMTier(log logging.Logger, numaID, nrNumaNodes int, sd *storageDetails) (*storage.TierConfig, error) {
scmTier := storage.NewTierConfig().WithStorageClass(sd.scmCls.String()).
WithScmMountPoint(fmt.Sprintf("%s%d", scmMountPrefix, numaID))
switch sd.scmCls {
case storage.ClassRam:
case storage.ClassDcpm:
// Assumes only one entry per NUMA node in map.
scmTier.WithScmDeviceList(sd.NumaSCMs[numaID][0])
default:
return nil, errors.Errorf("unrecognized scm tier class %q", sd.scmCls)
}
return scmTier, nil
}
func getBdevTiers(log logging.Logger, mdOnSSD bool, ssds *hardware.PCIAddressSet) (storage.TierConfigs, error) {
nrSSDs := ssds.Len()
addrs := ssds.Strings()
if ssds.HasVMD() {
// If addresses are for VMD backing devices, convert to the logical VMD
// domain address as this is what is expected in the server config.
newAddrSet, err := ssds.BackingToVMDAddresses()
if err != nil {
return nil, errors.Wrap(err, "converting backing addresses to vmd")
}
nrSSDs = newAddrSet.Len()
addrs = newAddrSet.Strings()
}
if nrSSDs == 0 {
log.Debugf("skip assigning ssd tiers as no ssds are available")
return nil, nil
}
if !mdOnSSD {
return storage.TierConfigs{
storage.NewTierConfig().
WithStorageClass(storage.ClassNvme.String()).
WithBdevDeviceList(addrs...),
}, nil
}
// Assign SSDs to multiple tiers for MD-on-SSD, NVMe SSDs on same NUMA as
// engine to be split into bdev tiers as follows:
// 1 SSD: tiers 1
// 2-5 SSDs: tiers 1:N-1