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 { 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 { 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 { 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 { 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 { 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) { func New(config *rest.Config) (ClientInterface, error) {
if config == nil { if config == nil {
config, err := rest.InClusterConfig() var err error
config, err = rest.InClusterConfig()
if err != nil { if err != nil {
return nil, err 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) config, err := os.Create(c.name)
if err != nil { if err != nil {
return err return err
@ -91,7 +91,7 @@ func (c Config) createAndTemplateConfig() (err error) {
if err = temp.Execute(config, c.params); err != nil { if err = temp.Execute(config, c.params); err != nil {
return err return err
} }
return return nil
} }
func getSrcConfig(prefix string, config string) (srcConfig string) { func getSrcConfig(prefix string, config string) (srcConfig string) {

View File

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

View File

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

View File

@ -3,14 +3,14 @@ package container
import ( import (
"fmt" "fmt"
"os" "os"
"strings" "strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
entry "github.com/stackanetes/kubernetes-entrypoint/entrypoint" entry "github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/logger" "github.com/stackanetes/kubernetes-entrypoint/logger"
"github.com/stackanetes/kubernetes-entrypoint/util" "github.com/stackanetes/kubernetes-entrypoint/util"
"github.com/stackanetes/kubernetes-entrypoint/util/env" "github.com/stackanetes/kubernetes-entrypoint/util/env"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
) )
const ( const (
@ -54,7 +54,7 @@ func (c Container) IsResolved(entrypoint entry.EntrypointInterface) (bool, error
} }
if strings.Contains(c.name, env.Separator) { 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 containers := pod.Status.ContainerStatuses
for _, container := range containers { for _, container := range containers {

View File

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

View File

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

View File

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

View File

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

View File

@ -4,11 +4,11 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
. "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/mocks"
) )
const ( const (
@ -32,7 +32,8 @@ var _ = Describe("Daemonset", func() {
daemonset, err := NewDaemonset(mocks.SucceedingDaemonsetName, daemonsetNamespace) daemonset, err := NewDaemonset(mocks.SucceedingDaemonsetName, daemonsetNamespace)
Expect(daemonset).To(BeNil()) 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() { 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(err).NotTo(HaveOccurred())
Expect(isResolved).To(BeTrue()) Expect(isResolved).To(BeTrue())
err = os.Unsetenv(PodNameEnvVar)
}) })
}) })

View File

@ -3,11 +3,12 @@ package job
import ( import (
"fmt" "fmt"
v1 "k8s.io/api/batch/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
entry "github.com/stackanetes/kubernetes-entrypoint/entrypoint" entry "github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/logger" "github.com/stackanetes/kubernetes-entrypoint/logger"
"github.com/stackanetes/kubernetes-entrypoint/util/env" "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" 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 { func (j Job) String() string {
var prefix string prefix := "Jobs"
if j.name != "" { if j.name != "" {
prefix = fmt.Sprintf("Job %s", j.name) prefix = fmt.Sprintf("Job %s", j.name)
} else if j.labels != nil { } else if j.labels != nil {
prefix = fmt.Sprintf("Jobs with labels %s", j.labels) prefix = fmt.Sprintf("Jobs with labels %s", j.labels)
} else {
prefix = "Jobs"
} }
return fmt.Sprintf("%s in namespace %s", prefix, j.namespace) return fmt.Sprintf("%s in namespace %s", prefix, j.namespace)
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -8,6 +8,7 @@ import (
. "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
cli "github.com/stackanetes/kubernetes-entrypoint/client" cli "github.com/stackanetes/kubernetes-entrypoint/client"
"github.com/stackanetes/kubernetes-entrypoint/logger" "github.com/stackanetes/kubernetes-entrypoint/logger"
"github.com/stackanetes/kubernetes-entrypoint/mocks" "github.com/stackanetes/kubernetes-entrypoint/mocks"
@ -103,6 +104,8 @@ var _ = Describe("Entrypoint", func() {
time.Sleep(5 * time.Second) time.Sleep(5 * time.Second)
stdout, _ := ioutil.ReadAll(r) 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 ( import (
"os" "os"
entry "github.com/stackanetes/kubernetes-entrypoint/entrypoint"
_ "github.com/stackanetes/kubernetes-entrypoint/dependencies/config" _ "github.com/stackanetes/kubernetes-entrypoint/dependencies/config"
_ "github.com/stackanetes/kubernetes-entrypoint/dependencies/container" _ "github.com/stackanetes/kubernetes-entrypoint/dependencies/container"
_ "github.com/stackanetes/kubernetes-entrypoint/dependencies/daemonset" _ "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/pod"
_ "github.com/stackanetes/kubernetes-entrypoint/dependencies/service" _ "github.com/stackanetes/kubernetes-entrypoint/dependencies/service"
_ "github.com/stackanetes/kubernetes-entrypoint/dependencies/socket" _ "github.com/stackanetes/kubernetes-entrypoint/dependencies/socket"
entry "github.com/stackanetes/kubernetes-entrypoint/entrypoint"
"github.com/stackanetes/kubernetes-entrypoint/logger" "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" "github.com/stackanetes/kubernetes-entrypoint/util/env"
) )

View File

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

View File

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

View File

@ -25,13 +25,15 @@ const (
) )
func (d dClient) Get(name string, opts metav1.GetOptions) (*v1beta1.DaemonSet, error) { 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 { matchLabelName := MockContainerName
return nil, fmt.Errorf("Mock daemonset didnt work") switch name {
} else if name == FailingMatchLabelsDaemonsetName { case FailingMatchLabelsDaemonsetName:
matchLabelName = FailingMatchLabel matchLabelName = FailingMatchLabel
} else if name == NotReadyMatchLabelsDaemonsetName { case NotReadyMatchLabelsDaemonsetName:
matchLabelName = SameHostNotReadyMatchLabel matchLabelName = SameHostNotReadyMatchLabel
} }
@ -46,8 +48,6 @@ func (d dClient) Get(name string, opts metav1.GetOptions) (*v1beta1.DaemonSet, e
if name == CorrectNamespaceDaemonsetName { if name == CorrectNamespaceDaemonsetName {
ds.ObjectMeta.Namespace = CorrectDaemonsetNamespace ds.ObjectMeta.Namespace = CorrectDaemonsetNamespace
} else if name == IncorrectNamespaceDaemonsetName {
return nil, fmt.Errorf("Mock daemonset didnt work")
} }
return ds, nil return ds, nil
@ -79,7 +79,8 @@ func (d dClient) Watch(options metav1.ListOptions) (watch.Interface, error) {
return nil, fmt.Errorf("Not implemented") 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") return nil, fmt.Errorf("Not implemented")
} }

View File

@ -3,12 +3,12 @@ package mocks
import ( import (
"fmt" "fmt"
"k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types" types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch" watch "k8s.io/apimachinery/pkg/watch"
v1core "k8s.io/client-go/kubernetes/typed/core/v1" v1core "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest" rest "k8s.io/client-go/rest"
) )
type eClient struct { type eClient struct {
@ -70,11 +70,13 @@ func (e eClient) Watch(options metav1.ListOptions) (watch.Interface, error) {
return nil, fmt.Errorf("Not implemented") 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 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") 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) { func (j jClient) List(options metav1.ListOptions) (*v1.JobList, error) {
var jobs []v1.Job 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)} 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)} jobs = []v1.Job{NewJob(1), NewJob(0)}
} else { default:
return nil, fmt.Errorf("Mock job didnt work") return nil, fmt.Errorf("Mock job didnt work")
} }
return &v1.JobList{ return &v1.JobList{
Items: jobs, Items: jobs,
}, nil }, nil
@ -69,7 +72,8 @@ func (j jClient) Watch(options metav1.ListOptions) (watch.Interface, error) {
return nil, fmt.Errorf("Not implemented") 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") return nil, fmt.Errorf("Not implemented")
} }
func NewJClient() v1batch.JobInterface { func NewJClient() v1batch.JobInterface {

View File

@ -3,13 +3,13 @@ package mocks
import ( import (
"fmt" "fmt"
"k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
policy "k8s.io/api/policy/v1beta1" policy "k8s.io/api/policy/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types" types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch" watch "k8s.io/apimachinery/pkg/watch"
v1core "k8s.io/client-go/kubernetes/typed/core/v1" v1core "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest" rest "k8s.io/client-go/rest"
) )
const MockContainerName = "TEST_CONTAINER" const MockContainerName = "TEST_CONTAINER"
@ -120,7 +120,8 @@ func (p pClient) GetLogs(name string, opts *v1.PodLogOptions) *rest.Request {
return nil 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") return nil, fmt.Errorf("Not implemented")
} }
func NewPClient() v1core.PodInterface { func NewPClient() v1core.PodInterface {

View File

@ -3,12 +3,12 @@ package mocks
import ( import (
"fmt" "fmt"
"k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types" types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch" watch "k8s.io/apimachinery/pkg/watch"
v1core "k8s.io/client-go/kubernetes/typed/core/v1" v1core "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest" rest "k8s.io/client-go/rest"
) )
type sClient struct { type sClient struct {
@ -57,11 +57,13 @@ func (s sClient) Watch(options metav1.ListOptions) (watch.Interface, error) {
return nil, fmt.Errorf("Not implemented") 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 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") return nil, fmt.Errorf("Not implemented")
} }

View File

@ -8,18 +8,18 @@ import (
"github.com/stackanetes/kubernetes-entrypoint/logger" "github.com/stackanetes/kubernetes-entrypoint/logger"
) )
func Execute(command []string) (err error) { func Execute(command []string) error {
path, err := exec.LookPath(command[0]) path, err := exec.LookPath(command[0])
if err != nil { if err != nil {
logger.Error.Printf("Cannot find a binary %v : %v", command[0], err) logger.Error.Printf("Cannot find a binary %v : %v", command[0], err)
return return err
} }
env := os.Environ() env := os.Environ()
err = syscall.Exec(path, command, env) err = syscall.Exec(path, command, env)
if err != nil { if err != nil {
logger.Error.Printf("Executing command %v failed: %v", command, err) 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) envVars := strings.Split(e, separator)
namespace := GetBaseNamespace() namespace := GetBaseNamespace()
dep := Dependency{} var dep Dependency
for _, envVar := range envVars { for _, envVar := range envVars {
if strings.Contains(envVar, Separator) { if strings.Contains(envVar, Separator) {
nameAfterSplit := strings.Split(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) logger.Warning.Printf("Invalid format, missing namespace %s", envVar)
continue continue
} }
dep = Dependency{Name: nameAfterSplit[1], Namespace: nameAfterSplit[0]} dep = Dependency{Name: nameAfterSplit[1], Namespace: nameAfterSplit[0]}
} else { } else {
dep = Dependency{Name: envVar, Namespace: namespace} dep = Dependency{Name: envVar, Namespace: namespace}
} }
envList = append(envList, dep) envList = append(envList, dep)
} }
return envList return envList

263
util/env/env_test.go vendored
View File

@ -6,79 +6,95 @@ import (
"testing" "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") defer os.Unsetenv("TEST_LIST")
os.Setenv("TEST_LIST", name1+","+name2)
os.Setenv("TEST_LIST", "foo,bar")
list := SplitEnvToDeps("TEST_LIST") list := SplitEnvToDeps("TEST_LIST")
if list == nil { if len(list) != 2 {
t.Errorf("Expected: not nil") t.Errorf("Expected len to be 2 not %d", len(list))
} }
if list[0].Name != "foo" { if list[0].Name != name1 {
t.Errorf("Expected: foo got %s", list[0]) t.Errorf("Expected: %s got %s", name1, list[0])
} }
if list[1].Name != "bar" { if list[1].Name != name2 {
t.Errorf("Expected: bar got %s", list[1]) t.Errorf("Expected: %s got %s", name2, list[1])
} }
}
os.Setenv("TEST_LIST", "foo1") func TestSplitEnvToList(t *testing.T) {
list1 := SplitEnvToDeps("TEST_LIST") defer os.Unsetenv("TEST_LIST")
if list1 == nil { os.Setenv("TEST_LIST", name1)
t.Errorf("Expected: not nil") list := SplitEnvToDeps("TEST_LIST")
if len(list) != 1 {
t.Errorf("Expected len to be 1 not %d", len(list))
} }
if len(list1) != 1 { if list[0].Name != name1 {
t.Errorf("Expected len to be 1 not %d", len(list1)) t.Errorf("Expected: %s got %s", name1, list[0])
} }
if list1[0].Name != "foo1" { if list[0].Namespace != defaultNamespace {
t.Errorf("Expected: foo1 got %s", list1[0]) t.Errorf("Expected: %s got %s", defaultNamespace, list[0].Namespace)
} }
}
os.Setenv("TEST_LIST", "foo:foo") func TestSplitEnvToListWithColon(t *testing.T) {
list2 := SplitEnvToDeps("TEST_LIST") defer os.Unsetenv("TEST_LIST")
if list2[0].Name != "foo" { os.Setenv("TEST_LIST", altNamespace1+":"+name1)
t.Errorf("Expected: foo got %s", list2[0].Name) list := SplitEnvToDeps("TEST_LIST")
if len(list) != 1 {
t.Errorf("Expected len to be 1 not %d", len(list))
} }
if list2[0].Namespace != "foo" { if list[0].Name != name1 {
t.Errorf("Expected: foo got %s", list2[0].Namespace) 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") func TestSplitEnvToListWithTooManyColons(t *testing.T) {
list3 := SplitEnvToDeps("TEST_LIST") // TODO(howell): This should probably expect an error
if list3[0].Name != "bar" { defer os.Unsetenv("TEST_LIST")
t.Errorf("Expected: bar got %s", list3[0].Name) os.Setenv("TEST_LIST", "too:many:colons")
} list := SplitEnvToDeps("TEST_LIST")
if list3[0].Namespace != "default" { if len(list) != 0 {
t.Errorf("Expected: default got %s", list3[0].Namespace)
}
os.Setenv("TEST_LIST", "foo:foo1:foo2")
list4 := SplitEnvToDeps("TEST_LIST")
if len(list4) != 0 {
t.Errorf("Expected list to be empty") t.Errorf("Expected list to be empty")
} }
}
os.Setenv("TEST_LIST", "foo:foo1:foo2,bar") func TestSplitEnvToListWithColonsAndCommas(t *testing.T) {
list5 := SplitEnvToDeps("TEST_LIST") defer os.Unsetenv("TEST_LIST")
if list5[0].Namespace != "default" { os.Setenv("TEST_LIST", altNamespace1+":"+name1+","+altNamespace2+":"+name2)
t.Errorf("Expected: default got %s", list5[0].Namespace) list := SplitEnvToDeps("TEST_LIST")
if len(list) != 2 {
t.Errorf("Expected len to be 2 not %d", len(list))
} }
if list5[0].Name != "bar" { if list[0].Name != name1 {
t.Errorf("Expected: bar got %s", list5[0].Name) 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") func TestSplitEnvToListWithMissingNamespace(t *testing.T) {
list6 := SplitEnvToDeps("TEST_LIST") defer os.Unsetenv("TEST_LIST")
if list6[0].Namespace != "bar" { os.Setenv("TEST_LIST", ":name")
t.Errorf("Expected: bar got %s", list6[0].Namespace) list := SplitEnvToDeps("TEST_LIST")
} if len(list) != 0 {
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 {
t.Errorf("Invalid format, missing namespace in pod") t.Errorf("Invalid format, missing namespace in pod")
} }
} }
@ -87,26 +103,48 @@ func TestSplitEmptyEnvWithColon(t *testing.T) {
defer os.Unsetenv("TEST_LIST") defer os.Unsetenv("TEST_LIST")
os.Setenv("TEST_LIST", "") os.Setenv("TEST_LIST", "")
list := SplitEnvToDeps("TEST_LIST") list := SplitEnvToDeps("TEST_LIST")
if list != nil { if len(list) != 0 {
t.Errorf("Expected nil got %v", list) t.Errorf("Expected list to be empty")
} }
} }
func TestSplitPodEnvToDepsSuccess(t *testing.T) { func TestSplitPodEnvToDepsSuccess(t *testing.T) {
defer os.Unsetenv("NAMESPACE") testListJSONVal := `[
os.Setenv("NAMESPACE", `TEST_NAMESPACE`) {
defer os.Unsetenv("TEST_LIST_JSON") "namespace": "` + name1 + `",
os.Setenv("TEST_LIST_JSON", `[{"namespace": "foo", "labels": {"k1": "v1", "k2": "v2"}, "requireSameNode": true}, {"labels": {"k1": "v1", "k2": "v2"}}]`) "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") actual := SplitPodEnvToDeps("TEST_LIST_JSON")
expected := []PodDependency{ expected := []PodDependency{
PodDependency{Namespace: "foo", Labels: map[string]string{ {
Namespace: name1,
Labels: map[string]string{
"k1": "v1", "k1": "v1",
"k2": "v2", "k2": "v2",
}, RequireSameNode: true}, },
PodDependency{Namespace: "TEST_NAMESPACE", Labels: map[string]string{ RequireSameNode: true,
},
{
Namespace: "TEST_NAMESPACE",
Labels: map[string]string{
"k1": "v1", "k1": "v1",
"k2": "v2", "k2": "v2",
}, RequireSameNode: false}, },
RequireSameNode: false,
},
} }
if !reflect.DeepEqual(expected, actual) { if !reflect.DeepEqual(expected, actual) {
@ -133,19 +171,35 @@ func TestSplitPodEnvToDepsIgnoreInvalid(t *testing.T) {
} }
func TestSplitJobEnvToDepsJsonSuccess(t *testing.T) { func TestSplitJobEnvToDepsJsonSuccess(t *testing.T) {
testListJSONVal := `[
{
"namespace": "` + altNamespace1 + `",
"labels": {
"k1": "v1",
"k2": "v2"
}
},
{
"name": "` + name1 + `"
}
]`
defer os.Unsetenv("NAMESPACE") defer os.Unsetenv("NAMESPACE")
os.Setenv("NAMESPACE", `TEST_NAMESPACE`) os.Setenv("NAMESPACE", "TEST_NAMESPACE")
defer os.Unsetenv("TEST_LIST_JSON") 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") actual := SplitJobEnvToDeps("TEST_LIST", "TEST_LIST_JSON")
expected := []JobDependency{ expected := []JobDependency{
JobDependency{ {
Name: "", Namespace: altNamespace1,
Namespace: "foo", Labels: map[string]string{ Labels: map[string]string{
"k1": "v1", "k1": "v1",
"k2": "v2", "k2": "v2",
}}, },
JobDependency{Name: "bar", Namespace: "TEST_NAMESPACE", Labels: nil}, },
{
Name: name1,
Namespace: "TEST_NAMESPACE",
},
} }
if !reflect.DeepEqual(expected, actual) { if !reflect.DeepEqual(expected, actual) {
@ -155,14 +209,16 @@ func TestSplitJobEnvToDepsJsonSuccess(t *testing.T) {
func TestSplitJobEnvToDepsPlainSuccess(t *testing.T) { func TestSplitJobEnvToDepsPlainSuccess(t *testing.T) {
defer os.Unsetenv("NAMESPACE") defer os.Unsetenv("NAMESPACE")
os.Setenv("NAMESPACE", `TEST_NAMESPACE`) os.Setenv("NAMESPACE", "TEST_NAMESPACE")
defer os.Unsetenv("TEST_LIST") defer os.Unsetenv("TEST_LIST")
os.Setenv("TEST_LIST", `plain`) os.Setenv("TEST_LIST", "plain")
actual := SplitJobEnvToDeps("TEST_LIST", "TEST_LIST_JSON") actual := SplitJobEnvToDeps("TEST_LIST", "TEST_LIST_JSON")
expected := []JobDependency{ expected := []JobDependency{
JobDependency{Name: "plain", Namespace: "TEST_NAMESPACE", Labels: nil}, {
Name: "plain",
Namespace: "TEST_NAMESPACE",
},
} }
if !reflect.DeepEqual(expected, actual) { if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected: %v Got: %v", expected, actual) t.Errorf("Expected: %v Got: %v", expected, actual)
} }
@ -170,16 +226,18 @@ func TestSplitJobEnvToDepsPlainSuccess(t *testing.T) {
func TestSplitJobEnvToDepsJsonPrecedence(t *testing.T) { func TestSplitJobEnvToDepsJsonPrecedence(t *testing.T) {
defer os.Unsetenv("NAMESPACE") defer os.Unsetenv("NAMESPACE")
os.Setenv("NAMESPACE", `TEST_NAMESPACE`) os.Setenv("NAMESPACE", "TEST_NAMESPACE")
defer os.Unsetenv("TEST_LIST_JSON") defer os.Unsetenv("TEST_LIST_JSON")
os.Setenv("TEST_LIST_JSON", `[{"name": "json"}]`) os.Setenv("TEST_LIST_JSON", `[{"name": "json"}]`)
defer os.Unsetenv("TEST_LIST") defer os.Unsetenv("TEST_LIST")
os.Setenv("TEST_LIST", `plain`) os.Setenv("TEST_LIST", "plain")
actual := SplitJobEnvToDeps("TEST_LIST", "TEST_LIST_JSON") actual := SplitJobEnvToDeps("TEST_LIST", "TEST_LIST_JSON")
expected := []JobDependency{ expected := []JobDependency{
JobDependency{Name: "json", Namespace: "TEST_NAMESPACE", Labels: nil}, {
Name: "json",
Namespace: "TEST_NAMESPACE",
},
} }
if !reflect.DeepEqual(expected, actual) { if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected: %v Got: %v", 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) { func TestSplitCommand(t *testing.T) {
defer os.Unsetenv("COMMAND") 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") os.Setenv("COMMAND", "echo test")
list := SplitCommand() list := SplitCommand()
if list == nil {
t.Errorf("Expected slice, got nil")
return
}
if len(list) != 2 { if len(list) != 2 {
t.Errorf("Expected two elements, got %v", len(list)) t.Errorf("Expected two elements, got %v", len(list))
} }
@ -222,30 +289,22 @@ func TestSplitCommand(t *testing.T) {
if list[1] != "test" { if list[1] != "test" {
t.Errorf("Expected test, got %s", list[1]) t.Errorf("Expected test, got %s", list[1])
} }
}
os.Setenv("COMMAND", "") func TestGetBaseNamespaceEmpty(t *testing.T) {
list1 := SplitCommand() defer os.Unsetenv("NAMESPACE")
if len(list1) > 0 { os.Setenv("NAMESPACE", "")
t.Errorf("Expected len to be 0, got %v", len(list1)) getBaseNamespace := GetBaseNamespace()
if getBaseNamespace != defaultNamespace {
t.Errorf("Expected namespace to be %s, got %s", defaultNamespace, getBaseNamespace)
} }
} }
func TestGetBaseNamespace(t *testing.T) { func TestGetBaseNamespace(t *testing.T) {
defer os.Unsetenv("NAMESPACE") 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") os.Setenv("NAMESPACE", "foo")
getBaseNamespace = GetBaseNamespace() getBaseNamespace := GetBaseNamespace()
if getBaseNamespace != "foo" { if getBaseNamespace != "foo" {
t.Errorf("Expected namespace to be foo, got %v", getBaseNamespace) 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 ( import (
"fmt" "fmt"
"github.com/stackanetes/kubernetes-entrypoint/util/env"
"net" "net"
"os" "os"
"strings" "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 var iface string
if iface = os.Getenv("INTERFACE_NAME"); iface == "" { if iface = os.Getenv("INTERFACE_NAME"); iface == "" {
return "", fmt.Errorf("Environment variable INTERFACE_NAME not set") 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) return "", fmt.Errorf("Cannot get ip: %v", err)
} }
//Take first element to get rid of subnet //Take first element to get rid of subnet
ip = strings.Split(address[0].String(), "/")[0] ip := strings.Split(address[0].String(), "/")[0]
return return ip, nil
} }
func ContainsSeparator(envString string, kind string) bool { func ContainsSeparator(envString string, kind string) bool {
if strings.Contains(envString, env.Separator) { 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 true
} }
return false return false

View File

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