Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kubeadm added unit tests for pkg app/util #35231

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 12 additions & 2 deletions cmd/kubeadm/app/apis/kubeadm/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ import (
"strings"
)

var GlobalEnvParams = SetEnvParams()

// TODO(phase2) use componentconfig
// we need some params for testing etc, let's keep these hidden for now
func GetEnvParams() map[string]string {
func SetEnvParams() *EnvParams {

envParams := map[string]string{
// TODO(phase1+): Mode prefix and host_pki_path to another place as constants, and use them everywhere
Expand All @@ -45,5 +47,13 @@ func GetEnvParams() map[string]string {
}
}

return envParams
return &EnvParams{
KubernetesDir: envParams["kubernetes_dir"],
HostPKIPath: envParams["host_pki_path"],
HostEtcdPath: envParams["host_etcd_path"],
HyperkubeImage: envParams["hyperkube_image"],
DiscoveryImage: envParams["discovery_image"],
EtcdImage: envParams["etcd_image"],
ComponentLoglevel: envParams["component_loglevel"],
}
}
10 changes: 10 additions & 0 deletions cmd/kubeadm/app/apis/kubeadm/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@ package kubeadm

import "k8s.io/kubernetes/pkg/api/unversioned"

type EnvParams struct {
KubernetesDir string
HostPKIPath string
HostEtcdPath string
HyperkubeImage string
DiscoveryImage string
EtcdImage string
ComponentLoglevel string
}

type MasterConfiguration struct {
unversioned.TypeMeta

Expand Down
5 changes: 2 additions & 3 deletions cmd/kubeadm/app/master/addons.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,12 @@ import (
)

func createKubeProxyPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec {
envParams := kubeadmapi.GetEnvParams()
privilegedTrue := true
return api.PodSpec{
SecurityContext: &api.PodSecurityContext{HostNetwork: true},
Containers: []api.Container{{
Name: kubeProxy,
Image: images.GetCoreImage(images.KubeProxyImage, cfg, envParams["hyperkube_image"]),
Image: images.GetCoreImage(images.KubeProxyImage, cfg, kubeadmapi.GlobalEnvParams.HyperkubeImage),
Command: append(getProxyCommand(cfg), "--kubeconfig=/run/kubeconfig"),
SecurityContext: &api.SecurityContext{Privileged: &privilegedTrue},
VolumeMounts: []api.VolumeMount{
Expand Down Expand Up @@ -67,7 +66,7 @@ func createKubeProxyPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec {
{
Name: "kubeconfig",
VolumeSource: api.VolumeSource{
HostPath: &api.HostPathVolumeSource{Path: path.Join(envParams["kubernetes_dir"], "kubelet.conf")},
HostPath: &api.HostPathVolumeSource{Path: path.Join(kubeadmapi.GlobalEnvParams.KubernetesDir, "kubelet.conf")},
},
},
{
Expand Down
3 changes: 1 addition & 2 deletions cmd/kubeadm/app/master/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ func encodeKubeDiscoverySecretData(cfg *kubeadmapi.MasterConfiguration, caCert *
}

func newKubeDiscoveryPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec {
envParams := kubeadmapi.GetEnvParams()
return api.PodSpec{
// We have to use host network namespace, as `HostPort`/`HostIP` are Docker's
// buisness and CNI support isn't quite there yet (except for kubenet)
Expand All @@ -70,7 +69,7 @@ func newKubeDiscoveryPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec {
SecurityContext: &api.PodSecurityContext{HostNetwork: true},
Containers: []api.Container{{
Name: kubeDiscoveryName,
Image: envParams["discovery_image"],
Image: kubeadmapi.GlobalEnvParams.DiscoveryImage,
Command: []string{"/usr/local/bin/kube-discovery"},
VolumeMounts: []api.VolumeMount{{
Name: kubeDiscoverySecretName,
Expand Down
22 changes: 9 additions & 13 deletions cmd/kubeadm/app/master/manifests.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,28 +54,27 @@ const (
// WriteStaticPodManifests builds manifest objects based on user provided configuration and then dumps it to disk
// where kubelet will pick and schedule them.
func WriteStaticPodManifests(cfg *kubeadmapi.MasterConfiguration) error {
envParams := kubeadmapi.GetEnvParams()
// Prepare static pod specs
staticPodSpecs := map[string]api.Pod{
kubeAPIServer: componentPod(api.Container{
Name: kubeAPIServer,
Image: images.GetCoreImage(images.KubeAPIServerImage, cfg, envParams["hyperkube_image"]),
Image: images.GetCoreImage(images.KubeAPIServerImage, cfg, kubeadmapi.GlobalEnvParams.HyperkubeImage),
Command: getAPIServerCommand(cfg),
VolumeMounts: []api.VolumeMount{certsVolumeMount(), k8sVolumeMount()},
LivenessProbe: componentProbe(8080, "/healthz"),
Resources: componentResources("250m"),
}, certsVolume(cfg), k8sVolume(cfg)),
kubeControllerManager: componentPod(api.Container{
Name: kubeControllerManager,
Image: images.GetCoreImage(images.KubeControllerManagerImage, cfg, envParams["hyperkube_image"]),
Image: images.GetCoreImage(images.KubeControllerManagerImage, cfg, kubeadmapi.GlobalEnvParams.HyperkubeImage),
Command: getControllerManagerCommand(cfg),
VolumeMounts: []api.VolumeMount{certsVolumeMount(), k8sVolumeMount()},
LivenessProbe: componentProbe(10252, "/healthz"),
Resources: componentResources("200m"),
}, certsVolume(cfg), k8sVolume(cfg)),
kubeScheduler: componentPod(api.Container{
Name: kubeScheduler,
Image: images.GetCoreImage(images.KubeSchedulerImage, cfg, envParams["hyperkube_image"]),
Image: images.GetCoreImage(images.KubeSchedulerImage, cfg, kubeadmapi.GlobalEnvParams.HyperkubeImage),
Command: getSchedulerCommand(cfg),
LivenessProbe: componentProbe(10251, "/healthz"),
Resources: componentResources("100m"),
Expand All @@ -93,7 +92,7 @@ func WriteStaticPodManifests(cfg *kubeadmapi.MasterConfiguration) error {
"--data-dir=/var/etcd/data",
},
VolumeMounts: []api.VolumeMount{certsVolumeMount(), etcdVolumeMount(), k8sVolumeMount()},
Image: images.GetCoreImage(images.KubeEtcdImage, cfg, envParams["etcd_image"]),
Image: images.GetCoreImage(images.KubeEtcdImage, cfg, kubeadmapi.GlobalEnvParams.EtcdImage),
LivenessProbe: componentProbe(2379, "/health"),
Resources: componentResources("200m"),
SecurityContext: &api.SecurityContext{
Expand All @@ -108,7 +107,7 @@ func WriteStaticPodManifests(cfg *kubeadmapi.MasterConfiguration) error {
}, certsVolume(cfg), etcdVolume(cfg), k8sVolume(cfg))
}

manifestsPath := path.Join(envParams["kubernetes_dir"], "manifests")
manifestsPath := path.Join(kubeadmapi.GlobalEnvParams.KubernetesDir, "manifests")
if err := os.MkdirAll(manifestsPath, 0700); err != nil {
return fmt.Errorf("<master/manifests> failed to create directory %q [%v]", manifestsPath, err)
}
Expand All @@ -127,11 +126,10 @@ func WriteStaticPodManifests(cfg *kubeadmapi.MasterConfiguration) error {

// etcdVolume exposes a path on the host in order to guarantee data survival during reboot.
func etcdVolume(cfg *kubeadmapi.MasterConfiguration) api.Volume {
envParams := kubeadmapi.GetEnvParams()
return api.Volume{
Name: "etcd",
VolumeSource: api.VolumeSource{
HostPath: &api.HostPathVolumeSource{Path: envParams["host_etcd_path"]},
HostPath: &api.HostPathVolumeSource{Path: kubeadmapi.GlobalEnvParams.HostEtcdPath},
},
}
}
Expand Down Expand Up @@ -162,11 +160,10 @@ func certsVolumeMount() api.VolumeMount {
}

func k8sVolume(cfg *kubeadmapi.MasterConfiguration) api.Volume {
envParams := kubeadmapi.GetEnvParams()
return api.Volume{
Name: "pki",
VolumeSource: api.VolumeSource{
HostPath: &api.HostPathVolumeSource{Path: envParams["kubernetes_dir"]},
HostPath: &api.HostPathVolumeSource{Path: kubeadmapi.GlobalEnvParams.KubernetesDir},
},
}
}
Expand Down Expand Up @@ -222,13 +219,12 @@ func componentPod(container api.Container, volumes ...api.Volume) api.Pod {
}

func getComponentBaseCommand(component string) (command []string) {
envParams := kubeadmapi.GetEnvParams()
if envParams["hyperkube_image"] != "" {
if kubeadmapi.GlobalEnvParams.HyperkubeImage != "" {
command = []string{"/hyperkube", component}
} else {
command = []string{"kube-" + component}
}
command = append(command, envParams["component_loglevel"])
command = append(command, kubeadmapi.GlobalEnvParams.ComponentLoglevel)
return
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/kubeadm/app/master/pki.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ func CreatePKIAssets(cfg *kubeadmapi.MasterConfiguration) (*rsa.PrivateKey, *x50
}
altNames.DNSNames = append(altNames.DNSNames, cfg.API.ExternalDNSNames...)

pkiPath := path.Join(kubeadmapi.GetEnvParams()["host_pki_path"])
pkiPath := path.Join(kubeadmapi.GlobalEnvParams.HostPKIPath)

caKey, caCert, err := newCertificateAuthority()
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions cmd/kubeadm/app/master/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ func generateTokenIfNeeded(s *kubeadmapi.Secrets) error {
}

func CreateTokenAuthFile(s *kubeadmapi.Secrets) error {
tokenAuthFilePath := path.Join(kubeadmapi.GetEnvParams()["host_pki_path"], "tokens.csv")
tokenAuthFilePath := path.Join(kubeadmapi.GlobalEnvParams.HostPKIPath, "tokens.csv")
if err := generateTokenIfNeeded(s); err != nil {
return fmt.Errorf("<master/tokens> failed to generate token(s) [%v]", err)
}
if err := os.MkdirAll(kubeadmapi.GetEnvParams()["host_pki_path"], 0700); err != nil {
return fmt.Errorf("<master/tokens> failed to create directory %q [%v]", kubeadmapi.GetEnvParams()["host_pki_path"], err)
if err := os.MkdirAll(kubeadmapi.GlobalEnvParams.HostPKIPath, 0700); err != nil {
return fmt.Errorf("<master/tokens> failed to create directory %q [%v]", kubeadmapi.GlobalEnvParams.HostPKIPath, err)
}
serialized := []byte(fmt.Sprintf("%s,kubeadm-node-csr,%s,system:kubelet-bootstrap\n", s.BearerToken, uuid.NewUUID()))
// DumpReaderToFile create a file with mode 0600
Expand Down
12 changes: 10 additions & 2 deletions cmd/kubeadm/app/util/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,16 @@ go_library(

go_test(
name = "go_default_test",
srcs = ["tokens_test.go"],
srcs = [
"error_test.go",
"kubeconfig_test.go",
"tokens_test.go",
],
library = "go_default_library",
tags = ["automanaged"],
deps = ["//cmd/kubeadm/app/apis/kubeadm:go_default_library"],
deps = [
"//cmd/kubeadm/app/apis/kubeadm:go_default_library",
"//cmd/kubeadm/app/preflight:go_default_library",
"//pkg/client/unversioned/clientcmd/api:go_default_library",
],
)
52 changes: 52 additions & 0 deletions cmd/kubeadm/app/util/error_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
Copyright 2016 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package util

import (
"fmt"
"testing"

"k8s.io/kubernetes/cmd/kubeadm/app/preflight"
)

func TestCheckErr(t *testing.T) {
var codeReturned int
errHandle := func(err string, code int) {
codeReturned = code
}

var tokenTest = []struct {
e error
expected int
}{
{nil, 0},
{fmt.Errorf(""), DefaultErrorExitCode},
{&preflight.PreFlightError{}, PreFlight},
}

for _, rt := range tokenTest {
codeReturned = 0
checkErr("", rt.e, errHandle)
if codeReturned != rt.expected {
t.Errorf(
"failed checkErr:\n\texpected: %d\n\t actual: %d",
rt.expected,
codeReturned,
)
}
}
}
7 changes: 3 additions & 4 deletions cmd/kubeadm/app/util/kubeconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,11 @@ func MakeClientConfigWithToken(config *clientcmdapi.Config, clusterName string,
}

func WriteKubeconfigIfNotExists(name string, kubeconfig *clientcmdapi.Config) error {
envParams := kubeadmapi.GetEnvParams()
if err := os.MkdirAll(envParams["kubernetes_dir"], 0700); err != nil {
return fmt.Errorf("<util/kubeconfig> failed to create directory %q [%v]", envParams["kubernetes_dir"], err)
if err := os.MkdirAll(kubeadmapi.GlobalEnvParams.KubernetesDir, 0700); err != nil {
return fmt.Errorf("<util/kubeconfig> failed to create directory %q [%v]", kubeadmapi.GlobalEnvParams.KubernetesDir, err)
}

filename := path.Join(envParams["kubernetes_dir"], fmt.Sprintf("%s.conf", name))
filename := path.Join(kubeadmapi.GlobalEnvParams.KubernetesDir, fmt.Sprintf("%s.conf", name))
// Create and open the file, only if it does not already exist.
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600)
if err != nil {
Expand Down