Fix some golint errors for packages in `pkg/kubectl`

- Fix some golint errors for `pkg/kubectl`
- Fix a golint error for `pkg/kubectl/apps`
- Fix all golint errors for `pkg/kubectl/cmd`
- Fix some golint errors for `pkg/kubectl/generate/versioned`
- Fix a golint error for `pkg/kubectl/generate`
- Fix some golint errors for `pkg/kubectl/metricsutil`
- Fix all golint errors for `pkg/kubectl/util`
- Fix all golint errors for `pkg/kubectl/util/slice`
pull/58/head
Yang Li 2018-10-30 17:48:27 +08:00
parent fdc653ebb9
commit 3d0c961d57
25 changed files with 83 additions and 79 deletions

View File

@ -141,7 +141,6 @@ pkg/kubeapiserver/authorizer/modes
pkg/kubeapiserver/options pkg/kubeapiserver/options
pkg/kubectl pkg/kubectl
pkg/kubectl/apps pkg/kubectl/apps
pkg/kubectl/cmd
pkg/kubectl/cmd/annotate pkg/kubectl/cmd/annotate
pkg/kubectl/cmd/apiresources pkg/kubectl/cmd/apiresources
pkg/kubectl/cmd/apply pkg/kubectl/cmd/apply
@ -189,8 +188,6 @@ pkg/kubectl/cmd/wait
pkg/kubectl/generate pkg/kubectl/generate
pkg/kubectl/generate/versioned pkg/kubectl/generate/versioned
pkg/kubectl/metricsutil pkg/kubectl/metricsutil
pkg/kubectl/util
pkg/kubectl/util/slice
pkg/kubectl/util/templates pkg/kubectl/util/templates
pkg/kubelet pkg/kubelet
pkg/kubelet/apis pkg/kubelet/apis

View File

@ -135,7 +135,8 @@ func CreateApplyAnnotation(obj runtime.Object, codec runtime.Encoder) error {
return setOriginalConfiguration(obj, modified) return setOriginalConfiguration(obj, modified)
} }
// Create the annotation used by kubectl apply only when createAnnotation is true // CreateOrUpdateAnnotation creates the annotation used by
// kubectl apply only when createAnnotation is true
// Otherwise, only update the annotation when it already exists // Otherwise, only update the annotation when it already exists
func CreateOrUpdateAnnotation(createAnnotation bool, obj runtime.Object, codec runtime.Encoder) error { func CreateOrUpdateAnnotation(createAnnotation bool, obj runtime.Object, codec runtime.Encoder) error {
if createAnnotation { if createAnnotation {

View File

@ -173,7 +173,7 @@ type TestKindVisitor struct {
var _ apps.KindVisitor = &TestKindVisitor{} var _ apps.KindVisitor = &TestKindVisitor{}
func (t *TestKindVisitor) Visit(kind apps.GroupKindElement) { t.visits[kind.Kind] += 1 } func (t *TestKindVisitor) Visit(kind apps.GroupKindElement) { t.visits[kind.Kind]++ }
func (t *TestKindVisitor) VisitDaemonSet(kind apps.GroupKindElement) { t.Visit(kind) } func (t *TestKindVisitor) VisitDaemonSet(kind apps.GroupKindElement) { t.Visit(kind) }
func (t *TestKindVisitor) VisitDeployment(kind apps.GroupKindElement) { t.Visit(kind) } func (t *TestKindVisitor) VisitDeployment(kind apps.GroupKindElement) { t.Visit(kind) }

View File

@ -77,7 +77,8 @@ func NewAPIResourceOptions(ioStreams genericclioptions.IOStreams) *ApiResourcesO
} }
} }
func NewCmdApiResources(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command { // NewCmdAPIResources creates the `api-resources` command
func NewCmdAPIResources(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
o := NewAPIResourceOptions(ioStreams) o := NewAPIResourceOptions(ioStreams)
cmd := &cobra.Command{ cmd := &cobra.Command{

View File

@ -48,7 +48,8 @@ func NewApiVersionsOptions(ioStreams genericclioptions.IOStreams) *ApiVersionsOp
} }
} }
func NewCmdApiVersions(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command { // NewCmdAPIVersions creates the `api-versions` command
func NewCmdAPIVersions(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
o := NewApiVersionsOptions(ioStreams) o := NewApiVersionsOptions(ioStreams)
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "api-versions", Use: "api-versions",

View File

@ -159,7 +159,7 @@ func (o *AutoscaleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args
CPUPercent: o.CpuPercent, CPUPercent: o.CpuPercent,
ScaleRefName: name, ScaleRefName: name,
ScaleRefKind: mapping.GroupVersionKind.Kind, ScaleRefKind: mapping.GroupVersionKind.Kind,
ScaleRefApiVersion: mapping.GroupVersionKind.GroupVersion().String(), ScaleRefAPIVersion: mapping.GroupVersionKind.GroupVersion().String(),
}, nil }, nil
default: default:
return nil, cmdutil.UsageErrorf(cmd, "Generator %s not supported. ", o.Generator) return nil, cmdutil.UsageErrorf(cmd, "Generator %s not supported. ", o.Generator)

View File

@ -284,7 +284,7 @@ __custom_func() {
) )
var ( var (
bash_completion_flags = map[string]string{ bashCompletionFlags = map[string]string{
"namespace": "__kubectl_get_resource_namespace", "namespace": "__kubectl_get_resource_namespace",
"context": "__kubectl_config_get_contexts", "context": "__kubectl_config_get_contexts",
"cluster": "__kubectl_config_get_clusters", "cluster": "__kubectl_config_get_clusters",
@ -292,10 +292,12 @@ var (
} }
) )
// NewDefaultKubectlCommand creates the `kubectl` command with default arguments
func NewDefaultKubectlCommand() *cobra.Command { func NewDefaultKubectlCommand() *cobra.Command {
return NewDefaultKubectlCommandWithArgs(&defaultPluginHandler{}, os.Args, os.Stdin, os.Stdout, os.Stderr) return NewDefaultKubectlCommandWithArgs(&defaultPluginHandler{}, os.Args, os.Stdin, os.Stdout, os.Stderr)
} }
// NewDefaultKubectlCommandWithArgs creates the `kubectl` command with arguments
func NewDefaultKubectlCommandWithArgs(pluginHandler PluginHandler, args []string, in io.Reader, out, errout io.Writer) *cobra.Command { func NewDefaultKubectlCommandWithArgs(pluginHandler PluginHandler, args []string, in io.Reader, out, errout io.Writer) *cobra.Command {
cmd := NewKubectlCommand(in, out, errout) cmd := NewKubectlCommand(in, out, errout)
@ -528,7 +530,7 @@ func NewKubectlCommand(in io.Reader, out, err io.Writer) *cobra.Command {
templates.ActsAsRootCommand(cmds, filters, groups...) templates.ActsAsRootCommand(cmds, filters, groups...)
for name, completion := range bash_completion_flags { for name, completion := range bashCompletionFlags {
if cmds.Flag(name) != nil { if cmds.Flag(name) != nil {
if cmds.Flag(name).Annotations == nil { if cmds.Flag(name).Annotations == nil {
cmds.Flag(name).Annotations = map[string][]string{} cmds.Flag(name).Annotations = map[string][]string{}
@ -544,8 +546,8 @@ func NewKubectlCommand(in io.Reader, out, err io.Writer) *cobra.Command {
cmds.AddCommand(cmdconfig.NewCmdConfig(f, clientcmd.NewDefaultPathOptions(), ioStreams)) cmds.AddCommand(cmdconfig.NewCmdConfig(f, clientcmd.NewDefaultPathOptions(), ioStreams))
cmds.AddCommand(plugin.NewCmdPlugin(f, ioStreams)) cmds.AddCommand(plugin.NewCmdPlugin(f, ioStreams))
cmds.AddCommand(version.NewCmdVersion(f, ioStreams)) cmds.AddCommand(version.NewCmdVersion(f, ioStreams))
cmds.AddCommand(apiresources.NewCmdApiVersions(f, ioStreams)) cmds.AddCommand(apiresources.NewCmdAPIVersions(f, ioStreams))
cmds.AddCommand(apiresources.NewCmdApiResources(f, ioStreams)) cmds.AddCommand(apiresources.NewCmdAPIResources(f, ioStreams))
cmds.AddCommand(options.NewCmdOptions(ioStreams.Out)) cmds.AddCommand(options.NewCmdOptions(ioStreams.Out))
return cmds return cmds

View File

@ -102,7 +102,7 @@ func AnnotateFlags(cmd *cobra.Command, generators map[string]Generator) {
} }
} }
// EnsureFlagsValid ensures that no invalid flags are being used against a // EnsureFlagsValid ensures that no invalid flags are being used against a
func EnsureFlagsValid(cmd *cobra.Command, generators map[string]Generator, generatorInUse string) error { func EnsureFlagsValid(cmd *cobra.Command, generators map[string]Generator, generatorInUse string) error {
AnnotateFlags(cmd, generators) AnnotateFlags(cmd, generators)

View File

@ -25,12 +25,12 @@ import (
"k8s.io/kubernetes/pkg/kubectl/generate" "k8s.io/kubernetes/pkg/kubectl/generate"
) )
// HorizontalPodAutoscalerV1Generator supports stable generation of a horizontal pod autoscaler. // HorizontalPodAutoscalerGeneratorV1 supports stable generation of a horizontal pod autoscaler.
type HorizontalPodAutoscalerGeneratorV1 struct { type HorizontalPodAutoscalerGeneratorV1 struct {
Name string Name string
ScaleRefKind string ScaleRefKind string
ScaleRefName string ScaleRefName string
ScaleRefApiVersion string ScaleRefAPIVersion string
MinReplicas int32 MinReplicas int32
MaxReplicas int32 MaxReplicas int32
CPUPercent int32 CPUPercent int32
@ -53,7 +53,7 @@ func (s *HorizontalPodAutoscalerGeneratorV1) StructuredGenerate() (runtime.Objec
ScaleTargetRef: autoscalingv1.CrossVersionObjectReference{ ScaleTargetRef: autoscalingv1.CrossVersionObjectReference{
Kind: s.ScaleRefKind, Kind: s.ScaleRefKind,
Name: s.ScaleRefName, Name: s.ScaleRefName,
APIVersion: s.ScaleRefApiVersion, APIVersion: s.ScaleRefAPIVersion,
}, },
MaxReplicas: s.MaxReplicas, MaxReplicas: s.MaxReplicas,
}, },

View File

@ -31,7 +31,7 @@ func TestHPAGenerate(t *testing.T) {
HPAName string HPAName string
scaleRefKind string scaleRefKind string
scaleRefName string scaleRefName string
scaleRefApiVersion string scaleRefAPIVersion string
minReplicas int32 minReplicas int32
maxReplicas int32 maxReplicas int32
CPUPercent int32 CPUPercent int32
@ -46,7 +46,7 @@ func TestHPAGenerate(t *testing.T) {
CPUPercent: 80, CPUPercent: 80,
scaleRefKind: "kind", scaleRefKind: "kind",
scaleRefName: "name", scaleRefName: "name",
scaleRefApiVersion: "apiVersion", scaleRefAPIVersion: "apiVersion",
expected: &autoscalingv1.HorizontalPodAutoscaler{ expected: &autoscalingv1.HorizontalPodAutoscaler{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
Name: "foo", Name: "foo",
@ -68,7 +68,7 @@ func TestHPAGenerate(t *testing.T) {
name: "'name' is a required parameter", name: "'name' is a required parameter",
scaleRefKind: "kind", scaleRefKind: "kind",
scaleRefName: "name", scaleRefName: "name",
scaleRefApiVersion: "apiVersion", scaleRefAPIVersion: "apiVersion",
expectErr: true, expectErr: true,
}, },
{ {
@ -76,7 +76,7 @@ func TestHPAGenerate(t *testing.T) {
HPAName: "foo", HPAName: "foo",
scaleRefKind: "kind", scaleRefKind: "kind",
scaleRefName: "name", scaleRefName: "name",
scaleRefApiVersion: "apiVersion", scaleRefAPIVersion: "apiVersion",
expectErr: true, expectErr: true,
}, },
{ {
@ -86,7 +86,7 @@ func TestHPAGenerate(t *testing.T) {
maxReplicas: 1, maxReplicas: 1,
scaleRefKind: "kind", scaleRefKind: "kind",
scaleRefName: "name", scaleRefName: "name",
scaleRefApiVersion: "apiVersion", scaleRefAPIVersion: "apiVersion",
expectErr: true, expectErr: true,
}, },
{ {
@ -96,7 +96,7 @@ func TestHPAGenerate(t *testing.T) {
maxReplicas: -10, maxReplicas: -10,
scaleRefKind: "kind", scaleRefKind: "kind",
scaleRefName: "name", scaleRefName: "name",
scaleRefApiVersion: "apiVersion", scaleRefAPIVersion: "apiVersion",
expectErr: true, expectErr: true,
}, },
} }
@ -107,7 +107,7 @@ func TestHPAGenerate(t *testing.T) {
Name: tt.HPAName, Name: tt.HPAName,
ScaleRefKind: tt.scaleRefKind, ScaleRefKind: tt.scaleRefKind,
ScaleRefName: tt.scaleRefName, ScaleRefName: tt.scaleRefName,
ScaleRefApiVersion: tt.scaleRefApiVersion, ScaleRefAPIVersion: tt.scaleRefAPIVersion,
MinReplicas: tt.minReplicas, MinReplicas: tt.minReplicas,
MaxReplicas: tt.maxReplicas, MaxReplicas: tt.maxReplicas,
CPUPercent: tt.CPUPercent, CPUPercent: tt.CPUPercent,

View File

@ -29,7 +29,7 @@ import (
"k8s.io/kubernetes/pkg/kubectl/generate" "k8s.io/kubernetes/pkg/kubectl/generate"
) )
// BaseDeploymentGenerator: implement the common functionality of // BaseDeploymentGenerator implements the common functionality of
// DeploymentBasicGeneratorV1, DeploymentBasicAppsGeneratorV1Beta1 and DeploymentBasicAppsGeneratorV1. To reduce // DeploymentBasicGeneratorV1, DeploymentBasicAppsGeneratorV1Beta1 and DeploymentBasicAppsGeneratorV1. To reduce
// confusion, it's best to keep this struct in the same file as those // confusion, it's best to keep this struct in the same file as those
// generators. // generators.

View File

@ -205,7 +205,7 @@ func handleFromFileSources(secret *v1.Secret, fileSources []string) error {
} }
if info.IsDir() { if info.IsDir() {
if strings.Contains(fileSource, "=") { if strings.Contains(fileSource, "=") {
return fmt.Errorf("cannot give a key name for a directory path.") return fmt.Errorf("cannot give a key name for a directory path")
} }
fileList, err := ioutil.ReadDir(filePath) fileList, err := ioutil.ReadDir(filePath)
if err != nil { if err != nil {
@ -265,7 +265,7 @@ func addKeyFromLiteralToSecret(secret *v1.Secret, keyName string, data []byte) e
} }
if _, entryExists := secret.Data[keyName]; entryExists { if _, entryExists := secret.Data[keyName]; entryExists {
return fmt.Errorf("cannot add key %s, another key by that name already exists: %v.", keyName, secret.Data) return fmt.Errorf("cannot add key %s, another key by that name already exists: %v", keyName, secret.Data)
} }
secret.Data[keyName] = data secret.Data[keyName] = data
return nil return nil

View File

@ -97,11 +97,11 @@ func (s SecretForDockerRegistryGeneratorV1) StructuredGenerate() (runtime.Object
} }
} }
if len(s.FileSources) == 0 { if len(s.FileSources) == 0 {
dockercfgJsonContent, err := handleDockerCfgJsonContent(s.Username, s.Password, s.Email, s.Server) dockercfgJSONContent, err := handleDockerCfgJSONContent(s.Username, s.Password, s.Email, s.Server)
if err != nil { if err != nil {
return nil, err return nil, err
} }
secret.Data[v1.DockerConfigJsonKey] = dockercfgJsonContent secret.Data[v1.DockerConfigJsonKey] = dockercfgJSONContent
} }
if s.AppendHash { if s.AppendHash {
h, err := hash.SecretHash(secret) h, err := hash.SecretHash(secret)
@ -146,24 +146,24 @@ func (s SecretForDockerRegistryGeneratorV1) validate() error {
return nil return nil
} }
// handleDockerCfgJsonContent serializes a ~/.docker/config.json file // handleDockerCfgJSONContent serializes a ~/.docker/config.json file
func handleDockerCfgJsonContent(username, password, email, server string) ([]byte, error) { func handleDockerCfgJSONContent(username, password, email, server string) ([]byte, error) {
dockercfgAuth := DockerConfigEntry{ dockercfgAuth := DockerConfigEntry{
Username: username, Username: username,
Password: password, Password: password,
Email: email, Email: email,
} }
dockerCfgJson := DockerConfigJson{ dockerCfgJSON := DockerConfigJSON{
Auths: map[string]DockerConfigEntry{server: dockercfgAuth}, Auths: map[string]DockerConfigEntry{server: dockercfgAuth},
} }
return json.Marshal(dockerCfgJson) return json.Marshal(dockerCfgJSON)
} }
// DockerConfigJson represents a local docker auth config file // DockerConfigJSON represents a local docker auth config file
// for pulling images. // for pulling images.
type DockerConfigJson struct { type DockerConfigJSON struct {
Auths DockerConfig `json:"auths"` Auths DockerConfig `json:"auths"`
// +optional // +optional
HttpHeaders map[string]string `json:"HttpHeaders,omitempty"` HttpHeaders map[string]string `json:"HttpHeaders,omitempty"`

View File

@ -26,11 +26,11 @@ import (
func TestSecretForDockerRegistryGenerate(t *testing.T) { func TestSecretForDockerRegistryGenerate(t *testing.T) {
username, password, email, server := "test-user", "test-password", "test-user@example.org", "https://index.docker.io/v1/" username, password, email, server := "test-user", "test-password", "test-user@example.org", "https://index.docker.io/v1/"
secretData, err := handleDockerCfgJsonContent(username, password, email, server) secretData, err := handleDockerCfgJSONContent(username, password, email, server)
if err != nil { if err != nil {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
} }
secretDataNoEmail, err := handleDockerCfgJsonContent(username, password, "", server) secretDataNoEmail, err := handleDockerCfgJSONContent(username, password, "", server)
if err != nil { if err != nil {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
} }

View File

@ -88,7 +88,7 @@ func generateService(genericParams map[string]interface{}) (runtime.Object, erro
} }
selectorString, found := params["selector"] selectorString, found := params["selector"]
if !found || len(selectorString) == 0 { if !found || len(selectorString) == 0 {
return nil, fmt.Errorf("'selector' is a required parameter.") return nil, fmt.Errorf("'selector' is a required parameter")
} }
selector, err := generate.ParseLabels(selectorString) selector, err := generate.ParseLabels(selectorString)
if err != nil { if err != nil {
@ -108,7 +108,7 @@ func generateService(genericParams map[string]interface{}) (runtime.Object, erro
if !found || len(name) == 0 { if !found || len(name) == 0 {
name, found = params["default-name"] name, found = params["default-name"]
if !found || len(name) == 0 { if !found || len(name) == 0 {
return nil, fmt.Errorf("'name' is a required parameter.") return nil, fmt.Errorf("'name' is a required parameter")
} }
} }
@ -136,7 +136,7 @@ func generateService(genericParams map[string]interface{}) (runtime.Object, erro
if portString, found = params["ports"]; !found { if portString, found = params["ports"]; !found {
portString, found = params["port"] portString, found = params["port"]
if !found && !isHeadlessService { if !found && !isHeadlessService {
return nil, fmt.Errorf("'ports' or 'port' is a required parameter.") return nil, fmt.Errorf("'ports' or 'port' is a required parameter")
} }
} }

View File

@ -64,7 +64,7 @@ func NewHeapsterMetricsClient(svcClient corev1client.ServicesGetter, namespace,
} }
} }
func podMetricsUrl(namespace string, name string) (string, error) { func podMetricsURL(namespace string, name string) (string, error) {
if namespace == metav1.NamespaceAll { if namespace == metav1.NamespaceAll {
return fmt.Sprintf("%s/pods", metricsRoot), nil return fmt.Sprintf("%s/pods", metricsRoot), nil
} }
@ -83,7 +83,7 @@ func podMetricsUrl(namespace string, name string) (string, error) {
return fmt.Sprintf("%s/namespaces/%s/pods/%s", metricsRoot, namespace, name), nil return fmt.Sprintf("%s/namespaces/%s/pods/%s", metricsRoot, namespace, name), nil
} }
func nodeMetricsUrl(name string) (string, error) { func nodeMetricsURL(name string) (string, error) {
if len(name) > 0 { if len(name) > 0 {
errs := validation.NameIsDNSSubdomain(name, false) errs := validation.NameIsDNSSubdomain(name, false)
if len(errs) > 0 { if len(errs) > 0 {
@ -96,7 +96,7 @@ func nodeMetricsUrl(name string) (string, error) {
func (cli *HeapsterMetricsClient) GetNodeMetrics(nodeName string, selector string) (*metricsapi.NodeMetricsList, error) { func (cli *HeapsterMetricsClient) GetNodeMetrics(nodeName string, selector string) (*metricsapi.NodeMetricsList, error) {
params := map[string]string{"labelSelector": selector} params := map[string]string{"labelSelector": selector}
path, err := nodeMetricsUrl(nodeName) path, err := nodeMetricsURL(nodeName)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -130,7 +130,7 @@ func (cli *HeapsterMetricsClient) GetPodMetrics(namespace string, podName string
if allNamespaces { if allNamespaces {
namespace = metav1.NamespaceAll namespace = metav1.NamespaceAll
} }
path, err := podMetricsUrl(namespace, podName) path, err := podMetricsURL(namespace, podName)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -54,7 +54,7 @@ func valOrZero(val *int32) int32 {
const ( const (
kubectlAnnotationPrefix = "kubectl.kubernetes.io/" kubectlAnnotationPrefix = "kubectl.kubernetes.io/"
sourceIdAnnotation = kubectlAnnotationPrefix + "update-source-id" sourceIDAnnotation = kubectlAnnotationPrefix + "update-source-id"
desiredReplicasAnnotation = kubectlAnnotationPrefix + "desired-replicas" desiredReplicasAnnotation = kubectlAnnotationPrefix + "desired-replicas"
originalReplicasAnnotation = kubectlAnnotationPrefix + "original-replicas" originalReplicasAnnotation = kubectlAnnotationPrefix + "original-replicas"
nextControllerAnnotation = kubectlAnnotationPrefix + "next-controller-id" nextControllerAnnotation = kubectlAnnotationPrefix + "next-controller-id"
@ -135,7 +135,7 @@ type RollingUpdater struct {
scaleAndWait func(rc *corev1.ReplicationController, retry *RetryParams, wait *RetryParams) (*corev1.ReplicationController, error) scaleAndWait func(rc *corev1.ReplicationController, retry *RetryParams, wait *RetryParams) (*corev1.ReplicationController, error)
//getOrCreateTargetController gets and validates an existing controller or //getOrCreateTargetController gets and validates an existing controller or
//makes a new one. //makes a new one.
getOrCreateTargetController func(controller *corev1.ReplicationController, sourceId string) (*corev1.ReplicationController, bool, error) getOrCreateTargetController func(controller *corev1.ReplicationController, sourceID string) (*corev1.ReplicationController, bool, error)
// cleanup performs post deployment cleanup tasks for newRc and oldRc. // cleanup performs post deployment cleanup tasks for newRc and oldRc.
cleanup func(oldRc, newRc *corev1.ReplicationController, config *RollingUpdaterConfig) error cleanup func(oldRc, newRc *corev1.ReplicationController, config *RollingUpdaterConfig) error
// getReadyPods returns the amount of old and new ready pods. // getReadyPods returns the amount of old and new ready pods.
@ -188,8 +188,8 @@ func (r *RollingUpdater) Update(config *RollingUpdaterConfig) error {
// Find an existing controller (for continuing an interrupted update) or // Find an existing controller (for continuing an interrupted update) or
// create a new one if necessary. // create a new one if necessary.
sourceId := fmt.Sprintf("%s:%s", oldRc.Name, oldRc.UID) sourceID := fmt.Sprintf("%s:%s", oldRc.Name, oldRc.UID)
newRc, existed, err := r.getOrCreateTargetController(config.NewRc, sourceId) newRc, existed, err := r.getOrCreateTargetController(config.NewRc, sourceID)
if err != nil { if err != nil {
return err return err
} }
@ -458,14 +458,14 @@ func (r *RollingUpdater) readyPods(oldRc, newRc *corev1.ReplicationController, m
} }
// getOrCreateTargetControllerWithClient looks for an existing controller with // getOrCreateTargetControllerWithClient looks for an existing controller with
// sourceId. If found, the existing controller is returned with true // sourceID. If found, the existing controller is returned with true
// indicating that the controller already exists. If the controller isn't // indicating that the controller already exists. If the controller isn't
// found, a new one is created and returned along with false indicating the // found, a new one is created and returned along with false indicating the
// controller was created. // controller was created.
// //
// Existing controllers are validated to ensure their sourceIdAnnotation // Existing controllers are validated to ensure their sourceIDAnnotation
// matches sourceId; if there's a mismatch, an error is returned. // matches sourceID; if there's a mismatch, an error is returned.
func (r *RollingUpdater) getOrCreateTargetControllerWithClient(controller *corev1.ReplicationController, sourceId string) (*corev1.ReplicationController, bool, error) { func (r *RollingUpdater) getOrCreateTargetControllerWithClient(controller *corev1.ReplicationController, sourceID string) (*corev1.ReplicationController, bool, error) {
existingRc, err := r.existingController(controller) existingRc, err := r.existingController(controller)
if err != nil { if err != nil {
if !errors.IsNotFound(err) { if !errors.IsNotFound(err) {
@ -474,24 +474,24 @@ func (r *RollingUpdater) getOrCreateTargetControllerWithClient(controller *corev
return nil, false, err return nil, false, err
} }
if valOrZero(controller.Spec.Replicas) <= 0 { if valOrZero(controller.Spec.Replicas) <= 0 {
return nil, false, fmt.Errorf("Invalid controller spec for %s; required: > 0 replicas, actual: %d\n", controller.Name, valOrZero(controller.Spec.Replicas)) return nil, false, fmt.Errorf("Invalid controller spec for %s; required: > 0 replicas, actual: %d", controller.Name, valOrZero(controller.Spec.Replicas))
} }
// The controller wasn't found, so create it. // The controller wasn't found, so create it.
if controller.Annotations == nil { if controller.Annotations == nil {
controller.Annotations = map[string]string{} controller.Annotations = map[string]string{}
} }
controller.Annotations[desiredReplicasAnnotation] = fmt.Sprintf("%d", valOrZero(controller.Spec.Replicas)) controller.Annotations[desiredReplicasAnnotation] = fmt.Sprintf("%d", valOrZero(controller.Spec.Replicas))
controller.Annotations[sourceIdAnnotation] = sourceId controller.Annotations[sourceIDAnnotation] = sourceID
controller.Spec.Replicas = newInt32Ptr(0) controller.Spec.Replicas = newInt32Ptr(0)
newRc, err := r.rcClient.ReplicationControllers(r.ns).Create(controller) newRc, err := r.rcClient.ReplicationControllers(r.ns).Create(controller)
return newRc, false, err return newRc, false, err
} }
// Validate and use the existing controller. // Validate and use the existing controller.
annotations := existingRc.Annotations annotations := existingRc.Annotations
source := annotations[sourceIdAnnotation] source := annotations[sourceIDAnnotation]
_, ok := annotations[desiredReplicasAnnotation] _, ok := annotations[desiredReplicasAnnotation]
if source != sourceId || !ok { if source != sourceID || !ok {
return nil, false, fmt.Errorf("Missing/unexpected annotations for controller %s, expected %s : %s", controller.Name, sourceId, annotations) return nil, false, fmt.Errorf("Missing/unexpected annotations for controller %s, expected %s : %s", controller.Name, sourceID, annotations)
} }
return existingRc, true, nil return existingRc, true, nil
} }
@ -517,7 +517,7 @@ func (r *RollingUpdater) cleanupWithClients(oldRc, newRc *corev1.ReplicationCont
return err return err
} }
applyUpdate := func(rc *corev1.ReplicationController) { applyUpdate := func(rc *corev1.ReplicationController) {
delete(rc.Annotations, sourceIdAnnotation) delete(rc.Annotations, sourceIDAnnotation)
delete(rc.Annotations, desiredReplicasAnnotation) delete(rc.Annotations, desiredReplicasAnnotation)
} }
if newRc, err = updateRcWithRetries(r.rcClient, r.ns, newRc, applyUpdate); err != nil { if newRc, err = updateRcWithRetries(r.rcClient, r.ns, newRc, applyUpdate); err != nil {
@ -662,7 +662,7 @@ func AbortRollingUpdate(c *RollingUpdaterConfig) error {
if c.NewRc.Annotations == nil { if c.NewRc.Annotations == nil {
c.NewRc.Annotations = map[string]string{} c.NewRc.Annotations = map[string]string{}
} }
c.NewRc.Annotations[sourceIdAnnotation] = fmt.Sprintf("%s:%s", c.OldRc.Name, c.OldRc.UID) c.NewRc.Annotations[sourceIDAnnotation] = fmt.Sprintf("%s:%s", c.OldRc.Name, c.OldRc.UID)
// Use the original value since the replica count change from old to new // Use the original value since the replica count change from old to new
// could be asymmetric. If we don't know the original count, we can't safely // could be asymmetric. If we don't know the original count, we can't safely
@ -841,7 +841,7 @@ func FindSourceController(r corev1client.ReplicationControllersGetter, namespace
} }
for ix := range list.Items { for ix := range list.Items {
rc := &list.Items[ix] rc := &list.Items[ix]
if rc.Annotations != nil && strings.HasPrefix(rc.Annotations[sourceIdAnnotation], name) { if rc.Annotations != nil && strings.HasPrefix(rc.Annotations[sourceIDAnnotation], name) {
return rc, nil return rc, nil
} }
} }

View File

@ -86,7 +86,7 @@ func newRc(replicas int, desired int) *corev1.ReplicationController {
Name: "foo-v2", Name: "foo-v2",
Annotations: map[string]string{ Annotations: map[string]string{
desiredReplicasAnnotation: fmt.Sprintf("%d", desired), desiredReplicasAnnotation: fmt.Sprintf("%d", desired),
sourceIdAnnotation: "foo-v1:7764ae47-9092-11e4-8393-42010af018ff", sourceIDAnnotation: "foo-v1:7764ae47-9092-11e4-8393-42010af018ff",
}, },
} }
return rc return rc
@ -812,7 +812,7 @@ Scaling foo-v2 up to 2
rc.Status.Replicas = *rc.Spec.Replicas rc.Status.Replicas = *rc.Spec.Replicas
return rc, nil return rc, nil
}, },
getOrCreateTargetController: func(controller *corev1.ReplicationController, sourceId string) (*corev1.ReplicationController, bool, error) { getOrCreateTargetController: func(controller *corev1.ReplicationController, sourceID string) (*corev1.ReplicationController, bool, error) {
// Simulate a create vs. update of an existing controller. // Simulate a create vs. update of an existing controller.
return tt.newRc, tt.newRcExists, nil return tt.newRc, tt.newRcExists, nil
}, },
@ -865,7 +865,7 @@ func TestUpdate_progressTimeout(t *testing.T) {
// Do nothing. // Do nothing.
return rc, nil return rc, nil
}, },
getOrCreateTargetController: func(controller *corev1.ReplicationController, sourceId string) (*corev1.ReplicationController, bool, error) { getOrCreateTargetController: func(controller *corev1.ReplicationController, sourceID string) (*corev1.ReplicationController, bool, error) {
return newRc, false, nil return newRc, false, nil
}, },
cleanup: func(oldRc, newRc *corev1.ReplicationController, config *RollingUpdaterConfig) error { cleanup: func(oldRc, newRc *corev1.ReplicationController, config *RollingUpdaterConfig) error {
@ -909,7 +909,7 @@ func TestUpdate_assignOriginalAnnotation(t *testing.T) {
scaleAndWait: func(rc *corev1.ReplicationController, retry *RetryParams, wait *RetryParams) (*corev1.ReplicationController, error) { scaleAndWait: func(rc *corev1.ReplicationController, retry *RetryParams, wait *RetryParams) (*corev1.ReplicationController, error) {
return rc, nil return rc, nil
}, },
getOrCreateTargetController: func(controller *corev1.ReplicationController, sourceId string) (*corev1.ReplicationController, bool, error) { getOrCreateTargetController: func(controller *corev1.ReplicationController, sourceID string) (*corev1.ReplicationController, bool, error) {
return newRc, false, nil return newRc, false, nil
}, },
cleanup: func(oldRc, newRc *corev1.ReplicationController, config *RollingUpdaterConfig) error { cleanup: func(oldRc, newRc *corev1.ReplicationController, config *RollingUpdaterConfig) error {
@ -1244,7 +1244,7 @@ func TestFindSourceController(t *testing.T) {
Namespace: metav1.NamespaceDefault, Namespace: metav1.NamespaceDefault,
Name: "foo", Name: "foo",
Annotations: map[string]string{ Annotations: map[string]string{
sourceIdAnnotation: "bar:1234", sourceIDAnnotation: "bar:1234",
}, },
}, },
} }
@ -1253,7 +1253,7 @@ func TestFindSourceController(t *testing.T) {
Namespace: metav1.NamespaceDefault, Namespace: metav1.NamespaceDefault,
Name: "bar", Name: "bar",
Annotations: map[string]string{ Annotations: map[string]string{
sourceIdAnnotation: "foo:12345", sourceIDAnnotation: "foo:12345",
}, },
}, },
} }
@ -1262,7 +1262,7 @@ func TestFindSourceController(t *testing.T) {
Namespace: metav1.NamespaceDefault, Namespace: metav1.NamespaceDefault,
Name: "baz", Name: "baz",
Annotations: map[string]string{ Annotations: map[string]string{
sourceIdAnnotation: "baz:45667", sourceIDAnnotation: "baz:45667",
}, },
}, },
} }

View File

@ -175,7 +175,7 @@ func scaleHasDesiredReplicas(sClient scaleclient.ScalesGetter, gr schema.GroupRe
// or returns error when timeout happens // or returns error when timeout happens
func WaitForScaleHasDesiredReplicas(sClient scaleclient.ScalesGetter, gr schema.GroupResource, resourceName string, namespace string, newSize uint, waitForReplicas *RetryParams) error { func WaitForScaleHasDesiredReplicas(sClient scaleclient.ScalesGetter, gr schema.GroupResource, resourceName string, namespace string, newSize uint, waitForReplicas *RetryParams) error {
if waitForReplicas == nil { if waitForReplicas == nil {
return fmt.Errorf("waitForReplicas parameter cannot be nil!") return fmt.Errorf("waitForReplicas parameter cannot be nil")
} }
err := wait.PollImmediate( err := wait.PollImmediate(
waitForReplicas.Interval, waitForReplicas.Interval,

View File

@ -37,7 +37,7 @@ import (
"vbom.ml/util/sortorder" "vbom.ml/util/sortorder"
) )
// Sorting printer sorts list types before delegating to another printer. // SortingPrinter sorts list types before delegating to another printer.
// Non-list types are simply passed through // Non-list types are simply passed through
type SortingPrinter struct { type SortingPrinter struct {
SortField string SortField string
@ -296,7 +296,8 @@ func (r *RuntimeSort) Less(i, j int) bool {
return less return less
} }
// Returns the starting (original) position of a particular index. e.g. If OriginalPosition(0) returns 5 than the // OriginalPosition returns the starting (original) position of a particular index.
// e.g. If OriginalPosition(0) returns 5 than the
// the item currently at position 0 was at position 5 in the original unsorted array. // the item currently at position 0 was at position 5 in the original unsorted array.
func (r *RuntimeSort) OriginalPosition(ix int) int { func (r *RuntimeSort) OriginalPosition(ix int) int {
if ix < 0 || ix > len(r.origPosition) { if ix < 0 || ix > len(r.origPosition) {

View File

@ -23,8 +23,8 @@ import (
"k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/intstr"
) )
// Lookup containerPort number from Service port number // LookupContainerPortNumberByServicePort implements
// It implements the handling of resolving container named port, as well as ignoring targetPort when clusterIP=None // the handling of resolving container named port, as well as ignoring targetPort when clusterIP=None
// It returns an error when a named port can't find a match (with -1 returned), or when the service does not // It returns an error when a named port can't find a match (with -1 returned), or when the service does not
// declare such port (with the input port number returned). // declare such port (with the input port number returned).
func LookupContainerPortNumberByServicePort(svc v1.Service, pod v1.Pod, port int32) (int32, error) { func LookupContainerPortNumberByServicePort(svc v1.Service, pod v1.Pod, port int32) (int32, error) {
@ -39,12 +39,10 @@ func LookupContainerPortNumberByServicePort(svc v1.Service, pod v1.Pod, port int
if svcportspec.TargetPort.IntValue() == 0 { if svcportspec.TargetPort.IntValue() == 0 {
// targetPort is omitted, and the IntValue() would be zero // targetPort is omitted, and the IntValue() would be zero
return svcportspec.Port, nil return svcportspec.Port, nil
} else {
return int32(svcportspec.TargetPort.IntValue()), nil
} }
} else { return int32(svcportspec.TargetPort.IntValue()), nil
return LookupContainerPortNumberByName(pod, svcportspec.TargetPort.String())
} }
return LookupContainerPortNumberByName(pod, svcportspec.TargetPort.String())
} }
return port, fmt.Errorf("Service %s does not have a service port %d", svc.Name, port) return port, fmt.Errorf("Service %s does not have a service port %d", svc.Name, port)
} }

View File

@ -20,5 +20,5 @@ import (
"sort" "sort"
) )
// Sorts []int64 in increasing order // SortInts64 sorts []int64 in increasing order
func SortInts64(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) } func SortInts64(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }

View File

@ -22,6 +22,7 @@ import (
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
// Umask is a wrapper for `unix.Umask()` on non-Windows platforms
func Umask(mask int) (old int, err error) { func Umask(mask int) (old int, err error) {
return unix.Umask(mask), nil return unix.Umask(mask), nil
} }

View File

@ -22,6 +22,7 @@ import (
"errors" "errors"
) )
// Umask returns an error on Windows
func Umask(mask int) (int, error) { func Umask(mask int) (int, error) {
return 0, errors.New("platform and architecture is not supported") return 0, errors.New("platform and architecture is not supported")
} }

View File

@ -41,6 +41,7 @@ func ParseRFC3339(s string, nowFn func() metav1.Time) (metav1.Time, error) {
return metav1.Time{Time: t}, nil return metav1.Time{Time: t}, nil
} }
// HashObject returns the hash of a Object hash by a Codec
func HashObject(obj runtime.Object, codec runtime.Codec) (string, error) { func HashObject(obj runtime.Object, codec runtime.Codec) (string, error) {
data, err := runtime.Encode(codec, obj) data, err := runtime.Encode(codec, obj)
if err != nil { if err != nil {
@ -63,11 +64,11 @@ func ParseFileSource(source string) (keyName, filePath string, err error) {
case numSeparators == 0: case numSeparators == 0:
return path.Base(filepath.ToSlash(source)), source, nil return path.Base(filepath.ToSlash(source)), source, nil
case numSeparators == 1 && strings.HasPrefix(source, "="): case numSeparators == 1 && strings.HasPrefix(source, "="):
return "", "", fmt.Errorf("key name for file path %v missing.", strings.TrimPrefix(source, "=")) return "", "", fmt.Errorf("key name for file path %v missing", strings.TrimPrefix(source, "="))
case numSeparators == 1 && strings.HasSuffix(source, "="): case numSeparators == 1 && strings.HasSuffix(source, "="):
return "", "", fmt.Errorf("file path for key name %v missing.", strings.TrimSuffix(source, "=")) return "", "", fmt.Errorf("file path for key name %v missing", strings.TrimSuffix(source, "="))
case numSeparators > 1: case numSeparators > 1:
return "", "", errors.New("Key names or file paths cannot contain '='.") return "", "", errors.New("Key names or file paths cannot contain '='")
default: default:
components := strings.Split(source, "=") components := strings.Split(source, "=")
return components[0], components[1], nil return components[0], components[1], nil