repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
eks-distro-build-tooling
aws
Go
// +build rpm_crashtraceback package runtime func init() { setTraceback("crash") }
8
eks-distro-build-tooling
aws
Go
// +build rpm_crashtraceback package runtime func init() { setTraceback("crash") }
8
eks-distro-build-tooling
aws
Go
// +build rpm_crashtraceback package runtime func init() { setTraceback("crash") }
8
eks-distro-build-tooling
aws
Go
// +build rpm_crashtraceback package runtime func init() { setTraceback("crash") }
8
eks-distro-build-tooling
aws
Go
//go:build rpm_crashtraceback // +build rpm_crashtraceback package SOURCES func init() { setTraceback("crash") }
9
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package main import ( "github.com/aws/eks-distro-build-tooling/release/cmd" ) func main() { cmd.Execute() }
24
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. // Package v1alpha1 contains API Schema definitions for the eks-distro v1alpha1 API group // +kubebuilder:object:generate=true // +groupName=distro.eks.amazonaws.com package v1alpha1 import ( "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/scheme" ) var ( // GroupVersion is group version used to register these objects GroupVersion = schema.GroupVersion{Group: "distro.eks.amazonaws.com", Version: "v1alpha1"} // 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. AddToScheme = SchemeBuilder.AddToScheme )
35
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // ReleaseSpec defines the desired state of Release type ReleaseSpec struct { // +kubebuilder:validation:Required Channel string `json:"channel,omitempty"` // +kubebuilder:validation:Required // +kubebuilder:validation:Minimum=1 // Monotonically increasing release number Number int `json:"number,omitempty"` // +kubebuilder:validation:Required BuildRepoCommit string `json:"buildRepoCommit,omitempty"` } // +kubebuilder:object:root=true // +kubebuilder:printcolumn:name="Release Channel",type=string,JSONPath=`.spec.channel`,description="The release channel" // +kubebuilder:printcolumn:name="Release",type=integer,JSONPath=`.spec.number`,description="Release number" // +kubebuilder:printcolumn:name="Release Date",type=string,format=date-time,JSONPath=`.status.date`,description="The date the release was published" // +kubebuilder:resource:singular="release",path="releases",shortName={"rel"} // Release is the Schema for the releases API type Release struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec ReleaseSpec `json:"spec,omitempty"` Status ReleaseStatus `json:"status,omitempty"` } // +kubebuilder:object:root=true // ReleaseList contains a list of Release type ReleaseList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []Release `json:"items"` } func init() { SchemeBuilder.Register(&Release{}, &ReleaseList{}) }
62
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // ReleaseChannelSpec defines the desired state of ReleaseChannel type ReleaseChannelSpec struct { SNSTopicARN string `json:"snsTopicARN,omitempty"` } // +kubebuilder:object:root=true // +kubebuilder:printcolumn:name="TopicARN",type=string,JSONPath=`.spec.snsTopicARN`,description="The SNS Topic ARN for this release channel" // +kubebuilder:printcolumn:name="Active",type=boolean,JSONPath=`.status.active`,description="Indicates if this channel is active" // +kubebuilder:printcolumn:name="Latest Release",type=integer,format=int32,JSONPath=`.status.latestRelease`,description="The latest release of this channel" // +kubebuilder:resource:singular="releasechannel",path="releasechannels" // ReleaseChannel is the Schema for the releasechannels API type ReleaseChannel struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec ReleaseChannelSpec `json:"spec,omitempty"` Status ReleaseChannelStatus `json:"status,omitempty"` } // +kubebuilder:object:root=true // ReleaseChannelList contains a list of ReleaseChannel type ReleaseChannelList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []ReleaseChannel `json:"items"` } func init() { SchemeBuilder.Register(&ReleaseChannel{}, &ReleaseChannelList{}) }
53
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package v1alpha1 // ReleaseChannelStatus defines the observed state of ReleaseChannel type ReleaseChannelStatus struct { // +kubebuilder:validation:Required Active bool `json:"active,omitempty"` // +kubebuilder:validation:Required // +kubebuilder:validation:Minimum=1 LatestRelease int `json:"latestRelease,omitempty"` }
25
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package v1alpha1 // ReleaseStatus defines the observed state of Release type ReleaseStatus struct { // +kubebuilder:validation:Required // +kubebuilder:validation:Type=string // +kubebuilder:validation:Format=date-time Date string `json:"date,omitempty"` // +kubebuilder:validation:Required Components []Component `json:"components,omitempty"` } // A component of a release type Component struct { // +kubebuilder:validation:Required Name string `json:"name,omitempty"` // +kubebuilder:validation:Required // Git commit the component is built from, before any patches GitCommit string `json:"gitCommit,omitempty"` // Git tag the component is built from, before any patches GitTag string `json:"gitTag,omitempty"` // +kubebuilder:validation:Required Assets []Asset `json:"assets,omitempty"` } type Asset struct { // +kubebuilder:validation:Required // The asset name Name string `json:"name,omitempty"` // +kubebuilder:validation:Required // +kubebuilder:validation:Enum=Archive;Image; // The type of the asset Type string `json:"type,omitempty"` // +kubebuilder:validation:Required Description string `json:"description,omitempty"` // +kubebuilder:validation:Enum=linux;darwin;windows // Operating system of the asset OS string `json:"os,omitempty"` // Architectures of the asset Arch []string `json:"arch,omitempty"` // +optional Image *AssetImage `json:"image,omitempty"` // +optional Archive *AssetArchive `json:"archive,omitempty"` } type AssetArchive struct { // +kubebuilder:validation:Required // The URI where the asset is located URI string `json:"uri,omitempty"` // +kubebuilder:validation:Required // The sha512 of the asset, only applies for 'file' store SHA512 string `json:"sha512,omitempty"` // +kubebuilder:validation:Required // The sha256 of the asset, only applies for 'file' store SHA256 string `json:"sha256,omitempty"` } type AssetImage struct { // +kubebuilder:validation:Required // The image repository, name, and tag URI string `json:"uri,omitempty"` // +kubebuilder:validation:Required // SHA256 digest for the image ImageDigest string `json:"imageDigest,omitempty"` }
92
eks-distro-build-tooling
aws
Go
//go:build !ignore_autogenerated // +build !ignore_autogenerated // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. // Code generated by controller-gen. DO NOT EDIT. package v1alpha1 import ( runtime "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Asset) DeepCopyInto(out *Asset) { *out = *in if in.Arch != nil { in, out := &in.Arch, &out.Arch *out = make([]string, len(*in)) copy(*out, *in) } if in.Image != nil { in, out := &in.Image, &out.Image *out = new(AssetImage) **out = **in } if in.Archive != nil { in, out := &in.Archive, &out.Archive *out = new(AssetArchive) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Asset. func (in *Asset) DeepCopy() *Asset { if in == nil { return nil } out := new(Asset) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AssetArchive) DeepCopyInto(out *AssetArchive) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AssetArchive. func (in *AssetArchive) DeepCopy() *AssetArchive { if in == nil { return nil } out := new(AssetArchive) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AssetImage) DeepCopyInto(out *AssetImage) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AssetImage. func (in *AssetImage) DeepCopy() *AssetImage { if in == nil { return nil } out := new(AssetImage) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Component) DeepCopyInto(out *Component) { *out = *in if in.Assets != nil { in, out := &in.Assets, &out.Assets *out = make([]Asset, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Component. func (in *Component) DeepCopy() *Component { if in == nil { return nil } out := new(Component) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Release) DeepCopyInto(out *Release) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) out.Spec = in.Spec in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Release. func (in *Release) DeepCopy() *Release { if in == nil { return nil } out := new(Release) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *Release) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ReleaseChannel) DeepCopyInto(out *ReleaseChannel) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) out.Spec = in.Spec out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReleaseChannel. func (in *ReleaseChannel) DeepCopy() *ReleaseChannel { if in == nil { return nil } out := new(ReleaseChannel) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *ReleaseChannel) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ReleaseChannelList) DeepCopyInto(out *ReleaseChannelList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]ReleaseChannel, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReleaseChannelList. func (in *ReleaseChannelList) DeepCopy() *ReleaseChannelList { if in == nil { return nil } out := new(ReleaseChannelList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *ReleaseChannelList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ReleaseChannelSpec) DeepCopyInto(out *ReleaseChannelSpec) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReleaseChannelSpec. func (in *ReleaseChannelSpec) DeepCopy() *ReleaseChannelSpec { if in == nil { return nil } out := new(ReleaseChannelSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ReleaseChannelStatus) DeepCopyInto(out *ReleaseChannelStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReleaseChannelStatus. func (in *ReleaseChannelStatus) DeepCopy() *ReleaseChannelStatus { if in == nil { return nil } out := new(ReleaseChannelStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ReleaseList) DeepCopyInto(out *ReleaseList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Release, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReleaseList. func (in *ReleaseList) DeepCopy() *ReleaseList { if in == nil { return nil } out := new(ReleaseList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *ReleaseList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ReleaseSpec) DeepCopyInto(out *ReleaseSpec) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReleaseSpec. func (in *ReleaseSpec) DeepCopy() *ReleaseSpec { if in == nil { return nil } out := new(ReleaseSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ReleaseStatus) DeepCopyInto(out *ReleaseStatus) { *out = *in if in.Components != nil { in, out := &in.Components, &out.Components *out = make([]Component, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReleaseStatus. func (in *ReleaseStatus) DeepCopy() *ReleaseStatus { if in == nil { return nil } out := new(ReleaseStatus) in.DeepCopyInto(out) return out }
292
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package cmd import ( "fmt" "os" "github.com/aws/eks-distro-build-tooling/release/pkg" "github.com/spf13/cobra" "github.com/spf13/viper" ) const ( releaseManifestUrlFlagName = "release-manifest-url" releaseBranchFlagName = "release-branch" releaseNumberFlagName = "release-number" componentFlagName = "component" osFlagName = "os" architectureFlagName = "arch" typeFlagName = "type" ) var requiredFlags = []string{componentFlagName, typeFlagName} // getAssetUriCmd represents the get-asset-uri command var getAssetUriCmd = &cobra.Command{ Use: "get-asset-uri", Short: "Get asset URI corresponding to an eks-distro release", PreRun: func(cmd *cobra.Command, args []string) { viper.BindPFlags(cmd.Flags()) }, SilenceUsage: true, Run: func(cmd *cobra.Command, args []string) { releaseManifestUrl := viper.GetString(releaseManifestUrlFlagName) releaseBranch := viper.GetString(releaseBranchFlagName) releaseNumber := viper.GetString(releaseNumberFlagName) component := viper.GetString(componentFlagName) assetType := viper.GetString(typeFlagName) osName := viper.GetString(osFlagName) arch := viper.GetString(architectureFlagName) if releaseManifestUrl == "" && (releaseBranch == "" || releaseNumber == "") { fmt.Printf("Both release branch and release number must be provided\n") os.Exit(1) } if releaseManifestUrl != "" && (releaseBranch != "" || releaseNumber != "") { fmt.Printf("Both release manifest URL and release branch/number combination cannot be provided\n") os.Exit(1) } if releaseManifestUrl == "" { releaseManifestUrl = pkg.GetEksDistroReleaseManifestUrl(releaseBranch, releaseNumber) } else { releaseBranch, releaseNumber = pkg.ParseEksDistroReleaseManifestUrl(releaseManifestUrl) } uri, err := pkg.GetAssetUri(releaseManifestUrl, component, assetType, osName, arch) if err != nil { fmt.Printf("Error getting %s-%s %s asset for component %s in EKS Distro %s-%s release: %v\n", osName, arch, assetType, component, releaseBranch, releaseNumber, err) os.Exit(1) } fmt.Println(uri) }, } func init() { rootCmd.AddCommand(getAssetUriCmd) getAssetUriCmd.Flags().StringP(releaseManifestUrlFlagName, "f", "", "The release manifest to parse") getAssetUriCmd.Flags().StringP(releaseBranchFlagName, "b", "", "The release branch to get assets for") getAssetUriCmd.Flags().StringP(releaseNumberFlagName, "n", "", "The release number to get assets for") getAssetUriCmd.Flags().StringP(componentFlagName, "c", "", "The component to get URI for") getAssetUriCmd.Flags().StringP(typeFlagName, "t", "", "The type of asset for getting URI") getAssetUriCmd.Flags().StringP(osFlagName, "o", "linux", "OS of the asset (default: linux)") getAssetUriCmd.Flags().StringP(architectureFlagName, "a", "amd64", "Architecture of the asset (default: amd64)") for _, flag := range requiredFlags { err := getAssetUriCmd.MarkFlagRequired(flag) if err != nil { fmt.Printf("Error marking flag %s as required: %v", flag, err) } } }
98
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package cmd import ( "fmt" "os" "sigs.k8s.io/yaml" "time" "github.com/aws/aws-sdk-go/service/ecrpublic" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/aws/eks-distro-build-tooling/release/pkg" "github.com/spf13/cobra" "github.com/spf13/viper" ) // releaseCmd represents the release command var releaseCmd = &cobra.Command{ Use: "release", Short: "Cut a eks-distro release", PreRun: func(cmd *cobra.Command, args []string) { viper.BindPFlags(cmd.Flags()) }, Run: func(cmd *cobra.Command, args []string) { // TODO validation on these flags releaseBranch := viper.GetString("release-branch") sourceDir := viper.GetString("source") gitCommit := viper.GetString("git-commit") imageRepository := viper.GetString("image-repository") cdnURL := viper.GetString("cdn") releaseNumber := viper.GetInt("release-number") devRelease := viper.GetBool("dev-release") artifactDir := fmt.Sprintf("kubernetes-%s/releases/%d/artifacts/", releaseBranch, releaseNumber) var ecrPublicClient *ecrpublic.ECRPublic releaseConfig := &pkg.ReleaseConfig{ ContainerImageRepository: imageRepository, BuildRepoSource: sourceDir, ArtifactDir: artifactDir, ReleaseDate: time.Now().UTC(), } release := &distrov1alpha1.Release{ Spec: distrov1alpha1.ReleaseSpec{ Channel: releaseBranch, Number: releaseNumber, BuildRepoCommit: gitCommit, }, } release.Name = fmt.Sprintf("kubernetes-%s-eks-%d", releaseBranch, releaseNumber) // TODO figure out how to get these automatically added release.APIVersion = "distro.eks.amazonaws.com/v1alpha1" release.Kind = "Release" if devRelease { client, err := releaseConfig.CreateDevReleaseClients() if err != nil { fmt.Printf("Error creating clients: %v\n", err) os.Exit(1) } ecrPublicClient = client cdnURL, err = buildDevS3URL() if err != nil { fmt.Printf("Error building dev s3 url: %v\n", err) os.Exit(1) } } else { client, err := releaseConfig.CreateProdReleaseClients() if err != nil { fmt.Printf("Error creating clients: %v\n", err) os.Exit(1) } ecrPublicClient = client } releaseConfig.ArtifactURL = cdnURL componentsTable, err := releaseConfig.GenerateComponentsTable(release) if err != nil { fmt.Printf("Error generating components table: %+v\n", err) os.Exit(1) } err = pkg.UpdateImageDigests(ecrPublicClient, releaseConfig, componentsTable) if err != nil { fmt.Printf("Error updating image digests: %+v\n", err) os.Exit(1) } err = releaseConfig.UpdateReleaseStatus(release, componentsTable) if err != nil { fmt.Printf("Error creating release: %+v\n", err) os.Exit(1) } output, err := yaml.Marshal(release) if err != nil { fmt.Printf("Error marshaling release: %+v\n", err) os.Exit(1) } fmt.Println(string(output)) }, } func buildDevS3URL() (string, error) { bucket := os.Getenv("ARTIFACT_BUCKET") if bucket == "" { return "", fmt.Errorf("ARTIFACT_BUCKET must be set") } region := "us-west-2" // dev buckets stored in this region return fmt.Sprintf("https://%v.s3.%v.amazonaws.com", bucket, region), nil } func init() { rootCmd.AddCommand(releaseCmd) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: // releaseCmd.PersistentFlags().String("foo", "", "A help for foo") // Cobra supports local flags which will only run when this command // is called directly, e.g.: releaseCmd.Flags().String("release-branch", "1-18", "The release branch to create a release for") releaseCmd.Flags().String("source", "", "The eks-distro source location") // TODO: exec `git -C $SOURCE describe --always --long --abbrev=64 HEAD` instead of prompting releaseCmd.Flags().String("git-commit", "", "The eks-distro git commit") releaseCmd.Flags().String("image-repository", "", "The container image repository name") releaseCmd.Flags().String("cdn", "https://distro.eks.amazonaws.com", "The URL base for artifacts") releaseCmd.Flags().Int("release-number", 1, "The release-number to create") releaseCmd.Flags().Bool("dev-release", true, "Flag to indicate it's a dev release") }
145
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package cmd import ( "fmt" "os" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" "github.com/spf13/viper" ) var cfgFile string // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "eks-distro-release", Short: "A release tool for EKS Distro", } // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } func init() { cobra.OnInitialize(initConfig) // Here you will define your flags and configuration settings. // Cobra supports persistent flags, which, if defined here, // will be global for your application. rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.eks-distro.yaml)") } // initConfig reads in config file and ENV variables if set. func initConfig() { if cfgFile != "" { // Use config file from the flag. viper.SetConfigFile(cfgFile) } else { // Find home directory. home, err := homedir.Dir() if err != nil { fmt.Println(err) os.Exit(1) } // Search config in home directory with name ".eks-distro" (without extension). viper.AddConfigPath(home) viper.SetConfigName(".eks-distro") } viper.AutomaticEnv() // read in environment variables that match // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) } }
78
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "fmt" "path/filepath" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/pkg/errors" ) // GetAttacherComponent returns the Component for External Attacher func (r *ReleaseConfig) GetAttacherComponent(spec distrov1alpha1.ReleaseSpec) (*distrov1alpha1.Component, error) { projectSource := "projects/kubernetes-csi/external-attacher" tagFile := filepath.Join(r.BuildRepoSource, projectSource, spec.Channel, "GIT_TAG") gitTag, err := readTag(tagFile) if err != nil { return nil, errors.Cause(err) } assets := []distrov1alpha1.Asset{} binary := "external-attacher" assets = append(assets, distrov1alpha1.Asset{ Name: fmt.Sprintf("%s-image", binary), Type: "Image", Description: fmt.Sprintf("%s container image", binary), OS: "linux", Arch: []string{"amd64", "arm64"}, Image: &distrov1alpha1.AssetImage{ URI: fmt.Sprintf("%s/kubernetes-csi/%s:%s-eks-%s-%d", r.ContainerImageRepository, binary, gitTag, spec.Channel, spec.Number, ), }, }) component := &distrov1alpha1.Component{ Name: "external-attacher", GitTag: gitTag, Assets: assets, } return component, nil }
58
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "fmt" "path/filepath" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/pkg/errors" ) // GetAuthenticatorComponent returns the Component for AWS IAM Authenticator func (r *ReleaseConfig) GetAuthenticatorComponent(spec distrov1alpha1.ReleaseSpec) (*distrov1alpha1.Component, error) { projectSource := "projects/kubernetes-sigs/aws-iam-authenticator" tagFile := filepath.Join(r.BuildRepoSource, projectSource, spec.Channel, "GIT_TAG") gitTag, err := readTag(tagFile) if err != nil { return nil, errors.Cause(err) } assets := []distrov1alpha1.Asset{} osArchMap := map[string][]string{ "linux": []string{"arm64", "amd64"}, "windows": []string{"amd64"}, "darwin": []string{"amd64"}, } for os, arches := range osArchMap { for _, arch := range arches { filename := fmt.Sprintf("aws-iam-authenticator-%s-%s-%s.tar.gz", os, arch, gitTag) dirname := fmt.Sprintf("aws-iam-authenticator/%s/", gitTag) tarfile := filepath.Join(r.ArtifactDir, dirname, filename) sha256, sha512, err := r.readShaSums(tarfile) if err != nil { return nil, errors.Cause(err) } assetPath, err := r.GetURI(filepath.Join( fmt.Sprintf("kubernetes-%s", spec.Channel), "releases", fmt.Sprintf("%d", spec.Number), "artifacts", "aws-iam-authenticator", gitTag, filename, )) if err != nil { return nil, errors.Cause(err) } assets = append(assets, distrov1alpha1.Asset{ Name: filename, Type: "Archive", Description: fmt.Sprintf("aws-iam-authenticator tarball for %s/%s", os, arch), OS: os, Arch: []string{arch}, Archive: &distrov1alpha1.AssetArchive{ URI: assetPath, SHA512: sha512, SHA256: sha256, }, }) } } binary := "aws-iam-authenticator" assets = append(assets, distrov1alpha1.Asset{ Name: fmt.Sprintf("%s-image", binary), Type: "Image", Description: fmt.Sprintf("%s container image", binary), OS: "linux", Arch: []string{"amd64", "arm64"}, Image: &distrov1alpha1.AssetImage{ URI: fmt.Sprintf("%s/kubernetes-sigs/%s:%s-eks-%s-%d", r.ContainerImageRepository, binary, gitTag, spec.Channel, spec.Number, ), }, }) component := &distrov1alpha1.Component{ Name: "aws-iam-authenticator", GitTag: gitTag, Assets: assets, } return component, nil }
99
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "fmt" "path/filepath" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/pkg/errors" ) // GetCniComponent returns the Component for CNI plugins func (r *ReleaseConfig) GetCniComponent(spec distrov1alpha1.ReleaseSpec) (*distrov1alpha1.Component, error) { projectSource := "projects/containernetworking/plugins" tagFile := filepath.Join(r.BuildRepoSource, projectSource, spec.Channel, "GIT_TAG") gitTag, err := readTag(tagFile) if err != nil { return nil, errors.Cause(err) } assets := []distrov1alpha1.Asset{} osArchMap := map[string][]string{ "linux": []string{"arm64", "amd64"}, } for os, arches := range osArchMap { for _, arch := range arches { filename := fmt.Sprintf("cni-plugins-%s-%s-%s.tar.gz", os, arch, gitTag) tarfile := filepath.Join(r.ArtifactDir, "plugins", gitTag, filename) sha256, sha512, err := r.readShaSums(tarfile) if err != nil { return nil, errors.Cause(err) } assetPath, err := r.GetURI(filepath.Join( fmt.Sprintf("kubernetes-%s", spec.Channel), "releases", fmt.Sprintf("%d", spec.Number), "artifacts", "plugins", gitTag, filename, )) if err != nil { return nil, errors.Cause(err) } assets = append(assets, distrov1alpha1.Asset{ Name: filename, Type: "Archive", Description: fmt.Sprintf("cni-plugins tarball for %s/%s", os, arch), OS: os, Arch: []string{arch}, Archive: &distrov1alpha1.AssetArchive{ URI: assetPath, SHA512: sha512, SHA256: sha256, }, }) } } component := &distrov1alpha1.Component{ Name: "cni-plugins", GitTag: gitTag, Assets: assets, } return component, nil }
79
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "fmt" "path/filepath" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/pkg/errors" ) // GetCorednsComponent returns the Component for CoreDNS func (r *ReleaseConfig) GetCorednsComponent(spec distrov1alpha1.ReleaseSpec) (*distrov1alpha1.Component, error) { projectSource := "projects/coredns/coredns" tagFile := filepath.Join(r.BuildRepoSource, projectSource, spec.Channel, "GIT_TAG") gitTag, err := readTag(tagFile) if err != nil { return nil, errors.Cause(err) } assets := []distrov1alpha1.Asset{} binary := "coredns" assets = append(assets, distrov1alpha1.Asset{ Name: fmt.Sprintf("%s-image", binary), Type: "Image", Description: fmt.Sprintf("%s container image", binary), OS: "linux", Arch: []string{"amd64", "arm64"}, Image: &distrov1alpha1.AssetImage{ URI: fmt.Sprintf("%s/coredns/%s:%s-eks-%s-%d", r.ContainerImageRepository, binary, gitTag, spec.Channel, spec.Number, ), }, }) component := &distrov1alpha1.Component{ Name: "coredns", GitTag: gitTag, Assets: assets, } return component, nil }
58
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "fmt" "path/filepath" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/pkg/errors" ) // GetEtcdComponent returns the Component for Etcd func (r *ReleaseConfig) GetEtcdComponent(spec distrov1alpha1.ReleaseSpec) (*distrov1alpha1.Component, error) { projectSource := "projects/etcd-io/etcd" tagFile := filepath.Join(r.BuildRepoSource, projectSource, spec.Channel, "GIT_TAG") gitTag, err := readTag(tagFile) if err != nil { return nil, errors.Cause(err) } assets := []distrov1alpha1.Asset{} osArchMap := map[string][]string{ "linux": []string{"arm64", "amd64"}, } for os, arches := range osArchMap { for _, arch := range arches { filename := fmt.Sprintf("etcd-%s-%s-%s.tar.gz", os, arch, gitTag) tarfile := filepath.Join(r.ArtifactDir, "etcd", gitTag, filename) sha256, sha512, err := r.readShaSums(tarfile) if err != nil { return nil, errors.Cause(err) } assetPath, err := r.GetURI(filepath.Join( fmt.Sprintf("kubernetes-%s", spec.Channel), "releases", fmt.Sprintf("%d", spec.Number), "artifacts", "etcd", gitTag, filename, )) if err != nil { return nil, errors.Cause(err) } assets = append(assets, distrov1alpha1.Asset{ Name: filename, Type: "Archive", Description: fmt.Sprintf("etcd tarball for %s/%s", os, arch), OS: os, Arch: []string{arch}, Archive: &distrov1alpha1.AssetArchive{ URI: assetPath, SHA512: sha512, SHA256: sha256, }, }) } } binary := "etcd" assets = append(assets, distrov1alpha1.Asset{ Name: fmt.Sprintf("%s-image", binary), Type: "Image", Description: fmt.Sprintf("%s container image", binary), OS: "linux", Arch: []string{"amd64", "arm64"}, Image: &distrov1alpha1.AssetImage{ URI: fmt.Sprintf("%s/etcd-io/%s:%s-eks-%s-%d", r.ContainerImageRepository, binary, gitTag, spec.Channel, spec.Number, ), }, }) component := &distrov1alpha1.Component{ Name: "etcd", GitTag: gitTag, Assets: assets, } return component, nil }
96
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "fmt" "path/filepath" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" ) // GetKubernetesComponent returns the Component for Kubernetes func (r *ReleaseConfig) GetKubernetesComponent(spec distrov1alpha1.ReleaseSpec) (*distrov1alpha1.Component, error) { kgv, err := newKubeGitVersionFile(r.BuildRepoSource, spec.Channel) if err != nil { return nil, err } gitTag, err := r.readK8sTag(r.BuildRepoSource, spec.Channel) if err != nil { return nil, err } assets := []distrov1alpha1.Asset{} osComponentMap := map[string][]string{ "linux": []string{"client", "server", "node"}, "windows": []string{"client", "node"}, "darwin": []string{"client"}, } osArchMap := map[string][]string{ "linux": []string{"arm64", "amd64"}, "windows": []string{"amd64"}, "darwin": []string{"amd64"}, } osBinaryMap := map[string][]string{ "linux": []string{ "kube-apiserver", "kube-controller-manager", "kube-proxy", "kube-scheduler", "kubectl", "kubelet", "kubeadm", }, "darwin": []string{ "kubectl", }, "windows": []string{ "kube-proxy.exe", "kubeadm.exe", "kubectl.exe", "kubelet.exe", }, } binaryAssets := []distrov1alpha1.Asset{} for os, arches := range osArchMap { for _, arch := range arches { for _, binary := range osBinaryMap[os] { filename := filepath.Join("bin", os, arch, binary) sha256, sha512, err := r.ReadK8sShaSums(gitTag, filename) if err != nil { return nil, err } assetPath, err := r.GetURI(filepath.Join( fmt.Sprintf("kubernetes-%s", spec.Channel), "releases", fmt.Sprintf("%d", spec.Number), "artifacts", "kubernetes", gitTag, filename, )) if err != nil { return nil, err } binaryAssets = append(binaryAssets, distrov1alpha1.Asset{ Name: filename, Type: "Archive", Description: fmt.Sprintf("%s binary for %s/%s", binary, os, arch), OS: os, Arch: []string{arch}, Archive: &distrov1alpha1.AssetArchive{ URI: assetPath, SHA512: sha512, SHA256: sha256, }, }) } for _, component := range osComponentMap[os] { filename := fmt.Sprintf("kubernetes-%s-%s-%s.tar.gz", component, os, arch) sha256, sha512, err := r.ReadK8sShaSums(gitTag, filename) if err != nil { return nil, err } assetPath, err := r.GetURI(filepath.Join( fmt.Sprintf("kubernetes-%s", spec.Channel), "releases", fmt.Sprintf("%d", spec.Number), "artifacts", "kubernetes", gitTag, filename, )) if err != nil { return nil, err } assets = append(assets, distrov1alpha1.Asset{ Name: filename, Type: "Archive", Description: fmt.Sprintf("Kubernetes %s tarball for %s/%s", component, os, arch), OS: os, Arch: []string{arch}, Archive: &distrov1alpha1.AssetArchive{ URI: assetPath, SHA512: sha512, SHA256: sha256, }, }) } } } imageTarAssets := []distrov1alpha1.Asset{} linuxImageArches := []string{"amd64", "arm64"} images := []string{ "kube-apiserver", "kube-controller-manager", "kube-scheduler", "kube-proxy", "pause", } for _, binary := range images { assets = append(assets, distrov1alpha1.Asset{ Name: fmt.Sprintf("%s-image", binary), Type: "Image", Description: fmt.Sprintf("%s container image", binary), OS: "linux", Arch: []string{"amd64", "arm64"}, Image: &distrov1alpha1.AssetImage{ URI: fmt.Sprintf("%s/kubernetes/%s:%s-eks-%s-%d", r.ContainerImageRepository, binary, gitTag, spec.Channel, spec.Number, ), }, }) if binary != "pause" { for _, arch := range linuxImageArches { filename := filepath.Join("bin", "linux", arch, fmt.Sprintf("%s.tar", binary)) sha256, sha512, err := r.ReadK8sShaSums(gitTag, filename) if err != nil { return nil, err } assetPath, err := r.GetURI(filepath.Join( fmt.Sprintf("kubernetes-%s", spec.Channel), "releases", fmt.Sprintf("%d", spec.Number), "artifacts", "kubernetes", gitTag, filename, )) if err != nil { return nil, err } imageTarAssets = append(imageTarAssets, distrov1alpha1.Asset{ Name: filename, Type: "Archive", Description: fmt.Sprintf("%s linux/%s OCI image tar", binary, arch), OS: "linux", Arch: []string{arch}, Archive: &distrov1alpha1.AssetArchive{ URI: assetPath, SHA512: sha512, SHA256: sha256, }, }) } } } assets = append(assets, binaryAssets...) assets = append(assets, imageTarAssets...) filename := "kubernetes-src.tar.gz" sha256, sha512, err := r.ReadK8sShaSums(gitTag, filename) if err != nil { return nil, err } assetPath, err := r.GetURI(filepath.Join( fmt.Sprintf("kubernetes-%s", spec.Channel), "releases", fmt.Sprintf("%d", spec.Number), "artifacts", "kubernetes", gitTag, filename, )) if err != nil { return nil, err } assets = append(assets, distrov1alpha1.Asset{ Name: filename, Type: "Archive", Description: "Kubernetes source tarball", Archive: &distrov1alpha1.AssetArchive{ URI: assetPath, SHA512: sha512, SHA256: sha256, }, }) component := &distrov1alpha1.Component{ Name: "kubernetes", GitCommit: kgv.KubeGitCommit, GitTag: gitTag, Assets: assets, } return component, nil }
236
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "fmt" "path/filepath" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/pkg/errors" ) // GetLivenessprobeComponent returns the Component for Liveness Probe func (r *ReleaseConfig) GetLivenessprobeComponent(spec distrov1alpha1.ReleaseSpec) (*distrov1alpha1.Component, error) { projectSource := "projects/kubernetes-csi/livenessprobe" tagFile := filepath.Join(r.BuildRepoSource, projectSource, spec.Channel, "GIT_TAG") gitTag, err := readTag(tagFile) if err != nil { return nil, errors.Cause(err) } assets := []distrov1alpha1.Asset{} binary := "livenessprobe" assets = append(assets, distrov1alpha1.Asset{ Name: fmt.Sprintf("%s-image", binary), Type: "Image", Description: fmt.Sprintf("%s container image", binary), OS: "linux", Arch: []string{"amd64", "arm64"}, Image: &distrov1alpha1.AssetImage{ URI: fmt.Sprintf("%s/kubernetes-csi/%s:%s-eks-%s-%d", r.ContainerImageRepository, binary, gitTag, spec.Channel, spec.Number, ), }, }) component := &distrov1alpha1.Component{ Name: "livenessprobe", GitTag: gitTag, Assets: assets, } return component, nil }
58
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "fmt" "path/filepath" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/pkg/errors" ) // GetMetricsServerComponent returns the Component for Metrics Server func (r *ReleaseConfig) GetMetricsServerComponent(spec distrov1alpha1.ReleaseSpec) (*distrov1alpha1.Component, error) { projectSource := "projects/kubernetes-sigs/metrics-server" tagFile := filepath.Join(r.BuildRepoSource, projectSource, spec.Channel, "GIT_TAG") gitTag, err := readTag(tagFile) if err != nil { return nil, errors.Cause(err) } assets := []distrov1alpha1.Asset{} binary := "metrics-server" assets = append(assets, distrov1alpha1.Asset{ Name: fmt.Sprintf("%s-image", binary), Type: "Image", Description: fmt.Sprintf("%s container image", binary), OS: "linux", Arch: []string{"amd64", "arm64"}, Image: &distrov1alpha1.AssetImage{ URI: fmt.Sprintf("%s/kubernetes-sigs/%s:%s-eks-%s-%d", r.ContainerImageRepository, binary, gitTag, spec.Channel, spec.Number, ), }, }) component := &distrov1alpha1.Component{ Name: "metrics-server", GitTag: gitTag, Assets: assets, } return component, nil }
58
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "fmt" "path/filepath" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/pkg/errors" ) // GetProvisionerComponent returns the Component for External Provisioner func (r *ReleaseConfig) GetProvisionerComponent(spec distrov1alpha1.ReleaseSpec) (*distrov1alpha1.Component, error) { projectSource := "projects/kubernetes-csi/external-provisioner" tagFile := filepath.Join(r.BuildRepoSource, projectSource, spec.Channel, "GIT_TAG") gitTag, err := readTag(tagFile) if err != nil { return nil, errors.Cause(err) } assets := []distrov1alpha1.Asset{} binary := "external-provisioner" assets = append(assets, distrov1alpha1.Asset{ Name: fmt.Sprintf("%s-image", binary), Type: "Image", Description: fmt.Sprintf("%s container image", binary), OS: "linux", Arch: []string{"amd64", "arm64"}, Image: &distrov1alpha1.AssetImage{ URI: fmt.Sprintf("%s/kubernetes-csi/%s:%s-eks-%s-%d", r.ContainerImageRepository, binary, gitTag, spec.Channel, spec.Number, ), }, }) component := &distrov1alpha1.Component{ Name: "external-provisioner", GitTag: gitTag, Assets: assets, } return component, nil }
58
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "fmt" "path/filepath" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/pkg/errors" ) // GetRegistrarComponent returns the Component for Node Driver Registrar func (r *ReleaseConfig) GetRegistrarComponent(spec distrov1alpha1.ReleaseSpec) (*distrov1alpha1.Component, error) { projectSource := "projects/kubernetes-csi/node-driver-registrar" tagFile := filepath.Join(r.BuildRepoSource, projectSource, spec.Channel, "GIT_TAG") gitTag, err := readTag(tagFile) if err != nil { return nil, errors.Cause(err) } assets := []distrov1alpha1.Asset{} binary := "node-driver-registrar" assets = append(assets, distrov1alpha1.Asset{ Name: fmt.Sprintf("%s-image", binary), Type: "Image", Description: fmt.Sprintf("%s container image", binary), OS: "linux", Arch: []string{"amd64", "arm64"}, Image: &distrov1alpha1.AssetImage{ URI: fmt.Sprintf("%s/kubernetes-csi/%s:%s-eks-%s-%d", r.ContainerImageRepository, binary, gitTag, spec.Channel, spec.Number, ), }, }) component := &distrov1alpha1.Component{ Name: "node-driver-registrar", GitTag: gitTag, Assets: assets, } return component, nil }
58
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "fmt" "path/filepath" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/pkg/errors" ) // GetResizerComponent returns the Component for External Resizer func (r *ReleaseConfig) GetResizerComponent(spec distrov1alpha1.ReleaseSpec) (*distrov1alpha1.Component, error) { projectSource := "projects/kubernetes-csi/external-resizer" tagFile := filepath.Join(r.BuildRepoSource, projectSource, spec.Channel, "GIT_TAG") gitTag, err := readTag(tagFile) if err != nil { return nil, errors.Cause(err) } assets := []distrov1alpha1.Asset{} binary := "external-resizer" assets = append(assets, distrov1alpha1.Asset{ Name: fmt.Sprintf("%s-image", binary), Type: "Image", Description: fmt.Sprintf("%s container image", binary), OS: "linux", Arch: []string{"amd64", "arm64"}, Image: &distrov1alpha1.AssetImage{ URI: fmt.Sprintf("%s/kubernetes-csi/%s:%s-eks-%s-%d", r.ContainerImageRepository, binary, gitTag, spec.Channel, spec.Number, ), }, }) component := &distrov1alpha1.Component{ Name: "external-resizer", GitTag: gitTag, Assets: assets, } return component, nil }
58
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "fmt" "path/filepath" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/pkg/errors" ) // GetSnapshotterComponent returns the Component for External Snapshotter func (r *ReleaseConfig) GetSnapshotterComponent(spec distrov1alpha1.ReleaseSpec) (*distrov1alpha1.Component, error) { projectSource := "projects/kubernetes-csi/external-snapshotter" tagFile := filepath.Join(r.BuildRepoSource, projectSource, spec.Channel, "GIT_TAG") gitTag, err := readTag(tagFile) if err != nil { return nil, errors.Cause(err) } assets := []distrov1alpha1.Asset{} binaries := []string{"csi-snapshotter", "snapshot-controller", "snapshot-validation-webhook"} for _, binary := range binaries { assets = append(assets, distrov1alpha1.Asset{ Name: fmt.Sprintf("%s-image", binary), Type: "Image", Description: fmt.Sprintf("%s container image", binary), OS: "linux", Arch: []string{"amd64", "arm64"}, Image: &distrov1alpha1.AssetImage{ URI: fmt.Sprintf("%s/kubernetes-csi/external-snapshotter/%s:%s-eks-%s-%d", r.ContainerImageRepository, binary, gitTag, spec.Channel, spec.Number, ), }, }) } component := &distrov1alpha1.Component{ Name: "external-snapshotter", GitTag: gitTag, Assets: assets, } return component, nil }
60
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ecrpublic" "github.com/pkg/errors" ) // Function to create release clients for dev release func (r *ReleaseConfig) CreateDevReleaseClients() (*ecrpublic.ECRPublic, error) { // IAD session for eks-d-build-prod-pdx session, err := session.NewSession(&aws.Config{ Region: aws.String("us-east-1"), }) if err != nil { return nil, errors.Cause(err) } // Create release ECR Public client ecrPublicClient := ecrpublic.New(session) return ecrPublicClient, nil } // Function to create clients for production release func (r *ReleaseConfig) CreateProdReleaseClients() (*ecrpublic.ECRPublic, error) { // Session for eks-d-artifact-prod-iad session, err := session.NewSessionWithOptions(session.Options{ Config: aws.Config{ Region: aws.String("us-east-1"), }, Profile: "release-account", }) if err != nil { return nil, errors.Cause(err) } // Create release ECR Public client ecrPublicClient := ecrpublic.New(session) return ecrPublicClient, nil }
58
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "fmt" "io/ioutil" "net/http" "regexp" "strings" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/pkg/errors" "sigs.k8s.io/yaml" ) func readTag(filename string) (string, error) { data, err := ioutil.ReadFile(filename) if err != nil { return "", errors.Cause(err) } return strings.TrimSpace(string(data)), nil } func (r *ReleaseConfig) readShaSums(filename string) (sha256, sha512 string, err error) { sha256Path := filename + ".sha256" sha256, err = readShaFile(sha256Path) if err != nil { return "", "", errors.Cause(err) } sha512Path := filename + ".sha512" sha512, err = readShaFile(sha512Path) if err != nil { return "", "", errors.Cause(err) } return sha256, sha512, nil } func readShaFile(filename string) (string, error) { data, err := ioutil.ReadFile(filename) if err != nil { return "", errors.Cause(err) } if parts := strings.Split(string(data), " "); len(parts) == 2 { return parts[0], nil } return "", errors.Errorf("Error parsing shasum file %s", filename) } func GetEksDistroReleaseManifestUrl(releaseChannel, releaseNumber string) string { manifestUrl := fmt.Sprintf("https://distro.eks.amazonaws.com/kubernetes-%[1]s/kubernetes-%[1]s-eks-%s.yaml", releaseChannel, releaseNumber) return manifestUrl } func ParseEksDistroReleaseManifestUrl(releaseManifestUrl string) (string, string) { r := regexp.MustCompile(`^https://distro.eks.amazonaws.com/kubernetes-\d-\d+/kubernetes-(?P<ReleaseBranch>\d-\d+)-eks-(?P<ReleaseNumber>\d+).yaml$`) search := r.FindStringSubmatch(releaseManifestUrl) return search[1], search[2] } func getEksdRelease(eksdReleaseURL string) (*distrov1alpha1.Release, error) { content, err := readHttpFile(eksdReleaseURL) if err != nil { return nil, err } eksd := &distrov1alpha1.Release{} if err = yaml.UnmarshalStrict(content, eksd); err != nil { return nil, errors.Wrapf(err, "failed to unmarshal eksd manifest") } return eksd, nil } func readHttpFile(uri string) ([]byte, error) { resp, err := http.Get(uri) if err != nil { return nil, errors.Wrapf(err, "failed reading file from url [%s]", uri) } defer resp.Body.Close() data, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, errors.Wrapf(err, "failed reading file from url [%s]", uri) } return data, nil } func sliceContains(s []string, str string) bool { for _, elem := range s { if elem == str { return true } } return false }
111
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "net/url" "strings" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecrpublic" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/pkg/errors" ) // ReleaseConfig contains metadata fields for a release type ReleaseConfig struct { ContainerImageRepository string ArtifactURL string BuildRepoSource string ArtifactDir string ReleaseDate time.Time } // GenerateComponentsTable generates a table of EKS-D components func (r *ReleaseConfig) GenerateComponentsTable(release *distrov1alpha1.Release) (map[string]*distrov1alpha1.Component, error) { componentsTable := map[string]*distrov1alpha1.Component{} componentFuncs := map[string]func(distrov1alpha1.ReleaseSpec) (*distrov1alpha1.Component, error){ "kubernetes": r.GetKubernetesComponent, "aws-iam-authenticator": r.GetAuthenticatorComponent, "livenessprobe": r.GetLivenessprobeComponent, "external-attacher": r.GetAttacherComponent, "external-provisioner": r.GetProvisionerComponent, "external-resizer": r.GetResizerComponent, "node-driver-registrar": r.GetRegistrarComponent, "external-snapshotter": r.GetSnapshotterComponent, "metrics-server": r.GetMetricsServerComponent, "cni-plugin": r.GetCniComponent, "etcd": r.GetEtcdComponent, "coredns": r.GetCorednsComponent, } for componentName, componentFunc := range componentFuncs { component, err := componentFunc(release.Spec) if err != nil { return nil, errors.Wrapf(err, "Error getting %s components", componentName) } componentsTable[componentName] = component } return componentsTable, nil } // UpdateReleaseStatus returns a release struct func (r *ReleaseConfig) UpdateReleaseStatus(release *distrov1alpha1.Release, componentsTable map[string]*distrov1alpha1.Component) error { components := []distrov1alpha1.Component{} for _, component := range componentsTable { components = append(components, *component) } release.Status = distrov1alpha1.ReleaseStatus{ Date: r.ReleaseDate.Format(time.RFC3339), Components: components, } return nil } func UpdateImageDigests(ecrPublicClient *ecrpublic.ECRPublic, r *ReleaseConfig, componentsTable map[string]*distrov1alpha1.Component) error { for _, component := range componentsTable { componentDer := *component assets := componentDer.Assets for _, asset := range assets { if asset.Image != nil { var imageTag string releaseUriSplit := strings.Split(asset.Image.URI, ":") repoName := strings.Replace(releaseUriSplit[0], r.ContainerImageRepository+"/", "", -1) imageTag = releaseUriSplit[1] describeImagesOutput, err := ecrPublicClient.DescribeImages( &ecrpublic.DescribeImagesInput{ ImageIds: []*ecrpublic.ImageIdentifier{ { ImageTag: aws.String(imageTag), }, }, RepositoryName: aws.String(repoName), }, ) if err != nil { return errors.Cause(err) } imageDigest := describeImagesOutput.ImageDetails[0].ImageDigest asset.Image.ImageDigest = *imageDigest } } } return nil } // GetURI returns an full URL for the given path func (r *ReleaseConfig) GetURI(path string) (string, error) { uri, err := url.Parse(r.ArtifactURL) if err != nil { return "", err } uri.Path = path return uri.String(), nil }
122
eks-distro-build-tooling
aws
Go
package pkg import ( "fmt" "strings" distrov1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" ) func GetAssetUri(releaseManifestUrl, component, assetType, os, arch string) (string, error) { eksDRelease, err := getEksdRelease(releaseManifestUrl) if err != nil { return "", fmt.Errorf("error getting EKS Distro release from manifest URL: %v", err) } uri, err := parseReleaseForUri(eksDRelease, component, assetType, os, arch) if err != nil { return "", fmt.Errorf("error parsing EKS Distro release for component URI: %v", err) } return uri, nil } func parseReleaseForUri(release *distrov1alpha1.Release, componentName, assetType, osName, arch string) (string, error) { assets := []distrov1alpha1.Asset{} for _, component := range release.Status.Components { if component.Name == componentName { for _, asset := range component.Assets { if asset.OS == osName && strings.ToLower(asset.Type) == assetType && sliceContains(asset.Arch, arch) { assets = append(assets, asset) } } } } pos := 1 if len(assets) > 0 { if len(assets) > 1 { fmt.Printf("Component %s has the following assets corresponding to %s type:\n", componentName, assetType) for i, asset := range assets { fmt.Printf("%d. %s\n", (i + 1), asset.Description) } fmt.Printf("\nPlease select the required asset from the above list: ") fmt.Scanf("%d\n", &pos) } switch assetType { case "image": return assets[(pos - 1)].Image.URI, nil case "archive": return assets[(pos - 1)].Archive.URI, nil } } return "", fmt.Errorf("no artifact found for requested combination") }
56
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "bufio" "io" "os" "path/filepath" "strconv" "strings" "github.com/pkg/errors" ) func (r *ReleaseConfig) ReadK8sShaSums(gitTag, filename string) (sha256, sha512 string, err error) { assetFile := filepath.Join(r.ArtifactDir, "kubernetes", gitTag, filename) return r.readShaSums(assetFile) } func (r *ReleaseConfig) readK8sTag(buildSource, releaseBranch string) (string, error) { return readTag(filepath.Join(buildSource, "projects/kubernetes/kubernetes", releaseBranch, "GIT_TAG")) } type kubeGitVersionFile struct { KubeGitCommit string KubeGitVersion string KubeGitMajor int KubeGitMinor int SourceDateEpoch int KubeGitTreeState string } func newKubeGitVersionFile(buildSource, releaseBranch string) (*kubeGitVersionFile, error) { versionFile := filepath.Join(buildSource, "projects/kubernetes/kubernetes", releaseBranch, "KUBE_GIT_VERSION_FILE") f, err := os.Open(versionFile) if err != nil { return nil, err } return parseKubeGitVersionContent(f) } func parseKubeGitVersionContent(input io.Reader) (*kubeGitVersionFile, error) { resp := &kubeGitVersionFile{} scanner := bufio.NewScanner(input) for scanner.Scan() { line := scanner.Text() parts := strings.SplitN(line, "=", 2) if len(parts) != 2 { return nil, errors.Errorf("no equal sign in line: %s", line) } value := strings.Trim(parts[1], `'`) switch parts[0] { case "KUBE_GIT_COMMIT": resp.KubeGitCommit = value case "KUBE_GIT_VERSION": resp.KubeGitVersion = value case "KUBE_GIT_MAJOR": val, err := strconv.Atoi(value) if err != nil { return nil, errors.Wrapf(err, "Could not parse '%s'", value) } resp.KubeGitMajor = val case "KUBE_GIT_MINOR": val, err := strconv.Atoi(value) if err != nil { return nil, errors.Wrapf(err, "Could not parse '%s'", value) } resp.KubeGitMinor = val case "SOURCE_DATE_EPOCH": val, err := strconv.Atoi(value) if err != nil { return nil, errors.Wrapf(err, "Could not parse '%s'", value) } resp.SourceDateEpoch = val case "KUBE_GIT_TREE_STATE": resp.KubeGitTreeState = value default: } } if err := scanner.Err(); err != nil { return nil, errors.Wrap(err, "Error reading KUBE_GIT_VERSION_FILE") } return resp, nil }
99
eks-distro-build-tooling
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. package pkg import ( "reflect" "strings" "testing" ) func TestReadKubeVersion(t *testing.T) { cases := []struct { name string content string want *kubeGitVersionFile wantErrMsg string }{ { name: "valid file", content: `KUBE_GIT_COMMIT='94f372e501c973a7fa9eb40ec9ebd2fe7ca69848' KUBE_GIT_VERSION='v1.18.9-eks-1-18-1' KUBE_GIT_MAJOR='1' KUBE_GIT_MINOR='18' SOURCE_DATE_EPOCH='1600264008' KUBE_GIT_TREE_STATE='archive'`, want: &kubeGitVersionFile{ KubeGitCommit: "94f372e501c973a7fa9eb40ec9ebd2fe7ca69848", KubeGitVersion: "v1.18.9-eks-1-18-1", KubeGitMajor: 1, KubeGitMinor: 18, SourceDateEpoch: 1600264008, KubeGitTreeState: "archive", }, wantErrMsg: "", }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { t.Parallel() reader := strings.NewReader(tc.content) got, err := parseKubeGitVersionContent(reader) if err != nil && err.Error() != tc.wantErrMsg { t.Errorf("Incorrect error message: Got '%s', wanted '%s'", err.Error(), tc.wantErrMsg) } if !reflect.DeepEqual(got, tc.want) { t.Errorf("Incorrect response: Got %#v, wanted %#v", got, tc.want) } }) } }
65
eks-distro-build-tooling
aws
Go
package main import ( "os" "os/signal" "syscall" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/cmd/consumerUpdater/cmd" ) func main() { sigChannel := make(chan os.Signal, 1) signal.Notify(sigChannel, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigChannel os.Exit(-1) }() if cmd.Execute() == nil { os.Exit(0) } os.Exit(-1) }
22
eks-distro-build-tooling
aws
Go
package cmd import ( "context" "fmt" "log" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/aws/eks-distro-build-tooling/tools/pkg/logger" ) const ( allConsumersFlag = "allConsumers" eksDistroReleasesFlag = "eksDistroReleases" ) var ( rootCmd = &cobra.Command{ Use: "eksDistroConsumerUpdater", Short: "Amazon EKS Distro downstream consumer updater", Long: `Tools for updating EKS Distro consumers and notifiying them of new releases`, PersistentPreRun: rootPersistentPreRun, } ) func init() { rootCmd.PersistentFlags().IntP("verbosity", "v", 0, "Set the log level verbosity") rootCmd.PersistentFlags().Bool(allConsumersFlag, true, "Rebuild all consumers") rootCmd.PersistentFlags().StringSlice(eksDistroReleasesFlag, []string{}, "EKS Distro releases to update consumers for") // Bind config flags to viper if err := viper.BindPFlags(rootCmd.PersistentFlags()); err != nil { log.Fatalf("failed to bind persistent flags for root: %v", err) } } func rootPersistentPreRun(cmd *cobra.Command, args []string) { if err := initLogger(); err != nil { log.Fatal(err) } } func initLogger() error { if err := logger.InitZap(viper.GetInt("verbosity")); err != nil { return fmt.Errorf("failed init zap logger in root command: %v", err) } return nil } func Execute() error { return rootCmd.ExecuteContext(context.Background()) }
56
eks-distro-build-tooling
aws
Go
package cmd import ( "fmt" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/consumerUpdater" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/eksDistroRelease" ) var ( updateConsumerCommand = &cobra.Command{ Use: "update", Short: "Update consumers of EKS Distro", Long: "Tool for updating consumers of EKS Distro generated artifacts", RunE: func(cmd *cobra.Command, args []string) error { var eksDReleases []*eksDistroRelease.Release for _, v := range viper.GetStringSlice(eksDistroReleasesFlag) { r, err := eksDistroRelease.NewEksDistroReleaseObject(v) if err != nil { return err } eksDReleases = append(eksDReleases, r) } consumerFactory := consumerUpdater.NewFactory(eksDReleases) var err error for _, c := range consumerFactory.ConsumerUpdaters() { err = c.UpdateAll() if err != nil { return fmt.Errorf("updating consumer %s: %v", c.Info().Name, err) } } return nil }, } ) func init() { rootCmd.AddCommand(updateConsumerCommand) }
45
eks-distro-build-tooling
aws
Go
/* Copyright 2017 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. */ package main import ( "flag" "fmt" "net/http" "os" "strconv" "time" "github.com/sirupsen/logrus" "k8s.io/test-infra/pkg/flagutil" "k8s.io/test-infra/prow/config/secret" prowflagutil "k8s.io/test-infra/prow/flagutil" "k8s.io/test-infra/prow/interrupts" "k8s.io/test-infra/prow/logrusutil" "k8s.io/test-infra/prow/pjutil" "k8s.io/test-infra/prow/pluginhelp/externalplugins" opstool "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/externalplugin" ) type options struct { port int dryRun bool github prowflagutil.GitHubOptions labels prowflagutil.Strings instrumentationOptions prowflagutil.InstrumentationOptions logLevel string webhookSecretFile string prowAssignments bool allowAll bool issueOnConflict bool labelPrefix string } func (o *options) Validate() error { for idx, group := range []flagutil.OptionGroup{&o.github} { if err := group.Validate(o.dryRun); err != nil { return fmt.Errorf("%d: %w", idx, err) } } return nil } func gatherOptions() options { o := options{} fs := flag.NewFlagSet(os.Args[0], flag.ExitOnError) fs.IntVar(&o.port, "port", 8888, "Port to listen on.") fs.BoolVar(&o.dryRun, "dry-run", true, "Dry run for testing. Uses API tokens but does not mutate.") fs.Var(&o.labels, "labels", "Labels to apply to the backported issue.") fs.StringVar(&o.webhookSecretFile, "hmac-secret-file", "/etc/webhook/hmac", "Path to the file containing the GitHub HMAC secret.") fs.StringVar(&o.logLevel, "log-level", "debug", fmt.Sprintf("Log level is one of %v.", logrus.AllLevels)) fs.BoolVar(&o.prowAssignments, "use-prow-assignments", true, "Use prow commands to assign backported issues.") fs.BoolVar(&o.allowAll, "allow-all", false, "Allow anybody to use automated backports by skipping GitHub organization membership checks.") fs.BoolVar(&o.issueOnConflict, "create-issue-on-conflict", false, "Create a GitHub issue and assign it to the requestor on cherrypick conflict.") fs.StringVar(&o.labelPrefix, "label-prefix", "", "Set a custom label prefix.") for _, group := range []flagutil.OptionGroup{&o.github, &o.instrumentationOptions} { group.AddFlags(fs) } if err := fs.Parse(os.Args[1:]); err != nil { logrus.Fatalf("Parsing Args: %v", err) } return o } func main() { logrusutil.ComponentInit() o := gatherOptions() if err := o.Validate(); err != nil { logrus.Fatalf("Invalid options: %v", err) } logLevel, err := logrus.ParseLevel(o.logLevel) if err != nil { logrus.WithError(err).Fatal("Failed to parse loglevel") } logrus.SetLevel(logLevel) log := logrus.StandardLogger().WithField("plugin", opstool.PluginName) if err := secret.Add(o.webhookSecretFile); err != nil { logrus.WithError(err).Fatal("Error starting secrets agent.") } githubClient, err := o.github.GitHubClient(o.dryRun) if err != nil { logrus.WithError(err).Fatal("Error getting GitHub client.") } gitClient, err := o.github.GitClientFactory("", nil, o.dryRun) if err != nil { logrus.WithError(err).Fatal("Error getting Git client.") } interrupts.OnInterrupt(func() { if err := gitClient.Clean(); err != nil { logrus.WithError(err).Error("Could not clean up git client cache.") } }) email, err := githubClient.Email() if err != nil { log.WithError(err).Fatal("Error getting bot e-mail.") } botUser, err := githubClient.BotUser() if err != nil { logrus.WithError(err).Fatal("Error getting bot name.") } repos, err := githubClient.GetRepos(botUser.Login, true) if err != nil { log.WithError(err).Fatal("Error listing bot repositories.") } s := &opstool.Server{ TokenGenerator: secret.GetTokenGenerator(o.webhookSecretFile), BotUser: botUser, Email: email, Gc: gitClient, Ghc: githubClient, Log: log, Labels: o.labels.Strings(), ProwAssignments: o.prowAssignments, AllowAll: o.allowAll, IssueOnConflict: o.issueOnConflict, LabelPrefix: o.labelPrefix, Bare: &http.Client{}, PatchURL: "https://patch-diff.githubusercontent.com", Repos: repos, } health := pjutil.NewHealthOnPort(o.instrumentationOptions.HealthPort) health.ServeReady() mux := http.NewServeMux() mux.Handle("/", s) externalplugins.ServeExternalPluginHelp(mux, log, opstool.HelpProvider) httpServer := &http.Server{Addr: ":" + strconv.Itoa(o.port), Handler: mux} defer interrupts.WaitForGracefulShutdown() interrupts.ListenAndServe(httpServer, 5*time.Second) }
163
eks-distro-build-tooling
aws
Go
package main import ( "os" "os/signal" "syscall" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/cmd/eksGoTool/cmd" ) func main() { sigChannel := make(chan os.Signal, 1) signal.Notify(sigChannel, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigChannel os.Exit(-1) }() if cmd.Execute() == nil { os.Exit(0) } os.Exit(-1) }
23
eks-distro-build-tooling
aws
Go
package cmd import "github.com/spf13/cobra" var ( backportCmd = &cobra.Command{ Use: "backport", Short: "Commit backport automation", Long: "Tool for backporting commits and managing the backport process in version control", } ) func init() { rootCmd.AddCommand(backportCmd) }
16
eks-distro-build-tooling
aws
Go
package cmd import ( "fmt" "log" "strings" "time" gogithub "github.com/google/go-github/v48/github" "github.com/spf13/cobra" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/constants" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/github" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/issueManager" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/logger" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/repoManager" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/retrier" ) const ( // Flag Names backportVersionFlag = "backportVersions" requestedByFlag = "requestedBy" toplevelIssueIdFlag = "toplevelIssueId" ) type backportIssueOptions struct { backportVersions []string requestedBy string toplevelIssueId int } var bpOptions = &backportIssueOptions{} func init() { backportCmd.AddCommand(backportIssueCmd) backportIssueCmd.Flags().IntVarP(&bpOptions.toplevelIssueId, toplevelIssueIdFlag, "i", 0, "Issue ID to be backported e.g. 254") backportIssueCmd.Flags().StringVarP(&bpOptions.requestedBy, requestedByFlag, "r", "", "github username of the requester") backportIssueCmd.Flags().StringSliceVarP(&bpOptions.backportVersions, backportVersionFlag, "b", nil, "to specify versions to backport use this flag. Multiple versions can be specified separated by commas. e.g. <ver>,<ver>,<ver>. If no option is supplied, default is to use MAINTAINED_EOL_VERSIONS file in eks-distro-build-tooling/golang/go") requiredFlags := []string{ toplevelIssueIdFlag, } for _, flag := range requiredFlags { if err := backportIssueCmd.MarkFlagRequired(flag); err != nil { log.Fatalf("failed to mark flag %v as requred: %v", flag, err) } } } var backportIssueCmd = &cobra.Command{ Use: "issue", Short: "Opens backport issues for top level github issue", Long: "Opens issues to backport top level issue to EKS-Distro supported versions of Golang", RunE: func(cmd *cobra.Command, args []string) error { label := []string{"golang", "security"} issueState := "open" retrier := retrier.New(time.Second*380, retrier.WithBackoffFactor(1.5), retrier.WithMaxRetries(15, time.Second*30)) token, err := github.GetGithubToken() if err != nil { return fmt.Errorf("getting Github PAT from environment at variable %s: %v", github.PersonalAccessTokenEnvVar, err) } githubClient, err := github.NewClient(cmd.Context(), token) if err != nil { return fmt.Errorf("setting up Github client: %v", err) } if bpOptions.backportVersions == nil { // When no version(s) are included as args, the default is to backport to all EOL versions // tracked at eks-distro-build-tooling/golang/go/MAINTAINED_EOL_VERSIONS // set up Repo Content Creator handler repoManagerOpts := &repoManager.Opts{ SourceOwner: constants.AwsOrgName, SourceRepo: constants.EksdBuildToolingRepoName, } rm := repoManager.New(retrier, githubClient, repoManagerOpts) gfOpts := &repoManager.GetFileOpts{ Owner: constants.AwsOrgName, Repo: constants.EksdBuildToolingRepoName, Path: constants.EksGoSupportedVersionsPath, Ref: nil, } f, err := rm.GetFile(cmd.Context(), gfOpts) if err != nil { return fmt.Errorf("getting file at %s: %v", gfOpts.Path, err) } fc, err := f.GetContent() if err != nil { return fmt.Errorf("getting file content from %v: %v", f.Name, err) } bpOptions.backportVersions = strings.Split(fc, "\n") } // set up Issue Creator handler issueManagerOpts := &issueManager.Opts{ SourceOwner: constants.AwsOrgName, SourceRepo: constants.EksdBuildToolingRepoName, } im := issueManager.New(retrier, githubClient, issueManagerOpts) giOpts := &issueManager.GetIssueOpts{ Owner: constants.AwsOrgName, Repo: constants.EksdBuildToolingRepoName, Issue: bpOptions.toplevelIssueId, } toplevelIssue, err := im.GetIssue(cmd.Context(), giOpts) if err != nil { return fmt.Errorf("getting toplevel issue %v from %v: %v", giOpts.Issue, giOpts.Repo, err) } for _, ver := range bpOptions.backportVersions { if ver != "" { issueOpts := &issueManager.CreateIssueOpts{ Title: GenerateBackportIssueTitle(toplevelIssue, ver), Body: GenerateBackportIssueBody(toplevelIssue, ver), Labels: &label, Assignee: nil, State: &issueState, } _, err := im.CreateIssue(cmd.Context(), issueOpts) if err != nil { return fmt.Errorf("creating issue: %v", err) } } } return nil }, } func GenerateBackportIssueBody(ui *gogithub.Issue, ver string) *string { b := strings.Builder{} b.WriteString(fmt.Sprintf("A backport of issue %v to EKS Go %v was requested by @%v\n", *ui.HTMLURL, ver, bpOptions.requestedBy)) b.WriteString(fmt.Sprintf("%v", *ui.Body)) bs := b.String() logger.V(4).Info("Created Issues Body: `%s`\n", bs) return &bs } func GenerateBackportIssueTitle(ui *gogithub.Issue, ver string) *string { t := strings.Builder{} if *ui.Title != "" { t.WriteString(fmt.Sprintf("%v - [eks go%v backport]", *ui.Title, ver)) } ts := t.String() logger.V(4).Info("Created Issues Title: `%s`\n", ts) return &ts }
158
eks-distro-build-tooling
aws
Go
package cmd import ( "fmt" "log" "strings" "time" gogithub "github.com/google/go-github/v48/github" "github.com/spf13/cobra" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/constants" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/github" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/issueManager" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/logger" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/retrier" ) const ( cveIdFlag = "cveId" upstreamIssueIdFlag = "upstreamIssueId" upstreamCommitHashFlag = "upstreamCommitHash" announcementSourceUrlFlag = "announcementSourceUrl" ) type createToplevelIssueOptions struct { announcementSourceUrl string cveId string upstreamCommitHash string upstreamIssueId int } var ctiOpts = &createToplevelIssueOptions{} func init() { rootCmd.AddCommand(createCveIssue) createCveIssue.Flags().StringVarP(&ctiOpts.cveId, cveIdFlag, "c", "", "CVE ID") createCveIssue.Flags().IntVarP(&ctiOpts.upstreamIssueId, upstreamIssueIdFlag, "i", 0, "Upstream Issue ID e.g. 56350") createCveIssue.Flags().StringVarP(&ctiOpts.upstreamCommitHash, upstreamCommitHashFlag, "u", "", "Upstream Commit Hash e.g. 76cad4edc29d28432a7a0aa27e87385d3d7db7a1") createCveIssue.Flags().StringVarP(&ctiOpts.announcementSourceUrl, announcementSourceUrlFlag, "a", "", "Announcement Source URL e.g. https://groups.google.com/g/golang-announce/c/-hjNw559_tE/m/KlGTfid5CAAJ") requiredFlags := []string{ cveIdFlag, upstreamIssueIdFlag, } for _, flag := range requiredFlags { if err := createCveIssue.MarkFlagRequired(flag); err != nil { log.Fatalf("failed to mark flag %v as requred: %v", flag, err) } } } var createCveIssue = &cobra.Command{ Use: "createCveIssue [OPTIONS]", Short: "Create new top level CVE Issue", Long: "Create a new top level CVE Issue in aws/eks-distro-build-tooling", RunE: func(cmd *cobra.Command, args []string) error { cveLabels := []string{"golang", "security"} issueState := "open" retrier := retrier.New(time.Second*380, retrier.WithBackoffFactor(1.5), retrier.WithMaxRetries(15, time.Second*30)) token, err := github.GetGithubToken() if err != nil { return fmt.Errorf("getting Github PAT from environment at variable %s: %v", github.PersonalAccessTokenEnvVar, err) } githubClient, err := github.NewClient(cmd.Context(), token) if err != nil { return fmt.Errorf("setting up Github client: %v", err) } // set up Issue Creator handler issueManagerOpts := &issueManager.Opts{ SourceOwner: constants.AwsOrgName, SourceRepo: constants.EksdBuildToolingRepoName, } im := issueManager.New(retrier, githubClient, issueManagerOpts) giOpts := &issueManager.GetIssueOpts{ Owner: "golang", Repo: "go", Issue: ctiOpts.upstreamIssueId, } upstreamIssue, err := im.GetIssue(cmd.Context(), giOpts) if err != nil { return fmt.Errorf("getting upstream issue: %v", err) } issueOpts := &issueManager.CreateIssueOpts{ Title: GenerateIssueTitle(upstreamIssue), Body: GenerateIssueBody(upstreamIssue), Labels: &cveLabels, Assignee: nil, State: &issueState, } _, err = im.CreateIssue(cmd.Context(), issueOpts) if err != nil { return fmt.Errorf("creating issue: %v", err) } return nil }, } func GenerateIssueBody(ui *gogithub.Issue) *string { b := strings.Builder{} if ctiOpts.announcementSourceUrl != "" { b.WriteString(fmt.Sprintf("From [Goland Security Announcemnt](%s),\n", ctiOpts.announcementSourceUrl)) } b.WriteString(fmt.Sprintf("For additional information for %s, go to the upstream issue %s", ctiOpts.cveId, *ui.HTMLURL)) if ctiOpts.upstreamCommitHash != "" { b.WriteString(fmt.Sprintf(" and fix commit https://github.com/golang/go/commit/%s", ctiOpts.upstreamCommitHash)) } bs := b.String() logger.V(4).Info("Created Issues Body: `%s`\n", bs) return &bs } func GenerateIssueTitle(ui *gogithub.Issue) *string { t := strings.Builder{} if *ui.Title != "" { t.WriteString(fmt.Sprintf("%v", *ui.Title)) } ts := t.String() logger.V(4).Info("Created Issues Title: `%s`\n", ts) return &ts }
133
eks-distro-build-tooling
aws
Go
package cmd import ( "context" "fmt" "log" "path/filepath" "strings" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/aws/eks-distro-build-tooling/tools/pkg/logger" ) const ( repositoryOwnerFlag = "owner" repositoryFlag = "repository" githubEmailFlag = "githubEmail" commitBranchFlag = "baseBranch" authorNameFlag = "author" dryrunFlag = "dryrun" ) var ( config string // config file location rootCmd = &cobra.Command{ Use: "eksGoTool", Short: "Amazon EKS Golang Operational Tooling", Long: `Tools for the release, management and operations of EKS Go`, PersistentPreRun: rootPersistentPreRun, } ) func init() { // Config defaults repository := "eks-distro-build-tooling" owner := "aws" githubEmail := "" commitBranch := "" authorName := "" // Config flags rootCmd.PersistentFlags().IntP("verbosity", "v", 0, "Set the log level verbosity") rootCmd.PersistentFlags().String(repositoryFlag, repository, "The name of the repository to operate against") rootCmd.PersistentFlags().String(repositoryOwnerFlag, owner, "Name of the owner of the target GitHub repository") rootCmd.PersistentFlags().String(githubEmailFlag, githubEmail, "Email associated with the GitHub account") rootCmd.PersistentFlags().String(commitBranchFlag, commitBranch, "Base branch against which pull requests should be made") rootCmd.PersistentFlags().String(authorNameFlag, authorName, "Author of any commits made by the CLI") // Bind config flags to viper if err := viper.BindPFlags(rootCmd.PersistentFlags()); err != nil { log.Fatalf("failed to bind persistent flags for root: %v", err) } // Cli flags rootCmd.Flags().StringVar(&config, "config", "", "Path to config file with extension") } func rootPersistentPreRun(cmd *cobra.Command, args []string) { if err := readConfig(); err != nil { log.Fatal(err) } if err := initLogger(); err != nil { log.Fatal(err) } } func initLogger() error { if err := logger.InitZap(viper.GetInt("verbosity")); err != nil { return fmt.Errorf("failed init zap logger in root command: %v", err) } return nil } func readConfig() error { // Attempt to parse the config file when flag present if config != "" { filename := filepath.Base(config) viper.SetConfigName(strings.TrimSuffix(filename, filepath.Ext(filename))) viper.AddConfigPath(filepath.Dir(config)) if err := viper.ReadInConfig(); err != nil { return fmt.Errorf("read config into viper: %v", err) } } return nil } func Execute() error { return rootCmd.ExecuteContext(context.Background()) }
95
eks-distro-build-tooling
aws
Go
package constants const ( AwsOrgName = "aws" EksdBuildToolingRepoName = "eks-distro-build-tooling" EksDistroBotName = "eks-distro-bot" EksDistroPrBotName = "eks-distro-pr-bot" EksGoSupportedVersionsPath = "projects/golang/go/MAINTAINED_EOL_VERSIONS" GolangOrgName = "golang" GoRepoName = "go" OwnerWriteallReadOctal = 0644 SemverRegex = `[0-9]+\.[0-9]+\.[0-9]+` AllowAllFailRespTemplate = "@%s only [%s](https://github.com/orgs/%s/people) org members may request may trigger automated issues. You can still create the issue manually." )
15
eks-distro-build-tooling
aws
Go
package consumerUpdater import ( "bytes" "fmt" "os" "path/filepath" "regexp" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/eksDistroRelease" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/constants" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/logger" ) const ( bottlerocketName = "Bottlerocket" ) var ( linebreak = []byte("\n") ) func NewBottleRocketUpdater(releases []*eksDistroRelease.Release) Consumer { return &BottlerocketUpdater{ updaters: bottlerocketUpdaters(releases), notifiers: bottlerocketNotifiers(), bottlerocketInfo: bottlerocketConsumerInfo(), } } type BottlerocketUpdater struct { updaters []Updater notifiers []Notifier bottlerocketInfo ConsumerInfo } func (b BottlerocketUpdater) Updaters() []Updater { return b.updaters } func (b BottlerocketUpdater) UpdateAll() error { for _, u := range b.Updaters() { err := u.Update() if err != nil { return err } } return nil } func (b BottlerocketUpdater) Notifiers() []Notifier { return b.notifiers } func (b BottlerocketUpdater) NotifyAll() error { for _, u := range b.Notifiers() { err := u.Notify() if err != nil { return err } } return nil } func (b BottlerocketUpdater) Info() ConsumerInfo { return b.bottlerocketInfo } func bottlerocketConsumerInfo() ConsumerInfo { return ConsumerInfo{ Name: bottlerocketName, } } func bottlerocketUpdaters(releases []*eksDistroRelease.Release) []Updater { var updaters []Updater updaters = append(updaters, bottlerocketGithubUpdaters(releases)...) return updaters } func bottlerocketGithubUpdaters(releases []*eksDistroRelease.Release) []Updater { var updaters []Updater for _, r := range releases { updaters = append(updaters, &bottlerocketGithubUpdater { eksDistroRelease: r, }) } return updaters } func bottlerocketNotifiers() []Notifier { return []Notifier{} } type bottlerocketGithubUpdater struct { eksDistroRelease *eksDistroRelease.Release } func (g *bottlerocketGithubUpdater) Update() error { //implement updater here fmt.Printf("Bottlerocket update invoked for EKS D release \n Major: %d\n Minor: %d\n Patch: %d\n Release: %d\n", g.eksDistroRelease.KubernetesMajorVersion(), g.eksDistroRelease.KubernetesMinorVersion(), g.eksDistroRelease.KubernetesPatchVersion(), g.eksDistroRelease.ReleaseNumber()) brRootDir, err := bottlerocketHomeDir() if err != nil { return fmt.Errorf("getting BR home dir: %v", err) } brReleaseDir := filepath.Join(brRootDir, "packages", fmt.Sprintf("kubernetes-%d.%d", g.eksDistroRelease.Major, g.eksDistroRelease.Minor)) specPath := filepath.Join(brReleaseDir, fmt.Sprintf("kubernetes-%d.%d.spec", g.eksDistroRelease.Major, g.eksDistroRelease.Minor)) if err = updateSpec(specPath, *g.eksDistroRelease); err != nil { return fmt.Errorf("updating spec file: %w", err) } cargoPath := filepath.Join(brReleaseDir, "Cargo.toml") if err = updateCargo(cargoPath, *g.eksDistroRelease); err != nil { return fmt.Errorf("updating cargo file: %w", err) } return nil } // updateCargo updates the file at provided path cargoPath func updateCargo(cargoPath string, eksD eksDistroRelease.Release) error { logger.Info("updating Bottlerockt cargo.toml", "cargo.toml path", cargoPath, "eks distro release", eksD.EksDistroReleaseFullVersion()) data, err := os.ReadFile(cargoPath) if err != nil { return fmt.Errorf("reading cargo file: %w", err) } splitData := bytes.Split(data, linebreak) urlLinePrefix := []byte("url = ") shaLinePrefix := []byte("sha512 = ") urlFound := false for i := 0; i < len(splitData); i++ { if bytes.HasPrefix(splitData[i], urlLinePrefix) { // Example —> url = "https://distro.eks.amazonaws.com/kubernetes-1-23/releases/6/artifacts/kubernetes/v1.23.12/kubernetes-src.tar.gz" splitData[i] = append(urlLinePrefix, fmt.Sprintf("%q", eksD.KubernetesSourceArchive().Archive.URI)...) urlFound = true for j := i + 1; j < len(splitData); j++ { if bytes.HasPrefix(splitData[j], shaLinePrefix) { // Example —> sha512 = "3033c434d02e6e0296a6659e36e64ce65f7d5408a5d6338dae04bd03225abc7b3a6691e6cce788ac624ba556602a0638b228c64af09e2c8ae19188286a21b5b5" splitData[j] = append(shaLinePrefix, fmt.Sprintf("%q", eksD.KubernetesSourceArchive().Archive.SHA512)...) logger.Info("updated cargo.toml file", "cargo.toml", cargoPath) return os.WriteFile(cargoPath, bytes.Join(splitData, linebreak), constants.OwnerWriteallReadOctal) } } } } var missingPrefix []byte if !urlFound { missingPrefix = urlLinePrefix } else { missingPrefix = shaLinePrefix } return fmt.Errorf("finding line with prefix %s in %s", missingPrefix, cargoPath) } // updateSpec updates the file at provided path specPath func updateSpec(specPath string, eksD eksDistroRelease.Release) error { logger.Info("updating Bottlerockt spec file", "spec path", specPath, "eks distro release", eksD.EksDistroReleaseFullVersion()) data, err := os.ReadFile(specPath) if err != nil { return fmt.Errorf("reading spec file: %w", err) } splitData := bytes.Split(data, linebreak) goverLinePrefix := []byte("%global gover ") sourceLinePrefix := []byte("Source0: ") goverFound := false for i := 0; i < len(splitData); i++ { if bytes.HasPrefix(splitData[i], goverLinePrefix) { // Example —> %global gover 1.23.12 splitData[i] = append(goverLinePrefix, eksD.KubernetesFullVersion()...) goverFound = true for j := i + 1; j < len(splitData); j++ { if bytes.HasPrefix(splitData[j], sourceLinePrefix) { re := regexp.MustCompile(constants.SemverRegex) // Example —> Source0: https://distro.eks.amazonaws.com/kubernetes-1-23/releases/6/artifacts/kubernetes/v%{gover}/kubernetes-src.tar.gz splitData[j] = append(sourceLinePrefix, re.ReplaceAll([]byte(eksD.KubernetesSourceArchive().Archive.URI), []byte("%{gover}"))...) logger.Info("updated spec file", "spec", specPath) return os.WriteFile(specPath, bytes.Join(splitData, linebreak), constants.OwnerWriteallReadOctal) } } } } var missingPrefix []byte if !goverFound { missingPrefix = goverLinePrefix } else { missingPrefix = sourceLinePrefix } return fmt.Errorf("finding line with prefix %s in %s", missingPrefix, specPath) } func bottlerocketHomeDir()(string, error){ dir, err := os.UserHomeDir() if err != nil { return "", err } return filepath.Join(dir, "workspace", "bottlerocket"), nil }
209
eks-distro-build-tooling
aws
Go
package consumerUpdater import "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/eksDistroRelease" func NewFactory(releases []*eksDistroRelease.Release) *Factory { var consumers []Consumer consumers = append(consumers, NewBottleRocketUpdater(releases)) return &Factory{ consumerUpdaters: consumers, } } type Factory struct { consumerUpdaters []Consumer } func (f Factory) ConsumerUpdaters() []Consumer { return f.consumerUpdaters }
21
eks-distro-build-tooling
aws
Go
package consumerUpdater type Consumer interface { Info() ConsumerInfo UpdateAll() error Updaters() []Updater NotifyAll() error Notifiers() []Notifier } type Notifier interface { Notify() error } type Updater interface { Update() error } type ConsumerInfo struct { Name string }
22
eks-distro-build-tooling
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/consumerUpdater (interfaces: Consumer,Updater,Notifier) // Package mocks is a generated GoMock package. package mocks import ( reflect "reflect" consumerUpdater "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/consumerUpdater" gomock "github.com/golang/mock/gomock" ) // MockConsumer is a mock of Consumer interface. type MockConsumer struct { ctrl *gomock.Controller recorder *MockConsumerMockRecorder } // MockConsumerMockRecorder is the mock recorder for MockConsumer. type MockConsumerMockRecorder struct { mock *MockConsumer } // NewMockConsumer creates a new mock instance. func NewMockConsumer(ctrl *gomock.Controller) *MockConsumer { mock := &MockConsumer{ctrl: ctrl} mock.recorder = &MockConsumerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockConsumer) EXPECT() *MockConsumerMockRecorder { return m.recorder } // Info mocks base method. func (m *MockConsumer) Info() consumerUpdater.ConsumerInfo { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Info") ret0, _ := ret[0].(consumerUpdater.ConsumerInfo) return ret0 } // Info indicates an expected call of Info. func (mr *MockConsumerMockRecorder) Info() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Info", reflect.TypeOf((*MockConsumer)(nil).Info)) } // Notifiers mocks base method. func (m *MockConsumer) Notifiers() []consumerUpdater.Notifier { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Notifiers") ret0, _ := ret[0].([]consumerUpdater.Notifier) return ret0 } // Notifiers indicates an expected call of Notifiers. func (mr *MockConsumerMockRecorder) Notifiers() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Notifiers", reflect.TypeOf((*MockConsumer)(nil).Notifiers)) } // NotifyAll mocks base method. func (m *MockConsumer) NotifyAll() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NotifyAll") ret0, _ := ret[0].(error) return ret0 } // NotifyAll indicates an expected call of NotifyAll. func (mr *MockConsumerMockRecorder) NotifyAll() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NotifyAll", reflect.TypeOf((*MockConsumer)(nil).NotifyAll)) } // UpdateAll mocks base method. func (m *MockConsumer) UpdateAll() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UpdateAll") ret0, _ := ret[0].(error) return ret0 } // UpdateAll indicates an expected call of UpdateAll. func (mr *MockConsumerMockRecorder) UpdateAll() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateAll", reflect.TypeOf((*MockConsumer)(nil).UpdateAll)) } // Updaters mocks base method. func (m *MockConsumer) Updaters() []consumerUpdater.Updater { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Updaters") ret0, _ := ret[0].([]consumerUpdater.Updater) return ret0 } // Updaters indicates an expected call of Updaters. func (mr *MockConsumerMockRecorder) Updaters() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Updaters", reflect.TypeOf((*MockConsumer)(nil).Updaters)) } // MockUpdater is a mock of Updater interface. type MockUpdater struct { ctrl *gomock.Controller recorder *MockUpdaterMockRecorder } // MockUpdaterMockRecorder is the mock recorder for MockUpdater. type MockUpdaterMockRecorder struct { mock *MockUpdater } // NewMockUpdater creates a new mock instance. func NewMockUpdater(ctrl *gomock.Controller) *MockUpdater { mock := &MockUpdater{ctrl: ctrl} mock.recorder = &MockUpdaterMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockUpdater) EXPECT() *MockUpdaterMockRecorder { return m.recorder } // Update mocks base method. func (m *MockUpdater) Update() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Update") ret0, _ := ret[0].(error) return ret0 } // Update indicates an expected call of Update. func (mr *MockUpdaterMockRecorder) Update() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockUpdater)(nil).Update)) } // MockNotifier is a mock of Notifier interface. type MockNotifier struct { ctrl *gomock.Controller recorder *MockNotifierMockRecorder } // MockNotifierMockRecorder is the mock recorder for MockNotifier. type MockNotifierMockRecorder struct { mock *MockNotifier } // NewMockNotifier creates a new mock instance. func NewMockNotifier(ctrl *gomock.Controller) *MockNotifier { mock := &MockNotifier{ctrl: ctrl} mock.recorder = &MockNotifierMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockNotifier) EXPECT() *MockNotifierMockRecorder { return m.recorder } // Notify mocks base method. func (m *MockNotifier) Notify() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Notify") ret0, _ := ret[0].(error) return ret0 } // Notify indicates an expected call of Notify. func (mr *MockNotifierMockRecorder) Notify() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Notify", reflect.TypeOf((*MockNotifier)(nil).Notify)) }
180
eks-distro-build-tooling
aws
Go
package dependencyUpdater import ( "fmt" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/eksDistroRelease" ) const ( etcdName = "etcd" ) func NewEtcdDependencyUpdater(releases []*eksDistroRelease.Release) Dependency { return &EtcdUpdater{ updaters: etcdUpdaters(releases), etcdInfo: etcdConsumerInfo(), } } type EtcdUpdater struct { updaters []Updater etcdInfo DependencyInfo } func (b EtcdUpdater) Updaters() []Updater { return b.updaters } func (b EtcdUpdater) UpdateAll() error { for _, u := range b.Updaters() { err := u.Update() if err != nil { return err } } return nil } func (b EtcdUpdater) Info() DependencyInfo { return b.etcdInfo } func etcdConsumerInfo() DependencyInfo { return DependencyInfo{ Name: etcdName, } } func etcdUpdaters(releases []*eksDistroRelease.Release) []Updater { var updaters []Updater updaters = append(updaters, etcdGithubUpdaters(releases)...) return updaters } func etcdGithubUpdaters(releases []*eksDistroRelease.Release) []Updater { var updaters []Updater for _, r := range releases { updaters = append(updaters, &etcdGithubUpdater { eksDistroRelease: r, }) } return updaters } type etcdGithubUpdater struct { eksDistroRelease *eksDistroRelease.Release } func (g *etcdGithubUpdater) Update() error { //implement updater here fmt.Printf("Etcd dependency update stub invoked for EKS D release \n Major: %d\n Minor: %d\n Patch: %d\n Release: %d\n", g.eksDistroRelease.KubernetesMajorVersion(), g.eksDistroRelease.KubernetesMinorVersion(), g.eksDistroRelease.KubernetesPatchVersion(), g.eksDistroRelease.ReleaseNumber()) return nil }
77
eks-distro-build-tooling
aws
Go
package dependencyUpdater import "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/eksDistroRelease" func NewFactory(releases []*eksDistroRelease.Release) *Factory { var dependencies []Dependency dependencies = append(dependencies, NewEtcdDependencyUpdater(releases)) return &Factory{ dependencyUpdaters: dependencies, } } type Factory struct { dependencyUpdaters []Dependency } func (f Factory) DependencyUpdaters() []Dependency { return f.dependencyUpdaters }
21
eks-distro-build-tooling
aws
Go
package dependencyUpdater type Dependency interface { Info() DependencyInfo UpdateAll() error Updaters() []Updater } type Updater interface { Update() error } type DependencyInfo struct { Name string }
16
eks-distro-build-tooling
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/dependencyUpdater (interfaces: Dependency,Updater) // Package mocks is a generated GoMock package. package mocks import ( reflect "reflect" dependencyUpdater "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/dependencyUpdater" gomock "github.com/golang/mock/gomock" ) // MockDependency is a mock of Dependency interface. type MockDependency struct { ctrl *gomock.Controller recorder *MockDependencyMockRecorder } // MockDependencyMockRecorder is the mock recorder for MockDependency. type MockDependencyMockRecorder struct { mock *MockDependency } // NewMockDependency creates a new mock instance. func NewMockDependency(ctrl *gomock.Controller) *MockDependency { mock := &MockDependency{ctrl: ctrl} mock.recorder = &MockDependencyMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockDependency) EXPECT() *MockDependencyMockRecorder { return m.recorder } // Info mocks base method. func (m *MockDependency) Info() dependencyUpdater.DependencyInfo { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Info") ret0, _ := ret[0].(dependencyUpdater.DependencyInfo) return ret0 } // Info indicates an expected call of Info. func (mr *MockDependencyMockRecorder) Info() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Info", reflect.TypeOf((*MockDependency)(nil).Info)) } // UpdateAll mocks base method. func (m *MockDependency) UpdateAll() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UpdateAll") ret0, _ := ret[0].(error) return ret0 } // UpdateAll indicates an expected call of UpdateAll. func (mr *MockDependencyMockRecorder) UpdateAll() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateAll", reflect.TypeOf((*MockDependency)(nil).UpdateAll)) } // Updaters mocks base method. func (m *MockDependency) Updaters() []dependencyUpdater.Updater { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Updaters") ret0, _ := ret[0].([]dependencyUpdater.Updater) return ret0 } // Updaters indicates an expected call of Updaters. func (mr *MockDependencyMockRecorder) Updaters() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Updaters", reflect.TypeOf((*MockDependency)(nil).Updaters)) } // MockUpdater is a mock of Updater interface. type MockUpdater struct { ctrl *gomock.Controller recorder *MockUpdaterMockRecorder } // MockUpdaterMockRecorder is the mock recorder for MockUpdater. type MockUpdaterMockRecorder struct { mock *MockUpdater } // NewMockUpdater creates a new mock instance. func NewMockUpdater(ctrl *gomock.Controller) *MockUpdater { mock := &MockUpdater{ctrl: ctrl} mock.recorder = &MockUpdaterMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockUpdater) EXPECT() *MockUpdaterMockRecorder { return m.recorder } // Update mocks base method. func (m *MockUpdater) Update() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Update") ret0, _ := ret[0].(error) return ret0 } // Update indicates an expected call of Update. func (mr *MockUpdaterMockRecorder) Update() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockUpdater)(nil).Update)) }
115
eks-distro-build-tooling
aws
Go
package eksDistroRelease import ( "fmt" "io" "net/http" "sigs.k8s.io/yaml" "strconv" "strings" "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/aws/eks-distro-build-tooling/tools/pkg/logger" ) const ( expectedStatusCode = 200 eksDistroReleaseManifestUriTemplate = "https://distro.eks.amazonaws.com/kubernetes-%s/kubernetes-%s-eks-%d.yaml" kubernetesComponentName = "kubernetes" kubernetesSourceArchiveAsset = "kubernetes-src.tar.gz" ) func NewEksDistroReleaseObject(versionString string) (*Release, error) { splitVersion := strings.Split(versionString, ".") patchAndRelease := strings.Split(splitVersion[2], "-") major, err := strconv.Atoi(splitVersion[0]) if err != nil { return nil, err } minor, err := strconv.Atoi(splitVersion[1]) if err != nil { return nil, err } patch, err := strconv.Atoi(patchAndRelease[0]) if err != nil { return nil, err } release, err := strconv.Atoi(patchAndRelease[1]) if err != nil { return nil, err } releaseBranch := fmt.Sprintf("%d-%d", major, minor) manifest, err := getReleaseManifestBody(releaseBranch, release) if err != nil { return nil, fmt.Errorf("getting release manifest body: %v", err) } return &Release{ Major: major, Manifest: manifest, Minor: minor, Patch: patch, Release: release, components: map[string]v1alpha1.Component{}, assets: map[string]v1alpha1.Asset{}, }, nil } type Release struct { Major int Minor int Patch int Release int Manifest *v1alpha1.Release components map[string]v1alpha1.Component assets map[string]v1alpha1.Asset } func (r Release) KubernetesReleaseBranch() string { return fmt.Sprintf("%d-%d", r.Major, r.Minor) } func (r Release) KubernetesMajorVersion() int { return r.Major } func (r Release) KubernetesMinorVersion() int { return r.Minor } func (r Release) KubernetesPatchVersion() int { return r.Patch } func (r Release) ReleaseNumber() int { return r.Release } func (r Release) ReleaseManifest() v1alpha1.Release { return *r.Manifest } func (r Release) EksDistroReleaseFullVersion() string { return fmt.Sprintf("v%d.%d.%d-%d", r.Major, r.Minor, r.Patch, r.Release) } func (r Release) KubernetesFullVersion() string { return fmt.Sprintf("%d.%d.%d", r.Major, r.Minor, r.Patch) } func (r Release) KubernetesSemver() string { return fmt.Sprintf("v%d.%d.%d", r.Major, r.Minor, r.Patch) } func (r Release) KubernetesComponent() *v1alpha1.Component { component, ok := r.components[kubernetesComponentName]; if ok { return &component } for _, c := range r.ReleaseManifest().Status.Components { if c.Name == kubernetesComponentName { r.components[kubernetesComponentName] = c return &c } } return nil } func (r Release) KubernetesSourceArchive() *v1alpha1.Asset { asset, ok := r.assets[kubernetesSourceArchiveAsset]; if ok { return &asset } for _, a := range r.KubernetesComponent().Assets { if a.Name == kubernetesSourceArchiveAsset { r.assets[kubernetesSourceArchiveAsset] = a return &a } } return nil } func (r Release) Equals(release Release) bool { if r.Major != release.KubernetesMajorVersion() { logger.V(4).Info("Major version not equal", "self Major", r.Major, "compare Major", release.KubernetesMajorVersion()) return false } if r.Minor != release.KubernetesMinorVersion() { logger.V(4).Info("Minor version not equal", "self Minor", r.Minor, "compare Minor", release.KubernetesMinorVersion()) return false } if r.Patch != release.KubernetesPatchVersion() { logger.V(4).Info("Patch version not equal", "self Patch", r.Patch, "compare Patch", release.KubernetesPatchVersion()) return false } if r.Release != release.ReleaseNumber() { logger.V(4).Info("Release version not equal", "self Release", r.Release, "compare Release", release.ReleaseNumber()) return false } return true } func getReleaseManifestBody(releaseBranch string, release int) (*v1alpha1.Release, error) { releaseManifestURL := fmt.Sprintf(eksDistroReleaseManifestUriTemplate, releaseBranch, releaseBranch, release) logger.Info("release manifest url", "ur", releaseManifestURL) fmt.Println(releaseManifestURL) resp, err := http.Get(releaseManifestURL) if err != nil { return nil, fmt.Errorf("getting Release Manifest: %w\n", err) } defer resp.Body.Close() if resp.StatusCode != expectedStatusCode { return nil, fmt.Errorf("got status code %v when getting Release Manifest (expected %d)", resp.StatusCode, expectedStatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("reading Release Manifest: %w", err) } releaseObject := &v1alpha1.Release{} err = yaml.Unmarshal(body, releaseObject) return releaseObject, err }
182
eks-distro-build-tooling
aws
Go
package eksDistroRelease_test import ( "testing" "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/eksDistroRelease" ) func TestIssueManagerCreateIssueSuccess(t *testing.T) { releaseObject, err := eksDistroRelease.NewEksDistroReleaseObject("1.25.5-5") if err != nil { t.Errorf("NewEksDistroReleaseObject error = %v, want nil", err) } testReleaseObject := newTestEksDistroRelease(t) releasesAreEqual := releaseObject.Equals(testReleaseObject) if !releasesAreEqual { t.Errorf("EKS Distro Release object is not equal to the test Release object! Release object: %v, testReleaseObject: %v", releaseObject, testReleaseObject) } } func newTestEksDistroRelease(t *testing.T) eksDistroRelease.Release { return eksDistroRelease.Release { Major: 1, Minor: 25, Patch: 5, Release: 5, Manifest: &v1alpha1.Release{}, } }
34
eks-distro-build-tooling
aws
Go
package externalplugin import ( "fmt" "sync" "github.com/sirupsen/logrus" "k8s.io/test-infra/prow/github" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/constants" ) func (s *Server) backportGolang(logger *logrus.Entry, requestor string, comment *github.IssueComment, issue *github.Issue, project string, versions []string, org, repo string, num int) error { var lock *sync.Mutex func() { s.mapLock.Lock() defer s.mapLock.Unlock() if _, ok := s.lockBackportMap[backportRequest{org, project, repo, num}]; !ok { if s.lockBackportMap == nil { s.lockBackportMap = map[backportRequest]*sync.Mutex{} } s.lockBackportMap[backportRequest{org, project, repo, num}] = &sync.Mutex{} } lock = s.lockBackportMap[backportRequest{org, project, repo, num}] }() lock.Lock() defer lock.Unlock() // Only consider non-PR issues for /backport:<project> [versions] requests, // For PR requests it seems more fitting to use the /cherrypick command provided by Prow if issue.IsPullRequest() { return nil } for _, version := range versions { err := s.createIssue(logger, org, repo, fmt.Sprintf("[%s]%s", version, issue.Title), CreateBackportBody(constants.GolangOrgName, constants.GoRepoName, issue.Number, requestor, ""), issue.Number, comment, nil, []string{requestor}) if err != nil { return err } } return nil }
44
eks-distro-build-tooling
aws
Go
package externalplugin import ( "fmt" "regexp" "sync" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/constants" "github.com/sirupsen/logrus" "k8s.io/test-infra/prow/github" ) type backportRequest struct { project string org string repo string issNum int } // Follows the format `/backport:golang 1.2.2 ... var backportRe = regexp.MustCompile(`(?m)^(?:/backport:)([a-zA-z]+)\s+(.+)$`) func (s *Server) handleBackportRequest(l *logrus.Entry, requestor string, comment *github.IssueComment, issue *github.Issue, project string, versions []string, org, repo string, num int) error { var lock *sync.Mutex func() { s.mapLock.Lock() defer s.mapLock.Unlock() if _, ok := s.lockBackportMap[backportRequest{project, org, repo, num}]; !ok { if s.lockBackportMap == nil { s.lockBackportMap = map[backportRequest]*sync.Mutex{} } s.lockBackportMap[backportRequest{project, org, repo, num}] = &sync.Mutex{} } lock = s.lockBackportMap[backportRequest{project, org, repo, num}] }() lock.Lock() defer lock.Unlock() //Only a org member should be able to request a issue backport if !s.AllowAll { ok, err := s.Ghc.IsMember(org, requestor) if err != nil { return err } if !ok { resp := fmt.Sprintf(constants.AllowAllFailRespTemplate, requestor, org, org) l.Info(resp) return s.Ghc.CreateComment(org, repo, num, resp) } } // Handle "/backport:<project> [versions] - ie /backport:golang 1.18.12 ... switch project { case "golang": case "go": if err := s.backportGolang(l, requestor, comment, issue, project, versions, org, repo, num); err != nil { return err } default: if err := s.createComment(l, org, repo, issue.Number, comment, fmt.Sprintf("%s not a valid project for /backport: command", project)); err != nil { return err } } return nil } func CreateBackportBody(org, repo string, num int, requestor, note string) string { backportBody := fmt.Sprintf("This is an automated backport of %s/%s#%d", org, repo, num) if len(requestor) != 0 { backportBody = fmt.Sprintf("%s\n\n This backport was requested by: %s\n/assign %s", backportBody, requestor, requestor) } if len(note) != 0 { backportBody = fmt.Sprintf("%s\n\nNotes from backported issue:%s", backportBody, note) } return backportBody }
78
eks-distro-build-tooling
aws
Go
package externalplugin import ( "fmt" "regexp" "strconv" "sync" "github.com/sirupsen/logrus" "k8s.io/test-infra/prow/github" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/constants" ) type golangPatchReleaseRequest struct { org string repo string issNum int } // Currently handling Golang Patch Releases and Golang Minor Releases var golangPatchReleaseRe = regexp.MustCompile(`(?m)^(?:Golang Patch Release:)\s+(.+)$`) func (s *Server) handleGolangPatchRelease(l *logrus.Entry, requestor string, issue *github.Issue, org, repo, title, body string, num int) error { var lock *sync.Mutex func() { s.mapLock.Lock() defer s.mapLock.Unlock() if _, ok := s.lockGolangPatchMap[golangPatchReleaseRequest{org, repo, num}]; !ok { if s.lockGolangPatchMap == nil { s.lockGolangPatchMap = map[golangPatchReleaseRequest]*sync.Mutex{} } s.lockGolangPatchMap[golangPatchReleaseRequest{org, repo, num}] = &sync.Mutex{} } lock = s.lockGolangPatchMap[golangPatchReleaseRequest{org, repo, num}] }() lock.Lock() defer lock.Unlock() // This check is to all only AWS org members to trigger the automation. if !s.AllowAll { // eks-distro-bot is not part of the AWS org so we add exception for the bot account. if requestor != constants.EksDistroBotName { ok, err := s.Ghc.IsMember(org, requestor) if err != nil { return err } if !ok { resp := fmt.Sprintf(constants.AllowAllFailRespTemplate, requestor, org, org) l.Info(resp) return s.Ghc.CreateComment(org, repo, num, resp) } } } var golangVersionsRe = regexp.MustCompile(`(?m)(\d+.\d+.\d+)`) var issNumRe = regexp.MustCompile(`(#\d+)`) m := make(map[string]int) for _, version := range golangVersionsRe.FindAllString(issue.Title, -1) { query := fmt.Sprintf("repo:%s/%s milestone:Go%s label:Security", constants.GolangOrgName, constants.GoRepoName, version) milestoneIssues, err := s.Ghc.FindIssuesWithOrg(constants.GolangOrgName, query, "", false) if err != nil { return fmt.Errorf("Find Golang Milestone: %v", err) } for _, i := range milestoneIssues { for _, biMatch := range issNumRe.FindAllString(i.Body, -1) { if m[biMatch] == 0 { m[biMatch] = 1 } } } } for biNum := range m { biInt, err := strconv.Atoi(biNum[1:]) if err != nil { return fmt.Errorf("Converting issue number to int: %w", err) } baseIssue, err := s.Ghc.GetIssue(constants.GolangOrgName, constants.GoRepoName, biInt) if err != nil { return fmt.Errorf("Getting base issue(%s/%s#%d): %w", constants.GolangOrgName, constants.GoRepoName, biInt, err) } miNum, err := s.Ghc.CreateIssue(constants.AwsOrgName, constants.EksdBuildToolingRepoName, baseIssue.Title, baseIssue.Body, 0, nil, nil) if err != nil { return fmt.Errorf("Creating mirrored issue: %w", err) } l.Info(fmt.Sprintf("Created Issue: %s/%s#%d", constants.AwsOrgName, constants.EksdBuildToolingRepoName, miNum)) } return nil }
90
eks-distro-build-tooling
aws
Go
package externalplugin import ( "encoding/json" "fmt" "net/http" "regexp" "sync" "github.com/sirupsen/logrus" "k8s.io/test-infra/prow/config" "k8s.io/test-infra/prow/git/v2" "k8s.io/test-infra/prow/github" "k8s.io/test-infra/prow/pluginhelp" "k8s.io/test-infra/prow/plugins" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/constants" ) const PluginName = "eksdistroopstool" type githubClient interface { AssignIssue(org, repo string, number int, logins []string) error CreateComment(org, repo string, number int, comment string) error CreateIssue(org, repo, title, body string, milestone int, labels, assignees []string) (int, error) FindIssuesWithOrg(org, query, sort string, asc bool) ([]github.Issue, error) GetIssue(org, repo string, number int) (*github.Issue, error) IsMember(org, user string) (bool, error) } var versionsRe = regexp.MustCompile(fmt.Sprintf(`(?m)(%s)`, constants.SemverRegex)) // HelpProvider construct the pluginhelp.PluginHelp for this plugin. func HelpProvider(_ []config.OrgRepo) (*pluginhelp.PluginHelp, error) { pluginHelp := &pluginhelp.PluginHelp{ Description: `The golang patch release plugin is used for EKS-Distro automation creating issues of upstream Golang security fixes for EKS supported versions. For every successful golang patch release trigger, a new issue is created that mirrors upstream security issues and assigned to the requestor.`, } pluginHelp.AddCommand(pluginhelp.Command{ Usage: "Triggered off issues with |Golang Patch Release: | in title", Description: "Create issue that mirrors security issues when Patch/Security releases are announced.", Featured: true, WhoCanUse: "No use case. Follows automation", Examples: []string{""}, }) return pluginHelp, nil } // Server implements http.Handler. It validates incoming GitHub webhooks and // then dispatches them to the appropriate plugins. type Server struct { TokenGenerator func() []byte BotUser *github.UserData Email string Gc git.ClientFactory Ghc githubClient Log *logrus.Entry // Labels to apply. Labels []string // Use prow to assign users issues. ProwAssignments bool // Allow anybody to request or trigger event. AllowAll bool // Create an issue on conflict. IssueOnConflict bool // Set a custom label prefix. LabelPrefix string Bare *http.Client PatchURL string Repos []github.Repo mapLock sync.Mutex lockGolangPatchMap map[golangPatchReleaseRequest]*sync.Mutex lockBackportMap map[backportRequest]*sync.Mutex } // ServeHTTP validates an incoming webhook and puts it into the event channel. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { eventType, eventGUID, payload, ok, _ := github.ValidateWebhook(w, r, s.TokenGenerator) if !ok { return } fmt.Fprint(w, "Event received. Have a nice day.") if err := s.handleEvent(eventType, eventGUID, payload); err != nil { logrus.WithError(err).Error("Error parsing event.") } } func (s *Server) handleEvent(eventType, eventGUID string, payload []byte) error { l := logrus.WithFields(logrus.Fields{ "event-type": eventType, github.EventGUID: eventGUID, }) switch eventType { case "issues": var ie github.IssueEvent if err := json.Unmarshal(payload, &ie); err != nil { return err } go func() { if err := s.handleIssue(l, ie); err != nil { s.Log.WithError(err).WithFields(l.Data).Info("Handle Issue Failed.") } }() case "issue_comment": var ic github.IssueCommentEvent if err := json.Unmarshal(payload, &ic); err != nil { return err } go func() { if err := s.handleIssueComment(l, ic); err != nil { s.Log.WithError(err).WithFields(l.Data).Info("Handle Issue Comment Failed.") } }() default: logrus.Debugf("skipping event of type %q", eventType) } return nil } func (s *Server) handleIssue(l *logrus.Entry, ie github.IssueEvent) error { // Only consider newly opened issues and not PRs if ie.Action != github.IssueActionOpened && !ie.Issue.IsPullRequest() { return nil } org := ie.Repo.Owner.Login repo := ie.Repo.Name num := ie.Issue.Number author := ie.Sender.Login title := ie.Issue.Title body := ie.Issue.Body // Do not create a new logger, its fields are re-used by the caller in case of errors *l = *l.WithFields(logrus.Fields{ github.OrgLogField: org, github.RepoLogField: repo, github.PrLogField: num, }) golangPatchMatches := golangPatchReleaseRe.FindAllStringSubmatch(ie.Issue.Title, -1) if len(golangPatchMatches) != 0 { if err := s.handleGolangPatchRelease(l, author, &ie.Issue, org, repo, title, body, num); err != nil { return fmt.Errorf("handle GolangPatchrelease: %w", err) } } //TODO: add golangMinorMatches := golangMinorReleaseRe.FindAllStringSubmatch(ie.Issue.Title, -1) //Regex for thisi is below. //var golangMinorReleaseRe = regexp.MustCompile(`(?m)^(?:Golang Minor Release:)\s+(.+)$`) return nil } func (s *Server) handleIssueComment(l *logrus.Entry, ic github.IssueCommentEvent) error { // Only consider newly opened issues. if ic.Action != github.IssueCommentActionCreated { return nil } org := ic.Repo.Owner.Login repo := ic.Repo.Name num := ic.Issue.Number commentAuthor := ic.Comment.User.Login // Do not create a new logger, its fields are re-used by the caller in case of errors *l = *l.WithFields(logrus.Fields{ github.OrgLogField: org, github.RepoLogField: repo, github.PrLogField: num, }) // backportMatches should hold 3 values: // backportMatches[0] holds the full comment body // backportMatches[1] holds the project // backportMatches[2] holds the versions to backport to unparsed. ("v1.2.2 ...") backportMatches := backportRe.FindStringSubmatch(ic.Comment.Body) versions := versionsRe.FindAllString(backportMatches[2], -1) if len(backportMatches) != 0 && len(backportMatches) == 3 { if err := s.handleBackportRequest(l, commentAuthor, &ic.Comment, &ic.Issue, backportMatches[1], versions, org, repo, num); err != nil { return fmt.Errorf("Handle backport request failure: %w", err) } } return nil } // Created based off plugins.FormatICResponse func FormatIEResponse(ie github.IssueEvent, s string) string { return plugins.FormatResponseRaw(ie.Issue.Title, ie.Issue.HTMLURL, ie.Sender.Login, s) } func (s *Server) createComment(l *logrus.Entry, org, repo string, num int, comment *github.IssueComment, resp string) error { if err := func() error { if comment != nil { return s.Ghc.CreateComment(org, repo, num, plugins.FormatICResponse(*comment, resp)) } return s.Ghc.CreateComment(org, repo, num, fmt.Sprintf("In response to: %s", resp)) }(); err != nil { l.WithError(err).Warn("failed to create comment") return err } logrus.Debug("Created comment") return nil } // createIssue creates an issue on GitHub. func (s *Server) createIssue(l *logrus.Entry, org, repo, title, body string, num int, comment *github.IssueComment, labels, assignees []string) error { issueNum, err := s.Ghc.CreateIssue(org, repo, title, body, 0, labels, assignees) if err != nil { return s.createComment(l, org, repo, num, comment, fmt.Sprintf("new issue could not be created for previous request: %v", err)) } return s.createComment(l, org, repo, num, comment, fmt.Sprintf("new issue created for: #%d", issueNum)) }
217
eks-distro-build-tooling
aws
Go
package externalplugin import ( "fmt" "reflect" "sync" "testing" "github.com/sirupsen/logrus" "k8s.io/test-infra/prow/github" ) var commentFormat = "%s/%s#%d %s" type fghc struct { sync.Mutex iss *github.Issue isMember bool comments []string iComments []github.IssueComment iLabels []github.Label orgMembers []github.TeamMember issues []github.Issue } func (f *fghc) AddLabel(org, repo string, number int, label string) error { f.Lock() defer f.Unlock() for i := range f.issues { if number == f.issues[i].Number { f.issues[i].Labels = append(f.issues[i].Labels, github.Label{Name: label}) } } return nil } func (f *fghc) AssignIssue(org, repo string, number int, logins []string) error { var users []github.User for _, login := range logins { users = append(users, github.User{Login: login}) } f.Lock() for i := range f.issues { if number == f.issues[i].Number { f.issues[i].Assignees = append(f.issues[i].Assignees, users...) } } defer f.Unlock() return nil } func (f *fghc) CreateComment(org, repo string, number int, comment string) error { f.Lock() defer f.Unlock() f.comments = append(f.comments, fmt.Sprintf(commentFormat, org, repo, number, comment)) return nil } func (f *fghc) IsMember(org, user string) (bool, error) { f.Lock() defer f.Unlock() return f.isMember, nil } func (f *fghc) GetRepo(owner, name string) (github.FullRepo, error) { f.Lock() defer f.Unlock() return github.FullRepo{}, nil } func (f *fghc) CreateIssue(org, repo, title, body string, milestone int, labels, assignees []string) (int, error) { f.Lock() defer f.Unlock() var ghLabels []github.Label var ghAssignees []github.User num := len(f.issues) + 1 for _, label := range labels { ghLabels = append(ghLabels, github.Label{Name: label}) } for _, assignee := range assignees { ghAssignees = append(ghAssignees, github.User{Login: assignee}) } f.issues = append(f.issues, github.Issue{ Title: title, Body: body, Number: num, Labels: ghLabels, Assignees: ghAssignees, }) return num, nil } func (f *fghc) ListIssueComments(org, repo string, number int) ([]github.IssueComment, error) { f.Lock() defer f.Unlock() return f.iComments, nil } func (f *fghc) GetIssueLabels(org, repo string, number int) ([]github.Label, error) { f.Lock() defer f.Unlock() return f.iLabels, nil } func (f *fghc) ListOrgMembers(org, role string) ([]github.TeamMember, error) { f.Lock() defer f.Unlock() if role != "all" { return nil, fmt.Errorf("all is only supported role, not: %s", role) } return f.orgMembers, nil } func (f *fghc) GetIssue(org, repo string, number int) (*github.Issue, error) { f.Lock() defer f.Unlock() return f.iss, nil } func (f *fghc) FindIssuesWithOrg(org, query, sort string, asc bool) ([]github.Issue, error) { f.Lock() defer f.Unlock() var iss []github.Issue iss = append(iss, f.issues...) for _, i := range f.issues { iss = append(iss, github.Issue{ User: i.User, Number: i.Number, }) } return iss, nil } func TestUpstreamPickCreateIssue(t *testing.T) { t.Parallel() testCases := []struct { org string repo string title string body string prNum int labels []string assignees []string }{ { org: "istio", repo: "istio", title: "brand new feature", body: "automated upstream-pick", prNum: 2190, labels: nil, assignees: []string{"clarketm"}, }, { org: "kubernetes", repo: "kubernetes", title: "alpha feature", body: "automated upstream-pick", prNum: 3444, labels: []string{"new", "1.18"}, assignees: nil, }, } errMsg := func(field string) string { return fmt.Sprintf("GH issue %q does not match: \nexpected: \"%%v\" \nactual: \"%%v\"", field) } for _, tc := range testCases { ghc := &fghc{} s := &Server{ Ghc: ghc, } if err := s.createIssue(logrus.WithField("test", t.Name()), tc.org, tc.repo, tc.title, tc.body, tc.prNum, nil, tc.labels, tc.assignees); err != nil { t.Fatalf("unexpected error: %v", err) } if len(ghc.issues) < 1 { t.Fatalf("Expected 1 GH issue to be created but got: %d", len(ghc.issues)) } ghIssue := ghc.issues[len(ghc.issues)-1] if tc.title != ghIssue.Title { t.Fatalf(errMsg("title"), tc.title, ghIssue.Title) } if tc.body != ghIssue.Body { t.Fatalf(errMsg("body"), tc.title, ghIssue.Title) } if len(ghc.issues) != ghIssue.Number { t.Fatalf(errMsg("number"), len(ghc.issues), ghIssue.Number) } var actualAssignees []string for _, assignee := range ghIssue.Assignees { actualAssignees = append(actualAssignees, assignee.Login) } if !reflect.DeepEqual(tc.assignees, actualAssignees) { t.Fatalf(errMsg("assignees"), tc.assignees, actualAssignees) } var actualLabels []string for _, label := range ghIssue.Labels { actualLabels = append(actualLabels, label.Name) } if !reflect.DeepEqual(tc.labels, actualLabels) { t.Fatalf(errMsg("labels"), tc.labels, actualLabels) } cpFormat := fmt.Sprintf(commentFormat, tc.org, tc.repo, tc.prNum, "In response to: %s") expectedComment := fmt.Sprintf(cpFormat, fmt.Sprintf("new issue created for: #%d", ghIssue.Number)) actualComment := ghc.comments[len(ghc.comments)-1] if expectedComment != actualComment { t.Fatalf(errMsg("comment"), expectedComment, actualComment) } } }
235
eks-distro-build-tooling
aws
Go
package git import "fmt" type RepositoryDoesNotExistError struct { repository string owner string Err error } func (e *RepositoryDoesNotExistError) Error() string { return fmt.Sprintf("repository %s with owner %s not found: %s", e.repository, e.owner, e.Err) } type RepositoryIsEmptyError struct { Repository string } func (e *RepositoryIsEmptyError) Error() string { return fmt.Sprintf("repository %s is empty can cannot be cloned", e.Repository) } type RepositoryUpToDateError struct{} func (e *RepositoryUpToDateError) Error() string { return "error pulling from repository: already up-to-date" } type RemoteBranchDoesNotExistError struct { Repository string Branch string } func (e *RemoteBranchDoesNotExistError) Error() string { return fmt.Sprintf("error pulling from repository %s: remote branch %s does not exist", e.Repository, e.Branch) }
37
eks-distro-build-tooling
aws
Go
package git import "context" type Client interface { Add(filename string) error Remove(filename string) error Clone(ctx context.Context) error Commit(message string, opts ...CommitOpt) error Push(ctx context.Context) error Pull(ctx context.Context, branch string) error Init() error Branch(name string) error ValidateRemoteExists(ctx context.Context) error }
16
eks-distro-build-tooling
aws
Go
package git import ( "context" "errors" "fmt" "os" "strings" "time" "github.com/go-git/go-billy/v5" "github.com/go-git/go-billy/v5/memfs" gogit "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/config" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" "github.com/go-git/go-git/v5/plumbing/transport" "github.com/go-git/go-git/v5/storage/memory" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/logger" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/retrier" ) const ( gitTimeout = 60 * time.Second maxRetries = 5 backOffPeriod = 5 * time.Second emptyRepoError = "remote repository is empty" ) type GogitClient struct { Auth transport.AuthMethod Client GoGit RepoUrl string RepoDirectory *string InMemory bool Retrier *retrier.Retrier } type Opt func(*GogitClient) func NewClient(opts ...Opt) Client { c := &GogitClient{ Client: &goGit{}, Retrier: retrier.NewWithMaxRetries(maxRetries, backOffPeriod), } for _, opt := range opts { opt(c) } return c } func WithAuth(auth transport.AuthMethod) Opt { return func(c *GogitClient) { c.Auth = auth } } func WithRepositoryUrl(repoUrl string) Opt { return func(c *GogitClient) { c.RepoUrl = repoUrl } } func WithRepositoryDirectory(repoDir string) Opt { return func(c *GogitClient) { c.RepoDirectory = &repoDir } } func WithInMemoryFilesystem() Opt { return func(c *GogitClient) { c.InMemory = true } } func (g *GogitClient) Clone(ctx context.Context) error { if g.RepoDirectory != nil && !g.InMemory { _, err := g.Client.Clone(ctx, *g.RepoDirectory, g.RepoUrl, g.Auth) if err != nil && strings.Contains(err.Error(), emptyRepoError) { return &RepositoryIsEmptyError{ Repository: *g.RepoDirectory, } } return nil } _, err := g.Client.CloneInMemory(ctx, g.RepoUrl, g.Auth) if err != nil && strings.Contains(err.Error(), emptyRepoError) { return &RepositoryIsEmptyError{ Repository: g.RepoUrl, } } return err } func (g *GogitClient) Add(filename string) error { logger.V(3).Info("Opening directory", "directory", g.RepoDirectory) r, err := g.Client.OpenRepo() if err != nil { return err } logger.V(3).Info("Opening working tree") w, err := g.Client.OpenWorktree(r) if err != nil { return err } logger.V(3).Info("Tracking specified files", "file", filename) err = g.Client.AddGlob(filename, w) return err } func (g *GogitClient) Remove(filename string) error { logger.V(3).Info("Opening directory", "directory", g.RepoDirectory) r, err := g.Client.OpenRepo() if err != nil { return err } logger.V(3).Info("Opening working tree") w, err := g.Client.OpenWorktree(r) if err != nil { return err } logger.V(3).Info("Removing specified files", "file", filename) _, err = g.Client.Remove(filename, w) return err } type CommitOpt func(signature *object.Signature) func WithUser(user string) CommitOpt { return func (o *object.Signature) { o.Name = user } } func WithEmail(email string) CommitOpt { return func (o *object.Signature) { o.Email = email } } func (g *GogitClient) Commit(message string, opts ...CommitOpt) error { logger.V(3).Info("Opening directory", "directory", g.RepoDirectory) r, err := g.Client.OpenRepo() if err != nil { logger.Info("Failed while attempting to open repo") return err } logger.V(3).Info("Opening working tree") w, err := g.Client.OpenWorktree(r) if err != nil { return err } logger.V(3).Info("Generating Commit object...") commitSignature := &object.Signature{ When: time.Now(), } for _, opt := range opts { opt(commitSignature) } commit, err := g.Client.Commit(message, commitSignature, w) if err != nil { return err } logger.V(3).Info("Committing Object to local repo", "repo", g.RepoDirectory) finalizedCommit, err := g.Client.CommitObject(r, commit) if err != nil { return err } logger.Info("Finalized commit and committed to local repository", "hash", finalizedCommit.Hash) return err } func (g *GogitClient) Push(ctx context.Context) error { logger.V(3).Info("Pushing to remote", "repo", g.RepoDirectory) r, err := g.Client.OpenRepo() if err != nil { return fmt.Errorf("err pushing: %v", err) } err = g.Client.PushWithContext(ctx, r, g.Auth) if err != nil { return fmt.Errorf("pushing: %v", err) } return err } func (g *GogitClient) Pull(ctx context.Context, branch string) error { logger.V(3).Info("Pulling from remote", "repo", g.RepoDirectory, "remote", gogit.DefaultRemoteName) r, err := g.Client.OpenRepo() if err != nil { return fmt.Errorf("pulling from remote: %v", err) } w, err := g.Client.OpenWorktree(r) if err != nil { return fmt.Errorf("pulling from remote: %v", err) } branchRef := plumbing.NewBranchReferenceName(branch) err = g.Client.PullWithContext(ctx, w, g.Auth, branchRef) if errors.Is(err, gogit.NoErrAlreadyUpToDate) { logger.V(3).Info("Local repo already up-to-date", "repo", g.RepoDirectory, "remote", gogit.DefaultRemoteName) return &RepositoryUpToDateError{} } if err != nil { return fmt.Errorf("pulling from remote: %v", err) } ref, err := g.Client.Head(r) if err != nil { return fmt.Errorf("pulling from remote: %v", err) } commit, err := g.Client.CommitObject(r, ref.Hash()) if err != nil { return fmt.Errorf("accessing latest commit after pulling from remote: %v", err) } logger.V(3).Info("Successfully pulled from remote", "repo", g.RepoDirectory, "remote", gogit.DefaultRemoteName, "latest commit", commit.Hash) return nil } func (g *GogitClient) Init() error { r, err := g.Client.Init(*g.RepoDirectory) if err != nil { return err } if _, err = g.Client.Create(r, g.RepoUrl); err != nil { return fmt.Errorf("initializing repository: %v", err) } return nil } func (g *GogitClient) Branch(name string) error { r, err := g.Client.OpenRepo() if err != nil { return fmt.Errorf("creating branch %s: %v", name, err) } localBranchRef := plumbing.NewBranchReferenceName(name) branchOpts := &config.Branch{ Name: name, Remote: gogit.DefaultRemoteName, Merge: localBranchRef, Rebase: "true", } err = g.Client.CreateBranch(r, branchOpts) branchExistsLocally := errors.Is(err, gogit.ErrBranchExists) if err != nil && !branchExistsLocally { return fmt.Errorf("creating branch %s: %v", name, err) } if branchExistsLocally { logger.V(3).Info("Branch already exists locally", "branch", name) } if !branchExistsLocally { logger.V(3).Info("Branch does not exist locally", "branch", name) headref, err := g.Client.Head(r) if err != nil { return fmt.Errorf("creating branch %s: %v", name, err) } h := headref.Hash() err = g.Client.SetRepositoryReference(r, plumbing.NewHashReference(localBranchRef, h)) if err != nil { return fmt.Errorf("creating branch %s: %v", name, err) } } w, err := g.Client.OpenWorktree(r) if err != nil { return fmt.Errorf("creating branch %s: %v", name, err) } err = g.Client.Checkout(w, &gogit.CheckoutOptions{ Branch: plumbing.ReferenceName(localBranchRef.String()), Force: true, }) if err != nil { return fmt.Errorf("creating branch %s: %v", name, err) } err = g.pullIfRemoteExists(r, w, name, localBranchRef) if err != nil { return fmt.Errorf("creating branch %s: %v", name, err) } return nil } func (g *GogitClient) ValidateRemoteExists(ctx context.Context) error { logger.V(3).Info("Validating git setup", "repoUrl", g.RepoUrl) remote := g.Client.NewRemote(g.RepoUrl, gogit.DefaultRemoteName) // Check if we are able to make a connection to the remote by attempting to list refs _, err := g.Client.ListWithContext(ctx, remote, g.Auth) if err != nil { return fmt.Errorf("connecting with remote %v for repository: %v", gogit.DefaultRemoteName, err) } return nil } func (g *GogitClient) pullIfRemoteExists(r *gogit.Repository, w *gogit.Worktree, branchName string, localBranchRef plumbing.ReferenceName) error { err := g.Retrier.Retry(func() error { remoteExists, err := g.remoteBranchExists(r, localBranchRef) if err != nil { return fmt.Errorf("checking if remote branch exists %s: %v", branchName, err) } if remoteExists { err = g.Client.PullWithContext(context.Background(), w, g.Auth, localBranchRef) if err != nil && !errors.Is(err, gogit.NoErrAlreadyUpToDate) && !errors.Is(err, gogit.ErrRemoteNotFound) { return fmt.Errorf("pulling from remote when checking out existing branch %s: %v", branchName, err) } } return nil }) return err } func (g *GogitClient) remoteBranchExists(r *gogit.Repository, localBranchRef plumbing.ReferenceName) (bool, error) { reflist, err := g.Client.ListRemotes(r, g.Auth) if err != nil { if strings.Contains(err.Error(), emptyRepoError) { return false, nil } return false, fmt.Errorf("listing remotes: %v", err) } lb := localBranchRef.String() for _, ref := range reflist { if ref.Name().String() == lb { return true, nil } } return false, nil } type GoGit interface { AddGlob(f string, w *gogit.Worktree) error Checkout(w *gogit.Worktree, opts *gogit.CheckoutOptions) error Clone(ctx context.Context, dir string, repoUrl string, auth transport.AuthMethod) (*gogit.Repository, error) CloneInMemory(ctx context.Context, repourl string, auth transport.AuthMethod) (*gogit.Repository, error) Commit(m string, sig *object.Signature, w *gogit.Worktree) (plumbing.Hash, error) CommitObject(r *gogit.Repository, h plumbing.Hash) (*object.Commit, error) Create(r *gogit.Repository, url string) (*gogit.Remote, error) CreateBranch(r *gogit.Repository, config *config.Branch) error Head(r *gogit.Repository) (*plumbing.Reference, error) NewRemote(url, remoteName string) *gogit.Remote Init(dir string) (*gogit.Repository, error) OpenRepo() (*gogit.Repository, error) OpenWorktree(r *gogit.Repository) (*gogit.Worktree, error) PushWithContext(ctx context.Context, r *gogit.Repository, auth transport.AuthMethod) error PullWithContext(ctx context.Context, w *gogit.Worktree, auth transport.AuthMethod, ref plumbing.ReferenceName) error ListRemotes(r *gogit.Repository, auth transport.AuthMethod) ([]*plumbing.Reference, error) ListWithContext(ctx context.Context, r *gogit.Remote, auth transport.AuthMethod) ([]*plumbing.Reference, error) Remove(f string, w *gogit.Worktree) (plumbing.Hash, error) SetRepositoryReference(r *gogit.Repository, p *plumbing.Reference) error WithRepositoryDirectory(dir string) } type goGit struct{ storer *memory.Storage worktreeFilesystem billy.Filesystem repositoryDirectory string } func (gg *goGit) WithRepositoryDirectory(dir string) { gg.repositoryDirectory = dir } func (gg *goGit) CloneInMemory(ctx context.Context, repourl string, auth transport.AuthMethod) (*gogit.Repository, error) { ctx, cancel := context.WithTimeout(ctx, gitTimeout) defer cancel() if gg.storer == nil { gg.storer = memory.NewStorage() } return gogit.CloneContext(ctx, gg.storer, nil, &gogit.CloneOptions{ Auth: auth, URL: repourl, Progress: os.Stdout, }) } func (gg *goGit) Clone(ctx context.Context, dir string, repourl string, auth transport.AuthMethod) (*gogit.Repository, error) { ctx, cancel := context.WithTimeout(ctx, gitTimeout) defer cancel() return gogit.PlainCloneContext(ctx, dir, false, &gogit.CloneOptions{ Auth: auth, URL: repourl, Progress: os.Stdout, }) } func (gg *goGit) OpenRepo() (*gogit.Repository, error) { if gg.storer == nil && gg.repositoryDirectory != "" { return gogit.PlainOpen(gg.repositoryDirectory) } if gg.worktreeFilesystem == nil { gg.worktreeFilesystem = memfs.New() } return gogit.Open(gg.storer, gg.worktreeFilesystem) } func (gg *goGit) OpenWorktree(r *gogit.Repository) (*gogit.Worktree, error) { return r.Worktree() } func (gg *goGit) AddGlob(f string, w *gogit.Worktree) error { return w.AddGlob(f) } func (gg *goGit) Commit(m string, sig *object.Signature, w *gogit.Worktree) (plumbing.Hash, error) { return w.Commit(m, &gogit.CommitOptions{ Author: sig, }) } func (gg *goGit) CommitObject(r *gogit.Repository, h plumbing.Hash) (*object.Commit, error) { return r.CommitObject(h) } func (gg *goGit) PushWithContext(ctx context.Context, r *gogit.Repository, auth transport.AuthMethod) error { ctx, cancel := context.WithTimeout(ctx, gitTimeout) defer cancel() return r.PushContext(ctx, &gogit.PushOptions{ Auth: auth, }) } func (gg *goGit) PullWithContext(ctx context.Context, w *gogit.Worktree, auth transport.AuthMethod, ref plumbing.ReferenceName) error { ctx, cancel := context.WithTimeout(ctx, gitTimeout) defer cancel() return w.PullContext(ctx, &gogit.PullOptions{RemoteName: gogit.DefaultRemoteName, Auth: auth, ReferenceName: ref}) } func (gg *goGit) Head(r *gogit.Repository) (*plumbing.Reference, error) { return r.Head() } func (gg *goGit) Init(dir string) (*gogit.Repository, error) { return gogit.PlainInit(dir, false) } func (ggc *goGit) NewRemote(url, remoteName string) *gogit.Remote { return gogit.NewRemote(memory.NewStorage(), &config.RemoteConfig{ Name: remoteName, URLs: []string{url}, }) } func (gg *goGit) Checkout(worktree *gogit.Worktree, opts *gogit.CheckoutOptions) error { return worktree.Checkout(opts) } func (gg *goGit) Create(r *gogit.Repository, url string) (*gogit.Remote, error) { return r.CreateRemote(&config.RemoteConfig{ Name: gogit.DefaultRemoteName, URLs: []string{url}, }) } func (gg *goGit) CreateBranch(repo *gogit.Repository, config *config.Branch) error { return repo.CreateBranch(config) } func (gg *goGit) ListRemotes(r *gogit.Repository, auth transport.AuthMethod) ([]*plumbing.Reference, error) { remote, err := r.Remote(gogit.DefaultRemoteName) if err != nil { if errors.Is(err, gogit.ErrRemoteNotFound) { return []*plumbing.Reference{}, nil } return nil, err } refList, err := remote.List(&gogit.ListOptions{Auth: auth}) if err != nil { return nil, err } return refList, nil } func (gg *goGit) Remove(f string, w *gogit.Worktree) (plumbing.Hash, error) { return w.Remove(f) } func (gg *goGit) ListWithContext(ctx context.Context, r *gogit.Remote, auth transport.AuthMethod) ([]*plumbing.Reference, error) { refList, err := r.ListContext(ctx, &gogit.ListOptions{Auth: auth}) if err != nil { return nil, err } return refList, nil } func (gg *goGit) SetRepositoryReference(r *gogit.Repository, p *plumbing.Reference) error { return r.Storer.SetReference(p) }
518
eks-distro-build-tooling
aws
Go
package git_test import ( "context" "fmt" "reflect" "testing" goGit "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/config" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" "github.com/go-git/go-git/v5/plumbing/transport" "github.com/go-git/go-git/v5/plumbing/transport/http" "github.com/golang/mock/gomock" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/git" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/git/mocks" ) var ( repoDir = "testrepo" ) func TestGoGitClone(t *testing.T) { tests := []struct { name string wantErr bool throwError error matchError error }{ { name: "clone repo success", wantErr: false, }, { name: "empty repository error", wantErr: true, throwError: fmt.Errorf("remote repository is empty"), matchError: &git.RepositoryIsEmptyError{ Repository: "testrepo", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, client := newGoGitMock(t) repoUrl := "testurl" auth := &http.BasicAuth{} g := &git.GogitClient{ RepoDirectory: &repoDir, RepoUrl: repoUrl, Auth: auth, Client: client, InMemory: false, } client.EXPECT().Clone(ctx, repoDir, repoUrl, auth).Return(&goGit.Repository{}, tt.throwError) err := g.Clone(ctx) if (err != nil) != tt.wantErr { t.Errorf("Clone() error = %v, wantErr = %v", err, tt.wantErr) return } if tt.wantErr { if !reflect.DeepEqual(err, tt.matchError) { t.Errorf("Clone() error = %v, matchError %v", err, tt.matchError) } } }) } } func TestGoGitAdd(t *testing.T) { _, client := newGoGitMock(t) filename := "testfile" client.EXPECT().OpenRepo().Return(&goGit.Repository{}, nil) client.EXPECT().OpenWorktree(gomock.Any()).Do(func(arg0 *goGit.Repository) {}).Return(&goGit.Worktree{}, nil) client.EXPECT().AddGlob(gomock.Any(), gomock.Any()).Do(func(arg0 string, arg1 *goGit.Worktree) {}).Return(nil) g := &git.GogitClient{ RepoDirectory: &repoDir, Client: client, } err := g.Add(filename) if err != nil { t.Errorf("Add() error = %v", err) return } } func TestGoGitRemove(t *testing.T) { _, client := newGoGitMock(t) filename := "testfile" client.EXPECT().OpenRepo().Return(&goGit.Repository{}, nil) client.EXPECT().OpenWorktree(gomock.Any()).Do(func(arg0 *goGit.Repository) {}).Return(&goGit.Worktree{}, nil) client.EXPECT().Remove(gomock.Any(), gomock.Any()).Do(func(arg0 string, arg1 *goGit.Worktree) {}).Return(plumbing.Hash{}, nil) g := &git.GogitClient{ RepoDirectory: &repoDir, Client: client, } err := g.Remove(filename) if err != nil { t.Errorf("Remove() error = %v", err) return } } func TestGoGitCommit(t *testing.T) { _, client := newGoGitMock(t) message := "message" client.EXPECT().OpenRepo().Return(&goGit.Repository{}, nil) client.EXPECT().OpenWorktree(gomock.Any()).Do(func(arg0 *goGit.Repository) {}).Return(&goGit.Worktree{}, nil) client.EXPECT().Commit(gomock.Any(), gomock.Any(), gomock.Any()).Do(func(arg0 string, arg1 *object.Signature, arg2 *goGit.Worktree) {}).Return(plumbing.Hash{}, nil) client.EXPECT().CommitObject(gomock.Any(), gomock.Any()).Do(func(arg0 *goGit.Repository, arg1 plumbing.Hash) {}).Return(&object.Commit{}, nil) g := &git.GogitClient{ RepoDirectory: &repoDir, Client: client, } err := g.Commit(message) if err != nil { t.Errorf("Commit() error = %v", err) return } } func TestGoGitPush(t *testing.T) { ctx, client := newGoGitMock(t) g := &git.GogitClient{ RepoDirectory: &repoDir, Client: client, } client.EXPECT().OpenRepo().Return(&goGit.Repository{}, nil) client.EXPECT().PushWithContext(ctx, gomock.Any(), gomock.Any()).Do(func(arg0 context.Context, arg1 *goGit.Repository, arg2 transport.AuthMethod) {}).Return(nil) err := g.Push(ctx) if err != nil { t.Errorf("Push() error = %v", err) return } } func TestGoGitPull(t *testing.T) { tests := []struct { name string wantErr bool throwError error matchError error }{ { name: "pull success", wantErr: false, }, { name: "repo already up-to-date", wantErr: true, throwError: fmt.Errorf("already up-to-date"), matchError: fmt.Errorf("pulling from remote: %v", goGit.NoErrAlreadyUpToDate), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, client := newGoGitMock(t) branch := "testbranch" g := &git.GogitClient{ RepoDirectory: &repoDir, Client: client, } client.EXPECT().OpenRepo().Return(&goGit.Repository{}, nil) client.EXPECT().OpenWorktree(gomock.Any()).Do(func(arg0 *goGit.Repository) {}).Return(&goGit.Worktree{}, nil) client.EXPECT().PullWithContext(ctx, gomock.Any(), gomock.Any(), gomock.Any()).Do(func(arg0 context.Context, arg1 *goGit.Worktree, arg2 transport.AuthMethod, name plumbing.ReferenceName) { }).Return(tt.throwError) if !tt.wantErr { client.EXPECT().Head(gomock.Any()).Do(func(arg0 *goGit.Repository) {}).Return(&plumbing.Reference{}, nil) client.EXPECT().CommitObject(gomock.Any(), gomock.Any()).Do(func(arg0 *goGit.Repository, arg1 plumbing.Hash) {}).Return(&object.Commit{}, nil) } err := g.Pull(ctx, branch) if (err != nil) != tt.wantErr { t.Errorf("Pull() error = %v, wantErr %v", err, tt.wantErr) return } if tt.wantErr { if !reflect.DeepEqual(err, tt.matchError) { t.Errorf("Pull() error = %v, matchError %v", err, tt.matchError) } } }) } } func TestGoGitInit(t *testing.T) { _, client := newGoGitMock(t) url := "testurl" client.EXPECT().Init(repoDir).Return(&goGit.Repository{}, nil) client.EXPECT().Create(gomock.Any(), url).Do(func(arg0 *goGit.Repository, arg1 string) {}).Return(&goGit.Remote{}, nil) g := &git.GogitClient{ RepoDirectory: &repoDir, RepoUrl: url, Client: client, } err := g.Init() if err != nil { t.Errorf("Init() error = %v", err) return } } func TestGoGitBranch(t *testing.T) { _, client := newGoGitMock(t) repo := &goGit.Repository{} headRef := &plumbing.Reference{} worktree := &goGit.Worktree{} bOpts := &config.Branch{ Name: "testBranch", Remote: "origin", Merge: "refs/heads/testBranch", Rebase: "true", } cOpts := &goGit.CheckoutOptions{ Branch: plumbing.NewBranchReferenceName("testBranch"), Force: true, } client.EXPECT().OpenRepo().Return(repo, nil) client.EXPECT().CreateBranch(repo, bOpts).Return(nil) client.EXPECT().Head(repo).Return(headRef, nil) client.EXPECT().OpenWorktree(gomock.Any()).Do(func(arg0 *goGit.Repository) {}).Return(worktree, nil) client.EXPECT().SetRepositoryReference(repo, gomock.Any()).Return(nil) client.EXPECT().Checkout(worktree, cOpts).Return(nil) client.EXPECT().ListRemotes(repo, gomock.Any()).Return(nil, nil) g := &git.GogitClient{ RepoDirectory: &repoDir, Client: client, } err := g.Branch("testBranch") if err != nil { t.Errorf("Branch() error = %v", err) return } } func TestGoGitBranchRemoteExists(t *testing.T) { _, client := newGoGitMock(t) repo := &goGit.Repository{} headRef := &plumbing.Reference{} worktree := &goGit.Worktree{} bOpts := &config.Branch{ Name: "testBranch", Remote: "origin", Merge: "refs/heads/testBranch", Rebase: "true", } localBranchRef := plumbing.NewBranchReferenceName("testBranch") cOpts := &goGit.CheckoutOptions{ Branch: localBranchRef, Force: true, } returnReferences := []*plumbing.Reference{ plumbing.NewHashReference("refs/heads/testBranch", headRef.Hash()), } client.EXPECT().OpenRepo().Return(repo, nil) client.EXPECT().CreateBranch(repo, bOpts).Return(nil) client.EXPECT().Head(repo).Return(headRef, nil) client.EXPECT().OpenWorktree(gomock.Any()).Do(func(arg0 *goGit.Repository) {}).Return(worktree, nil) client.EXPECT().SetRepositoryReference(repo, gomock.Any()).Return(nil) client.EXPECT().Checkout(worktree, cOpts).Return(nil) client.EXPECT().ListRemotes(repo, gomock.Any()).Return(returnReferences, nil) client.EXPECT().PullWithContext(gomock.Any(), worktree, gomock.Any(), localBranchRef) g := &git.GogitClient{ RepoDirectory: &repoDir, Client: client, } err := g.Branch("testBranch") if err != nil { t.Errorf("Branch() error = %v", err) return } } func TestGoGitValidateRemoteExists(t *testing.T) { tests := []struct { name string wantErr bool throwError error }{ { name: "validate success", wantErr: false, }, { name: "invalid repository error", wantErr: true, throwError: fmt.Errorf("remote repository does not exist"), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, client := newGoGitMock(t) g := &git.GogitClient{ RepoUrl: "testurl", Client: client, } remote := &goGit.Remote{} client.EXPECT().NewRemote(g.RepoUrl, goGit.DefaultRemoteName).Return(remote) client.EXPECT().ListWithContext(ctx, remote, g.Auth).Return([]*plumbing.Reference{}, tt.throwError) err := g.ValidateRemoteExists(ctx) if (err != nil) != tt.wantErr { t.Errorf("Clone() error = %v, wantErr = %v", err, tt.wantErr) } }) } } func newGoGitMock(t *testing.T) (context.Context, *mocks.MockGoGit) { ctx := context.Background() ctrl := gomock.NewController(t) client := mocks.NewMockGoGit(ctrl) return ctx, client }
349
eks-distro-build-tooling
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/git (interfaces: Client,GoGit) // Package mocks is a generated GoMock package. package mocks import ( context "context" reflect "reflect" git "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/git" git0 "github.com/go-git/go-git/v5" config "github.com/go-git/go-git/v5/config" plumbing "github.com/go-git/go-git/v5/plumbing" object "github.com/go-git/go-git/v5/plumbing/object" transport "github.com/go-git/go-git/v5/plumbing/transport" gomock "github.com/golang/mock/gomock" ) // MockClient is a mock of Client interface. type MockClient struct { ctrl *gomock.Controller recorder *MockClientMockRecorder } // MockClientMockRecorder is the mock recorder for MockClient. type MockClientMockRecorder struct { mock *MockClient } // NewMockClient creates a new mock instance. func NewMockClient(ctrl *gomock.Controller) *MockClient { mock := &MockClient{ctrl: ctrl} mock.recorder = &MockClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockClient) EXPECT() *MockClientMockRecorder { return m.recorder } // Add mocks base method. func (m *MockClient) Add(arg0 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Add", arg0) ret0, _ := ret[0].(error) return ret0 } // Add indicates an expected call of Add. func (mr *MockClientMockRecorder) Add(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockClient)(nil).Add), arg0) } // Branch mocks base method. func (m *MockClient) Branch(arg0 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Branch", arg0) ret0, _ := ret[0].(error) return ret0 } // Branch indicates an expected call of Branch. func (mr *MockClientMockRecorder) Branch(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Branch", reflect.TypeOf((*MockClient)(nil).Branch), arg0) } // Clone mocks base method. func (m *MockClient) Clone(arg0 context.Context) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Clone", arg0) ret0, _ := ret[0].(error) return ret0 } // Clone indicates an expected call of Clone. func (mr *MockClientMockRecorder) Clone(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Clone", reflect.TypeOf((*MockClient)(nil).Clone), arg0) } // Commit mocks base method. func (m *MockClient) Commit(arg0 string, arg1 ...git.CommitOpt) error { m.ctrl.T.Helper() varargs := []interface{}{arg0} for _, a := range arg1 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "Commit", varargs...) ret0, _ := ret[0].(error) return ret0 } // Commit indicates an expected call of Commit. func (mr *MockClientMockRecorder) Commit(arg0 interface{}, arg1 ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{arg0}, arg1...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Commit", reflect.TypeOf((*MockClient)(nil).Commit), varargs...) } // Init mocks base method. func (m *MockClient) Init() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Init") ret0, _ := ret[0].(error) return ret0 } // Init indicates an expected call of Init. func (mr *MockClientMockRecorder) Init() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Init", reflect.TypeOf((*MockClient)(nil).Init)) } // Pull mocks base method. func (m *MockClient) Pull(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Pull", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // Pull indicates an expected call of Pull. func (mr *MockClientMockRecorder) Pull(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Pull", reflect.TypeOf((*MockClient)(nil).Pull), arg0, arg1) } // Push mocks base method. func (m *MockClient) Push(arg0 context.Context) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Push", arg0) ret0, _ := ret[0].(error) return ret0 } // Push indicates an expected call of Push. func (mr *MockClientMockRecorder) Push(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Push", reflect.TypeOf((*MockClient)(nil).Push), arg0) } // Remove mocks base method. func (m *MockClient) Remove(arg0 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Remove", arg0) ret0, _ := ret[0].(error) return ret0 } // Remove indicates an expected call of Remove. func (mr *MockClientMockRecorder) Remove(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockClient)(nil).Remove), arg0) } // ValidateRemoteExists mocks base method. func (m *MockClient) ValidateRemoteExists(arg0 context.Context) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ValidateRemoteExists", arg0) ret0, _ := ret[0].(error) return ret0 } // ValidateRemoteExists indicates an expected call of ValidateRemoteExists. func (mr *MockClientMockRecorder) ValidateRemoteExists(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateRemoteExists", reflect.TypeOf((*MockClient)(nil).ValidateRemoteExists), arg0) } // MockGoGit is a mock of GoGit interface. type MockGoGit struct { ctrl *gomock.Controller recorder *MockGoGitMockRecorder } // MockGoGitMockRecorder is the mock recorder for MockGoGit. type MockGoGitMockRecorder struct { mock *MockGoGit } // NewMockGoGit creates a new mock instance. func NewMockGoGit(ctrl *gomock.Controller) *MockGoGit { mock := &MockGoGit{ctrl: ctrl} mock.recorder = &MockGoGitMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockGoGit) EXPECT() *MockGoGitMockRecorder { return m.recorder } // AddGlob mocks base method. func (m *MockGoGit) AddGlob(arg0 string, arg1 *git0.Worktree) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddGlob", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // AddGlob indicates an expected call of AddGlob. func (mr *MockGoGitMockRecorder) AddGlob(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddGlob", reflect.TypeOf((*MockGoGit)(nil).AddGlob), arg0, arg1) } // Checkout mocks base method. func (m *MockGoGit) Checkout(arg0 *git0.Worktree, arg1 *git0.CheckoutOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Checkout", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // Checkout indicates an expected call of Checkout. func (mr *MockGoGitMockRecorder) Checkout(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Checkout", reflect.TypeOf((*MockGoGit)(nil).Checkout), arg0, arg1) } // Clone mocks base method. func (m *MockGoGit) Clone(arg0 context.Context, arg1, arg2 string, arg3 transport.AuthMethod) (*git0.Repository, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Clone", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(*git0.Repository) ret1, _ := ret[1].(error) return ret0, ret1 } // Clone indicates an expected call of Clone. func (mr *MockGoGitMockRecorder) Clone(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Clone", reflect.TypeOf((*MockGoGit)(nil).Clone), arg0, arg1, arg2, arg3) } // CloneInMemory mocks base method. func (m *MockGoGit) CloneInMemory(arg0 context.Context, arg1 string, arg2 transport.AuthMethod) (*git0.Repository, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CloneInMemory", arg0, arg1, arg2) ret0, _ := ret[0].(*git0.Repository) ret1, _ := ret[1].(error) return ret0, ret1 } // CloneInMemory indicates an expected call of CloneInMemory. func (mr *MockGoGitMockRecorder) CloneInMemory(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CloneInMemory", reflect.TypeOf((*MockGoGit)(nil).CloneInMemory), arg0, arg1, arg2) } // Commit mocks base method. func (m *MockGoGit) Commit(arg0 string, arg1 *object.Signature, arg2 *git0.Worktree) (plumbing.Hash, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Commit", arg0, arg1, arg2) ret0, _ := ret[0].(plumbing.Hash) ret1, _ := ret[1].(error) return ret0, ret1 } // Commit indicates an expected call of Commit. func (mr *MockGoGitMockRecorder) Commit(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Commit", reflect.TypeOf((*MockGoGit)(nil).Commit), arg0, arg1, arg2) } // CommitObject mocks base method. func (m *MockGoGit) CommitObject(arg0 *git0.Repository, arg1 plumbing.Hash) (*object.Commit, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CommitObject", arg0, arg1) ret0, _ := ret[0].(*object.Commit) ret1, _ := ret[1].(error) return ret0, ret1 } // CommitObject indicates an expected call of CommitObject. func (mr *MockGoGitMockRecorder) CommitObject(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitObject", reflect.TypeOf((*MockGoGit)(nil).CommitObject), arg0, arg1) } // Create mocks base method. func (m *MockGoGit) Create(arg0 *git0.Repository, arg1 string) (*git0.Remote, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Create", arg0, arg1) ret0, _ := ret[0].(*git0.Remote) ret1, _ := ret[1].(error) return ret0, ret1 } // Create indicates an expected call of Create. func (mr *MockGoGitMockRecorder) Create(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockGoGit)(nil).Create), arg0, arg1) } // CreateBranch mocks base method. func (m *MockGoGit) CreateBranch(arg0 *git0.Repository, arg1 *config.Branch) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateBranch", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // CreateBranch indicates an expected call of CreateBranch. func (mr *MockGoGitMockRecorder) CreateBranch(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateBranch", reflect.TypeOf((*MockGoGit)(nil).CreateBranch), arg0, arg1) } // Head mocks base method. func (m *MockGoGit) Head(arg0 *git0.Repository) (*plumbing.Reference, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Head", arg0) ret0, _ := ret[0].(*plumbing.Reference) ret1, _ := ret[1].(error) return ret0, ret1 } // Head indicates an expected call of Head. func (mr *MockGoGitMockRecorder) Head(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Head", reflect.TypeOf((*MockGoGit)(nil).Head), arg0) } // Init mocks base method. func (m *MockGoGit) Init(arg0 string) (*git0.Repository, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Init", arg0) ret0, _ := ret[0].(*git0.Repository) ret1, _ := ret[1].(error) return ret0, ret1 } // Init indicates an expected call of Init. func (mr *MockGoGitMockRecorder) Init(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Init", reflect.TypeOf((*MockGoGit)(nil).Init), arg0) } // ListRemotes mocks base method. func (m *MockGoGit) ListRemotes(arg0 *git0.Repository, arg1 transport.AuthMethod) ([]*plumbing.Reference, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListRemotes", arg0, arg1) ret0, _ := ret[0].([]*plumbing.Reference) ret1, _ := ret[1].(error) return ret0, ret1 } // ListRemotes indicates an expected call of ListRemotes. func (mr *MockGoGitMockRecorder) ListRemotes(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListRemotes", reflect.TypeOf((*MockGoGit)(nil).ListRemotes), arg0, arg1) } // ListWithContext mocks base method. func (m *MockGoGit) ListWithContext(arg0 context.Context, arg1 *git0.Remote, arg2 transport.AuthMethod) ([]*plumbing.Reference, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListWithContext", arg0, arg1, arg2) ret0, _ := ret[0].([]*plumbing.Reference) ret1, _ := ret[1].(error) return ret0, ret1 } // ListWithContext indicates an expected call of ListWithContext. func (mr *MockGoGitMockRecorder) ListWithContext(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWithContext", reflect.TypeOf((*MockGoGit)(nil).ListWithContext), arg0, arg1, arg2) } // NewRemote mocks base method. func (m *MockGoGit) NewRemote(arg0, arg1 string) *git0.Remote { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NewRemote", arg0, arg1) ret0, _ := ret[0].(*git0.Remote) return ret0 } // NewRemote indicates an expected call of NewRemote. func (mr *MockGoGitMockRecorder) NewRemote(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewRemote", reflect.TypeOf((*MockGoGit)(nil).NewRemote), arg0, arg1) } // OpenRepo mocks base method. func (m *MockGoGit) OpenRepo() (*git0.Repository, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "OpenRepo") ret0, _ := ret[0].(*git0.Repository) ret1, _ := ret[1].(error) return ret0, ret1 } // OpenRepo indicates an expected call of OpenRepo. func (mr *MockGoGitMockRecorder) OpenRepo() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OpenRepo", reflect.TypeOf((*MockGoGit)(nil).OpenRepo)) } // OpenWorktree mocks base method. func (m *MockGoGit) OpenWorktree(arg0 *git0.Repository) (*git0.Worktree, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "OpenWorktree", arg0) ret0, _ := ret[0].(*git0.Worktree) ret1, _ := ret[1].(error) return ret0, ret1 } // OpenWorktree indicates an expected call of OpenWorktree. func (mr *MockGoGitMockRecorder) OpenWorktree(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OpenWorktree", reflect.TypeOf((*MockGoGit)(nil).OpenWorktree), arg0) } // PullWithContext mocks base method. func (m *MockGoGit) PullWithContext(arg0 context.Context, arg1 *git0.Worktree, arg2 transport.AuthMethod, arg3 plumbing.ReferenceName) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PullWithContext", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(error) return ret0 } // PullWithContext indicates an expected call of PullWithContext. func (mr *MockGoGitMockRecorder) PullWithContext(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PullWithContext", reflect.TypeOf((*MockGoGit)(nil).PullWithContext), arg0, arg1, arg2, arg3) } // PushWithContext mocks base method. func (m *MockGoGit) PushWithContext(arg0 context.Context, arg1 *git0.Repository, arg2 transport.AuthMethod) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PushWithContext", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // PushWithContext indicates an expected call of PushWithContext. func (mr *MockGoGitMockRecorder) PushWithContext(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PushWithContext", reflect.TypeOf((*MockGoGit)(nil).PushWithContext), arg0, arg1, arg2) } // Remove mocks base method. func (m *MockGoGit) Remove(arg0 string, arg1 *git0.Worktree) (plumbing.Hash, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Remove", arg0, arg1) ret0, _ := ret[0].(plumbing.Hash) ret1, _ := ret[1].(error) return ret0, ret1 } // Remove indicates an expected call of Remove. func (mr *MockGoGitMockRecorder) Remove(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockGoGit)(nil).Remove), arg0, arg1) } // SetRepositoryReference mocks base method. func (m *MockGoGit) SetRepositoryReference(arg0 *git0.Repository, arg1 *plumbing.Reference) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetRepositoryReference", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // SetRepositoryReference indicates an expected call of SetRepositoryReference. func (mr *MockGoGitMockRecorder) SetRepositoryReference(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetRepositoryReference", reflect.TypeOf((*MockGoGit)(nil).SetRepositoryReference), arg0, arg1) } // WithRepositoryDirectory mocks base method. func (m *MockGoGit) WithRepositoryDirectory(arg0 string) { m.ctrl.T.Helper() m.ctrl.Call(m, "WithRepositoryDirectory", arg0) } // WithRepositoryDirectory indicates an expected call of WithRepositoryDirectory. func (mr *MockGoGitMockRecorder) WithRepositoryDirectory(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WithRepositoryDirectory", reflect.TypeOf((*MockGoGit)(nil).WithRepositoryDirectory), arg0) }
486
eks-distro-build-tooling
aws
Go
package github import ( "context" "fmt" "github.com/google/go-github/v48/github" "golang.org/x/oauth2" ) type Client struct { Git GitClient Repositories RepoClient PullRequests PullRequestClient Issues IssueClient } type GitClient interface { GetRef(ctx context.Context, owner string, repo string, ref string) (*github.Reference, *github.Response, error) CreateRef(ctx context.Context, owner string, repo string, ref *github.Reference) (*github.Reference, *github.Response, error) CreateTree(ctx context.Context, owner string, repo string, baseTree string, entries []*github.TreeEntry) (*github.Tree, *github.Response, error) CreateCommit(ctx context.Context, owner string, repo string, commit *github.Commit) (*github.Commit, *github.Response, error) UpdateRef(ctx context.Context, owner string, repo string, ref *github.Reference, force bool) (*github.Reference, *github.Response, error) } type RepoClient interface { GetCommit(ctx context.Context, owner, repo, sha string, opts *github.ListOptions) (*github.RepositoryCommit, *github.Response, error) GetContents(ctx context.Context, owner, repo, path string, opts *github.RepositoryContentGetOptions) (fileContent *github.RepositoryContent, directoryContent []*github.RepositoryContent, resp *github.Response, err error) } type PullRequestClient interface { Get(ctx context.Context, owner string, repo string, number int) (*github.PullRequest, *github.Response, error) Create(ctx context.Context, owner string, repo string, pull *github.NewPullRequest) (*github.PullRequest, *github.Response, error) List(ctx context.Context, owner string, repo string, opts *github.PullRequestListOptions) ([]*github.PullRequest, *github.Response, error) } type IssueClient interface { Create(ctx context.Context, owner string, repo string, issue *github.IssueRequest) (*github.Issue, *github.Response, error) Get(ctx context.Context, owner string, repo string, issueNum int) (*github.Issue, *github.Response, error) } func NewClient(ctx context.Context, personalAccessToken string) (*Client, error) { if personalAccessToken == "" { return nil, fmt.Errorf("no personal access token provided when instantiating Github client") } ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: personalAccessToken}) tc := oauth2.NewClient(ctx, ts) c := github.NewClient(tc) client := &Client{ Git: c.Git, Repositories: c.Repositories, PullRequests: c.PullRequests, Issues: c.Issues, } return client, nil }
57
eks-distro-build-tooling
aws
Go
package github const ( SecondaryRateLimitResponse = "You have exceeded a secondary rate limit and have been temporarily blocked from content creation. Please retry your request again later." SecondaryRateLimitStatusCode = 403 ResourceGoneStatusCode = 410 IssuesDisabledForRepoResponse = "Issues are disabled for this repo" PullRequestAlreadyExistsForBranchError = "A pull request already exists for" )
10
eks-distro-build-tooling
aws
Go
package github_test import ( "fmt" "os" "testing" "github.com/stretchr/testify/assert" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/github" ) const ( TestPatValue = "abcdefghijklmnopqrstuvwxyz" ) func TestGithubPATAccessFailsUnset(t *testing.T) { err := os.Unsetenv(github.PersonalAccessTokenEnvVar) if err != nil { t.Errorf("failed to unset Github PAT env var during test setup") } _, err = github.GetGithubToken() assert.Errorf(t, err, fmt.Sprintf("Github Token environment variable %s not set", github.PersonalAccessTokenEnvVar)) } func TestGithubPATAccessFailsSetEmpty(t *testing.T) { err := os.Setenv(github.PersonalAccessTokenEnvVar, "") if err != nil { t.Errorf("failed to set Github PAT env var during test setup") } _, err = github.GetGithubToken() assert.Errorf(t, err, fmt.Sprintf("Github Token enviornment variable %s is empty", github.PersonalAccessTokenEnvVar)) } func TestGithubPATAccessSuccess(t *testing.T) { err := os.Setenv(github.PersonalAccessTokenEnvVar, TestPatValue) if err != nil { t.Errorf("failed to set Github PAT env var during test setup") } token, err := github.GetGithubToken() assert.Nil(t, err) assert.NotNil(t, token) assert.EqualValues(t, token, TestPatValue) }
45
eks-distro-build-tooling
aws
Go
package github import ( "fmt" "os" ) const ( PersonalAccessTokenEnvVar = "GITHUB_TOKEN" ) func GetGithubToken() (string, error){ t, ok := os.LookupEnv(PersonalAccessTokenEnvVar); if !ok { return "", fmt.Errorf("Github Token environment variable %s not set", PersonalAccessTokenEnvVar) } if t == "" { return "", fmt.Errorf("Github Token enviornment variable %s is empty", PersonalAccessTokenEnvVar) } return t, nil }
20
eks-distro-build-tooling
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/github (interfaces: GitClient,IssueClient,RepoClient,PullRequestClient) // Package mocks is a generated GoMock package. package mocks import ( context "context" reflect "reflect" gomock "github.com/golang/mock/gomock" github "github.com/google/go-github/v48/github" ) // MockGitClient is a mock of GitClient interface. type MockGitClient struct { ctrl *gomock.Controller recorder *MockGitClientMockRecorder } // MockGitClientMockRecorder is the mock recorder for MockGitClient. type MockGitClientMockRecorder struct { mock *MockGitClient } // NewMockGitClient creates a new mock instance. func NewMockGitClient(ctrl *gomock.Controller) *MockGitClient { mock := &MockGitClient{ctrl: ctrl} mock.recorder = &MockGitClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockGitClient) EXPECT() *MockGitClientMockRecorder { return m.recorder } // CreateCommit mocks base method. func (m *MockGitClient) CreateCommit(arg0 context.Context, arg1, arg2 string, arg3 *github.Commit) (*github.Commit, *github.Response, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateCommit", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(*github.Commit) ret1, _ := ret[1].(*github.Response) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // CreateCommit indicates an expected call of CreateCommit. func (mr *MockGitClientMockRecorder) CreateCommit(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateCommit", reflect.TypeOf((*MockGitClient)(nil).CreateCommit), arg0, arg1, arg2, arg3) } // CreateRef mocks base method. func (m *MockGitClient) CreateRef(arg0 context.Context, arg1, arg2 string, arg3 *github.Reference) (*github.Reference, *github.Response, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateRef", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(*github.Reference) ret1, _ := ret[1].(*github.Response) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // CreateRef indicates an expected call of CreateRef. func (mr *MockGitClientMockRecorder) CreateRef(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateRef", reflect.TypeOf((*MockGitClient)(nil).CreateRef), arg0, arg1, arg2, arg3) } // CreateTree mocks base method. func (m *MockGitClient) CreateTree(arg0 context.Context, arg1, arg2, arg3 string, arg4 []*github.TreeEntry) (*github.Tree, *github.Response, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateTree", arg0, arg1, arg2, arg3, arg4) ret0, _ := ret[0].(*github.Tree) ret1, _ := ret[1].(*github.Response) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // CreateTree indicates an expected call of CreateTree. func (mr *MockGitClientMockRecorder) CreateTree(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateTree", reflect.TypeOf((*MockGitClient)(nil).CreateTree), arg0, arg1, arg2, arg3, arg4) } // GetRef mocks base method. func (m *MockGitClient) GetRef(arg0 context.Context, arg1, arg2, arg3 string) (*github.Reference, *github.Response, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetRef", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(*github.Reference) ret1, _ := ret[1].(*github.Response) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // GetRef indicates an expected call of GetRef. func (mr *MockGitClientMockRecorder) GetRef(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRef", reflect.TypeOf((*MockGitClient)(nil).GetRef), arg0, arg1, arg2, arg3) } // UpdateRef mocks base method. func (m *MockGitClient) UpdateRef(arg0 context.Context, arg1, arg2 string, arg3 *github.Reference, arg4 bool) (*github.Reference, *github.Response, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UpdateRef", arg0, arg1, arg2, arg3, arg4) ret0, _ := ret[0].(*github.Reference) ret1, _ := ret[1].(*github.Response) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // UpdateRef indicates an expected call of UpdateRef. func (mr *MockGitClientMockRecorder) UpdateRef(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateRef", reflect.TypeOf((*MockGitClient)(nil).UpdateRef), arg0, arg1, arg2, arg3, arg4) } // MockIssueClient is a mock of IssueClient interface. type MockIssueClient struct { ctrl *gomock.Controller recorder *MockIssueClientMockRecorder } // MockIssueClientMockRecorder is the mock recorder for MockIssueClient. type MockIssueClientMockRecorder struct { mock *MockIssueClient } // NewMockIssueClient creates a new mock instance. func NewMockIssueClient(ctrl *gomock.Controller) *MockIssueClient { mock := &MockIssueClient{ctrl: ctrl} mock.recorder = &MockIssueClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockIssueClient) EXPECT() *MockIssueClientMockRecorder { return m.recorder } // Create mocks base method. func (m *MockIssueClient) Create(arg0 context.Context, arg1, arg2 string, arg3 *github.IssueRequest) (*github.Issue, *github.Response, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Create", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(*github.Issue) ret1, _ := ret[1].(*github.Response) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // Create indicates an expected call of Create. func (mr *MockIssueClientMockRecorder) Create(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockIssueClient)(nil).Create), arg0, arg1, arg2, arg3) } // Get mocks base method. func (m *MockIssueClient) Get(arg0 context.Context, arg1, arg2 string, arg3 int) (*github.Issue, *github.Response, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(*github.Issue) ret1, _ := ret[1].(*github.Response) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // Get indicates an expected call of Get. func (mr *MockIssueClientMockRecorder) Get(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockIssueClient)(nil).Get), arg0, arg1, arg2, arg3) } // MockRepoClient is a mock of RepoClient interface. type MockRepoClient struct { ctrl *gomock.Controller recorder *MockRepoClientMockRecorder } // MockRepoClientMockRecorder is the mock recorder for MockRepoClient. type MockRepoClientMockRecorder struct { mock *MockRepoClient } // NewMockRepoClient creates a new mock instance. func NewMockRepoClient(ctrl *gomock.Controller) *MockRepoClient { mock := &MockRepoClient{ctrl: ctrl} mock.recorder = &MockRepoClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockRepoClient) EXPECT() *MockRepoClientMockRecorder { return m.recorder } // GetCommit mocks base method. func (m *MockRepoClient) GetCommit(arg0 context.Context, arg1, arg2, arg3 string, arg4 *github.ListOptions) (*github.RepositoryCommit, *github.Response, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetCommit", arg0, arg1, arg2, arg3, arg4) ret0, _ := ret[0].(*github.RepositoryCommit) ret1, _ := ret[1].(*github.Response) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // GetCommit indicates an expected call of GetCommit. func (mr *MockRepoClientMockRecorder) GetCommit(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCommit", reflect.TypeOf((*MockRepoClient)(nil).GetCommit), arg0, arg1, arg2, arg3, arg4) } // GetContents mocks base method. func (m *MockRepoClient) GetContents(arg0 context.Context, arg1, arg2, arg3 string, arg4 *github.RepositoryContentGetOptions) (*github.RepositoryContent, []*github.RepositoryContent, *github.Response, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetContents", arg0, arg1, arg2, arg3, arg4) ret0, _ := ret[0].(*github.RepositoryContent) ret1, _ := ret[1].([]*github.RepositoryContent) ret2, _ := ret[2].(*github.Response) ret3, _ := ret[3].(error) return ret0, ret1, ret2, ret3 } // GetContents indicates an expected call of GetContents. func (mr *MockRepoClientMockRecorder) GetContents(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetContents", reflect.TypeOf((*MockRepoClient)(nil).GetContents), arg0, arg1, arg2, arg3, arg4) } // MockPullRequestClient is a mock of PullRequestClient interface. type MockPullRequestClient struct { ctrl *gomock.Controller recorder *MockPullRequestClientMockRecorder } // MockPullRequestClientMockRecorder is the mock recorder for MockPullRequestClient. type MockPullRequestClientMockRecorder struct { mock *MockPullRequestClient } // NewMockPullRequestClient creates a new mock instance. func NewMockPullRequestClient(ctrl *gomock.Controller) *MockPullRequestClient { mock := &MockPullRequestClient{ctrl: ctrl} mock.recorder = &MockPullRequestClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockPullRequestClient) EXPECT() *MockPullRequestClientMockRecorder { return m.recorder } // Create mocks base method. func (m *MockPullRequestClient) Create(arg0 context.Context, arg1, arg2 string, arg3 *github.NewPullRequest) (*github.PullRequest, *github.Response, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Create", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(*github.PullRequest) ret1, _ := ret[1].(*github.Response) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // Create indicates an expected call of Create. func (mr *MockPullRequestClientMockRecorder) Create(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockPullRequestClient)(nil).Create), arg0, arg1, arg2, arg3) } // Get mocks base method. func (m *MockPullRequestClient) Get(arg0 context.Context, arg1, arg2 string, arg3 int) (*github.PullRequest, *github.Response, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(*github.PullRequest) ret1, _ := ret[1].(*github.Response) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // Get indicates an expected call of Get. func (mr *MockPullRequestClientMockRecorder) Get(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockPullRequestClient)(nil).Get), arg0, arg1, arg2, arg3) } // List mocks base method. func (m *MockPullRequestClient) List(arg0 context.Context, arg1, arg2 string, arg3 *github.PullRequestListOptions) ([]*github.PullRequest, *github.Response, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "List", arg0, arg1, arg2, arg3) ret0, _ := ret[0].([]*github.PullRequest) ret1, _ := ret[1].(*github.Response) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // List indicates an expected call of List. func (mr *MockPullRequestClientMockRecorder) List(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockPullRequestClient)(nil).List), arg0, arg1, arg2, arg3) }
299
eks-distro-build-tooling
aws
Go
package issueManager import ( "context" "fmt" "io" "strings" "time" gogithub "github.com/google/go-github/v48/github" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/github" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/logger" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/retrier" ) type IssueManager struct { client *github.Client sourceOwner string sourceRepo string retrier *retrier.Retrier } type Opts struct { SourceOwner string SourceRepo string } func New(r *retrier.Retrier, githubClient *github.Client, opts *Opts) *IssueManager { return &IssueManager{ client: githubClient, sourceOwner: opts.SourceOwner, sourceRepo: opts.SourceRepo, retrier: r, } } type CreateIssueOpts struct { Title *string Body *string Labels *[]string Assignee *string State *string } func (p *IssueManager) CreateIssue(ctx context.Context, opts *CreateIssueOpts) (*gogithub.Issue, error) { i := &gogithub.IssueRequest{ Title: opts.Title, Body: opts.Body, Labels: opts.Labels, Assignee: opts.Assignee, State: opts.State, } var issue *gogithub.Issue var resp *gogithub.Response var err error issue, resp, err = p.client.Issues.Create(ctx, p.sourceOwner, p.sourceRepo, i) if resp != nil { if resp.StatusCode == github.SecondaryRateLimitStatusCode { b, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("reading Github response body: %v", err) } if strings.Contains(string(b), github.SecondaryRateLimitResponse) { logger.V(4).Info("rate limited while attempting to create github issue") return nil, fmt.Errorf("rate limited while attempting to create github issues: %v", err) } } if resp.StatusCode == github.ResourceGoneStatusCode { b, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("reading Github response body: %v", err) } if strings.Contains(string(b), github.IssuesDisabledForRepoResponse) { logger.V(4).Info("Can't create an issue, issues are disabled for repo", "repo", p.sourceRepo) return nil, fmt.Errorf("creating Github issue: issues are disabled for repo. error: %v, response: %v", err, resp) } } } if err != nil { logger.V(4).Error(err, "creating Github issue", "response", resp) return nil, fmt.Errorf("creating Github issue: %v; resp: %v", err, resp) } logger.V(4).Info("create issue response", "response", resp.Response.StatusCode) logger.V(1).Info("Github issue created", "issue URL", issue.GetHTMLURL()) return issue, nil } type GetIssueOpts struct { Owner string Repo string Issue int } func (p *IssueManager) GetIssue(ctx context.Context, opts *GetIssueOpts) (*gogithub.Issue, error) { var issue *gogithub.Issue var resp *gogithub.Response var err error issue, resp, err = p.client.Issues.Get(ctx, opts.Owner, opts.Repo, opts.Issue) if resp != nil { if resp.StatusCode == github.SecondaryRateLimitStatusCode { b, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("reading Github response body: %v", err) } if strings.Contains(string(b), github.SecondaryRateLimitResponse) { logger.V(4).Info("rate limited while attempting to get github issue") return nil, fmt.Errorf("rate limited while attempting to get github issues: %v", err) } } if resp.StatusCode == github.ResourceGoneStatusCode { _, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("reading Github response body: %v", err) } } } if err != nil { logger.V(4).Error(err, "getting Github issue", "response", resp) return nil, fmt.Errorf("getting Github issue: %v; resp: %v", err, resp) } logger.V(4).Info("get issue response", "response", resp.Response.StatusCode) logger.V(1).Info("Github issue received", "issue URL", issue.GetHTMLURL()) logger.V(4).Info("sleeping after Issue request to avoid secondary rate limiting by Github content API") time.Sleep(time.Second * 1) return issue, nil }
131
eks-distro-build-tooling
aws
Go
package issueManager_test import ( "context" "io" "net/http" "strings" "testing" "github.com/golang/mock/gomock" gogithub "github.com/google/go-github/v48/github" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/github" githubMocks "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/github/mocks" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/issueManager" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/retrier" ) const ( HttpOkStatusCode = 200 rateLimitingIssuesError = "rate limited while attempting to create github issues" ) var ( TestRepoOwner = "TestTesterson" TestRepo = "TestRepo" IssueTitle = "Title" IssueBody = "Body" IssueAssignee = "Jeff" IssueState = "Open" ReturnIssueHtmlUrl = "https://github.com/testrepo/issues/999" IssueNumber = 999 ) func expectedLabels() *[]string { return &[]string{"sup", "test"} } func TestIssueManagerCreateIssueSuccess(t *testing.T) { ctx := context.Background() im := newTestIssueManager(t) opts := &issueManager.CreateIssueOpts{ Title: &IssueTitle, Body: &IssueBody, Labels: expectedLabels(), Assignee: &IssueAssignee, State: &IssueState, } expectedIssue := &gogithub.IssueRequest{ Title: &IssueTitle, Body: &IssueBody, Labels: expectedLabels(), Assignee: &IssueAssignee, State: &IssueState, } expectedReturnIssue := &gogithub.Issue{ HTMLURL: &ReturnIssueHtmlUrl, } expectedResponse := &gogithub.Response{ Response: &http.Response{ StatusCode: HttpOkStatusCode, }, } im.issuesClient.EXPECT().Create(ctx, TestRepoOwner, TestRepo, expectedIssue).Return(expectedReturnIssue, expectedResponse, nil) _, err := im.issueManager.CreateIssue(context.Background(), opts) if err != nil { t.Errorf("IssueManager.CreateIssue() error = %v, want nil", err) } } func TestIssueManagerCreateIssueRateLimitedFail(t *testing.T) { ctx := context.Background() im := newTestIssueManager(t) opts := &issueManager.CreateIssueOpts{ Title: &IssueTitle, Body: &IssueBody, Labels: expectedLabels(), Assignee: &IssueAssignee, State: &IssueState, } expectedIssue := &gogithub.IssueRequest{ Title: &IssueTitle, Body: &IssueBody, Labels: expectedLabels(), Assignee: &IssueAssignee, State: &IssueState, } expectedReturnIssue := &gogithub.Issue{ HTMLURL: &ReturnIssueHtmlUrl, } im.issuesClient.EXPECT().Create(ctx, TestRepoOwner, TestRepo, expectedIssue).Return(expectedReturnIssue, rateLimitedResponseBody(), nil) _, err := im.issueManager.CreateIssue(context.Background(), opts) if err != nil && !strings.Contains(err.Error(), rateLimitingIssuesError) { t.Errorf("IssueManager.CreateIssue() rate limiting exepcted error; error = nil, want %s", rateLimitingIssuesError) } } func TestIssueManagerGetIssueSuccess(t *testing.T) { ctx := context.Background() im := newTestIssueManager(t) opts := &issueManager.GetIssueOpts{ Owner: TestRepoOwner, Repo: TestRepo, Issue: IssueNumber, } expectedReturnIssue := &gogithub.Issue{ HTMLURL: &ReturnIssueHtmlUrl, } expectedResponse := &gogithub.Response{ Response: &http.Response{ StatusCode: HttpOkStatusCode, }, } im.issuesClient.EXPECT().Get(ctx, TestRepoOwner, TestRepo, IssueNumber).Return(expectedReturnIssue, expectedResponse, nil) _, err := im.issueManager.GetIssue(context.Background(), opts) if err != nil { t.Errorf("IssueManager.GetIssue() error = %v, want nil", err) } } func givenRetrier() *retrier.Retrier { return retrier.NewWithMaxRetries(4, 1) } type testIssueManager struct { issueManager *issueManager.IssueManager issuesClient *githubMocks.MockIssueClient } func newTestIssueManager(t *testing.T) testIssueManager { mockCtrl := gomock.NewController(t) issueClient := githubMocks.NewMockIssueClient(mockCtrl) githubClient := &github.Client{ Issues: issueClient, } o := &issueManager.Opts{ SourceOwner: TestRepoOwner, SourceRepo: TestRepo, } return testIssueManager{ issuesClient: issueClient, issueManager: issueManager.New(givenRetrier(), githubClient, o), } } func rateLimitedResponseBody() *gogithub.Response { rateLimitResponseBody := io.NopCloser(strings.NewReader(github.SecondaryRateLimitResponse)) return &gogithub.Response{ Response: &http.Response{ StatusCode: github.SecondaryRateLimitStatusCode, Body: rateLimitResponseBody, }, } }
157
eks-distro-build-tooling
aws
Go
/* Package logger implements a simple way to init a global logger and access it through a logr.Logger interface. Message: All messages should start with a capital letter. Log level: The loggers only support verbosity levels (V-levels) instead of semantic levels. Level zero, the default, matters most. Increasing levels matter less and less. - 0: You always want to see this. - 1: Common logging that you don't want to show by default. - 2: Useful steady state information about the operation and important log messages that may correlate to significant changes in the system. - 3: Extended information about changes. Somehow useful information to the user that is not important enough for level 2. - 4: Debugging information. Starting from this level, all logs are oriented to developers and troubleshooting. - 5: Traces. Information to follow the code path. - 6: Information about interaction with external resources. External binary commands, api calls. - 7: Extra information passed to external systems. Configuration files, kubernetes manifests, etc. - 8: Truncated external binaries and clients output/responses. - 9: Full external binaries and clients output/responses. Logging WithValues: Logging WithValues should be preferred to embedding values into log messages because it allows machine readability. Variables name should start with a capital letter. Logging WithNames: Logging WithNames should be used carefully. Please consider that practices like prefixing the logs with something indicating which part of code is generating the log entry might be useful for developers, but it can create confusion for the end users because it increases the verbosity without providing information the user can understand/take benefit from. Logging errors: A proper error management should always be preferred to the usage of log.Error. */ package logger
43
eks-distro-build-tooling
aws
Go
package logger import ( "fmt" "time" "github.com/go-logr/zapr" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) // InitZap creates a zap logger with the provided verbosity level // and sets it as the package logger. // 0 is the least verbose and 10 the most verbose. // The package logger can only be init once, so subsequent calls to this method // won't have any effect. func InitZap(level int, opts ...LoggerOpt) error { cfg := zap.NewDevelopmentConfig() cfg.Level = zap.NewAtomicLevelAt(zapcore.Level(-1 * level)) cfg.EncoderConfig.EncodeLevel = nil cfg.EncoderConfig.EncodeTime = NullTimeEncoder cfg.DisableCaller = true cfg.DisableStacktrace = true // Only enabling this at level 4 because that's when // our debugging levels start. Ref: doc.go if level >= 4 { cfg.EncoderConfig.EncodeLevel = VLevelEncoder cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder } zapLog, err := cfg.Build() if err != nil { return fmt.Errorf("creating zap logger: %v", err) } logr := zapr.NewLogger(zapLog) for _, opt := range opts { opt(&logr) } set(logr) l.V(4).Info("Logger init completed", "vlevel", level) return nil } // VLevelEncoder serializes a Level to V + v-level number,. func VLevelEncoder(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) { enc.AppendString(fmt.Sprintf("V%d", -1*int(l))) } // NullTimeEncoder skips time serialization. func NullTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {}
54
eks-distro-build-tooling
aws
Go
package metrics import ( "fmt" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/cloudwatch" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/logger" ) func New(cloudwatchClient cloudwatch.CloudWatch) *MetricPublisher { return &MetricPublisher{ cloudwatchClient: cloudwatchClient, } } type MetricPublisher struct { cloudwatchClient cloudwatch.CloudWatch } func (m *MetricPublisher) PublishMetric(metric *cloudwatch.PutMetricDataInput) (*cloudwatch.PutMetricDataOutput, error) { outputData, err := m.cloudwatchClient.PutMetricData(metric) logger.V(9).Info("put metric data", "inputData", metric.MetricData, "outputData", outputData) if err != nil { if awsErr, ok := err.(awserr.Error); ok { switch awsErr.Code() { case cloudwatch.ErrCodeInvalidParameterValueException: return nil, fmt.Errorf("invalid parameter value: %v code: %v", awsErr.Message(), awsErr.Code()) case cloudwatch.ErrCodeMissingRequiredParameterException: return nil, fmt.Errorf("required parameter missing: %v code: %v", awsErr.Message(), awsErr.Code()) case cloudwatch.ErrCodeInvalidParameterCombinationException: return nil, fmt.Errorf("invalid parameter combination: %v code: %v", awsErr.Message(), awsErr.Code()) case cloudwatch.ErrCodeInternalServiceFault : return nil, fmt.Errorf("cloudwatch internal service fault: %v code: %v", awsErr.Message(), awsErr.Code()) } } return nil, fmt.Errorf("putting metric data %v: %v", metric.MetricData, err) } return outputData, nil }
42
eks-distro-build-tooling
aws
Go
package prmanager import ( "context" "errors" "fmt" "strings" "time" gogithub "github.com/google/go-github/v48/github" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/github" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/logger" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/retrier" ) type PrCreator struct { client *github.Client sourceOwner string sourceRepo string prRepo string prRepoOwner string retrier *retrier.Retrier } type Opts struct { SourceOwner string SourceRepo string PrRepo string PrRepoOwner string } func New(retrier *retrier.Retrier, client *github.Client, opts *Opts) *PrCreator { return &PrCreator{ client: client, sourceOwner: opts.SourceOwner, sourceRepo: opts.SourceRepo, prRepo: opts.PrRepo, prRepoOwner: opts.PrRepoOwner, retrier: retrier, } } // getRef returns the commit branch reference object if it exists or creates it // from the base branch before returning it. func (p *PrCreator) getRef(ctx context.Context, commitBranch string, baseBranch string) (ref *gogithub.Reference, err error) { if ref, _, err = p.client.Git.GetRef(ctx, p.sourceOwner, p.sourceRepo, "refs/heads/"+commitBranch); err == nil { return ref, nil } if commitBranch == baseBranch { return nil, errors.New("the commit-branch does not exist but base-branch is the same as commit-branch") } var baseRef *gogithub.Reference if baseRef, _, err = p.client.Git.GetRef(ctx, p.sourceOwner, p.sourceRepo, "refs/heads/"+baseBranch); err != nil { return nil, err } newRef := &gogithub.Reference{Ref: gogithub.String("refs/heads/" + commitBranch), Object: &gogithub.GitObject{SHA: baseRef.Object.SHA}} ref, _, err = p.client.Git.CreateRef(ctx, p.sourceOwner, p.sourceRepo, newRef) return ref, err } // getTree generates the tree to commit based on the given files and the commit // of the ref you got in getRef. func (p *PrCreator) getTree(ctx context.Context, ref *gogithub.Reference, sourceFileBody []byte, destFilePath string) (tree *gogithub.Tree, err error) { // Create a tree with what to commit. entries := []*gogithub.TreeEntry{} entries = append(entries, &gogithub.TreeEntry{Path: gogithub.String(destFilePath), Type: gogithub.String("blob"), Content: gogithub.String(string(sourceFileBody)), Mode: gogithub.String("100644")}) tree, _, err = p.client.Git.CreateTree(ctx, p.sourceOwner, p.sourceRepo, *ref.Object.SHA, entries) return tree, err } // pushCommit creates the commit in the given reference using the given tree. func (p *PrCreator) pushCommit(ctx context.Context, ref *gogithub.Reference, tree *gogithub.Tree, authorName string, authorEmail string, commitMessage string) (err error) { // Get the parent commit to attach the commit to. parent, _, err := p.client.Repositories.GetCommit(ctx, p.sourceOwner, p.sourceRepo, *ref.Object.SHA, nil) if err != nil { return err } // This is not always populated, but is needed. parent.Commit.SHA = parent.SHA // Create the commit using the tree. date := time.Now() author := &gogithub.CommitAuthor{ Date: &date, Name: &authorName, Email: &authorEmail, } commit := &gogithub.Commit{ Author: author, Message: &commitMessage, Tree: tree, Parents: []*gogithub.Commit{ parent.Commit, }, } newCommit, _, err := p.client.Git.CreateCommit(ctx, p.sourceOwner, p.sourceRepo, commit) if err != nil { return err } // Attach the commit to the master branch. ref.Object.SHA = newCommit.SHA _, _, err = p.client.Git.UpdateRef(ctx, p.sourceOwner, p.sourceRepo, ref, false) return err } func (p *PrCreator) getPr(ctx context.Context, opts *GetPrOpts) (*gogithub.PullRequest, error) { o := &gogithub.PullRequestListOptions{ Head: fmt.Sprintf("%v:%v", p.prRepoOwner, opts.CommitBranch), Base: opts.BaseBranch, } list, r, err := p.client.PullRequests.List(ctx, p.prRepoOwner, p.prRepo, o) if err != nil { if r != nil { logger.V(3).Info("listing pr response", "status code", r.Response.StatusCode) } return nil, fmt.Errorf("getting open PR into %v from %v: listing PR: %v", opts.BaseBranch, opts.CommitBranch, err) } if len(list) > 1 { return nil, fmt.Errorf("getting open PR into %v from %v: open PR list is greater than 1, this is impossible or wrong. PR list length: %d", opts.BaseBranch, opts.CommitBranch, len(list)) } if len(list) == 0 { return nil, nil } prNumber := *list[0].Number pr, r, err := p.client.PullRequests.Get(ctx, p.prRepoOwner, p.sourceRepo, prNumber) if err != nil { if r != nil { logger.V(3).Info("getting pr response", "status code", r.Response.StatusCode) } return nil, fmt.Errorf("getting open PR number %d: %v", prNumber, err) } return pr, nil } func (p *PrCreator) createPR(ctx context.Context, opts *CreatePrOpts) (pr *gogithub.PullRequest, err error) { if opts.PrSubject == "" { return nil, fmt.Errorf("PR subject is required") } if p.prRepoOwner != "" && p.prRepoOwner != p.sourceOwner { opts.CommitBranch = fmt.Sprintf("%s:%s", p.sourceOwner, opts.CommitBranch) } else { p.prRepoOwner = p.sourceOwner } if p.prRepo == "" { p.prRepo = p.sourceRepo } newPR := &gogithub.NewPullRequest{ Title: &opts.PrSubject, Head: &opts.CommitBranch, Base: &opts.PrBranch, Body: &opts.PrDescription, MaintainerCanModify: gogithub.Bool(true), } var pullRequest *gogithub.PullRequest var resp *gogithub.Response err = p.retrier.Retry(func() error { pullRequest, resp, err = p.client.PullRequests.Create(ctx, p.prRepoOwner, p.prRepo, newPR) if resp.StatusCode == github.SecondaryRateLimitStatusCode { if strings.Contains(err.Error(), github.SecondaryRateLimitResponse) { return fmt.Errorf("rate limited while attempting to create github pull request: %v", err) } } if err != nil && strings.Contains(err.Error(), github.PullRequestAlreadyExistsForBranchError) { // there can only be one PR per branch; if there's already an existing PR for the branch, we won't create one, but continue logger.V(1).Info("A Pull Request already exists for the given branch", "branch", opts.CommitBranch) getPrOpts := &GetPrOpts{ CommitBranch: opts.CommitBranch, BaseBranch: "main", } pullRequest, err = p.getPr(ctx, getPrOpts) if err != nil { return err } return nil } if err != nil { return fmt.Errorf("creating Github pull request: %v; resp: %v", err, resp) } logger.V(1).Info("Github Pull Request Created", "Pull Request URL", pullRequest.GetHTMLURL()) return nil }) if err != nil { return nil, fmt.Errorf("creating github pull request: %v", err) } return pullRequest, nil } type CreatePrOpts struct { CommitBranch string BaseBranch string AuthorName string AuthorEmail string CommitMessage string PrSubject string PrBranch string PrDescription string DestFileGitPath string SourceFileBody []byte } func (p *PrCreator) CreatePr(ctx context.Context, opts *CreatePrOpts) (string, error) { ref, err := p.getRef(ctx, opts.CommitBranch, opts.BaseBranch) if err != nil { return "", fmt.Errorf("creating pull request: get/create the commit reference: %s\n", err) } if ref == nil { return "", fmt.Errorf("creating pull request: the reference is nil") } tree, err := p.getTree(ctx, ref, opts.SourceFileBody, opts.DestFileGitPath) if err != nil { return "", fmt.Errorf("creating the tree based on the provided files: %s\n", err) } if err := p.pushCommit(ctx, ref, tree, opts.AuthorName, opts.AuthorEmail, opts.CommitMessage); err != nil { return "", fmt.Errorf("creating the commit: %s\n", err) } pr, err := p.createPR(ctx, opts) if err != nil { return "", fmt.Errorf("creating pull request: %s", err) } return pr.GetHTMLURL(), nil } type GetPrOpts struct { CommitBranch string BaseBranch string } func (p *PrCreator) GetPr(ctx context.Context, opts *GetPrOpts) (string, error) { pr, err := p.getPr(ctx, opts) if err != nil { return "", fmt.Errorf("getting pull request: %s", err) } return pr.GetHTMLURL(), nil }
248
eks-distro-build-tooling
aws
Go
package prmanager_test import ( "context" "errors" "net/http" "testing" "time" "github.com/golang/mock/gomock" gogithub "github.com/google/go-github/v48/github" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/github" githubMocks "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/github/mocks" prmanager "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/prManager" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/retrier" ) const ( HttpOkStatusCode = 200 ) var baseBranchSha = "940a814c746924db2019139e3de9ca9f2d60c22d" var parentCommitSha = "d060b1b4309627ddc7bc0bc08cbcbe1894690c7c" var testNewCommitSha = "72d34fc14ed813e183cce5f0bda5c71e7f0d058e" var treeRootSha = "f7c2fc2f4f811ab8e7246a7b5ceee40f9f77be0f" var ( testRepoOwner = "TestTesterson" testRepo = "testRepo" testCommitBranchRef = "refs/heads/testCommitBranch" testBaseBranchRef = "refs/heads/main" testCommitAuthor = "Author McTesterson" testCommitAuthorEmail = "[email protected]" testCommitMessage = "testing this out" testPrSubject = "test pr" testPrbranch = "testBranch" testPrDescription = "testing testing 123" testDestFileGitPath = "test.txt" testBaseBranch = "main" testCommitBranch = "testCommitBranch" ) func TestPrManagerCreatePRSuccess(t *testing.T) { ctx := context.Background() pr := newTestPrManager(t) opts := &prmanager.CreatePrOpts{ CommitBranch: testCommitBranch, BaseBranch: testBaseBranch, AuthorName: testCommitAuthor, AuthorEmail: testCommitAuthorEmail, CommitMessage: testCommitMessage, PrSubject: testPrSubject, PrBranch: testPrbranch, PrDescription: testPrDescription, DestFileGitPath: testDestFileGitPath, SourceFileBody: nil, } initialGitTree := &gogithub.Tree{ SHA: &treeRootSha, Entries: nil, Truncated: gogithub.Bool(false), } baseBranchRef := &gogithub.Reference{ Object: &gogithub.GitObject{ SHA: &baseBranchSha, }, Ref: gogithub.String(testCommitBranchRef), } // getRef() pr.gitClient.EXPECT().GetRef(ctx, testRepoOwner, testRepo, testCommitBranchRef).Return(baseBranchRef, nil, nil) // getTree() pr.gitClient.EXPECT().CreateTree(ctx, testRepoOwner, testRepo, baseBranchSha, gomock.Any()).Return(initialGitTree, nil, nil) // pushCommit() pr.repoClient.EXPECT().GetCommit(ctx, testRepoOwner, testRepo, baseBranchSha, nil).Return(getCommitExpectedCommit(), nil, nil) pr.gitClient.EXPECT().CreateCommit(ctx, testRepoOwner, testRepo, gomock.Any()).Return(newCommit(), nil, nil) pr.gitClient.EXPECT().UpdateRef(ctx, testRepoOwner, testRepo, baseBranchRef, false).Return(nil, nil, nil) // createReop() createdPr := &gogithub.PullRequest{} createPrResponse := &gogithub.Response{ Response: &http.Response{ StatusCode: HttpOkStatusCode, }, } pr.prClient.EXPECT().Create(ctx, testRepoOwner, testRepo, gomock.Any()).Return(createdPr, createPrResponse, nil) _, err := pr.prManager.CreatePr(ctx, opts) if err != nil { t.Errorf("PrManager.CreatePr() exepcted no error; error = %s, want nil", err) } } func TestPrManagerCreatePRSuccessAlternatePath(t *testing.T) { ctx := context.Background() pr := newTestPrManager(t) opts := &prmanager.CreatePrOpts{ CommitBranch: testCommitBranch, BaseBranch: testBaseBranch, AuthorName: testCommitAuthor, AuthorEmail: testCommitAuthorEmail, CommitMessage: testCommitMessage, PrSubject: testPrSubject, PrBranch: testPrbranch, PrDescription: testPrDescription, DestFileGitPath: testDestFileGitPath, SourceFileBody: nil, } initialGitTree := &gogithub.Tree{ SHA: &treeRootSha, Entries: nil, Truncated: gogithub.Bool(false), } commitBranchRef := &gogithub.Reference{ Object: &gogithub.GitObject{ SHA: &baseBranchSha, }, Ref: gogithub.String(testBaseBranchRef), } commitBranchPostCommitRef := &gogithub.Reference{ Object: &gogithub.GitObject{ SHA: &baseBranchSha, }, Ref: gogithub.String(testCommitBranchRef), } baseBranchRef := &gogithub.Reference{ Object: &gogithub.GitObject{ SHA: &baseBranchSha, }, Ref: gogithub.String(testCommitBranchRef), } newCommitRef := &gogithub.Reference{ Object: &gogithub.GitObject{ SHA: &testNewCommitSha, }, Ref: gogithub.String(testCommitBranchRef), } newRef := &gogithub.Reference{ Object: &gogithub.GitObject{ SHA: commitBranchPostCommitRef.Object.SHA, }, Ref: gogithub.String(testCommitBranchRef), } // getRef() pr.gitClient.EXPECT().GetRef(ctx, testRepoOwner, testRepo, testCommitBranchRef).Return(baseBranchRef, nil, errors.New("commit not found")) pr.gitClient.EXPECT().GetRef(ctx, testRepoOwner, testRepo, testBaseBranchRef).Return(commitBranchRef, nil, nil) pr.gitClient.EXPECT().CreateRef(ctx, testRepoOwner, testRepo, newRef).Return(commitBranchPostCommitRef, nil, nil) // getTree() pr.gitClient.EXPECT().CreateTree(ctx, testRepoOwner, testRepo, baseBranchSha, gomock.Any()).Return(initialGitTree, nil, nil) // pushCommit() pr.repoClient.EXPECT().GetCommit(ctx, testRepoOwner, testRepo, baseBranchSha, nil).Return(getCommitExpectedCommit(), nil, nil) pr.gitClient.EXPECT().CreateCommit(ctx, testRepoOwner, testRepo, gomock.Any()).Return(newCommit(), nil, nil) pr.gitClient.EXPECT().UpdateRef(ctx, testRepoOwner, testRepo, newCommitRef, false).Return(nil, nil, nil) // createReop() createdPr := &gogithub.PullRequest{} createPrResponse := &gogithub.Response{ Response: &http.Response{ StatusCode: HttpOkStatusCode, }, } pr.prClient.EXPECT().Create(ctx, testRepoOwner, testRepo, gomock.Any()).Return(createdPr, createPrResponse, nil) _, err := pr.prManager.CreatePr(ctx, opts) if err != nil { t.Errorf("PrManager.CreatePr() exepcted no error; error = %s, want nil", err) } } func givenRetrier() *retrier.Retrier { return retrier.NewWithMaxRetries(4, 1) } type testPrManager struct { prManager *prmanager.PrCreator prClient *githubMocks.MockPullRequestClient gitClient *githubMocks.MockGitClient repoClient *githubMocks.MockRepoClient } func newTestPrManager(t *testing.T) testPrManager { mockCtrl := gomock.NewController(t) prClient := githubMocks.NewMockPullRequestClient(mockCtrl) gitClient := githubMocks.NewMockGitClient(mockCtrl) repoClient := githubMocks.NewMockRepoClient(mockCtrl) githubClient := &github.Client{ PullRequests: prClient, Git: gitClient, Repositories: repoClient, } o := &prmanager.Opts{ SourceOwner: testRepoOwner, SourceRepo: testRepo, PrRepo: testRepo, PrRepoOwner: testRepoOwner, } return testPrManager{ prClient: prClient, gitClient: gitClient, repoClient: repoClient, prManager: prmanager.New(givenRetrier(), githubClient, o), } } func getCommitExpectedCommit() *gogithub.RepositoryCommit { commit := &gogithub.Commit{ Author: commitAuthor(), Message: &testCommitMessage, Tree: nil, Parents: []*gogithub.Commit{ { SHA: &baseBranchSha, }, }, } return &gogithub.RepositoryCommit{ SHA: gogithub.String(parentCommitSha), Commit: commit, } } func commitAuthor() *gogithub.CommitAuthor { date := time.Now() return &gogithub.CommitAuthor{ Date: &date, Name: &testCommitAuthor, Email: &testCommitAuthorEmail, } } func newCommit() *gogithub.Commit { return &gogithub.Commit{ Author: commitAuthor(), Message: &testCommitMessage, Tree: nil, SHA: gogithub.String(testNewCommitSha), Parents: []*gogithub.Commit{ { SHA: &baseBranchSha, }, }, } }
266
eks-distro-build-tooling
aws
Go
package repoManager import ( "context" "fmt" "io" "strings" gogithub "github.com/google/go-github/v48/github" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/github" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/logger" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/retrier" ) type RepoContentManager struct { client *github.Client retrier *retrier.Retrier sourceOwner string sourceRepo string } type Opts struct { SourceOwner string SourceRepo string } func New(r *retrier.Retrier, githubClient *github.Client, opts *Opts) *RepoContentManager { return &RepoContentManager{ client: githubClient, sourceOwner: opts.SourceOwner, sourceRepo: opts.SourceRepo, retrier: r, } } type GetFileOpts struct { Owner string Repo string Path string Ref *gogithub.RepositoryContentGetOptions // Can be a SHA, branch, or tag. Optional } func (p *RepoContentManager) GetFile(ctx context.Context, opts *GetFileOpts) (*gogithub.RepositoryContent, error) { var fileContent *gogithub.RepositoryContent var resp *gogithub.Response var err error fileContent, _, resp, err = p.client.Repositories.GetContents(ctx, opts.Owner, opts.Repo, opts.Path, opts.Ref) if resp != nil { if resp.StatusCode == github.SecondaryRateLimitStatusCode { b, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("reading Github response body: %v", err) } if strings.Contains(string(b), github.SecondaryRateLimitResponse) { logger.V(4).Info("rate limited while attempting to get github file") return nil, fmt.Errorf("rate limited while attempting to get github file") } } if resp.StatusCode == github.ResourceGoneStatusCode { _, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("reading Github response body: %v", err) } } } if err != nil { logger.V(4).Error(err, "getting file from Github", "response", resp) return nil, fmt.Errorf("getting file from Github: %v; resp: %v", err, resp) } logger.V(4).Info("get file response", "response", resp.Response.StatusCode) logger.V(1).Info("Github file received", "fileContent URL", fileContent.GetHTMLURL()) return fileContent, nil }
76
eks-distro-build-tooling
aws
Go
package repoManager_test import ( "context" "io" "net/http" "strings" "testing" "github.com/golang/mock/gomock" gogithub "github.com/google/go-github/v48/github" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/github" githubMocks "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/github/mocks" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/repoManager" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/retrier" ) const ( HttpOkStatusCode = 200 rateLimitingGetFileError = "rate limited while attempting to get github file" ) var ( TestRepoOwner = "TestTesterson" TestRepo = "TestRepo" TestFilePath = "test/path/to/file" TestFileContent = "Test content: Hello there" FileName = "File" ) func TestRepoManagerGetFileSuccess(t *testing.T) { ctx := context.Background() rm := newTestRepoManager(t) opts := &repoManager.GetFileOpts{ Owner: TestRepoOwner, Repo: TestRepo, Path: TestFilePath, Ref: nil, } expectedFile := &gogithub.RepositoryContent{ Name: &FileName, Path: &TestFilePath, Content: &TestFileContent, } expectedResponse := &gogithub.Response{ Response: &http.Response{ StatusCode: HttpOkStatusCode, }, } rm.repoClient.EXPECT().GetContents(ctx, TestRepoOwner, TestRepo, TestFilePath, opts.Ref).Return(expectedFile, nil, expectedResponse, nil) _, err := rm.repoManager.GetFile(context.Background(), opts) if err != nil { t.Errorf("RepoManager.GetFile() error = %v, want nil", err) } } func TestRepoManagerGetFileRateLimitedFail(t *testing.T) { ctx := context.Background() rm := newTestRepoManager(t) opts := &repoManager.GetFileOpts{ Owner: TestRepoOwner, Repo: TestRepo, Path: TestFilePath, Ref: nil, } expectedFile := &gogithub.RepositoryContent{ Name: &FileName, Path: &TestFilePath, Content: &TestFileContent, } rm.repoClient.EXPECT().GetContents(ctx, TestRepoOwner, TestRepo, TestFilePath, opts.Ref).Return(expectedFile, nil, rateLimitedResponseBody(), nil) _, err := rm.repoManager.GetFile(context.Background(), opts) if err != nil && !strings.Contains(err.Error(), rateLimitingGetFileError) { t.Errorf("RepoManager.GetFile() rate limiting exepcted error; error = %v, want %s", err, rateLimitingGetFileError) } } func givenRetrier() *retrier.Retrier { return retrier.NewWithMaxRetries(4, 1) } type testRepoManager struct { repoManager *repoManager.RepoContentManager repoClient *githubMocks.MockRepoClient } func newTestRepoManager(t *testing.T) testRepoManager { mockCtrl := gomock.NewController(t) repoClient := githubMocks.NewMockRepoClient(mockCtrl) githubClient := &github.Client{ Repositories: repoClient, } o := &repoManager.Opts{ SourceOwner: TestRepoOwner, SourceRepo: TestRepo, } return testRepoManager{ repoClient: repoClient, repoManager: repoManager.New(givenRetrier(), githubClient, o), } } func rateLimitedResponseBody() *gogithub.Response { rateLimitResponseBody := io.NopCloser(strings.NewReader(github.SecondaryRateLimitResponse)) return &gogithub.Response{ Response: &http.Response{ StatusCode: github.SecondaryRateLimitStatusCode, Body: rateLimitResponseBody, }, } }
115
eks-distro-build-tooling
aws
Go
package retrier import ( "math" "time" "github.com/aws/eks-distro-build-tooling/tools/eksDistroBuildToolingOpsTools/pkg/logger" ) type Retrier struct { retryPolicy RetryPolicy timeout time.Duration backoffFactor *float32 } type ( // RetryPolicy allows to customize the retrying logic. The boolean retry indicates if a new retry // should be performed and the wait duration indicates the wait time before the next retry RetryPolicy func(totalRetries int, err error) (retry bool, wait time.Duration) RetrierOpt func(*Retrier) ) // New creates a new retrier with a global timeout (max time allowed for the whole execution) // The default retry policy is to always retry with no wait time in between retries func New(timeout time.Duration, opts ...RetrierOpt) *Retrier { r := &Retrier{ timeout: timeout, retryPolicy: zeroWaitPolicy, } for _, o := range opts { o(r) } return r } // NewWithMaxRetries creates a new retrier with no global timeout and a max retries policy func NewWithMaxRetries(maxRetries int, backOffPeriod time.Duration) *Retrier { // this value is roughly 292 years, so in practice there is no timeout return New(time.Duration(math.MaxInt64), WithMaxRetries(maxRetries, backOffPeriod)) } // WithMaxRetries sets a retry policy that will retry up to maxRetries times // with a wait time between retries of backOffPeriod func WithMaxRetries(maxRetries int, backOffPeriod time.Duration) RetrierOpt { return func(r *Retrier) { r.retryPolicy = maxRetriesPolicy(maxRetries, backOffPeriod) } } func WithBackoffFactor(factor float32) RetrierOpt { return func(r *Retrier) { r.backoffFactor = &factor } } func WithRetryPolicy(policy RetryPolicy) RetrierOpt { return func(r *Retrier) { r.retryPolicy = policy } } // Retry runs the fn function until it either successful completes (not error), // the set timeout reached or the retry policy aborts the execution func (r *Retrier) Retry(fn func() error) error { start := time.Now() retries := 0 var err error for retry := true; retry; retry = time.Since(start) < r.timeout { err = fn() retries += 1 if err == nil { logger.V(5).Info("Retry execution successful", "retries", retries, "duration", time.Since(start)) return nil } logger.V(5).Info("Error happened during retry", "error", err, "retries", retries) retry, wait := r.retryPolicy(retries, err) if !retry { logger.V(5).Info("Execution aborted by retry policy") return err } if r.backoffFactor != nil { wait = wait * time.Duration(*r.backoffFactor*float32(retries)) } logger.V(5).Info("Sleeping before next retry", "time", wait) time.Sleep(wait) } logger.V(5).Info("Timeout reached. Returning error", "retries", retries, "duration", time.Since(start), "error", err) return err } // Retry runs fn with a MaxRetriesPolicy func Retry(maxRetries int, backOffPeriod time.Duration, fn func() error) error { r := NewWithMaxRetries(maxRetries, backOffPeriod) return r.Retry(fn) } func zeroWaitPolicy(_ int, _ error) (retry bool, wait time.Duration) { return true, 0 } func maxRetriesPolicy(maxRetries int, backOffPeriod time.Duration) RetryPolicy { return func(totalRetries int, _ error) (retry bool, wait time.Duration) { return totalRetries < maxRetries, backOffPeriod } }
110
eks-distro-build-tooling
aws
Go
package version var gitVersion string type Info struct { GitVersion string } func Get() Info { return Info{ GitVersion: gitVersion, } }
13
eks-distro-build-tooling
aws
Go
package cmd import ( "github.com/spf13/cobra" ) var cleanCmd = &cobra.Command{ Use: "clean", Short: "", Long: "", } func init() { rootCmd.AddCommand(cleanCmd) }
16
eks-distro-build-tooling
aws
Go
package cmd import ( "github.com/spf13/cobra" ) var cleandocsCommand = &cobra.Command{ Use: "docs", Short: "", Long: "", } func init() { cleanCmd.AddCommand(cleandocsCmd) }
16
eks-distro-build-tooling
aws
Go
package cmd import ( "github.com/spf13/cobra" ) var cleanInstallCmd = &cobra.Command{ Use: "install", Short: "", Long: "", } func init() { cleanCmd.AddCommand(cleanInstallCmd) }
16
eks-distro-build-tooling
aws
Go
1
eks-distro-build-tooling
aws
Go
package cmd import ( "github.com/spf13/cobra" ) var cleanYumCmd = &cobra.Command{ Use: "yum", Short: "", Long: "", } func init() { cleanCmd.AddCommand(cleanYumCmd) }
16
eks-distro-build-tooling
aws
Go
1
eks-distro-build-tooling
aws
Go
1
eks-distro-build-tooling
aws
Go
1
eks-distro-build-tooling
aws
Go
package cmd import ( "github.com/spf13/cobra" ) var installCmd = &cobra.Command{ Use: "install", Short: "", Long: "", } func init() { rootCmd.AddCommand(installCmd) }
16
eks-distro-build-tooling
aws
Go
package cmd import ( "github.com/spf13/cobra" ) var installBinaryCmd = &cobra.Command{ Use: "binary", Short: "", Long: "", } func init() { installCmd.AddCommand(installBinaryCmd) }
16
eks-distro-build-tooling
aws
Go
package cmd import ( "github.com/spf13/cobra" ) var installDepsForBinaryCmd = &cobra.Command{ Use: "deps", Short: "", Long: "", } func init() { installCmd.AddCommand(installDepsForBinaryCmd) }
16
eks-distro-build-tooling
aws
Go
package cmd import ( "github.com/spf13/cobra" ) var installRpmCmd = &cobra.Command{ Use: "rpm", Short: "", Long: "", } func init() { installCmd.AddCommand(installRpmCmd) }
16
eks-distro-build-tooling
aws
Go
package main import ( "os" "os/signal" "syscall" "github.com/aws/eks-distro-build-tooling/slim-jim/cmd/slim-jim/cmd" ) func main() { sigChannel := make(chan os.Signal, 1) signal.Notify(sigChannel, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigChannel os.Exit(-1) }() if cmd.Execute() == nil { os.Exit(0) } os.Exit(-1) }
23
eks-distro-build-tooling
aws
Go
package cmd import ( "github.com/spf13/cobra" ) var removeCmd = &cobra.Command{ Use: "remove", Short: "", Long: "", } func init() { rootCmd.AddCommand(removeCmd) }
16
eks-distro-build-tooling
aws
Go
package cmd import ( "github.com/spf13/cobra" ) var removePackageCmd = &cobra.Command{ Use: "package", Short: "", Long: "", } func init() { removeCmd.AddCommand(removePackageCmd) }
16
eks-distro-build-tooling
aws
Go
package cmd import ( "context" "fmt" "log" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/aws/eks-distro-build-tooling/tools/minimalImageBuildTool/pkg/logger" ) var rootCmd = &cobra.Command{ Use: "minimal-image-build", Short: "Minimial Image CLI", Long: `Use minimal-image-build to create your own minimal image based off Amazon Linux`, PersistentPreRun: rootPersistentPreRun, } func init() { rootCmd.PersistentFlags().IntP("verbosity", "v", 0, "Set the log level verbosity") if err := viper.BindPFlags(rootCmd.PersistentFlags()); err != nil { log.Fatalf("failed to bind flags for root: %v", err) } } func rootPersistentPreRun(cmd *cobra.Command, args []string) { if err := initLogger(); err != nil { log.Fatal(err) } } func initLogger() error { if err := logger.InitZap(viper.GetInt("verbosity")); err != nil { return fmt.Errorf("failed init zap logger in root command: %v", err) } return nil } func Execute() error { return rootCmd.ExecuteContext(context.Background()) }
45
eks-distro-build-tooling
aws
Go
package cmd import ( "github.com/spf13/cobra" ) var validateCmd = &cobra.Command{ Use: "validate", Short: "Validate Libraries and Symlinks", Long: "", } func init() { rootCmd.AddCommand(validateCmd) }
16
eks-distro-build-tooling
aws
Go
package cmd import ( "github.com/spf13/cobra" ) var validateLibrariesCmd = &cobra.Command{ Use: "libraries", Short: "Validate all executables and libraries have all dependencies", Long: "Validate all executables and libraries have all dependencies", } func init() { validateCmd.AddCommand(validateLibrariesCmd) }
16
eks-distro-build-tooling
aws
Go
package cmd import ( "github.com/spf13/cobra" ) var validateSymlinksCmd = &cobra.Command{ Use: "symlinks", Short: "Validate all symlinks", Long: "Validate all symlinks", } func init() { validateCmd.AddCommand(validateSymlinksCmd) }
16
eks-distro-build-tooling
aws
Go
1
eks-distro-build-tooling
aws
Go
1