This is a code-linting refactor

This refactors a large part of the codebase using the suggestions from
golangci-lint

Change-Id: I2b7735086a64e50f3d5e0b30c225870bddc70935
This commit is contained in:
Ian Howell 2019-08-08 16:13:42 -05:00
parent 3b835bb0ee
commit bba1bd9d3d
37 changed files with 312 additions and 244 deletions

View File

@ -20,27 +20,28 @@ type Client struct {
}
func (c Client) Pods(namespace string) v1core.PodInterface {
return c.Clientset.Core().Pods(namespace)
return c.Clientset.CoreV1().Pods(namespace)
}
func (c Client) Jobs(namespace string) v1batch.JobInterface {
return c.Clientset.Batch().Jobs(namespace)
return c.Clientset.BatchV1().Jobs(namespace)
}
func (c Client) Endpoints(namespace string) v1core.EndpointsInterface {
return c.Clientset.Core().Endpoints(namespace)
return c.Clientset.CoreV1().Endpoints(namespace)
}
func (c Client) DaemonSets(namespace string) v1beta1extensions.DaemonSetInterface {
return c.Clientset.Extensions().DaemonSets(namespace)
return c.Clientset.ExtensionsV1beta1().DaemonSets(namespace)
}
func (c Client) Services(namespace string) v1core.ServiceInterface {
return c.Clientset.Core().Services(namespace)
return c.Clientset.CoreV1().Services(namespace)
}
func New(config *rest.Config) (ClientInterface, error) {
if config == nil {
config, err := rest.InClusterConfig()
var err error
config, err = rest.InClusterConfig()
if err != nil {
return nil, err
}

View File

@ -80,7 +80,7 @@ func (c Config) IsResolved(entrypoint entry.EntrypointInterface) (bool, error) {
}
func (c Config) createAndTemplateConfig() (err error) {
func (c Config) createAndTemplateConfig() error {
config, err := os.Create(c.name)
if err != nil {
return err
@ -91,7 +91,7 @@ func (c Config) createAndTemplateConfig() (err error) {
if err = temp.Execute(config, c.params); err != nil {
return err
}
return
return nil
}
func getSrcConfig(prefix string, config string) (srcConfig string) {

View File

@ -1,10 +1,10 @@
package config_test
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestConfig(t *testing.T) {

View File

@ -7,11 +7,11 @@ import (
"os"
"path/filepath"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
)
const (
@ -28,7 +28,6 @@ var testEntrypoint entrypoint.EntrypointInterface
var testConfigContents string
var testConfigPath string
var testTemplatePath string
var hostname string
// var testClient cli.ClientInterface
@ -53,17 +52,17 @@ func teardownOsEnvironment() (err error) {
return os.Unsetenv(interfaceName)
}
func setupConfigTemplate(templatePath string) (err error) {
func setupConfigTemplate(templatePath string) error {
configContent := []byte(testConfigContents)
if err := os.MkdirAll(filepath.Dir(templatePath), 0755); err != nil {
return err
}
if err = ioutil.WriteFile(templatePath, configContent, 0644); err != nil {
if err := ioutil.WriteFile(templatePath, configContent, 0644); err != nil {
return err
}
return
return nil
}
func teardownConfigTemplate(templatePath string) (err error) {
@ -111,7 +110,8 @@ var _ = Describe("Config", func() {
It("checks the format of a newly created config file", func() {
config, _ := NewConfig(testConfigPath, templatePrefix)
config.IsResolved(testEntrypoint)
_, err := config.IsResolved(testEntrypoint)
Expect(err).NotTo(HaveOccurred())
result, err := ioutil.ReadFile(fmt.Sprintf("%s/%s", testDir, testConfigName))
Expect(err).NotTo(HaveOccurred())
@ -121,7 +121,7 @@ var _ = Describe("Config", func() {
expectedFile := fmt.Sprintf(testConfigContentsFormat, hostname)
readConfig := string(result[:])
readConfig := string(result)
Expect(readConfig).To(BeEquivalentTo(expectedFile))
})

View File

@ -3,14 +3,14 @@ package container
import (
"fmt"
"os"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
entry "github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/logger"
"github.com/stackanetes/kubernetes-entrypoint/util"
"github.com/stackanetes/kubernetes-entrypoint/util/env"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
@ -54,7 +54,7 @@ func (c Container) IsResolved(entrypoint entry.EntrypointInterface) (bool, error
}
if strings.Contains(c.name, env.Separator) {
return false, fmt.Errorf("Specifing namespace is not permitted")
return false, fmt.Errorf("Specifying namespace is not permitted")
}
containers := pod.Status.ContainerStatuses
for _, container := range containers {

View File

@ -1,10 +1,10 @@
package container_test
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestContainer(t *testing.T) {

View File

@ -4,11 +4,11 @@ import (
"fmt"
"os"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
)
const (

View File

@ -4,11 +4,12 @@ import (
"fmt"
"os"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
entry "github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/logger"
"github.com/stackanetes/kubernetes-entrypoint/util/env"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
@ -24,15 +25,14 @@ type Daemonset struct {
func init() {
daemonsetEnv := fmt.Sprintf("%sDAEMONSET", entry.DependencyPrefix)
if daemonsetsDeps := env.SplitEnvToDeps(daemonsetEnv); daemonsetsDeps != nil {
for _, dep := range daemonsetsDeps {
daemonset, err := NewDaemonset(dep.Name, dep.Namespace)
if err != nil {
logger.Error.Printf("Cannot initialize daemonset: %v", err)
continue
}
entry.Register(daemonset)
daemonsetsDeps := env.SplitEnvToDeps(daemonsetEnv)
for _, dep := range daemonsetsDeps {
daemonset, err := NewDaemonset(dep.Name, dep.Namespace)
if err != nil {
logger.Error.Printf("Cannot initialize daemonset: %v", err)
continue
}
entry.Register(daemonset)
}
}
@ -71,6 +71,7 @@ func (d Daemonset) IsResolved(entrypoint entry.EntrypointInterface) (bool, error
myHost := myPod.Status.HostIP
for _, pod := range daemonsetPods.Items {
pod := pod // pinning
if !isPodOnHost(&pod, myHost) {
continue
}
@ -84,10 +85,7 @@ func (d Daemonset) IsResolved(entrypoint entry.EntrypointInterface) (bool, error
}
func isPodOnHost(pod *v1.Pod, hostIP string) bool {
if pod.Status.HostIP == hostIP {
return true
}
return false
return pod.Status.HostIP == hostIP
}
func isPodReady(pod v1.Pod) bool {

View File

@ -1,10 +1,10 @@
package daemonset_test
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestDaemonset(t *testing.T) {

View File

@ -4,11 +4,11 @@ import (
"fmt"
"os"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
)
const (
@ -32,7 +32,8 @@ var _ = Describe("Daemonset", func() {
daemonset, err := NewDaemonset(mocks.SucceedingDaemonsetName, daemonsetNamespace)
Expect(daemonset).To(BeNil())
Expect(err.Error()).To(Equal(fmt.Sprintf(PodNameNotSetErrorFormat, mocks.SucceedingDaemonsetName, daemonsetNamespace)))
errMsg := fmt.Sprintf(PodNameNotSetErrorFormat, mocks.SucceedingDaemonsetName, daemonsetNamespace)
Expect(err.Error()).To(Equal(errMsg))
})
It(fmt.Sprintf("creates new daemonset with %s set and checks its name", PodNameEnvVar), func() {
@ -126,6 +127,5 @@ var _ = Describe("Daemonset", func() {
Expect(err).NotTo(HaveOccurred())
Expect(isResolved).To(BeTrue())
err = os.Unsetenv(PodNameEnvVar)
})
})

View File

@ -3,11 +3,12 @@ package job
import (
"fmt"
v1 "k8s.io/api/batch/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
entry "github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/logger"
"github.com/stackanetes/kubernetes-entrypoint/util/env"
v1 "k8s.io/api/batch/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const FailingStatusFormat = "Job %s is not completed yet"
@ -78,13 +79,11 @@ func (j Job) IsResolved(entrypoint entry.EntrypointInterface) (bool, error) {
}
func (j Job) String() string {
var prefix string
prefix := "Jobs"
if j.name != "" {
prefix = fmt.Sprintf("Job %s", j.name)
} else if j.labels != nil {
prefix = fmt.Sprintf("Jobs with labels %s", j.labels)
} else {
prefix = "Jobs"
}
return fmt.Sprintf("%s in namespace %s", prefix, j.namespace)
}

View File

@ -1,10 +1,10 @@
package job_test
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestJob(t *testing.T) {

View File

@ -3,11 +3,11 @@ package job
import (
"fmt"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
)
const testJobName = "TEST_JOB_NAME"

View File

@ -4,11 +4,12 @@ import (
"fmt"
"os"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
entry "github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/logger"
"github.com/stackanetes/kubernetes-entrypoint/util/env"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
@ -25,15 +26,14 @@ type Pod struct {
func init() {
podEnv := fmt.Sprintf("%sPOD%s", entry.DependencyPrefix, entry.JsonSuffix)
if podDeps := env.SplitPodEnvToDeps(podEnv); podDeps != nil {
for _, dep := range podDeps {
pod, err := NewPod(dep.Labels, dep.Namespace, dep.RequireSameNode)
if err != nil {
logger.Error.Printf("Cannot initialize pod: %v", err)
continue
}
entry.Register(pod)
podDeps := env.SplitPodEnvToDeps(podEnv)
for _, dep := range podDeps {
pod, err := NewPod(dep.Labels, dep.Namespace, dep.RequireSameNode)
if err != nil {
logger.Error.Printf("Cannot initialize pod: %v", err)
continue
}
entry.Register(pod)
}
}
@ -73,6 +73,7 @@ func (p Pod) IsResolved(entrypoint entry.EntrypointInterface) (bool, error) {
podCount := 0
for _, pod := range matchingPods {
podCount++
pod := pod // pinning
if p.requireSameNode && !isPodOnHost(&pod, myHost) {
continue
}
@ -92,10 +93,7 @@ func (p Pod) IsResolved(entrypoint entry.EntrypointInterface) (bool, error) {
}
func isPodOnHost(pod *v1.Pod, hostIP string) bool {
if pod.Status.HostIP == hostIP {
return true
}
return false
return pod.Status.HostIP == hostIP
}
func isPodReady(pod v1.Pod) bool {

View File

@ -1,10 +1,10 @@
package pod_test
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestPod(t *testing.T) {

View File

@ -4,11 +4,11 @@ import (
"fmt"
"os"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
)
const (

View File

@ -3,9 +3,10 @@ package service
import (
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
entry "github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/util/env"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const FailingStatusFormat = "Service %v has no endpoints"

View File

@ -1,10 +1,10 @@
package service_test
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestService(t *testing.T) {

View File

@ -3,11 +3,11 @@ package service
import (
"fmt"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
)
const testServiceName = "TEST_SERVICE_NAME"

View File

@ -1,10 +1,10 @@
package socket_test
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestSocket(t *testing.T) {

View File

@ -4,11 +4,11 @@ import (
"fmt"
"os"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
)
const (

View File

@ -4,9 +4,10 @@ import (
"sync"
"time"
"k8s.io/client-go/rest"
cli "github.com/stackanetes/kubernetes-entrypoint/client"
"github.com/stackanetes/kubernetes-entrypoint/logger"
"k8s.io/client-go/rest"
)
var dependencies []Resolver // List containing all dependencies to be resolved
@ -66,7 +67,7 @@ func (e Entrypoint) Resolve() {
logger.Info.Printf("Resolving %v", dep)
var err error
status := false
for status == false {
for !status {
if status, err = dep.IsResolved(e); err != nil {
logger.Warning.Printf("Resolving dependency %s failed: %v .", dep, err)
}

View File

@ -1,10 +1,10 @@
package entrypoint_test
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestEntrypoint(t *testing.T) {

View File

@ -8,6 +8,7 @@ import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
cli "github.com/stackanetes/kubernetes-entrypoint/client"
"github.com/stackanetes/kubernetes-entrypoint/logger"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
@ -103,6 +104,8 @@ var _ = Describe("Entrypoint", func() {
time.Sleep(5 * time.Second)
stdout, _ := ioutil.ReadAll(r)
Expect(string(stdout)).To(Equal(fmt.Sprintf("%sResolving %v\n%sDependency %v is resolved.\n", loggerInfoText, dummy, loggerInfoText, dummy)))
resolvedString := fmt.Sprintf("%sResolving %v\n%sDependency %v is resolved.\n",
loggerInfoText, dummy, loggerInfoText, dummy)
Expect(string(stdout)).To(Equal(resolvedString))
})
})

View File

@ -3,8 +3,6 @@ package main
import (
"os"
entry "github.com/stackanetes/kubernetes-entrypoint/entrypoint"
_ "github.com/stackanetes/kubernetes-entrypoint/dependencies/config"
_ "github.com/stackanetes/kubernetes-entrypoint/dependencies/container"
_ "github.com/stackanetes/kubernetes-entrypoint/dependencies/daemonset"
@ -12,8 +10,9 @@ import (
_ "github.com/stackanetes/kubernetes-entrypoint/dependencies/pod"
_ "github.com/stackanetes/kubernetes-entrypoint/dependencies/service"
_ "github.com/stackanetes/kubernetes-entrypoint/dependencies/socket"
entry "github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/logger"
command "github.com/stackanetes/kubernetes-entrypoint/util/command"
"github.com/stackanetes/kubernetes-entrypoint/util/command"
"github.com/stackanetes/kubernetes-entrypoint/util/env"
)

View File

@ -6,9 +6,9 @@ import (
)
var (
//"Info logger""
//Info logger
Info *log.Logger
//"Error logger"
//Error logger
Error *log.Logger
//Warning logger
Warning *log.Logger

View File

@ -1,10 +1,11 @@
package mocks
import (
cli "github.com/stackanetes/kubernetes-entrypoint/client"
v1batch "k8s.io/client-go/kubernetes/typed/batch/v1"
v1core "k8s.io/client-go/kubernetes/typed/core/v1"
v1beta1extensions "k8s.io/client-go/kubernetes/typed/extensions/v1beta1"
cli "github.com/stackanetes/kubernetes-entrypoint/client"
)
type Client struct {

View File

@ -25,13 +25,15 @@ const (
)
func (d dClient) Get(name string, opts metav1.GetOptions) (*v1beta1.DaemonSet, error) {
matchLabelName := MockContainerName
if name == FailingDaemonsetName || name == IncorrectNamespaceDaemonsetName {
return nil, fmt.Errorf("Mock daemonset didn't work")
}
if name == FailingDaemonsetName {
return nil, fmt.Errorf("Mock daemonset didnt work")
} else if name == FailingMatchLabelsDaemonsetName {
matchLabelName := MockContainerName
switch name {
case FailingMatchLabelsDaemonsetName:
matchLabelName = FailingMatchLabel
} else if name == NotReadyMatchLabelsDaemonsetName {
case NotReadyMatchLabelsDaemonsetName:
matchLabelName = SameHostNotReadyMatchLabel
}
@ -46,8 +48,6 @@ func (d dClient) Get(name string, opts metav1.GetOptions) (*v1beta1.DaemonSet, e
if name == CorrectNamespaceDaemonsetName {
ds.ObjectMeta.Namespace = CorrectDaemonsetNamespace
} else if name == IncorrectNamespaceDaemonsetName {
return nil, fmt.Errorf("Mock daemonset didnt work")
}
return ds, nil
@ -79,7 +79,8 @@ func (d dClient) Watch(options metav1.ListOptions) (watch.Interface, error) {
return nil, fmt.Errorf("Not implemented")
}
func (d dClient) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.DaemonSet, err error) {
func (d dClient) Patch(name string, pt types.PatchType, data []byte,
subresources ...string) (result *v1beta1.DaemonSet, err error) {
return nil, fmt.Errorf("Not implemented")
}

View File

@ -3,12 +3,12 @@ package mocks
import (
"fmt"
"k8s.io/api/core/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
v1core "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest"
rest "k8s.io/client-go/rest"
)
type eClient struct {
@ -70,11 +70,13 @@ func (e eClient) Watch(options metav1.ListOptions) (watch.Interface, error) {
return nil, fmt.Errorf("Not implemented")
}
func (e eClient) ProxyGet(scheme string, name string, port string, path string, params map[string]string) rest.ResponseWrapper {
func (e eClient) ProxyGet(scheme string, name string, port string, path string,
params map[string]string) rest.ResponseWrapper {
return nil
}
func (e eClient) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Endpoints, err error) {
func (e eClient) Patch(name string, pt types.PatchType, data []byte,
subresources ...string) (result *v1.Endpoints, err error) {
return nil, fmt.Errorf("Not implemented")
}

View File

@ -45,13 +45,16 @@ func (j jClient) DeleteCollection(options *metav1.DeleteOptions, listOptions met
}
func (j jClient) List(options metav1.ListOptions) (*v1.JobList, error) {
var jobs []v1.Job
if options.LabelSelector == fmt.Sprintf("name=%s", SucceedingJobLabel) {
switch options.LabelSelector {
case fmt.Sprintf("name=%s", SucceedingJobLabel):
jobs = []v1.Job{NewJob(1)}
} else if options.LabelSelector == fmt.Sprintf("name=%s", FailingJobLabel) {
case fmt.Sprintf("name=%s", FailingJobLabel):
jobs = []v1.Job{NewJob(1), NewJob(0)}
} else {
default:
return nil, fmt.Errorf("Mock job didnt work")
}
return &v1.JobList{
Items: jobs,
}, nil
@ -69,7 +72,8 @@ func (j jClient) Watch(options metav1.ListOptions) (watch.Interface, error) {
return nil, fmt.Errorf("Not implemented")
}
func (j jClient) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Job, err error) {
func (j jClient) Patch(name string, pt types.PatchType, data []byte,
subresources ...string) (result *v1.Job, err error) {
return nil, fmt.Errorf("Not implemented")
}
func NewJClient() v1batch.JobInterface {

View File

@ -3,13 +3,13 @@ package mocks
import (
"fmt"
"k8s.io/api/core/v1"
v1 "k8s.io/api/core/v1"
policy "k8s.io/api/policy/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
v1core "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest"
rest "k8s.io/client-go/rest"
)
const MockContainerName = "TEST_CONTAINER"
@ -120,7 +120,8 @@ func (p pClient) GetLogs(name string, opts *v1.PodLogOptions) *rest.Request {
return nil
}
func (p pClient) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Pod, err error) {
func (p pClient) Patch(name string, pt types.PatchType, data []byte,
subresources ...string) (result *v1.Pod, err error) {
return nil, fmt.Errorf("Not implemented")
}
func NewPClient() v1core.PodInterface {

View File

@ -3,12 +3,12 @@ package mocks
import (
"fmt"
"k8s.io/api/core/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
v1core "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest"
rest "k8s.io/client-go/rest"
)
type sClient struct {
@ -57,11 +57,13 @@ func (s sClient) Watch(options metav1.ListOptions) (watch.Interface, error) {
return nil, fmt.Errorf("Not implemented")
}
func (s sClient) ProxyGet(scheme string, name string, port string, path string, params map[string]string) rest.ResponseWrapper {
func (s sClient) ProxyGet(scheme string, name string, port string, path string,
params map[string]string) rest.ResponseWrapper {
return nil
}
func (s sClient) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Service, err error) {
func (s sClient) Patch(name string, pt types.PatchType, data []byte,
subresources ...string) (result *v1.Service, err error) {
return nil, fmt.Errorf("Not implemented")
}

View File

@ -8,18 +8,18 @@ import (
"github.com/stackanetes/kubernetes-entrypoint/logger"
)
func Execute(command []string) (err error) {
func Execute(command []string) error {
path, err := exec.LookPath(command[0])
if err != nil {
logger.Error.Printf("Cannot find a binary %v : %v", command[0], err)
return
return err
}
env := os.Environ()
err = syscall.Exec(path, command, env)
if err != nil {
logger.Error.Printf("Executing command %v failed: %v", command, err)
return
return err
}
return
return nil
}

6
util/env/env.go vendored
View File

@ -49,7 +49,7 @@ func SplitEnvToDeps(env string) (envList []Dependency) {
envVars := strings.Split(e, separator)
namespace := GetBaseNamespace()
dep := Dependency{}
var dep Dependency
for _, envVar := range envVars {
if strings.Contains(envVar, Separator) {
nameAfterSplit := strings.Split(envVar, Separator)
@ -61,15 +61,11 @@ func SplitEnvToDeps(env string) (envList []Dependency) {
logger.Warning.Printf("Invalid format, missing namespace %s", envVar)
continue
}
dep = Dependency{Name: nameAfterSplit[1], Namespace: nameAfterSplit[0]}
} else {
dep = Dependency{Name: envVar, Namespace: namespace}
}
envList = append(envList, dep)
}
return envList

271
util/env/env_test.go vendored
View File

@ -6,79 +6,95 @@ import (
"testing"
)
func TestSplitEnvToListWithColon(t *testing.T) {
const (
name1 = "foo"
name2 = "bar"
defaultNamespace = "default"
altNamespace1 = "fooNS"
altNamespace2 = "barNS"
)
func TestSplitEnvToListWithComma(t *testing.T) {
defer os.Unsetenv("TEST_LIST")
os.Setenv("TEST_LIST", "foo,bar")
os.Setenv("TEST_LIST", name1+","+name2)
list := SplitEnvToDeps("TEST_LIST")
if list == nil {
t.Errorf("Expected: not nil")
if len(list) != 2 {
t.Errorf("Expected len to be 2 not %d", len(list))
}
if list[0].Name != "foo" {
t.Errorf("Expected: foo got %s", list[0])
if list[0].Name != name1 {
t.Errorf("Expected: %s got %s", name1, list[0])
}
if list[1].Name != "bar" {
t.Errorf("Expected: bar got %s", list[1])
if list[1].Name != name2 {
t.Errorf("Expected: %s got %s", name2, list[1])
}
}
os.Setenv("TEST_LIST", "foo1")
list1 := SplitEnvToDeps("TEST_LIST")
if list1 == nil {
t.Errorf("Expected: not nil")
func TestSplitEnvToList(t *testing.T) {
defer os.Unsetenv("TEST_LIST")
os.Setenv("TEST_LIST", name1)
list := SplitEnvToDeps("TEST_LIST")
if len(list) != 1 {
t.Errorf("Expected len to be 1 not %d", len(list))
}
if len(list1) != 1 {
t.Errorf("Expected len to be 1 not %d", len(list1))
if list[0].Name != name1 {
t.Errorf("Expected: %s got %s", name1, list[0])
}
if list1[0].Name != "foo1" {
t.Errorf("Expected: foo1 got %s", list1[0])
if list[0].Namespace != defaultNamespace {
t.Errorf("Expected: %s got %s", defaultNamespace, list[0].Namespace)
}
}
os.Setenv("TEST_LIST", "foo:foo")
list2 := SplitEnvToDeps("TEST_LIST")
if list2[0].Name != "foo" {
t.Errorf("Expected: foo got %s", list2[0].Name)
func TestSplitEnvToListWithColon(t *testing.T) {
defer os.Unsetenv("TEST_LIST")
os.Setenv("TEST_LIST", altNamespace1+":"+name1)
list := SplitEnvToDeps("TEST_LIST")
if len(list) != 1 {
t.Errorf("Expected len to be 1 not %d", len(list))
}
if list2[0].Namespace != "foo" {
t.Errorf("Expected: foo got %s", list2[0].Namespace)
if list[0].Name != name1 {
t.Errorf("Expected: %s got %s", name1, list[0].Name)
}
if list[0].Namespace != altNamespace1 {
t.Errorf("Expected: %s got %s", altNamespace1, list[0].Namespace)
}
}
os.Setenv("TEST_LIST", "bar")
list3 := SplitEnvToDeps("TEST_LIST")
if list3[0].Name != "bar" {
t.Errorf("Expected: bar got %s", list3[0].Name)
}
if list3[0].Namespace != "default" {
t.Errorf("Expected: default got %s", list3[0].Namespace)
}
os.Setenv("TEST_LIST", "foo:foo1:foo2")
list4 := SplitEnvToDeps("TEST_LIST")
if len(list4) != 0 {
func TestSplitEnvToListWithTooManyColons(t *testing.T) {
// TODO(howell): This should probably expect an error
defer os.Unsetenv("TEST_LIST")
os.Setenv("TEST_LIST", "too:many:colons")
list := SplitEnvToDeps("TEST_LIST")
if len(list) != 0 {
t.Errorf("Expected list to be empty")
}
}
os.Setenv("TEST_LIST", "foo:foo1:foo2,bar")
list5 := SplitEnvToDeps("TEST_LIST")
if list5[0].Namespace != "default" {
t.Errorf("Expected: default got %s", list5[0].Namespace)
func TestSplitEnvToListWithColonsAndCommas(t *testing.T) {
defer os.Unsetenv("TEST_LIST")
os.Setenv("TEST_LIST", altNamespace1+":"+name1+","+altNamespace2+":"+name2)
list := SplitEnvToDeps("TEST_LIST")
if len(list) != 2 {
t.Errorf("Expected len to be 2 not %d", len(list))
}
if list5[0].Name != "bar" {
t.Errorf("Expected: bar got %s", list5[0].Name)
if list[0].Name != name1 {
t.Errorf("Expected: %s got %s", name1, list[0].Name)
}
if list[0].Namespace != altNamespace1 {
t.Errorf("Expected: %s got %s", altNamespace1, list[0].Namespace)
}
if list[1].Name != name2 {
t.Errorf("Expected: %s got %s", name2, list[0].Name)
}
if list[1].Namespace != altNamespace2 {
t.Errorf("Expected: %s got %s", altNamespace2, list[0].Namespace)
}
}
os.Setenv("TEST_LIST", "foo:foo1:foo2,bar:foo")
list6 := SplitEnvToDeps("TEST_LIST")
if list6[0].Namespace != "bar" {
t.Errorf("Expected: bar got %s", list6[0].Namespace)
}
if list6[0].Name != "foo" {
t.Errorf("Expected: foo got %s", list6[0].Name)
}
os.Setenv("TEST_LIST", ":foo")
list7 := SplitEnvToDeps("TEST_LIST")
if len(list7) != 0 {
func TestSplitEnvToListWithMissingNamespace(t *testing.T) {
defer os.Unsetenv("TEST_LIST")
os.Setenv("TEST_LIST", ":name")
list := SplitEnvToDeps("TEST_LIST")
if len(list) != 0 {
t.Errorf("Invalid format, missing namespace in pod")
}
}
@ -87,26 +103,48 @@ func TestSplitEmptyEnvWithColon(t *testing.T) {
defer os.Unsetenv("TEST_LIST")
os.Setenv("TEST_LIST", "")
list := SplitEnvToDeps("TEST_LIST")
if list != nil {
t.Errorf("Expected nil got %v", list)
if len(list) != 0 {
t.Errorf("Expected list to be empty")
}
}
func TestSplitPodEnvToDepsSuccess(t *testing.T) {
defer os.Unsetenv("NAMESPACE")
os.Setenv("NAMESPACE", `TEST_NAMESPACE`)
defer os.Unsetenv("TEST_LIST_JSON")
os.Setenv("TEST_LIST_JSON", `[{"namespace": "foo", "labels": {"k1": "v1", "k2": "v2"}, "requireSameNode": true}, {"labels": {"k1": "v1", "k2": "v2"}}]`)
testListJSONVal := `[
{
"namespace": "` + name1 + `",
"labels": {
"k1": "v1",
"k2": "v2"
},
"requireSameNode": true
},
{
"labels": {
"k1": "v1",
"k2": "v2"
}
}
]`
os.Setenv("NAMESPACE", "TEST_NAMESPACE")
os.Setenv("TEST_LIST_JSON", testListJSONVal)
actual := SplitPodEnvToDeps("TEST_LIST_JSON")
expected := []PodDependency{
PodDependency{Namespace: "foo", Labels: map[string]string{
"k1": "v1",
"k2": "v2",
}, RequireSameNode: true},
PodDependency{Namespace: "TEST_NAMESPACE", Labels: map[string]string{
"k1": "v1",
"k2": "v2",
}, RequireSameNode: false},
{
Namespace: name1,
Labels: map[string]string{
"k1": "v1",
"k2": "v2",
},
RequireSameNode: true,
},
{
Namespace: "TEST_NAMESPACE",
Labels: map[string]string{
"k1": "v1",
"k2": "v2",
},
RequireSameNode: false,
},
}
if !reflect.DeepEqual(expected, actual) {
@ -133,19 +171,35 @@ func TestSplitPodEnvToDepsIgnoreInvalid(t *testing.T) {
}
func TestSplitJobEnvToDepsJsonSuccess(t *testing.T) {
testListJSONVal := `[
{
"namespace": "` + altNamespace1 + `",
"labels": {
"k1": "v1",
"k2": "v2"
}
},
{
"name": "` + name1 + `"
}
]`
defer os.Unsetenv("NAMESPACE")
os.Setenv("NAMESPACE", `TEST_NAMESPACE`)
os.Setenv("NAMESPACE", "TEST_NAMESPACE")
defer os.Unsetenv("TEST_LIST_JSON")
os.Setenv("TEST_LIST_JSON", `[{"namespace": "foo", "labels": {"k1": "v1", "k2": "v2"}}, {"name": "bar"}]`)
os.Setenv("TEST_LIST_JSON", testListJSONVal)
actual := SplitJobEnvToDeps("TEST_LIST", "TEST_LIST_JSON")
expected := []JobDependency{
JobDependency{
Name: "",
Namespace: "foo", Labels: map[string]string{
{
Namespace: altNamespace1,
Labels: map[string]string{
"k1": "v1",
"k2": "v2",
}},
JobDependency{Name: "bar", Namespace: "TEST_NAMESPACE", Labels: nil},
},
},
{
Name: name1,
Namespace: "TEST_NAMESPACE",
},
}
if !reflect.DeepEqual(expected, actual) {
@ -155,14 +209,16 @@ func TestSplitJobEnvToDepsJsonSuccess(t *testing.T) {
func TestSplitJobEnvToDepsPlainSuccess(t *testing.T) {
defer os.Unsetenv("NAMESPACE")
os.Setenv("NAMESPACE", `TEST_NAMESPACE`)
os.Setenv("NAMESPACE", "TEST_NAMESPACE")
defer os.Unsetenv("TEST_LIST")
os.Setenv("TEST_LIST", `plain`)
os.Setenv("TEST_LIST", "plain")
actual := SplitJobEnvToDeps("TEST_LIST", "TEST_LIST_JSON")
expected := []JobDependency{
JobDependency{Name: "plain", Namespace: "TEST_NAMESPACE", Labels: nil},
{
Name: "plain",
Namespace: "TEST_NAMESPACE",
},
}
if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected: %v Got: %v", expected, actual)
}
@ -170,16 +226,18 @@ func TestSplitJobEnvToDepsPlainSuccess(t *testing.T) {
func TestSplitJobEnvToDepsJsonPrecedence(t *testing.T) {
defer os.Unsetenv("NAMESPACE")
os.Setenv("NAMESPACE", `TEST_NAMESPACE`)
os.Setenv("NAMESPACE", "TEST_NAMESPACE")
defer os.Unsetenv("TEST_LIST_JSON")
os.Setenv("TEST_LIST_JSON", `[{"name": "json"}]`)
defer os.Unsetenv("TEST_LIST")
os.Setenv("TEST_LIST", `plain`)
os.Setenv("TEST_LIST", "plain")
actual := SplitJobEnvToDeps("TEST_LIST", "TEST_LIST_JSON")
expected := []JobDependency{
JobDependency{Name: "json", Namespace: "TEST_NAMESPACE", Labels: nil},
{
Name: "json",
Namespace: "TEST_NAMESPACE",
},
}
if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected: %v Got: %v", expected, actual)
}
@ -201,18 +259,27 @@ func TestSplitJobEnvToDepsIgnoreInvalid(t *testing.T) {
}
}
func TestSplitCommandUnset(t *testing.T) {
defer os.Unsetenv("COMMAND")
list := SplitCommand()
if len(list) > 0 {
t.Errorf("Expected len to be 0, got %d", len(list))
}
}
func TestSplitCommandEmpty(t *testing.T) {
defer os.Unsetenv("COMMAND")
os.Setenv("COMMAND", "")
list := SplitCommand()
if len(list) > 0 {
t.Errorf("Expected len to be 0, got %v", len(list))
}
}
func TestSplitCommand(t *testing.T) {
defer os.Unsetenv("COMMAND")
list2 := SplitCommand()
if len(list2) > 0 {
t.Errorf("Expected len to be 0, got %v", len(list2))
}
os.Setenv("COMMAND", "echo test")
list := SplitCommand()
if list == nil {
t.Errorf("Expected slice, got nil")
return
}
if len(list) != 2 {
t.Errorf("Expected two elements, got %v", len(list))
}
@ -222,30 +289,22 @@ func TestSplitCommand(t *testing.T) {
if list[1] != "test" {
t.Errorf("Expected test, got %s", list[1])
}
}
os.Setenv("COMMAND", "")
list1 := SplitCommand()
if len(list1) > 0 {
t.Errorf("Expected len to be 0, got %v", len(list1))
func TestGetBaseNamespaceEmpty(t *testing.T) {
defer os.Unsetenv("NAMESPACE")
os.Setenv("NAMESPACE", "")
getBaseNamespace := GetBaseNamespace()
if getBaseNamespace != defaultNamespace {
t.Errorf("Expected namespace to be %s, got %s", defaultNamespace, getBaseNamespace)
}
}
func TestGetBaseNamespace(t *testing.T) {
defer os.Unsetenv("NAMESPACE")
os.Setenv("NAMESPACE", "")
getBaseNamespace := GetBaseNamespace()
if getBaseNamespace != "default" {
t.Errorf("Expected namespace to be default, got %v", getBaseNamespace)
}
os.Setenv("NAMESPACE", "foo")
getBaseNamespace = GetBaseNamespace()
getBaseNamespace := GetBaseNamespace()
if getBaseNamespace != "foo" {
t.Errorf("Expected namespace to be foo, got %v", getBaseNamespace)
}
os.Setenv("NAMESPACE", "default")
getBaseNamespace = GetBaseNamespace()
if getBaseNamespace != "default" {
t.Errorf("Expected namespace to be default, got %v", getBaseNamespace)
}
}

View File

@ -2,13 +2,15 @@ package util
import (
"fmt"
"github.com/stackanetes/kubernetes-entrypoint/util/env"
"net"
"os"
"strings"
"github.com/stackanetes/kubernetes-entrypoint/logger"
"github.com/stackanetes/kubernetes-entrypoint/util/env"
)
func GetIp() (ip string, err error) {
func GetIp() (string, error) {
var iface string
if iface = os.Getenv("INTERFACE_NAME"); iface == "" {
return "", fmt.Errorf("Environment variable INTERFACE_NAME not set")
@ -23,13 +25,13 @@ func GetIp() (ip string, err error) {
return "", fmt.Errorf("Cannot get ip: %v", err)
}
//Take first element to get rid of subnet
ip = strings.Split(address[0].String(), "/")[0]
return
ip := strings.Split(address[0].String(), "/")[0]
return ip, nil
}
func ContainsSeparator(envString string, kind string) bool {
if strings.Contains(envString, env.Separator) {
fmt.Errorf("%s doesn't accept namespace: %s", kind, envString)
logger.Error.Printf("%s doesn't accept namespace: %s", kind, envString)
return true
}
return false

View File

@ -1,10 +1,10 @@
package util_test
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestUtil(t *testing.T) {