Пример #1
0
func TestCNIPlugin(t *testing.T) {
	// install some random plugin
	pluginName := fmt.Sprintf("test%d", rand.Intn(1000))
	vendorName := fmt.Sprintf("test_vendor%d", rand.Intn(1000))

	tmpDir := utiltesting.MkTmpdirOrDie("cni-test")
	testNetworkConfigPath := path.Join(tmpDir, "plugins", "net", "cni")
	testVendorCNIDirPrefix := tmpDir
	defer tearDownPlugin(tmpDir)
	installPluginUnderTest(t, testVendorCNIDirPrefix, testNetworkConfigPath, vendorName, pluginName)

	np := probeNetworkPluginsWithVendorCNIDirPrefix(path.Join(testNetworkConfigPath, pluginName), testVendorCNIDirPrefix)
	plug, err := network.InitNetworkPlugin(np, "cni", NewFakeHost(nil), componentconfig.HairpinNone)
	if err != nil {
		t.Fatalf("Failed to select the desired plugin: %v", err)
	}

	err = plug.SetUpPod("podNamespace", "podName", kubecontainer.ContainerID{Type: "docker", ID: "test_infra_container"})
	if err != nil {
		t.Errorf("Expected nil: %v", err)
	}
	outputEnv := path.Join(testNetworkConfigPath, pluginName, pluginName+".env")
	eo, eerr := ioutil.ReadFile(outputEnv)
	outputFile := path.Join(testNetworkConfigPath, pluginName, pluginName+".out")
	output, err := ioutil.ReadFile(outputFile)
	if err != nil {
		t.Errorf("Failed to read output file %s: %v (env %s err %v)", outputFile, err, eo, eerr)
	}
	expectedOutput := "ADD /proc/12345/ns/net podNamespace podName test_infra_container"
	if string(output) != expectedOutput {
		t.Errorf("Mismatch in expected output for setup hook. Expected '%s', got '%s'", expectedOutput, string(output))
	}
	err = plug.TearDownPod("podNamespace", "podName", kubecontainer.ContainerID{Type: "docker", ID: "test_infra_container"})
	if err != nil {
		t.Errorf("Expected nil: %v", err)
	}
	output, err = ioutil.ReadFile(path.Join(testNetworkConfigPath, pluginName, pluginName+".out"))
	expectedOutput = "DEL /proc/12345/ns/net podNamespace podName test_infra_container"
	if string(output) != expectedOutput {
		t.Errorf("Mismatch in expected output for setup hook. Expected '%s', got '%s'", expectedOutput, string(output))
	}
}
Пример #2
0
func TestSavePodToFile(t *testing.T) {
	pod := volume.NewPersistentVolumeRecyclerPodTemplate()

	// sets all default values on a pod for equality comparison after decoding from file
	codec := api.Codecs.LegacyCodec(registered.GroupOrDie(api.GroupName).GroupVersion)
	encoded, err := runtime.Encode(codec, pod)
	runtime.DecodeInto(codec, encoded, pod)

	tmpDir := utiltesting.MkTmpdirOrDie("kube-io-test")
	defer os.RemoveAll(tmpDir)
	path := fmt.Sprintf("/%s/kube-io-test-%s", tmpDir, uuid.New())

	if err := io.SavePodToFile(pod, path, 777); err != nil {
		t.Fatalf("failed to save pod to file: %v", err)
	}

	podFromFile, err := io.LoadPodFromFile(path)
	if err != nil {
		t.Fatalf("failed to load pod from file: %v", err)
	}
	if !api.Semantic.DeepEqual(pod, podFromFile) {
		t.Errorf("\nexpected %#v\ngot	%#v\n", pod, podFromFile)
	}
}
Пример #3
0
func NewFakeDiskManager() *fakeDiskManager {
	return &fakeDiskManager{
		tmpDir: utiltesting.MkTmpdirOrDie("fc_test"),
	}
}
Пример #4
0
func TestCNIPlugin(t *testing.T) {
	// install some random plugin
	pluginName := fmt.Sprintf("test%d", rand.Intn(1000))
	vendorName := fmt.Sprintf("test_vendor%d", rand.Intn(1000))

	podIP := "10.0.0.2"
	podIPOutput := fmt.Sprintf("4: eth0    inet %s/24 scope global dynamic eth0\\       valid_lft forever preferred_lft forever", podIP)
	fakeCmds := []utilexec.FakeCommandAction{
		func(cmd string, args ...string) utilexec.Cmd {
			return utilexec.InitFakeCmd(&utilexec.FakeCmd{
				CombinedOutputScript: []utilexec.FakeCombinedOutputAction{
					func() ([]byte, error) {
						return []byte(podIPOutput), nil
					},
				},
			}, cmd, args...)
		},
	}

	fexec := &utilexec.FakeExec{
		CommandScript: fakeCmds,
		LookPathFunc: func(file string) (string, error) {
			return fmt.Sprintf("/fake-bin/%s", file), nil
		},
	}

	mockLoCNI := &mock_cni.MockCNI{}
	// TODO mock for the test plugin too

	tmpDir := utiltesting.MkTmpdirOrDie("cni-test")
	testNetworkConfigPath := path.Join(tmpDir, "plugins", "net", "cni")
	testVendorCNIDirPrefix := tmpDir
	defer tearDownPlugin(tmpDir)
	installPluginUnderTest(t, testVendorCNIDirPrefix, testNetworkConfigPath, vendorName, pluginName)

	containerID := kubecontainer.ContainerID{Type: "test", ID: "test_infra_container"}
	pods := []*containertest.FakePod{{
		Pod: &kubecontainer.Pod{
			Containers: []*kubecontainer.Container{
				{ID: containerID},
			},
		},
		NetnsPath: "/proc/12345/ns/net",
	}}

	plugins := probeNetworkPluginsWithVendorCNIDirPrefix(path.Join(testNetworkConfigPath, pluginName), "", testVendorCNIDirPrefix)
	if len(plugins) != 1 {
		t.Fatalf("Expected only one network plugin, got %d", len(plugins))
	}
	if plugins[0].Name() != "cni" {
		t.Fatalf("Expected CNI network plugin, got %q", plugins[0].Name())
	}

	cniPlugin, ok := plugins[0].(*cniNetworkPlugin)
	if !ok {
		t.Fatalf("Not a CNI network plugin!")
	}
	cniPlugin.execer = fexec
	cniPlugin.loNetwork.CNIConfig = mockLoCNI

	mockLoCNI.On("AddNetwork", cniPlugin.loNetwork.NetworkConfig, mock.AnythingOfType("*libcni.RuntimeConf")).Return(&cnitypes.Result{IP4: &cnitypes.IPConfig{IP: net.IPNet{IP: []byte{127, 0, 0, 1}}}}, nil)

	plug, err := network.InitNetworkPlugin(plugins, "cni", NewFakeHost(nil, pods), componentconfig.HairpinNone, "10.0.0.0/8", network.UseDefaultMTU)
	if err != nil {
		t.Fatalf("Failed to select the desired plugin: %v", err)
	}

	// Set up the pod
	err = plug.SetUpPod("podNamespace", "podName", containerID)
	if err != nil {
		t.Errorf("Expected nil: %v", err)
	}
	outputEnv := path.Join(testNetworkConfigPath, pluginName, pluginName+".env")
	eo, eerr := ioutil.ReadFile(outputEnv)
	outputFile := path.Join(testNetworkConfigPath, pluginName, pluginName+".out")
	output, err := ioutil.ReadFile(outputFile)
	if err != nil {
		t.Errorf("Failed to read output file %s: %v (env %s err %v)", outputFile, err, eo, eerr)
	}
	expectedOutput := "ADD /proc/12345/ns/net podNamespace podName test_infra_container"
	if string(output) != expectedOutput {
		t.Errorf("Mismatch in expected output for setup hook. Expected '%s', got '%s'", expectedOutput, string(output))
	}

	// Get its IP address
	status, err := plug.GetPodNetworkStatus("podNamespace", "podName", containerID)
	if err != nil {
		t.Errorf("Failed to read pod network status: %v", err)
	}
	if status.IP.String() != podIP {
		t.Errorf("Expected pod IP %q but got %q", podIP, status.IP.String())
	}

	// Tear it down
	err = plug.TearDownPod("podNamespace", "podName", containerID)
	if err != nil {
		t.Errorf("Expected nil: %v", err)
	}
	output, err = ioutil.ReadFile(path.Join(testNetworkConfigPath, pluginName, pluginName+".out"))
	expectedOutput = "DEL /proc/12345/ns/net podNamespace podName test_infra_container"
	if string(output) != expectedOutput {
		t.Errorf("Mismatch in expected output for setup hook. Expected '%s', got '%s'", expectedOutput, string(output))
	}

	mockLoCNI.AssertExpectations(t)
}
Пример #5
0
func TestSecretForTLSGenerate(t *testing.T) {
	invalidCertTmpDir := utiltesting.MkTmpdirOrDie("tls-test")
	defer tearDown(invalidCertTmpDir)
	invalidKeyPath, invalidCertPath := writeKeyPair(invalidCertTmpDir, "test", "test", t)

	validCertTmpDir := utiltesting.MkTmpdirOrDie("tls-test")
	defer tearDown(validCertTmpDir)
	validKeyPath, validCertPath := writeKeyPair(validCertTmpDir, rsaKeyPEM, rsaCertPEM, t)

	mismatchCertTmpDir := utiltesting.MkTmpdirOrDie("tls-mismatch-test")
	defer tearDown(mismatchCertTmpDir)
	mismatchKeyPath, mismatchCertPath := writeKeyPair(mismatchCertTmpDir, mismatchRSAKeyPEM, rsaCertPEM, t)

	tests := map[string]struct {
		params    map[string]interface{}
		expected  *api.Secret
		expectErr bool
	}{
		"test-valid-tls-secret": {
			params: map[string]interface{}{
				"name": "foo",
				"key":  validKeyPath,
				"cert": validCertPath,
			},
			expected: &api.Secret{
				ObjectMeta: api.ObjectMeta{
					Name: "foo",
				},
				Data: map[string][]byte{
					api.TLSCertKey:       []byte(rsaCertPEM),
					api.TLSPrivateKeyKey: []byte(rsaKeyPEM),
				},
				Type: api.SecretTypeTLS,
			},
			expectErr: false,
		},
		"test-invalid-key-pair": {
			params: map[string]interface{}{
				"name": "foo",
				"key":  invalidKeyPath,
				"cert": invalidCertPath,
			},
			expected: &api.Secret{
				ObjectMeta: api.ObjectMeta{
					Name: "foo",
				},
				Data: map[string][]byte{
					api.TLSCertKey:       []byte("test"),
					api.TLSPrivateKeyKey: []byte("test"),
				},
				Type: api.SecretTypeTLS,
			},
			expectErr: true,
		},
		"test-mismatched-key-pair": {
			params: map[string]interface{}{
				"name": "foo",
				"key":  mismatchKeyPath,
				"cert": mismatchCertPath,
			},
			expected: &api.Secret{
				ObjectMeta: api.ObjectMeta{
					Name: "foo",
				},
				Data: map[string][]byte{
					api.TLSCertKey:       []byte(rsaCertPEM),
					api.TLSPrivateKeyKey: []byte(mismatchRSAKeyPEM),
				},
				Type: api.SecretTypeTLS,
			},
			expectErr: true,
		},
		"test-missing-required-param": {
			params: map[string]interface{}{
				"name": "foo",
				"key":  "/tmp/foo.key",
			},
			expectErr: true,
		},
	}

	generator := SecretForTLSGeneratorV1{}
	for _, test := range tests {
		obj, err := generator.Generate(test.params)
		if !test.expectErr && err != nil {
			t.Errorf("unexpected error: %v", err)
		}
		if test.expectErr && err != nil {
			continue
		}
		if !reflect.DeepEqual(obj.(*api.Secret), test.expected) {
			t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*api.Secret))
		}
	}
}