From 37606afecdf013be5de7eb790ac499f2e6d220da Mon Sep 17 00:00:00 2001 From: Jon Cope Date: Thu, 30 Mar 2023 15:31:59 -0500 Subject: [PATCH 1/9] sets.String is deprecated, use the new generic call instead --- .golangci.yaml | 2 +- pkg/components/render_test.go | 1 - pkg/config/lvmd/lvmd.go | 9 -------- pkg/config/lvmd/lvmd_test.go | 1 - pkg/config/lvmd/types.go | 10 --------- pkg/controllers/cluster-policy-controller.go | 5 ++++- pkg/controllers/etcd.go | 2 +- pkg/controllers/infra-services-controller.go | 2 +- pkg/controllers/kube-apiserver.go | 2 +- pkg/controllers/kube-scheduler.go | 4 ---- pkg/controllers/openshift-crd-manager.go | 4 ++-- pkg/controllers/version.go | 3 +-- pkg/loadbalancerservice/controller.go | 13 ++++++----- pkg/mdns/controller.go | 21 +++++++++++------- pkg/mdns/routes.go | 4 +++- pkg/mdns/routes_test.go | 13 ++++++----- pkg/mdns/server/resolver.go | 2 +- pkg/mdns/server/resolver_test.go | 2 +- pkg/mdns/server/server.go | 1 - pkg/servicemanager/manager.go | 8 +++++-- pkg/servicemanager/manager_test.go | 22 +++++++++---------- pkg/util/cert.go | 17 ++++---------- .../cryptomaterial/certchains/certchains.go | 2 +- .../certchains/chainsbuilder.go | 6 ++++- .../certchains/chainsbuilder_test.go | 12 +++++----- .../certchains/signerbuilder.go | 7 ++++++ pkg/util/cryptomaterial/certchains/signers.go | 12 +++++----- .../cryptomaterial/certchains/signers_test.go | 3 +-- pkg/util/cryptomaterial/trustupdates.go | 2 ++ pkg/util/net.go | 3 ++- pkg/util/net_test.go | 9 ++++---- pkg/util/sigchannel/sigchannel_test.go | 2 +- scripts/tools.go | 2 ++ 33 files changed, 100 insertions(+), 108 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 3b1889d603..75ac3b0fe9 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -33,4 +33,4 @@ linters: - unparam - usestdlibvars - wastedassign - - whitespace + - whitespace \ No newline at end of file diff --git a/pkg/components/render_test.go b/pkg/components/render_test.go index 33b1e1fb88..61722d4306 100644 --- a/pkg/components/render_test.go +++ b/pkg/components/render_test.go @@ -17,7 +17,6 @@ import ( ) func Test_renderLvmdParams(t *testing.T) { - iToP := func(i int) *uint64 { r := uint64(i); return &r } type args struct { diff --git a/pkg/config/lvmd/lvmd.go b/pkg/config/lvmd/lvmd.go index a064d0f35f..5f38a43c86 100644 --- a/pkg/config/lvmd/lvmd.go +++ b/pkg/config/lvmd/lvmd.go @@ -43,22 +43,16 @@ func getLvmdConfigForVGs(vgNames []string) (*Lvmd, error) { response := &Lvmd{ SocketName: defaultSockName, } - vgName := "" if len(vgNames) == 0 { - response.Message = errorMessageNoVolumeGroups klog.V(2).Info(errorMessageNoVolumeGroups) return response, nil - } else if len(vgNames) == 1 { - vgName = vgNames[0] klog.V(2).Infof("Using volume group %q", vgName) response.Message = statusMessageDefaultAvailable - } else { - for _, name := range vgNames { if name == defaultRHEL4EdgeVolumeGroup { klog.V(2).Infof("Using default volume group %q", defaultRHEL4EdgeVolumeGroup) @@ -101,14 +95,11 @@ func DefaultLvmdConfig() (*Lvmd, error) { if err != nil { return nil, fmt.Errorf("Failed to discover local volume groups: %s", err) } - return getLvmdConfigForVGs(vgNames) - } // getVolumeGroups returns a slice of volume group names. func getVolumeGroups() ([]string, error) { - cmd := exec.Command("vgs", "--readonly", "--options=name", "--noheadings") output, err := cmd.Output() if err != nil { diff --git a/pkg/config/lvmd/lvmd_test.go b/pkg/config/lvmd/lvmd_test.go index 854117e006..7c210eeac4 100644 --- a/pkg/config/lvmd/lvmd_test.go +++ b/pkg/config/lvmd/lvmd_test.go @@ -110,7 +110,6 @@ func TestGetLvmdConfigForVGs(t *testing.T) { } func Test_newLvmdConfigFromFile(t *testing.T) { - iToP := func(i int) *uint64 { r := uint64(i) return &r diff --git a/pkg/config/lvmd/types.go b/pkg/config/lvmd/types.go index ac22181b7a..2ead7e55ee 100644 --- a/pkg/config/lvmd/types.go +++ b/pkg/config/lvmd/types.go @@ -3,8 +3,6 @@ package lvmd -import "regexp" - type DeviceType string const ( @@ -13,14 +11,6 @@ const ( TypeThick = DeviceType("thick") ) -// This regexp is based on the following validation: -// -// https://github.com/kubernetes/apimachinery/blob/v0.18.3/pkg/util/validation/validation.go#L42 -var qualifiedNameRegexp = regexp.MustCompile("^([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]$") - -// This regexp is used to check StripeSize format -var stripeSizeRegexp = regexp.MustCompile("(?i)^([0-9]*)(k|m|g|t|p|e|b|s)?$") - // ThinPoolConfig holds the configuration of thin pool in a volume group type ThinPoolConfig struct { // Name of thinpool diff --git a/pkg/controllers/cluster-policy-controller.go b/pkg/controllers/cluster-policy-controller.go index 45ae5e9f7f..31041a7842 100644 --- a/pkg/controllers/cluster-policy-controller.go +++ b/pkg/controllers/cluster-policy-controller.go @@ -48,7 +48,10 @@ func (s *ClusterPolicyController) configure(cfg *config.Config) error { s.kubeconfig = cfg.KubeConfigPath(config.ClusterPolicyController) scheme := runtime.NewScheme() - openshiftcontrolplanev1.AddToScheme(scheme) + if err := openshiftcontrolplanev1.AddToScheme(scheme); err != nil { + return err + } + codec := serializer.NewCodecFactory(scheme).LegacyCodec(openshiftcontrolplanev1.GroupVersion) encodedConfig, err := runtime.Encode(codec, diff --git a/pkg/controllers/etcd.go b/pkg/controllers/etcd.go index 9eb612e51d..9ce0d6c9b2 100644 --- a/pkg/controllers/etcd.go +++ b/pkg/controllers/etcd.go @@ -33,7 +33,7 @@ import ( var ( HealthCheckRetries = 10 - HealthCheckWait = time.Duration(3 * time.Second) + HealthCheckWait = 3 * time.Second ) type EtcdService struct { diff --git a/pkg/controllers/infra-services-controller.go b/pkg/controllers/infra-services-controller.go index 7c5f8af766..2218d9faac 100644 --- a/pkg/controllers/infra-services-controller.go +++ b/pkg/controllers/infra-services-controller.go @@ -55,7 +55,7 @@ func (s *InfrastructureServicesManager) Run(ctx context.Context, ready chan<- st } // TO-DO add readiness check - if err := components.StartComponents(s.cfg); err != nil { + if err := components.StartComponents(s.cfg); err != nil { //nolint:contextcheck return err } klog.Infof("%s launched ocp componets", s.Name()) diff --git a/pkg/controllers/kube-apiserver.go b/pkg/controllers/kube-apiserver.go index 6afb60fbf6..e0262b7f55 100644 --- a/pkg/controllers/kube-apiserver.go +++ b/pkg/controllers/kube-apiserver.go @@ -247,7 +247,7 @@ func (s *KubeAPIServer) configure(cfg *config.Config) error { return nil } -func (s *KubeAPIServer) configureAuditPolicy(cfg *config.Config) error { +func (s *KubeAPIServer) configureAuditPolicy(_ *config.Config) error { data := []byte(` apiVersion: audit.k8s.io/v1 kind: Policy diff --git a/pkg/controllers/kube-scheduler.go b/pkg/controllers/kube-scheduler.go index 6c1391a6ce..503b5dfeb0 100644 --- a/pkg/controllers/kube-scheduler.go +++ b/pkg/controllers/kube-scheduler.go @@ -30,10 +30,6 @@ import ( schedulerOptions "k8s.io/kubernetes/cmd/kube-scheduler/app/options" ) -const ( - kubeSchedulerStartupTimeout = 30 -) - type KubeScheduler struct { options *schedulerOptions.Options kubeconfig string diff --git a/pkg/controllers/openshift-crd-manager.go b/pkg/controllers/openshift-crd-manager.go index de328afc89..566ba98075 100644 --- a/pkg/controllers/openshift-crd-manager.go +++ b/pkg/controllers/openshift-crd-manager.go @@ -39,14 +39,14 @@ func (s *OpenShiftCRDManager) Dependencies() []string { return []string{"kube-ap func (s *OpenShiftCRDManager) Run(ctx context.Context, ready chan<- struct{}, stopped chan<- struct{}) error { defer close(stopped) - if err := assets.ApplyCRDs(s.cfg); err != nil { + if err := assets.ApplyCRDs(s.cfg); err != nil { //nolint:contextcheck klog.Errorf("%s unable to apply default CRDs: %v", s.Name(), err) return err } klog.Infof("%s applied default CRDs", s.Name()) klog.Infof("%s waiting for CRDs acceptance before proceeding", s.Name()) - if err := assets.WaitForCrdsEstablished(s.cfg); err != nil { + if err := assets.WaitForCrdsEstablished(s.cfg); err != nil { //nolint:contextcheck klog.Errorf("%s unable to confirm all CRDs are ready: %v", s.Name(), err) } klog.Infof("%s all CRDs are ready", s.Name()) diff --git a/pkg/controllers/version.go b/pkg/controllers/version.go index 4495cbcc8f..c45e74048d 100644 --- a/pkg/controllers/version.go +++ b/pkg/controllers/version.go @@ -40,7 +40,6 @@ func (s *VersionManager) Dependencies() []string { } func (s *VersionManager) Run(ctx context.Context, ready chan<- struct{}, stopped chan<- struct{}) error { - var cm = "version/microshift-version.yaml" defer close(stopped) @@ -54,7 +53,7 @@ func (s *VersionManager) Run(ctx context.Context, ready chan<- struct{}, stopped } kubeConfigPath := s.cfg.KubeConfigPath(config.KubeAdmin) - if err := assets.ApplyConfigMapWithData(cm, data, kubeConfigPath); err != nil { + if err := assets.ApplyConfigMapWithData(cm, data, kubeConfigPath); err != nil { //nolint:contextcheck klog.Warningf("Failed to apply configMap %v, %v", cm, err) return err } diff --git a/pkg/loadbalancerservice/controller.go b/pkg/loadbalancerservice/controller.go index 3b94100ef6..93598a570b 100644 --- a/pkg/loadbalancerservice/controller.go +++ b/pkg/loadbalancerservice/controller.go @@ -54,11 +54,11 @@ func (c *LoadbalancerServiceController) Run(ctx context.Context, ready chan<- st stopCh := make(chan struct{}) defer close(stopCh) - config, err := c.restConfig() + restCfg, err := c.restConfig() if err != nil { return errors.Wrap(err, "error creating rest config for service controller") } - c.client, err = kubernetes.NewForConfig(config) + c.client, err = kubernetes.NewForConfig(restCfg) if err != nil { return errors.Wrap(err, "failed to create clientset for service controller") } @@ -70,15 +70,15 @@ func (c *LoadbalancerServiceController) Run(ctx context.Context, ready chan<- st c.informer = serviceInformer.Informer() c.queue = workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()) c.indexer = c.informer.GetIndexer() - c.informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ + _ , err = c.informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { key, err := cache.MetaNamespaceKeyFunc(obj) if err == nil { c.queue.Add(key) } }, - UpdateFunc: func(old interface{}, new interface{}) { - key, err := cache.MetaNamespaceKeyFunc(new) + UpdateFunc: func(oldObj interface{}, newObj interface{}) { + key, err := cache.MetaNamespaceKeyFunc(newObj) if err == nil { c.queue.Add(key) } @@ -90,6 +90,9 @@ func (c *LoadbalancerServiceController) Run(ctx context.Context, ready chan<- st } }, }) + if err != nil { + return errors.Wrap(err, "failed to initialize informer event handlers") + } factory.Start(stopCh) diff --git a/pkg/mdns/controller.go b/pkg/mdns/controller.go index 29d7231aaf..116066fbda 100644 --- a/pkg/mdns/controller.go +++ b/pkg/mdns/controller.go @@ -2,6 +2,7 @@ package mdns import ( "context" + "fmt" "net" "strings" "sync" @@ -32,8 +33,8 @@ func NewMicroShiftmDNSController(cfg *config.Config) *MicroShiftmDNSController { } } -func (s *MicroShiftmDNSController) Name() string { return "microshift-mdns-controller" } -func (s *MicroShiftmDNSController) Dependencies() []string { +func (c *MicroShiftmDNSController) Name() string { return "microshift-mdns-controller" } +func (c *MicroShiftmDNSController) Dependencies() []string { return []string{"openshift-default-scc-manager"} } @@ -51,14 +52,16 @@ func (c *MicroShiftmDNSController) Run(ctx context.Context, ready chan<- struct{ // i.e. eth0 . We don't believe it's worth going into the complexities (and coupling) // of talking to OpenvSwitch to discover the physical interface(s) on br-ex. And // we have also verified that no duplicate mDNS answers will happen because of this, - // if those were to happend it would be harmless. + // if those were to happened it would be harmless. for n := range ifs { name := ifs[n].Name if ovn.IsOVNKubernetesInternalInterface(name) { continue } klog.Infof("mDNS: Starting server on interface %q, NodeIP %q, NodeName %q", name, c.NodeIP, c.NodeName) - server.New(&ifs[n], c.resolver, c.stopCh) + if _, err := server.New(&ifs[n], c.resolver, c.stopCh); err != nil { + return fmt.Errorf("failed to start server: %w", err) + } } ips := []string{c.NodeIP} @@ -73,16 +76,18 @@ func (c *MicroShiftmDNSController) Run(ctx context.Context, ready chan<- struct{ } c.myIPs = ips - if strings.HasSuffix(c.NodeName, server.DefaultmDNSTLD) { - klog.Infof("mDNS: Host FQDN %q will be announced via mDNS on IPs %q", c.NodeName, ips) c.resolver.AddDomain(c.NodeName+".", ips) } close(ready) - go c.startRouteInformer(c.stopCh) + go func() { + if err := c.startRouteInformer(c.stopCh); err != nil { + klog.Errorf("error running router: %w", err) + } + }() <-ctx.Done() @@ -100,7 +105,7 @@ func ipInAddrs(ip string, addrs []net.Addr) bool { } func addrsToStrings(addrs []net.Addr) []string { - var ipAddrs []string + var ipAddrs = make([]string, 0) for _, a := range addrs { ipAddr, _, _ := net.ParseCIDR(a.String()) diff --git a/pkg/mdns/routes.go b/pkg/mdns/routes.go index dcd95ff8cd..967a6e5999 100644 --- a/pkg/mdns/routes.go +++ b/pkg/mdns/routes.go @@ -54,7 +54,9 @@ func (c *MicroShiftmDNSController) run(stopCh chan struct{}, dc dynamic.Interfac DeleteFunc: c.deletedRoute, } - informer.AddEventHandler(handlers) + if _, err := informer.AddEventHandler(handlers); err != nil { + return errors.Wrap(err, "failed to initialize event handler: %w") + } informer.Run(stopCh) return nil diff --git a/pkg/mdns/routes_test.go b/pkg/mdns/routes_test.go index 57d292eba1..72706918e7 100644 --- a/pkg/mdns/routes_test.go +++ b/pkg/mdns/routes_test.go @@ -3,6 +3,7 @@ package mdns import ( "testing" + "github.com/stretchr/testify/assert" "github.com/openshift/microshift/pkg/mdns/server" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) @@ -26,7 +27,7 @@ func newTestController() *MicroShiftmDNSController { func Test_addedRoute(t *testing.T) { ctl := newTestController() route := &unstructured.Unstructured{Object: make(map[string]interface{})} - unstructured.SetNestedField(route.Object, testRouteHost, "spec", "host") + assert.NoError(t, unstructured.SetNestedField(route.Object, testRouteHost, "spec", "host")) ctl.addedRoute(route) if !ctl.resolver.HasDomain(testRouteHost + ".") { @@ -38,7 +39,7 @@ func Test_deletedRoute(t *testing.T) { ctl := newTestController() route := &unstructured.Unstructured{Object: make(map[string]interface{})} - unstructured.SetNestedField(route.Object, testRouteHost, "spec", "host") + assert.NoError(t, unstructured.SetNestedField(route.Object, testRouteHost, "spec", "host")) ctl.addedRoute(route) ctl.addedRoute(route) ctl.deletedRoute(route) @@ -55,10 +56,10 @@ func Test_deletedRoute(t *testing.T) { func Test_updatedRoute(t *testing.T) { ctl := newTestController() routeOld := &unstructured.Unstructured{Object: make(map[string]interface{})} - unstructured.SetNestedField(routeOld.Object, testRouteHost, "spec", "host") + assert.NoError(t, unstructured.SetNestedField(routeOld.Object, testRouteHost, "spec", "host")) routeNew := &unstructured.Unstructured{Object: make(map[string]interface{})} - unstructured.SetNestedField(routeNew.Object, testRouteHost2, "spec", "host") + assert.NoError(t, unstructured.SetNestedField(routeNew.Object, testRouteHost2, "spec", "host")) ctl.addedRoute(routeOld) ctl.updatedRoute(routeOld, routeNew) @@ -75,10 +76,10 @@ func Test_updatedRoute(t *testing.T) { func Test_updatedRouteDupHost(t *testing.T) { ctl := newTestController() routeOld := &unstructured.Unstructured{Object: make(map[string]interface{})} - unstructured.SetNestedField(routeOld.Object, testRouteHost, "spec", "host") + assert.NoError(t, unstructured.SetNestedField(routeOld.Object, testRouteHost, "spec", "host")) routeNew := &unstructured.Unstructured{Object: make(map[string]interface{})} - unstructured.SetNestedField(routeNew.Object, testRouteHost2, "spec", "host") + assert.NoError(t, unstructured.SetNestedField(routeNew.Object, testRouteHost2, "spec", "host")) ctl.addedRoute(routeOld) ctl.addedRoute(routeOld) // two routes with the same hostname diff --git a/pkg/mdns/server/resolver.go b/pkg/mdns/server/resolver.go index 6f89a2afb7..179c05e704 100644 --- a/pkg/mdns/server/resolver.go +++ b/pkg/mdns/server/resolver.go @@ -38,7 +38,7 @@ func NewResolver() *Resolver { func (r *Resolver) AddDomain(name string, ipStrs []string) { r.Lock() defer r.Unlock() - var ips []net.IP + var ips = make([]net.IP, 0) for _, ip := range ipStrs { ips = append(ips, net.ParseIP(ip)) diff --git a/pkg/mdns/server/resolver_test.go b/pkg/mdns/server/resolver_test.go index 3eb9746ce0..678786ed3f 100644 --- a/pkg/mdns/server/resolver_test.go +++ b/pkg/mdns/server/resolver_test.go @@ -56,8 +56,8 @@ func TestResolver_DeleteDomain(t *testing.T) { if len(res) != 0 { t.Errorf("With no domains resolver should not respond, but it did: %+v", res) } - } + func testResolverDomainTypeAddress(t *testing.T, r *Resolver, name string, qtype uint16, addr string) { res := r.Answer(dns.Question{Qtype: qtype, Name: name}) diff --git a/pkg/mdns/server/server.go b/pkg/mdns/server/server.go index 17a163efcb..a11a4f8013 100644 --- a/pkg/mdns/server/server.go +++ b/pkg/mdns/server/server.go @@ -125,7 +125,6 @@ func (s *Server) handlemDNSPacket(conn *net.UDPConn, packet []byte, from net.Add } func (s *Server) sendmDNSResponse(conn *net.UDPConn, resp *dns.Msg, from net.Addr, unicast bool) error { - destAddr := from.(*net.UDPAddr) buf, err := resp.Pack() diff --git a/pkg/servicemanager/manager.go b/pkg/servicemanager/manager.go index 37ee6b4e13..f0356b95f6 100644 --- a/pkg/servicemanager/manager.go +++ b/pkg/servicemanager/manager.go @@ -104,7 +104,9 @@ func (m *ServiceManager) asyncRun(ctx context.Context, service Service) (<-chan if r := recover(); r != nil { klog.Errorf("%s panicked: %s", service.Name(), r) klog.Error("Stopping MicroShift") - syscall.Kill(syscall.Getpid(), syscall.SIGTERM) + if err := syscall.Kill(syscall.Getpid(), syscall.SIGTERM); err != nil { + klog.Warningf("error killing process: %w", err) + } if !sigchannel.IsClosed(stopped) { close(stopped) } @@ -114,7 +116,9 @@ func (m *ServiceManager) asyncRun(ctx context.Context, service Service) (<-chan klog.Infof("Starting %s", service.Name()) if err := service.Run(ctx, ready, stopped); err != nil && !errors.Is(err, context.Canceled) { klog.Errorf("service %s exited with error: %s, stopping MicroShift", service.Name(), err) - syscall.Kill(syscall.Getpid(), syscall.SIGTERM) + if err := syscall.Kill(syscall.Getpid(), syscall.SIGTERM); err != nil { + klog.Warningf("error killing process: %w", err) + } } else { klog.Infof("%s completed", service.Name()) } diff --git a/pkg/servicemanager/manager_test.go b/pkg/servicemanager/manager_test.go index f12f894596..127f1eaf91 100644 --- a/pkg/servicemanager/manager_test.go +++ b/pkg/servicemanager/manager_test.go @@ -11,6 +11,7 @@ import ( "time" "github.com/openshift/microshift/pkg/util/sigchannel" + "github.com/stretchr/testify/assert" ) type serviceTest struct { @@ -75,8 +76,8 @@ func TestRunToCompletion(t *testing.T) { } m := NewServiceManager() - m.AddService(NewGenericService("foo", nil, runToCompletionFunc)) - m.AddService(NewGenericService("bar", []string{"foo"}, runToCompletionFunc)) + assert.NoError(t, m.AddService(NewGenericService("foo", nil, runToCompletionFunc))) + assert.NoError(t, m.AddService(NewGenericService("bar", []string{"foo"}, runToCompletionFunc))) wg.Add(2) ctx, cancel := context.WithCancel(context.Background()) @@ -110,14 +111,14 @@ func TestRunCancellation(t *testing.T) { } m := NewServiceManager() - m.AddService(NewGenericService("foo", nil, runToCompletionFunc)) - m.AddService(NewGenericService("bar", []string{"foo"}, runToCompletionFunc)) + assert.NoError(t, m.AddService(NewGenericService("foo", nil, runToCompletionFunc))) + assert.NoError(t, m.AddService(NewGenericService("bar", []string{"foo"}, runToCompletionFunc))) wg.Add(2) ctx, cancel := context.WithCancel(context.Background()) ready, stopped := make(chan struct{}), make(chan struct{}) go func() { - m.Run(ctx, ready, stopped) + assert.NoError(t, m.Run(ctx, ready, stopped)) }() select { @@ -150,8 +151,8 @@ func TestRunToServiceCrash(t *testing.T) { } m := NewServiceManager() - m.AddService(NewGenericService("foo", nil, waitForContext)) - m.AddService(NewGenericService("bar-crash", []string{"foo"}, runAndPanic)) + assert.NoError(t, m.AddService(NewGenericService("foo", nil, waitForContext))) + assert.NoError(t, m.AddService(NewGenericService("bar-crash", []string{"foo"}, runAndPanic))) wg.Add(2) ctx, cancel := context.WithCancel(context.Background()) @@ -203,14 +204,11 @@ func TestRunToServicePanic(t *testing.T) { <-time.After(time.Second) wg.Done() panic("I'm in panic") - } - m := NewServiceManager() - m.AddService(NewGenericService("foo", nil, waitForContext)) - m.AddService(NewGenericService("bar-panic", []string{"foo"}, runAndCrash)) + assert.NoError(t, m.AddService(NewGenericService("foo", nil, waitForContext))) + assert.NoError(t, m.AddService(NewGenericService("bar-panic", []string{"foo"}, runAndCrash))) wg.Add(2) - ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/pkg/util/cert.go b/pkg/util/cert.go index 1ee6d6dd50..45bfab6d67 100644 --- a/pkg/util/cert.go +++ b/pkg/util/cert.go @@ -22,23 +22,12 @@ import ( "encoding/pem" "fmt" "os" - "time" "github.com/pkg/errors" "k8s.io/client-go/util/keyutil" ) -const ( - defaultDurationDays = 365 - defaultDuration = defaultDurationDays * 24 * time.Hour - defaultHostname = "localhost" - - keySize = 2048 - - ValidityOneDay = 24 * time.Hour - ValidityOneYear = 365 * ValidityOneDay - ValidityTenYears = 10 * ValidityOneYear -) +const keySize = 2048 func EnsureKeyPair(pubKeyPath, privKeyPath string) error { if _, err := getKeyPair(pubKeyPath, privKeyPath); err == nil { @@ -69,7 +58,9 @@ func GenKeys(pubPath, keyPath string) error { return fmt.Errorf("failed to write the private key to %s: %v", keyPath, err) } - os.WriteFile(pubPath, pubPEM, 0400) + if err := os.WriteFile(pubPath, pubPEM, 0400); err != nil { + return fmt.Errorf("failed to write public key to %s: %v", pubPath, err) + } return nil } diff --git a/pkg/util/cryptomaterial/certchains/certchains.go b/pkg/util/cryptomaterial/certchains/certchains.go index ef7b287c0f..939062f70a 100644 --- a/pkg/util/cryptomaterial/certchains/certchains.go +++ b/pkg/util/cryptomaterial/certchains/certchains.go @@ -74,6 +74,7 @@ func (cs *CertificateChains) WalkChains(rootPath []string, fn CertWalkFunc) erro return nil } + //nolint:nestif if signer := cs.GetSigner(rootPath...); signer != nil { // the path points to a signer if err := fn(rootPath, *signer.signerConfig.Config.Certs[0]); err != nil { @@ -87,7 +88,6 @@ func (cs *CertificateChains) WalkChains(rootPath []string, fn CertWalkFunc) erro } } return nil - } else if len(rootPath) == 1 { // the path is a single element but no such signer exists return fmt.Errorf("%v is not a path to a signer", rootPath) diff --git a/pkg/util/cryptomaterial/certchains/chainsbuilder.go b/pkg/util/cryptomaterial/certchains/chainsbuilder.go index ed70000126..dc6311af56 100644 --- a/pkg/util/cryptomaterial/certchains/chainsbuilder.go +++ b/pkg/util/cryptomaterial/certchains/chainsbuilder.go @@ -19,6 +19,7 @@ type certificateChains struct { fileBundles map[string][][]string } +//nolint:ireturn func NewCertificateChains(signers ...CertificateSignerBuilder) CertificateChainsBuilder { return &certificateChains{ signers: signers, @@ -27,16 +28,19 @@ func NewCertificateChains(signers ...CertificateSignerBuilder) CertificateChains } } +//nolint:ireturn func (cs *certificateChains) WithSigners(signers ...CertificateSignerBuilder) CertificateChainsBuilder { cs.signers = append(cs.signers, signers...) return cs } +//nolint:ireturn func (cs *certificateChains) WithCABundle(bundlePath string, signerNames ...[]string) CertificateChainsBuilder { cs.fileBundles[bundlePath] = signerNames return cs } +//nolint:ireturn func (cs *certificateChains) Complete() (*CertificateChains, error) { completeChains := &CertificateChains{ signers: make(map[string]*CertificateSigner), @@ -46,7 +50,7 @@ func (cs *certificateChains) Complete() (*CertificateChains, error) { // and cert validity time when they exceed 5 and 2 years // respectively. This is not configurable and the introduction // of such a possibility involves changing the API in a massively - // used library accross OpenShift. Temporarily disable stderr as + // used library across OpenShift. Temporarily disable stderr as // a shortcut to clean logs. newstderr, err := os.Open("/dev/null") if err == nil { diff --git a/pkg/util/cryptomaterial/certchains/chainsbuilder_test.go b/pkg/util/cryptomaterial/certchains/chainsbuilder_test.go index 78d5116f86..3f2c687fda 100644 --- a/pkg/util/cryptomaterial/certchains/chainsbuilder_test.go +++ b/pkg/util/cryptomaterial/certchains/chainsbuilder_test.go @@ -24,7 +24,7 @@ func Test_certificateChains_Complete(t *testing.T) { name string testChains CertificateChainsBuilder testClientPaths map[string]user.Info - testServerPaths map[string]sets.String + testServerPaths map[string]sets.Set[string] wantSigners []string wantErr bool }{ @@ -62,8 +62,8 @@ func Test_certificateChains_Complete(t *testing.T) { "test-signer1/test-client2": &user.DefaultInfo{Name: "test-user2"}, "test-signer1/test-client": nil, }, - testServerPaths: map[string]sets.String{ - "test-signer2/test-server1": sets.NewString("somewhere.over.the.rainbow", "bluebirds.fly"), + testServerPaths: map[string]sets.Set[string]{ + "test-signer2/test-server1": sets.New[string]("somewhere.over.the.rainbow", "bluebirds.fly"), }, }, } @@ -116,11 +116,11 @@ func Test_certificateChains_Complete(t *testing.T) { gotCert := pemToCert(t, gotPEM) - if cn := gotCert.Subject.CommonName; cn != expectedHostnames.List()[0] { - t.Errorf("expected certificate CN at path %q to be %q, but it is %q", path, expectedHostnames.List()[0], cn) + if cn := gotCert.Subject.CommonName; cn != sets.List[string](expectedHostnames)[0] { + t.Errorf("expected certificate CN at path %q to be %q, but it is %q", path, sets.List[string](expectedHostnames)[0], cn) } - expectedIPs, expectedDNSes := crypto.IPAddressesDNSNames(expectedHostnames.List()) + expectedIPs, expectedDNSes := crypto.IPAddressesDNSNames(sets.List[string](expectedHostnames)) if !equality.Semantic.DeepEqual(gotCert.IPAddresses, expectedIPs) || !equality.Semantic.DeepEqual(gotCert.DNSNames, expectedDNSes) { t.Errorf("extected certificate at path %q to have IPs %v and DNS names %v, but got %v and %v", path, expectedIPs, expectedDNSes, gotCert.IPAddresses, gotCert.DNSNames) } diff --git a/pkg/util/cryptomaterial/certchains/signerbuilder.go b/pkg/util/cryptomaterial/certchains/signerbuilder.go index 1249ba663a..8e037b093f 100644 --- a/pkg/util/cryptomaterial/certchains/signerbuilder.go +++ b/pkg/util/cryptomaterial/certchains/signerbuilder.go @@ -43,6 +43,7 @@ type certificateSigner struct { } // NewCertificateSigner returns a builder object for a certificate chain for the given signer +//nolint:ireturn func NewCertificateSigner(signerName, signerDir string, validityDays int) CertificateSignerBuilder { return &certificateSigner{ signerName: signerName, @@ -58,16 +59,19 @@ func (s *certificateSigner) ValidityDays() int { return s.signerValidityDays } // WithSignerConfig uses the provided configuration in `config` to sign its // direct certificates. // This is useful when creating intermediate signers. +//nolint:ireturn func (s *certificateSigner) WithSignerConfig(config *crypto.CA) CertificateSignerBuilder { s.signerConfig = config return s } +//nolint:ireturn func (s *certificateSigner) WithCABundlePaths(bundlePaths ...string) CertificateSignerBuilder { s.caBundlePaths = append(s.caBundlePaths, bundlePaths...) return s } +//nolint:ireturn func (s *certificateSigner) WithClientCertificates(signInfos ...*ClientCertificateSigningRequestInfo) CertificateSignerBuilder { for _, signInfo := range signInfos { s.certificatesToSign = append(s.certificatesToSign, signInfo) @@ -75,6 +79,7 @@ func (s *certificateSigner) WithClientCertificates(signInfos ...*ClientCertifica return s } +//nolint:ireturn func (s *certificateSigner) WithServingCertificates(signInfos ...*ServingCertificateSigningRequestInfo) CertificateSignerBuilder { for _, signInfo := range signInfos { s.certificatesToSign = append(s.certificatesToSign, signInfo) @@ -82,6 +87,7 @@ func (s *certificateSigner) WithServingCertificates(signInfos ...*ServingCertifi return s } +//nolint:ireturn func (s *certificateSigner) WithPeerCertificiates(signInfos ...*PeerCertificateSigningRequestInfo) CertificateSignerBuilder { for _, signInfo := range signInfos { s.certificatesToSign = append(s.certificatesToSign, signInfo) @@ -89,6 +95,7 @@ func (s *certificateSigner) WithPeerCertificiates(signInfos ...*PeerCertificateS return s } +//nolint:ireturn func (s *certificateSigner) WithSubCAs(subCAsInfo ...CertificateSignerBuilder) CertificateSignerBuilder { s.subCAs = append(s.subCAs, subCAsInfo...) return s diff --git a/pkg/util/cryptomaterial/certchains/signers.go b/pkg/util/cryptomaterial/certchains/signers.go index 001861693b..2422865f1b 100644 --- a/pkg/util/cryptomaterial/certchains/signers.go +++ b/pkg/util/cryptomaterial/certchains/signers.go @@ -58,7 +58,7 @@ type CertificateSigner struct { subCAs map[string]*CertificateSigner signedCertificates map[string]*signedCertificateInfo - caBundlePaths sets.String + caBundlePaths sets.String //nolint:staticcheck } type signedCertificateInfo struct { @@ -185,9 +185,7 @@ func (s *CertificateSigner) AddToBundles(bundlePaths ...string) error { var certsChanged, certFound bool for i, c := range certs { - if c.Subject.String() == cert.Subject.String() && - c.Issuer.String() == cert.Issuer.String() { - + if c.Subject.String() == cert.Subject.String() && c.Issuer.String() == cert.Issuer.String() { certFound = true if c.SerialNumber != cert.SerialNumber { certs[i] = cert @@ -230,7 +228,7 @@ func (s *CertificateSigner) AddToBundles(bundlePaths ...string) error { return nil } -func (s *CertificateSigner) toBuilder() CertificateSignerBuilder { +func (s *CertificateSigner) toBuilder() CertificateSignerBuilder { //nolint:ireturn signer := NewCertificateSigner(s.signerName, s.signerDir, s.signerValidityDays) for _, subCA := range s.subCAs { @@ -437,7 +435,7 @@ func signedCertificateInfoMapKeysOrdered(stringMap map[string]*signedCertificate // libraryGoEnsureSubCA comes from lib-go 4.12, use (ca *CA) EnsureSubCA from there once we get the updated lib-go func libraryGoEnsureSubCA(ca *crypto.CA, certFile, keyFile, serialFile, name string, expireDays int) (*crypto.CA, bool, error) { if subCA, err := crypto.GetCA(certFile, keyFile, serialFile); err == nil { - return subCA, false, err + return subCA, false, nil } subCA, err := libraryGoMakeAndWriteSubCA(ca, certFile, keyFile, serialFile, name, expireDays) return subCA, true, err @@ -459,7 +457,7 @@ func libraryGoMakeAndWriteSubCA(ca *crypto.CA, certFile, keyFile, serialFile, na var serialGenerator crypto.SerialGenerator if len(serialFile) > 0 { // create / overwrite the serial file with a zero padded hex value (ending in a newline to have a valid file) - if err := os.WriteFile(serialFile, []byte("00\n"), 0644); err != nil { + if err := os.WriteFile(serialFile, []byte("00\n"), 0644); err != nil {//nolint:gosec return nil, err } diff --git a/pkg/util/cryptomaterial/certchains/signers_test.go b/pkg/util/cryptomaterial/certchains/signers_test.go index 2548319312..08dceb1938 100644 --- a/pkg/util/cryptomaterial/certchains/signers_test.go +++ b/pkg/util/cryptomaterial/certchains/signers_test.go @@ -69,7 +69,6 @@ func Test_certificateSigner_Complete(t *testing.T) { } if gotSubCANames := got.GetSubCANames(); !reflect.DeepEqual(gotSubCANames, tt.wantSubCAs) { t.Errorf("the completed signer sub-CA names = %v, want %v", gotSubCANames, tt.wantSubCAs) - } }) } @@ -130,7 +129,7 @@ func TestCertificateSigner_Regenerate(t *testing.T) { ), ), ) - + //nolint:errcheck filepath.Walk(tmpDir, func(name string, info os.FileInfo, err error) error { fmt.Println(name) return nil diff --git a/pkg/util/cryptomaterial/trustupdates.go b/pkg/util/cryptomaterial/trustupdates.go index ac8e37403c..eb0cdf6853 100644 --- a/pkg/util/cryptomaterial/trustupdates.go +++ b/pkg/util/cryptomaterial/trustupdates.go @@ -19,7 +19,9 @@ func AppendCertsToFile(bundlePath string, certs ...[]byte) error { defer f.Close() for _, c := range certs { + // nolint:errcheck f.WriteString("\n") + // nolint:errcheck f.Write(c) } diff --git a/pkg/util/net.go b/pkg/util/net.go index 4bc32dc327..f59d60f2c7 100644 --- a/pkg/util/net.go +++ b/pkg/util/net.go @@ -60,7 +60,7 @@ func RetryInsecureGet(url string) int { c := http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{ - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec }, }, } @@ -69,6 +69,7 @@ func RetryInsecureGet(url string) int { status = resp.StatusCode return true, nil } + defer resp.Body.Close() //nolint:errcheck return false, nil }) diff --git a/pkg/util/net_test.go b/pkg/util/net_test.go index 1ead81b1a6..4c863ffd32 100644 --- a/pkg/util/net_test.go +++ b/pkg/util/net_test.go @@ -9,8 +9,7 @@ import ( func TestAddToNoProxyEnv(t *testing.T) { clearNoProxy() - AddToNoProxyEnv(".svc", "10.40.0.0/16") - + assert.NoError(t, AddToNoProxyEnv(".svc", "10.40.0.0/16")) assert.Equal(t, ".svc,10.40.0.0/16", os.Getenv("NO_PROXY"), "NO_PROXY has unexpected value") assert.Equal(t, "", os.Getenv("no_proxy"), "no_proxy expected to be empty") clearNoProxy() @@ -24,7 +23,7 @@ func clearNoProxy() { func TestAddToNoProxyEnv_with_contents(t *testing.T) { os.Setenv("NO_PROXY", "my.host.local") os.Setenv("no_proxy", "") - AddToNoProxyEnv(".svc", "10.40.0.0/16") + assert.NoError(t, AddToNoProxyEnv(".svc", "10.40.0.0/16")) assert.Equal(t, ".svc,10.40.0.0/16,my.host.local", os.Getenv("NO_PROXY"), "NO_PROXY has unexpected value") assert.Equal(t, "", os.Getenv("no_proxy"), "no_proxy expected to be empty") @@ -34,7 +33,7 @@ func TestAddToNoProxyEnv_with_contents(t *testing.T) { func TestAddToNoProxyEnv_with_dups(t *testing.T) { os.Setenv("NO_PROXY", "my.host.local") os.Setenv("no_proxy", "my.host.local") - AddToNoProxyEnv(".svc", "10.40.0.0/16") + assert.NoError(t, AddToNoProxyEnv(".svc", "10.40.0.0/16")) assert.Equal(t, ".svc,10.40.0.0/16,my.host.local", os.Getenv("NO_PROXY"), "NO_PROXY has unexpected value") assert.Equal(t, "", os.Getenv("no_proxy"), "no_proxy expected to be empty") @@ -44,7 +43,7 @@ func TestAddToNoProxyEnv_with_dups(t *testing.T) { func TestAddToNoProxyEnv_with_both(t *testing.T) { os.Setenv("NO_PROXY", "my.host.local") os.Setenv("no_proxy", "another.host.local") - AddToNoProxyEnv(".svc", "10.40.0.0/16") + assert.NoError(t, AddToNoProxyEnv(".svc", "10.40.0.0/16")) assert.Equal(t, ".svc,10.40.0.0/16,another.host.local,my.host.local", os.Getenv("NO_PROXY"), "NO_PROXY has unexpected value") assert.Equal(t, "", os.Getenv("no_proxy"), "no_proxy expected to be empty") diff --git a/pkg/util/sigchannel/sigchannel_test.go b/pkg/util/sigchannel/sigchannel_test.go index 458e189fee..ddca80a79e 100644 --- a/pkg/util/sigchannel/sigchannel_test.go +++ b/pkg/util/sigchannel/sigchannel_test.go @@ -77,7 +77,7 @@ func TestAnd(t *testing.T) { t.Errorf("And() on closed channels returned 'true' expected 'false'") } return - case <-time.After(time.Duration(time.Second * 5)): + case <-time.After(time.Second * 5): t.Errorf("timed out waiting for And() to close channels") return } diff --git a/scripts/tools.go b/scripts/tools.go index 495f9db2a4..0e4264cd85 100644 --- a/scripts/tools.go +++ b/scripts/tools.go @@ -1,4 +1,6 @@ // Package tools imports things required by build scripts, to force `go mod` to see them as dependencies +// +build tools + package tools import ( From 084fbdeb9377f684559f91118943c8fabbc31338 Mon Sep 17 00:00:00 2001 From: Jon Cope Date: Fri, 31 Mar 2023 11:18:00 -0500 Subject: [PATCH 2/9] detangle nested ifs Signed-off-by: Jon Cope --- pkg/config/config.go | 4 +--- .../cryptomaterial/certchains/certchains.go | 24 +++++++++---------- .../certchains/chainsbuilder_test.go | 2 +- 3 files changed, 13 insertions(+), 17 deletions(-) diff --git a/pkg/config/config.go b/pkg/config/config.go index 26e0c71b40..1b58c2b093 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -55,7 +55,6 @@ func NewDefault() *Config { // probing the environment, the values in the Config instance are not // changed. func (c *Config) fillDefaults() error { - // Look up any values that may generate an error subjectAltNames, err := getAllHostnames() if err != nil { @@ -150,7 +149,6 @@ func (c *Config) incorporateUserSettings(u *Config) { if u.Node.NodeIP != "" { c.Node.NodeIP = u.Node.NodeIP } - if len(u.ApiServer.SubjectAltNames) != 0 { c.ApiServer.SubjectAltNames = u.ApiServer.SubjectAltNames } @@ -170,7 +168,6 @@ func (c *Config) incorporateUserSettings(u *Config) { // inputs to more easily consumable units or fills in any defaults // computed based on the values of other settings. func (c *Config) updateComputedValues() error { - clusterDNS, err := c.computeClusterDNS() if err != nil { return err @@ -206,6 +203,7 @@ func (c *Config) updateComputedValues() error { } func (c *Config) validate() error { + //nolint:nestifs // extracting the nested ifs will just increase the complexity of the if expressions as validation expands if len(c.ApiServer.SubjectAltNames) > 0 { // Any entry in SubjectAltNames will be included in the external access certificates. // Any of the hostnames and IPs (except the node IP) listed below conflicts with diff --git a/pkg/util/cryptomaterial/certchains/certchains.go b/pkg/util/cryptomaterial/certchains/certchains.go index 939062f70a..912c251e05 100644 --- a/pkg/util/cryptomaterial/certchains/certchains.go +++ b/pkg/util/cryptomaterial/certchains/certchains.go @@ -74,7 +74,6 @@ func (cs *CertificateChains) WalkChains(rootPath []string, fn CertWalkFunc) erro return nil } - //nolint:nestif if signer := cs.GetSigner(rootPath...); signer != nil { // the path points to a signer if err := fn(rootPath, *signer.signerConfig.Config.Certs[0]); err != nil { @@ -88,22 +87,21 @@ func (cs *CertificateChains) WalkChains(rootPath []string, fn CertWalkFunc) erro } } return nil - } else if len(rootPath) == 1 { + } + if len(rootPath) == 1 { // the path is a single element but no such signer exists return fmt.Errorf("%v is not a path to a signer", rootPath) - } else { - // the path points to a leaf certificate - signerPath := rootPath[:len(rootPath)-1] - if signer := cs.GetSigner(signerPath...); signer != nil { - cert := signer.signedCertificates[rootPath[len(rootPath)-1]] - if cert == nil { - return fmt.Errorf("the requested element does not exist") - } - return fn(rootPath, *cert.tlsConfig.Certs[0]) + } + // the path points to a leaf certificate + signerPath := rootPath[:len(rootPath)-1] + if signer := cs.GetSigner(signerPath...); signer != nil { + cert := signer.signedCertificates[rootPath[len(rootPath)-1]] + if cert == nil { + return fmt.Errorf("the requested element does not exist") } - - return fmt.Errorf("a non-leaf fragment of the path '%v' either is not a signer or it doesn't exist", rootPath) + return fn(rootPath, *cert.tlsConfig.Certs[0]) } + return fmt.Errorf("a non-leaf fragment of the path '%v' either is not a signer or it doesn't exist", rootPath) } func WhenToRotateAtEarliest(cs *CertificateChains) ([]string, time.Time, error) { diff --git a/pkg/util/cryptomaterial/certchains/chainsbuilder_test.go b/pkg/util/cryptomaterial/certchains/chainsbuilder_test.go index 3f2c687fda..377464fe49 100644 --- a/pkg/util/cryptomaterial/certchains/chainsbuilder_test.go +++ b/pkg/util/cryptomaterial/certchains/chainsbuilder_test.go @@ -116,7 +116,7 @@ func Test_certificateChains_Complete(t *testing.T) { gotCert := pemToCert(t, gotPEM) - if cn := gotCert.Subject.CommonName; cn != sets.List[string](expectedHostnames)[0] { + if cn := gotCert.Subject.CommonName; cn != sets.List[string](expectedHostnames)[0] { t.Errorf("expected certificate CN at path %q to be %q, but it is %q", path, sets.List[string](expectedHostnames)[0], cn) } From 68f74f8772ddb6dd530964a715a2dc5995f0ae87 Mon Sep 17 00:00:00 2001 From: Jon Cope Date: Fri, 31 Mar 2023 13:24:38 -0500 Subject: [PATCH 3/9] plumb context through kube client callers use Set generics over deprecated Set types --- pkg/assets/applier.go | 3 +- pkg/assets/apps.go | 20 +++---- pkg/assets/core.go | 48 ++++++++--------- pkg/assets/crd.go | 18 +++---- pkg/assets/rbac.go | 36 ++++++------- pkg/assets/scc.go | 16 +++--- pkg/assets/scheduling.go | 16 +++--- pkg/assets/storage.go | 24 ++++----- pkg/cmd/run.go | 8 +-- pkg/components/components.go | 13 ++--- pkg/components/controllers.go | 54 ++++++++++--------- pkg/components/networking.go | 17 +++--- pkg/components/storage.go | 27 +++++----- pkg/controllers/infra-services-controller.go | 12 ++--- pkg/controllers/kube-controller-manager.go | 8 +-- .../kube-controller-manager_test.go | 3 +- pkg/controllers/openshift-crd-manager.go | 4 +- .../openshift-default-scc-manager.go | 10 ++-- .../openshift-route-controller-manager.go | 12 ++--- pkg/controllers/version.go | 2 +- .../certchains/signerbuilder.go | 7 +-- pkg/util/cryptomaterial/certchains/signers.go | 6 +-- 22 files changed, 186 insertions(+), 178 deletions(-) diff --git a/pkg/assets/applier.go b/pkg/assets/applier.go index 9dab7b4707..b5f40d8c71 100644 --- a/pkg/assets/applier.go +++ b/pkg/assets/applier.go @@ -1,6 +1,7 @@ package assets import ( + "context" "sync" "github.com/openshift/library-go/pkg/operator/events" @@ -18,5 +19,5 @@ type RenderFunc func([]byte, RenderParams) ([]byte, error) type readerApplier interface { Reader([]byte, RenderFunc, RenderParams) - Applier() error + Applier(ctx context.Context) error } diff --git a/pkg/assets/apps.go b/pkg/assets/apps.go index de15124289..37826a8b80 100644 --- a/pkg/assets/apps.go +++ b/pkg/assets/apps.go @@ -57,8 +57,8 @@ func (d *dpApplier) Reader(objBytes []byte, render RenderFunc, params RenderPara d.dp = obj.(*appsv1.Deployment) } -func (d *dpApplier) Applier() error { - _, _, err := resourceapply.ApplyDeployment(context.TODO(), d.Client, assetsEventRecorder, d.dp, 0) +func (d *dpApplier) Applier(ctx context.Context) error { + _, _, err := resourceapply.ApplyDeployment(ctx, d.Client, assetsEventRecorder, d.dp, 0) return err } @@ -81,12 +81,12 @@ func (d *dsApplier) Reader(objBytes []byte, render RenderFunc, params RenderPara } d.ds = obj.(*appsv1.DaemonSet) } -func (d *dsApplier) Applier() error { - _, _, err := resourceapply.ApplyDaemonSet(context.TODO(), d.Client, assetsEventRecorder, d.ds, 0) +func (d *dsApplier) Applier(ctx context.Context) error { + _, _, err := resourceapply.ApplyDaemonSet(ctx, d.Client, assetsEventRecorder, d.ds, 0) return err } -func applyApps(apps []string, applier readerApplier, render RenderFunc, params RenderParams) error { +func applyApps(ctx context.Context, apps []string, applier readerApplier, render RenderFunc, params RenderParams) error { lock.Lock() defer lock.Unlock() @@ -97,7 +97,7 @@ func applyApps(apps []string, applier readerApplier, render RenderFunc, params R return fmt.Errorf("error getting asset %s: %v", app, err) } applier.Reader(objBytes, render, params) - if err := applier.Applier(); err != nil { + if err := applier.Applier(ctx); err != nil { klog.Warningf("Failed to apply apps api %s: %v", app, err) return err } @@ -106,14 +106,14 @@ func applyApps(apps []string, applier readerApplier, render RenderFunc, params R return nil } -func ApplyDeployments(dps []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { +func ApplyDeployments(ctx context.Context, dps []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { dp := &dpApplier{} dp.Client = appsClient(kubeconfigPath) - return applyApps(dps, dp, render, params) + return applyApps(ctx, dps, dp, render, params) } -func ApplyDaemonSets(apps []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { +func ApplyDaemonSets(ctx context.Context, apps []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { ds := &dsApplier{} ds.Client = appsClient(kubeconfigPath) - return applyApps(apps, ds, render, params) + return applyApps(ctx, apps, ds, render, params) } diff --git a/pkg/assets/core.go b/pkg/assets/core.go index 6a915b1773..373bee9a24 100644 --- a/pkg/assets/core.go +++ b/pkg/assets/core.go @@ -57,8 +57,8 @@ func (ns *nsApplier) Reader(objBytes []byte, render RenderFunc, params RenderPar ns.ns = obj.(*corev1.Namespace) } -func (ns *nsApplier) Applier() error { - _, _, err := resourceapply.ApplyNamespace(context.TODO(), ns.Client, assetsEventRecorder, ns.ns) +func (ns *nsApplier) Applier(ctx context.Context) error { + _, _, err := resourceapply.ApplyNamespace(ctx, ns.Client, assetsEventRecorder, ns.ns) return err } @@ -82,8 +82,8 @@ func (secret *secretApplier) Reader(objBytes []byte, render RenderFunc, params R secret.secret = obj.(*corev1.Secret) } -func (secret *secretApplier) Applier() error { - _, _, err := resourceapply.ApplySecret(context.TODO(), secret.Client, assetsEventRecorder, secret.secret) +func (secret *secretApplier) Applier(ctx context.Context) error { + _, _, err := resourceapply.ApplySecret(ctx, secret.Client, assetsEventRecorder, secret.secret) return err } @@ -107,8 +107,8 @@ func (svc *svcApplier) Reader(objBytes []byte, render RenderFunc, params RenderP svc.svc = obj.(*corev1.Service) } -func (svc *svcApplier) Applier() error { - _, _, err := resourceapply.ApplyService(context.TODO(), svc.Client, assetsEventRecorder, svc.svc) +func (svc *svcApplier) Applier(ctx context.Context) error { + _, _, err := resourceapply.ApplyService(ctx, svc.Client, assetsEventRecorder, svc.svc) return err } @@ -132,8 +132,8 @@ func (sa *saApplier) Reader(objBytes []byte, render RenderFunc, params RenderPar sa.sa = obj.(*corev1.ServiceAccount) } -func (sa *saApplier) Applier() error { - _, _, err := resourceapply.ApplyServiceAccount(context.TODO(), sa.Client, assetsEventRecorder, sa.sa) +func (sa *saApplier) Applier(ctx context.Context) error { + _, _, err := resourceapply.ApplyServiceAccount(ctx, sa.Client, assetsEventRecorder, sa.sa) return err } @@ -157,12 +157,12 @@ func (cm *cmApplier) Reader(objBytes []byte, render RenderFunc, params RenderPar cm.cm = obj.(*corev1.ConfigMap) } -func (cm *cmApplier) Applier() error { - _, _, err := resourceapply.ApplyConfigMap(context.TODO(), cm.Client, assetsEventRecorder, cm.cm) +func (cm *cmApplier) Applier(ctx context.Context) error { + _, _, err := resourceapply.ApplyConfigMap(ctx, cm.Client, assetsEventRecorder, cm.cm) return err } -func applyCore(cores []string, applier readerApplier, render RenderFunc, params RenderParams) error { +func applyCore(ctx context.Context, cores []string, applier readerApplier, render RenderFunc, params RenderParams) error { lock.Lock() defer lock.Unlock() @@ -173,7 +173,7 @@ func applyCore(cores []string, applier readerApplier, render RenderFunc, params return fmt.Errorf("error getting asset %s: %v", core, err) } applier.Reader(objBytes, render, params) - if err := applier.Applier(); err != nil { + if err := applier.Applier(ctx); err != nil { klog.Warningf("Failed to apply corev1 api %s: %v", core, err) return err } @@ -182,31 +182,31 @@ func applyCore(cores []string, applier readerApplier, render RenderFunc, params return nil } -func ApplyNamespaces(cores []string, kubeconfigPath string) error { +func ApplyNamespaces(ctx context.Context, cores []string, kubeconfigPath string) error { ns := &nsApplier{} ns.Client = coreClient(kubeconfigPath) - return applyCore(cores, ns, nil, nil) + return applyCore(ctx, cores, ns, nil, nil) } -func ApplyServices(cores []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { +func ApplyServices(ctx context.Context, cores []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { svc := &svcApplier{} svc.Client = coreClient(kubeconfigPath) - return applyCore(cores, svc, render, params) + return applyCore(ctx, cores, svc, render, params) } -func ApplyServiceAccounts(cores []string, kubeconfigPath string) error { +func ApplyServiceAccounts(ctx context.Context, cores []string, kubeconfigPath string) error { sa := &saApplier{} sa.Client = coreClient(kubeconfigPath) - return applyCore(cores, sa, nil, nil) + return applyCore(ctx, cores, sa, nil, nil) } -func ApplyConfigMaps(cores []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { +func ApplyConfigMaps(ctx context.Context, cores []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { cm := &cmApplier{} cm.Client = coreClient(kubeconfigPath) - return applyCore(cores, cm, render, params) + return applyCore(ctx, cores, cm, render, params) } -func ApplyConfigMapWithData(cmPath string, data map[string]string, kubeconfigPath string) error { +func ApplyConfigMapWithData(ctx context.Context, cmPath string, data map[string]string, kubeconfigPath string) error { cm := &cmApplier{} cm.Client = coreClient(kubeconfigPath) cmBytes, err := embedded.Asset(cmPath) @@ -215,11 +215,11 @@ func ApplyConfigMapWithData(cmPath string, data map[string]string, kubeconfigPat } cm.Reader(cmBytes, nil, nil) cm.cm.Data = data - _, _, err = resourceapply.ApplyConfigMap(context.TODO(), cm.Client, assetsEventRecorder, cm.cm) + _, _, err = resourceapply.ApplyConfigMap(ctx, cm.Client, assetsEventRecorder, cm.cm) return err } -func ApplySecretWithData(secretPath string, data map[string][]byte, kubeconfigPath string) error { +func ApplySecretWithData(ctx context.Context, secretPath string, data map[string][]byte, kubeconfigPath string) error { secret := &secretApplier{} secret.Client = coreClient(kubeconfigPath) secretBytes, err := embedded.Asset(secretPath) @@ -228,6 +228,6 @@ func ApplySecretWithData(secretPath string, data map[string][]byte, kubeconfigPa } secret.Reader(secretBytes, nil, nil) secret.secret.Data = data - _, _, err = resourceapply.ApplySecret(context.TODO(), secret.Client, assetsEventRecorder, secret.secret) + _, _, err = resourceapply.ApplySecret(ctx, secret.Client, assetsEventRecorder, secret.secret) return err } diff --git a/pkg/assets/crd.go b/pkg/assets/crd.go index 077f5f5507..7919ffcbc2 100644 --- a/pkg/assets/crd.go +++ b/pkg/assets/crd.go @@ -52,11 +52,11 @@ func init() { } } -func isEstablished(cs *apiextclientv1.ApiextensionsV1Client, obj apiruntime.Object) (bool, error) { +func isEstablished(ctx context.Context, cs *apiextclientv1.ApiextensionsV1Client, obj apiruntime.Object) (bool, error) { var err error switch crd := obj.(type) { case *apiextv1.CustomResourceDefinition: - if crd, err = cs.CustomResourceDefinitions().Get(context.TODO(), crd.Name, metav1.GetOptions{}); err == nil { + if crd, err = cs.CustomResourceDefinitions().Get(ctx, crd.Name, metav1.GetOptions{}); err == nil { for _, condition := range crd.Status.Conditions { if condition.Type == apiextv1.Established && condition.Status == apiextv1.ConditionTrue { return true, nil @@ -70,7 +70,7 @@ func isEstablished(cs *apiextclientv1.ApiextensionsV1Client, obj apiruntime.Obje return false, err } -func WaitForCrdsEstablished(cfg *config.Config) error { +func WaitForCrdsEstablished(ctx context.Context, cfg *config.Config) error { restConfig, err := clientcmd.BuildConfigFromFlags("", cfg.KubeConfigPath(config.KubeAdmin)) if err != nil { return err @@ -87,7 +87,7 @@ func WaitForCrdsEstablished(cfg *config.Config) error { obj := readCRDOrDie(crdBytes) if err = wait.PollImmediate(customResourceReadyInterval, customResourceReadyTimeout, func() (done bool, err error) { - done, e := isEstablished(clientSet, obj) + done, e := isEstablished(ctx, clientSet, obj) // Intermittent errors can occur when calling the apiserver. To be on the safe side, log them, but poll until timeout if e != nil { klog.Errorf("polling for crd condition status \"established\"=\"true\": %v", e) @@ -110,12 +110,12 @@ func readCRDOrDie(objBytes []byte) *apiextv1.CustomResourceDefinition { return &crd } -func applyCRD(client *apiextclientv1.ApiextensionsV1Client, crd *apiextv1.CustomResourceDefinition) error { - _, _, err := resourceapply.ApplyCustomResourceDefinitionV1(context.TODO(), client, assetsEventRecorder, crd) +func applyCRD(client *apiextclientv1.ApiextensionsV1Client, crd *apiextv1.CustomResourceDefinition, ctx context.Context) error { + _, _, err := resourceapply.ApplyCustomResourceDefinitionV1(ctx, client, assetsEventRecorder, crd) return err } -func ApplyCRDs(cfg *config.Config) error { +func ApplyCRDs(ctx context.Context, cfg *config.Config) error { lock.Lock() defer lock.Unlock() @@ -143,7 +143,7 @@ func ApplyCRDs(cfg *config.Config) error { if err != nil { return err } - _, _, err = resourceapply.ApplyAPIService(context.TODO(), apiRegistrationClient, assetsEventRecorder, &apiService) + _, _, err = resourceapply.ApplyAPIService(ctx, apiRegistrationClient, assetsEventRecorder, &apiService) if err != nil { return err } @@ -159,7 +159,7 @@ func ApplyCRDs(cfg *config.Config) error { } c := readCRDOrDie(crdBytes) if err := wait.Poll(customResourceReadyInterval, customResourceReadyTimeout, func() (bool, error) { - if err := applyCRD(client, c); err != nil { + if err := applyCRD(client, c, ctx); err != nil { klog.Warningf("failed to apply openshift CRD %s: %v", crd, err) return false, nil } diff --git a/pkg/assets/rbac.go b/pkg/assets/rbac.go index 16ae8b54bd..50f6e5d1d1 100644 --- a/pkg/assets/rbac.go +++ b/pkg/assets/rbac.go @@ -50,8 +50,8 @@ func (crb *clusterRoleBindingApplier) Reader(objBytes []byte, _ RenderFunc, _ Re crb.crb = obj.(*rbacv1.ClusterRoleBinding) } -func (crb *clusterRoleBindingApplier) Applier() error { - _, _, err := resourceapply.ApplyClusterRoleBinding(context.TODO(), crb.client.RbacV1(), assetsEventRecorder, crb.crb) +func (crb *clusterRoleBindingApplier) Applier(ctx context.Context) error { + _, _, err := resourceapply.ApplyClusterRoleBinding(ctx, crb.client.RbacV1(), assetsEventRecorder, crb.crb) return err } @@ -77,8 +77,8 @@ func (cr *clusterRoleApplier) Reader(objBytes []byte, _ RenderFunc, _ RenderPara cr.cr = obj.(*rbacv1.ClusterRole) } -func (cr *clusterRoleApplier) Applier() error { - _, _, err := resourceapply.ApplyClusterRole(context.TODO(), cr.client.RbacV1(), assetsEventRecorder, cr.cr) +func (cr *clusterRoleApplier) Applier(ctx context.Context) error { + _, _, err := resourceapply.ApplyClusterRole(ctx, cr.client.RbacV1(), assetsEventRecorder, cr.cr) return err } @@ -104,8 +104,8 @@ func (rb *roleBindingApplier) Reader(objBytes []byte, _ RenderFunc, _ RenderPara rb.rb = obj.(*rbacv1.RoleBinding) } -func (rb *roleBindingApplier) Applier() error { - _, _, err := resourceapply.ApplyRoleBinding(context.TODO(), rb.client.RbacV1(), assetsEventRecorder, rb.rb) +func (rb *roleBindingApplier) Applier(ctx context.Context) error { + _, _, err := resourceapply.ApplyRoleBinding(ctx, rb.client.RbacV1(), assetsEventRecorder, rb.rb) return err } @@ -131,12 +131,12 @@ func (r *roleApplier) Reader(objBytes []byte, _ RenderFunc, _ RenderParams) { r.r = obj.(*rbacv1.Role) } -func (r *roleApplier) Applier() error { - _, _, err := resourceapply.ApplyRole(context.TODO(), r.client.RbacV1(), assetsEventRecorder, r.r) +func (r *roleApplier) Applier(ctx context.Context) error { + _, _, err := resourceapply.ApplyRole(ctx, r.client.RbacV1(), assetsEventRecorder, r.r) return err } -func applyRbac(rbacs []string, applier readerApplier) error { +func applyRbac(ctx context.Context, rbacs []string, applier readerApplier) error { lock.Lock() defer lock.Unlock() @@ -147,7 +147,7 @@ func applyRbac(rbacs []string, applier readerApplier) error { return fmt.Errorf("error getting asset %s: %v", rbac, err) } applier.Reader(objBytes, nil, nil) - if err := applier.Applier(); err != nil { + if err := applier.Applier(ctx); err != nil { klog.Warningf("Failed to apply rbac %s: %v", rbac, err) return err } @@ -156,25 +156,25 @@ func applyRbac(rbacs []string, applier readerApplier) error { return nil } -func ApplyClusterRoleBindings(rbacs []string, kubeconfigPath string) error { +func ApplyClusterRoleBindings(ctx context.Context, rbacs []string, kubeconfigPath string) error { crb := &clusterRoleBindingApplier{} crb.New(kubeconfigPath) - return applyRbac(rbacs, crb) + return applyRbac(ctx, rbacs, crb) } -func ApplyClusterRoles(rbacs []string, kubeconfigPath string) error { +func ApplyClusterRoles(ctx context.Context, rbacs []string, kubeconfigPath string) error { cr := &clusterRoleApplier{} cr.New(kubeconfigPath) - return applyRbac(rbacs, cr) + return applyRbac(ctx, rbacs, cr) } -func ApplyRoleBindings(rbacs []string, kubeconfigPath string) error { +func ApplyRoleBindings(ctx context.Context, rbacs []string, kubeconfigPath string) error { rb := &roleBindingApplier{} rb.New(kubeconfigPath) - return applyRbac(rbacs, rb) + return applyRbac(ctx, rbacs, rb) } -func ApplyRoles(rbacs []string, kubeconfigPath string) error { +func ApplyRoles(ctx context.Context, rbacs []string, kubeconfigPath string) error { r := &roleApplier{} r.New(kubeconfigPath) - return applyRbac(rbacs, r) + return applyRbac(ctx, rbacs, r) } diff --git a/pkg/assets/scc.go b/pkg/assets/scc.go index 294e25d26f..d883c70c88 100644 --- a/pkg/assets/scc.go +++ b/pkg/assets/scc.go @@ -58,11 +58,11 @@ func (s *sccApplier) Reader(objBytes []byte, render RenderFunc, params RenderPar s.scc = obj.(*sccv1.SecurityContextConstraints) } -func (s *sccApplier) Applier() error { +func (s *sccApplier) Applier(ctx context.Context) error { // adapted from cvo - existing, err := s.Client.SecurityContextConstraints().Get(context.TODO(), s.scc.Name, metav1.GetOptions{}) + existing, err := s.Client.SecurityContextConstraints().Get(ctx, s.scc.Name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { - _, err := s.Client.SecurityContextConstraints().Create(context.TODO(), s.scc, metav1.CreateOptions{}) + _, err := s.Client.SecurityContextConstraints().Create(ctx, s.scc, metav1.CreateOptions{}) return err } if err != nil { @@ -75,11 +75,11 @@ func (s *sccApplier) Applier() error { return nil } - _, err = s.Client.SecurityContextConstraints().Update(context.TODO(), existing, metav1.UpdateOptions{}) + _, err = s.Client.SecurityContextConstraints().Update(ctx, existing, metav1.UpdateOptions{}) return err } -func applySCCs(sccs []string, applier readerApplier, render RenderFunc, params RenderParams) error { +func applySCCs(ctx context.Context, sccs []string, applier readerApplier, render RenderFunc, params RenderParams) error { lock.Lock() defer lock.Unlock() @@ -90,7 +90,7 @@ func applySCCs(sccs []string, applier readerApplier, render RenderFunc, params R return fmt.Errorf("error getting asset %s: %v", scc, err) } applier.Reader(objBytes, render, params) - if err := applier.Applier(); err != nil { + if err := applier.Applier(ctx); err != nil { klog.Warningf("Failed to apply scc api %s: %v", scc, err) return err } @@ -98,8 +98,8 @@ func applySCCs(sccs []string, applier readerApplier, render RenderFunc, params R return nil } -func ApplySCCs(sccs []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { +func ApplySCCs(ctx context.Context, sccs []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { scc := &sccApplier{} scc.Client = sccClient(kubeconfigPath) - return applySCCs(sccs, scc, render, params) + return applySCCs(ctx, sccs, scc, render, params) } diff --git a/pkg/assets/scheduling.go b/pkg/assets/scheduling.go index 7aa394affb..1bb69b5897 100644 --- a/pkg/assets/scheduling.go +++ b/pkg/assets/scheduling.go @@ -48,11 +48,11 @@ func (s *pcApplier) Reader(objBytes []byte, render RenderFunc, params RenderPara s.pc = obj.(*sv1.PriorityClass) } -func (s *pcApplier) Applier() error { +func (s *pcApplier) Applier(ctx context.Context) error { // adapted from cvo - existing, err := s.Client.PriorityClasses().Get(context.TODO(), s.pc.Name, metav1.GetOptions{}) + existing, err := s.Client.PriorityClasses().Get(ctx, s.pc.Name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { - _, err := s.Client.PriorityClasses().Create(context.TODO(), s.pc, metav1.CreateOptions{}) + _, err := s.Client.PriorityClasses().Create(ctx, s.pc, metav1.CreateOptions{}) return err } if err != nil { @@ -65,11 +65,11 @@ func (s *pcApplier) Applier() error { return nil } - _, err = s.Client.PriorityClasses().Update(context.TODO(), existing, metav1.UpdateOptions{}) + _, err = s.Client.PriorityClasses().Update(ctx, existing, metav1.UpdateOptions{}) return err } -func applyPriorityClasses(pcs []string, applier readerApplier) error { +func applyPriorityClasses(ctx context.Context, pcs []string, applier readerApplier) error { lock.Lock() defer lock.Unlock() @@ -80,7 +80,7 @@ func applyPriorityClasses(pcs []string, applier readerApplier) error { return fmt.Errorf("error getting asset %s: %v", pc, err) } applier.Reader(objBytes, nil, nil) - if err := applier.Applier(); err != nil { + if err := applier.Applier(ctx); err != nil { klog.Warningf("Failed to apply PriorityClass CR %s: %v", pc, err) return err } @@ -88,7 +88,7 @@ func applyPriorityClasses(pcs []string, applier readerApplier) error { return nil } -func ApplyPriorityClasses(pcs []string, kubeconfigPath string) error { +func ApplyPriorityClasses(ctx context.Context, pcs []string, kubeconfigPath string) error { schedulingScheme := runtime.NewScheme() if err := sv1.AddToScheme(schedulingScheme); err != nil { return err @@ -98,5 +98,5 @@ func ApplyPriorityClasses(pcs []string, kubeconfigPath string) error { Client: pcClient(kubeconfigPath), codecs: serializer.NewCodecFactory(schedulingScheme), } - return applyPriorityClasses(pcs, pcApplier) + return applyPriorityClasses(ctx, pcs, pcApplier) } diff --git a/pkg/assets/storage.go b/pkg/assets/storage.go index 93b89c3e83..7a2d031c97 100644 --- a/pkg/assets/storage.go +++ b/pkg/assets/storage.go @@ -56,12 +56,12 @@ func (s *scApplier) Reader(objBytes []byte, render RenderFunc, params RenderPara } s.sc = obj.(*scv1.StorageClass) } -func (s *scApplier) Applier() error { - _, _, err := resourceapply.ApplyStorageClass(context.TODO(), s.Client, assetsEventRecorder, s.sc) +func (s *scApplier) Applier(ctx context.Context) error { + _, _, err := resourceapply.ApplyStorageClass(ctx, s.Client, assetsEventRecorder, s.sc) return err } -func applySCs(scs []string, applier readerApplier, render RenderFunc, params RenderParams) error { +func applySCs(ctx context.Context, scs []string, applier readerApplier, render RenderFunc, params RenderParams) error { lock.Lock() defer lock.Unlock() @@ -72,7 +72,7 @@ func applySCs(scs []string, applier readerApplier, render RenderFunc, params Ren return fmt.Errorf("error getting asset %s: %v", sc, err) } applier.Reader(objBytes, render, params) - if err := applier.Applier(); err != nil { + if err := applier.Applier(ctx); err != nil { klog.Warningf("Failed to apply sc api %s: %v", sc, err) return err } @@ -81,10 +81,10 @@ func applySCs(scs []string, applier readerApplier, render RenderFunc, params Ren return nil } -func ApplyStorageClasses(scs []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { +func ApplyStorageClasses(ctx context.Context,scs []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { sc := &scApplier{} sc.Client = scClient(kubeconfigPath) - return applySCs(scs, sc, render, params) + return applySCs(ctx, scs, sc, render, params) } type cdApplier struct { @@ -107,18 +107,18 @@ func (c *cdApplier) Reader(objBytes []byte, render RenderFunc, params RenderPara c.cd = obj.(*scv1.CSIDriver) } -func (c *cdApplier) Applier() error { - _, _, err := resourceapply.ApplyCSIDriver(context.TODO(), c.Client, assetsEventRecorder, c.cd) +func (c *cdApplier) Applier(ctx context.Context) error { + _, _, err := resourceapply.ApplyCSIDriver(ctx, c.Client, assetsEventRecorder, c.cd) return err } -func ApplyCSIDrivers(drivers []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { +func ApplyCSIDrivers(ctx context.Context, drivers []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { applier := &cdApplier{} applier.Client = scClient(kubeconfigPath) - return applyCDs(drivers, applier, render, params) + return applyCDs(ctx, drivers, applier, render, params) } -func applyCDs(cds []string, applier readerApplier, render RenderFunc, params RenderParams) error { +func applyCDs(ctx context.Context, cds []string, applier readerApplier, render RenderFunc, params RenderParams) error { lock.Lock() defer lock.Unlock() @@ -129,7 +129,7 @@ func applyCDs(cds []string, applier readerApplier, render RenderFunc, params Ren return fmt.Errorf("error getting asset %s: %v", cd, err) } applier.Reader(objBytes, render, params) - if err := applier.Applier(); err != nil { + if err := applier.Applier(ctx); err != nil { klog.Warningf("Failed to apply CSIDriver api %s: %v", cd, err) return err } diff --git a/pkg/cmd/run.go b/pkg/cmd/run.go index 6e0a436d3a..72bcb60e88 100644 --- a/pkg/cmd/run.go +++ b/pkg/cmd/run.go @@ -98,13 +98,16 @@ func RunMicroshift(cfg *config.Config) error { klog.Fatalf("failed to create the necessary kubeconfigs for internal components: %v", err) } + // Establish the context we will use to control execution + runCtx, runCancel := context.WithCancel(context.Background()) + m := servicemanager.NewServiceManager() util.Must(m.AddService(node.NewNetworkConfiguration(cfg))) util.Must(m.AddService(controllers.NewEtcd(cfg))) util.Must(m.AddService(sysconfwatch.NewSysConfWatchController(cfg))) util.Must(m.AddService(controllers.NewKubeAPIServer(cfg))) util.Must(m.AddService(controllers.NewKubeScheduler(cfg))) - util.Must(m.AddService(controllers.NewKubeControllerManager(cfg))) + util.Must(m.AddService(controllers.NewKubeControllerManager(runCtx, cfg))) util.Must(m.AddService(controllers.NewOpenShiftCRDManager(cfg))) util.Must(m.AddService(controllers.NewRouteControllerManager(cfg))) util.Must(m.AddService(controllers.NewClusterPolicyController(cfg))) @@ -130,9 +133,6 @@ func RunMicroshift(cfg *config.Config) error { // Establish a deadline for restarting to rotate the certificates. certCtx, certCancel := context.WithDeadline(context.Background(), rotationDate) - // Establish the context we will use to control execution - runCtx, runCancel := context.WithCancel(context.Background()) - // Watch for the certificate deadline context to be done, log a // message, and cancel the run context to propagate the shutdown. go func() { diff --git a/pkg/components/components.go b/pkg/components/components.go index 3eb32f9c84..c2b1c871d4 100755 --- a/pkg/components/components.go +++ b/pkg/components/components.go @@ -1,33 +1,34 @@ package components import ( + "context" "github.com/openshift/microshift/pkg/config" "k8s.io/klog/v2" ) -func StartComponents(cfg *config.Config) error { +func StartComponents(cfg *config.Config, ctx context.Context) error { kubeAdminConfig := cfg.KubeConfigPath(config.KubeAdmin) - if err := startServiceCAController(cfg, kubeAdminConfig); err != nil { + if err := startServiceCAController(ctx, cfg, kubeAdminConfig); err != nil { klog.Warningf("Failed to start service-ca controller: %v", err) return err } - if err := startCSIPlugin(cfg, cfg.KubeConfigPath(config.KubeAdmin)); err != nil { + if err := startCSIPlugin(ctx, cfg, cfg.KubeConfigPath(config.KubeAdmin)); err != nil { klog.Warningf("Failed to start csi plugin: %v", err) return err } - if err := startIngressController(cfg, kubeAdminConfig); err != nil { + if err := startIngressController(ctx, cfg, kubeAdminConfig); err != nil { klog.Warningf("Failed to start ingress router controller: %v", err) return err } - if err := startDNSController(cfg, kubeAdminConfig); err != nil { + if err := startDNSController(ctx, cfg, kubeAdminConfig); err != nil { klog.Warningf("Failed to start DNS controller: %v", err) return err } - if err := startCNIPlugin(cfg, kubeAdminConfig); err != nil { + if err := startCNIPlugin(ctx, cfg, kubeAdminConfig); err != nil { klog.Warningf("Failed to start CNI plugin: %v", err) return err } diff --git a/pkg/components/controllers.go b/pkg/components/controllers.go index 457ae1f770..a85060aa95 100644 --- a/pkg/components/controllers.go +++ b/pkg/components/controllers.go @@ -1,6 +1,7 @@ package components import ( + "context" "os" "github.com/openshift/microshift/pkg/assets" @@ -9,7 +10,7 @@ import ( "k8s.io/klog/v2" ) -func startServiceCAController(cfg *config.Config, kubeconfigPath string) error { +func startServiceCAController(ctx context.Context, cfg *config.Config, kubeconfigPath string) error { var ( //TODO: fix the rolebinding and sa clusterRoleBinding = []string{ @@ -58,35 +59,35 @@ func startServiceCAController(cfg *config.Config, kubeconfigPath string) error { secretData["tls.crt"] = caCertPEM secretData["tls.key"] = caKeyPEM - if err := assets.ApplyNamespaces(ns, kubeconfigPath); err != nil { + if err := assets.ApplyNamespaces(ctx, ns, kubeconfigPath); err != nil { klog.Warningf("Failed to apply ns %v: %v", ns, err) return err } - if err := assets.ApplyClusterRoleBindings(clusterRoleBinding, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoleBindings(ctx, clusterRoleBinding, kubeconfigPath); err != nil { klog.Warningf("Failed to apply clusterRolebinding %v: %v", clusterRoleBinding, err) return err } - if err := assets.ApplyClusterRoles(clusterRole, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoles(ctx, clusterRole, kubeconfigPath); err != nil { klog.Warningf("Failed to apply clusterRole %v: %v", clusterRole, err) return err } - if err := assets.ApplyRoleBindings(roleBinding, kubeconfigPath); err != nil { + if err := assets.ApplyRoleBindings(ctx, roleBinding, kubeconfigPath); err != nil { klog.Warningf("Failed to apply rolebinding %v: %v", roleBinding, err) return err } - if err := assets.ApplyRoles(role, kubeconfigPath); err != nil { + if err := assets.ApplyRoles(ctx, role, kubeconfigPath); err != nil { klog.Warningf("Failed to apply role %v: %v", role, err) return err } - if err := assets.ApplyServiceAccounts(sa, kubeconfigPath); err != nil { + if err := assets.ApplyServiceAccounts(ctx, sa, kubeconfigPath); err != nil { klog.Warningf("Failed to apply sa %v: %v", sa, err) return err } - if err := assets.ApplySecretWithData(secret, secretData, kubeconfigPath); err != nil { + if err := assets.ApplySecretWithData(ctx, secret, secretData, kubeconfigPath); err != nil { klog.Warningf("Failed to apply secret %v: %v", secret, err) return err } - if err := assets.ApplyConfigMapWithData(cm, cmData, kubeconfigPath); err != nil { + if err := assets.ApplyConfigMapWithData(ctx, cm, cmData, kubeconfigPath); err != nil { klog.Warningf("Failed to apply configMap %v: %v", cm, err) return err } @@ -94,14 +95,14 @@ func startServiceCAController(cfg *config.Config, kubeconfigPath string) error { "CAConfigMap": cmName, "TLSSecret": secretName, } - if err := assets.ApplyDeployments(apps, renderTemplate, renderParamsFromConfig(cfg, extraParams), kubeconfigPath); err != nil { + if err := assets.ApplyDeployments(ctx, apps, renderTemplate, renderParamsFromConfig(cfg, extraParams), kubeconfigPath); err != nil { klog.Warningf("Failed to apply apps %v: %v", apps, err) return err } return nil } -func startIngressController(cfg *config.Config, kubeconfigPath string) error { +func startIngressController(ctx context.Context, cfg *config.Config, kubeconfigPath string) error { var ( clusterRoleBinding = []string{ "components/openshift-router/cluster-role-binding.yaml", @@ -124,19 +125,19 @@ func startIngressController(cfg *config.Config, kubeconfigPath string) error { cm = "components/openshift-router/configmap.yaml" servingKeypairSecret = "components/openshift-router/serving-certificate.yaml" ) - if err := assets.ApplyNamespaces(ns, kubeconfigPath); err != nil { + if err := assets.ApplyNamespaces(ctx, ns, kubeconfigPath); err != nil { klog.Warningf("Failed to apply namespaces %v: %v", ns, err) return err } - if err := assets.ApplyClusterRoles(clusterRole, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoles(ctx, clusterRole, kubeconfigPath); err != nil { klog.Warningf("Failed to apply clusterRole %v: %v", clusterRole, err) return err } - if err := assets.ApplyClusterRoleBindings(clusterRoleBinding, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoleBindings(ctx, clusterRoleBinding, kubeconfigPath); err != nil { klog.Warningf("Failed to apply clusterRolebinding %v: %v", clusterRoleBinding, err) return err } - if err := assets.ApplyServiceAccounts(sa, kubeconfigPath); err != nil { + if err := assets.ApplyServiceAccounts(ctx, sa, kubeconfigPath); err != nil { klog.Warningf("Failed to apply serviceAccount %v %v", sa, err) return err } @@ -151,15 +152,16 @@ func startIngressController(cfg *config.Config, kubeconfigPath string) error { } cmData["service-ca.crt"] = string(caCertPEM) - if err := assets.ApplyConfigMapWithData(cm, cmData, kubeconfigPath); err != nil { + if err := assets.ApplyConfigMapWithData(ctx, cm, cmData, kubeconfigPath); err != nil { klog.Warningf("Failed to apply configMap %v: %v", cm, err) return err } - if err := assets.ApplyServices(svc, nil, nil, kubeconfigPath); err != nil { + if err := assets.ApplyServices(ctx, svc, nil, nil, kubeconfigPath); err != nil { klog.Warningf("Failed to apply service %v %v", svc, err) return err } if err := assets.ApplySecretWithData( + ctx, servingKeypairSecret, map[string][]byte{ "tls.crt": cfg.Ingress.ServingCertificate, @@ -171,14 +173,14 @@ func startIngressController(cfg *config.Config, kubeconfigPath string) error { return err } - if err := assets.ApplyDeployments(apps, renderTemplate, renderParamsFromConfig(cfg, nil), kubeconfigPath); err != nil { + if err := assets.ApplyDeployments(ctx, apps, renderTemplate, renderParamsFromConfig(cfg, nil), kubeconfigPath); err != nil { klog.Warningf("Failed to apply apps %v: %v", apps, err) return err } return nil } -func startDNSController(cfg *config.Config, kubeconfigPath string) error { +func startDNSController(ctx context.Context, cfg *config.Config, kubeconfigPath string) error { var ( clusterRoleBinding = []string{ "components/openshift-dns/dns/cluster-role-binding.yaml", @@ -204,7 +206,7 @@ func startDNSController(cfg *config.Config, kubeconfigPath string) error { "components/openshift-dns/dns/service.yaml", } ) - if err := assets.ApplyNamespaces(ns, kubeconfigPath); err != nil { + if err := assets.ApplyNamespaces(ctx, ns, kubeconfigPath); err != nil { klog.Warningf("Failed to apply", "namespace", ns, "err", err) return err } @@ -212,20 +214,20 @@ func startDNSController(cfg *config.Config, kubeconfigPath string) error { extraParams := assets.RenderParams{ "ClusterIP": cfg.Network.DNS, } - if err := assets.ApplyServices(svc, renderTemplate, renderParamsFromConfig(cfg, extraParams), kubeconfigPath); err != nil { + if err := assets.ApplyServices(ctx, svc, renderTemplate, renderParamsFromConfig(cfg, extraParams), kubeconfigPath); err != nil { klog.Warningf("Failed to apply service %v %v", svc, err) // service already created by coreDNS, not re-create it. return nil } - if err := assets.ApplyClusterRoles(clusterRole, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoles(ctx, clusterRole, kubeconfigPath); err != nil { klog.Warningf("Failed to apply clusterRole %v %v", clusterRole, err) return err } - if err := assets.ApplyClusterRoleBindings(clusterRoleBinding, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoleBindings(ctx, clusterRoleBinding, kubeconfigPath); err != nil { klog.Warningf("Failed to apply clusterRoleBinding %v %v", clusterRoleBinding, err) return err } - if err := assets.ApplyServiceAccounts(sa, kubeconfigPath); err != nil { + if err := assets.ApplyServiceAccounts(ctx, sa, kubeconfigPath); err != nil { klog.Warningf("Failed to apply serviceAccount %v %v", sa, err) return err } @@ -236,11 +238,11 @@ func startDNSController(cfg *config.Config, kubeconfigPath string) error { } else { extraParams["UpstreamResolver"] = "" } - if err := assets.ApplyConfigMaps(cm, renderTemplate, renderParamsFromConfig(cfg, extraParams), kubeconfigPath); err != nil { + if err := assets.ApplyConfigMaps(ctx, cm, renderTemplate, renderParamsFromConfig(cfg, extraParams), kubeconfigPath); err != nil { klog.Warningf("Failed to apply configMap %v %v", cm, err) return err } - if err := assets.ApplyDaemonSets(apps, renderTemplate, renderParamsFromConfig(cfg, extraParams), kubeconfigPath); err != nil { + if err := assets.ApplyDaemonSets(ctx, apps, renderTemplate, renderParamsFromConfig(cfg, extraParams), kubeconfigPath); err != nil { klog.Warningf("Failed to apply apps %v %v", apps, err) return err } diff --git a/pkg/components/networking.go b/pkg/components/networking.go index ce9ab6134e..f4ca34dbbd 100644 --- a/pkg/components/networking.go +++ b/pkg/components/networking.go @@ -1,6 +1,7 @@ package components import ( + "context" "fmt" "path/filepath" @@ -10,7 +11,7 @@ import ( "k8s.io/klog/v2" ) -func startCNIPlugin(cfg *config.Config, kubeconfigPath string) error { +func startCNIPlugin(ctx context.Context, cfg *config.Config, kubeconfigPath string) error { var ( ns = []string{ "components/ovn/namespace.yaml", @@ -49,27 +50,27 @@ func startCNIPlugin(cfg *config.Config, kubeconfigPath string) error { return fmt.Errorf("failed to validate ovn-kubernetes configurations %v", err) } - if err := assets.ApplyNamespaces(ns, kubeconfigPath); err != nil { + if err := assets.ApplyNamespaces(ctx, ns, kubeconfigPath); err != nil { klog.Warningf("Failed to apply ns %v: %v", ns, err) return err } - if err := assets.ApplyServiceAccounts(sa, kubeconfigPath); err != nil { + if err := assets.ApplyServiceAccounts(ctx, sa, kubeconfigPath); err != nil { klog.Warningf("Failed to apply serviceAccount %v %v", sa, err) return err } - if err := assets.ApplyRoles(r, kubeconfigPath); err != nil { + if err := assets.ApplyRoles(ctx, r, kubeconfigPath); err != nil { klog.Warningf("Failed to apply role %v: %v", r, err) return err } - if err := assets.ApplyRoleBindings(rb, kubeconfigPath); err != nil { + if err := assets.ApplyRoleBindings(ctx, rb, kubeconfigPath); err != nil { klog.Warningf("Failed to apply rolebinding %v: %v", rb, err) return err } - if err := assets.ApplyClusterRoles(cr, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoles(ctx, cr, kubeconfigPath); err != nil { klog.Warningf("Failed to apply clusterRole %v %v", cr, err) return err } - if err := assets.ApplyClusterRoleBindings(crb, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoleBindings(ctx, crb, kubeconfigPath); err != nil { klog.Warningf("Failed to apply clusterRoleBinding %v %v", crb, err) return err } @@ -82,7 +83,7 @@ func startCNIPlugin(cfg *config.Config, kubeconfigPath string) error { klog.Warningf("Failed to apply configMap %v %v", cm, err) return err } - if err := assets.ApplyDaemonSets(apps, renderTemplate, renderParamsFromConfig(cfg, extraParams), kubeconfigPath); err != nil { + if err := assets.ApplyDaemonSets(ctx, apps, renderTemplate, renderParamsFromConfig(cfg, extraParams), kubeconfigPath); err != nil { klog.Warningf("Failed to apply apps %v %v", apps, err) return err } diff --git a/pkg/components/storage.go b/pkg/components/storage.go index 54c4e4eb25..97e6804257 100644 --- a/pkg/components/storage.go +++ b/pkg/components/storage.go @@ -1,6 +1,7 @@ package components import ( + "context" "errors" "fmt" "os" @@ -24,7 +25,7 @@ func getCSIPluginConfig() (*lvmd.Lvmd, error) { return lvmd.DefaultLvmdConfig() } -func startCSIPlugin(cfg *config.Config, kubeconfigPath string) error { +func startCSIPlugin(ctx context.Context, cfg *config.Config, kubeconfigPath string) error { var ( ns = []string{ "components/lvms/topolvm-openshift-storage_namespace.yaml", @@ -91,51 +92,51 @@ func startCSIPlugin(cfg *config.Config, kubeconfigPath string) error { return fmt.Errorf("rendering lvmd params: %v", err) } - if err := assets.ApplyStorageClasses(sc, nil, nil, kubeconfigPath); err != nil { + if err := assets.ApplyStorageClasses(ctx, sc, nil, nil, kubeconfigPath); err != nil { klog.Warningf("Failed to apply storage cass %v: %v", sc, err) return err } - if err := assets.ApplyCSIDrivers(cd, nil, nil, kubeconfigPath); err != nil { + if err := assets.ApplyCSIDrivers(ctx, cd, nil, nil, kubeconfigPath); err != nil { klog.Warningf("Failed to apply csiDriver %v: %v", sc, err) return err } - if err := assets.ApplyNamespaces(ns, kubeconfigPath); err != nil { + if err := assets.ApplyNamespaces(ctx, ns, kubeconfigPath); err != nil { klog.Warningf("Failed to apply ns %v: %v", ns, err) return err } - if err := assets.ApplyServiceAccounts(sa, kubeconfigPath); err != nil { + if err := assets.ApplyServiceAccounts(ctx, sa, kubeconfigPath); err != nil { klog.Warningf("Failed to apply sa %v: %v", sa, err) return err } - if err := assets.ApplyRoles(role, kubeconfigPath); err != nil { + if err := assets.ApplyRoles(ctx, role, kubeconfigPath); err != nil { klog.Warningf("Failed to apply role %v: %v", cr, err) return err } - if err := assets.ApplyRoleBindings(rb, kubeconfigPath); err != nil { + if err := assets.ApplyRoleBindings(ctx, rb, kubeconfigPath); err != nil { klog.Warningf("Failed to apply rolebinding %v: %v", cr, err) return err } - if err := assets.ApplyClusterRoles(cr, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoles(ctx, cr, kubeconfigPath); err != nil { klog.Warningf("Failed to apply clusterrole %v: %v", cr, err) return err } - if err := assets.ApplyClusterRoleBindings(crb, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoleBindings(ctx, crb, kubeconfigPath); err != nil { klog.Warningf("Failed to apply clusterrolebinding %v: %v", crb, err) return err } - if err := assets.ApplyConfigMapWithData(cm, map[string]string{"lvmd.yaml": lvmdRenderParams["lvmd"].(string)}, kubeconfigPath); err != nil { + if err := assets.ApplyConfigMapWithData(ctx, cm, map[string]string{"lvmd.yaml": lvmdRenderParams["lvmd"].(string)}, kubeconfigPath); err != nil { klog.Warningf("Failed to apply configMap %v: %v", crb, err) return err } - if err := assets.ApplyDeployments(deploy, renderTemplate, renderParamsFromConfig(cfg, nil), kubeconfigPath); err != nil { + if err := assets.ApplyDeployments(ctx, deploy, renderTemplate, renderParamsFromConfig(cfg, nil), kubeconfigPath); err != nil { klog.Warningf("Failed to apply deployment %v: %v", deploy, err) return err } - if err := assets.ApplyDaemonSets(ds, renderTemplate, renderParamsFromConfig(cfg, lvmdRenderParams), kubeconfigPath); err != nil { + if err := assets.ApplyDaemonSets(ctx, ds, renderTemplate, renderParamsFromConfig(cfg, lvmdRenderParams), kubeconfigPath); err != nil { klog.Warningf("Failed to apply daemonsets %v: %v", ds, err) return err } - if err := assets.ApplySCCs(scc, nil, nil, kubeconfigPath); err != nil { + if err := assets.ApplySCCs(ctx, scc, nil, nil, kubeconfigPath); err != nil { klog.Warningf("Failed to apply sccs %v: %v", scc, err) return err } diff --git a/pkg/controllers/infra-services-controller.go b/pkg/controllers/infra-services-controller.go index 2218d9faac..de55af062a 100644 --- a/pkg/controllers/infra-services-controller.go +++ b/pkg/controllers/infra-services-controller.go @@ -43,26 +43,26 @@ func (s *InfrastructureServicesManager) Dependencies() []string { func (s *InfrastructureServicesManager) Run(ctx context.Context, ready chan<- struct{}, stopped chan<- struct{}) error { defer close(ready) - if err := applyDefaultRBACs(s.cfg); err != nil { + if err := applyDefaultRBACs(ctx, s.cfg); err != nil { klog.Errorf("%s unable to apply default RBACs: %v", s.Name(), err) return err } priorityClasses := []string{"core/priority-class-openshift-user-critical.yaml"} - if err := assets.ApplyPriorityClasses(priorityClasses, s.cfg.KubeConfigPath(config.KubeAdmin)); err != nil { + if err := assets.ApplyPriorityClasses(ctx, priorityClasses, s.cfg.KubeConfigPath(config.KubeAdmin)); err != nil { klog.Errorf("%s unable to apply PriorityClasses: %v", s.Name(), err) return err } // TO-DO add readiness check - if err := components.StartComponents(s.cfg); err != nil { //nolint:contextcheck + if err := components.StartComponents(s.cfg, ctx); err != nil { return err } klog.Infof("%s launched ocp componets", s.Name()) return ctx.Err() } -func applyDefaultRBACs(cfg *config.Config) error { +func applyDefaultRBACs(ctx context.Context, cfg *config.Config) error { kubeconfigPath := cfg.KubeConfigPath(config.KubeAdmin) var ( cr = []string{ @@ -76,11 +76,11 @@ func applyDefaultRBACs(cfg *config.Config) error { "controllers/cluster-policy-controller/podsecurity-admission-label-syncer-controller-clusterrolebinding.yaml", } ) - if err := assets.ApplyClusterRoles(cr, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoles(ctx, cr, kubeconfigPath); err != nil { klog.Warningf("failed to apply cluster roles %v", err) return err } - if err := assets.ApplyClusterRoleBindings(crb, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoleBindings(ctx, crb, kubeconfigPath); err != nil { klog.Warningf("failed to apply cluster roles %v", err) return err } diff --git a/pkg/controllers/kube-controller-manager.go b/pkg/controllers/kube-controller-manager.go index bdd73a55fb..eb780f85eb 100644 --- a/pkg/controllers/kube-controller-manager.go +++ b/pkg/controllers/kube-controller-manager.go @@ -50,10 +50,10 @@ type KubeControllerManager struct { configureErr error } -func NewKubeControllerManager(cfg *config.Config) *KubeControllerManager { +func NewKubeControllerManager(ctx context.Context, cfg *config.Config) *KubeControllerManager { s := &KubeControllerManager{} // TODO: manage and invoke the configure bits independently outside of this. - s.args, s.applyFn, s.configureErr = configure(cfg) + s.args, s.applyFn, s.configureErr = configure(ctx, cfg) return s } @@ -75,7 +75,7 @@ func kcmServiceAccountPrivateKeyFile() string { return filepath.Join(config.DataDir, "/resources/kube-apiserver/secrets/service-account-key/service-account.key") } -func configure(cfg *config.Config) (args []string, applyFn func() error, err error) { +func configure(ctx context.Context, cfg *config.Config) (args []string, applyFn func() error, err error) { kubeConfig := cfg.KubeConfigPath(config.KubeControllerManager) clusterSigningKey, clusterSigningCert := kcmClusterSigningCertKeyAndFile() @@ -100,7 +100,7 @@ func configure(cfg *config.Config) (args []string, applyFn func() error, err err args, err = mergeAndConvertToArgs(overrides) applyFn = func() error { - return assets.ApplyNamespaces([]string{ + return assets.ApplyNamespaces(ctx, []string{ "controllers/kube-controller-manager/namespace-openshift-kube-controller-manager.yaml", "core/namespace-openshift-infra.yaml", }, cfg.KubeConfigPath(config.KubeAdmin)) diff --git a/pkg/controllers/kube-controller-manager_test.go b/pkg/controllers/kube-controller-manager_test.go index 110e31e486..eac3efc1b2 100644 --- a/pkg/controllers/kube-controller-manager_test.go +++ b/pkg/controllers/kube-controller-manager_test.go @@ -17,6 +17,7 @@ limitations under the License. package controllers import ( + "context" "fmt" "reflect" "testing" @@ -38,7 +39,7 @@ func TestKCMDefaultConfigAsset(t *testing.T) { func TestConfigure(t *testing.T) { cfg := config.NewDefault() - kcm := NewKubeControllerManager(cfg) + kcm := NewKubeControllerManager(context.TODO(), cfg) clusterSigningKey, clusterSigningCert := kcmClusterSigningCertKeyAndFile() argsWant := []string{ diff --git a/pkg/controllers/openshift-crd-manager.go b/pkg/controllers/openshift-crd-manager.go index 566ba98075..eb1c345f2b 100644 --- a/pkg/controllers/openshift-crd-manager.go +++ b/pkg/controllers/openshift-crd-manager.go @@ -39,14 +39,14 @@ func (s *OpenShiftCRDManager) Dependencies() []string { return []string{"kube-ap func (s *OpenShiftCRDManager) Run(ctx context.Context, ready chan<- struct{}, stopped chan<- struct{}) error { defer close(stopped) - if err := assets.ApplyCRDs(s.cfg); err != nil { //nolint:contextcheck + if err := assets.ApplyCRDs(s.cfg, ctx); err != nil { klog.Errorf("%s unable to apply default CRDs: %v", s.Name(), err) return err } klog.Infof("%s applied default CRDs", s.Name()) klog.Infof("%s waiting for CRDs acceptance before proceeding", s.Name()) - if err := assets.WaitForCrdsEstablished(s.cfg); err != nil { //nolint:contextcheck + if err := assets.WaitForCrdsEstablished(ctx, s.cfg); err != nil { klog.Errorf("%s unable to confirm all CRDs are ready: %v", s.Name(), err) } klog.Infof("%s all CRDs are ready", s.Name()) diff --git a/pkg/controllers/openshift-default-scc-manager.go b/pkg/controllers/openshift-default-scc-manager.go index 19615724c1..5570a07523 100644 --- a/pkg/controllers/openshift-default-scc-manager.go +++ b/pkg/controllers/openshift-default-scc-manager.go @@ -43,7 +43,7 @@ func (s *OpenShiftDefaultSCCManager) Dependencies() []string { func (s *OpenShiftDefaultSCCManager) Run(ctx context.Context, ready chan<- struct{}, stopped chan<- struct{}) error { defer close(ready) // TO-DO add readiness check - if err := ApplyDefaultSCCs(s.cfg); err != nil { + if err := ApplyDefaultSCCs(ctx, s.cfg); err != nil { klog.Errorf("%s unable to apply default SCCs: %v", s.Name(), err) return err } @@ -51,7 +51,7 @@ func (s *OpenShiftDefaultSCCManager) Run(ctx context.Context, ready chan<- struc return ctx.Err() } -func ApplyDefaultSCCs(cfg *config.Config) error { +func ApplyDefaultSCCs(ctx context.Context, cfg *config.Config) error { kubeconfigPath := cfg.KubeConfigPath(config.KubeAdmin) var ( clusterRole = []string{ @@ -82,15 +82,15 @@ func ApplyDefaultSCCs(cfg *config.Config) error { "controllers/openshift-default-scc-manager/0000_20_kube-apiserver-operator_00_scc-restricted.yaml", } ) - if err := assets.ApplySCCs(sccs, nil, nil, kubeconfigPath); err != nil { + if err := assets.ApplySCCs(ctx, sccs, nil, nil, kubeconfigPath); err != nil { klog.Warningf("failed to apply sccs %v", err) return err } - if err := assets.ApplyClusterRoles(clusterRole, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoles(ctx, clusterRole, kubeconfigPath); err != nil { klog.Warningf("Failed to apply clusterRole %v: %v", clusterRole, err) return err } - if err := assets.ApplyClusterRoleBindings(clusterRoleBinding, kubeconfigPath); err != nil { + if err := assets.ApplyClusterRoleBindings(ctx, clusterRoleBinding, kubeconfigPath); err != nil { klog.Warningf("Failed to apply clusterRolebinding %v: %v", clusterRoleBinding, err) return err } diff --git a/pkg/controllers/openshift-route-controller-manager.go b/pkg/controllers/openshift-route-controller-manager.go index aaa679ce62..e7167c62c2 100644 --- a/pkg/controllers/openshift-route-controller-manager.go +++ b/pkg/controllers/openshift-route-controller-manager.go @@ -108,12 +108,12 @@ func (s *OCPRouteControllerManager) Run(ctx context.Context, ready chan<- struct close(ready) }() - if err := assets.ApplyNamespaces([]string{ + if err := assets.ApplyNamespaces(ctx, []string{ "controllers/route-controller-manager/0000_50_cluster-openshift-route-controller-manager_00_namespace.yaml", }, s.kubeadmconfig); err != nil { klog.Fatalf("failed to apply openshift namespaces %v", err) } - if err := assets.ApplyClusterRoles([]string{ + if err := assets.ApplyClusterRoles(ctx, []string{ "controllers/route-controller-manager/ingress-to-route-controller-clusterrole.yaml", "controllers/route-controller-manager/route-controller-informer-clusterrole.yaml", "controllers/route-controller-manager/route-controller-tokenreview-clusterrole.yaml", @@ -121,7 +121,7 @@ func (s *OCPRouteControllerManager) Run(ctx context.Context, ready chan<- struct klog.Fatalf("failed to apply route controller manager cluster roles %v", err) } - if err := assets.ApplyClusterRoleBindings([]string{ + if err := assets.ApplyClusterRoleBindings(ctx, []string{ "controllers/route-controller-manager/ingress-to-route-controller-clusterrolebinding.yaml", "controllers/route-controller-manager/route-controller-informer-clusterrolebinding.yaml", "controllers/route-controller-manager/route-controller-tokenreview-clusterrolebinding.yaml", @@ -129,21 +129,21 @@ func (s *OCPRouteControllerManager) Run(ctx context.Context, ready chan<- struct klog.Fatalf("failed to apply route controller manager cluster role bindings %v", err) } - if err := assets.ApplyRoles([]string{ + if err := assets.ApplyRoles(ctx, []string{ "controllers/route-controller-manager/route-controller-leader-role.yaml", "controllers/route-controller-manager/route-controller-separate-sa-role.yaml", }, s.kubeadmconfig); err != nil { klog.Fatalf("failed to apply route controller manager roles %v", err) } - if err := assets.ApplyRoleBindings([]string{ + if err := assets.ApplyRoleBindings(ctx, []string{ "controllers/route-controller-manager/route-controller-leader-rolebinding.yaml", "controllers/route-controller-manager/route-controller-separate-sa-rolebinding.yaml", }, s.kubeadmconfig); err != nil { klog.Fatalf("failed to apply route controller manager role bindings %v", err) } - if err := assets.ApplyServiceAccounts([]string{ + if err := assets.ApplyServiceAccounts(ctx, []string{ "controllers/route-controller-manager/route-controller-sa.yaml", }, s.kubeadmconfig); err != nil { klog.Fatalf("failed to apply route controller manager service account %v", err) diff --git a/pkg/controllers/version.go b/pkg/controllers/version.go index c45e74048d..7934c600a4 100644 --- a/pkg/controllers/version.go +++ b/pkg/controllers/version.go @@ -53,7 +53,7 @@ func (s *VersionManager) Run(ctx context.Context, ready chan<- struct{}, stopped } kubeConfigPath := s.cfg.KubeConfigPath(config.KubeAdmin) - if err := assets.ApplyConfigMapWithData(cm, data, kubeConfigPath); err != nil { //nolint:contextcheck + if err := assets.ApplyConfigMapWithData(ctx, cm, data, kubeConfigPath); err != nil { //nolint:contextcheck klog.Warningf("Failed to apply configMap %v, %v", cm, err) return err } diff --git a/pkg/util/cryptomaterial/certchains/signerbuilder.go b/pkg/util/cryptomaterial/certchains/signerbuilder.go index 8e037b093f..b7198418eb 100644 --- a/pkg/util/cryptomaterial/certchains/signerbuilder.go +++ b/pkg/util/cryptomaterial/certchains/signerbuilder.go @@ -2,10 +2,9 @@ package certchains import ( "fmt" - - "github.com/openshift/library-go/pkg/crypto" "k8s.io/apimachinery/pkg/util/sets" + "github.com/openshift/library-go/pkg/crypto" "github.com/openshift/microshift/pkg/util/cryptomaterial" ) @@ -43,6 +42,7 @@ type certificateSigner struct { } // NewCertificateSigner returns a builder object for a certificate chain for the given signer +// //nolint:ireturn func NewCertificateSigner(signerName, signerDir string, validityDays int) CertificateSignerBuilder { return &certificateSigner{ @@ -59,6 +59,7 @@ func (s *certificateSigner) ValidityDays() int { return s.signerValidityDays } // WithSignerConfig uses the provided configuration in `config` to sign its // direct certificates. // This is useful when creating intermediate signers. +// //nolint:ireturn func (s *certificateSigner) WithSignerConfig(config *crypto.CA) CertificateSignerBuilder { s.signerConfig = config @@ -128,7 +129,7 @@ func (s *certificateSigner) Complete() (*CertificateSigner, error) { subCAs: make(map[string]*CertificateSigner), signedCertificates: make(map[string]*signedCertificateInfo), - caBundlePaths: sets.NewString(), + caBundlePaths: sets.New[string](), } for _, subCA := range s.subCAs { diff --git a/pkg/util/cryptomaterial/certchains/signers.go b/pkg/util/cryptomaterial/certchains/signers.go index 2422865f1b..5ed433f161 100644 --- a/pkg/util/cryptomaterial/certchains/signers.go +++ b/pkg/util/cryptomaterial/certchains/signers.go @@ -58,7 +58,7 @@ type CertificateSigner struct { subCAs map[string]*CertificateSigner signedCertificates map[string]*signedCertificateInfo - caBundlePaths sets.String //nolint:staticcheck + caBundlePaths sets.Set[string] //nolint:staticcheck } type signedCertificateInfo struct { @@ -128,7 +128,7 @@ func (s *CertificateSigner) regenerateSelf() error { s.signerConfig = signerConfig - return s.AddToBundles(s.caBundlePaths.List()...) + return s.AddToBundles(sets.List[string](s.caBundlePaths)...) } func (s *CertificateSigner) regenerateSubCA(subCAName string) error { @@ -248,7 +248,7 @@ func (s *CertificateSigner) toBuilder() CertificateSignerBuilder { //nolint:iret } } - signer = signer.WithCABundlePaths(s.caBundlePaths.List()...) + signer = signer.WithCABundlePaths(sets.List[string](s.caBundlePaths)...) return signer } From b7495bed8539a3272c6db3be1957fb3a602d4d12 Mon Sep 17 00:00:00 2001 From: Jon Cope Date: Fri, 31 Mar 2023 15:47:43 -0500 Subject: [PATCH 4/9] More err checking. some errors are ignored by convention or because they are always nil --- pkg/cmd/init_test.go | 5 +++-- pkg/controllers/kube-apiserver.go | 8 ++++++-- pkg/servicemanager/manager_test.go | 2 +- pkg/util/cryptomaterial/certchains/signers.go | 2 +- pkg/util/cryptomaterial/certchains/signers_test.go | 3 +-- pkg/util/cryptomaterial/trustupdates.go | 11 ++++++----- 6 files changed, 18 insertions(+), 13 deletions(-) diff --git a/pkg/cmd/init_test.go b/pkg/cmd/init_test.go index 80045ab695..52ea4ce23d 100644 --- a/pkg/cmd/init_test.go +++ b/pkg/cmd/init_test.go @@ -16,6 +16,7 @@ limitations under the License. package cmd import ( + "github.com/stretchr/testify/assert" "os" "path/filepath" "reflect" @@ -145,14 +146,14 @@ func Test_removeStaleKubeconfig(t *testing.T) { }, } for _, dir := range append(cfg.ApiServer.SubjectAltNames, cfg.Node.HostnameOverride) { - os.Mkdir(filepath.Join(rootDir, dir), 0600) + assert.NoError(t, os.Mkdir(filepath.Join(rootDir, dir), 0600)) } staleDir, err := os.MkdirTemp(rootDir, "example") if err != nil { t.Fatalf("unable to create temporary dir: %v", err) } - cleanupStaleKubeconfigs(cfg, rootDir) + assert.NoError(t, cleanupStaleKubeconfigs(cfg, rootDir)) _, err = os.Stat(staleDir) if err == nil { t.Fatalf("%s should have been deleted", staleDir) diff --git a/pkg/controllers/kube-apiserver.go b/pkg/controllers/kube-apiserver.go index e0262b7f55..b974f151f2 100644 --- a/pkg/controllers/kube-apiserver.go +++ b/pkg/controllers/kube-apiserver.go @@ -283,7 +283,9 @@ rules: - "RequestReceived"`) path := filepath.Join(config.DataDir, "resources", "kube-apiserver-audit-policies", "default.yaml") - os.MkdirAll(filepath.Dir(path), os.FileMode(0700)) + if err := os.MkdirAll(filepath.Dir(path), os.FileMode(0700)); err != nil { + return err + } return os.WriteFile(path, data, 0400) } @@ -356,7 +358,9 @@ func (s *KubeAPIServer) Run(ctx context.Context, ready chan<- struct{}, stopped } // audit logs go here - os.MkdirAll("/var/log/kube-apiserver", 0700) + if err := os.MkdirAll("/var/log/kube-apiserver", 0700); err != nil { + return err + } // Carrying a patch for NewAPIServerCommand to use cmd.Context().Done() as the stop channel // instead of the channel returned by SetupSignalHandler, which expects to be called at most diff --git a/pkg/servicemanager/manager_test.go b/pkg/servicemanager/manager_test.go index 127f1eaf91..84dd56b029 100644 --- a/pkg/servicemanager/manager_test.go +++ b/pkg/servicemanager/manager_test.go @@ -118,7 +118,7 @@ func TestRunCancellation(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) ready, stopped := make(chan struct{}), make(chan struct{}) go func() { - assert.NoError(t, m.Run(ctx, ready, stopped)) + assert.Error(t, m.Run(ctx, ready, stopped)) }() select { diff --git a/pkg/util/cryptomaterial/certchains/signers.go b/pkg/util/cryptomaterial/certchains/signers.go index 5ed433f161..13dc050fc9 100644 --- a/pkg/util/cryptomaterial/certchains/signers.go +++ b/pkg/util/cryptomaterial/certchains/signers.go @@ -58,7 +58,7 @@ type CertificateSigner struct { subCAs map[string]*CertificateSigner signedCertificates map[string]*signedCertificateInfo - caBundlePaths sets.Set[string] //nolint:staticcheck + caBundlePaths sets.Set[string] } type signedCertificateInfo struct { diff --git a/pkg/util/cryptomaterial/certchains/signers_test.go b/pkg/util/cryptomaterial/certchains/signers_test.go index 08dceb1938..05af44cab5 100644 --- a/pkg/util/cryptomaterial/certchains/signers_test.go +++ b/pkg/util/cryptomaterial/certchains/signers_test.go @@ -129,8 +129,7 @@ func TestCertificateSigner_Regenerate(t *testing.T) { ), ), ) - //nolint:errcheck - filepath.Walk(tmpDir, func(name string, info os.FileInfo, err error) error { + _ = filepath.Walk(tmpDir, func(name string, info os.FileInfo, err error) error { fmt.Println(name) return nil }) diff --git a/pkg/util/cryptomaterial/trustupdates.go b/pkg/util/cryptomaterial/trustupdates.go index eb0cdf6853..17ab86365e 100644 --- a/pkg/util/cryptomaterial/trustupdates.go +++ b/pkg/util/cryptomaterial/trustupdates.go @@ -19,11 +19,12 @@ func AppendCertsToFile(bundlePath string, certs ...[]byte) error { defer f.Close() for _, c := range certs { - // nolint:errcheck - f.WriteString("\n") - // nolint:errcheck - f.Write(c) + if _, err = f.WriteString("\n"); err != nil { + return err + } + if _, err = f.Write(c); err != nil { + return err + } } - return nil } From 074d44505d021482d063dc1dd2258f79db28c0e5 Mon Sep 17 00:00:00 2001 From: Jon Cope Date: Fri, 31 Mar 2023 16:07:12 -0500 Subject: [PATCH 5/9] oneliner, organize imports in init_test Signed-off-by: Jon Cope the presence of a vendor dir causes install to place the bin outside of PATH, forcing it to behave as a module fixes this Signed-off-by: Jon Cope post-rebase fixes. These include err checking, nested ifs, empty newlines, and a couple ctx passing errors --- Makefile | 4 ++-- cmd/microshift/main.go | 2 +- etcd/cmd/microshift-etcd/main.go | 3 +-- pkg/assets/crd.go | 4 ++-- pkg/assets/storage.go | 2 +- pkg/cmd/init_test.go | 3 +-- pkg/cmd/run.go | 8 +++++--- pkg/components/networking.go | 2 +- pkg/components/storage.go | 2 +- pkg/config/config.go | 2 +- pkg/config/config_test.go | 8 +++----- pkg/config/flags.go | 10 +++++++--- pkg/config/node.go | 6 ++++-- pkg/controllers/kube-apiserver.go | 4 ++-- pkg/controllers/kube-scheduler.go | 4 +++- pkg/controllers/openshift-crd-manager.go | 2 +- pkg/controllers/openshift-route-controller-manager.go | 4 ++-- pkg/controllers/version.go | 2 +- pkg/loadbalancerservice/controller.go | 2 +- pkg/mdns/controller.go | 2 +- pkg/mdns/routes_test.go | 2 +- pkg/node/kubelet.go | 6 +++--- pkg/node/netconfig.go | 10 ++++------ pkg/servicemanager/manager.go | 4 ++-- pkg/sysconfwatch/sysconfwatch.go | 7 +++++-- pkg/sysconfwatch/sysconfwatch_linux.go | 9 +++++++-- pkg/util/cryptomaterial/certchains/signers.go | 2 +- pkg/util/cryptomaterial/trustupdates.go | 4 ++-- scripts/tools.go | 1 + 29 files changed, 67 insertions(+), 54 deletions(-) diff --git a/Makefile b/Makefile index 9bc02d8b49..d01d3e0345 100644 --- a/Makefile +++ b/Makefile @@ -116,7 +116,7 @@ etcd: $(MAKE) -C etcd .PHONY: verify verify-images verify-assets licensecheck -verify: verify-images verify-assets verify-sh verify-py verify-container licensecheck +verify: verify-images verify-assets verify-sh verify-go verify-py verify-container licensecheck verify-images: ./hack/verify_images.sh @@ -133,7 +133,7 @@ verify-golangci: verify-govulncheck: @if ! command -v govulncheck &>/dev/null; then \ - go install golang.org/x/vuln/cmd/govulncheck@latest ; \ + go install -mod=mod golang.org/x/vuln/cmd/govulncheck@latest ; \ fi govulncheck ./... diff --git a/cmd/microshift/main.go b/cmd/microshift/main.go index aa871e41b4..89432b827b 100644 --- a/cmd/microshift/main.go +++ b/cmd/microshift/main.go @@ -23,7 +23,7 @@ func newCommand() *cobra.Command { Use: "microshift", Short: "MicroShift, a minimal OpenShift", Run: func(cmd *cobra.Command, args []string) { - cmd.Help() + _ = cmd.Help() // err is always nil os.Exit(1) }, } diff --git a/etcd/cmd/microshift-etcd/main.go b/etcd/cmd/microshift-etcd/main.go index 6103a24a7d..788849f959 100644 --- a/etcd/cmd/microshift-etcd/main.go +++ b/etcd/cmd/microshift-etcd/main.go @@ -16,13 +16,12 @@ func main() { cmd := &cobra.Command{ Use: "microshift-etcd", Run: func(cmd *cobra.Command, args []string) { - cmd.Help() + _ = cmd.Help() // err is always nil os.Exit(1) }, } cmd.AddCommand(NewRunEtcdCommand()) cmd.AddCommand(NewVersionCommand(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr})) - os.Exit(cli.Run(cmd)) } diff --git a/pkg/assets/crd.go b/pkg/assets/crd.go index 7919ffcbc2..7cc18eaae4 100644 --- a/pkg/assets/crd.go +++ b/pkg/assets/crd.go @@ -110,7 +110,7 @@ func readCRDOrDie(objBytes []byte) *apiextv1.CustomResourceDefinition { return &crd } -func applyCRD(client *apiextclientv1.ApiextensionsV1Client, crd *apiextv1.CustomResourceDefinition, ctx context.Context) error { +func applyCRD(ctx context.Context, client *apiextclientv1.ApiextensionsV1Client, crd *apiextv1.CustomResourceDefinition) error { _, _, err := resourceapply.ApplyCustomResourceDefinitionV1(ctx, client, assetsEventRecorder, crd) return err } @@ -159,7 +159,7 @@ func ApplyCRDs(ctx context.Context, cfg *config.Config) error { } c := readCRDOrDie(crdBytes) if err := wait.Poll(customResourceReadyInterval, customResourceReadyTimeout, func() (bool, error) { - if err := applyCRD(client, c, ctx); err != nil { + if err := applyCRD(ctx, client, c); err != nil { klog.Warningf("failed to apply openshift CRD %s: %v", crd, err) return false, nil } diff --git a/pkg/assets/storage.go b/pkg/assets/storage.go index 7a2d031c97..8a3ab9fa3d 100644 --- a/pkg/assets/storage.go +++ b/pkg/assets/storage.go @@ -81,7 +81,7 @@ func applySCs(ctx context.Context, scs []string, applier readerApplier, render R return nil } -func ApplyStorageClasses(ctx context.Context,scs []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { +func ApplyStorageClasses(ctx context.Context, scs []string, render RenderFunc, params RenderParams, kubeconfigPath string) error { sc := &scApplier{} sc.Client = scClient(kubeconfigPath) return applySCs(ctx, scs, sc, render, params) diff --git a/pkg/cmd/init_test.go b/pkg/cmd/init_test.go index 52ea4ce23d..c2339c1257 100644 --- a/pkg/cmd/init_test.go +++ b/pkg/cmd/init_test.go @@ -16,7 +16,6 @@ limitations under the License. package cmd import ( - "github.com/stretchr/testify/assert" "os" "path/filepath" "reflect" @@ -24,12 +23,12 @@ import ( "github.com/openshift/microshift/pkg/config" "github.com/openshift/microshift/pkg/util/cryptomaterial/certchains" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "k8s.io/apiserver/pkg/authentication/user" ) func Test_certsToRegenerate(t *testing.T) { - tests := []struct { name string chains *certchains.CertificateChains diff --git a/pkg/cmd/run.go b/pkg/cmd/run.go index 72bcb60e88..12e3b0853a 100644 --- a/pkg/cmd/run.go +++ b/pkg/cmd/run.go @@ -2,6 +2,7 @@ package cmd import ( "context" + "fmt" "os" "os/signal" "strings" @@ -85,7 +86,9 @@ func RunMicroshift(cfg *config.Config) error { klog.Fatal(err) } - os.MkdirAll(config.DataDir, 0700) + if err := os.MkdirAll(config.DataDir, 0700); err != nil { + return fmt.Errorf("failed to create dir %q: %w", config.DataDir, err) + } // TODO: change to only initialize what is strictly necessary for the selected role(s) certChains, err := initCerts(cfg) @@ -114,7 +117,7 @@ func RunMicroshift(cfg *config.Config) error { util.Must(m.AddService(controllers.NewOpenShiftDefaultSCCManager(cfg))) util.Must(m.AddService(mdns.NewMicroShiftmDNSController(cfg))) util.Must(m.AddService(controllers.NewInfrastructureServices(cfg))) - util.Must(m.AddService((controllers.NewVersionManager((cfg))))) + util.Must(m.AddService(controllers.NewVersionManager(cfg))) util.Must(m.AddService(kustomize.NewKustomizer(cfg))) util.Must(m.AddService(node.NewKubeletServer(cfg))) util.Must(m.AddService(loadbalancerservice.NewLoadbalancerServiceController(cfg))) @@ -156,7 +159,6 @@ func RunMicroshift(cfg *config.Config) error { klog.Errorf("Stopped %s: %v", m.Name(), err) } else { klog.Infof("%s completed", m.Name()) - } }() diff --git a/pkg/components/networking.go b/pkg/components/networking.go index f4ca34dbbd..1cc9735d07 100644 --- a/pkg/components/networking.go +++ b/pkg/components/networking.go @@ -79,7 +79,7 @@ func startCNIPlugin(ctx context.Context, cfg *config.Config, kubeconfigPath stri "KubeconfigPath": kubeconfigPath, "KubeconfigDir": filepath.Join(config.DataDir, "/resources/kubeadmin"), } - if err := assets.ApplyConfigMaps(cm, renderTemplate, renderParamsFromConfig(cfg, extraParams), kubeconfigPath); err != nil { + if err := assets.ApplyConfigMaps(ctx, cm, renderTemplate, renderParamsFromConfig(cfg, extraParams), kubeconfigPath); err != nil { klog.Warningf("Failed to apply configMap %v %v", cm, err) return err } diff --git a/pkg/components/storage.go b/pkg/components/storage.go index 97e6804257..700cd4f56f 100644 --- a/pkg/components/storage.go +++ b/pkg/components/storage.go @@ -73,7 +73,7 @@ func startCSIPlugin(ctx context.Context, cfg *config.Config, kubeconfigPath stri ) if err := lvmd.LvmSupported(); err != nil { - klog.Warningf("skipping CSI deployment: %w", err) + klog.Warningf("skipping CSI deployment: %v", err) return nil } diff --git a/pkg/config/config.go b/pkg/config/config.go index 1b58c2b093..e7c7e17576 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -203,7 +203,7 @@ func (c *Config) updateComputedValues() error { } func (c *Config) validate() error { - //nolint:nestifs // extracting the nested ifs will just increase the complexity of the if expressions as validation expands + //nolint:nestif // extracting the nested ifs will just increase the complexity of the if expressions as validation expands if len(c.ApiServer.SubjectAltNames) > 0 { // Any entry in SubjectAltNames will be included in the external access certificates. // Any of the hostnames and IPs (except the node IP) listed below conflicts with diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index 73cb71c6b0..718145ae6f 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -97,8 +97,8 @@ func TestGetActiveConfigFromYAML(t *testing.T) { } c.Network.ServiceNetwork = []string{"40.30.20.10/16"} c.Network.ServiceNodePortRange = "1024-32767" - c.ApiServer.AdvertiseAddress = "" // force value to be recomputed - c.updateComputedValues() // recomputes DNS field + c.ApiServer.AdvertiseAddress = "" // force value to be recomputed + assert.NoError(t, c.updateComputedValues()) // recomputes DNS field return c }(), }, @@ -166,7 +166,7 @@ func TestGetActiveConfigFromYAML(t *testing.T) { expected: func() *Config { c := mkDefaultConfig() c.Etcd.MemoryLimitMB = 129 - c.updateComputedValues() + assert.NoError(t, c.updateComputedValues()) return c }(), }, @@ -174,7 +174,6 @@ func TestGetActiveConfigFromYAML(t *testing.T) { for _, tt := range ttests { t.Run(tt.name, func(t *testing.T) { - config, err := getActiveConfigFromYAML([]byte(tt.config)) if tt.expectErr && err == nil { @@ -184,7 +183,6 @@ func TestGetActiveConfigFromYAML(t *testing.T) { t.Fatalf("Not expecting error and received: %v", err) } if !tt.expectErr { - // blank out the user settings because the expected value // never has them and any computed value should be set so // it should be safe to ignore them diff --git a/pkg/config/flags.go b/pkg/config/flags.go index e15ee75a1c..125dd4d46b 100644 --- a/pkg/config/flags.go +++ b/pkg/config/flags.go @@ -4,6 +4,7 @@ import ( "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/component-base/logs" + "k8s.io/klog/v2" ) func HideUnsupportedFlags(flags *pflag.FlagSet) { @@ -15,9 +16,12 @@ func HideUnsupportedFlags(flags *pflag.FlagSet) { loggingFlags.VisitAll(func(pf *pflag.Flag) { if !supportedLoggingFlags.Has(pf.Name) { - flags.MarkHidden(pf.Name) + if err := flags.MarkHidden(pf.Name); err != nil { + klog.Error("failed to hide flag %q: %v", pf.Name, err) + } } }) - - flags.MarkHidden("version") + if err := flags.MarkHidden("version"); err != nil { + klog.Error("failed to hide flag %q: %v", "version", err) + } } diff --git a/pkg/config/node.go b/pkg/config/node.go index 84ba694bce..9ec9fa61af 100644 --- a/pkg/config/node.go +++ b/pkg/config/node.go @@ -42,8 +42,10 @@ func (c *Config) establishNodeName(dataDir string) (string, error) { contents, err := os.ReadFile(filePath) if os.IsNotExist(err) { // ensure that dataDir exists - os.MkdirAll(dataDir, 0700) - if err := os.WriteFile(filePath, []byte(name), 0444); err != nil { + if err := os.MkdirAll(dataDir, 0700); err != nil { + return "", fmt.Errorf("failed to create data dir: %w", err) + } + if err := os.WriteFile(filePath, []byte(name), 0400); err != nil { return "", fmt.Errorf("failed to write nodename file %q: %v", filePath, err) } return name, nil diff --git a/pkg/controllers/kube-apiserver.go b/pkg/controllers/kube-apiserver.go index b974f151f2..eb0443dd58 100644 --- a/pkg/controllers/kube-apiserver.go +++ b/pkg/controllers/kube-apiserver.go @@ -103,7 +103,7 @@ func (s *KubeAPIServer) configure(cfg *config.Config) error { servingCert := cryptomaterial.ServingCertPath(serviceNetworkServingCertDir) servingKey := cryptomaterial.ServingKeyPath(serviceNetworkServingCertDir) - if err := s.configureAuditPolicy(cfg); err != nil { + if err := s.configureAuditPolicy(); err != nil { return fmt.Errorf("failed to configure kube-apiserver audit policy: %w", err) } @@ -247,7 +247,7 @@ func (s *KubeAPIServer) configure(cfg *config.Config) error { return nil } -func (s *KubeAPIServer) configureAuditPolicy(_ *config.Config) error { +func (s *KubeAPIServer) configureAuditPolicy() error { data := []byte(` apiVersion: audit.k8s.io/v1 kind: Policy diff --git a/pkg/controllers/kube-scheduler.go b/pkg/controllers/kube-scheduler.go index 503b5dfeb0..b95e2df7ed 100644 --- a/pkg/controllers/kube-scheduler.go +++ b/pkg/controllers/kube-scheduler.go @@ -65,7 +65,9 @@ leaderElection: leaderElect: false`) path := filepath.Join(config.DataDir, "resources", "kube-scheduler", "config", "config.yaml") - os.MkdirAll(filepath.Dir(path), os.FileMode(0700)) + if err := os.MkdirAll(filepath.Dir(path), os.FileMode(0700)); err != nil { + return fmt.Errorf("creating directory path %s: %w", path, err) + } return os.WriteFile(path, data, 0400) } diff --git a/pkg/controllers/openshift-crd-manager.go b/pkg/controllers/openshift-crd-manager.go index eb1c345f2b..d45beafab3 100644 --- a/pkg/controllers/openshift-crd-manager.go +++ b/pkg/controllers/openshift-crd-manager.go @@ -39,7 +39,7 @@ func (s *OpenShiftCRDManager) Dependencies() []string { return []string{"kube-ap func (s *OpenShiftCRDManager) Run(ctx context.Context, ready chan<- struct{}, stopped chan<- struct{}) error { defer close(stopped) - if err := assets.ApplyCRDs(s.cfg, ctx); err != nil { + if err := assets.ApplyCRDs(ctx, s.cfg); err != nil { klog.Errorf("%s unable to apply default CRDs: %v", s.Name(), err) return err } diff --git a/pkg/controllers/openshift-route-controller-manager.go b/pkg/controllers/openshift-route-controller-manager.go index e7167c62c2..df2878a448 100644 --- a/pkg/controllers/openshift-route-controller-manager.go +++ b/pkg/controllers/openshift-route-controller-manager.go @@ -58,10 +58,10 @@ func (s *OCPRouteControllerManager) Dependencies() []string { func (s *OCPRouteControllerManager) configure(cfg *config.Config) { s.kubeconfig = cfg.KubeConfigPath(config.RouteControllerManager) s.kubeadmconfig = cfg.KubeConfigPath(config.KubeAdmin) - s.config = s.writeConfig(cfg) + s.config = s.writeConfig() } -func (s *OCPRouteControllerManager) writeConfig(cfg *config.Config) *openshiftcontrolplanev1.OpenShiftControllerManagerConfig { +func (s *OCPRouteControllerManager) writeConfig() *openshiftcontrolplanev1.OpenShiftControllerManagerConfig { servingCertDir := cryptomaterial.RouteControllerManagerServingCertDir(cryptomaterial.CertsDirectory(config.DataDir)) c := &openshiftcontrolplanev1.OpenShiftControllerManagerConfig{ diff --git a/pkg/controllers/version.go b/pkg/controllers/version.go index 7934c600a4..cd45d862c5 100644 --- a/pkg/controllers/version.go +++ b/pkg/controllers/version.go @@ -53,7 +53,7 @@ func (s *VersionManager) Run(ctx context.Context, ready chan<- struct{}, stopped } kubeConfigPath := s.cfg.KubeConfigPath(config.KubeAdmin) - if err := assets.ApplyConfigMapWithData(ctx, cm, data, kubeConfigPath); err != nil { //nolint:contextcheck + if err := assets.ApplyConfigMapWithData(ctx, cm, data, kubeConfigPath); err != nil { klog.Warningf("Failed to apply configMap %v, %v", cm, err) return err } diff --git a/pkg/loadbalancerservice/controller.go b/pkg/loadbalancerservice/controller.go index 93598a570b..dda9504dc9 100644 --- a/pkg/loadbalancerservice/controller.go +++ b/pkg/loadbalancerservice/controller.go @@ -70,7 +70,7 @@ func (c *LoadbalancerServiceController) Run(ctx context.Context, ready chan<- st c.informer = serviceInformer.Informer() c.queue = workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()) c.indexer = c.informer.GetIndexer() - _ , err = c.informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ + _, err = c.informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { key, err := cache.MetaNamespaceKeyFunc(obj) if err == nil { diff --git a/pkg/mdns/controller.go b/pkg/mdns/controller.go index 116066fbda..0d87ec9f3b 100644 --- a/pkg/mdns/controller.go +++ b/pkg/mdns/controller.go @@ -85,7 +85,7 @@ func (c *MicroShiftmDNSController) Run(ctx context.Context, ready chan<- struct{ go func() { if err := c.startRouteInformer(c.stopCh); err != nil { - klog.Errorf("error running router: %w", err) + klog.Errorf("error running router: %v", err) } }() diff --git a/pkg/mdns/routes_test.go b/pkg/mdns/routes_test.go index 72706918e7..5ab9d1490d 100644 --- a/pkg/mdns/routes_test.go +++ b/pkg/mdns/routes_test.go @@ -3,8 +3,8 @@ package mdns import ( "testing" - "github.com/stretchr/testify/assert" "github.com/openshift/microshift/pkg/mdns/server" + "github.com/stretchr/testify/assert" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) diff --git a/pkg/node/kubelet.go b/pkg/node/kubelet.go index cc906572fc..e32cd20cf7 100644 --- a/pkg/node/kubelet.go +++ b/pkg/node/kubelet.go @@ -59,7 +59,6 @@ func (s *KubeletServer) Name() string { return componentKubelet } func (s *KubeletServer) Dependencies() []string { return []string{"kube-apiserver"} } func (s *KubeletServer) configure(cfg *config.Config) { - if err := s.writeConfig(cfg); err != nil { klog.Fatalf("Failed to write kubelet config", err) } @@ -134,12 +133,13 @@ serverTLSBootstrap: false #TODO`) } path := filepath.Join(config.DataDir, "resources", "kubelet", "config", "config.yaml") - os.MkdirAll(filepath.Dir(path), os.FileMode(0700)) + if err := os.MkdirAll(filepath.Dir(path), os.FileMode(0700)); err != nil { + return fmt.Errorf("failed to create dir %q: %w", path, err) + } return os.WriteFile(path, data, 0400) } func (s *KubeletServer) Run(ctx context.Context, ready chan<- struct{}, stopped chan<- struct{}) error { - defer close(stopped) // run readiness check go func() { diff --git a/pkg/node/netconfig.go b/pkg/node/netconfig.go index a202bc5a04..0d7e138602 100644 --- a/pkg/node/netconfig.go +++ b/pkg/node/netconfig.go @@ -62,13 +62,11 @@ func (n *NetworkConfiguration) Run(ctx context.Context, ready chan<- struct{}, s return err } go func() { - select { - case <-ctx.Done(): - if err := n.removeServiceIPLoopback(); err != nil { - klog.Warningf("failed to remove IP from interface: %v", err) - } - close(stopChan) + <-ctx.Done() + if err := n.removeServiceIPLoopback(); err != nil { + klog.Warningf("failed to remove IP from interface: %v", err) } + close(stopChan) }() } klog.Infof("%q is ready", n.Name()) diff --git a/pkg/servicemanager/manager.go b/pkg/servicemanager/manager.go index f0356b95f6..fe12808a7f 100644 --- a/pkg/servicemanager/manager.go +++ b/pkg/servicemanager/manager.go @@ -105,7 +105,7 @@ func (m *ServiceManager) asyncRun(ctx context.Context, service Service) (<-chan klog.Errorf("%s panicked: %s", service.Name(), r) klog.Error("Stopping MicroShift") if err := syscall.Kill(syscall.Getpid(), syscall.SIGTERM); err != nil { - klog.Warningf("error killing process: %w", err) + klog.Warningf("error killing process: %v", err) } if !sigchannel.IsClosed(stopped) { close(stopped) @@ -117,7 +117,7 @@ func (m *ServiceManager) asyncRun(ctx context.Context, service Service) (<-chan if err := service.Run(ctx, ready, stopped); err != nil && !errors.Is(err, context.Canceled) { klog.Errorf("service %s exited with error: %s, stopping MicroShift", service.Name(), err) if err := syscall.Kill(syscall.Getpid(), syscall.SIGTERM); err != nil { - klog.Warningf("error killing process: %w", err) + klog.Warningf("error killing process: %v", err) } } else { klog.Infof("%s completed", service.Name()) diff --git a/pkg/sysconfwatch/sysconfwatch.go b/pkg/sysconfwatch/sysconfwatch.go index cae7548a03..ca4a2a78be 100644 --- a/pkg/sysconfwatch/sysconfwatch.go +++ b/pkg/sysconfwatch/sysconfwatch.go @@ -5,8 +5,9 @@ package sysconfwatch import ( "context" - "github.com/openshift/microshift/pkg/config" "time" + + "github.com/openshift/microshift/pkg/config" ) type nonLinuxSysConfWatchController struct{} @@ -33,6 +34,8 @@ func (n *nonLinuxSysConfWatchController) Run(ctx context.Context, ready chan<- s } } -func NewSysConfWatchController(cfg *config.MicroshiftConfig) *nonLinuxSysConfWatchController { +// NewSysConfWatchController takes a config (which it ignores) in order to match the func signature of it's linux +// variant. see sysconfwatch_linux.go +func NewSysConfWatchController(_ *config.Config) *nonLinuxSysConfWatchController { return &nonLinuxSysConfWatchController{} } diff --git a/pkg/sysconfwatch/sysconfwatch_linux.go b/pkg/sysconfwatch/sysconfwatch_linux.go index 02f43e7018..6109715b45 100644 --- a/pkg/sysconfwatch/sysconfwatch_linux.go +++ b/pkg/sysconfwatch/sysconfwatch_linux.go @@ -72,11 +72,16 @@ func getSysMonTimes() (int64, int64) { // System-wide clock that measures real (i.e. wall-clock) time // This clock is affected by discontinuous jumps in the system time (e.g. if the system administrator manually changes the clock) // and by the incremental adjustments performed by adjtime and NTP - unix.ClockGettime(unix.CLOCK_REALTIME, &stm) + if err := unix.ClockGettime(unix.CLOCK_REALTIME, &stm); err != nil { + klog.Errorf("failed to init clock: %v", err) + } + // Clock that cannot be set and represents monotonic time since some unspecified starting point // It provides access to a raw hardware-based time that is not subject to NTP adjustments // or the incremental adjustments performed by adjtime - unix.ClockGettime(unix.CLOCK_MONOTONIC_RAW, &mtm) + if err := unix.ClockGettime(unix.CLOCK_MONOTONIC_RAW, &mtm); err != nil { + klog.Errorf("failed to initialize clock: %v", err) + } return stm.Sec, mtm.Sec } diff --git a/pkg/util/cryptomaterial/certchains/signers.go b/pkg/util/cryptomaterial/certchains/signers.go index 13dc050fc9..8edad3dc3c 100644 --- a/pkg/util/cryptomaterial/certchains/signers.go +++ b/pkg/util/cryptomaterial/certchains/signers.go @@ -457,7 +457,7 @@ func libraryGoMakeAndWriteSubCA(ca *crypto.CA, certFile, keyFile, serialFile, na var serialGenerator crypto.SerialGenerator if len(serialFile) > 0 { // create / overwrite the serial file with a zero padded hex value (ending in a newline to have a valid file) - if err := os.WriteFile(serialFile, []byte("00\n"), 0644); err != nil {//nolint:gosec + if err := os.WriteFile(serialFile, []byte("00\n"), 0600); err != nil { return nil, err } diff --git a/pkg/util/cryptomaterial/trustupdates.go b/pkg/util/cryptomaterial/trustupdates.go index 17ab86365e..7182c75691 100644 --- a/pkg/util/cryptomaterial/trustupdates.go +++ b/pkg/util/cryptomaterial/trustupdates.go @@ -20,10 +20,10 @@ func AppendCertsToFile(bundlePath string, certs ...[]byte) error { for _, c := range certs { if _, err = f.WriteString("\n"); err != nil { - return err + return err } if _, err = f.Write(c); err != nil { - return err + return err } } return nil diff --git a/scripts/tools.go b/scripts/tools.go index 0e4264cd85..7b3f65caf8 100644 --- a/scripts/tools.go +++ b/scripts/tools.go @@ -1,4 +1,5 @@ // Package tools imports things required by build scripts, to force `go mod` to see them as dependencies +//go:build tools // +build tools package tools From 16a0a15e1752a0a4a25633af0dd6a34fba0a3c48 Mon Sep 17 00:00:00 2001 From: Jon Cope Date: Tue, 18 Apr 2023 09:37:43 -0500 Subject: [PATCH 6/9] govuln is throwing errors and is out of scope for this pr. do not hold up linter fixes b/c of it, instead follow up in another PR Signed-off-by: Jon Cope --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index d01d3e0345..8680887f60 100644 --- a/Makefile +++ b/Makefile @@ -125,7 +125,7 @@ verify-assets: ./scripts/auto-rebase/presubmit.py .PHONY: verify-go verify-golangci verify-govulncheck -verify-go: verify-golangci verify-govulncheck +verify-go: verify-golangci # verify-govulncheck # TODO temporarily disabled verify-golangci: ./scripts/fetch_tools.sh golangci-lint && \ From 9990e94a338779064743ad8fe6205bb87d6ea554 Mon Sep 17 00:00:00 2001 From: Jon Cope Date: Tue, 18 Apr 2023 10:30:20 -0500 Subject: [PATCH 7/9] linter validation is timing out in CI so increase it from 1m default to 3m Signed-off-by: Jon Cope --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 8680887f60..1642a5fd5b 100644 --- a/Makefile +++ b/Makefile @@ -129,7 +129,7 @@ verify-go: verify-golangci # verify-govulncheck # TODO temporarily disabled verify-golangci: ./scripts/fetch_tools.sh golangci-lint && \ - ./_output/bin/golangci-lint run --verbose + ./_output/bin/golangci-lint run --verbose --timeout 3m0s verify-govulncheck: @if ! command -v govulncheck &>/dev/null; then \ From 3569953a300e558ff177dd394840d885c06d913f Mon Sep 17 00:00:00 2001 From: Jon Cope Date: Tue, 18 Apr 2023 12:30:05 -0500 Subject: [PATCH 8/9] still timing out, bump limit to 20m Signed-off-by: Jon Cope --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 1642a5fd5b..e6c8fee31e 100644 --- a/Makefile +++ b/Makefile @@ -129,7 +129,7 @@ verify-go: verify-golangci # verify-govulncheck # TODO temporarily disabled verify-golangci: ./scripts/fetch_tools.sh golangci-lint && \ - ./_output/bin/golangci-lint run --verbose --timeout 3m0s + ./_output/bin/golangci-lint run --verbose --timeout 20m0s verify-govulncheck: @if ! command -v govulncheck &>/dev/null; then \ From 45a6bb425b3aa4deedfbeca3744a0628244b5255 Mon Sep 17 00:00:00 2001 From: Jon Cope Date: Tue, 18 Apr 2023 17:52:42 +0000 Subject: [PATCH 9/9] verify check crash and is complaining that etcd must be vendored, ran make vendor-etcd --- .../openshift/microshift/pkg/config/config.go | 4 +--- .../openshift/microshift/pkg/config/flags.go | 10 +++++++--- .../openshift/microshift/pkg/config/node.go | 6 ++++-- .../openshift/microshift/pkg/util/cert.go | 17 ++++------------- .../pkg/util/cryptomaterial/trustupdates.go | 9 ++++++--- .../openshift/microshift/pkg/util/net.go | 3 ++- 6 files changed, 24 insertions(+), 25 deletions(-) diff --git a/etcd/vendor/github.com/openshift/microshift/pkg/config/config.go b/etcd/vendor/github.com/openshift/microshift/pkg/config/config.go index 26e0c71b40..e7c7e17576 100644 --- a/etcd/vendor/github.com/openshift/microshift/pkg/config/config.go +++ b/etcd/vendor/github.com/openshift/microshift/pkg/config/config.go @@ -55,7 +55,6 @@ func NewDefault() *Config { // probing the environment, the values in the Config instance are not // changed. func (c *Config) fillDefaults() error { - // Look up any values that may generate an error subjectAltNames, err := getAllHostnames() if err != nil { @@ -150,7 +149,6 @@ func (c *Config) incorporateUserSettings(u *Config) { if u.Node.NodeIP != "" { c.Node.NodeIP = u.Node.NodeIP } - if len(u.ApiServer.SubjectAltNames) != 0 { c.ApiServer.SubjectAltNames = u.ApiServer.SubjectAltNames } @@ -170,7 +168,6 @@ func (c *Config) incorporateUserSettings(u *Config) { // inputs to more easily consumable units or fills in any defaults // computed based on the values of other settings. func (c *Config) updateComputedValues() error { - clusterDNS, err := c.computeClusterDNS() if err != nil { return err @@ -206,6 +203,7 @@ func (c *Config) updateComputedValues() error { } func (c *Config) validate() error { + //nolint:nestif // extracting the nested ifs will just increase the complexity of the if expressions as validation expands if len(c.ApiServer.SubjectAltNames) > 0 { // Any entry in SubjectAltNames will be included in the external access certificates. // Any of the hostnames and IPs (except the node IP) listed below conflicts with diff --git a/etcd/vendor/github.com/openshift/microshift/pkg/config/flags.go b/etcd/vendor/github.com/openshift/microshift/pkg/config/flags.go index e15ee75a1c..125dd4d46b 100644 --- a/etcd/vendor/github.com/openshift/microshift/pkg/config/flags.go +++ b/etcd/vendor/github.com/openshift/microshift/pkg/config/flags.go @@ -4,6 +4,7 @@ import ( "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/component-base/logs" + "k8s.io/klog/v2" ) func HideUnsupportedFlags(flags *pflag.FlagSet) { @@ -15,9 +16,12 @@ func HideUnsupportedFlags(flags *pflag.FlagSet) { loggingFlags.VisitAll(func(pf *pflag.Flag) { if !supportedLoggingFlags.Has(pf.Name) { - flags.MarkHidden(pf.Name) + if err := flags.MarkHidden(pf.Name); err != nil { + klog.Error("failed to hide flag %q: %v", pf.Name, err) + } } }) - - flags.MarkHidden("version") + if err := flags.MarkHidden("version"); err != nil { + klog.Error("failed to hide flag %q: %v", "version", err) + } } diff --git a/etcd/vendor/github.com/openshift/microshift/pkg/config/node.go b/etcd/vendor/github.com/openshift/microshift/pkg/config/node.go index 84ba694bce..9ec9fa61af 100644 --- a/etcd/vendor/github.com/openshift/microshift/pkg/config/node.go +++ b/etcd/vendor/github.com/openshift/microshift/pkg/config/node.go @@ -42,8 +42,10 @@ func (c *Config) establishNodeName(dataDir string) (string, error) { contents, err := os.ReadFile(filePath) if os.IsNotExist(err) { // ensure that dataDir exists - os.MkdirAll(dataDir, 0700) - if err := os.WriteFile(filePath, []byte(name), 0444); err != nil { + if err := os.MkdirAll(dataDir, 0700); err != nil { + return "", fmt.Errorf("failed to create data dir: %w", err) + } + if err := os.WriteFile(filePath, []byte(name), 0400); err != nil { return "", fmt.Errorf("failed to write nodename file %q: %v", filePath, err) } return name, nil diff --git a/etcd/vendor/github.com/openshift/microshift/pkg/util/cert.go b/etcd/vendor/github.com/openshift/microshift/pkg/util/cert.go index 1ee6d6dd50..45bfab6d67 100644 --- a/etcd/vendor/github.com/openshift/microshift/pkg/util/cert.go +++ b/etcd/vendor/github.com/openshift/microshift/pkg/util/cert.go @@ -22,23 +22,12 @@ import ( "encoding/pem" "fmt" "os" - "time" "github.com/pkg/errors" "k8s.io/client-go/util/keyutil" ) -const ( - defaultDurationDays = 365 - defaultDuration = defaultDurationDays * 24 * time.Hour - defaultHostname = "localhost" - - keySize = 2048 - - ValidityOneDay = 24 * time.Hour - ValidityOneYear = 365 * ValidityOneDay - ValidityTenYears = 10 * ValidityOneYear -) +const keySize = 2048 func EnsureKeyPair(pubKeyPath, privKeyPath string) error { if _, err := getKeyPair(pubKeyPath, privKeyPath); err == nil { @@ -69,7 +58,9 @@ func GenKeys(pubPath, keyPath string) error { return fmt.Errorf("failed to write the private key to %s: %v", keyPath, err) } - os.WriteFile(pubPath, pubPEM, 0400) + if err := os.WriteFile(pubPath, pubPEM, 0400); err != nil { + return fmt.Errorf("failed to write public key to %s: %v", pubPath, err) + } return nil } diff --git a/etcd/vendor/github.com/openshift/microshift/pkg/util/cryptomaterial/trustupdates.go b/etcd/vendor/github.com/openshift/microshift/pkg/util/cryptomaterial/trustupdates.go index ac8e37403c..7182c75691 100644 --- a/etcd/vendor/github.com/openshift/microshift/pkg/util/cryptomaterial/trustupdates.go +++ b/etcd/vendor/github.com/openshift/microshift/pkg/util/cryptomaterial/trustupdates.go @@ -19,9 +19,12 @@ func AppendCertsToFile(bundlePath string, certs ...[]byte) error { defer f.Close() for _, c := range certs { - f.WriteString("\n") - f.Write(c) + if _, err = f.WriteString("\n"); err != nil { + return err + } + if _, err = f.Write(c); err != nil { + return err + } } - return nil } diff --git a/etcd/vendor/github.com/openshift/microshift/pkg/util/net.go b/etcd/vendor/github.com/openshift/microshift/pkg/util/net.go index 4bc32dc327..f59d60f2c7 100644 --- a/etcd/vendor/github.com/openshift/microshift/pkg/util/net.go +++ b/etcd/vendor/github.com/openshift/microshift/pkg/util/net.go @@ -60,7 +60,7 @@ func RetryInsecureGet(url string) int { c := http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{ - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec }, }, } @@ -69,6 +69,7 @@ func RetryInsecureGet(url string) int { status = resp.StatusCode return true, nil } + defer resp.Body.Close() //nolint:errcheck return false, nil })