diff --git a/.golangci.yml b/.golangci.yml index c260a8e92..ece0c60a6 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -38,12 +38,11 @@ linters: # - goconst - TODO(ben): Consider moving consts into separate package - gocritic - godot + - gofmt + - gofumpt # TODO(ben): Enable those linters step by step and fix existing issues. -# - godox -# - gofmt -# - gofumpt # - goheader # - goimports # - gomoddirectives diff --git a/src/k8s/cmd/k8s/hooks.go b/src/k8s/cmd/k8s/hooks.go index c7dc87272..77a945580 100644 --- a/src/k8s/cmd/k8s/hooks.go +++ b/src/k8s/cmd/k8s/hooks.go @@ -40,7 +40,7 @@ func hookInitializeFormatter(env cmdutil.ExecutionEnvironment, format *string) f func hookCheckLXD() func(*cobra.Command, []string) { return func(cmd *cobra.Command, args []string) { // pathsOwnershipCheck paths to validate root is the owner - var pathsOwnershipCheck = []string{"/sys", "/proc", "/dev/kmsg"} + pathsOwnershipCheck := []string{"/sys", "/proc", "/dev/kmsg"} inLXD, err := cmdutil.InLXDContainer() if err != nil { cmd.PrintErrf("Failed to check if running inside LXD container: %s", err.Error()) diff --git a/src/k8s/cmd/k8s/k8s.go b/src/k8s/cmd/k8s/k8s.go index 45e26d0c8..815faff7e 100644 --- a/src/k8s/cmd/k8s/k8s.go +++ b/src/k8s/cmd/k8s/k8s.go @@ -35,13 +35,11 @@ func addCommands(root *cobra.Command, group *cobra.Group, commands ...*cobra.Com } func NewRootCmd(env cmdutil.ExecutionEnvironment) *cobra.Command { - var ( - opts struct { - logDebug bool - logVerbose bool - stateDir string - } - ) + var opts struct { + logDebug bool + logVerbose bool + stateDir string + } cmd := &cobra.Command{ Use: "k8s", Short: "Canonical Kubernetes CLI", diff --git a/src/k8s/cmd/k8s/k8s_bootstrap_test.go b/src/k8s/cmd/k8s/k8s_bootstrap_test.go index c4b852f7d..1ab92aa34 100644 --- a/src/k8s/cmd/k8s/k8s_bootstrap_test.go +++ b/src/k8s/cmd/k8s/k8s_bootstrap_test.go @@ -109,7 +109,7 @@ var testCases = []testCase{ func mustAddConfigToTestDir(t *testing.T, configPath string, data string) { t.Helper() // Create the cluster bootstrap config file - err := os.WriteFile(configPath, []byte(data), 0644) + err := os.WriteFile(configPath, []byte(data), 0o644) if err != nil { t.Fatal(err) } diff --git a/src/k8s/cmd/k8s/k8s_x_capi.go b/src/k8s/cmd/k8s/k8s_x_capi.go index 2da816bcb..232132dd9 100644 --- a/src/k8s/cmd/k8s/k8s_x_capi.go +++ b/src/k8s/cmd/k8s/k8s_x_capi.go @@ -48,7 +48,7 @@ func newXCAPICmd(env cmdutil.ExecutionEnvironment) *cobra.Command { return } - if err := os.WriteFile(env.Snap.NodeTokenFile(), []byte(token), 0600); err != nil { + if err := os.WriteFile(env.Snap.NodeTokenFile(), []byte(token), 0o600); err != nil { cmd.PrintErrf("Error: Failed to write the node token to file.\n\nThe error was: %v\n", err) env.Exit(1) return diff --git a/src/k8s/cmd/k8sd/k8sd_cluster_recover.go b/src/k8s/cmd/k8sd/k8sd_cluster_recover.go index ad8437ca9..7c1f74838 100644 --- a/src/k8s/cmd/k8sd/k8sd_cluster_recover.go +++ b/src/k8s/cmd/k8sd/k8sd_cluster_recover.go @@ -97,7 +97,6 @@ func logDebugf(format string, args ...interface{}) { msg := fmt.Sprintf(format, args...) log.L().Info(msg) } - } func newClusterRecoverCmd(env cmdutil.ExecutionEnvironment) *cobra.Command { @@ -294,7 +293,7 @@ func ensureK8sDqliteMembersStopped(ctx context.Context) error { }(ctx, dial, member.Address) } - for _, _ = range members { + for range members { addr, ok := <-c if !ok { return fmt.Errorf("channel closed unexpectedly") diff --git a/src/k8s/pkg/client/k8sd/mock/mock.go b/src/k8s/pkg/client/k8sd/mock/mock.go index d306e1a95..62915eb5b 100644 --- a/src/k8s/pkg/client/k8sd/mock/mock.go +++ b/src/k8s/pkg/client/k8sd/mock/mock.go @@ -56,14 +56,17 @@ func (m *Mock) BootstrapCluster(_ context.Context, request apiv1.BootstrapCluste m.BootstrapClusterCalledWith = request return m.BootstrapClusterResponse, m.BootstrapClusterErr } + func (m *Mock) GetJoinToken(_ context.Context, request apiv1.GetJoinTokenRequest) (apiv1.GetJoinTokenResponse, error) { m.GetJoinTokenCalledWith = request return m.GetJoinTokenResponse, m.GetJoinTokenErr } + func (m *Mock) JoinCluster(_ context.Context, request apiv1.JoinClusterRequest) error { m.JoinClusterCalledWith = request return m.JoinClusterErr } + func (m *Mock) RemoveNode(_ context.Context, request apiv1.RemoveNodeRequest) error { m.RemoveNodeCalledWith = request return m.RemoveNodeErr @@ -72,6 +75,7 @@ func (m *Mock) RemoveNode(_ context.Context, request apiv1.RemoveNodeRequest) er func (m *Mock) NodeStatus(_ context.Context) (apiv1.NodeStatusResponse, bool, error) { return m.NodeStatusResponse, m.NodeStatusInitialized, m.NodeStatusErr } + func (m *Mock) ClusterStatus(_ context.Context, waitReady bool) (apiv1.ClusterStatusResponse, error) { return m.ClusterStatusResponse, m.ClusterStatusErr } @@ -87,6 +91,7 @@ func (m *Mock) RefreshCertificatesRun(_ context.Context, request apiv1.RefreshCe func (m *Mock) GetClusterConfig(_ context.Context) (apiv1.GetClusterConfigResponse, error) { return m.GetClusterConfigResponse, m.GetClusterConfigErr } + func (m *Mock) SetClusterConfig(_ context.Context, request apiv1.SetClusterConfigRequest) error { m.SetClusterConfigCalledWith = request return m.SetClusterConfigErr diff --git a/src/k8s/pkg/client/kubernetes/configmap_test.go b/src/k8s/pkg/client/kubernetes/configmap_test.go index ea11d6aba..55b8ce713 100644 --- a/src/k8s/pkg/client/kubernetes/configmap_test.go +++ b/src/k8s/pkg/client/kubernetes/configmap_test.go @@ -79,7 +79,6 @@ func TestWatchConfigMap(t *testing.T) { case <-time.After(time.Second): t.Fatal("Timed out waiting for watch to complete") } - }) } } diff --git a/src/k8s/pkg/client/kubernetes/status.go b/src/k8s/pkg/client/kubernetes/status.go index 9046c4ca3..c89646c43 100644 --- a/src/k8s/pkg/client/kubernetes/status.go +++ b/src/k8s/pkg/client/kubernetes/status.go @@ -34,7 +34,6 @@ func (c *Client) CheckKubernetesEndpoint(ctx context.Context) error { // HasReadyNodes returns true if there is at least one Ready node in the cluster, false otherwise. func (c *Client) HasReadyNodes(ctx context.Context) (bool, error) { nodes, err := c.CoreV1().Nodes().List(ctx, metav1.ListOptions{}) - if err != nil { return false, fmt.Errorf("failed to list nodes: %w", err) } diff --git a/src/k8s/pkg/docgen/json_struct.go b/src/k8s/pkg/docgen/json_struct.go old mode 100755 new mode 100644 index d102fbced..7a65365fe --- a/src/k8s/pkg/docgen/json_struct.go +++ b/src/k8s/pkg/docgen/json_struct.go @@ -55,7 +55,7 @@ func MarkdownFromJsonStructToFile(i any, outFilePath string, projectDir string) return err } - err = os.WriteFile(outFilePath, []byte(content), 0644) + err = os.WriteFile(outFilePath, []byte(content), 0o644) if err != nil { return fmt.Errorf("failed to write markdown documentation to %s: %w", outFilePath, err) } diff --git a/src/k8s/pkg/k8sd/api/certificates_refresh.go b/src/k8s/pkg/k8sd/api/certificates_refresh.go index 540f87a40..beb519752 100644 --- a/src/k8s/pkg/k8sd/api/certificates_refresh.go +++ b/src/k8s/pkg/k8sd/api/certificates_refresh.go @@ -50,7 +50,6 @@ func (e *Endpoints) postRefreshCertsPlan(s state.State, r *http.Request) respons return response.SyncResponse(true, apiv1.RefreshCertificatesPlanResponse{ Seed: seed, }) - } func (e *Endpoints) postRefreshCertsRun(s state.State, r *http.Request) response.Response { @@ -187,7 +186,6 @@ func refreshCertsRunControlPlane(s state.State, r *http.Request, snap snap.Snap) f.Flush() return nil }) - } // refreshCertsRunWorker refreshes the certificates for a worker node. @@ -299,9 +297,7 @@ func refreshCertsRunWorker(s state.State, r *http.Request, snap snap.Snap) respo } return nil - }) - } if err := g.Wait(); err != nil { @@ -388,7 +384,6 @@ func refreshCertsRunWorker(s state.State, r *http.Request, snap snap.Snap) respo f.Flush() return nil }) - } // isCertificateSigningRequestApprovedAndIssued checks if the certificate @@ -399,7 +394,6 @@ func isCertificateSigningRequestApprovedAndIssued(csr *certv1.CertificateSigning for _, condition := range csr.Status.Conditions { if condition.Type == certv1.CertificateApproved && condition.Status == corev1.ConditionTrue { return len(csr.Status.Certificate) > 0, nil - } if condition.Type == certv1.CertificateDenied && condition.Status == corev1.ConditionTrue { return false, fmt.Errorf("CSR %s was denied: %s", csr.Name, condition.Reason) diff --git a/src/k8s/pkg/k8sd/api/impl/k8sd.go b/src/k8s/pkg/k8sd/api/impl/k8sd.go index bc8eabdb5..e062a12f5 100644 --- a/src/k8s/pkg/k8sd/api/impl/k8sd.go +++ b/src/k8s/pkg/k8sd/api/impl/k8sd.go @@ -59,5 +59,4 @@ func GetLocalNodeStatus(ctx context.Context, s state.State, snap snap.Snap) (api Address: s.Address().Hostname(), ClusterRole: clusterRole, }, nil - } diff --git a/src/k8s/pkg/k8sd/controllers/csrsigning/reconcile_approve.go b/src/k8s/pkg/k8sd/controllers/csrsigning/reconcile_approve.go index c767ce9ed..3c1bcc6a4 100644 --- a/src/k8s/pkg/k8sd/controllers/csrsigning/reconcile_approve.go +++ b/src/k8s/pkg/k8sd/controllers/csrsigning/reconcile_approve.go @@ -13,7 +13,8 @@ import ( ) func reconcileAutoApprove(ctx context.Context, log log.Logger, csr *certv1.CertificateSigningRequest, - priv *rsa.PrivateKey, client client.Client) (ctrl.Result, error) { + priv *rsa.PrivateKey, client client.Client, +) (ctrl.Result, error) { var result certv1.RequestConditionType if err := validateCSR(csr, priv); err != nil { diff --git a/src/k8s/pkg/k8sd/database/capi_auth.go b/src/k8s/pkg/k8sd/database/capi_auth.go index f8a4f54fc..498c2eaa7 100644 --- a/src/k8s/pkg/k8sd/database/capi_auth.go +++ b/src/k8s/pkg/k8sd/database/capi_auth.go @@ -8,12 +8,10 @@ import ( "github.com/canonical/microcluster/v3/cluster" ) -var ( - clusterAPIConfigsStmts = map[string]int{ - "insert-capi-token": MustPrepareStatement("cluster-configs", "insert-capi-token.sql"), - "select-capi-token": MustPrepareStatement("cluster-configs", "select-capi-token.sql"), - } -) +var clusterAPIConfigsStmts = map[string]int{ + "insert-capi-token": MustPrepareStatement("cluster-configs", "insert-capi-token.sql"), + "select-capi-token": MustPrepareStatement("cluster-configs", "select-capi-token.sql"), +} // SetClusterAPIToken stores the ClusterAPI token in the cluster config. func SetClusterAPIToken(ctx context.Context, tx *sql.Tx, token string) error { diff --git a/src/k8s/pkg/k8sd/database/cluster_config.go b/src/k8s/pkg/k8sd/database/cluster_config.go index 23e945a48..aab8f5c4b 100644 --- a/src/k8s/pkg/k8sd/database/cluster_config.go +++ b/src/k8s/pkg/k8sd/database/cluster_config.go @@ -10,12 +10,10 @@ import ( "github.com/canonical/microcluster/v3/cluster" ) -var ( - clusterConfigsStmts = map[string]int{ - "insert-v1alpha2": MustPrepareStatement("cluster-configs", "insert-v1alpha2.sql"), - "select-v1alpha2": MustPrepareStatement("cluster-configs", "select-v1alpha2.sql"), - } -) +var clusterConfigsStmts = map[string]int{ + "insert-v1alpha2": MustPrepareStatement("cluster-configs", "insert-v1alpha2.sql"), + "select-v1alpha2": MustPrepareStatement("cluster-configs", "select-v1alpha2.sql"), +} // SetClusterConfig updates the cluster configuration with any non-empty values that are set. // SetClusterConfig will attempt to merge the existing and new configs, and return an error if any protected fields have changed. diff --git a/src/k8s/pkg/k8sd/database/feature_status_test.go b/src/k8s/pkg/k8sd/database/feature_status_test.go index 7de15a07d..200e57f3b 100644 --- a/src/k8s/pkg/k8sd/database/feature_status_test.go +++ b/src/k8s/pkg/k8sd/database/feature_status_test.go @@ -46,7 +46,6 @@ func TestFeatureStatus(t *testing.T) { ss, err := database.GetFeatureStatuses(ctx, tx) g.Expect(err).To(Not(HaveOccurred())) g.Expect(ss).To(BeEmpty()) - }) t.Run("SettingNewStatus", func(t *testing.T) { @@ -70,7 +69,6 @@ func TestFeatureStatus(t *testing.T) { g.Expect(ss[features.DNS].Message).To(Equal(dnsStatus.Message)) g.Expect(ss[features.DNS].Version).To(Equal(dnsStatus.Version)) g.Expect(ss[features.DNS].UpdatedAt).To(Equal(dnsStatus.UpdatedAt)) - }) t.Run("UpdatingStatus", func(t *testing.T) { g := NewWithT(t) diff --git a/src/k8s/pkg/k8sd/database/kubernetes_auth_tokens.go b/src/k8s/pkg/k8sd/database/kubernetes_auth_tokens.go index 22c7b7a2b..73e708ef7 100644 --- a/src/k8s/pkg/k8sd/database/kubernetes_auth_tokens.go +++ b/src/k8s/pkg/k8sd/database/kubernetes_auth_tokens.go @@ -13,15 +13,13 @@ import ( "github.com/canonical/microcluster/v3/cluster" ) -var ( - k8sdTokensStmts = map[string]int{ - "insert-token": MustPrepareStatement("kubernetes-auth-tokens", "insert-token.sql"), - "select-by-token": MustPrepareStatement("kubernetes-auth-tokens", "select-by-token.sql"), - "select-by-username": MustPrepareStatement("kubernetes-auth-tokens", "select-by-username.sql"), - "delete-by-token": MustPrepareStatement("kubernetes-auth-tokens", "delete-by-token.sql"), - "delete-by-username": MustPrepareStatement("kubernetes-auth-tokens", "delete-by-username.sql"), - } -) +var k8sdTokensStmts = map[string]int{ + "insert-token": MustPrepareStatement("kubernetes-auth-tokens", "insert-token.sql"), + "select-by-token": MustPrepareStatement("kubernetes-auth-tokens", "select-by-token.sql"), + "select-by-username": MustPrepareStatement("kubernetes-auth-tokens", "select-by-username.sql"), + "delete-by-token": MustPrepareStatement("kubernetes-auth-tokens", "delete-by-token.sql"), + "delete-by-username": MustPrepareStatement("kubernetes-auth-tokens", "delete-by-username.sql"), +} func groupsToString(inGroups []string) (string, error) { groupMap := make(map[string]struct{}, len(inGroups)) diff --git a/src/k8s/pkg/k8sd/database/util_test.go b/src/k8s/pkg/k8sd/database/util_test.go index e9c9b7da2..e39712b59 100644 --- a/src/k8s/pkg/k8sd/database/util_test.go +++ b/src/k8s/pkg/k8sd/database/util_test.go @@ -18,10 +18,8 @@ const ( microclusterDatabaseShutdownTimeout = 3 * time.Second ) -var ( - // nextIdx is used to pick different listen ports for each microcluster instance. - nextIdx int -) +// nextIdx is used to pick different listen ports for each microcluster instance. +var nextIdx int // DB is an interface for the internal microcluster DB type. type DB interface { diff --git a/src/k8s/pkg/k8sd/database/worker.go b/src/k8s/pkg/k8sd/database/worker.go index c97da8267..043231a1a 100644 --- a/src/k8s/pkg/k8sd/database/worker.go +++ b/src/k8s/pkg/k8sd/database/worker.go @@ -12,13 +12,11 @@ import ( "github.com/canonical/microcluster/v3/cluster" ) -var ( - workerStmts = map[string]int{ - "insert-token": MustPrepareStatement("worker-tokens", "insert.sql"), - "select-token": MustPrepareStatement("worker-tokens", "select.sql"), - "delete-token": MustPrepareStatement("worker-tokens", "delete-by-token.sql"), - } -) +var workerStmts = map[string]int{ + "insert-token": MustPrepareStatement("worker-tokens", "insert.sql"), + "select-token": MustPrepareStatement("worker-tokens", "select.sql"), + "delete-token": MustPrepareStatement("worker-tokens", "delete-by-token.sql"), +} // CheckWorkerNodeToken returns true if the specified token can be used to join the specified node on the cluster. // CheckWorkerNodeToken will return true if the token is empty or if the token is associated with the specified node diff --git a/src/k8s/pkg/k8sd/features/cilium/gateway_test.go b/src/k8s/pkg/k8sd/features/cilium/gateway_test.go index d7037b947..2bcab0b11 100644 --- a/src/k8s/pkg/k8sd/features/cilium/gateway_test.go +++ b/src/k8s/pkg/k8sd/features/cilium/gateway_test.go @@ -144,7 +144,6 @@ func TestGatewayEnabled(t *testing.T) { g.Expect(status.Version).To(Equal(cilium.CiliumAgentImageTag)) g.Expect(status.Message).To(Equal(cilium.EnabledMsg)) }) - } func TestGatewayDisabled(t *testing.T) { @@ -200,7 +199,6 @@ func TestGatewayDisabled(t *testing.T) { g.Expect(helmCiliumArgs.Chart).To(Equal(cilium.ChartCilium)) g.Expect(helmCiliumArgs.State).To(Equal(helm.StateDeleted)) g.Expect(helmCiliumArgs.Values["gatewayAPI"].(map[string]any)["enabled"]).To(BeFalse()) - }) t.Run("RolloutFail", func(t *testing.T) { diff --git a/src/k8s/pkg/k8sd/features/cilium/network_test.go b/src/k8s/pkg/k8sd/features/cilium/network_test.go index 3462e5f1e..72551caa0 100644 --- a/src/k8s/pkg/k8sd/features/cilium/network_test.go +++ b/src/k8s/pkg/k8sd/features/cilium/network_test.go @@ -227,7 +227,6 @@ func TestNetworkMountPath(t *testing.T) { g.Expect(status.Message).To(Equal(fmt.Sprintf(networkDeployFailedMsgTmpl, err))) g.Expect(status.Version).To(Equal(CiliumAgentImageTag)) g.Expect(helmM.ApplyCalledWith).To(BeEmpty()) - }) } } @@ -265,7 +264,6 @@ func TestNetworkMountPropagationType(t *testing.T) { g.Expect(status.Version).To(Equal(CiliumAgentImageTag)) g.Expect(helmM.ApplyCalledWith).To(BeEmpty()) - }) t.Run("MountPropagationPrivateOnLXDError", func(t *testing.T) { @@ -375,7 +373,6 @@ func TestNetworkMountPropagationType(t *testing.T) { } func validateNetworkValues(g Gomega, values map[string]any, network types.Network, snap snap.Snap) { - ipv4CIDR, ipv6CIDR, err := utils.SplitCIDRStrings(network.GetPodCIDR()) g.Expect(err).ToNot(HaveOccurred()) diff --git a/src/k8s/pkg/k8sd/features/cilium/status_test.go b/src/k8s/pkg/k8sd/features/cilium/status_test.go index d591441b8..083844e5d 100644 --- a/src/k8s/pkg/k8sd/features/cilium/status_test.go +++ b/src/k8s/pkg/k8sd/features/cilium/status_test.go @@ -71,7 +71,6 @@ func TestCheckNetwork(t *testing.T) { err := cilium.CheckNetwork(context.Background(), snapM) g.Expect(err).To(HaveOccurred()) - }) t.Run("allPodsPresent", func(t *testing.T) { diff --git a/src/k8s/pkg/k8sd/features/contour/gateway_test.go b/src/k8s/pkg/k8sd/features/contour/gateway_test.go index 67ba82c9b..b4ac8e0b4 100644 --- a/src/k8s/pkg/k8sd/features/contour/gateway_test.go +++ b/src/k8s/pkg/k8sd/features/contour/gateway_test.go @@ -44,7 +44,6 @@ func TestGatewayDisabled(t *testing.T) { g.Expect(status.Enabled).To(BeFalse()) g.Expect(status.Version).To(Equal(contour.ContourGatewayProvisionerContourImageTag)) g.Expect(status.Message).To(Equal(fmt.Sprintf(contour.GatewayDeleteFailedMsgTmpl, err))) - }) t.Run("Success", func(t *testing.T) { @@ -68,7 +67,6 @@ func TestGatewayDisabled(t *testing.T) { g.Expect(status.Version).To(Equal(contour.ContourGatewayProvisionerContourImageTag)) g.Expect(status.Message).To(Equal(contour.DisabledMsg)) g.Expect(helmM.ApplyCalledWith).To(HaveLen(1)) - }) } @@ -124,7 +122,8 @@ func TestGatewayEnabled(t *testing.T) { {Name: "tlscertificatedelegations"}, {Name: "httpproxies"}, }, - }} + }, + } snapM := &snapmock.Snap{ Mock: snapmock.Mock{ HelmClient: helmM, @@ -182,7 +181,8 @@ func TestGatewayEnabled(t *testing.T) { { GroupVersion: "projectcontour.io/v1", APIResources: []v1.APIResource{}, - }} + }, + } snapM := &snapmock.Snap{ Mock: snapmock.Mock{ HelmClient: helmM, diff --git a/src/k8s/pkg/k8sd/features/contour/ingress_test.go b/src/k8s/pkg/k8sd/features/contour/ingress_test.go index 1dbbd9b9a..9547d2032 100644 --- a/src/k8s/pkg/k8sd/features/contour/ingress_test.go +++ b/src/k8s/pkg/k8sd/features/contour/ingress_test.go @@ -130,7 +130,8 @@ func TestIngressEnabled(t *testing.T) { {Name: "tlscertificatedelegations"}, {Name: "httpproxies"}, }, - }} + }, + } snapM := &snapmock.Snap{ Mock: snapmock.Mock{ HelmClient: helmM, @@ -186,7 +187,8 @@ func TestIngressEnabled(t *testing.T) { {Name: "tlscertificatedelegations"}, {Name: "httpproxies"}, }, - }} + }, + } snapM := &snapmock.Snap{ Mock: snapmock.Mock{ HelmClient: helmM, @@ -230,7 +232,6 @@ func TestIngressEnabled(t *testing.T) { fakeDiscovery, ok := clientset.Discovery().(*fakediscovery.FakeDiscovery) g.Expect(ok).To(BeTrue()) fakeDiscovery.Resources = []*metav1.APIResourceList{ - { GroupVersion: "projectcontour.io/v1alpha1", APIResources: []metav1.APIResource{ @@ -245,7 +246,8 @@ func TestIngressEnabled(t *testing.T) { {Name: "tlscertificatedelegations"}, {Name: "httpproxies"}, }, - }} + }, + } snapM := &snapmock.Snap{ Mock: snapmock.Mock{ HelmClient: helmM, @@ -294,7 +296,8 @@ func TestIngressEnabled(t *testing.T) { { GroupVersion: "projectcontour.io/metav1", APIResources: []metav1.APIResource{}, - }} + }, + } snapM := &snapmock.Snap{ Mock: snapmock.Mock{ HelmClient: helmM, @@ -349,7 +352,8 @@ func TestIngressEnabled(t *testing.T) { {Name: "tlscertificatedelegations"}, {Name: "httpproxies"}, }, - }} + }, + } snapM := &snapmock.Snap{ Mock: snapmock.Mock{ HelmClient: helmM, diff --git a/src/k8s/pkg/k8sd/features/coredns/coredns_test.go b/src/k8s/pkg/k8sd/features/coredns/coredns_test.go index b80328c14..0d10e2bd3 100644 --- a/src/k8s/pkg/k8sd/features/coredns/coredns_test.go +++ b/src/k8s/pkg/k8sd/features/coredns/coredns_test.go @@ -50,7 +50,6 @@ func TestDisabled(t *testing.T) { g.Expect(callArgs.Chart).To(Equal(coredns.Chart)) g.Expect(callArgs.State).To(Equal(helm.StateDeleted)) g.Expect(callArgs.Values).To(BeNil()) - }) t.Run("Success", func(t *testing.T) { g := NewWithT(t) diff --git a/src/k8s/pkg/k8sd/features/metrics-server/metrics_server_test.go b/src/k8s/pkg/k8sd/features/metrics-server/metrics_server_test.go index c6bdb78f0..006294d3c 100644 --- a/src/k8s/pkg/k8sd/features/metrics-server/metrics_server_test.go +++ b/src/k8s/pkg/k8sd/features/metrics-server/metrics_server_test.go @@ -15,7 +15,6 @@ import ( ) func TestApplyMetricsServer(t *testing.T) { - helmErr := errors.New("failed to apply") for _, tc := range []struct { name string diff --git a/src/k8s/pkg/k8sd/pki/worker_test.go b/src/k8s/pkg/k8sd/pki/worker_test.go index 4c9fac5cc..65d85215e 100644 --- a/src/k8s/pkg/k8sd/pki/worker_test.go +++ b/src/k8s/pkg/k8sd/pki/worker_test.go @@ -13,7 +13,6 @@ import ( ) func TestControlPlanePKI_CompleteWorkerNodePKI(t *testing.T) { - g := NewWithT(t) notBefore := time.Now() serverCACert, serverCAKey, err := pkiutil.GenerateSelfSignedCA(pkix.Name{CommonName: "kubernetes-ca"}, notBefore, notBefore.AddDate(1, 0, 0), 2048) diff --git a/src/k8s/pkg/k8sd/setup/certificates.go b/src/k8s/pkg/k8sd/setup/certificates.go index 283101e53..8508d9fc5 100644 --- a/src/k8s/pkg/k8sd/setup/certificates.go +++ b/src/k8s/pkg/k8sd/setup/certificates.go @@ -73,7 +73,7 @@ func ensureFiles(uid, gid int, mode fs.FileMode, files map[string]string) (bool, // and have the correct content, permissions and ownership. // It returns true if one or more files were updated and any error that occurred. func EnsureExtDatastorePKI(snap snap.Snap, certificates *pki.ExternalDatastorePKI) (bool, error) { - return ensureFiles(snap.UID(), snap.GID(), 0600, map[string]string{ + return ensureFiles(snap.UID(), snap.GID(), 0o600, map[string]string{ filepath.Join(snap.EtcdPKIDir(), "ca.crt"): certificates.DatastoreCACert, filepath.Join(snap.EtcdPKIDir(), "client.key"): certificates.DatastoreClientKey, filepath.Join(snap.EtcdPKIDir(), "client.crt"): certificates.DatastoreClientCert, @@ -84,7 +84,7 @@ func EnsureExtDatastorePKI(snap snap.Snap, certificates *pki.ExternalDatastorePK // and have the correct content, permissions and ownership. // It returns true if one or more files were updated and any error that occurred. func EnsureK8sDqlitePKI(snap snap.Snap, certificates *pki.K8sDqlitePKI) (bool, error) { - return ensureFiles(snap.UID(), snap.GID(), 0600, map[string]string{ + return ensureFiles(snap.UID(), snap.GID(), 0o600, map[string]string{ filepath.Join(snap.K8sDqliteStateDir(), "cluster.crt"): certificates.K8sDqliteCert, filepath.Join(snap.K8sDqliteStateDir(), "cluster.key"): certificates.K8sDqliteKey, }) @@ -94,7 +94,7 @@ func EnsureK8sDqlitePKI(snap snap.Snap, certificates *pki.K8sDqlitePKI) (bool, e // and have the correct content, permissions and ownership. // It returns true if one or more files were updated and any error that occurred. func EnsureControlPlanePKI(snap snap.Snap, certificates *pki.ControlPlanePKI) (bool, error) { - return ensureFiles(snap.UID(), snap.GID(), 0600, map[string]string{ + return ensureFiles(snap.UID(), snap.GID(), 0o600, map[string]string{ filepath.Join(snap.KubernetesPKIDir(), "apiserver-kubelet-client.crt"): certificates.APIServerKubeletClientCert, filepath.Join(snap.KubernetesPKIDir(), "apiserver-kubelet-client.key"): certificates.APIServerKubeletClientKey, filepath.Join(snap.KubernetesPKIDir(), "apiserver.crt"): certificates.APIServerCert, @@ -116,7 +116,7 @@ func EnsureControlPlanePKI(snap snap.Snap, certificates *pki.ControlPlanePKI) (b // and have the correct content, permissions and ownership. // It returns true if one or more files were updated and any error that occurred. func EnsureWorkerPKI(snap snap.Snap, certificates *pki.WorkerNodePKI) (bool, error) { - return ensureFiles(snap.UID(), snap.GID(), 0600, map[string]string{ + return ensureFiles(snap.UID(), snap.GID(), 0o600, map[string]string{ filepath.Join(snap.KubernetesPKIDir(), "ca.crt"): certificates.CACert, filepath.Join(snap.KubernetesPKIDir(), "client-ca.crt"): certificates.ClientCACert, filepath.Join(snap.KubernetesPKIDir(), "kubelet.crt"): certificates.KubeletCert, diff --git a/src/k8s/pkg/k8sd/setup/certificates_internal_test.go b/src/k8s/pkg/k8sd/setup/certificates_internal_test.go index 941392140..9454458d3 100644 --- a/src/k8s/pkg/k8sd/setup/certificates_internal_test.go +++ b/src/k8s/pkg/k8sd/setup/certificates_internal_test.go @@ -14,7 +14,7 @@ func TestEnsureFile(t *testing.T) { tempDir := t.TempDir() fname := filepath.Join(tempDir, "test") - updated, err := ensureFile(fname, "test", os.Getuid(), os.Getgid(), 0777) + updated, err := ensureFile(fname, "test", os.Getuid(), os.Getgid(), 0o777) g.Expect(err).To(Not(HaveOccurred())) g.Expect(updated).To(BeTrue()) @@ -28,12 +28,12 @@ func TestEnsureFile(t *testing.T) { fname := filepath.Join(tempDir, "test") // Create a file with some content. - updated, err := ensureFile(fname, "test", os.Getuid(), os.Getgid(), 0777) + updated, err := ensureFile(fname, "test", os.Getuid(), os.Getgid(), 0o777) g.Expect(err).To(Not(HaveOccurred())) g.Expect(updated).To(BeTrue()) // Delete the file. - updated, err = ensureFile(fname, "", os.Getuid(), os.Getgid(), 0777) + updated, err = ensureFile(fname, "", os.Getuid(), os.Getgid(), 0o777) g.Expect(err).To(Not(HaveOccurred())) g.Expect(updated).To(BeTrue()) @@ -47,17 +47,17 @@ func TestEnsureFile(t *testing.T) { fname := filepath.Join(tempDir, "test") // Create a file with some content. - updated, err := ensureFile(fname, "test", os.Getuid(), os.Getgid(), 0777) + updated, err := ensureFile(fname, "test", os.Getuid(), os.Getgid(), 0o777) g.Expect(err).To(Not(HaveOccurred())) g.Expect(updated).To(BeTrue()) // ensureFile with same content should return that the file was not updated. - updated, err = ensureFile(fname, "test", os.Getuid(), os.Getgid(), 0777) + updated, err = ensureFile(fname, "test", os.Getuid(), os.Getgid(), 0o777) g.Expect(err).To(Not(HaveOccurred())) g.Expect(updated).To(BeFalse()) // Change the content and ensureFile should return that the file was updated. - updated, err = ensureFile(fname, "new content", os.Getuid(), os.Getgid(), 0777) + updated, err = ensureFile(fname, "new content", os.Getuid(), os.Getgid(), 0o777) g.Expect(err).To(Not(HaveOccurred())) g.Expect(updated).To(BeTrue()) @@ -65,7 +65,7 @@ func TestEnsureFile(t *testing.T) { g.Expect(string(createdFile)).To(Equal("new content")) // Change permissions and ensureFile should return that the file was not updated. - updated, err = ensureFile(fname, "new content", os.Getuid(), os.Getgid(), 0666) + updated, err = ensureFile(fname, "new content", os.Getuid(), os.Getgid(), 0o666) g.Expect(err).To(Not(HaveOccurred())) g.Expect(updated).To(BeFalse()) }) @@ -76,7 +76,7 @@ func TestEnsureFile(t *testing.T) { fname := filepath.Join(tempDir, "test") // ensureFile on inexistent file with empty content should return that the file was not updated. - updated, err := ensureFile(fname, "", os.Getuid(), os.Getgid(), 0777) + updated, err := ensureFile(fname, "", os.Getuid(), os.Getgid(), 0o777) g.Expect(err).To(Not(HaveOccurred())) g.Expect(updated).To(BeFalse()) }) diff --git a/src/k8s/pkg/k8sd/setup/containerd.go b/src/k8s/pkg/k8sd/setup/containerd.go index dbf1545ec..15227e6cb 100644 --- a/src/k8s/pkg/k8sd/setup/containerd.go +++ b/src/k8s/pkg/k8sd/setup/containerd.go @@ -108,7 +108,7 @@ func Containerd(snap snap.Snap, extraContainerdConfig map[string]any, extraArgs return fmt.Errorf("failed to render containerd config.toml: %w", err) } - if err := os.WriteFile(filepath.Join(snap.ContainerdConfigDir(), "config.toml"), b, 0600); err != nil { + if err := os.WriteFile(filepath.Join(snap.ContainerdConfigDir(), "config.toml"), b, 0o600); err != nil { return fmt.Errorf("failed to write config.toml: %w", err) } @@ -131,7 +131,7 @@ func Containerd(snap snap.Snap, extraContainerdConfig map[string]any, extraArgs if err := utils.CopyFile(snap.CNIPluginsBinary(), cniBinary); err != nil { return fmt.Errorf("failed to copy cni plugin binary: %w", err) } - if err := os.Chmod(cniBinary, 0700); err != nil { + if err := os.Chmod(cniBinary, 0o700); err != nil { return fmt.Errorf("failed to chmod cni plugin binary: %w", err) } if err := os.Chown(cniBinary, snap.UID(), snap.GID()); err != nil { diff --git a/src/k8s/pkg/k8sd/setup/containerd_test.go b/src/k8s/pkg/k8sd/setup/containerd_test.go index bf895d263..66bfd2714 100644 --- a/src/k8s/pkg/k8sd/setup/containerd_test.go +++ b/src/k8s/pkg/k8sd/setup/containerd_test.go @@ -20,7 +20,7 @@ func TestContainerd(t *testing.T) { dir := t.TempDir() - g.Expect(os.WriteFile(filepath.Join(dir, "mockcni"), []byte("echo hi"), 0600)).To(Succeed()) + g.Expect(os.WriteFile(filepath.Join(dir, "mockcni"), []byte("echo hi"), 0o600)).To(Succeed()) s := &mock.Snap{ Mock: mock.Mock{ @@ -63,7 +63,7 @@ func TestContainerd(t *testing.T) { info, err := os.Stat(filepath.Join(dir, "containerd", "config.toml")) g.Expect(err).To(Not(HaveOccurred())) - g.Expect(info.Mode().Perm()).To(Equal(fs.FileMode(0600))) + g.Expect(info.Mode().Perm()).To(Equal(fs.FileMode(0o600))) switch stat := info.Sys().(type) { case *syscall.Stat_t: @@ -84,7 +84,7 @@ func TestContainerd(t *testing.T) { info, err := os.Stat(filepath.Join(dir, "opt-cni-bin")) g.Expect(err).To(Not(HaveOccurred())) - g.Expect(info.Mode().Perm()).To(Equal(fs.FileMode(0700))) + g.Expect(info.Mode().Perm()).To(Equal(fs.FileMode(0o700))) switch stat := info.Sys().(type) { case *syscall.Stat_t: diff --git a/src/k8s/pkg/k8sd/setup/directories.go b/src/k8s/pkg/k8sd/setup/directories.go index f4b8c4779..7b0a2afc9 100644 --- a/src/k8s/pkg/k8sd/setup/directories.go +++ b/src/k8s/pkg/k8sd/setup/directories.go @@ -33,7 +33,7 @@ func EnsureAllDirectories(snap snap.Snap) error { if dir == "" { continue } - if err := os.MkdirAll(dir, 0700); err != nil { + if err := os.MkdirAll(dir, 0o700); err != nil { return fmt.Errorf("failed to create required directory: %w", err) } } diff --git a/src/k8s/pkg/k8sd/setup/k8s_dqlite.go b/src/k8s/pkg/k8sd/setup/k8s_dqlite.go index ab4b8fbcd..92fc4812d 100644 --- a/src/k8s/pkg/k8sd/setup/k8s_dqlite.go +++ b/src/k8s/pkg/k8sd/setup/k8s_dqlite.go @@ -22,7 +22,7 @@ func K8sDqlite(snap snap.Snap, address string, cluster []string, extraArgs map[s if err := os.RemoveAll(snap.K8sDqliteStateDir()); err != nil { return fmt.Errorf("failed to cleanup not-empty k8s-dqlite directory: %w", err) } - if err := os.MkdirAll(snap.K8sDqliteStateDir(), 0700); err != nil { + if err := os.MkdirAll(snap.K8sDqliteStateDir(), 0o700); err != nil { return fmt.Errorf("failed to create k8s-dqlite state directory: %w", err) } } @@ -32,7 +32,7 @@ func K8sDqlite(snap snap.Snap, address string, cluster []string, extraArgs map[s return fmt.Errorf("failed to create init.yaml file for address=%s cluster=%v: %w", address, cluster, err) } - if err := os.WriteFile(filepath.Join(snap.K8sDqliteStateDir(), "init.yaml"), b, 0600); err != nil { + if err := os.WriteFile(filepath.Join(snap.K8sDqliteStateDir(), "init.yaml"), b, 0o600); err != nil { return fmt.Errorf("failed to write init.yaml: %w", err) } diff --git a/src/k8s/pkg/k8sd/setup/kube_apiserver.go b/src/k8s/pkg/k8sd/setup/kube_apiserver.go index 457ba1b96..09d38a660 100644 --- a/src/k8s/pkg/k8sd/setup/kube_apiserver.go +++ b/src/k8s/pkg/k8sd/setup/kube_apiserver.go @@ -52,7 +52,7 @@ var ( // KubeAPIServer configures kube-apiserver on the local node. func KubeAPIServer(snap snap.Snap, securePort int, nodeIP net.IP, serviceCIDR string, authWebhookURL string, enableFrontProxy bool, datastore types.Datastore, authorizationMode string, extraArgs map[string]*string) error { authTokenWebhookConfigFile := filepath.Join(snap.ServiceExtraConfigDir(), "auth-token-webhook.conf") - authTokenWebhookFile, err := os.OpenFile(authTokenWebhookConfigFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) + authTokenWebhookFile, err := os.OpenFile(authTokenWebhookConfigFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return fmt.Errorf("failed to open auth-token-webhook.conf: %w", err) } diff --git a/src/k8s/pkg/k8sd/setup/kube_scheduler_test.go b/src/k8s/pkg/k8sd/setup/kube_scheduler_test.go index 35ae0583f..cf406778d 100644 --- a/src/k8s/pkg/k8sd/setup/kube_scheduler_test.go +++ b/src/k8s/pkg/k8sd/setup/kube_scheduler_test.go @@ -53,7 +53,6 @@ func TestKubeScheduler(t *testing.T) { args, err := utils.ParseArgumentFile(filepath.Join(s.Mock.ServiceArgumentsDir, "kube-scheduler")) g.Expect(err).ToNot(HaveOccurred()) g.Expect(args).To(HaveLen(len(tests))) - }) t.Run("WithExtraArgs", func(t *testing.T) { @@ -100,7 +99,6 @@ func TestKubeScheduler(t *testing.T) { args, err := utils.ParseArgumentFile(filepath.Join(s.Mock.ServiceArgumentsDir, "kube-scheduler")) g.Expect(err).ToNot(HaveOccurred()) g.Expect(args).To(HaveLen(len(tests))) - }) t.Run("MissingArgsDir", func(t *testing.T) { diff --git a/src/k8s/pkg/k8sd/setup/kubelet_test.go b/src/k8s/pkg/k8sd/setup/kubelet_test.go index b2fc952df..2381b1acd 100644 --- a/src/k8s/pkg/k8sd/setup/kubelet_test.go +++ b/src/k8s/pkg/k8sd/setup/kubelet_test.go @@ -14,8 +14,10 @@ import ( // These values are hard-coded and need to be updated if the // implementation changes. -var expectedControlPlaneLabels = "node-role.kubernetes.io/control-plane=,node-role.kubernetes.io/worker=,k8sd.io/role=control-plane" -var expectedWorkerLabels = "node-role.kubernetes.io/worker=,k8sd.io/role=worker" +var ( + expectedControlPlaneLabels = "node-role.kubernetes.io/control-plane=,node-role.kubernetes.io/worker=,k8sd.io/role=control-plane" + expectedWorkerLabels = "node-role.kubernetes.io/worker=,k8sd.io/role=worker" +) var kubeletTLSCipherSuites = "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,TLS_RSA_WITH_AES_128_GCM_SHA256,TLS_RSA_WITH_AES_256_GCM_SHA384" diff --git a/src/k8s/pkg/k8sd/setup/templates.go b/src/k8s/pkg/k8sd/setup/templates.go index f2e7a965f..4fac815b4 100644 --- a/src/k8s/pkg/k8sd/setup/templates.go +++ b/src/k8s/pkg/k8sd/setup/templates.go @@ -7,10 +7,8 @@ import ( "text/template" ) -var ( - //go:embed embed - templates embed.FS -) +//go:embed embed +var templates embed.FS func mustTemplate(parts ...string) *template.Template { path := filepath.Join(append([]string{"embed"}, parts...)...) diff --git a/src/k8s/pkg/k8sd/setup/util_extra_files.go b/src/k8s/pkg/k8sd/setup/util_extra_files.go index 31f3cfb57..2376b5645 100644 --- a/src/k8s/pkg/k8sd/setup/util_extra_files.go +++ b/src/k8s/pkg/k8sd/setup/util_extra_files.go @@ -20,7 +20,7 @@ func ExtraNodeConfigFiles(snap snap.Snap, files map[string]string) error { filePath := filepath.Join(snap.ServiceExtraConfigDir(), filename) // Write the content to the file - if err := os.WriteFile(filePath, []byte(content), 0400); err != nil { + if err := os.WriteFile(filePath, []byte(content), 0o400); err != nil { return fmt.Errorf("failed to write to file %s: %w", filePath, err) } diff --git a/src/k8s/pkg/k8sd/setup/util_extra_files_test.go b/src/k8s/pkg/k8sd/setup/util_extra_files_test.go index ad4fa38bb..378810513 100644 --- a/src/k8s/pkg/k8sd/setup/util_extra_files_test.go +++ b/src/k8s/pkg/k8sd/setup/util_extra_files_test.go @@ -60,7 +60,7 @@ func TestExtraNodeConfigFiles(t *testing.T) { // Verify the file exists info, err := os.Stat(filePath) g.Expect(err).ToNot(gomega.HaveOccurred()) - g.Expect(info.Mode().Perm()).To(gomega.Equal(os.FileMode(0400))) + g.Expect(info.Mode().Perm()).To(gomega.Equal(os.FileMode(0o400))) // Verify the file content actualContent, err := os.ReadFile(filePath) diff --git a/src/k8s/pkg/k8sd/setup/util_kubeconfig.go b/src/k8s/pkg/k8sd/setup/util_kubeconfig.go index 413fa04a5..7b1157df1 100644 --- a/src/k8s/pkg/k8sd/setup/util_kubeconfig.go +++ b/src/k8s/pkg/k8sd/setup/util_kubeconfig.go @@ -74,5 +74,4 @@ func SetupControlPlaneKubeconfigs(kubeConfigDir string, localhostAddress string, } } return nil - } diff --git a/src/k8s/pkg/k8sd/types/cluster_config_certificates.go b/src/k8s/pkg/k8sd/types/cluster_config_certificates.go index ce61a612a..e7aa1120c 100644 --- a/src/k8s/pkg/k8sd/types/cluster_config_certificates.go +++ b/src/k8s/pkg/k8sd/types/cluster_config_certificates.go @@ -25,6 +25,7 @@ func (c Certificates) GetClientCACert() string { } return c.GetCACert() } + func (c Certificates) GetClientCAKey() string { // versions before 1.30.2 were using the same CA for server and client certificates if v := getField(c.ClientCAKey); v != "" { @@ -38,6 +39,7 @@ func (c Certificates) GetServiceAccountKey() string { return getField(c.ServiceA func (c Certificates) GetAPIServerKubeletClientCert() string { return getField(c.APIServerKubeletClientCert) } + func (c Certificates) GetAPIServerKubeletClientKey() string { return getField(c.APIServerKubeletClientKey) } diff --git a/src/k8s/pkg/k8sd/types/cluster_config_convert_test.go b/src/k8s/pkg/k8sd/types/cluster_config_convert_test.go index 47ed49deb..ad58cb846 100644 --- a/src/k8s/pkg/k8sd/types/cluster_config_convert_test.go +++ b/src/k8s/pkg/k8sd/types/cluster_config_convert_test.go @@ -254,6 +254,5 @@ func TestClusterConfigFromBootstrapConfig(t *testing.T) { g.Expect(err).To(HaveOccurred()) }) } - }) } diff --git a/src/k8s/pkg/k8sd/types/refresh.go b/src/k8s/pkg/k8sd/types/refresh.go index 365c9cb30..286826230 100644 --- a/src/k8s/pkg/k8sd/types/refresh.go +++ b/src/k8s/pkg/k8sd/types/refresh.go @@ -17,7 +17,7 @@ type RefreshOpts struct { } func RefreshOptsFromAPI(req apiv1.SnapRefreshRequest) (RefreshOpts, error) { - var optsMap = map[string]string{ + optsMap := map[string]string{ "localPath": req.LocalPath, "channel": req.Channel, "revision": req.Revision, diff --git a/src/k8s/pkg/proxy/config.go b/src/k8s/pkg/proxy/config.go index 08c2d6a86..3417016ec 100644 --- a/src/k8s/pkg/proxy/config.go +++ b/src/k8s/pkg/proxy/config.go @@ -33,7 +33,7 @@ func WriteEndpointsConfig(endpoints []string, file string) error { return fmt.Errorf("failed to marshal configuration: %w", err) } - if err := os.WriteFile(file, b, 0600); err != nil { + if err := os.WriteFile(file, b, 0o600); err != nil { return fmt.Errorf("failed to write configuration file %s: %w", file, err) } return nil diff --git a/src/k8s/pkg/snap/mock/mock.go b/src/k8s/pkg/snap/mock/mock.go index 4120303ca..17ecf9af2 100644 --- a/src/k8s/pkg/snap/mock/mock.go +++ b/src/k8s/pkg/snap/mock/mock.go @@ -78,6 +78,7 @@ func (s *Snap) StartService(ctx context.Context, name string) error { } return s.StartServiceErr } + func (s *Snap) StopService(ctx context.Context, name string) error { if len(s.StopServiceCalledWith) == 0 { s.StopServiceCalledWith = []string{name} @@ -86,6 +87,7 @@ func (s *Snap) StopService(ctx context.Context, name string) error { } return s.StopServiceErr } + func (s *Snap) RestartService(ctx context.Context, name string) error { if len(s.RestartServiceCalledWith) == 0 { s.RestartServiceCalledWith = []string{name} @@ -94,6 +96,7 @@ func (s *Snap) RestartService(ctx context.Context, name string) error { } return s.RestartServiceErr } + func (s *Snap) Refresh(ctx context.Context, opts types.RefreshOpts) (string, error) { if len(s.RefreshCalledWith) == 0 { s.RefreshCalledWith = []types.RefreshOpts{opts} @@ -102,107 +105,141 @@ func (s *Snap) Refresh(ctx context.Context, opts types.RefreshOpts) (string, err } return "", s.RefreshErr } + func (s *Snap) RefreshStatus(ctx context.Context, changeID string) (*types.RefreshStatus, error) { return nil, nil } + func (s *Snap) Strict() bool { return s.Mock.Strict } + func (s *Snap) OnLXD(context.Context) (bool, error) { return s.Mock.OnLXD, s.Mock.OnLXDErr } + func (s *Snap) UID() int { return s.Mock.UID } + func (s *Snap) GID() int { return s.Mock.GID } + func (s *Snap) Hostname() string { return s.Mock.Hostname } + func (s *Snap) ContainerdConfigDir() string { return s.Mock.ContainerdConfigDir } + func (s *Snap) ContainerdRootDir() string { return s.Mock.ContainerdRootDir } + func (s *Snap) ContainerdStateDir() string { return s.Mock.ContainerdStateDir } + func (s *Snap) ContainerdSocketDir() string { return s.Mock.ContainerdSocketDir } + func (s *Snap) ContainerdExtraConfigDir() string { return s.Mock.ContainerdExtraConfigDir } + func (s *Snap) ContainerdRegistryConfigDir() string { return s.Mock.ContainerdRegistryConfigDir } + func (s *Snap) KubernetesConfigDir() string { return s.Mock.KubernetesConfigDir } + func (s *Snap) KubernetesPKIDir() string { return s.Mock.KubernetesPKIDir } + func (s *Snap) EtcdPKIDir() string { return s.Mock.EtcdPKIDir } + func (s *Snap) KubeletRootDir() string { return s.Mock.KubeletRootDir } + func (s *Snap) CNIConfDir() string { return s.Mock.CNIConfDir } + func (s *Snap) CNIBinDir() string { return s.Mock.CNIBinDir } + func (s *Snap) CNIPluginsBinary() string { return s.Mock.CNIPluginsBinary } + func (s *Snap) CNIPlugins() []string { return s.Mock.CNIPlugins } + func (s *Snap) K8sdStateDir() string { return s.Mock.K8sdStateDir } + func (s *Snap) K8sDqliteStateDir() string { return s.Mock.K8sDqliteStateDir } + func (s *Snap) ServiceArgumentsDir() string { return s.Mock.ServiceArgumentsDir } + func (s *Snap) ServiceExtraConfigDir() string { return s.Mock.ServiceExtraConfigDir } + func (s *Snap) LockFilesDir() string { return s.Mock.LockFilesDir } + func (s *Snap) NodeTokenFile() string { return s.Mock.NodeTokenFile } + func (s *Snap) KubernetesClient(namespace string) (*kubernetes.Client, error) { return s.Mock.KubernetesClient, nil } + func (s *Snap) KubernetesNodeClient(namespace string) (*kubernetes.Client, error) { return s.Mock.KubernetesNodeClient, nil } + func (s *Snap) HelmClient() helm.Client { return s.Mock.HelmClient } + func (s *Snap) K8sDqliteClient(context.Context) (*dqlite.Client, error) { return s.Mock.K8sDqliteClient, nil } + func (s *Snap) K8sdClient(address string) (k8sd.Client, error) { return s.Mock.K8sdClient, nil } + func (s *Snap) SnapctlGet(ctx context.Context, args ...string) ([]byte, error) { s.SnapctlGetCalledWith = append(s.SnapctlGetCalledWith, args) return s.Mock.SnapctlGet[strings.Join(args, " ")], s.SnapctlGetErr } + func (s *Snap) SnapctlSet(ctx context.Context, args ...string) error { s.SnapctlSetCalledWith = append(s.SnapctlSetCalledWith, args) return s.SnapctlSetErr } + func (s *Snap) PreInitChecks(ctx context.Context, config types.ClusterConfig) error { s.PreInitChecksCalledWith = append(s.PreInitChecksCalledWith, config) return s.PreInitChecksErr diff --git a/src/k8s/pkg/snap/util/arguments.go b/src/k8s/pkg/snap/util/arguments.go index 74c52697c..12d3011be 100644 --- a/src/k8s/pkg/snap/util/arguments.go +++ b/src/k8s/pkg/snap/util/arguments.go @@ -103,7 +103,7 @@ func UpdateServiceArguments(snap snap.Snap, serviceName string, updateMap map[st // sort arguments so that output is consistent sort.Strings(newArguments) - if err := os.WriteFile(argumentsFile, []byte(strings.Join(newArguments, "\n")+"\n"), 0600); err != nil { + if err := os.WriteFile(argumentsFile, []byte(strings.Join(newArguments, "\n")+"\n"), 0o600); err != nil { return false, fmt.Errorf("failed to write arguments for service %s: %w", serviceName, err) } return changed, nil diff --git a/src/k8s/pkg/snap/util/arguments_test.go b/src/k8s/pkg/snap/util/arguments_test.go index 132d3f1e1..52fe4a1b3 100644 --- a/src/k8s/pkg/snap/util/arguments_test.go +++ b/src/k8s/pkg/snap/util/arguments_test.go @@ -32,7 +32,7 @@ func TestGetServiceArgument(t *testing.T) { --key=value-of-service-two `, } { - g.Expect(os.WriteFile(filepath.Join(dir, svc), []byte(args), 0600)).To(Succeed()) + g.Expect(os.WriteFile(filepath.Join(dir, svc), []byte(args), 0o600)).To(Succeed()) } for _, tc := range []struct { diff --git a/src/k8s/pkg/snap/util/node.go b/src/k8s/pkg/snap/util/node.go index 09dfe8289..d121970bc 100644 --- a/src/k8s/pkg/snap/util/node.go +++ b/src/k8s/pkg/snap/util/node.go @@ -25,7 +25,7 @@ func MarkAsWorkerNode(snap snap.Snap, mark bool) error { if err := os.Chown(fname, snap.UID(), snap.GID()); err != nil { return fmt.Errorf("failed to chown %s: %w", fname, err) } - if err := os.Chmod(fname, 0600); err != nil { + if err := os.Chmod(fname, 0o600); err != nil { return fmt.Errorf("failed to chmod %s: %w", fname, err) } } else { diff --git a/src/k8s/pkg/utils/control/retry_test.go b/src/k8s/pkg/utils/control/retry_test.go index ce1d078e3..1de78cb16 100644 --- a/src/k8s/pkg/utils/control/retry_test.go +++ b/src/k8s/pkg/utils/control/retry_test.go @@ -22,7 +22,6 @@ func TestRetryFor(t *testing.T) { } return nil }) - if err != nil { t.Errorf("Expected nil error, got: %v", err) } diff --git a/src/k8s/pkg/utils/file.go b/src/k8s/pkg/utils/file.go index 990471531..1b6728334 100644 --- a/src/k8s/pkg/utils/file.go +++ b/src/k8s/pkg/utils/file.go @@ -119,6 +119,7 @@ func CopyFile(srcFile, dstFile string) error { return nil } + func FileExists(path ...string) (bool, error) { if _, err := os.Stat(filepath.Join(path...)); err != nil { if !os.IsNotExist(err) { diff --git a/src/k8s/pkg/utils/file_test.go b/src/k8s/pkg/utils/file_test.go index 056056651..3efa8da76 100644 --- a/src/k8s/pkg/utils/file_test.go +++ b/src/k8s/pkg/utils/file_test.go @@ -88,7 +88,7 @@ func TestParseArgumentFile(t *testing.T) { g := NewWithT(t) filePath := filepath.Join(t.TempDir(), tc.name) - err := os.WriteFile(filePath, []byte(tc.content), 0755) + err := os.WriteFile(filePath, []byte(tc.content), 0o755) if err != nil { t.Fatalf("Failed to setup testfile: %v", err) } diff --git a/src/k8s/pkg/utils/time_test.go b/src/k8s/pkg/utils/time_test.go index dce809058..5b816ebfc 100644 --- a/src/k8s/pkg/utils/time_test.go +++ b/src/k8s/pkg/utils/time_test.go @@ -44,9 +44,7 @@ func TestSecondsToExpirationDate(t *testing.T) { got := utils.SecondsToExpirationDate(now, tt.seconds) g.Expect(got).To(Equal(tt.want)) }) - } - } func TestTTLToSeconds(t *testing.T) {