diff --git a/.golangci.yml b/.golangci.yml index 59990a35..e896af31 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,33 +1,122 @@ linters: - enable-all: true - disable: - - dupl - - funlen - - gochecknoglobals - - gochecknoinits - - lll - - godox - - wsl - - whitespace - - gocognit - - gomnd - - interfacer - - godot - - goerr113 - - nestif - # Run with --fast=false for more extensive checks - fast: true + disable-all: true + enable: + - asciicheck + - bodyclose + - deadcode + - depguard + - dogsled + - exportloopref + - errcheck + - goconst + - gocritic + - gocyclo + - godot + - gofmt + - goimports + - goprintffuncname + - gosec + - gosimple + - govet + - importas + - ineffassign + - misspell + - nakedret + - nolintlint + - prealloc + - revive + - rowserrcheck + - staticcheck + - structcheck + - stylecheck + - typecheck + - unconvert + - unparam + - varcheck + - whitespace + +linters-settings: + staticcheck: + go: "1.16" + stylecheck: + go: "1.16" + importas: + no-unaliased: true + alias: + # Kubernetes + - pkg: k8s.io/api/core/v1 + alias: corev1 + - pkg: k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1 + alias: apiextensionsv1 + - pkg: k8s.io/apimachinery/pkg/apis/meta/v1 + alias: metav1 + - pkg: k8s.io/apimachinery/pkg/api/errors + alias: apierrors + - pkg: k8s.io/apimachinery/pkg/util/errors + alias: kerrors + # Controller Runtime + - pkg: sigs.k8s.io/controller-runtime + alias: ctrl + issues: max-same-issues: 0 max-issues-per-linter: 0 + # We are disabling default golangci exclusions because we want to help reviewers to focus on reviewing the most relevant + # changes in PRs and avoid nitpicking. + exclude-use-default: false # List of regexps of issue texts to exclude, empty list by default. exclude: - - Using the variable on range scope `(tc)|(rt)|(tt)|(test)|(testcase)|(testCase)` in function literal - - "G108: Profiling endpoint is automatically exposed on /debug/pprof" + - "G108: Profiling endpoint is automatically exposed on /debug/pprof" + - Error return value of .((os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*print(f|ln)?|os\.(Un)?Setenv). is not checked + - "exported: exported method .*\\.(Reconcile|SetupWithManager|SetupWebhookWithManager) should have comment or be unexported" + # The following are being worked on to remove their exclusion. This list should be reduced or go away all together over time. + # If it is decided they will not be addressed they should be moved above this comment. + - Subprocess launch(ed with variable|ing should be audited) + - (Expect directory permissions to be 0750 or less|Expect file permissions to be 0600 or less) + - (G104|G307) + exclude-rules: + # With Go 1.16, the new embed directive can be used with an un-named import, + # revive (previously, golint) only allows these to be imported in a main.go, which wouldn't work for us. + # This directive allows the embed package to be imported with an underscore everywhere. + - linters: + - revive + source: _ "embed" + # Exclude some packages or code to require comments, for example test code, or fake clients. + - linters: + - revive + text: exported (method|function|type|const) (.+) should have comment or be unexported + source: (func|type).*Fake.* + - linters: + - revive + text: exported (method|function|type|const) (.+) should have comment or be unexported + path: fake_\.go + - linters: + - revive + text: exported (method|function|type|const) (.+) should have comment or be unexported + path: .*test/(providers|framework|e2e).*.go + # Disable unparam "always receives" which might not be really + # useful when building libraries. + - linters: + - unparam + text: always receives + # Dot imports for gomega or ginkgo are allowed + # within test files. + - path: _test\.go + text: should not use dot imports + - path: _test\.go + text: cyclomatic complexity + - path: test/(framework|e2e).*.go + text: should not use dot imports + # Append should be able to assign to a different var/slice. + - linters: + - gocritic + text: "appendAssign: append result not assigned to the same slice" + run: timeout: 10m skip-files: - - "zz_generated.*\\.go$" - - ".*conversion.*\\.go$" + - "zz_generated.*\\.go$" + - ".*conversion.*\\.go$" skip-dirs: - - third_party + - third_party + allow-parallel-runners: true \ No newline at end of file diff --git a/Makefile b/Makefile index 29ab43ec..6266b52f 100644 --- a/Makefile +++ b/Makefile @@ -112,8 +112,10 @@ manager-nested-controlplane: ## Build manager binary $(CONTROLLER_GEN): $(TOOLS_DIR)/go.mod # Build controller-gen from tools folder. cd $(TOOLS_DIR); go build -tags=tools -o $(BIN_DIR)/controller-gen sigs.k8s.io/controller-tools/cmd/controller-gen -$(GOLANGCI_LINT): $(TOOLS_DIR)/go.mod # Build golangci-lint from tools folder. - cd $(TOOLS_DIR); go build -tags=tools -o $(BIN_DIR)/golangci-lint github.com/golangci/golangci-lint/cmd/golangci-lint +$(GOLANGCI_LINT): # Download golanci-lint using hack script into tools folder. + hack/ensure-golangci-lint.sh \ + -b $(TOOLS_DIR)/$(BIN_DIR) \ + v1.40.1 $(RELEASE_NOTES): $(TOOLS_DIR)/go.mod cd $(TOOLS_DIR) && go build -tags=tools -o $(RELEASE_NOTES_BIN) sigs.k8s.io/cluster-api/hack/tools/release diff --git a/api/v1alpha4/groupversion_info.go b/api/v1alpha4/groupversion_info.go index 97ff37b3..44cb7192 100644 --- a/api/v1alpha4/groupversion_info.go +++ b/api/v1alpha4/groupversion_info.go @@ -14,9 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package v1alpha4 contains API Schema definitions for the infrastructure v1alpha4 API group -//+kubebuilder:object:generate=true -//+groupName=infrastructure.cluster.x-k8s.io +// Package v1alpha4 contains API Schema definitions for the infrastructure v1alpha4 API group. +// +kubebuilder:object:generate=true +// +groupName=infrastructure.cluster.x-k8s.io package v1alpha4 import ( @@ -25,10 +25,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "infrastructure.cluster.x-k8s.io", Version: "v1alpha4"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/api/v1alpha4/nestedcluster_types.go b/api/v1alpha4/nestedcluster_types.go index c814ce1d..dedff099 100644 --- a/api/v1alpha4/nestedcluster_types.go +++ b/api/v1alpha4/nestedcluster_types.go @@ -21,14 +21,14 @@ import ( clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha4" ) -// NestedClusterSpec defines the desired state of NestedCluster +// NestedClusterSpec defines the desired state of NestedCluster. type NestedClusterSpec struct { // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. // +optional ControlPlaneEndpoint clusterv1.APIEndpoint `json:"controlPlaneEndpoint"` } -// NestedClusterStatus defines the observed state of NestedCluster +// NestedClusterStatus defines the observed state of NestedCluster. type NestedClusterStatus struct { // Ready is when the NestedControlPlane has a API server URL. // +optional @@ -41,7 +41,7 @@ type NestedClusterStatus struct { //+kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" //+kubebuilder:subresource:status -// NestedCluster is the Schema for the nestedclusters API +// NestedCluster is the Schema for the nestedclusters API. type NestedCluster struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -52,7 +52,7 @@ type NestedCluster struct { //+kubebuilder:object:root=true -// NestedClusterList contains a list of NestedCluster +// NestedClusterList contains a list of NestedCluster. type NestedClusterList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/config/crd/bases/infrastructure.cluster.x-k8s.io_nestedclusters.yaml b/config/crd/bases/infrastructure.cluster.x-k8s.io_nestedclusters.yaml index d29f95b5..4664220f 100644 --- a/config/crd/bases/infrastructure.cluster.x-k8s.io_nestedclusters.yaml +++ b/config/crd/bases/infrastructure.cluster.x-k8s.io_nestedclusters.yaml @@ -4,7 +4,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - controller-gen.kubebuilder.io/version: v0.4.1-0.20201002000720-57250aac17f6 + controller-gen.kubebuilder.io/version: v0.6.0-beta.0 creationTimestamp: null name: nestedclusters.infrastructure.cluster.x-k8s.io spec: @@ -31,21 +31,26 @@ spec: name: v1alpha4 schema: openAPIV3Schema: - description: NestedCluster is the Schema for the nestedclusters API + description: NestedCluster is the Schema for the nestedclusters API. properties: apiVersion: - description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' + description: 'APIVersion defines the versioned schema of this representation + of an object. Servers should convert recognized schemas to the latest + internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' type: string kind: - description: 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' + description: 'Kind is a string value representing the REST resource this + object represents. Servers may infer this from the endpoint the client + submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' type: string metadata: type: object spec: - description: NestedClusterSpec defines the desired state of NestedCluster + description: NestedClusterSpec defines the desired state of NestedCluster. properties: controlPlaneEndpoint: - description: ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. + description: ControlPlaneEndpoint represents the endpoint used to + communicate with the control plane. properties: host: description: The hostname on which the API server is serving. @@ -60,10 +65,11 @@ spec: type: object type: object status: - description: NestedClusterStatus defines the observed state of NestedCluster + description: NestedClusterStatus defines the observed state of NestedCluster. properties: ready: - description: Ready is when the NestedControlPlane has a API server URL. + description: Ready is when the NestedControlPlane has a API server + URL. type: boolean type: object type: object diff --git a/controllers/nestedcluster_controller.go b/controllers/nestedcluster_controller.go index 3a3269f1..99d863a2 100644 --- a/controllers/nestedcluster_controller.go +++ b/controllers/nestedcluster_controller.go @@ -14,6 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package controllers contains all the Infrastructure group controllers for +// running nested clusters. package controllers import ( @@ -37,7 +39,7 @@ import ( //+kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=nestedclusters/finalizers,verbs=update //+kubebuilder:rbac:groups=controlplane.cluster.x-k8s.io,resources=nestedcontrolplanes,verbs=get;list;watch -// NestedClusterReconciler reconciles a NestedCluster object +// NestedClusterReconciler reconciles a NestedCluster object. type NestedClusterReconciler struct { client.Client Log logr.Logger diff --git a/controlplane/nested/api/v1alpha4/groupversion_info.go b/controlplane/nested/api/v1alpha4/groupversion_info.go index aa29a66e..84e2765a 100644 --- a/controlplane/nested/api/v1alpha4/groupversion_info.go +++ b/controlplane/nested/api/v1alpha4/groupversion_info.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package v1alpha4 contains API Schema definitions for the controlplane v1alpha4 API group +// Package v1alpha4 contains API Schema definitions for the controlplane v1alpha4 API group. // +kubebuilder:object:generate=true // +groupName=controlplane.cluster.x-k8s.io package v1alpha4 @@ -25,10 +25,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "controlplane.cluster.x-k8s.io", Version: "v1alpha4"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/controlplane/nested/api/v1alpha4/nestedapiserver_types.go b/controlplane/nested/api/v1alpha4/nestedapiserver_types.go index e1b27ebd..709f9652 100644 --- a/controlplane/nested/api/v1alpha4/nestedapiserver_types.go +++ b/controlplane/nested/api/v1alpha4/nestedapiserver_types.go @@ -22,21 +22,21 @@ import ( addonv1alpha1 "sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/addon/pkg/apis/v1alpha1" ) -// NestedAPIServerSpec defines the desired state of NestedAPIServer +// NestedAPIServerSpec defines the desired state of NestedAPIServer. type NestedAPIServerSpec struct { // NestedComponentSpec contains the common and user-specified information that are - // required for creating the component + // required for creating the component. // +optional NestedComponentSpec `json:",inline"` } -// NestedAPIServerStatus defines the observed state of NestedAPIServer +// NestedAPIServerStatus defines the observed state of NestedAPIServer. type NestedAPIServerStatus struct { - // APIServerService is the reference to the service that expose the APIServer + // APIServerService is the reference to the service that expose the APIServer. // +optional APIServerService *corev1.ObjectReference `json:"apiserverService,omitempty"` - // CommonStatus allows addons status monitoring + // CommonStatus allows addons status monitoring. addonv1alpha1.CommonStatus `json:",inline"` } @@ -46,7 +46,7 @@ type NestedAPIServerStatus struct { //+kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" //+kubebuilder:subresource:status -// NestedAPIServer is the Schema for the nestedapiservers API +// NestedAPIServer is the Schema for the nestedapiservers API. type NestedAPIServer struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -57,7 +57,7 @@ type NestedAPIServer struct { //+kubebuilder:object:root=true -// NestedAPIServerList contains a list of NestedAPIServer +// NestedAPIServerList contains a list of NestedAPIServer. type NestedAPIServerList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -72,30 +72,30 @@ var _ addonv1alpha1.CommonObject = &NestedAPIServer{} var _ addonv1alpha1.Patchable = &NestedAPIServer{} // ComponentName returns the name of the component for use with -// addonv1alpha1.CommonObject +// addonv1alpha1.CommonObject. func (c *NestedAPIServer) ComponentName() string { return string(APIServer) } // CommonSpec returns the addons spec of the object allowing common funcs like -// Channel & Version to be usable +// Channel & Version to be usable. func (c *NestedAPIServer) CommonSpec() addonv1alpha1.CommonSpec { return c.Spec.CommonSpec } // GetCommonStatus will return the common status for checking is a component -// was successfully deployed +// was successfully deployed. func (c *NestedAPIServer) GetCommonStatus() addonv1alpha1.CommonStatus { return c.Status.CommonStatus } // SetCommonStatus will set the status so that abstract representations can set -// Ready and Phases +// Ready and Phases. func (c *NestedAPIServer) SetCommonStatus(s addonv1alpha1.CommonStatus) { c.Status.CommonStatus = s } -// PatchSpec returns the patches to be applied +// PatchSpec returns the patches to be applied. func (c *NestedAPIServer) PatchSpec() addonv1alpha1.PatchSpec { return c.Spec.PatchSpec } diff --git a/controlplane/nested/api/v1alpha4/nestedcomponent_types.go b/controlplane/nested/api/v1alpha4/nestedcomponent_types.go index 5907e4cb..535e4866 100644 --- a/controlplane/nested/api/v1alpha4/nestedcomponent_types.go +++ b/controlplane/nested/api/v1alpha4/nestedcomponent_types.go @@ -21,38 +21,47 @@ import ( addonv1alpha1 "sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/addon/pkg/apis/v1alpha1" ) -// NestedComponentSpec defines the common fields for nested components +// NestedComponentSpec defines the common fields for nested components. type NestedComponentSpec struct { // NestedComponentSpec defines the common information for creating the - // component + // component. // +optional addonv1alpha1.CommonSpec `json:",inline"` - // PatchSpecs includes the user specified settings + // PatchSpecs includes the user specified settings. // +optional addonv1alpha1.PatchSpec `json:",inline"` // Resources defines the amount of computing resources that will be used - // by this component + // by this component. // +optional Resources corev1.ResourceRequirements `json:"resources,omitempty"` - // Replicas defines the number of replicas in the component's workload + // Replicas defines the number of replicas in the component's workload. // +optional Replicas int32 `json:"replicas,omitempty"` } +// ComponentPhase defines the state of the component. type ComponentPhase string const ( - Ready ComponentPhase = "Ready" + // Ready defines that the component is available and control plane can + // continue provisioning. + Ready ComponentPhase = "Ready" + + // Unready defines that the component is unavailable. Unready ComponentPhase = "Unready" ) +// ComponentKind defines the available kinds. type ComponentKind string const ( - APIServer ComponentKind = "NestedAPIServer" - Etcd ComponentKind = "NestedEtcd" + // APIServer defines the Kind name for the apiserver. + APIServer ComponentKind = "NestedAPIServer" + // Etcd defines the Kind name for the etcd. + Etcd ComponentKind = "NestedEtcd" + // ControllerManager defines the kind name for the controller-manager. ControllerManager ComponentKind = "NestedControllerManager" ) diff --git a/controlplane/nested/api/v1alpha4/nestedcontrollermanager_types.go b/controlplane/nested/api/v1alpha4/nestedcontrollermanager_types.go index f8eb46c2..0a8355fb 100644 --- a/controlplane/nested/api/v1alpha4/nestedcontrollermanager_types.go +++ b/controlplane/nested/api/v1alpha4/nestedcontrollermanager_types.go @@ -21,17 +21,17 @@ import ( addonv1alpha1 "sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/addon/pkg/apis/v1alpha1" ) -// NestedControllerManagerSpec defines the desired state of NestedControllerManager +// NestedControllerManagerSpec defines the desired state of NestedControllerManager. type NestedControllerManagerSpec struct { // NestedComponentSpec contains the common and user-specified information - // that are required for creating the component + // that are required for creating the component. // +optional NestedComponentSpec `json:",inline"` } -// NestedControllerManagerStatus defines the observed state of NestedControllerManager +// NestedControllerManagerStatus defines the observed state of NestedControllerManager. type NestedControllerManagerStatus struct { - // CommonStatus allows addons status monitoring + // CommonStatus allows addons status monitoring. addonv1alpha1.CommonStatus `json:",inline"` } @@ -41,7 +41,7 @@ type NestedControllerManagerStatus struct { //+kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" //+kubebuilder:subresource:status -// NestedControllerManager is the Schema for the nestedcontrollermanagers API +// NestedControllerManager is the Schema for the nestedcontrollermanagers API. type NestedControllerManager struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -52,7 +52,7 @@ type NestedControllerManager struct { //+kubebuilder:object:root=true -// NestedControllerManagerList contains a list of NestedControllerManager +// NestedControllerManagerList contains a list of NestedControllerManager. type NestedControllerManagerList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -67,30 +67,30 @@ var _ addonv1alpha1.CommonObject = &NestedControllerManager{} var _ addonv1alpha1.Patchable = &NestedControllerManager{} // ComponentName returns the name of the component for use with -// addonv1alpha1.CommonObject +// addonv1alpha1.CommonObject. func (c *NestedControllerManager) ComponentName() string { return string(ControllerManager) } // CommonSpec returns the addons spec of the object allowing common funcs like -// Channel & Version to be usable +// Channel & Version to be usable. func (c *NestedControllerManager) CommonSpec() addonv1alpha1.CommonSpec { return c.Spec.CommonSpec } // GetCommonStatus will return the common status for checking is a component -// was successfully deployed +// was successfully deployed. func (c *NestedControllerManager) GetCommonStatus() addonv1alpha1.CommonStatus { return c.Status.CommonStatus } // SetCommonStatus will set the status so that abstract representations can set -// Ready and Phases +// Ready and Phases. func (c *NestedControllerManager) SetCommonStatus(s addonv1alpha1.CommonStatus) { c.Status.CommonStatus = s } -// PatchSpec returns the patches to be applied +// PatchSpec returns the patches to be applied. func (c *NestedControllerManager) PatchSpec() addonv1alpha1.PatchSpec { return c.Spec.PatchSpec } diff --git a/controlplane/nested/api/v1alpha4/nestedcontrolplane_types.go b/controlplane/nested/api/v1alpha4/nestedcontrolplane_types.go index 8bb58888..8bba33b2 100644 --- a/controlplane/nested/api/v1alpha4/nestedcontrolplane_types.go +++ b/controlplane/nested/api/v1alpha4/nestedcontrolplane_types.go @@ -28,25 +28,25 @@ import ( const ( // NestedControlPlaneFinalizer is added to the NestedControlPlane to allow - // nested deletions to happen before the object is cleaned up + // nested deletions to happen before the object is cleaned up. NestedControlPlaneFinalizer = "nested.controlplane.cluster.x-k8s.io" ) -// NestedControlPlaneSpec defines the desired state of NestedControlPlane +// NestedControlPlaneSpec defines the desired state of NestedControlPlane. type NestedControlPlaneSpec struct { - // EtcdRef is the reference to the NestedEtcd + // EtcdRef is the reference to the NestedEtcd. EtcdRef *corev1.ObjectReference `json:"etcd,omitempty"` - // APIServerRef is the reference to the NestedAPIServer + // APIServerRef is the reference to the NestedAPIServer. // +optional APIServerRef *corev1.ObjectReference `json:"apiserver,omitempty"` - // ContollerManagerRef is the reference to the NestedControllerManager + // ContollerManagerRef is the reference to the NestedControllerManager. // +optional ControllerManagerRef *corev1.ObjectReference `json:"controllerManager,omitempty"` } -// NestedControlPlaneStatus defines the observed state of NestedControlPlane +// NestedControlPlaneStatus defines the observed state of NestedControlPlane. type NestedControlPlaneStatus struct { // Etcd stores the connection information from the downstream etcd // implementation if the NestedEtcd type isn't used this @@ -55,7 +55,7 @@ type NestedControlPlaneStatus struct { Etcd *NestedControlPlaneStatusEtcd `json:"etcd,omitempty"` // APIServer stores the connection information from the control plane - // this should contain anything shared between control plane components + // this should contain anything shared between control plane components. // +optional APIServer *NestedControlPlaneStatusAPIServer `json:"apiserver,omitempty"` @@ -64,7 +64,7 @@ type NestedControlPlaneStatus struct { Initialized bool `json:"initialized"` // Ready denotes that the NestedControlPlane API Server is ready to - // receive requests + // receive requests. // +kubebuilder:default=false Ready bool `json:"ready"` @@ -78,7 +78,7 @@ type NestedControlPlaneStatus struct { } // NestedControlPlaneStatusEtcd defines the status of the etcd component to -// allow other component controllers to take over the deployment +// allow other component controllers to take over the deployment. type NestedControlPlaneStatusEtcd struct { // Addresses defines how to address the etcd instance Addresses []NestedEtcdAddress `json:"addresses,omitempty"` @@ -86,9 +86,9 @@ type NestedControlPlaneStatusEtcd struct { // NestedControlPlaneStatusAPIServer defines the status of the APIServer // component, this allows the next set of component controllers to take over -// the deployment +// the deployment. type NestedControlPlaneStatusAPIServer struct { - // ServiceCIDRs which is provided to kube-apiserver and kube-controller-manager + // ServiceCIDRs which is provided to kube-apiserver and kube-controller-manager. // +optional ServiceCIDR string `json:"serviceCidr,omitempty"` } @@ -99,7 +99,7 @@ type NestedControlPlaneStatusAPIServer struct { //+kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" //+kubebuilder:subresource:status -// NestedControlPlane is the Schema for the nestedcontrolplanes API +// NestedControlPlane is the Schema for the nestedcontrolplanes API. type NestedControlPlane struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -110,7 +110,7 @@ type NestedControlPlane struct { // +kubebuilder:object:root=true -// NestedControlPlaneList contains a list of NestedControlPlane +// NestedControlPlaneList contains a list of NestedControlPlane. type NestedControlPlaneList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -121,15 +121,17 @@ func init() { SchemeBuilder.Register(&NestedControlPlane{}, &NestedControlPlaneList{}) } -// GetOwnerCluster is a utility to return the owning clusterv1.Cluster +// GetOwnerCluster is a utility to return the owning clusterv1.Cluster. func (r *NestedControlPlane) GetOwnerCluster(ctx context.Context, cli client.Client) (cluster *clusterv1.Cluster, err error) { return util.GetOwnerCluster(ctx, cli, r.ObjectMeta) } +// GetConditions will return the conditions from the status. func (r *NestedControlPlane) GetConditions() clusterv1.Conditions { return r.Status.Conditions } +// SetConditions will reset the conditions to the new ones. func (r *NestedControlPlane) SetConditions(conditions clusterv1.Conditions) { r.Status.Conditions = conditions } diff --git a/controlplane/nested/api/v1alpha4/nestedetcd_types.go b/controlplane/nested/api/v1alpha4/nestedetcd_types.go index 2cd01dc9..793bbe99 100644 --- a/controlplane/nested/api/v1alpha4/nestedetcd_types.go +++ b/controlplane/nested/api/v1alpha4/nestedetcd_types.go @@ -21,33 +21,33 @@ import ( addonv1alpha1 "sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/addon/pkg/apis/v1alpha1" ) -// NestedEtcdSpec defines the desired state of NestedEtcd +// NestedEtcdSpec defines the desired state of NestedEtcd. type NestedEtcdSpec struct { // NestedComponentSpec contains the common and user-specified information - // that are required for creating the component + // that are required for creating the component. // +optional NestedComponentSpec `json:",inline"` } -// NestedEtcdStatus defines the observed state of NestedEtcd +// NestedEtcdStatus defines the observed state of NestedEtcd. type NestedEtcdStatus struct { - // EtcdDomain defines how to address the etcd instance + // EtcdDomain defines how to address the etcd instance. Addresses []NestedEtcdAddress `json:"addresses,omitempty"` - // CommonStatus allows addons status monitoring + // CommonStatus allows addons status monitoring. addonv1alpha1.CommonStatus `json:",inline"` } -// EtcdAddress defines the observed addresses for etcd +// NestedEtcdAddress defines the observed addresses for etcd. type NestedEtcdAddress struct { // IP Address of the etcd instance. // +optional IP string `json:"ip,omitempty"` - // Hostname of the etcd instance + // Hostname of the etcd instance. Hostname string `json:"hostname,omitempty"` - // Port of the etcd instance + // Port of the etcd instance. // +optional Port int32 `json:"port"` } @@ -58,7 +58,7 @@ type NestedEtcdAddress struct { //+kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" //+kubebuilder:subresource:status -// NestedEtcd is the Schema for the nestedetcds API +// NestedEtcd is the Schema for the nestedetcds API. type NestedEtcd struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -69,7 +69,7 @@ type NestedEtcd struct { //+kubebuilder:object:root=true -// NestedEtcdList contains a list of NestedEtcd +// NestedEtcdList contains a list of NestedEtcd. type NestedEtcdList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -84,30 +84,30 @@ var _ addonv1alpha1.CommonObject = &NestedEtcd{} var _ addonv1alpha1.Patchable = &NestedEtcd{} // ComponentName returns the name of the component for use with -// addonv1alpha1.CommonObjec +// addonv1alpha1.CommonObject. func (c *NestedEtcd) ComponentName() string { return string(Etcd) } // CommonSpec returns the addons spec of the object allowing common funcs like -// Channel & Version to be usabl +// Channel & Version to be usable. func (c *NestedEtcd) CommonSpec() addonv1alpha1.CommonSpec { return c.Spec.CommonSpec } // GetCommonStatus will return the common status for checking is a component -// was successfully deployed +// was successfully deployed. func (c *NestedEtcd) GetCommonStatus() addonv1alpha1.CommonStatus { return c.Status.CommonStatus } // SetCommonStatus will set the status so that abstract representations can set -// Ready and Phases +// Ready and Phases. func (c *NestedEtcd) SetCommonStatus(s addonv1alpha1.CommonStatus) { c.Status.CommonStatus = s } -// PatchSpec returns the patches to be applie +// PatchSpec returns the patches to be applied. func (c *NestedEtcd) PatchSpec() addonv1alpha1.PatchSpec { return c.Spec.PatchSpec } diff --git a/controlplane/nested/certificate/consts.go b/controlplane/nested/certificate/consts.go index db676f05..81148b42 100644 --- a/controlplane/nested/certificate/consts.go +++ b/controlplane/nested/certificate/consts.go @@ -11,33 +11,34 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package certificate contains helpers for managing KeyPairs. package certificate import "sigs.k8s.io/cluster-api/util/secret" const ( // defaultClusterDomain defines the default that all control planes are - // provisioned with + // provisioned with. defaultClusterDomain = "cluster.local" - // EtcdClient defines the client cert name for etcd + // EtcdClient defines the client cert name for etcd. EtcdClient secret.Purpose = "etcd-client" - // EtcdHealthClient defines the client cert name for etcd + // EtcdHealthClient defines the client cert name for etcd. EtcdHealthClient secret.Purpose = "etcd-health-client" - // APIServerClient defines the client cert name for apiserver + // APIServerClient defines the client cert name for apiserver. APIServerClient secret.Purpose = "apiserver-client" - // APIServerEtcdClient mirrors capi APIServerEtcdClient + // APIServerEtcdClient mirrors capi APIServerEtcdClient. APIServerEtcdClient secret.Purpose = secret.APIServerEtcdClient - // KubeletClient defines the client cert name for kubelet + // KubeletClient defines the client cert name for kubelet. KubeletClient secret.Purpose = "kubelet-client" - // ProxyClient defines the client cert name for the front proxy + // ProxyClient defines the client cert name for the front proxy. ProxyClient secret.Purpose = "proxy-client" - // ControllerManagerKubeconfig defines the secret purpose for KCM Kubeconfigs + // ControllerManagerKubeconfig defines the secret purpose for KCM Kubeconfigs. ControllerManagerKubeconfig secret.Purpose = "controller-manager-kubeconfig" ) diff --git a/controlplane/nested/certificate/helpers.go b/controlplane/nested/certificate/helpers.go index 37280ba3..7e41aeb6 100644 --- a/controlplane/nested/certificate/helpers.go +++ b/controlplane/nested/certificate/helpers.go @@ -25,7 +25,7 @@ import ( "sigs.k8s.io/cluster-api-provider-nested/controlplane/nested/certificate/util" ) -// NewAPIServerCertAndKey creates crt and key for apiserver using ca. +// NewAPIServerCrtAndKey creates crt and key for apiserver using ca. func NewAPIServerCrtAndKey(ca *KeyPair, clusterName, clusterDomainArg, apiserverDomain string, apiserverIPs ...string) (*KeyPair, error) { clusterDomain := defaultClusterDomain if clusterDomainArg != "" { @@ -41,7 +41,7 @@ func NewAPIServerCrtAndKey(ca *KeyPair, clusterName, clusterDomainArg, apiserver "kubernetes.default.svc", fmt.Sprintf("kubernetes.default.svc.%s", clusterDomain), apiserverDomain, - // add virtual cluster name (i.e. namespace) for vn-agent + // add virtual cluster name (i.e. namespace) for vn-agent. clusterName, }, } @@ -96,8 +96,8 @@ func NewAPIServerKubeletClientCertAndKey(ca *KeyPair) (*KeyPair, error) { return &KeyPair{KubeletClient, apiClientCert, rsaKey, true, true}, nil } -// NewEtcdServerCrtAndKey creates new crt-key pair using ca for etcd -func NewEtcdServerCrtAndKey(ca *KeyPair, etcdDomains []string) (*KeyPair, error) { +// NewEtcdServerCertAndKey creates new crt-key pair using ca for etcd. +func NewEtcdServerCertAndKey(ca *KeyPair, etcdDomains []string) (*KeyPair, error) { // create AltNames with defaults DNSNames/IPs altNames := &cert.AltNames{ DNSNames: etcdDomains, @@ -108,7 +108,7 @@ func NewEtcdServerCrtAndKey(ca *KeyPair, etcdDomains []string) (*KeyPair, error) Config: cert.Config{ CommonName: "kube-etcd", AltNames: *altNames, - // all peers will use this crt-key pair as well + // all peers will use this crt-key pair as well. Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, }, } diff --git a/controlplane/nested/certificate/keypair.go b/controlplane/nested/certificate/keypair.go index 57c9e242..4105a20d 100644 --- a/controlplane/nested/certificate/keypair.go +++ b/controlplane/nested/certificate/keypair.go @@ -26,6 +26,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) +// AsSecret will take a KeyPair and convert it into a corev1.Secret. func (k *KeyPair) AsSecret(clusterName client.ObjectKey, owner metav1.OwnerReference) *corev1.Secret { s := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ diff --git a/controlplane/nested/certificate/keypairs.go b/controlplane/nested/certificate/keypairs.go index e3f15488..c12f1aaa 100644 --- a/controlplane/nested/certificate/keypairs.go +++ b/controlplane/nested/certificate/keypairs.go @@ -66,17 +66,13 @@ func (kp KeyPairs) SaveGenerated(ctx context.Context, ctrlclient client.Client, return nil } -// LookupOrGenerate is a convenience function that wraps cluster bootstrap certificate behavior. +// LookupOrSave is a convenience function that wraps cluster bootstrap certificate behavior. func (kp KeyPairs) LookupOrSave(ctx context.Context, ctrlclient client.Client, clusterName client.ObjectKey, owner metav1.OwnerReference) error { // Find the certificates that exist if err := kp.Lookup(ctx, ctrlclient, clusterName); err != nil { return err } - // Save any certificates that have been generated - if err := kp.SaveGenerated(ctx, ctrlclient, clusterName, owner); err != nil { - return err - } - - return nil + // Save any certificates that have been generated. + return kp.SaveGenerated(ctx, ctrlclient, clusterName, owner) } diff --git a/controlplane/nested/certificate/keypairs_test.go b/controlplane/nested/certificate/keypairs_test.go index ba541354..0bcba84e 100644 --- a/controlplane/nested/certificate/keypairs_test.go +++ b/controlplane/nested/certificate/keypairs_test.go @@ -17,15 +17,15 @@ import ( "context" "testing" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" controlplanev1 "sigs.k8s.io/cluster-api-provider-nested/controlplane/nested/api/v1alpha4" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" ) -func newSecret(fns ...func(*v1.Secret)) *v1.Secret { - secret := &v1.Secret{} +func newSecret(fns ...func(*corev1.Secret)) *corev1.Secret { + secret := &corev1.Secret{} for _, fn := range fns { fn(secret) } @@ -59,7 +59,7 @@ func TestKeyPairs_Lookup(t *testing.T) { KeyPairs{&KeyPair{Purpose: EtcdClient, New: true}}, args{ ctx, - fake.NewFakeClient(newSecret(func(s *v1.Secret) { + fake.NewFakeClient(newSecret(func(s *corev1.Secret) { s.Name = "test-cluster-etcd-client" s.Namespace = "default" })), @@ -123,8 +123,10 @@ func TestKeyPairs_SaveGenerated(t *testing.T) { t.Errorf("KeyPairs.SaveGenerated() error = %v, wantErr %v", err, tt.wantErr) } - secrets := &v1.SecretList{} - tt.args.ctrlclient.List(tt.args.ctx, secrets) + secrets := &corev1.SecretList{} + if err := tt.args.ctrlclient.List(tt.args.ctx, secrets); err != nil { + t.Errorf("List().Err expected = got %v", err) + } if len(secrets.Items) != tt.wantCount { t.Errorf("KeyPairs.SaveGenerated().Count expected = %v, got %v", len(secrets.Items), tt.wantCount) } diff --git a/controlplane/nested/certificate/types.go b/controlplane/nested/certificate/types.go index 65965155..2c97f707 100644 --- a/controlplane/nested/certificate/types.go +++ b/controlplane/nested/certificate/types.go @@ -21,7 +21,7 @@ import ( ) // KeyPair defines a cert/key pair that is used for the Kubernetes clients -// this was inspired by CAPI's KCP and how it manages CAs +// this was inspired by CAPI's KCP and how it manages CAs. type KeyPair struct { Purpose secret.Purpose Cert *x509.Certificate @@ -31,5 +31,5 @@ type KeyPair struct { } // KeyPairs defines a set of keypairs to act on, this is useful in providing -// helpers to operate on many keypairs +// helpers to operate on many keypairs. type KeyPairs []*KeyPair diff --git a/controlplane/nested/certificate/util/util.go b/controlplane/nested/certificate/util/util.go index a829d59a..41888108 100644 --- a/controlplane/nested/certificate/util/util.go +++ b/controlplane/nested/certificate/util/util.go @@ -11,6 +11,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package util contains helpers for creating private keys and certs. package util import ( @@ -37,7 +38,7 @@ const ( rsaPrivateKeyBlockType = "RSA PRIVATE KEY" rsaKeySize = 2048 - // certificateValidity defines the validity for all the signed certificates generated by this package + // certificateValidity defines the validity for all the signed certificates generated by this package. certificateValidity = time.Hour * 24 * 365 ) @@ -47,7 +48,7 @@ type CertConfig struct { PublicKeyAlgorithm x509.PublicKeyAlgorithm } -// NewCertAndKey creates new certificate and key by passing the certificate authority certificate and key +// NewCertAndKey creates new certificate and key by passing the certificate authority certificate and key. func NewCertAndKey(caCert *x509.Certificate, caKey crypto.Signer, config *CertConfig) (*x509.Certificate, crypto.Signer, error) { key, err := NewPrivateKey(config.PublicKeyAlgorithm) if err != nil { @@ -62,7 +63,7 @@ func NewCertAndKey(caCert *x509.Certificate, caKey crypto.Signer, config *CertCo return cert, key, nil } -// NewPrivateKey creates an RSA private key +// NewPrivateKey creates an RSA private key. func NewPrivateKey(keyType x509.PublicKeyAlgorithm) (crypto.Signer, error) { if keyType == x509.ECDSA { return ecdsa.GenerateKey(elliptic.P256(), cryptorand.Reader) @@ -71,7 +72,7 @@ func NewPrivateKey(keyType x509.PublicKeyAlgorithm) (crypto.Signer, error) { return rsa.GenerateKey(cryptorand.Reader, rsaKeySize) } -// NewSignedCert creates a signed certificate using the given CA certificate and key +// NewSignedCert creates a signed certificate using the given CA certificate and key. func NewSignedCert(cfg *CertConfig, key crypto.Signer, caCert *x509.Certificate, caKey crypto.Signer) (*x509.Certificate, error) { serial, err := cryptorand.Int(cryptorand.Reader, new(big.Int).SetInt64(math.MaxInt64)) if err != nil { @@ -104,7 +105,7 @@ func NewSignedCert(cfg *CertConfig, key crypto.Signer, caCert *x509.Certificate, return x509.ParseCertificate(certDERBytes) } -// EncodeCertPEM returns PEM-endcoded certificate data +// EncodeCertPEM returns PEM-endcoded certificate data. func EncodeCertPEM(cert *x509.Certificate) []byte { block := pem.Block{ Type: certificateBlockType, @@ -113,7 +114,7 @@ func EncodeCertPEM(cert *x509.Certificate) []byte { return pem.EncodeToMemory(&block) } -// EncodePrivateKeyPEM returns PEM-encoded private key data +// EncodePrivateKeyPEM returns PEM-encoded private key data. func EncodePrivateKeyPEM(key *rsa.PrivateKey) []byte { block := pem.Block{ Type: rsaPrivateKeyBlockType, diff --git a/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedapiservers.yaml b/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedapiservers.yaml index d6fbdda9..07fac27c 100644 --- a/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedapiservers.yaml +++ b/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedapiservers.yaml @@ -4,7 +4,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - controller-gen.kubebuilder.io/version: v0.4.1-0.20201002000720-57250aac17f6 + controller-gen.kubebuilder.io/version: v0.6.0-beta.0 creationTimestamp: null name: nestedapiservers.controlplane.cluster.x-k8s.io spec: @@ -31,32 +31,39 @@ spec: name: v1alpha4 schema: openAPIV3Schema: - description: NestedAPIServer is the Schema for the nestedapiservers API + description: NestedAPIServer is the Schema for the nestedapiservers API. properties: apiVersion: - description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' + description: 'APIVersion defines the versioned schema of this representation + of an object. Servers should convert recognized schemas to the latest + internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' type: string kind: - description: 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' + description: 'Kind is a string value representing the REST resource this + object represents. Servers may infer this from the endpoint the client + submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' type: string metadata: type: object spec: - description: NestedAPIServerSpec defines the desired state of NestedAPIServer + description: NestedAPIServerSpec defines the desired state of NestedAPIServer. properties: channel: - description: 'Channel specifies a channel that can be used to resolve a specific addon, eg: stable It will be ignored if Version is specified' + description: 'Channel specifies a channel that can be used to resolve + a specific addon, eg: stable It will be ignored if Version is specified' type: string patches: items: type: object type: array replicas: - description: Replicas defines the number of replicas in the component's workload + description: Replicas defines the number of replicas in the component's + workload. format: int32 type: integer resources: - description: Resources defines the amount of computing resources that will be used by this component + description: Resources defines the amount of computing resources that + will be used by this component. properties: limits: additionalProperties: @@ -65,7 +72,8 @@ spec: - type: string pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ x-kubernetes-int-or-string: true - description: 'Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/' + description: 'Limits describes the maximum amount of compute resources + allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/' type: object requests: additionalProperties: @@ -74,24 +82,39 @@ spec: - type: string pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ x-kubernetes-int-or-string: true - description: 'Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/' + description: 'Requests describes the minimum amount of compute + resources required. If Requests is omitted for a container, + it defaults to Limits if that is explicitly specified, otherwise + to an implementation-defined value. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/' type: object type: object version: - description: Version specifies the exact addon version to be deployed, eg 1.2.3 It should not be specified if Channel is specified + description: Version specifies the exact addon version to be deployed, + eg 1.2.3 It should not be specified if Channel is specified type: string type: object status: - description: NestedAPIServerStatus defines the observed state of NestedAPIServer + description: NestedAPIServerStatus defines the observed state of NestedAPIServer. properties: apiserverService: - description: APIServerService is the reference to the service that expose the APIServer + description: APIServerService is the reference to the service that + expose the APIServer. properties: apiVersion: description: API version of the referent. type: string fieldPath: - description: 'If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: "spec.containers{name}" (where "name" refers to the name of the container that triggered the event) or if no container name is specified "spec.containers[2]" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object. TODO: this design is not final and this field is subject to change in the future.' + description: 'If referring to a piece of an object instead of + an entire object, this string should contain a valid JSON/Go + field access statement, such as desiredState.manifest.containers[2]. + For example, if the object reference is to a container within + a pod, this would take on a value like: "spec.containers{name}" + (where "name" refers to the name of the container that triggered + the event) or if no container name is specified "spec.containers[2]" + (container with index 2 in this pod). This syntax is chosen + only to have some well-defined way of referencing a part of + an object. TODO: this design is not final and this field is + subject to change in the future.' type: string kind: description: 'Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' @@ -103,7 +126,8 @@ spec: description: 'Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/' type: string resourceVersion: - description: 'Specific resourceVersion to which this reference is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency' + description: 'Specific resourceVersion to which this reference + is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency' type: string uid: description: 'UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids' diff --git a/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedcontrollermanagers.yaml b/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedcontrollermanagers.yaml index 4bb4ceb5..50224605 100644 --- a/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedcontrollermanagers.yaml +++ b/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedcontrollermanagers.yaml @@ -4,7 +4,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - controller-gen.kubebuilder.io/version: v0.4.1-0.20201002000720-57250aac17f6 + controller-gen.kubebuilder.io/version: v0.6.0-beta.0 creationTimestamp: null name: nestedcontrollermanagers.controlplane.cluster.x-k8s.io spec: @@ -31,32 +31,41 @@ spec: name: v1alpha4 schema: openAPIV3Schema: - description: NestedControllerManager is the Schema for the nestedcontrollermanagers API + description: NestedControllerManager is the Schema for the nestedcontrollermanagers + API. properties: apiVersion: - description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' + description: 'APIVersion defines the versioned schema of this representation + of an object. Servers should convert recognized schemas to the latest + internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' type: string kind: - description: 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' + description: 'Kind is a string value representing the REST resource this + object represents. Servers may infer this from the endpoint the client + submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' type: string metadata: type: object spec: - description: NestedControllerManagerSpec defines the desired state of NestedControllerManager + description: NestedControllerManagerSpec defines the desired state of + NestedControllerManager. properties: channel: - description: 'Channel specifies a channel that can be used to resolve a specific addon, eg: stable It will be ignored if Version is specified' + description: 'Channel specifies a channel that can be used to resolve + a specific addon, eg: stable It will be ignored if Version is specified' type: string patches: items: type: object type: array replicas: - description: Replicas defines the number of replicas in the component's workload + description: Replicas defines the number of replicas in the component's + workload. format: int32 type: integer resources: - description: Resources defines the amount of computing resources that will be used by this component + description: Resources defines the amount of computing resources that + will be used by this component. properties: limits: additionalProperties: @@ -65,7 +74,8 @@ spec: - type: string pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ x-kubernetes-int-or-string: true - description: 'Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/' + description: 'Limits describes the maximum amount of compute resources + allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/' type: object requests: additionalProperties: @@ -74,15 +84,20 @@ spec: - type: string pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ x-kubernetes-int-or-string: true - description: 'Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/' + description: 'Requests describes the minimum amount of compute + resources required. If Requests is omitted for a container, + it defaults to Limits if that is explicitly specified, otherwise + to an implementation-defined value. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/' type: object type: object version: - description: Version specifies the exact addon version to be deployed, eg 1.2.3 It should not be specified if Channel is specified + description: Version specifies the exact addon version to be deployed, + eg 1.2.3 It should not be specified if Channel is specified type: string type: object status: - description: NestedControllerManagerStatus defines the observed state of NestedControllerManager + description: NestedControllerManagerStatus defines the observed state + of NestedControllerManager. properties: errors: items: diff --git a/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedcontrolplanes.yaml b/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedcontrolplanes.yaml index 549d9ad5..85f7a205 100644 --- a/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedcontrolplanes.yaml +++ b/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedcontrolplanes.yaml @@ -4,7 +4,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - controller-gen.kubebuilder.io/version: v0.4.1-0.20201002000720-57250aac17f6 + controller-gen.kubebuilder.io/version: v0.6.0-beta.0 creationTimestamp: null name: nestedcontrolplanes.controlplane.cluster.x-k8s.io spec: @@ -31,27 +31,42 @@ spec: name: v1alpha4 schema: openAPIV3Schema: - description: NestedControlPlane is the Schema for the nestedcontrolplanes API + description: NestedControlPlane is the Schema for the nestedcontrolplanes + API. properties: apiVersion: - description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' + description: 'APIVersion defines the versioned schema of this representation + of an object. Servers should convert recognized schemas to the latest + internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' type: string kind: - description: 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' + description: 'Kind is a string value representing the REST resource this + object represents. Servers may infer this from the endpoint the client + submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' type: string metadata: type: object spec: - description: NestedControlPlaneSpec defines the desired state of NestedControlPlane + description: NestedControlPlaneSpec defines the desired state of NestedControlPlane. properties: apiserver: - description: APIServerRef is the reference to the NestedAPIServer + description: APIServerRef is the reference to the NestedAPIServer. properties: apiVersion: description: API version of the referent. type: string fieldPath: - description: 'If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: "spec.containers{name}" (where "name" refers to the name of the container that triggered the event) or if no container name is specified "spec.containers[2]" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object. TODO: this design is not final and this field is subject to change in the future.' + description: 'If referring to a piece of an object instead of + an entire object, this string should contain a valid JSON/Go + field access statement, such as desiredState.manifest.containers[2]. + For example, if the object reference is to a container within + a pod, this would take on a value like: "spec.containers{name}" + (where "name" refers to the name of the container that triggered + the event) or if no container name is specified "spec.containers[2]" + (container with index 2 in this pod). This syntax is chosen + only to have some well-defined way of referencing a part of + an object. TODO: this design is not final and this field is + subject to change in the future.' type: string kind: description: 'Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' @@ -63,20 +78,31 @@ spec: description: 'Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/' type: string resourceVersion: - description: 'Specific resourceVersion to which this reference is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency' + description: 'Specific resourceVersion to which this reference + is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency' type: string uid: description: 'UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids' type: string type: object controllerManager: - description: ContollerManagerRef is the reference to the NestedControllerManager + description: ContollerManagerRef is the reference to the NestedControllerManager. properties: apiVersion: description: API version of the referent. type: string fieldPath: - description: 'If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: "spec.containers{name}" (where "name" refers to the name of the container that triggered the event) or if no container name is specified "spec.containers[2]" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object. TODO: this design is not final and this field is subject to change in the future.' + description: 'If referring to a piece of an object instead of + an entire object, this string should contain a valid JSON/Go + field access statement, such as desiredState.manifest.containers[2]. + For example, if the object reference is to a container within + a pod, this would take on a value like: "spec.containers{name}" + (where "name" refers to the name of the container that triggered + the event) or if no container name is specified "spec.containers[2]" + (container with index 2 in this pod). This syntax is chosen + only to have some well-defined way of referencing a part of + an object. TODO: this design is not final and this field is + subject to change in the future.' type: string kind: description: 'Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' @@ -88,20 +114,31 @@ spec: description: 'Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/' type: string resourceVersion: - description: 'Specific resourceVersion to which this reference is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency' + description: 'Specific resourceVersion to which this reference + is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency' type: string uid: description: 'UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids' type: string type: object etcd: - description: EtcdRef is the reference to the NestedEtcd + description: EtcdRef is the reference to the NestedEtcd. properties: apiVersion: description: API version of the referent. type: string fieldPath: - description: 'If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: "spec.containers{name}" (where "name" refers to the name of the container that triggered the event) or if no container name is specified "spec.containers[2]" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object. TODO: this design is not final and this field is subject to change in the future.' + description: 'If referring to a piece of an object instead of + an entire object, this string should contain a valid JSON/Go + field access statement, such as desiredState.manifest.containers[2]. + For example, if the object reference is to a container within + a pod, this would take on a value like: "spec.containers{name}" + (where "name" refers to the name of the container that triggered + the event) or if no container name is specified "spec.containers[2]" + (container with index 2 in this pod). This syntax is chosen + only to have some well-defined way of referencing a part of + an object. TODO: this design is not final and this field is + subject to change in the future.' type: string kind: description: 'Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' @@ -113,7 +150,8 @@ spec: description: 'Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/' type: string resourceVersion: - description: 'Specific resourceVersion to which this reference is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency' + description: 'Specific resourceVersion to which this reference + is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency' type: string uid: description: 'UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids' @@ -121,38 +159,57 @@ spec: type: object type: object status: - description: NestedControlPlaneStatus defines the observed state of NestedControlPlane + description: NestedControlPlaneStatus defines the observed state of NestedControlPlane. properties: apiserver: - description: APIServer stores the connection information from the control plane this should contain anything shared between control plane components + description: APIServer stores the connection information from the + control plane this should contain anything shared between control + plane components. properties: serviceCidr: - description: ServiceCIDRs which is provided to kube-apiserver and kube-controller-manager + description: ServiceCIDRs which is provided to kube-apiserver + and kube-controller-manager. type: string type: object conditions: - description: Conditions specifies the conditions for the managed control plane + description: Conditions specifies the conditions for the managed control + plane items: - description: Condition defines an observation of a Cluster API resource operational state. + description: Condition defines an observation of a Cluster API resource + operational state. properties: lastTransitionTime: - description: Last time the condition transitioned from one status to another. This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + description: Last time the condition transitioned from one status + to another. This should be when the underlying condition changed. + If that is not known, then using the time when the API field + changed is acceptable. format: date-time type: string message: - description: A human readable message indicating details about the transition. This field may be empty. + description: A human readable message indicating details about + the transition. This field may be empty. type: string reason: - description: The reason for the condition's last transition in CamelCase. The specific API may choose whether or not this field is considered a guaranteed API. This field may not be empty. + description: The reason for the condition's last transition + in CamelCase. The specific API may choose whether or not this + field is considered a guaranteed API. This field may not be + empty. type: string severity: - description: Severity provides an explicit classification of Reason code, so the users or machines can immediately understand the current situation and act accordingly. The Severity field MUST be set only when Status=False. + description: Severity provides an explicit classification of + Reason code, so the users or machines can immediately understand + the current situation and act accordingly. The Severity field + MUST be set only when Status=False. type: string status: description: Status of the condition, one of True, False, Unknown. type: string type: - description: Type of condition in CamelCase or in foo.example.com/CamelCase. Many .condition.type values are consistent across resources like Available, but because arbitrary conditions can be useful (see .node.status.conditions), the ability to deconflict is important. + description: Type of condition in CamelCase or in foo.example.com/CamelCase. + Many .condition.type values are consistent across resources + like Available, but because arbitrary conditions can be useful + (see .node.status.conditions), the ability to deconflict is + important. type: string required: - status @@ -160,35 +217,41 @@ spec: type: object type: array etcd: - description: Etcd stores the connection information from the downstream etcd implementation if the NestedEtcd type isn't used this allows other component controllers to fetch the endpoints. + description: Etcd stores the connection information from the downstream + etcd implementation if the NestedEtcd type isn't used this allows + other component controllers to fetch the endpoints. properties: addresses: description: Addresses defines how to address the etcd instance items: - description: EtcdAddress defines the observed addresses for etcd + description: NestedEtcdAddress defines the observed addresses + for etcd. properties: hostname: - description: Hostname of the etcd instance + description: Hostname of the etcd instance. type: string ip: description: IP Address of the etcd instance. type: string port: - description: Port of the etcd instance + description: Port of the etcd instance. format: int32 type: integer type: object type: array type: object failureMessage: - description: ErrorMessage indicates that there is a terminal problem reconciling the state, and will be set to a descriptive error message. + description: ErrorMessage indicates that there is a terminal problem + reconciling the state, and will be set to a descriptive error message. type: string initialized: - description: Initialized denotes whether or not the control plane finished initializing. + description: Initialized denotes whether or not the control plane + finished initializing. type: boolean ready: default: false - description: Ready denotes that the NestedControlPlane API Server is ready to receive requests + description: Ready denotes that the NestedControlPlane API Server + is ready to receive requests. type: boolean required: - ready diff --git a/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedetcds.yaml b/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedetcds.yaml index aab3535d..2bf6cd2d 100644 --- a/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedetcds.yaml +++ b/controlplane/nested/config/crd/bases/controlplane.cluster.x-k8s.io_nestedetcds.yaml @@ -4,7 +4,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - controller-gen.kubebuilder.io/version: v0.4.1-0.20201002000720-57250aac17f6 + controller-gen.kubebuilder.io/version: v0.6.0-beta.0 creationTimestamp: null name: nestedetcds.controlplane.cluster.x-k8s.io spec: @@ -31,32 +31,39 @@ spec: name: v1alpha4 schema: openAPIV3Schema: - description: NestedEtcd is the Schema for the nestedetcds API + description: NestedEtcd is the Schema for the nestedetcds API. properties: apiVersion: - description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' + description: 'APIVersion defines the versioned schema of this representation + of an object. Servers should convert recognized schemas to the latest + internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' type: string kind: - description: 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' + description: 'Kind is a string value representing the REST resource this + object represents. Servers may infer this from the endpoint the client + submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' type: string metadata: type: object spec: - description: NestedEtcdSpec defines the desired state of NestedEtcd + description: NestedEtcdSpec defines the desired state of NestedEtcd. properties: channel: - description: 'Channel specifies a channel that can be used to resolve a specific addon, eg: stable It will be ignored if Version is specified' + description: 'Channel specifies a channel that can be used to resolve + a specific addon, eg: stable It will be ignored if Version is specified' type: string patches: items: type: object type: array replicas: - description: Replicas defines the number of replicas in the component's workload + description: Replicas defines the number of replicas in the component's + workload. format: int32 type: integer resources: - description: Resources defines the amount of computing resources that will be used by this component + description: Resources defines the amount of computing resources that + will be used by this component. properties: limits: additionalProperties: @@ -65,7 +72,8 @@ spec: - type: string pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ x-kubernetes-int-or-string: true - description: 'Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/' + description: 'Limits describes the maximum amount of compute resources + allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/' type: object requests: additionalProperties: @@ -74,29 +82,34 @@ spec: - type: string pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ x-kubernetes-int-or-string: true - description: 'Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/' + description: 'Requests describes the minimum amount of compute + resources required. If Requests is omitted for a container, + it defaults to Limits if that is explicitly specified, otherwise + to an implementation-defined value. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/' type: object type: object version: - description: Version specifies the exact addon version to be deployed, eg 1.2.3 It should not be specified if Channel is specified + description: Version specifies the exact addon version to be deployed, + eg 1.2.3 It should not be specified if Channel is specified type: string type: object status: - description: NestedEtcdStatus defines the observed state of NestedEtcd + description: NestedEtcdStatus defines the observed state of NestedEtcd. properties: addresses: - description: EtcdDomain defines how to address the etcd instance + description: EtcdDomain defines how to address the etcd instance. items: - description: EtcdAddress defines the observed addresses for etcd + description: NestedEtcdAddress defines the observed addresses for + etcd. properties: hostname: - description: Hostname of the etcd instance + description: Hostname of the etcd instance. type: string ip: description: IP Address of the etcd instance. type: string port: - description: Port of the etcd instance + description: Port of the etcd instance. format: int32 type: integer type: object diff --git a/controlplane/nested/config/rbac/role.yaml b/controlplane/nested/config/rbac/role.yaml index d1c8bc4d..c21cafa5 100644 --- a/controlplane/nested/config/rbac/role.yaml +++ b/controlplane/nested/config/rbac/role.yaml @@ -12,7 +12,7 @@ rules: - secrets verbs: - create - - delete + - delete. - get - list - patch diff --git a/controlplane/nested/controllers/consts.go b/controlplane/nested/controllers/consts.go index 95c8b107..d5cb2bce 100644 --- a/controlplane/nested/controllers/consts.go +++ b/controlplane/nested/controllers/consts.go @@ -14,6 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package controllers contains the controller for the Control Plane +// api group. package controllers const ( diff --git a/controlplane/nested/controllers/controller_util.go b/controlplane/nested/controllers/controller_util.go index 0e3d216a..499133aa 100644 --- a/controlplane/nested/controllers/controller_util.go +++ b/controlplane/nested/controllers/controller_util.go @@ -44,7 +44,7 @@ import ( // +kubebuilder:rbac:groups="";apps,resources=services/status;statefulsets/status,verbs=get;update;patch // createNestedComponentSts will create the StatefulSet that runs the -// NestedComponent +// NestedComponent. func createNestedComponentSts(ctx context.Context, cli ctrlcli.Client, ncMeta metav1.ObjectMeta, ncSpec controlplanev1.NestedComponentSpec, @@ -91,7 +91,7 @@ func createNestedComponentSts(ctx context.Context, } // genServiceObject generates the Service object corresponding to the -// NestedComponent +// NestedComponent. func genServiceObject( templatePath string, ncMeta metav1.ObjectMeta, @@ -132,7 +132,7 @@ func genServiceObject( } // genStatefulSetObject generates the StatefulSet object corresponding to the -// NestedComponent +// NestedComponent. func genStatefulSetObject( templatePath string, ncMeta metav1.ObjectMeta, @@ -212,7 +212,7 @@ func getTemplateArgs(ncMeta metav1.ObjectMeta, controlPlaneName, clusterName str } } -// yamlToObject deserialize the yaml to the runtime object +// yamlToObject deserialize the yaml to the runtime object. func yamlToObject(yamlContent []byte, obj runtime.Object) error { decode := serializer.NewCodecFactory(scheme.Scheme). UniversalDeserializer().Decode @@ -223,7 +223,7 @@ func yamlToObject(yamlContent []byte, obj runtime.Object) error { return nil } -// substituteTemplate substitutes the template contents with the context +// substituteTemplate substitutes the template contents with the context. func substituteTemplate(context interface{}, tmpl string) (string, error) { t, tmplPrsErr := template.New("test"). Option("missingkey=zero").Parse(tmpl) @@ -238,7 +238,7 @@ func substituteTemplate(context interface{}, tmpl string) (string, error) { return writer.String(), nil } -// fetchTemplate fetches the component template through the tmplateURL +// fetchTemplate fetches the component template through the tmplateURL. func fetchTemplate(templateURL string) (string, error) { rep, err := openuri.Open(templateURL) if err != nil { @@ -254,7 +254,7 @@ func fetchTemplate(templateURL string) (string, error) { return string(bodyBytes), nil } -// getOwner gets the ownerreference of the NestedComponent +// getOwner gets the ownerreference of the NestedComponent. func getOwner(ncMeta metav1.ObjectMeta) metav1.OwnerReference { owners := ncMeta.GetOwnerReferences() if len(owners) == 0 { @@ -270,7 +270,7 @@ func getOwner(ncMeta metav1.ObjectMeta) metav1.OwnerReference { } // genAPIServerSvcRef generates the ObjectReference that points to the -// APISrver service +// APISrver service. func genAPIServerSvcRef(cli ctrlcli.Client, nkas controlplanev1.NestedAPIServer, clusterName string) (corev1.ObjectReference, error) { var ( @@ -287,7 +287,7 @@ func genAPIServerSvcRef(cli ctrlcli.Client, return objRef, nil } -// genObjRefFromObj generates the ObjectReference of the given object +// genObjRefFromObj generates the ObjectReference of the given object. func genObjRefFromObj(obj ctrlcli.Object) corev1.ObjectReference { return corev1.ObjectReference{ Kind: obj.GetObjectKind().GroupVersionKind().Kind, @@ -298,6 +298,7 @@ func genObjRefFromObj(obj ctrlcli.Object) corev1.ObjectReference { } } +// IsComponentReady will return bool if status Ready. func IsComponentReady(status addonv1alpha1.CommonStatus) bool { return status.Phase == string(controlplanev1.Ready) } diff --git a/controlplane/nested/controllers/controller_util_test.go b/controlplane/nested/controllers/controller_util_test.go index 14d9c42e..6e74e444 100644 --- a/controlplane/nested/controllers/controller_util_test.go +++ b/controlplane/nested/controllers/controller_util_test.go @@ -66,7 +66,6 @@ func TestSubstituteTemplate(t *testing.T) { t.Fatalf("\t%s\texpect %v, but get %v", failed, st.expect, get) } t.Logf("\t%s\texpect %v, get %v", succeed, st.expect, get) - } } t.Run(st.name, tf) @@ -158,7 +157,6 @@ func TestGetOwner(t *testing.T) { t.Fatalf("\t%s\texpect %v, but get %v", failed, st.expect, get) } t.Logf("\t%s\texpect %v, get %v", succeed, st.expect, get) - } } t.Run(st.name, tf) @@ -202,7 +200,6 @@ func TestGenInitialClusterArgs(t *testing.T) { t.Fatalf("\t%s\texpect %v, but get %v", failed, st.expect, get) } t.Logf("\t%s\texpect %v, get %v", succeed, st.expect, get) - } } t.Run(st.name, tf) diff --git a/controlplane/nested/controllers/nestedapiserver_controller.go b/controlplane/nested/controllers/nestedapiserver_controller.go index 1a4c60c3..4c03b7fc 100644 --- a/controlplane/nested/controllers/nestedapiserver_controller.go +++ b/controlplane/nested/controllers/nestedapiserver_controller.go @@ -31,14 +31,13 @@ import ( "sigs.k8s.io/cluster-api/util/secret" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" - ctrlcli "sigs.k8s.io/controller-runtime/pkg/client" controlplanev1 "sigs.k8s.io/cluster-api-provider-nested/controlplane/nested/api/v1alpha4" "sigs.k8s.io/cluster-api-provider-nested/controlplane/nested/certificate" clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha4" ) -// NestedAPIServerReconciler reconciles a NestedAPIServer object +// NestedAPIServerReconciler reconciles a NestedAPIServer object. type NestedAPIServerReconciler struct { client.Client Log logr.Logger @@ -55,7 +54,7 @@ func (r *NestedAPIServerReconciler) Reconcile(ctx context.Context, req ctrl.Requ log.Info("Reconciling NestedAPIServer...") var nkas controlplanev1.NestedAPIServer if err := r.Get(ctx, req.NamespacedName, &nkas); err != nil { - return ctrl.Result{}, ctrlcli.IgnoreNotFound(err) + return ctrl.Result{}, client.IgnoreNotFound(err) } log.Info("creating NestedAPIServer", "namespace", nkas.GetNamespace(), @@ -78,7 +77,7 @@ func (r *NestedAPIServerReconciler) Reconcile(ctx context.Context, req ctrl.Requ log.Info("the owner could not be found, will retry later", "namespace", nkas.GetNamespace(), "name", owner.Name) - return ctrl.Result{}, ctrlcli.IgnoreNotFound(err) + return ctrl.Result{}, client.IgnoreNotFound(err) } cluster, err := ncp.GetOwnerCluster(ctx, r.Client) @@ -95,7 +94,7 @@ func (r *NestedAPIServerReconciler) Reconcile(ctx context.Context, req ctrl.Requ Name: nkasName, }, &nkasSts); err != nil { if apierrors.IsNotFound(err) { - // as the statefulset is not found, mark the NestedAPIServer as unready + // as the statefulset is not found, mark the NestedAPIServer as unready. if IsComponentReady(nkas.Status.CommonStatus) { nkas.Status.Phase = string(controlplanev1.Unready) @@ -111,7 +110,7 @@ func (r *NestedAPIServerReconciler) Reconcile(ctx context.Context, req ctrl.Requ return ctrl.Result{}, err } - // the statefulset is not found, create one + // the statefulset is not found, create one. if err := createNestedComponentSts(ctx, r.Client, nkas.ObjectMeta, nkas.Spec.NestedComponentSpec, controlplanev1.APIServer, owner.Name, cluster.GetName(), r.TemplatePath, log); err != nil { @@ -126,12 +125,12 @@ func (r *NestedAPIServerReconciler) Reconcile(ctx context.Context, req ctrl.Requ } // 3. reconcile the NestedAPIServer based on the status of the StatefulSet. - // Mark the NestedAPIServer as Ready if the StatefulSet is ready + // Mark the NestedAPIServer as Ready if the StatefulSet is ready. if nkasSts.Status.ReadyReplicas == nkasSts.Status.Replicas { log.Info("The NestedAPIServer StatefulSet is ready") if !IsComponentReady(nkas.Status.CommonStatus) { // As the NestedAPIServer StatefulSet is ready, update - // NestedAPIServer status + // NestedAPIServer status. nkas.Status.Phase = string(controlplanev1.Ready) objRef, err := genAPIServerSvcRef(r.Client, nkas, cluster.GetName()) if err != nil { @@ -152,7 +151,7 @@ func (r *NestedAPIServerReconciler) Reconcile(ctx context.Context, req ctrl.Requ } // mark the NestedAPIServer as unready, if the NestedAPIServer - // StatefulSet is unready, + // StatefulSet is unready. if IsComponentReady(nkas.Status.CommonStatus) { nkas.Status.Phase = string(controlplanev1.Unready) if err := r.Status().Update(ctx, &nkas); err != nil { @@ -170,20 +169,20 @@ func (r *NestedAPIServerReconciler) SetupWithManager(mgr ctrl.Manager) error { if err := mgr.GetFieldIndexer().IndexField(context.TODO(), &appsv1.StatefulSet{}, statefulsetOwnerKeyNKas, - func(rawObj ctrlcli.Object) []string { - // grab the statefulset object, extract the owner + func(rawObj client.Object) []string { + // grab the statefulset object, extract the owner. sts := rawObj.(*appsv1.StatefulSet) owner := metav1.GetControllerOf(sts) if owner == nil { return nil } - // make sure it's a NestedAPIServer + // make sure it's a NestedAPIServer. if owner.APIVersion != controlplanev1.GroupVersion.String() || owner.Kind != string(controlplanev1.APIServer) { return nil } - // and if so, return it + // and if so, return it. return []string{owner.Name} }); err != nil { return err @@ -194,7 +193,7 @@ func (r *NestedAPIServerReconciler) SetupWithManager(mgr ctrl.Manager) error { Complete(r) } -// createAPIServerClientCrts will find of create client certs for the etcd cluster +// createAPIServerClientCrts will find of create client certs for the etcd cluster. func (r *NestedAPIServerReconciler) createAPIServerClientCrts(ctx context.Context, cluster *clusterv1.Cluster, ncp *controlplanev1.NestedControlPlane, nkas *controlplanev1.NestedAPIServer) error { certificates := secret.NewCertificatesForInitialControlPlane(nil) if err := certificates.Lookup(ctx, r.Client, util.ObjectKey(cluster)); err != nil { @@ -215,7 +214,7 @@ func (r *NestedAPIServerReconciler) createAPIServerClientCrts(ctx context.Contex return err } - // TODO(christopherhein) figure out how to get service clusterIPs + // TODO(christopherhein) figure out how to get service clusterIPs. apiKeyPair, err := certificate.NewAPIServerCrtAndKey(&certificate.KeyPair{Cert: cacrt, Key: cakey}, nkas.GetName(), "", cluster.Spec.ControlPlaneEndpoint.Host) if err != nil { return err @@ -253,9 +252,5 @@ func (r *NestedAPIServerReconciler) createAPIServerClientCrts(ctx context.Contex } controllerRef := metav1.NewControllerRef(ncp, controlplanev1.GroupVersion.WithKind("NestedControlPlane")) - if err := certs.LookupOrSave(ctx, r.Client, util.ObjectKey(cluster), *controllerRef); err != nil { - return err - } - - return nil + return certs.LookupOrSave(ctx, r.Client, util.ObjectKey(cluster), *controllerRef) } diff --git a/controlplane/nested/controllers/nestedcontrollermanager_controller.go b/controlplane/nested/controllers/nestedcontrollermanager_controller.go index eb631534..22feb217 100644 --- a/controlplane/nested/controllers/nestedcontrollermanager_controller.go +++ b/controlplane/nested/controllers/nestedcontrollermanager_controller.go @@ -28,12 +28,11 @@ import ( "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" - ctrlcli "sigs.k8s.io/controller-runtime/pkg/client" controlplanev1 "sigs.k8s.io/cluster-api-provider-nested/controlplane/nested/api/v1alpha4" ) -// NestedControllerManagerReconciler reconciles a NestedControllerManager object +// NestedControllerManagerReconciler reconciles a NestedControllerManager object. type NestedControllerManagerReconciler struct { client.Client Log logr.Logger @@ -50,7 +49,7 @@ func (r *NestedControllerManagerReconciler) Reconcile(ctx context.Context, req c log.Info("Reconciling NestedControllerManager...") var nkcm controlplanev1.NestedControllerManager if err := r.Get(ctx, req.NamespacedName, &nkcm); err != nil { - return ctrl.Result{}, ctrlcli.IgnoreNotFound(err) + return ctrl.Result{}, client.IgnoreNotFound(err) } log.Info("creating NestedControllerManager", "namespace", nkcm.GetNamespace(), @@ -73,7 +72,7 @@ func (r *NestedControllerManagerReconciler) Reconcile(ctx context.Context, req c log.Info("the owner could not be found, will retry later", "namespace", nkcm.GetNamespace(), "name", owner.Name) - return ctrl.Result{}, ctrlcli.IgnoreNotFound(err) + return ctrl.Result{}, client.IgnoreNotFound(err) } cluster, err := ncp.GetOwnerCluster(ctx, r.Client) @@ -154,7 +153,7 @@ func (r *NestedControllerManagerReconciler) SetupWithManager(mgr ctrl.Manager) e if err := mgr.GetFieldIndexer().IndexField(context.TODO(), &appsv1.StatefulSet{}, statefulsetOwnerKeyNKcm, - func(rawObj ctrlcli.Object) []string { + func(rawObj client.Object) []string { // grab the statefulset object, extract the owner sts := rawObj.(*appsv1.StatefulSet) owner := metav1.GetControllerOf(sts) diff --git a/controlplane/nested/controllers/nestedcontrolplane_controller.go b/controlplane/nested/controllers/nestedcontrolplane_controller.go index 14919244..38564681 100644 --- a/controlplane/nested/controllers/nestedcontrolplane_controller.go +++ b/controlplane/nested/controllers/nestedcontrolplane_controller.go @@ -49,16 +49,16 @@ import ( // +kubebuilder:rbac:groups=controlplane.cluster.x-k8s.io,resources=nestedcontrolplanes,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=controlplane.cluster.x-k8s.io,resources=nestedcontrolplanes/status,verbs=get;update;patch // +kubebuilder:rbac:groups=controlplane.cluster.x-k8s.io,resources=nestedcontrollermanagers/finalizers,verbs=update -// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch;delete. -// NestedControlPlaneReconciler reconciles a NestedControlPlane object +// NestedControlPlaneReconciler reconciles a NestedControlPlane object. type NestedControlPlaneReconciler struct { client.Client Log logr.Logger Scheme *runtime.Scheme } -// SetupWithManager will configure the controller with the manager +// SetupWithManager will configure the controller with the manager. func (r *NestedControlPlaneReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&controlplanev1.NestedControlPlane{}). @@ -68,7 +68,7 @@ func (r *NestedControlPlaneReconciler) SetupWithManager(mgr ctrl.Manager) error Complete(r) } -// Reconcile is ths main process which will handle updating the NCP +// Reconcile is ths main process which will handle updating the NCP. func (r *NestedControlPlaneReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { log := r.Log.WithValues("nestedcontrolplane", req.NamespacedName) log.Info("Reconciling NestedControlPlane...") @@ -134,7 +134,7 @@ func (r *NestedControlPlaneReconciler) Reconcile(ctx context.Context, req ctrl.R return r.reconcile(ctx, log, cluster, ncp) } -// reconcileDelete will delete the control plane and all it's nestedcomponents +// reconcileDelete will delete the control plane and all it's nestedcomponents. func (r *NestedControlPlaneReconciler) reconcileDelete(ctx context.Context, log logr.Logger, ncp *controlplanev1.NestedControlPlane) (ctrl.Result, error) { patchHelper, err := patch.NewHelper(ncp, r.Client) if err != nil { @@ -181,7 +181,7 @@ func patchControlPlane(ctx context.Context, patchHelper *patch.Helper, ncp *cont ) } -// reconcile will handle all "normal" NCP reconciles this means create/update actions +// reconcile will handle all "normal" NCP reconciles this means create/update actions. func (r *NestedControlPlaneReconciler) reconcile(ctx context.Context, log logr.Logger, cluster *clusterv1.Cluster, ncp *controlplanev1.NestedControlPlane) (res ctrl.Result, reterr error) { log.Info("Reconcile NestedControlPlane") @@ -321,7 +321,7 @@ func (r *NestedControlPlaneReconciler) reconcileKubeconfig(ctx context.Context, } // reconcileControllerOwners will loop through any known nested components that -// aren't owned by a control plane yet and associate them +// aren't owned by a control plane yet and associate them. func (r *NestedControlPlaneReconciler) reconcileControllerOwners(ctx context.Context, ncp *controlplanev1.NestedControlPlane, addOwners []client.Object) error { for _, component := range addOwners { if err := ctrl.SetControllerReference(ncp, component, r.Scheme); err != nil { diff --git a/controlplane/nested/controllers/nestedetcd_controller.go b/controlplane/nested/controllers/nestedetcd_controller.go index 9de7fafd..19bb22b4 100644 --- a/controlplane/nested/controllers/nestedetcd_controller.go +++ b/controlplane/nested/controllers/nestedetcd_controller.go @@ -33,14 +33,13 @@ import ( "sigs.k8s.io/cluster-api/util/secret" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" - ctrlcli "sigs.k8s.io/controller-runtime/pkg/client" controlplanev1 "sigs.k8s.io/cluster-api-provider-nested/controlplane/nested/api/v1alpha4" "sigs.k8s.io/cluster-api-provider-nested/controlplane/nested/certificate" "sigs.k8s.io/cluster-api/util" ) -// NestedEtcdReconciler reconciles a NestedEtcd object +// NestedEtcdReconciler reconciles a NestedEtcd object. type NestedEtcdReconciler struct { client.Client Log logr.Logger @@ -57,7 +56,7 @@ func (r *NestedEtcdReconciler) Reconcile(ctx context.Context, req ctrl.Request) log.Info("Reconciling NestedEtcd...") var netcd controlplanev1.NestedEtcd if err := r.Get(ctx, req.NamespacedName, &netcd); err != nil { - return ctrl.Result{}, ctrlcli.IgnoreNotFound(err) + return ctrl.Result{}, client.IgnoreNotFound(err) } log.Info("creating NestedEtcd", "namespace", netcd.GetNamespace(), @@ -79,7 +78,7 @@ func (r *NestedEtcdReconciler) Reconcile(ctx context.Context, req ctrl.Request) log.Info("the owner could not be found, will retry later", "namespace", netcd.GetNamespace(), "name", owner.Name) - return ctrl.Result{}, ctrlcli.IgnoreNotFound(err) + return ctrl.Result{}, client.IgnoreNotFound(err) } cluster, err := ncp.GetOwnerCluster(ctx, r.Client) @@ -174,7 +173,7 @@ func (r *NestedEtcdReconciler) SetupWithManager(mgr ctrl.Manager) error { if err := mgr.GetFieldIndexer().IndexField(context.TODO(), &appsv1.StatefulSet{}, statefulsetOwnerKeyNEtcd, - func(rawObj ctrlcli.Object) []string { + func(rawObj client.Object) []string { // grab the statefulset object, extract the owner sts := rawObj.(*appsv1.StatefulSet) owner := metav1.GetControllerOf(sts) @@ -199,7 +198,7 @@ func (r *NestedEtcdReconciler) SetupWithManager(mgr ctrl.Manager) error { Complete(r) } -func getNestedEtcdSvcClusterIP(ctx context.Context, cli ctrlcli.Client, +func getNestedEtcdSvcClusterIP(ctx context.Context, cli client.Client, clusterName string, netcd *controlplanev1.NestedEtcd) (string, error) { var svc corev1.Service if err := cli.Get(ctx, types.NamespacedName{ @@ -212,7 +211,7 @@ func getNestedEtcdSvcClusterIP(ctx context.Context, cli ctrlcli.Client, } // genInitialClusterArgs generates the values for `--initial-cluster` option of -// etcd based on the number of replicas specified in etcd StatefulSet +// etcd based on the number of replicas specified in etcd StatefulSet. func genInitialClusterArgs(replicas int32, stsName, svcName, svcNamespace string) (argsVal string) { for i := int32(0); i < replicas; i++ { @@ -238,7 +237,7 @@ func getEtcdServers(name, namespace string, replicas int32) (etcdServers []strin return etcdServers } -// createEtcdClientCrts will find of create client certs for the etcd cluster +// createEtcdClientCrts will find of create client certs for the etcd cluster. func (r *NestedEtcdReconciler) createEtcdClientCrts(ctx context.Context, cluster *controlplanev1alpha4.Cluster, ncp *controlplanev1.NestedControlPlane, netcd *controlplanev1.NestedEtcd) error { certificates := secret.NewCertificatesForInitialControlPlane(nil) if err := certificates.Lookup(ctx, r.Client, util.ObjectKey(cluster)); err != nil { @@ -259,7 +258,7 @@ func (r *NestedEtcdReconciler) createEtcdClientCrts(ctx context.Context, cluster return err } - etcdKeyPair, err := certificate.NewEtcdServerCrtAndKey(&certificate.KeyPair{Cert: crt, Key: key}, getEtcdServers(cluster.GetName(), cluster.GetNamespace(), netcd.Spec.Replicas)) + etcdKeyPair, err := certificate.NewEtcdServerCertAndKey(&certificate.KeyPair{Cert: crt, Key: key}, getEtcdServers(cluster.GetName(), cluster.GetNamespace(), netcd.Spec.Replicas)) if err != nil { return err } @@ -275,9 +274,5 @@ func (r *NestedEtcdReconciler) createEtcdClientCrts(ctx context.Context, cluster } controllerRef := metav1.NewControllerRef(ncp, controlplanev1.GroupVersion.WithKind("NestedControlPlane")) - if err := certs.LookupOrSave(ctx, r.Client, util.ObjectKey(cluster), *controllerRef); err != nil { - return err - } - - return nil + return certs.LookupOrSave(ctx, r.Client, util.ObjectKey(cluster), *controllerRef) } diff --git a/controlplane/nested/main.go b/controlplane/nested/main.go index 39cf3ffa..9cda84cb 100644 --- a/controlplane/nested/main.go +++ b/controlplane/nested/main.go @@ -46,7 +46,7 @@ var ( scheme = runtime.NewScheme() setupLog = ctrl.Log.WithName("setup") - // flags + // Command line flags for configuring the controller manager. metricsAddr string enableLeaderElection bool leaderElectionLeaseDuration time.Duration diff --git a/hack/boilerplate/test/fail.go b/hack/boilerplate/test/fail.go index 16159c5a..bbaaf641 100644 --- a/hack/boilerplate/test/fail.go +++ b/hack/boilerplate/test/fail.go @@ -16,4 +16,5 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package test contains test boilerplate. package test diff --git a/hack/ensure-golangci-lint.sh b/hack/ensure-golangci-lint.sh new file mode 100755 index 00000000..fb7dee13 --- /dev/null +++ b/hack/ensure-golangci-lint.sh @@ -0,0 +1,419 @@ +#!/usr/bin/env bash + +# Copyright 2021 The Kubernetes Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# NOTE: This script is copied from from https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh. + +set -e + +usage() { + this=$1 + cat </dev/null +} +echoerr() { + echo "$@" 1>&2 +} +log_prefix() { + echo "$0" +} +_logp=6 +log_set_priority() { + _logp="$1" +} +log_priority() { + if test -z "$1"; then + echo "$_logp" + return + fi + [ "$1" -le "$_logp" ] +} +log_tag() { + case $1 in + 0) echo "emerg" ;; + 1) echo "alert" ;; + 2) echo "crit" ;; + 3) echo "err" ;; + 4) echo "warning" ;; + 5) echo "notice" ;; + 6) echo "info" ;; + 7) echo "debug" ;; + *) echo "$1" ;; + esac +} +log_debug() { + log_priority 7 || return 0 + echoerr "$(log_prefix)" "$(log_tag 7)" "$@" +} +log_info() { + log_priority 6 || return 0 + echoerr "$(log_prefix)" "$(log_tag 6)" "$@" +} +log_err() { + log_priority 3 || return 0 + echoerr "$(log_prefix)" "$(log_tag 3)" "$@" +} +log_crit() { + log_priority 2 || return 0 + echoerr "$(log_prefix)" "$(log_tag 2)" "$@" +} +uname_os() { + os=$(uname -s | tr '[:upper:]' '[:lower:]') + case "$os" in + cygwin_nt*) os="windows" ;; + mingw*) os="windows" ;; + msys_nt*) os="windows" ;; + esac + echo "$os" +} +uname_arch() { + arch=$(uname -m) + case $arch in + x86_64) arch="amd64" ;; + x86) arch="386" ;; + i686) arch="386" ;; + i386) arch="386" ;; + aarch64) arch="arm64" ;; + armv5*) arch="armv5" ;; + armv6*) arch="armv6" ;; + armv7*) arch="armv7" ;; + esac + echo ${arch} +} +uname_os_check() { + os=$(uname_os) + case "$os" in + darwin) return 0 ;; + dragonfly) return 0 ;; + freebsd) return 0 ;; + linux) return 0 ;; + android) return 0 ;; + nacl) return 0 ;; + netbsd) return 0 ;; + openbsd) return 0 ;; + plan9) return 0 ;; + solaris) return 0 ;; + windows) return 0 ;; + esac + log_crit "uname_os_check '$(uname -s)' got converted to '$os' which is not a GOOS value. Please file bug at https://github.com/client9/shlib" + return 1 +} +uname_arch_check() { + arch=$(uname_arch) + case "$arch" in + 386) return 0 ;; + amd64) return 0 ;; + arm64) return 0 ;; + armv5) return 0 ;; + armv6) return 0 ;; + armv7) return 0 ;; + ppc64) return 0 ;; + ppc64le) return 0 ;; + mips) return 0 ;; + mipsle) return 0 ;; + mips64) return 0 ;; + mips64le) return 0 ;; + s390x) return 0 ;; + amd64p32) return 0 ;; + esac + log_crit "uname_arch_check '$(uname -m)' got converted to '$arch' which is not a GOARCH value. Please file bug report at https://github.com/client9/shlib" + return 1 +} +untar() { + tarball=$1 + case "${tarball}" in + *.tar.gz | *.tgz) tar --no-same-owner -xzf "${tarball}" ;; + *.tar) tar --no-same-owner -xf "${tarball}" ;; + *.zip) unzip "${tarball}" ;; + *) + log_err "untar unknown archive format for ${tarball}" + return 1 + ;; + esac +} +http_download_curl() { + local_file=$1 + source_url=$2 + header=$3 + if [ -z "$header" ]; then + code=$(curl -w '%{http_code}' -sL -o "$local_file" "$source_url") + else + code=$(curl -w '%{http_code}' -sL -H "$header" -o "$local_file" "$source_url") + fi + if [ "$code" != "200" ]; then + log_debug "http_download_curl received HTTP status $code" + return 1 + fi + return 0 +} +http_download_wget() { + local_file=$1 + source_url=$2 + header=$3 + if [ -z "$header" ]; then + wget -q -O "$local_file" "$source_url" + else + wget -q --header "$header" -O "$local_file" "$source_url" + fi +} +http_download() { + log_debug "http_download $2" + if is_command curl; then + http_download_curl "$@" + return + elif is_command wget; then + http_download_wget "$@" + return + fi + log_crit "http_download unable to find wget or curl" + return 1 +} +http_copy() { + tmp=$(mktemp) + http_download "${tmp}" "$1" "$2" || return 1 + body=$(cat "$tmp") + rm -f "${tmp}" + echo "$body" +} +github_release() { + owner_repo=$1 + version=$2 + test -z "$version" && version="latest" + giturl="https://github.com/${owner_repo}/releases/${version}" + json=$(http_copy "$giturl" "Accept:application/json") + test -z "$json" && return 1 + version=$(echo "$json" | tr -s '\n' ' ' | sed 's/.*"tag_name":"//' | sed 's/".*//') + test -z "$version" && return 1 + echo "$version" +} +hash_sha256() { + TARGET=${1:-/dev/stdin} + if is_command gsha256sum; then + hash=$(gsha256sum "$TARGET") || return 1 + echo "$hash" | cut -d ' ' -f 1 + elif is_command sha256sum; then + hash=$(sha256sum "$TARGET") || return 1 + echo "$hash" | cut -d ' ' -f 1 + elif is_command shasum; then + hash=$(shasum -a 256 "$TARGET" 2>/dev/null) || return 1 + echo "$hash" | cut -d ' ' -f 1 + elif is_command openssl; then + hash=$(openssl -dst openssl dgst -sha256 "$TARGET") || return 1 + echo "$hash" | cut -d ' ' -f a + else + log_crit "hash_sha256 unable to find command to compute sha-256 hash" + return 1 + fi +} +hash_sha256_verify() { + TARGET=$1 + checksums=$2 + if [ -z "$checksums" ]; then + log_err "hash_sha256_verify checksum file not specified in arg2" + return 1 + fi + BASENAME=${TARGET##*/} + want=$(grep "${BASENAME}" "${checksums}" 2>/dev/null | tr '\t' ' ' | cut -d ' ' -f 1) + if [ -z "$want" ]; then + log_err "hash_sha256_verify unable to find checksum for '${TARGET}' in '${checksums}'" + return 1 + fi + got=$(hash_sha256 "$TARGET") + if [ "$want" != "$got" ]; then + log_err "hash_sha256_verify checksum for '$TARGET' did not verify ${want} vs $got" + return 1 + fi +} +cat /dev/null <