chore: add generic methods and use them part #2

Use things from #5702.

Signed-off-by: Dmitriy Matrenichev <dmitry.matrenichev@siderolabs.com>
This commit is contained in:
Dmitriy Matrenichev 2022-06-08 00:08:23 +08:00
parent 7114292b6c
commit 4dbbf4ac50
No known key found for this signature in database
GPG Key ID: D3363CF894E68892
49 changed files with 199 additions and 424 deletions

View File

@ -28,6 +28,7 @@ import (
k8sctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/k8s" k8sctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/k8s"
"github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/logging"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/resources/k8s" "github.com/talos-systems/talos/pkg/machinery/resources/k8s"
"github.com/talos-systems/talos/pkg/machinery/resources/v1alpha1" "github.com/talos-systems/talos/pkg/machinery/resources/v1alpha1"
) )
@ -85,11 +86,7 @@ func (suite *ControlPlaneStaticPodSuite) assertControlPlaneStaticPods(manifests
return err return err
} }
ids := make([]string, 0, len(resources.Items)) ids := slices.Map(resources.Items, func(r resource.Resource) string { return r.Metadata().ID() })
for _, res := range resources.Items {
ids = append(ids, res.Metadata().ID())
}
if !reflect.DeepEqual(manifests, ids) { if !reflect.DeepEqual(manifests, ids) {
return retry.ExpectedError(fmt.Errorf("expected %q, got %q", manifests, ids)) return retry.ExpectedError(fmt.Errorf("expected %q, got %q", manifests, ids))

View File

@ -26,6 +26,7 @@ import (
k8sadapter "github.com/talos-systems/talos/internal/app/machined/pkg/adapters/k8s" k8sadapter "github.com/talos-systems/talos/internal/app/machined/pkg/adapters/k8s"
k8sctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/k8s" k8sctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/k8s"
"github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/logging"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/resources/k8s" "github.com/talos-systems/talos/pkg/machinery/resources/k8s"
"github.com/talos-systems/talos/pkg/machinery/resources/network" "github.com/talos-systems/talos/pkg/machinery/resources/network"
"github.com/talos-systems/talos/pkg/machinery/resources/v1alpha1" "github.com/talos-systems/talos/pkg/machinery/resources/v1alpha1"
@ -78,11 +79,7 @@ func (suite *ExtraManifestSuite) assertExtraManifests(manifests []string) error
return err return err
} }
ids := make([]string, 0, len(resources.Items)) ids := slices.Map(resources.Items, func(r resource.Resource) string { return r.Metadata().ID() })
for _, res := range resources.Items {
ids = append(ids, res.Metadata().ID())
}
if !reflect.DeepEqual(manifests, ids) { if !reflect.DeepEqual(manifests, ids) {
return retry.ExpectedError(fmt.Errorf("expected %q, got %q", manifests, ids)) return retry.ExpectedError(fmt.Errorf("expected %q, got %q", manifests, ids))

View File

@ -209,11 +209,9 @@ func (ctrl *ManifestApplyController) etcdLock(ctx context.Context, logger *zap.L
//nolint:gocyclo //nolint:gocyclo
func (ctrl *ManifestApplyController) apply(ctx context.Context, logger *zap.Logger, mapper *restmapper.DeferredDiscoveryRESTMapper, dyn dynamic.Interface, manifests resource.List) error { func (ctrl *ManifestApplyController) apply(ctx context.Context, logger *zap.Logger, mapper *restmapper.DeferredDiscoveryRESTMapper, dyn dynamic.Interface, manifests resource.List) error {
// flatten list of objects to be applied // flatten list of objects to be applied
objects := make([]*unstructured.Unstructured, 0, len(manifests.Items)) objects := slices.FlatMap(manifests.Items, func(m resource.Resource) []*unstructured.Unstructured {
return k8sadapter.Manifest(m.(*k8s.Manifest)).Objects()
for _, manifest := range manifests.Items { })
objects = append(objects, k8sadapter.Manifest(manifest.(*k8s.Manifest)).Objects()...)
}
// sort the list so that namespaces come first, followed by CRDs and everything else after that // sort the list so that namespaces come first, followed by CRDs and everything else after that
sort.SliceStable(objects, func(i, j int) bool { sort.SliceStable(objects, func(i, j int) bool {

View File

@ -26,6 +26,7 @@ import (
k8sctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/k8s" k8sctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/k8s"
"github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/logging"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/resources/k8s" "github.com/talos-systems/talos/pkg/machinery/resources/k8s"
"github.com/talos-systems/talos/pkg/machinery/resources/secrets" "github.com/talos-systems/talos/pkg/machinery/resources/secrets"
) )
@ -77,11 +78,7 @@ func (suite *ManifestSuite) assertManifests(manifests []string) error {
return err return err
} }
ids := make([]string, 0, len(resources.Items)) ids := slices.Map(resources.Items, func(r resource.Resource) string { return r.Metadata().ID() })
for _, res := range resources.Items {
ids = append(ids, res.Metadata().ID())
}
if !reflect.DeepEqual(manifests, ids) { if !reflect.DeepEqual(manifests, ids) {
return retry.ExpectedError(fmt.Errorf("expected %q, got %q", manifests, ids)) return retry.ExpectedError(fmt.Errorf("expected %q, got %q", manifests, ids))

View File

@ -22,6 +22,7 @@ import (
"github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/logging"
"github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/resources/config" "github.com/talos-systems/talos/pkg/machinery/resources/config"
) )
@ -67,11 +68,7 @@ func (suite *KubeSpanSuite) assertResourceIDs(md resource.Metadata, expectedIDs
return err return err
} }
actualIDs := make([]resource.ID, 0, len(l.Items)) actualIDs := slices.Map(l.Items, func(r resource.Resource) string { return r.Metadata().ID() })
for _, r := range l.Items {
actualIDs = append(actualIDs, r.Metadata().ID())
}
sort.Strings(expectedIDs) sort.Strings(expectedIDs)

View File

@ -15,6 +15,7 @@ import (
"go.uber.org/zap" "go.uber.org/zap"
"inet.af/netaddr" "inet.af/netaddr"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/resources/cluster" "github.com/talos-systems/talos/pkg/machinery/resources/cluster"
"github.com/talos-systems/talos/pkg/machinery/resources/config" "github.com/talos-systems/talos/pkg/machinery/resources/config"
"github.com/talos-systems/talos/pkg/machinery/resources/kubespan" "github.com/talos-systems/talos/pkg/machinery/resources/kubespan"
@ -178,12 +179,5 @@ func (ctrl *PeerSpecController) Run(ctx context.Context, r controller.Runtime, l
// dumpSet converts IPSet to a form suitable for logging. // dumpSet converts IPSet to a form suitable for logging.
func dumpSet(set *netaddr.IPSet) []string { func dumpSet(set *netaddr.IPSet) []string {
ranges := set.Ranges() return slices.Map(set.Ranges(), netaddr.IPRange.String)
res := make([]string, len(ranges))
for i, p := range ranges {
res[i] = p.String()
}
return res
} }

View File

@ -16,6 +16,7 @@ import (
"inet.af/netaddr" "inet.af/netaddr"
talosconfig "github.com/talos-systems/talos/pkg/machinery/config" talosconfig "github.com/talos-systems/talos/pkg/machinery/config"
"github.com/talos-systems/talos/pkg/machinery/generic/maps"
"github.com/talos-systems/talos/pkg/machinery/nethelpers" "github.com/talos-systems/talos/pkg/machinery/nethelpers"
"github.com/talos-systems/talos/pkg/machinery/ordered" "github.com/talos-systems/talos/pkg/machinery/ordered"
"github.com/talos-systems/talos/pkg/machinery/resources/network" "github.com/talos-systems/talos/pkg/machinery/resources/network"
@ -340,13 +341,7 @@ func (ctrl *LinkConfigController) processDevicesConfiguration(logger *zap.Logger
SetBondSlave(linkMap[slaveName], bondData) SetBondSlave(linkMap[slaveName], bondData)
} }
links := make([]network.LinkSpecSpec, 0, len(linkMap)) return maps.ValuesFunc(linkMap, func(link *network.LinkSpecSpec) network.LinkSpecSpec { return *link })
for _, link := range linkMap {
links = append(links, *link)
}
return links
} }
func vlanLink(linkName string, vlan talosconfig.Vlan) network.LinkSpecSpec { func vlanLink(linkName string, vlan talosconfig.Vlan) network.LinkSpecSpec {

View File

@ -28,6 +28,7 @@ import (
networkadapter "github.com/talos-systems/talos/internal/app/machined/pkg/adapters/network" networkadapter "github.com/talos-systems/talos/internal/app/machined/pkg/adapters/network"
netctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/network" netctrl "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/network"
"github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/logging"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/nethelpers" "github.com/talos-systems/talos/pkg/machinery/nethelpers"
"github.com/talos-systems/talos/pkg/machinery/resources/network" "github.com/talos-systems/talos/pkg/machinery/resources/network"
) )
@ -800,25 +801,18 @@ func TestSortBonds(t *testing.T) {
} }
func toResources(slice []network.LinkSpecSpec) []resource.Resource { func toResources(slice []network.LinkSpecSpec) []resource.Resource {
result := make([]resource.Resource, 0, len(slice)) return slices.Map(slice, func(spec network.LinkSpecSpec) resource.Resource {
for _, elem := range slice {
link := network.NewLinkSpec(network.NamespaceName, "bar") link := network.NewLinkSpec(network.NamespaceName, "bar")
*link.TypedSpec() = elem *link.TypedSpec() = spec
result = append(result, link) return link
} })
return result
} }
func toSpecs(slice []resource.Resource) []network.LinkSpecSpec { func toSpecs(slice []resource.Resource) []network.LinkSpecSpec {
result := make([]network.LinkSpecSpec, 0, len(slice)) return slices.Map(slice, func(r resource.Resource) network.LinkSpecSpec {
v := r.Spec().(*network.LinkSpecSpec) //nolint:errcheck
for _, elem := range slice { return *v
v := elem.Spec().(*network.LinkSpecSpec) //nolint:errcheck })
result = append(result, *v)
}
return result
} }

View File

@ -19,6 +19,7 @@ import (
"inet.af/netaddr" "inet.af/netaddr"
"github.com/talos-systems/talos/internal/app/machined/pkg/runtime" "github.com/talos-systems/talos/internal/app/machined/pkg/runtime"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/nethelpers" "github.com/talos-systems/talos/pkg/machinery/nethelpers"
"github.com/talos-systems/talos/pkg/machinery/resources/network" "github.com/talos-systems/talos/pkg/machinery/resources/network"
) )
@ -246,15 +247,15 @@ func (d *DHCP4) parseAck(ack *dhcpv4.DHCPv4) {
} }
if len(ack.DNS()) > 0 { if len(ack.DNS()) > 0 {
dns := make([]netaddr.IP, len(ack.DNS())) convertIP := func(ip net.IP) netaddr.IP {
result, _ := netaddr.FromStdIP(ip)
for i := range dns { return result
dns[i], _ = netaddr.FromStdIP(ack.DNS()[i])
} }
d.resolvers = []network.ResolverSpecSpec{ d.resolvers = []network.ResolverSpecSpec{
{ {
DNSServers: dns, DNSServers: slices.Map(ack.DNS(), convertIP),
ConfigLayer: network.ConfigOperator, ConfigLayer: network.ConfigOperator,
}, },
} }
@ -283,16 +284,15 @@ func (d *DHCP4) parseAck(ack *dhcpv4.DHCPv4) {
} }
if len(ack.NTPServers()) > 0 { if len(ack.NTPServers()) > 0 {
ntp := make([]string, len(ack.NTPServers())) convertIP := func(ip net.IP) string {
result, _ := netaddr.FromStdIP(ip)
for i := range ntp { return result.String()
ip, _ := netaddr.FromStdIP(ack.NTPServers()[i])
ntp[i] = ip.String()
} }
d.timeservers = []network.TimeServerSpecSpec{ d.timeservers = []network.TimeServerSpecSpec{
{ {
NTPServers: ntp, NTPServers: slices.Map(ack.NTPServers(), convertIP),
ConfigLayer: network.ConfigOperator, ConfigLayer: network.ConfigOperator,
}, },
} }

View File

@ -22,6 +22,7 @@ import (
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
"inet.af/netaddr" "inet.af/netaddr"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/nethelpers" "github.com/talos-systems/talos/pkg/machinery/nethelpers"
"github.com/talos-systems/talos/pkg/machinery/resources/network" "github.com/talos-systems/talos/pkg/machinery/resources/network"
) )
@ -172,15 +173,15 @@ func (d *DHCP6) parseReply(reply *dhcpv6.Message) (leaseTime time.Duration) {
} }
if len(reply.Options.DNS()) > 0 { if len(reply.Options.DNS()) > 0 {
dns := make([]netaddr.IP, len(reply.Options.DNS())) convertIP := func(ip net.IP) netaddr.IP {
result, _ := netaddr.FromStdIP(ip)
for i := range dns { return result
dns[i], _ = netaddr.FromStdIP(reply.Options.DNS()[i])
} }
d.resolvers = []network.ResolverSpecSpec{ d.resolvers = []network.ResolverSpecSpec{
{ {
DNSServers: dns, DNSServers: slices.Map(reply.Options.DNS(), convertIP),
ConfigLayer: network.ConfigOperator, ConfigLayer: network.ConfigOperator,
}, },
} }
@ -201,16 +202,15 @@ func (d *DHCP6) parseReply(reply *dhcpv6.Message) (leaseTime time.Duration) {
} }
if len(reply.Options.NTPServers()) > 0 { if len(reply.Options.NTPServers()) > 0 {
ntp := make([]string, len(reply.Options.NTPServers())) convertIP := func(ip net.IP) string {
result, _ := netaddr.FromStdIP(ip)
for i := range ntp { return result.String()
ip, _ := netaddr.FromStdIP(reply.Options.NTPServers()[i])
ntp[i] = ip.String()
} }
d.timeservers = []network.TimeServerSpecSpec{ d.timeservers = []network.TimeServerSpecSpec{
{ {
NTPServers: ntp, NTPServers: slices.Map(reply.Options.NTPServers(), convertIP),
ConfigLayer: network.ConfigOperator, ConfigLayer: network.ConfigOperator,
}, },
} }

View File

@ -16,6 +16,7 @@ import (
"go.uber.org/zap" "go.uber.org/zap"
talosconfig "github.com/talos-systems/talos/pkg/machinery/config" talosconfig "github.com/talos-systems/talos/pkg/machinery/config"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/resources/network" "github.com/talos-systems/talos/pkg/machinery/resources/network"
) )
@ -100,13 +101,9 @@ func (ctrl *OperatorConfigController) Run(ctx context.Context, r controller.Runt
specErrors *multierror.Error specErrors *multierror.Error
) )
devices := make([]talosconfig.Device, len(items.Items)) devices := slices.Map(items.Items, func(item resource.Resource) talosconfig.Device {
return item.(*network.DeviceConfigSpec).TypedSpec().Device
for i, item := range items.Items { })
device := item.(*network.DeviceConfigSpec).TypedSpec().Device
devices[i] = device
}
// operators from the config // operators from the config
if len(devices) > 0 { if len(devices) > 0 {

View File

@ -18,6 +18,7 @@ import (
"github.com/talos-systems/talos/internal/app/machined/pkg/controllers/network/operator/vip" "github.com/talos-systems/talos/internal/app/machined/pkg/controllers/network/operator/vip"
talosconfig "github.com/talos-systems/talos/pkg/machinery/config" talosconfig "github.com/talos-systems/talos/pkg/machinery/config"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/resources/network" "github.com/talos-systems/talos/pkg/machinery/resources/network"
) )
@ -72,13 +73,9 @@ func (ctrl *OperatorVIPConfigController) Run(ctx context.Context, r controller.R
} }
} }
devices := make([]talosconfig.Device, len(items.Items)) devices := slices.Map(items.Items, func(item resource.Resource) talosconfig.Device {
return item.(*network.DeviceConfigSpec).TypedSpec().Device
for i, item := range items.Items { })
device := item.(*network.DeviceConfigSpec).TypedSpec().Device
devices[i] = device
}
ignoredInterfaces := map[string]struct{}{} ignoredInterfaces := map[string]struct{}{}

View File

@ -12,7 +12,9 @@ import (
"github.com/cosi-project/runtime/pkg/resource" "github.com/cosi-project/runtime/pkg/resource"
"github.com/cosi-project/runtime/pkg/state" "github.com/cosi-project/runtime/pkg/state"
"go.uber.org/zap" "go.uber.org/zap"
"inet.af/netaddr"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/resources/network" "github.com/talos-systems/talos/pkg/machinery/resources/network"
) )
@ -87,12 +89,7 @@ func (ctrl *ResolverSpecController) Run(ctx context.Context, r controller.Runtim
return fmt.Errorf("error removing finalizer: %w", err) return fmt.Errorf("error removing finalizer: %w", err)
} }
case resource.PhaseRunning: case resource.PhaseRunning:
resolvers := make([]string, len(spec.TypedSpec().DNSServers)) resolvers := slices.Map(spec.TypedSpec().DNSServers, netaddr.IP.String)
for i := range resolvers {
resolvers[i] = spec.TypedSpec().DNSServers[i].String()
}
logger.Info("setting resolvers", zap.Strings("resolvers", resolvers)) logger.Info("setting resolvers", zap.Strings("resolvers", resolvers))
if err = r.Modify(ctx, network.NewResolverStatus(network.NamespaceName, spec.Metadata().ID()), func(r resource.Resource) error { if err = r.Modify(ctx, network.NewResolverStatus(network.NamespaceName, spec.Metadata().ID()), func(r resource.Resource) error {

View File

@ -38,6 +38,7 @@ import (
"github.com/talos-systems/talos/pkg/logging" "github.com/talos-systems/talos/pkg/logging"
talosconfig "github.com/talos-systems/talos/pkg/machinery/config" talosconfig "github.com/talos-systems/talos/pkg/machinery/config"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
configresource "github.com/talos-systems/talos/pkg/machinery/resources/config" configresource "github.com/talos-systems/talos/pkg/machinery/resources/config"
) )
@ -320,10 +321,7 @@ func (ctrl *Controller) updateLoggingConfig(ctx context.Context, cfg talosconfig
var prevSenders []runtime.LogSender var prevSenders []runtime.LogSender
if len(loggingEndpoints) > 0 { if len(loggingEndpoints) > 0 {
senders := make([]runtime.LogSender, len(loggingEndpoints)) senders := slices.Map(loggingEndpoints, runtimelogging.NewJSONLines)
for i, u := range loggingEndpoints {
senders[i] = runtimelogging.NewJSONLines(u)
}
ctrl.logger.Info("enabling JSON logging") ctrl.logger.Info("enabling JSON logging")
prevSenders = ctrl.loggingManager.SetSenders(senders) prevSenders = ctrl.loggingManager.SetSenders(senders)

View File

@ -11,6 +11,7 @@ import (
"github.com/talos-systems/talos/internal/app/machined/pkg/system/health" "github.com/talos-systems/talos/internal/app/machined/pkg/system/health"
machineapi "github.com/talos-systems/talos/pkg/machinery/api/machine" machineapi "github.com/talos-systems/talos/pkg/machinery/api/machine"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// MaxEventsToKeep is maximum number of events to keep per service before dropping old entries. // MaxEventsToKeep is maximum number of events to keep per service before dropping old entries.
@ -120,21 +121,19 @@ func (events *ServiceEvents) Get(count int) (result []ServiceEvent) {
func (events *ServiceEvents) AsProto(count int) *machineapi.ServiceEvents { func (events *ServiceEvents) AsProto(count int) *machineapi.ServiceEvents {
eventList := events.Get(count) eventList := events.Get(count)
result := &machineapi.ServiceEvents{ fn := func(event ServiceEvent) *machineapi.ServiceEvent {
Events: make([]*machineapi.ServiceEvent, len(eventList)), tspb := timestamppb.New(event.Timestamp)
}
for i := range eventList { return &machineapi.ServiceEvent{
tspb := timestamppb.New(eventList[i].Timestamp) Msg: event.Message,
State: event.State.String(),
result.Events[i] = &machineapi.ServiceEvent{
Msg: eventList[i].Message,
State: eventList[i].State.String(),
Ts: tspb, Ts: tspb,
} }
} }
return result return &machineapi.ServiceEvents{
Events: slices.Map(eventList, fn),
}
} }
// Recorder adds new event to the history of events, formatting message with args using Sprintf. // Recorder adds new event to the history of events, formatting message with args using Sprintf.

View File

@ -11,6 +11,7 @@ import (
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/talos-systems/talos/internal/app/machined/pkg/system/events" "github.com/talos-systems/talos/internal/app/machined/pkg/system/events"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
type EventsSuite struct { type EventsSuite struct {
@ -18,12 +19,7 @@ type EventsSuite struct {
} }
func (suite *EventsSuite) assertEvents(expectedMessages []string, evs []events.ServiceEvent) { func (suite *EventsSuite) assertEvents(expectedMessages []string, evs []events.ServiceEvent) {
messages := make([]string, len(evs)) messages := slices.Map(evs, func(ev events.ServiceEvent) string { return ev.Message })
for i := range evs {
messages[i] = evs[i].Message
}
suite.Assert().Equal(expectedMessages, messages) suite.Assert().Equal(expectedMessages, messages)
} }

View File

@ -17,6 +17,7 @@ import (
"github.com/talos-systems/talos/internal/app/machined/pkg/system/runner" "github.com/talos-systems/talos/internal/app/machined/pkg/system/runner"
"github.com/talos-systems/talos/pkg/conditions" "github.com/talos-systems/talos/pkg/conditions"
machineapi "github.com/talos-systems/talos/pkg/machinery/api/machine" machineapi "github.com/talos-systems/talos/pkg/machinery/api/machine"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// WaitConditionCheckInterval is time between checking for wait condition // WaitConditionCheckInterval is time between checking for wait condition
@ -200,11 +201,7 @@ func (svcrunner *ServiceRunner) Start() {
dependencies := svcrunner.service.DependsOn(svcrunner.runtime) dependencies := svcrunner.service.DependsOn(svcrunner.runtime)
if len(dependencies) > 0 { if len(dependencies) > 0 {
serviceConditions := make([]conditions.Condition, len(dependencies)) serviceConditions := slices.Map(dependencies, func(dep string) conditions.Condition { return WaitForService(StateEventUp, dep) })
for i := range dependencies {
serviceConditions[i] = WaitForService(StateEventUp, dependencies[i])
}
serviceDependencies := conditions.WaitForAll(serviceConditions...) serviceDependencies := conditions.WaitForAll(serviceConditions...)
if condition != nil { if condition != nil {

View File

@ -16,6 +16,8 @@ import (
"github.com/talos-systems/talos/internal/app/machined/pkg/runtime" "github.com/talos-systems/talos/internal/app/machined/pkg/runtime"
"github.com/talos-systems/talos/pkg/conditions" "github.com/talos-systems/talos/pkg/conditions"
"github.com/talos-systems/talos/pkg/machinery/generic/maps"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// singleton the system services API interface. // singleton the system services API interface.
@ -176,12 +178,7 @@ func (s *singleton) Start(serviceIDs ...string) error {
// StartAll starts all the services. // StartAll starts all the services.
func (s *singleton) StartAll() { func (s *singleton) StartAll() {
s.mu.Lock() s.mu.Lock()
serviceIDs := make([]string, 0, len(s.state)) serviceIDs := maps.Keys(s.state)
for id := range s.state {
serviceIDs = append(serviceIDs, id)
}
s.mu.Unlock() s.mu.Unlock()
//nolint:errcheck //nolint:errcheck
@ -335,13 +332,9 @@ func (s *singleton) stopServices(ctx context.Context, services []string, waitFor
go func(svcrunner *ServiceRunner, reverseDeps []string) { go func(svcrunner *ServiceRunner, reverseDeps []string) {
defer shutdownWg.Done() defer shutdownWg.Done()
conds := make([]conditions.Condition, len(reverseDeps)) conds := slices.Map(reverseDeps, func(dep string) conditions.Condition { return WaitForService(StateEventDown, dep) })
for i := range reverseDeps {
conds[i] = WaitForService(StateEventDown, reverseDeps[i])
}
allDeps := conditions.WaitForAll(conds...) allDeps := conditions.WaitForAll(conds...)
if err := allDeps.Wait(shutdownCtx); err != nil { if err := allDeps.Wait(shutdownCtx); err != nil {
log.Printf("gave up on %s while stopping %q", allDeps, svcrunner.id) log.Printf("gave up on %s while stopping %q", allDeps, svcrunner.id)
} }
@ -360,10 +353,7 @@ func (s *singleton) List() (result []*ServiceRunner) {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
result = make([]*ServiceRunner, 0, len(s.state)) result = maps.Values(s.state)
for _, svcrunner := range s.state {
result = append(result, svcrunner)
}
// TODO: results should be sorted properly with topological sort on dependencies // TODO: results should be sorted properly with topological sort on dependencies
// but, we don't have dependencies yet, so sort by service id for now to get stable order // but, we don't have dependencies yet, so sort by service id for now to get stable order

View File

@ -26,6 +26,7 @@ import (
"github.com/talos-systems/talos/pkg/grpc/gen" "github.com/talos-systems/talos/pkg/grpc/gen"
"github.com/talos-systems/talos/pkg/grpc/middleware/authz" "github.com/talos-systems/talos/pkg/grpc/middleware/authz"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/resources/network" "github.com/talos-systems/talos/pkg/machinery/resources/network"
) )
@ -161,11 +162,7 @@ func genTLSConfig(ips []netaddr.IP, dnsNames []string) (tlsConfig *tls.Config, p
ips = append(ips, netaddr.MustParseIP("127.0.0.1"), netaddr.MustParseIP("::1")) ips = append(ips, netaddr.MustParseIP("127.0.0.1"), netaddr.MustParseIP("::1"))
netIPs := make([]net.IP, len(ips)) netIPs := slices.Map(ips, func(ip netaddr.IP) net.IP { return ip.IPAddr().IP })
for i := range netIPs {
netIPs[i] = ips[i].IPAddr().IP
}
var generator ttls.Generator var generator ttls.Generator

View File

@ -20,6 +20,7 @@ import (
"github.com/talos-systems/talos/pkg/grpc/middleware/authz" "github.com/talos-systems/talos/pkg/grpc/middleware/authz"
resourceapi "github.com/talos-systems/talos/pkg/machinery/api/resource" resourceapi "github.com/talos-systems/talos/pkg/machinery/api/resource"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/role" "github.com/talos-systems/talos/pkg/machinery/role"
) )
@ -110,11 +111,7 @@ func (s *Server) resolveResourceKind(ctx context.Context, kind *resourceKind) (*
return matched[0], nil return matched[0], nil
case len(matched) > 1: case len(matched) > 1:
matchedTypes := make([]string, len(matched)) matchedTypes := slices.Map(matched, func(rd *meta.ResourceDefinition) string { return rd.Metadata().ID() })
for i := range matched {
matchedTypes[i] = matched[i].Metadata().ID()
}
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("resource type %q is ambiguous: %v", kind.Type, matchedTypes)) return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("resource type %q is ambiguous: %v", kind.Type, matchedTypes))
default: default:

View File

@ -11,6 +11,7 @@ import (
"google.golang.org/protobuf/types/known/emptypb" "google.golang.org/protobuf/types/known/emptypb"
"github.com/talos-systems/talos/pkg/machinery/api/storage" "github.com/talos-systems/talos/pkg/machinery/api/storage"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// Server implements storage.StorageService. // Server implements storage.StorageService.
@ -26,21 +27,21 @@ func (s *Server) Disks(ctx context.Context, in *emptypb.Empty) (reply *storage.D
return nil, err return nil, err
} }
diskList := make([]*storage.Disk, len(disks)) diskConv := func(d *disk.Disk) *storage.Disk {
return &storage.Disk{
for i, disk := range disks { DeviceName: d.DeviceName,
diskList[i] = &storage.Disk{ Model: d.Model,
DeviceName: disk.DeviceName, Size: d.Size,
Model: disk.Model, Name: d.Name,
Size: disk.Size, Serial: d.Serial,
Name: disk.Name, Modalias: d.Modalias,
Serial: disk.Serial, Type: storage.Disk_DiskType(d.Type),
Modalias: disk.Modalias, BusPath: d.BusPath,
Type: storage.Disk_DiskType(disk.Type),
BusPath: disk.BusPath,
} }
} }
diskList := slices.Map(disks, diskConv)
reply = &storage.DisksResponse{ reply = &storage.DisksResponse{
Messages: []*storage.Disks{ Messages: []*storage.Disks{
{ {

View File

@ -14,6 +14,7 @@ import (
"strings" "strings"
"github.com/talos-systems/talos/internal/integration/base" "github.com/talos-systems/talos/internal/integration/base"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// DmesgSuite verifies dmesg command. // DmesgSuite verifies dmesg command.
@ -36,13 +37,11 @@ func (suite *DmesgSuite) TestClusterHasOutput() {
nodes := suite.DiscoverNodes(context.TODO()).Nodes() nodes := suite.DiscoverNodes(context.TODO()).Nodes()
suite.Require().NotEmpty(nodes) suite.Require().NotEmpty(nodes)
matchers := make([]base.RunOption, 0, len(nodes)) matchers := slices.Map(nodes, func(node string) base.RunOption {
return base.StdoutShouldMatch(
for _, node := range nodes { regexp.MustCompile(fmt.Sprintf(`(?m)^%s:`, regexp.QuoteMeta(node))),
matchers = append(matchers, )
base.StdoutShouldMatch( })
regexp.MustCompile(fmt.Sprintf(`(?m)^%s:`, regexp.QuoteMeta(node)))))
}
suite.RunCLI([]string{"--nodes", strings.Join(nodes, ","), "dmesg"}, suite.RunCLI([]string{"--nodes", strings.Join(nodes, ","), "dmesg"},
matchers...) matchers...)

View File

@ -41,6 +41,7 @@ import (
"github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/generate" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/generate"
"github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/provision" "github.com/talos-systems/talos/pkg/provision"
"github.com/talos-systems/talos/pkg/provision/access" "github.com/talos-systems/talos/pkg/provision/access"
"github.com/talos-systems/talos/pkg/provision/providers/qemu" "github.com/talos-systems/talos/pkg/provision/providers/qemu"
@ -524,12 +525,7 @@ func (suite *UpgradeSuite) runE2E(k8sVersion string) {
} }
func (suite *UpgradeSuite) assertSameVersionCluster(client *talosclient.Client, expectedVersion string) { func (suite *UpgradeSuite) assertSameVersionCluster(client *talosclient.Client, expectedVersion string) {
nodes := make([]string, len(suite.Cluster.Info().Nodes)) nodes := slices.Map(suite.Cluster.Info().Nodes, func(node provision.NodeInfo) string { return node.IPs[0].String() })
for i, node := range suite.Cluster.Info().Nodes {
nodes[i] = node.IPs[0].String()
}
ctx := talosclient.WithNodes(suite.ctx, nodes...) ctx := talosclient.WithNodes(suite.ctx, nodes...)
var v *machineapi.VersionResponse var v *machineapi.VersionResponse

View File

@ -8,6 +8,8 @@ package circular
import ( import (
"fmt" "fmt"
"sync" "sync"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// Buffer implements circular buffer with a thread-safe writer, // Buffer implements circular buffer with a thread-safe writer,
@ -76,9 +78,7 @@ func (buf *Buffer) Write(p []byte) (int, error) {
size = buf.opt.MaxCapacity size = buf.opt.MaxCapacity
} }
data := make([]byte, size) buf.data = slices.Copy(buf.data, size)
copy(data, buf.data)
buf.data = data
} }
} }

View File

@ -17,6 +17,7 @@ import (
"github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/generate" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/generate"
v1alpha1machine "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine" v1alpha1machine "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// Generate config for GenerateConfiguration grpc. // Generate config for GenerateConfiguration grpc.
@ -45,15 +46,19 @@ func Generate(ctx context.Context, in *machine.GenerateConfigurationRequest) (re
networkConfig.NetworkInterfaces = make([]*v1alpha1.Device, len(networkInterfaces)) networkConfig.NetworkInterfaces = make([]*v1alpha1.Device, len(networkInterfaces))
for i, device := range networkInterfaces { for i, device := range networkInterfaces {
routes := make([]*v1alpha1.Route, len(device.Routes))
iface := &v1alpha1.Device{ iface := &v1alpha1.Device{
DeviceInterface: device.Interface, DeviceInterface: device.Interface,
DeviceMTU: int(device.Mtu), DeviceMTU: int(device.Mtu),
DeviceCIDR: device.Cidr, DeviceCIDR: device.Cidr,
DeviceDHCP: device.Dhcp, DeviceDHCP: device.Dhcp,
DeviceIgnore: device.Ignore, DeviceIgnore: device.Ignore,
DeviceRoutes: routes, DeviceRoutes: slices.Map(device.Routes, func(route *machine.RouteConfig) *v1alpha1.Route {
return &v1alpha1.Route{
RouteNetwork: route.Network,
RouteGateway: route.Gateway,
RouteMetric: route.Metric,
}
}),
} }
if device.DhcpOptions != nil { if device.DhcpOptions != nil {

View File

@ -26,6 +26,7 @@ import (
"github.com/talos-systems/talos/pkg/kubernetes" "github.com/talos-systems/talos/pkg/kubernetes"
"github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/resources/cluster" "github.com/talos-systems/talos/pkg/machinery/resources/cluster"
) )
@ -125,33 +126,15 @@ func AffiliateFromNode(node *v1.Node) *cluster.AffiliateSpec {
} }
func ipsToString(in []netaddr.IP) string { func ipsToString(in []netaddr.IP) string {
items := make([]string, len(in)) return strings.Join(slices.Map(in, netaddr.IP.String), ",")
for i := range in {
items[i] = in[i].String()
}
return strings.Join(items, ",")
} }
func ipPrefixesToString(in []netaddr.IPPrefix) string { func ipPrefixesToString(in []netaddr.IPPrefix) string {
items := make([]string, len(in)) return strings.Join(slices.Map(in, netaddr.IPPrefix.String), ",")
for i := range in {
items[i] = in[i].String()
}
return strings.Join(items, ",")
} }
func ipPortsToString(in []netaddr.IPPort) string { func ipPortsToString(in []netaddr.IPPort) string {
items := make([]string, len(in)) return strings.Join(slices.Map(in, netaddr.IPPort.String), ",")
for i := range in {
items[i] = in[i].String()
}
return strings.Join(items, ",")
} }
func parseIPs(in string) []netaddr.IP { func parseIPs(in string) []netaddr.IP {

View File

@ -8,6 +8,8 @@ import (
"fmt" "fmt"
"sort" "sort"
"strings" "strings"
"github.com/talos-systems/talos/pkg/machinery/generic/maps"
) )
// Key represents an arg key. // Key represents an arg key.
@ -88,12 +90,7 @@ func (a Args) Set(k, v Key) ArgsBuilder {
// Args implements the ArgsBuilder interface. // Args implements the ArgsBuilder interface.
func (a Args) Args() []string { func (a Args) Args() []string {
keys := make([]string, 0, len(a)) keys := maps.Keys(a)
for key := range a {
keys = append(keys, key)
}
sort.Strings(keys) sort.Strings(keys)
args := []string{} args := []string{}

View File

@ -10,6 +10,7 @@ import (
"io" "io"
"github.com/talos-systems/talos/pkg/chunker" "github.com/talos-systems/talos/pkg/chunker"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// Options is the functional options struct. // Options is the functional options struct.
@ -87,8 +88,7 @@ func (c *Stream) Read() <-chan []byte {
if n != 0 { if n != 0 {
// Copy the buffer since we will modify it in the next loop. // Copy the buffer since we will modify it in the next loop.
b := make([]byte, n) b := slices.Copy(buf, n)
copy(b, buf[:n])
select { select {
case <-c.ctx.Done(): case <-c.ctx.Done():

View File

@ -39,6 +39,7 @@ import (
v1alpha1config "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1" v1alpha1config "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1"
machinetype "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine" machinetype "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/machinery/resources/config" "github.com/talos-systems/talos/pkg/machinery/resources/config"
"github.com/talos-systems/talos/pkg/machinery/resources/k8s" "github.com/talos-systems/talos/pkg/machinery/resources/k8s"
) )
@ -756,11 +757,7 @@ func checkDeprecated(ctx context.Context, cluster UpgradeProvider, options Upgra
probeResources := func(namespaces ...v1.Namespace) error { probeResources := func(namespaces ...v1.Namespace) error {
r := k8sClient.Resource(*gvr) r := k8sClient.Resource(*gvr)
namespaceNames := make([]string, 0, len(namespaces)) namespaceNames := slices.Map(namespaces, func(ns v1.Namespace) string { return ns.Name })
for _, ns := range namespaces {
namespaceNames = append(namespaceNames, ns.Name)
}
if len(namespaceNames) == 0 { if len(namespaceNames) == 0 {
namespaceNames = append(namespaceNames, "default") namespaceNames = append(namespaceNames, "default")

View File

@ -9,6 +9,8 @@ import (
"fmt" "fmt"
"os" "os"
"time" "time"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
type file string type file string
@ -47,10 +49,7 @@ func WaitForFileToExist(filename string) Condition {
// WaitForFilesToExist is a service condition that will wait for the existence of all the files. // WaitForFilesToExist is a service condition that will wait for the existence of all the files.
func WaitForFilesToExist(filenames ...string) Condition { func WaitForFilesToExist(filenames ...string) Condition {
conditions := make([]Condition, len(filenames)) conditions := slices.Map(filenames, WaitForFileToExist)
for i := range filenames {
conditions[i] = WaitForFileToExist(filenames[i])
}
return WaitForAll(conditions...) return WaitForAll(conditions...)
} }

View File

@ -15,6 +15,8 @@ import (
"google.golang.org/grpc" "google.golang.org/grpc"
metadata "google.golang.org/grpc/metadata" metadata "google.golang.org/grpc/metadata"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
"github.com/talos-systems/talos/pkg/machinery/generic/maps"
) )
// Middleware provides grpc logging middleware. // Middleware provides grpc logging middleware.
@ -36,12 +38,7 @@ var sensitiveFields = map[string]struct{}{
// ExtractMetadata formats metadata from incoming grpc context as string for the log. // ExtractMetadata formats metadata from incoming grpc context as string for the log.
func ExtractMetadata(ctx context.Context) string { func ExtractMetadata(ctx context.Context) string {
md, _ := metadata.FromIncomingContext(ctx) md, _ := metadata.FromIncomingContext(ctx)
keys := make([]string, 0, len(md)) keys := maps.Keys(md)
for key := range md {
keys = append(keys, key)
}
sort.Strings(keys) sort.Strings(keys)
pairs := make([]string, 0, len(keys)) pairs := make([]string, 0, len(keys))

View File

@ -9,6 +9,7 @@ import (
"github.com/talos-systems/talos/pkg/machinery/config" "github.com/talos-systems/talos/pkg/machinery/config"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// Image implements the config.APIServer interface. // Image implements the config.APIServer interface.
@ -29,13 +30,7 @@ func (a *APIServerConfig) ExtraArgs() map[string]string {
// ExtraVolumes implements the config.APIServer interface. // ExtraVolumes implements the config.APIServer interface.
func (a *APIServerConfig) ExtraVolumes() []config.VolumeMount { func (a *APIServerConfig) ExtraVolumes() []config.VolumeMount {
volumes := make([]config.VolumeMount, 0, len(a.ExtraVolumesConfig)) return slices.Map(a.ExtraVolumesConfig, func(v VolumeMountConfig) config.VolumeMount { return v })
for _, volume := range a.ExtraVolumesConfig {
volumes = append(volumes, volume)
}
return volumes
} }
// Env implements the config.APIServer interface. // Env implements the config.APIServer interface.
@ -50,15 +45,5 @@ func (a *APIServerConfig) DisablePodSecurityPolicy() bool {
// AdmissionControl implements the config.APIServer interface. // AdmissionControl implements the config.APIServer interface.
func (a *APIServerConfig) AdmissionControl() []config.AdmissionPlugin { func (a *APIServerConfig) AdmissionControl() []config.AdmissionPlugin {
if a.AdmissionControlConfig == nil { return slices.Map(a.AdmissionControlConfig, func(c *AdmissionPluginConfig) config.AdmissionPlugin { return c })
return nil
}
res := make([]config.AdmissionPlugin, 0, len(a.AdmissionControlConfig))
for _, c := range a.AdmissionControlConfig {
res = append(res, c)
}
return res
} }

View File

@ -16,6 +16,7 @@ import (
"github.com/talos-systems/talos/pkg/machinery/config" "github.com/talos-systems/talos/pkg/machinery/config"
"github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// ClusterConfig implements config.ClusterConfig, config.Token, and config.ClusterNetwork interfaces. // ClusterConfig implements config.ClusterConfig, config.Token, and config.ClusterNetwork interfaces.
@ -158,13 +159,7 @@ func (c *ClusterConfig) ExtraManifestHeaderMap() map[string]string {
// InlineManifests implements the config.ClusterConfig interface. // InlineManifests implements the config.ClusterConfig interface.
func (c *ClusterConfig) InlineManifests() []config.InlineManifest { func (c *ClusterConfig) InlineManifests() []config.InlineManifest {
manifests := make([]config.InlineManifest, len(c.ClusterInlineManifests)) return slices.Map(c.ClusterInlineManifests, func(m ClusterInlineManifest) config.InlineManifest { return m })
for i := range manifests {
manifests[i] = c.ClusterInlineManifests[i]
}
return manifests
} }
// AdminKubeconfig implements the config.ClusterConfig interface. // AdminKubeconfig implements the config.ClusterConfig interface.

View File

@ -9,6 +9,7 @@ import (
"github.com/talos-systems/talos/pkg/machinery/config" "github.com/talos-systems/talos/pkg/machinery/config"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// Image implements the config.ControllerManager interface. // Image implements the config.ControllerManager interface.
@ -29,13 +30,7 @@ func (c *ControllerManagerConfig) ExtraArgs() map[string]string {
// ExtraVolumes implements the config.ControllerManager interface. // ExtraVolumes implements the config.ControllerManager interface.
func (c *ControllerManagerConfig) ExtraVolumes() []config.VolumeMount { func (c *ControllerManagerConfig) ExtraVolumes() []config.VolumeMount {
volumes := make([]config.VolumeMount, 0, len(c.ExtraVolumesConfig)) return slices.Map(c.ExtraVolumesConfig, func(v VolumeMountConfig) config.VolumeMount { return v })
for _, volume := range c.ExtraVolumesConfig {
volumes = append(volumes, volume)
}
return volumes
} }
// Env implements the config.ControllerManager interface. // Env implements the config.ControllerManager interface.

View File

@ -6,20 +6,12 @@ package v1alpha1
import ( import (
"github.com/talos-systems/talos/pkg/machinery/config" "github.com/talos-systems/talos/pkg/machinery/config"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// Modules implements config.Kernel interface. // Modules implements config.Kernel interface.
func (kc *KernelConfig) Modules() []config.KernelModule { func (kc *KernelConfig) Modules() []config.KernelModule {
if kc.KernelModules == nil { return slices.Map(kc.KernelModules, func(kmc *KernelModuleConfig) config.KernelModule { return kmc })
return nil
}
res := make([]config.KernelModule, len(kc.KernelModules))
for i, m := range kc.KernelModules {
res[i] = config.KernelModule(m)
}
return res
} }
// Name implements config.KernelModule interface. // Name implements config.KernelModule interface.

View File

@ -12,6 +12,7 @@ import (
"github.com/talos-systems/talos/pkg/machinery/config" "github.com/talos-systems/talos/pkg/machinery/config"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// Validate checks logging configuration for errors. // Validate checks logging configuration for errors.
@ -49,12 +50,7 @@ func (lc *LoggingConfig) Validate() error {
// Destinations implements config.Logging interface. // Destinations implements config.Logging interface.
func (lc *LoggingConfig) Destinations() []config.LoggingDestination { func (lc *LoggingConfig) Destinations() []config.LoggingDestination {
res := make([]config.LoggingDestination, len(lc.LoggingDestinations)) return slices.Map(lc.LoggingDestinations, func(ld LoggingDestination) config.LoggingDestination { return ld })
for i, ld := range lc.LoggingDestinations {
res[i] = config.LoggingDestination(ld)
}
return res
} }
// Endpoint implements config.LoggingDestination interface. // Endpoint implements config.LoggingDestination interface.

View File

@ -20,6 +20,7 @@ import (
"github.com/talos-systems/talos/pkg/machinery/config/encoder" "github.com/talos-systems/talos/pkg/machinery/config/encoder"
"github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
const ( const (
@ -101,13 +102,7 @@ func (m *MachineConfig) Security() config.Security {
// Disks implements the config.Provider interface. // Disks implements the config.Provider interface.
func (m *MachineConfig) Disks() []config.Disk { func (m *MachineConfig) Disks() []config.Disk {
disks := make([]config.Disk, len(m.MachineDisks)) return slices.Map(m.MachineDisks, func(d *MachineDisk) config.Disk { return d })
for i := 0; i < len(m.MachineDisks); i++ {
disks[i] = m.MachineDisks[i]
}
return disks
} }
// Network implements the config.Provider interface. // Network implements the config.Provider interface.
@ -139,17 +134,7 @@ func (m *MachineConfig) Controlplane() config.MachineControlPlane {
// Pods implements the config.Provider interface. // Pods implements the config.Provider interface.
func (m *MachineConfig) Pods() []map[string]interface{} { func (m *MachineConfig) Pods() []map[string]interface{} {
if m.MachinePods == nil { return slices.Map(m.MachinePods, func(u Unstructured) map[string]interface{} { return u.Object })
return nil
}
v := make([]map[string]interface{}, len(m.MachinePods))
for i := range v {
v[i] = m.MachinePods[i].Object
}
return v
} }
// ControllerManager implements the config.Provider interface. // ControllerManager implements the config.Provider interface.
@ -196,13 +181,7 @@ func (m *MachineConfig) Env() config.Env {
// Files implements the config.Provider interface. // Files implements the config.Provider interface.
func (m *MachineConfig) Files() ([]config.File, error) { func (m *MachineConfig) Files() ([]config.File, error) {
files := make([]config.File, len(m.MachineFiles)) return slices.Map(m.MachineFiles, func(f *MachineFile) config.File { return f }), nil
for i := 0; i < len(m.MachineFiles); i++ {
files[i] = m.MachineFiles[i]
}
return files, nil
} }
// Type implements the config.Provider interface. // Type implements the config.Provider interface.
@ -331,17 +310,7 @@ func (k *KubeletConfig) ExtraArgs() map[string]string {
// ExtraMounts implements the config.Provider interface. // ExtraMounts implements the config.Provider interface.
func (k *KubeletConfig) ExtraMounts() []specs.Mount { func (k *KubeletConfig) ExtraMounts() []specs.Mount {
if k.KubeletExtraMounts == nil { return slices.Map(k.KubeletExtraMounts, func(m ExtraMount) specs.Mount { return m.Mount })
return nil
}
out := make([]specs.Mount, len(k.KubeletExtraMounts))
for i := range k.KubeletExtraMounts {
out[i] = k.KubeletExtraMounts[i].Mount
}
return out
} }
// ExtraConfig implements the config.Provider interface. // ExtraConfig implements the config.Provider interface.
@ -476,13 +445,7 @@ func (n *NetworkConfig) DisableSearchDomain() bool {
// Devices implements the config.Provider interface. // Devices implements the config.Provider interface.
func (n *NetworkConfig) Devices() []config.Device { func (n *NetworkConfig) Devices() []config.Device {
interfaces := make([]config.Device, len(n.NetworkInterfaces)) return slices.Map(n.NetworkInterfaces, func(d *Device) config.Device { return d })
for i := 0; i < len(n.NetworkInterfaces); i++ {
interfaces[i] = n.NetworkInterfaces[i]
}
return interfaces
} }
// getDevice adds or returns existing Device by name. // getDevice adds or returns existing Device by name.
@ -511,13 +474,7 @@ func (n *NetworkConfig) Resolvers() []string {
// ExtraHosts implements the config.Provider interface. // ExtraHosts implements the config.Provider interface.
func (n *NetworkConfig) ExtraHosts() []config.ExtraHost { func (n *NetworkConfig) ExtraHosts() []config.ExtraHost {
hosts := make([]config.ExtraHost, len(n.ExtraHostEntries)) return slices.Map(n.ExtraHostEntries, func(e *ExtraHost) config.ExtraHost { return e })
for i := 0; i < len(n.ExtraHostEntries); i++ {
hosts[i] = n.ExtraHostEntries[i]
}
return hosts
} }
// KubeSpan implements the config.Provider interface. // KubeSpan implements the config.Provider interface.
@ -554,13 +511,7 @@ func (d *Device) Addresses() []string {
// Routes implements the MachineNetwork interface. // Routes implements the MachineNetwork interface.
func (d *Device) Routes() []config.Route { func (d *Device) Routes() []config.Route {
routes := make([]config.Route, len(d.DeviceRoutes)) return slices.Map(d.DeviceRoutes, func(r *Route) config.Route { return r })
for i := 0; i < len(d.DeviceRoutes); i++ {
routes[i] = d.DeviceRoutes[i]
}
return routes
} }
// Bond implements the MachineNetwork interface. // Bond implements the MachineNetwork interface.
@ -574,13 +525,7 @@ func (d *Device) Bond() config.Bond {
// Vlans implements the MachineNetwork interface. // Vlans implements the MachineNetwork interface.
func (d *Device) Vlans() []config.Vlan { func (d *Device) Vlans() []config.Vlan {
vlans := make([]config.Vlan, len(d.DeviceVlans)) return slices.Map(d.DeviceVlans, func(v *Vlan) config.Vlan { return v })
for i := 0; i < len(d.DeviceVlans); i++ {
vlans[i] = d.DeviceVlans[i]
}
return vlans
} }
// MTU implements the MachineNetwork interface. // MTU implements the MachineNetwork interface.
@ -720,13 +665,7 @@ func (wc *DeviceWireguardConfig) FirewallMark() int {
// Peers implements the MachineNetwork interface. // Peers implements the MachineNetwork interface.
func (wc *DeviceWireguardConfig) Peers() []config.WireguardPeer { func (wc *DeviceWireguardConfig) Peers() []config.WireguardPeer {
peers := make([]config.WireguardPeer, len(wc.WireguardPeers)) return slices.Map(wc.WireguardPeers, func(p *DeviceWireguardPeer) config.WireguardPeer { return p })
for i := 0; i < len(wc.WireguardPeers); i++ {
peers[i] = wc.WireguardPeers[i]
}
return peers
} }
// PublicKey implements the MachineNetwork interface. // PublicKey implements the MachineNetwork interface.
@ -964,13 +903,7 @@ func (v *Vlan) VIPConfig() config.VIPConfig {
// Routes implements the MachineNetwork interface. // Routes implements the MachineNetwork interface.
func (v *Vlan) Routes() []config.Route { func (v *Vlan) Routes() []config.Route {
routes := make([]config.Route, len(v.VlanRoutes)) return slices.Map(v.VlanRoutes, func(r *Route) config.Route { return r })
for i := 0; i < len(v.VlanRoutes); i++ {
routes[i] = v.VlanRoutes[i]
}
return routes
} }
// DHCP implements the MachineNetwork interface. // DHCP implements the MachineNetwork interface.
@ -1015,17 +948,7 @@ func (i *InstallConfig) Image() string {
// Extensions implements the config.Provider interface. // Extensions implements the config.Provider interface.
func (i *InstallConfig) Extensions() []config.Extension { func (i *InstallConfig) Extensions() []config.Extension {
if len(i.InstallExtensions) == 0 { return slices.Map(i.InstallExtensions, func(e InstallExtensionConfig) config.Extension { return e })
return nil
}
extensions := make([]config.Extension, 0, len(i.InstallExtensions))
for _, ext := range i.InstallExtensions {
extensions = append(extensions, ext)
}
return extensions
} }
// Disk implements the config.Provider interface. // Disk implements the config.Provider interface.
@ -1178,13 +1101,7 @@ func (d *MachineDisk) Device() string {
// Partitions implements the config.Provider interface. // Partitions implements the config.Provider interface.
func (d *MachineDisk) Partitions() []config.Partition { func (d *MachineDisk) Partitions() []config.Partition {
partitions := make([]config.Partition, len(d.DiskPartitions)) return slices.Map(d.DiskPartitions, func(p *DiskPartition) config.Partition { return p })
for i := 0; i < len(d.DiskPartitions); i++ {
partitions[i] = d.DiskPartitions[i]
}
return partitions
} }
// Size implements the config.Provider interface. // Size implements the config.Provider interface.
@ -1224,13 +1141,7 @@ func (e *EncryptionConfig) Options() []string {
// Keys implements the config.Provider interface. // Keys implements the config.Provider interface.
func (e *EncryptionConfig) Keys() []config.EncryptionKey { func (e *EncryptionConfig) Keys() []config.EncryptionKey {
keys := make([]config.EncryptionKey, len(e.EncryptionKeys)) return slices.Map(e.EncryptionKeys, func(k *EncryptionKey) config.EncryptionKey { return k })
for i, key := range e.EncryptionKeys {
keys[i] = key
}
return keys
} }
// Static implements the config.Provider interface. // Static implements the config.Provider interface.

View File

@ -9,6 +9,7 @@ import (
"github.com/talos-systems/talos/pkg/machinery/config" "github.com/talos-systems/talos/pkg/machinery/config"
"github.com/talos-systems/talos/pkg/machinery/constants" "github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// Image implements the config.Scheduler interface. // Image implements the config.Scheduler interface.
@ -29,13 +30,7 @@ func (s *SchedulerConfig) ExtraArgs() map[string]string {
// ExtraVolumes implements the config.Scheduler interface. // ExtraVolumes implements the config.Scheduler interface.
func (s *SchedulerConfig) ExtraVolumes() []config.VolumeMount { func (s *SchedulerConfig) ExtraVolumes() []config.VolumeMount {
volumes := make([]config.VolumeMount, 0, len(s.ExtraVolumesConfig)) return slices.Map(s.ExtraVolumesConfig, func(v VolumeMountConfig) config.VolumeMount { return v })
for _, volume := range s.ExtraVolumesConfig {
volumes = append(volumes, volume)
}
return volumes
} }
// Env implements the config.Scheduler interface. // Env implements the config.Scheduler interface.

View File

@ -74,6 +74,18 @@ func KeysFunc[K comparable, V, R any](m map[K]V, fn func(K) R) []R {
return r return r
} }
// Values returns the values of the map m.
// The values will be in an indeterminate order.
func Values[K comparable, V any](m map[K]V) []V {
r := make([]V, 0, len(m))
for _, v := range m {
r = append(r, v)
}
return r
}
// ValuesFunc applies the function fn to each value of the map m and returns a new slice with the results. // ValuesFunc applies the function fn to each value of the map m and returns a new slice with the results.
// The values will be in an indeterminate order. // The values will be in an indeterminate order.
func ValuesFunc[K comparable, V, R any](m map[K]V, fn func(V) R) []R { func ValuesFunc[K comparable, V, R any](m map[K]V, fn func(V) R) []R {

View File

@ -146,3 +146,15 @@ func IndexFunc[T any](slc []T, fn func(T) bool) int {
func Contains[T any](s []T, fn func(T) bool) bool { func Contains[T any](s []T, fn func(T) bool) bool {
return IndexFunc(s, fn) >= 0 return IndexFunc(s, fn) >= 0
} }
// Copy returns a slice of V with the last n elements removed.
func Copy[S ~[]V, V any](s S, n int) S {
if s == nil {
return nil
}
result := make([]V, n)
copy(result, s)
return result
}

View File

@ -11,6 +11,8 @@ import (
"github.com/cosi-project/runtime/pkg/resource/meta" "github.com/cosi-project/runtime/pkg/resource/meta"
"github.com/cosi-project/runtime/pkg/resource/typed" "github.com/cosi-project/runtime/pkg/resource/typed"
"inet.af/netaddr" "inet.af/netaddr"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// EndpointType is type of Endpoint resource. // EndpointType is type of Endpoint resource.
@ -78,11 +80,5 @@ func (l EndpointList) Merge(endpoint *Endpoint) EndpointList {
// Strings returns a slice of formatted endpoints to string. // Strings returns a slice of formatted endpoints to string.
func (l EndpointList) Strings() []string { func (l EndpointList) Strings() []string {
res := make([]string, len(l)) return slices.Map(l, netaddr.IP.String)
for i := range l {
res[i] = l[i].String()
}
return res
} }

View File

@ -11,6 +11,8 @@ import (
"github.com/cosi-project/runtime/pkg/resource/meta" "github.com/cosi-project/runtime/pkg/resource/meta"
"github.com/cosi-project/runtime/pkg/resource/typed" "github.com/cosi-project/runtime/pkg/resource/typed"
"inet.af/netaddr" "inet.af/netaddr"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// NodeAddressType is type of NodeAddress resource. // NodeAddressType is type of NodeAddress resource.
@ -68,13 +70,7 @@ func (NodeAddressRD) ResourceDefinition(resource.Metadata, NodeAddressSpec) meta
// IPs returns IP without prefix. // IPs returns IP without prefix.
func (spec *NodeAddressSpec) IPs() []netaddr.IP { func (spec *NodeAddressSpec) IPs() []netaddr.IP {
result := make([]netaddr.IP, len(spec.Addresses)) return slices.Map(spec.Addresses, netaddr.IPPrefix.IP)
for i := range spec.Addresses {
result[i] = spec.Addresses[i].IP()
}
return result
} }
// FilteredNodeAddressID returns resource ID for node addresses with filter applied. // FilteredNodeAddressID returns resource ID for node addresses with filter applied.

View File

@ -12,6 +12,8 @@ import (
"github.com/cosi-project/runtime/pkg/resource/meta" "github.com/cosi-project/runtime/pkg/resource/meta"
"github.com/cosi-project/runtime/pkg/resource/typed" "github.com/cosi-project/runtime/pkg/resource/typed"
"inet.af/netaddr" "inet.af/netaddr"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
) )
// CertSANType is type of CertSAN resource. // CertSANType is type of CertSAN resource.
@ -121,13 +123,7 @@ func (spec *CertSANSpec) AppendDNSNames(dnsNames ...string) {
// StdIPs returns a list of converted std.IPs. // StdIPs returns a list of converted std.IPs.
func (spec *CertSANSpec) StdIPs() []net.IP { func (spec *CertSANSpec) StdIPs() []net.IP {
result := make([]net.IP, len(spec.IPs)) return slices.Map(spec.IPs, func(ip netaddr.IP) net.IP { return ip.IPAddr().IP })
for i := range spec.IPs {
result[i] = spec.IPs[i].IPAddr().IP
}
return result
} }
// Sort the CertSANs. // Sort the CertSANs.

View File

@ -7,6 +7,8 @@ package role
import ( import (
"sort" "sort"
"strings" "strings"
"github.com/talos-systems/talos/pkg/machinery/generic/maps"
) )
// Role represents Talos user role. // Role represents Talos user role.
@ -87,12 +89,7 @@ func Parse(str []string) (Set, []string) {
// Strings returns a set as a slice of strings. // Strings returns a set as a slice of strings.
func (s Set) Strings() []string { func (s Set) Strings() []string {
res := make([]string, 0, len(s.roles)) res := maps.KeysFunc(s.roles, func(r Role) string { return string(r) })
for r := range s.roles {
res = append(res, string(r))
}
sort.Strings(res) sort.Strings(res)
return res return res

View File

@ -20,7 +20,7 @@ func TestSet(t *testing.T) {
assert.Equal(t, role.MakeSet(role.Admin, role.Reader, role.Role("os:future"), role.Impersonator), roles) assert.Equal(t, role.MakeSet(role.Admin, role.Reader, role.Role("os:future"), role.Impersonator), roles)
assert.Equal(t, []string{"os:admin", "os:future", "os:impersonator", "os:reader"}, roles.Strings()) assert.Equal(t, []string{"os:admin", "os:future", "os:impersonator", "os:reader"}, roles.Strings())
assert.Equal(t, []string{}, role.MakeSet().Strings()) assert.Equal(t, []string(nil), role.MakeSet().Strings())
assert.True(t, roles.Includes(role.Admin)) assert.True(t, roles.Includes(role.Admin))
assert.False(t, roles.Includes(role.Role("wrong"))) assert.False(t, roles.Includes(role.Role("wrong")))

View File

@ -7,6 +7,7 @@ package access
import ( import (
"github.com/talos-systems/talos/pkg/cluster" "github.com/talos-systems/talos/pkg/cluster"
"github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine" "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/provision" "github.com/talos-systems/talos/pkg/provision"
) )
@ -25,13 +26,7 @@ type infoWrapper struct {
} }
func (wrapper *infoWrapper) Nodes() []string { func (wrapper *infoWrapper) Nodes() []string {
nodes := make([]string, len(wrapper.clusterInfo.Nodes)) return slices.Map(wrapper.clusterInfo.Nodes, func(node provision.NodeInfo) string { return node.IPs[0].String() })
for i := range nodes {
nodes[i] = wrapper.clusterInfo.Nodes[i].IPs[0].String()
}
return nodes
} }
func (wrapper *infoWrapper) NodesByType(t machine.Type) []string { func (wrapper *infoWrapper) NodesByType(t machine.Type) []string {

View File

@ -23,6 +23,7 @@ import (
"github.com/talos-systems/go-blockdevice/blockdevice/partition/gpt" "github.com/talos-systems/go-blockdevice/blockdevice/partition/gpt"
talosnet "github.com/talos-systems/net" talosnet "github.com/talos-systems/net"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/provision" "github.com/talos-systems/talos/pkg/provision"
"github.com/talos-systems/talos/pkg/provision/internal/cniutils" "github.com/talos-systems/talos/pkg/provision/internal/cniutils"
"github.com/talos-systems/talos/pkg/provision/providers/vm" "github.com/talos-systems/talos/pkg/provision/providers/vm"
@ -110,10 +111,7 @@ func withCNI(ctx context.Context, config *LaunchConfig, f func(config *LaunchCon
ips[j] = talosnet.FormatCIDR(config.IPs[j], config.CIDRs[j]) ips[j] = talosnet.FormatCIDR(config.IPs[j], config.CIDRs[j])
} }
gatewayAddrs := make([]string, len(config.GatewayAddrs)) gatewayAddrs := slices.Map(config.GatewayAddrs, net.IP.String)
for j := range gatewayAddrs {
gatewayAddrs[j] = config.GatewayAddrs[j].String()
}
runtimeConf := libcni.RuntimeConf{ runtimeConf := libcni.RuntimeConf{
ContainerID: containerID, ContainerID: containerID,

View File

@ -23,6 +23,7 @@ import (
"github.com/insomniacslk/dhcp/iana" "github.com/insomniacslk/dhcp/iana"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/provision" "github.com/talos-systems/talos/pkg/provision"
) )
@ -260,10 +261,7 @@ func (p *Provisioner) CreateDHCPd(state *State, clusterReq provision.ClusterRequ
return err return err
} }
gatewayAddrs := make([]string, len(clusterReq.Network.GatewayAddrs)) gatewayAddrs := slices.Map(clusterReq.Network.GatewayAddrs, net.IP.String)
for j := range gatewayAddrs {
gatewayAddrs[j] = clusterReq.Network.GatewayAddrs[j].String()
}
args := []string{ args := []string{
"dhcpd-launch", "dhcpd-launch",

View File

@ -21,6 +21,7 @@ import (
"github.com/jsimonetti/rtnetlink" "github.com/jsimonetti/rtnetlink"
talosnet "github.com/talos-systems/net" talosnet "github.com/talos-systems/net"
"github.com/talos-systems/talos/pkg/machinery/generic/slices"
"github.com/talos-systems/talos/pkg/provision" "github.com/talos-systems/talos/pkg/provision"
) )
@ -81,10 +82,7 @@ func (p *Provisioner) CreateNetwork(ctx context.Context, state *State, network p
fakeIPs[j] = talosnet.FormatCIDR(fakeIP, network.CIDRs[j]) fakeIPs[j] = talosnet.FormatCIDR(fakeIP, network.CIDRs[j])
} }
gatewayAddrs := make([]string, len(network.GatewayAddrs)) gatewayAddrs := slices.Map(network.GatewayAddrs, net.IP.String)
for j := range gatewayAddrs {
gatewayAddrs[j] = network.GatewayAddrs[j].String()
}
containerID := uuid.New().String() containerID := uuid.New().String()
runtimeConf := libcni.RuntimeConf{ runtimeConf := libcni.RuntimeConf{