func fetchStreamingResponse(t *check.C, url string) (*http.Response, string) {
	// Create temp file for this unit test.
	tmpFile, err := ioutil.TempFile("", "testfile_")
	if err != nil {
		t.Error(err)
	}

	err = tmpFile.Close()
	if err != nil {
		t.Error(err)
	}

	responseBody := []byte(fmt.Sprintf(`{"instance_path": "%s"}`, tmpFile.Name()))
	fc := func(w http.ResponseWriter, r *http.Request) {
		w.Write(responseBody)
	}

	lc, hc, pc := startTestServer(http.HandlerFunc(fc))
	defer lc.Close()

	h := handler{
		deaHost:          hc,
		deaPort:          pc,
		streamingTimeout: 1,
		deaClient:        &DeaClient{Host: hc, Port: pc},
	}

	ld, hd, pd := startTestServer(h)
	defer ld.Close()

	// Start writing content to the temp file in a separate thread.
	go dump(tmpFile, t, 10) // thread.
	time.Sleep(1 * time.Second)

	response, err := http.Get(fmt.Sprintf("http://%s:%d%s", hd, pd, url))
	if err != nil {
		t.Error(err)
	}

	body := make([]byte, 100)
	_, err = response.Body.Read(body)
	if err != nil {
		// If no data comes through before timeout expires
		// stream handler will just close the connection
		// causing EOF error which is ok.
		if err != io.EOF && err != io.ErrUnexpectedEOF {
			t.Error(err)
		}
	}

	if err = os.Remove(tmpFile.Name()); err != nil {
		t.Error(err)
	}

	return response, string(body)
}
Beispiel #2
0
func (s *MySuite) SetUpTest(c *check.C) {
	dir, _ := os.Getwd()
	c.Log("Entering setup in directory", dir)

	common.MockPortsInConfig("../common/testdata/romana.sample.yaml")
	s.configFile = "/tmp/romana.yaml"
	var err error
	s.config, err = common.ReadConfig(s.configFile)
	if err != nil {
		panic(err)
	}

	c.Log("Root configuration: ", s.config.Services["root"].Common.Api.GetHostPort())

	// Starting root service
	fmt.Println("STARTING ROOT SERVICE")
	channelRoot, addr, err := root.Run(s.configFile)
	if err != nil {
		c.Error(err)
	}
	s.rootUrl = "http://" + addr
	c.Log("Root URL:", s.rootUrl)

	msg := <-channelRoot
	c.Log("Root service said:", msg)
	c.Log("Waiting a bit...")
	time.Sleep(time.Second)
	c.Log("Creating topology schema with root URL", s.rootUrl)

	err = topology.CreateSchema(s.rootUrl, true)
	if err != nil {
		c.Fatal(err)
	}
	c.Log("OK")

	c.Log("Creating tenant schema")
	err = tenant.CreateSchema(s.rootUrl, true)
	if err != nil {
		c.Fatal(err)
	}
	c.Log("OK")

	c.Log("Creating IPAM schema")
	err = ipam.CreateSchema(s.rootUrl, true)
	if err != nil {
		c.Fatal(err)
	}
	c.Log("OK")

	myLog(c, "Done with setup")

}
func dump(file *os.File, t *check.C, numLines int) error {
	handle, err := os.OpenFile(file.Name(), syscall.O_WRONLY, 0666)
	if err != nil {
		t.Error(err)
	}

	for i := 0; i < numLines; i++ {
		_, err = handle.WriteString(fmt.Sprintf("blah%d", i))
		if err != nil {
			t.Error(err)
		}
		time.Sleep(250 * time.Millisecond)
	}

	err = handle.Close()
	return err
}
func (s *DirectoryServerSuite) TestHandler_ServeHTTP_EntityNotFound(t *check.C) {
	responseBody := []byte("{\"instance_path\" : \"dummy\"}")
	fc := func(w http.ResponseWriter, r *http.Request) {
		w.Write(responseBody)
	}

	lc, hc, pc := startTestServer(http.HandlerFunc(fc))
	defer lc.Close()

	h := handler{
		deaHost:          hc,
		deaPort:          pc,
		streamingTimeout: 1,
		deaClient:        &DeaClient{Host: hc, Port: pc},
	}

	ld, hd, pd := startTestServer(h)
	defer ld.Close()

	response, err := http.Get(fmt.Sprintf("http://%s:%d/path", hd, pd))
	if err != nil {
		t.Error(err)
	}

	// Check status code.
	if response.StatusCode != 400 {
		t.Fail()
	}

	// Check headers.
	if response.Header.Get("Content-Type") != "text/plain" {
		t.Fail()
	}
	if response.Header.Get("X-Cascade") != "pass" {
		t.Fail()
	}

	// Check body.
	body, err := getBody(response)
	if err != nil {
		t.Error(err)
	}
	if strings.ToLower(string(body)) != "entity not found.\n" {
		t.Fail()
	}
}
func assertPortList(c *check.C, out string, expected []string) bool {
	//lines := strings.Split(out, "\n")
	lines := strings.Split(strings.Trim(out, "\n "), "\n")
	if len(lines) != len(expected) {
		c.Errorf("different size lists %s, %d, %d", out, len(lines), len(expected))
		return false
	}
	sort.Strings(lines)
	sort.Strings(expected)

	for i := 0; i < len(expected); i++ {
		if lines[i] != expected[i] {
			c.Error("|" + lines[i] + "!=" + expected[i] + "|")
			return false
		}
	}

	return true
}
func (s *DockerSuite) TestPortHostBinding(c *check.C) {
	out, _ := dockerCmd(c, "run", "-d", "-p", "9876:80", "busybox",
		"nc", "-l", "-p", "80")
	firstID := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "port", firstID, "80")

	if !assertPortList(c, out, []string{"0.0.0.0:9876"}) {
		c.Error("Port list is not correct")
	}

	dockerCmd(c, "run", "--net=host", "busybox",
		"nc", "localhost", "9876")

	dockerCmd(c, "rm", "-f", firstID)

	if _, _, err := dockerCmdWithError("run", "--net=host", "busybox",
		"nc", "localhost", "9876"); err == nil {
		c.Error("Port is still bound after the Container is removed")
	}
}
func (s *DirectoryServerSuite) TestHandler_ServeHTTP_RequestDeniedByDea(t *check.C) {
	responseBody := []byte("{\"instance_path\" : \"dummy\"}")
	fc := func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusBadRequest)
		w.Write(responseBody)
	}

	lc, hc, pc := startTestServer(http.HandlerFunc(fc))
	defer lc.Close()

	h := handler{
		deaHost:          hc,
		deaPort:          pc,
		streamingTimeout: 1,
		deaClient:        &DeaClient{Host: hc, Port: pc},
	}

	ld, hd, pd := startTestServer(h)
	defer ld.Close()

	response, err := http.Get(fmt.Sprintf("http://%s:%d/path", hd, pd))
	if err != nil {
		t.Error(err)
	}

	// Check status code.
	if response.StatusCode != 400 {
		t.Fail()
	}

	// Check body.
	body, err := getBody(response)
	if err != nil {
		t.Error(err)
	}
	if bytes.Compare(body, responseBody) != 0 {
		t.Fail()
	}
}
func (s *DockerSuite) TestExecWindowsOpenHandles(c *check.C) {
	testRequires(c, DaemonIsWindows)
	runSleepingContainer(c, "-d", "--name", "test")
	exec := make(chan bool)
	go func() {
		dockerCmd(c, "exec", "test", "cmd", "/c", "start sleep 10")
		exec <- true
	}()

	for {
		top := make(chan string)
		var out string
		go func() {
			out, _ := dockerCmd(c, "top", "test")
			top <- out
		}()

		select {
		case <-time.After(time.Second * 5):
			c.Error("timed out waiting for top while exec is exiting")
		case out = <-top:
			break
		}

		if strings.Count(out, "busybox.exe") == 2 && !strings.Contains(out, "cmd.exe") {
			// The initial exec process (cmd.exe) has exited, and both sleeps are currently running
			break
		}
		time.Sleep(1 * time.Second)
	}

	inspect := make(chan bool)
	go func() {
		dockerCmd(c, "inspect", "test")
		inspect <- true
	}()

	select {
	case <-time.After(time.Second * 5):
		c.Error("timed out waiting for inspect while exec is exiting")
	case <-inspect:
		break
	}

	// Ensure the background sleep is still running
	out, _ := dockerCmd(c, "top", "test")
	c.Assert(strings.Count(out, "busybox.exe"), checker.Equals, 2)

	// The exec should exit when the background sleep exits
	select {
	case <-time.After(time.Second * 15):
		c.Error("timed out waiting for async exec to exit")
	case <-exec:
		// Ensure the background sleep has actually exited
		out, _ := dockerCmd(c, "top", "test")
		c.Assert(strings.Count(out, "busybox.exe"), checker.Equals, 1)
		break
	}
}
Beispiel #9
0
func (s *MySuite) SetUpTest(c *check.C) {

	myLog(c, "Entering SetUP, services started: ", s.servicesStarted)
	if !s.servicesStarted {
		dir, _ := os.Getwd()
		myLog(c, "Entering setup in directory", dir)
		var err error
		err = s.RomanaTestSuite.MockConfig(common.DefaultTestConfigFile)
		if err != nil {
			panic(err)
		}

		myLog(c, "Root configuration: ", s.RomanaTestSuite.Config.Services["root"].Common.Api.GetHostPort())
		root.Run(s.RomanaTestSuite.ConfigFile)

		// Starting root service
		myLog(c, "Starting root service...")
		svcInfo, err := root.Run(s.RomanaTestSuite.ConfigFile)
		if err != nil {
			c.Error(err)
		}
		s.rootURL = "http://" + svcInfo.Address
		myLog(c, "Root URL:", s.rootURL)

		msg := <-svcInfo.Channel
		myLog(c, "Root service said:", msg)

		myLog(c, "Creating topology schema")
		topoSvc := &TopologySvc{}
		err = common.SimpleOverwriteSchema(topoSvc, s.rootURL)
		myLog(c, "CreateSchema returned err: ", err, "which is of type", reflect.TypeOf(err), "let's compare it to", nil, ": err != nil: ", err != nil)
		if err != nil {
			c.Fatal(err)
		}
		s.servicesStarted = true
		myLog(c, "Done with setup")
	}
}
Beispiel #10
0
func (s *MySuite) SetUpTest(c *check.C) {
	myLog(c, "Entering SetUP, services started: ", s.servicesStarted)
	if !s.servicesStarted {
		dir, _ := os.Getwd()
		myLog(c, "Entering setup in directory", dir)
		common.MockPortsInConfig("../common/testdata/romana.sample.yaml")
		s.configFile = "/tmp/romana.yaml"
		var err error
		s.config, err = common.ReadConfig(s.configFile)
		if err != nil {
			panic(err)
		}

		myLog(c, "Root configuration: ", s.config.Services["root"].Common.Api.GetHostPort())
		root.Run(s.configFile)

		// Starting root service
		myLog(c, "Starting root service...")
		channelRoot, addr, err := root.Run(s.configFile)
		if err != nil {
			c.Error(err)
		}
		s.rootUrl = "http://" + addr
		myLog(c, "Root URL:", s.rootUrl)

		msg := <-channelRoot
		myLog(c, "Root service said:", msg)

		myLog(c, "Creating topology schema")
		err = CreateSchema(s.rootUrl, true)
		myLog(c, "CreateSchema returned err: ", err, "which is of type", reflect.TypeOf(err), "let's compare it to", nil, ": err != nil: ", err != nil)
		if err != nil {
			c.Fatal(err)
		}
		s.servicesStarted = true
		myLog(c, "Done with setup")
	}
}
func (s *DockerSuite) TestPortExposeHostBinding(c *check.C) {
	runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--expose", "80", "busybox",
		"nc", "-l", "-p", "80")
	out, _, err := runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}
	firstID := strings.TrimSpace(out)

	runCmd = exec.Command(dockerBinary, "port", firstID, "80")
	out, _, err = runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	_, exposedPort, err := net.SplitHostPort(out)

	if err != nil {
		c.Fatal(out, err)
	}

	runCmd = exec.Command(dockerBinary, "run", "--net=host", "busybox",
		"nc", "localhost", strings.TrimSpace(exposedPort))
	if out, _, err = runCommandWithOutput(runCmd); err != nil {
		c.Fatal(out, err)
	}

	runCmd = exec.Command(dockerBinary, "rm", "-f", firstID)
	if out, _, err = runCommandWithOutput(runCmd); err != nil {
		c.Fatal(out, err)
	}

	runCmd = exec.Command(dockerBinary, "run", "--net=host", "busybox",
		"nc", "localhost", strings.TrimSpace(exposedPort))
	if out, _, err = runCommandWithOutput(runCmd); err == nil {
		c.Error("Port is still bound after the Container is removed")
	}
}
Beispiel #12
0
// Test the topology service
func (s *MySuite) TestTopology(c *check.C) {
	myLog(c, "Entering TestTopology()")

	dir, _ := os.Getwd()
	myLog(c, "In", dir)
	myLog(c, "Starting topology service")

	channelTop, addr, err := Run(s.rootUrl)
	if err != nil {
		c.Error(err)
	}
	msg := <-channelTop
	myLog(c, "Topology service said:", msg)
	addr = "http://" + addr
	client, err := common.NewRestClient(addr, common.DefaultRestTimeout)
	if err != nil {
		c.Error(err)
	}
	myLog(c, "Calling ", addr)

	topIndex := &common.IndexResponse{}
	err = client.Get("/", &topIndex)
	if err != nil {
		c.Error(err)
	}

	c.Assert(topIndex.ServiceName, check.Equals, "topology")
	hostsRelUrl := topIndex.Links.FindByRel("host-list")
	hostsUrl := addr + hostsRelUrl
	myLog(c, "Host list URL: ", hostsUrl)

	// Get list of hosts - should be empty for now.
	var hostList []Host
	client.Get(hostsRelUrl, &hostList)
	myLog(c, "Host list: ", hostList)
	c.Assert(len(hostList), check.Equals, 0)
	newHostReq := common.HostMessage{Ip: "10.10.10.10", AgentPort: 9999, Name: "host10"}

	newHostResp := common.HostMessage{}
	client.Post(hostsRelUrl, newHostReq, &newHostResp)
	myLog(c, "Response: ", newHostResp)
	c.Assert(newHostResp.Ip, check.Equals, "10.10.10.10")
	c.Assert(newHostResp.Id, check.Equals, "1")

	newHostReq = common.HostMessage{Ip: "10.10.10.11", AgentPort: 9999, Name: "host11"}
	newHostResp = common.HostMessage{}
	client.Post(hostsRelUrl, newHostReq, &newHostResp)
	myLog(c, "Response: ", newHostResp)

	c.Assert(newHostResp.Ip, check.Equals, "10.10.10.11")
	c.Assert(newHostResp.Id, check.Equals, "2")

	var hostList2 []Host
	client.Get(hostsRelUrl, &hostList2)
	myLog(c, "Host list: ", hostList2)
	c.Assert(len(hostList2), check.Equals, 2)

}
func (s *DirectoryServerSuite) TestHandler_ServeHTTP_RequestToDeaFailed(t *check.C) {
	lc, hc, pc := startTestServer(http.NotFoundHandler())
	lc.Close()

	h := handler{
		deaHost:          hc,
		deaPort:          pc,
		streamingTimeout: 1,
		deaClient:        &DeaClient{Host: hc, Port: pc},
	}

	ld, hd, pd := startTestServer(h)
	defer ld.Close()

	response, err := http.Get(fmt.Sprintf("http://%s:%d/path", hd, pd))
	if err != nil {
		t.Error(err)
	}

	if response.StatusCode != 500 {
		t.Fail()
	}
}
Beispiel #14
0
// TestHostMarshaling tests marshaling/unmarshaling of Host
// structure to/from proper JSON.
func (s *MySuite) TestHostMarshaling(c *check.C) {
	host := common.Host{}
	host.ID = 1
	host.RomanaIp = "192.168.0.1/16"
	host.Ip = "10.1.1.1"
	host.Name = "host1"
	host.AgentPort = 9999
	m := common.ContentTypeMarshallers["application/json"]
	json, _ := m.Marshal(host)
	marshaledJSONStr := string(json)
	myLog(c, "Marshaled ", host, "to", marshaledJSONStr)
	expectedJSONStr := "{\"id\":1,\"name\":\"host1\",\"ip\":\"10.1.1.1\",\"romana_ip\":\"192.168.0.1/16\",\"agent_port\":9999}"
	c.Assert(marshaledJSONStr, check.Equals, expectedJSONStr)
	host2 := common.Host{}
	err := m.Unmarshal([]byte(expectedJSONStr), &host2)
	if err != nil {
		c.Error(err)
	}
	c.Assert(host2.ID, check.Equals, uint64(1))
	c.Assert(host2.Ip, check.Equals, "10.1.1.1")
	c.Assert(host2.RomanaIp, check.Equals, "192.168.0.1/16")
	c.Assert(host2.AgentPort, check.Equals, uint64(9999))
}
func (s *DockerSuite) TestPortExposeHostBinding(c *check.C) {
	out, _ := dockerCmd(c, "run", "-d", "-P", "--expose", "80", "busybox",
		"nc", "-l", "-p", "80")
	firstID := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "port", firstID, "80")

	_, exposedPort, err := net.SplitHostPort(out)

	if err != nil {
		c.Fatal(out, err)
	}

	dockerCmd(c, "run", "--net=host", "busybox",
		"nc", "localhost", strings.TrimSpace(exposedPort))

	dockerCmd(c, "rm", "-f", firstID)

	if _, _, err = dockerCmdWithError("run", "--net=host", "busybox",
		"nc", "localhost", strings.TrimSpace(exposedPort)); err == nil {
		c.Error("Port is still bound after the Container is removed")
	}
}
func (s *DockerSuite) TestPortHostBinding(c *check.C) {
	runCmd := exec.Command(dockerBinary, "run", "-d", "-p", "9876:80", "busybox",
		"nc", "-l", "-p", "80")
	out, _, err := runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}
	firstID := strings.TrimSpace(out)

	runCmd = exec.Command(dockerBinary, "port", firstID, "80")
	out, _, err = runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	if !assertPortList(c, out, []string{"0.0.0.0:9876"}) {
		c.Error("Port list is not correct")
	}

	runCmd = exec.Command(dockerBinary, "run", "--net=host", "busybox",
		"nc", "localhost", "9876")
	if out, _, err = runCommandWithOutput(runCmd); err != nil {
		c.Fatal(out, err)
	}

	runCmd = exec.Command(dockerBinary, "rm", "-f", firstID)
	if out, _, err = runCommandWithOutput(runCmd); err != nil {
		c.Fatal(out, err)
	}

	runCmd = exec.Command(dockerBinary, "run", "--net=host", "busybox",
		"nc", "localhost", "9876")
	if out, _, err = runCommandWithOutput(runCmd); err == nil {
		c.Error("Port is still bound after the Container is removed")
	}
}
func (s *DockerSuite) TestPortList(c *check.C) {

	// one port
	runCmd := exec.Command(dockerBinary, "run", "-d", "-p", "9876:80", "busybox", "top")
	out, _, err := runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}
	firstID := strings.TrimSpace(out)

	runCmd = exec.Command(dockerBinary, "port", firstID, "80")
	out, _, err = runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	if !assertPortList(c, out, []string{"0.0.0.0:9876"}) {
		c.Error("Port list is not correct")
	}

	runCmd = exec.Command(dockerBinary, "port", firstID)
	out, _, err = runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	if !assertPortList(c, out, []string{"80/tcp -> 0.0.0.0:9876"}) {
		c.Error("Port list is not correct")
	}
	runCmd = exec.Command(dockerBinary, "rm", "-f", firstID)
	if out, _, err = runCommandWithOutput(runCmd); err != nil {
		c.Fatal(out, err)
	}

	// three port
	runCmd = exec.Command(dockerBinary, "run", "-d",
		"-p", "9876:80",
		"-p", "9877:81",
		"-p", "9878:82",
		"busybox", "top")
	out, _, err = runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}
	ID := strings.TrimSpace(out)

	runCmd = exec.Command(dockerBinary, "port", ID, "80")
	out, _, err = runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	if !assertPortList(c, out, []string{"0.0.0.0:9876"}) {
		c.Error("Port list is not correct")
	}

	runCmd = exec.Command(dockerBinary, "port", ID)
	out, _, err = runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	if !assertPortList(c, out, []string{
		"80/tcp -> 0.0.0.0:9876",
		"81/tcp -> 0.0.0.0:9877",
		"82/tcp -> 0.0.0.0:9878"}) {
		c.Error("Port list is not correct")
	}
	runCmd = exec.Command(dockerBinary, "rm", "-f", ID)
	out, _, err = runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	// more and one port mapped to the same container port
	runCmd = exec.Command(dockerBinary, "run", "-d",
		"-p", "9876:80",
		"-p", "9999:80",
		"-p", "9877:81",
		"-p", "9878:82",
		"busybox", "top")
	out, _, err = runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}
	ID = strings.TrimSpace(out)

	runCmd = exec.Command(dockerBinary, "port", ID, "80")
	out, _, err = runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	if !assertPortList(c, out, []string{"0.0.0.0:9876", "0.0.0.0:9999"}) {
		c.Error("Port list is not correct")
	}

	runCmd = exec.Command(dockerBinary, "port", ID)
	out, _, err = runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	if !assertPortList(c, out, []string{
		"80/tcp -> 0.0.0.0:9876",
		"80/tcp -> 0.0.0.0:9999",
		"81/tcp -> 0.0.0.0:9877",
		"82/tcp -> 0.0.0.0:9878"}) {
		c.Error("Port list is not correct\n", out)
	}
	runCmd = exec.Command(dockerBinary, "rm", "-f", ID)
	if out, _, err = runCommandWithOutput(runCmd); err != nil {
		c.Fatal(out, err)
	}

}
func (s *DockerSuite) TestPortList(c *check.C) {
	testRequires(c, DaemonIsLinux)
	// one port
	out, _ := dockerCmd(c, "run", "-d", "-p", "9876:80", "busybox", "top")
	firstID := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "port", firstID, "80")

	if !assertPortList(c, out, []string{"0.0.0.0:9876"}) {
		c.Error("Port list is not correct")
	}

	out, _ = dockerCmd(c, "port", firstID)

	if !assertPortList(c, out, []string{"80/tcp -> 0.0.0.0:9876"}) {
		c.Error("Port list is not correct")
	}
	dockerCmd(c, "rm", "-f", firstID)

	// three port
	out, _ = dockerCmd(c, "run", "-d",
		"-p", "9876:80",
		"-p", "9877:81",
		"-p", "9878:82",
		"busybox", "top")
	ID := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "port", ID, "80")

	if !assertPortList(c, out, []string{"0.0.0.0:9876"}) {
		c.Error("Port list is not correct")
	}

	out, _ = dockerCmd(c, "port", ID)

	if !assertPortList(c, out, []string{
		"80/tcp -> 0.0.0.0:9876",
		"81/tcp -> 0.0.0.0:9877",
		"82/tcp -> 0.0.0.0:9878"}) {
		c.Error("Port list is not correct")
	}
	dockerCmd(c, "rm", "-f", ID)

	// more and one port mapped to the same container port
	out, _ = dockerCmd(c, "run", "-d",
		"-p", "9876:80",
		"-p", "9999:80",
		"-p", "9877:81",
		"-p", "9878:82",
		"busybox", "top")
	ID = strings.TrimSpace(out)

	out, _ = dockerCmd(c, "port", ID, "80")

	if !assertPortList(c, out, []string{"0.0.0.0:9876", "0.0.0.0:9999"}) {
		c.Error("Port list is not correct")
	}

	out, _ = dockerCmd(c, "port", ID)

	if !assertPortList(c, out, []string{
		"80/tcp -> 0.0.0.0:9876",
		"80/tcp -> 0.0.0.0:9999",
		"81/tcp -> 0.0.0.0:9877",
		"82/tcp -> 0.0.0.0:9878"}) {
		c.Error("Port list is not correct\n", out)
	}
	dockerCmd(c, "rm", "-f", ID)

	testRange := func() {
		// host port ranges used
		IDs := make([]string, 3)
		for i := 0; i < 3; i++ {
			out, _ = dockerCmd(c, "run", "-d",
				"-p", "9090-9092:80",
				"busybox", "top")
			IDs[i] = strings.TrimSpace(out)

			out, _ = dockerCmd(c, "port", IDs[i])

			if !assertPortList(c, out, []string{
				fmt.Sprintf("80/tcp -> 0.0.0.0:%d", 9090+i)}) {
				c.Error("Port list is not correct\n", out)
			}
		}

		// test port range exhaustion
		out, _, err := dockerCmdWithError("run", "-d",
			"-p", "9090-9092:80",
			"busybox", "top")
		if err == nil {
			c.Errorf("Exhausted port range did not return an error.  Out: %s", out)
		}

		for i := 0; i < 3; i++ {
			dockerCmd(c, "rm", "-f", IDs[i])
		}
	}
	testRange()
	// Verify we ran re-use port ranges after they are no longer in use.
	testRange()

	// test invalid port ranges
	for _, invalidRange := range []string{"9090-9089:80", "9090-:80", "-9090:80"} {
		out, _, err := dockerCmdWithError("run", "-d",
			"-p", invalidRange,
			"busybox", "top")
		if err == nil {
			c.Errorf("Port range should have returned an error.  Out: %s", out)
		}
	}

	// test host range:container range spec.
	out, _ = dockerCmd(c, "run", "-d",
		"-p", "9800-9803:80-83",
		"busybox", "top")
	ID = strings.TrimSpace(out)

	out, _ = dockerCmd(c, "port", ID)

	if !assertPortList(c, out, []string{
		"80/tcp -> 0.0.0.0:9800",
		"81/tcp -> 0.0.0.0:9801",
		"82/tcp -> 0.0.0.0:9802",
		"83/tcp -> 0.0.0.0:9803"}) {
		c.Error("Port list is not correct\n", out)
	}
	dockerCmd(c, "rm", "-f", ID)

	// test mixing protocols in same port range
	out, _ = dockerCmd(c, "run", "-d",
		"-p", "8000-8080:80",
		"-p", "8000-8080:80/udp",
		"busybox", "top")
	ID = strings.TrimSpace(out)

	out, _ = dockerCmd(c, "port", ID)

	if !assertPortList(c, out, []string{
		"80/tcp -> 0.0.0.0:8000",
		"80/udp -> 0.0.0.0:8000"}) {
		c.Error("Port list is not correct\n", out)
	}
	dockerCmd(c, "rm", "-f", ID)
}
// TestV1 starts a daemon in 'normal' mode
// and ensure v1 endpoints are hit for the following operations:
// login, push, pull, build & run
func (s *DockerRegistrySuite) TestV1(c *check.C) {
	reg, err := newTestRegistry(c)
	if err != nil {
		c.Fatal(err.Error())
	}

	v2Pings := 0
	reg.registerHandler("/v2/", func(w http.ResponseWriter, r *http.Request) {
		v2Pings++
		// V2 ping 404 causes fallback to v1
		w.WriteHeader(404)
	})

	v1Pings := 0
	reg.registerHandler("/v1/_ping", func(w http.ResponseWriter, r *http.Request) {
		v1Pings++
	})

	v1Logins := 0
	reg.registerHandler("/v1/users/", func(w http.ResponseWriter, r *http.Request) {
		v1Logins++
	})

	v1Repo := 0
	reg.registerHandler("/v1/repositories/busybox/", func(w http.ResponseWriter, r *http.Request) {
		v1Repo++
	})

	reg.registerHandler("/v1/repositories/busybox/images", func(w http.ResponseWriter, r *http.Request) {
		v1Repo++
	})

	err = s.d.Start("--insecure-registry", reg.hostport, "--disable-legacy-registry=false")
	if err != nil {
		c.Fatalf("Error starting daemon: %s", err.Error())
	}

	dockerfileName, cleanup, err := makefile(fmt.Sprintf("FROM %s/busybox", reg.hostport))
	if err != nil {
		c.Fatalf("Unable to create test dockerfile")
	}
	defer cleanup()

	s.d.Cmd("build", "--file", dockerfileName, ".")
	if v1Repo == 0 {
		c.Errorf("Expected v1 repository access after build")
	}

	repoName := fmt.Sprintf("%s/busybox", reg.hostport)
	s.d.Cmd("run", repoName)
	if v1Repo == 1 {
		c.Errorf("Expected v1 repository access after run")
	}

	s.d.Cmd("login", "-u", "richard", "-p", "testtest", "-e", "*****@*****.**", reg.hostport)
	if v1Logins == 0 {
		c.Errorf("Expected v1 login attempt")
	}

	s.d.Cmd("tag", "busybox", repoName)
	s.d.Cmd("push", repoName)

	if v1Repo != 2 || v1Pings != 1 {
		c.Error("Not all endpoints contacted after push", v1Repo, v1Pings)
	}

	s.d.Cmd("pull", repoName)
	if v1Repo != 3 {
		c.Errorf("Expected v1 repository access after pull")
	}

}
Beispiel #20
0
// Test the topology service
func (s *MySuite) TestTopology(c *check.C) {
	myLog(c, "Entering TestTopology()")

	dir, _ := os.Getwd()
	myLog(c, "In", dir)
	myLog(c, "Starting topology service")
	topoSvc := &TopologySvc{}
	svcInfo, err := common.SimpleStartService(topoSvc, s.rootURL)
	if err != nil {
		c.Error(err)
	}
	msg := <-svcInfo.Channel
	myLog(c, "Topology service said:", msg)
	addr := "http://" + svcInfo.Address
	client, err := common.NewRestClient(common.GetDefaultRestClientConfig(addr))
	if err != nil {
		c.Error(err)
	}
	myLog(c, "Calling ", addr)

	topIndex := &common.IndexResponse{}
	err = client.Get("/", &topIndex)
	if err != nil {
		c.Error(err)
		c.FailNow()
	}

	c.Assert(topIndex.ServiceName, check.Equals, "topology")
	hostsRelURL := topIndex.Links.FindByRel("host-list")
	hostsURL := addr + hostsRelURL
	myLog(c, "Host list URL: ", hostsURL)

	// Get list of hosts - should be empty for now.
	var hostList []common.Host
	err = client.Get(hostsRelURL, &hostList)
	if err != nil {
		c.Error(err)
		c.FailNow()
	}
	myLog(c, "Host list: ", hostList)
	c.Assert(len(hostList), check.Equals, 0)
	newHostReq := common.Host{Ip: "10.10.10.10", AgentPort: 9999, Name: "host10", RomanaIp: "15.15.15.15"}

	newHostResp := common.Host{}
	err = client.Post(hostsRelURL, newHostReq, &newHostResp)
	if err != nil {
		c.Error(err)
		c.FailNow()
	}
	myLog(c, "Response: ", newHostResp)
	myLog(c, "Waiting for....", time.Hour)
	//	time.Sleep(time.Hour)

	c.Assert(newHostResp.Ip, check.Equals, "10.10.10.10")
	c.Assert(newHostResp.ID, check.Equals, uint64(1))

	newHostReq = common.Host{Ip: "10.10.10.11", AgentPort: 9999, Name: "host11", RomanaIp: "15.15.15.16"}
	newHostResp = common.Host{}
	err = client.Post(hostsRelURL, newHostReq, &newHostResp)
	if err != nil {
		c.Error(err)
		c.FailNow()
	}
	myLog(c, "Response: ", newHostResp)
	c.Assert(newHostResp.ID, check.Equals, uint64(2))

	err = client.Post(hostsRelURL, newHostReq, &newHostResp)
	httpErr := err.(common.HttpError)
	myLog(c, "Attempt to add duplicate host: %v", httpErr)
	c.Assert(httpErr.StatusCode, check.Equals, 409)

	newHostReqWithoutRomanaIP := common.Host{Ip: "10.10.10.12", AgentPort: 9999, Name: "host12"}
	newHostRespWithoutRomanaIP := common.Host{}
	err = client.Post(hostsRelURL, newHostReqWithoutRomanaIP, &newHostRespWithoutRomanaIP)
	if err != nil {
		c.Error(err)
		c.FailNow()
	}
	myLog(c, "Response: ", newHostRespWithoutRomanaIP)

	c.Assert(newHostRespWithoutRomanaIP.Ip, check.Equals, "10.10.10.12")
	c.Assert(newHostRespWithoutRomanaIP.RomanaIp, check.Equals, "10.2.0.0/16")
	c.Assert(newHostRespWithoutRomanaIP.ID, check.Equals, uint64(3))

	newHostReqWithoutRomanaIP = common.Host{Ip: "10.10.10.13", AgentPort: 9999, Name: "host13"}
	newHostRespWithoutRomanaIP = common.Host{}
	err = client.Post(hostsRelURL, newHostReqWithoutRomanaIP, &newHostRespWithoutRomanaIP)
	if err != nil {
		c.Error(err)
		c.FailNow()
	}
	myLog(c, "Response: ", newHostRespWithoutRomanaIP)

	c.Assert(newHostRespWithoutRomanaIP.Ip, check.Equals, "10.10.10.13")
	c.Assert(newHostRespWithoutRomanaIP.RomanaIp, check.Equals, "10.3.0.0/16")
	c.Assert(newHostRespWithoutRomanaIP.ID, check.Equals, uint64(4))

	// TODO: auto generation of romana cidr currently don't
	//       handle manually assigned one gracefully, thus tests
	//       to be added here once that support is added.

	var hostList2 []common.Host
	err = client.Get(hostsRelURL, &hostList2)
	if err != nil {
		c.Error(err)
		c.FailNow()
	}
	myLog(c, "Host list: ", hostList2)
	c.Assert(len(hostList2), check.Equals, 4)
}
func (s *DirectoryServerSuite) TestHandler_ServeHTTP_DumpFile_FailedRangeQuery(t *check.C) {
	// Create temp file for this unit test.
	tmpFile, err := ioutil.TempFile("", "testfile_")
	if err != nil {
		t.Error(err)
	}
	err = tmpFile.Close()
	if err != nil {
		t.Error(err)
	}
	var dump bytes.Buffer
	for index := 0; index < 1000; index++ {
		dump.WriteString("A")
	}
	err = ioutil.WriteFile(tmpFile.Name(), []byte(dump.String()), 0600)
	if err != nil {
		t.Error(err)
	}

	responseBody := []byte(fmt.Sprintf(`{"instance_path": "%s"}`, tmpFile.Name()))
	fc := func(w http.ResponseWriter, r *http.Request) {
		w.Write(responseBody)
	}

	lc, hc, pc := startTestServer(http.HandlerFunc(fc))
	defer lc.Close()

	h := handler{
		deaHost:          hc,
		deaPort:          pc,
		streamingTimeout: 1,
		deaClient:        &DeaClient{Host: hc, Port: pc},
	}

	ld, hd, pd := startTestServer(h)
	defer ld.Close()

	request, err := http.NewRequest("GET", fmt.Sprintf("http://%s:%d/path", hd, pd), nil)
	if err != nil {
		t.Error(err)
	}

	request.Header.Set("Range", "bytes=10000-")

	response, err := http.DefaultClient.Do(request)
	if err != nil {
		t.Error(err)
	}

	// Check status code.
	if response.StatusCode != 416 {
		t.Fail()
	}

	// Clean up.
	if err = os.Remove(tmpFile.Name()); err != nil {
		t.Error(err)
	}
}
func (s *DockerSuite) TestPortList(c *check.C) {

	// one port
	out, _ := dockerCmd(c, "run", "-d", "-p", "9876:80", "busybox", "top")
	firstID := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "port", firstID, "80")

	if !assertPortList(c, out, []string{"0.0.0.0:9876"}) {
		c.Error("Port list is not correct")
	}

	out, _ = dockerCmd(c, "port", firstID)

	if !assertPortList(c, out, []string{"80/tcp -> 0.0.0.0:9876"}) {
		c.Error("Port list is not correct")
	}
	dockerCmd(c, "rm", "-f", firstID)

	// three port
	out, _ = dockerCmd(c, "run", "-d",
		"-p", "9876:80",
		"-p", "9877:81",
		"-p", "9878:82",
		"busybox", "top")
	ID := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "port", ID, "80")

	if !assertPortList(c, out, []string{"0.0.0.0:9876"}) {
		c.Error("Port list is not correct")
	}

	out, _ = dockerCmd(c, "port", ID)

	if !assertPortList(c, out, []string{
		"80/tcp -> 0.0.0.0:9876",
		"81/tcp -> 0.0.0.0:9877",
		"82/tcp -> 0.0.0.0:9878"}) {
		c.Error("Port list is not correct")
	}
	dockerCmd(c, "rm", "-f", ID)

	// more and one port mapped to the same container port
	out, _ = dockerCmd(c, "run", "-d",
		"-p", "9876:80",
		"-p", "9999:80",
		"-p", "9877:81",
		"-p", "9878:82",
		"busybox", "top")
	ID = strings.TrimSpace(out)

	out, _ = dockerCmd(c, "port", ID, "80")

	if !assertPortList(c, out, []string{"0.0.0.0:9876", "0.0.0.0:9999"}) {
		c.Error("Port list is not correct")
	}

	out, _ = dockerCmd(c, "port", ID)

	if !assertPortList(c, out, []string{
		"80/tcp -> 0.0.0.0:9876",
		"80/tcp -> 0.0.0.0:9999",
		"81/tcp -> 0.0.0.0:9877",
		"82/tcp -> 0.0.0.0:9878"}) {
		c.Error("Port list is not correct\n", out)
	}
	dockerCmd(c, "rm", "-f", ID)

}
Beispiel #23
0
func (s *MySuite) TestPolicy(c *check.C) {
	cfg := &common.ServiceConfig{Common: common.CommonConfig{Api: &common.Api{Port: 0, RestTimeoutMillis: 100}}}
	log.Printf("Test: Mock service config:\n\t%#v\n\t%#v\n", cfg.Common.Api, cfg.ServiceSpecific)
	svc := &mockSvc{mySuite: s}
	svc.tenants = make(map[uint64]string)
	svc.tenantsStr = make(map[string]uint64)
	svc.segments = make(map[uint64]string)
	svc.segmentsStr = make(map[string]uint64)
	svcInfo, err := common.InitializeService(svc, *cfg, nil)

	if err != nil {
		c.Error(err)
		c.FailNow()
	}
	msg := <-svcInfo.Channel
	log.Printf("Test: Mock service says %s; listening on %s\n", msg, svcInfo.Address)
	addrComponents := strings.Split(svcInfo.Address, ":")
	portStr := addrComponents[len(addrComponents)-1]
	s.servicePort, err = strconv.ParseUint(portStr, 10, 64)
	if err != nil {
		c.Error(err)
		c.FailNow()
	}
	s.serviceURL = fmt.Sprintf("http://%s", svcInfo.Address)
	log.Printf("Test: Mock service listens at %s\n", s.serviceURL)

	polSvc := &PolicySvc{}
	err = common.SimpleOverwriteSchema(polSvc, s.serviceURL)
	if err != nil {
		c.Fatal(err)
	}
	log.Printf("Policy schema created.")

	svcInfo, err = common.SimpleStartService(polSvc, s.serviceURL)
	if err != nil {
		c.Fatal(err)
	}

	msg = <-svcInfo.Channel
	fmt.Printf("Policy service listening %s on said: %s", svcInfo.Address, msg)

	clientConfig := common.GetDefaultRestClientConfig(s.serviceURL)
	client, err := common.NewRestClient(clientConfig)
	if err != nil {
		c.Fatal(err)
	}
	polURL := "http://" + svcInfo.Address + "/policies"

	log.Println("1. Add policy pol1")
	policyIn := common.Policy{}
	err = json.Unmarshal([]byte(romanaPolicy1), &policyIn)
	if err != nil {
		c.Fatal(err)
		c.FailNow()
	}
	policyOut := common.Policy{}
	err = client.Post(polURL, policyIn, &policyOut)
	if err != nil {
		c.Error(err)
		c.FailNow()
	}
	log.Printf("Added policy result: %s", policyOut)
	c.Assert(policyOut.Name, check.Equals, "pol1")
	c.Assert(policyOut.ID, check.Equals, uint64(1))
	c.Assert(len(policyOut.AppliedTo), check.Equals, len(policyIn.AppliedTo))
	c.Assert(len(policyOut.Ingress[0].Peers), check.Equals, len(policyIn.Ingress[0].Peers))
	c.Assert(client.GetStatusCode(), check.Equals, 200)

	pol1ExternalID := policyIn.ExternalID
	policyIn.ExternalID = "asdfghjkl"
	policyIn.ID = policyOut.ID
	log.Printf("2. Add policy again with different External ID %s but same ID %d", policyIn.ExternalID, policyIn.ID)
	err = client.Post(polURL, policyIn, &policyOut)
	c.Assert(err.(common.HttpError).StatusCode, check.Equals, http.StatusConflict)
	log.Printf("2. Result: %+v", policyOut)

	log.Println("3. Add policy again")
	policyIn.ExternalID = pol1ExternalID
	policyIn.ID = 0
	err = client.Post(polURL, policyIn, &policyOut)
	c.Assert(err.(common.HttpError).StatusCode, check.Equals, http.StatusConflict)
	log.Printf("3. Result: %+v", policyOut)

	log.Println("4. Add policy pol2")
	err = json.Unmarshal([]byte(romanaPolicy2), &policyIn)
	if err != nil {
		c.Fatal(err)
	}
	err = client.Post(polURL, policyIn, &policyOut)
	if err != nil {
		c.Fatal(err)
	}
	log.Printf("Added policy result: %s", policyOut)
	c.Assert(client.GetStatusCode(), check.Equals, 200)
	c.Assert(policyOut.Name, check.Equals, "pol2")

	log.Println("5. Add default policy")
	one := uint64(1)
	defPol := common.Policy{
		Direction:  common.PolicyDirectionIngress,
		Name:       "default",
		ExternalID: "default",
		AppliedTo:  []common.Endpoint{{TenantNetworkID: &one}},
		Ingress: []common.RomanaIngress{
			common.RomanaIngress{
				Peers: []common.Endpoint{{Peer: common.Wildcard}},
				Rules: []common.Rule{{Protocol: common.Wildcard}},
			},
		},
	}
	err = client.Post(polURL, defPol, &policyOut)
	if err != nil {
		c.Fatal(err)
	}
	log.Printf("Added policy result: %s", policyOut)
	c.Assert(client.GetStatusCode(), check.Equals, 200)
	c.Assert(policyOut.Name, check.Equals, "default")

	log.Println("6. Test list policies - should have 3.")
	var policies []common.Policy
	err = client.Get(polURL, &policies)
	if err != nil {
		c.Fatal(err)
	}
	c.Assert(len(policies), check.Equals, 3)
	c.Assert(client.GetStatusCode(), check.Equals, 200)
	c.Assert(policies[0].Name, check.Equals, "pol1")
	c.Assert(policies[1].Name, check.Equals, "pol2")
	c.Assert(policies[2].Name, check.Equals, "default")

	log.Println("7. Test get policy.")
	policyGet := common.Policy{}
	err = client.Get(polURL+"/1", &policyGet)
	if err != nil {
		c.Fatal(err)
	}
	c.Assert(policyGet.Name, check.Equals, policies[0].Name)
	c.Assert(client.GetStatusCode(), check.Equals, 200)

	log.Println("8. Test delete by ID - delete pol1")
	policyOut = common.Policy{}
	err = client.Delete(polURL+"/1", nil, &policyOut)
	if err != nil {
		c.Fatal(err)
	}
	log.Printf("Deleted policy result: %s", policyOut)
	c.Assert(policyOut.Name, check.Equals, "pol1")
	c.Assert(policyOut.ID, check.Equals, uint64(1))
	c.Assert(client.GetStatusCode(), check.Equals, 200)

	log.Println("9. Test list policies - should have 2 now - pol2 and default.")
	err = client.Get(polURL, &policies)
	if err != nil {
		c.Fatal(err)
	}
	c.Assert(len(policies), check.Equals, 2)
	c.Assert(policies[0].Name, check.Equals, "pol2")
	c.Assert(policies[1].Name, check.Equals, "default")
	c.Assert(client.GetStatusCode(), check.Equals, 200)

	log.Println("10. Test delete by ExternalID - delete policy 2")
	err = json.Unmarshal([]byte(romanaPolicy2), &policyIn)
	if err != nil {
		c.Fatal(err)
	}
	log.Printf("Unmarshaled %s to %v", romanaPolicy2, policyIn)
	policyOut = common.Policy{}
	err = client.Delete(polURL, policyIn, &policyOut)
	if err != nil {
		c.Fatal(err)
	}
	log.Printf("Deleted policy result: %s", policyOut)
	c.Assert(client.GetStatusCode(), check.Equals, 200)
	c.Assert(policyOut.Name, check.Equals, policyIn.Name)

	log.Println("10. Test list policies - should have 1 now - only default")
	err = client.Get(polURL, &policies)
	if err != nil {
		c.Fatal(err)
	}
	c.Assert(client.GetStatusCode(), check.Equals, 200)
	c.Assert(len(policies), check.Equals, 1)
	c.Assert(policies[0].Name, check.Equals, "default")

	log.Println("11. Test find by name policies - should find it")
	findURL := "http://" + svcInfo.Address + "/find/policies"
	err = client.Get(findURL+"/default", &policyOut)
	if err != nil {
		c.Fatal(err)
	}
	c.Assert(policyOut.Name, check.Equals, "default")

	log.Println("12. Test find by name policies with non-existent policy - should NOT find it")
	err = client.Get(findURL+"/blabla", &policyOut)
	httpErr := err.(common.HttpError)
	c.Assert(client.GetStatusCode(), check.Equals, http.StatusNotFound)
	c.Assert(httpErr.ResourceType, check.Equals, "policy")
	c.Assert(httpErr.StatusCode, check.Equals, http.StatusNotFound)
	c.Assert(httpErr.ResourceID, check.Equals, "blabla")
	log.Printf("%v", err)

	log.Println("13. Test delete by ExternalID - delete default policy")
	policyOut = common.Policy{}
	err = client.Delete(polURL, defPol, &policyOut)

	if err != nil {
		c.Fatal(err)
	}
	log.Printf("Deleted policy result: %s", policyOut)
	c.Assert(policyOut.Name, check.Equals, defPol.Name)
	c.Assert(client.GetStatusCode(), check.Equals, 200)

	log.Println("14. Test list policies - should have 0 now")
	err = client.Get(polURL, &policies)
	if err != nil {
		c.Fatal(err)
	}
	c.Assert(len(policies), check.Equals, 0)

	log.Println("15. Test delete by ExternalID - delete default policy - should be Not Found error now")
	policyOut = common.Policy{}
	err = client.Delete(polURL, defPol, &policyOut)
	if err == nil {
		panic("Expected error")
	}
	httpErr = err.(common.HttpError)
	c.Assert(client.GetStatusCode(), check.Equals, http.StatusNotFound)
	c.Assert(httpErr.ResourceType, check.Equals, "policy")
	c.Assert(httpErr.StatusCode, check.Equals, http.StatusNotFound)
	// TODO
	// Important! This should really be done in policy agent.
	// Only done here as temporary measure.
	id := makeId(defPol.AppliedTo, defPol.Name)
	c.Assert(httpErr.ResourceID, check.Equals, id)
	//	c.Assert(httpErr.ResourceID, check.Equals, "default")

	log.Printf("%v", err)

}
Beispiel #24
0
func (s *MySuite) TestStore(c *check.C) {
	var err error

	store := ipamStore{}
	store.ServiceStore = &store

	storeConfig := make(map[string]interface{})
	storeConfig["type"] = "sqlite3"
	storeConfig["database"] = s.RomanaTestSuite.GetMockSqliteFile("ipam")
	err = store.SetConfig(storeConfig)
	c.Assert(err, check.IsNil)
	cidr := "10.0.0.0/8"
	ip, _, _ := net.ParseCIDR(cidr)

	dc := common.Datacenter{Cidr: cidr, IpVersion: 4, Prefix: common.IPv4ToInt(ip), PrefixBits: 8, PortBits: 8, TenantBits: 4, SegmentBits: 4}

	_, network, _ := net.ParseCIDR("10.1.0.0/16")
	hostIpInt := common.IPv4ToInt(network.IP)

	segmentBitShift := uint64(8)
	tenantBitShift := uint64(segmentBitShift + 4)
	upToEndpointIpInt := hostIpInt | (1 << tenantBitShift) | (1 << segmentBitShift)
	// 253
	// 127
	// 63
	// 31
	for _, stride := range []uint{0, 1, 2, 4} {
		//	for _, stride := range []uint{0} {
		err = store.CreateSchema(true)
		if err != nil {
			panic(err)
		}
		err = store.Connect()
		if err != nil {
			panic(err)
		}
		dc.EndpointSpaceBits = stride
		dc.EndpointBits = 8 - stride
		endpoint := &Endpoint{Id: 0, EffectiveNetworkID: 0, HostId: "X", SegmentID: "X", TenantID: "X"}
		i := uint(1)
		firstIp := ""
		var upperBound uint
		switch stride {
		case 0:
			upperBound = 253
		case 1:
			upperBound = 127
		case 2:
			upperBound = 64
		case 4:
			upperBound = 16
		}
		log.Printf("For %d/%d go until 1= %d", dc.EndpointBits, stride, upperBound)
		for i = 1; i <= uint(upperBound); i++ {
			endpoint.Id = 0
			msg := fmt.Sprintf("For stride %d, endpoint bits %d, try %d\n", stride, dc.EndpointBits, i)
			log.Println(msg)
			err = store.addEndpoint(endpoint, upToEndpointIpInt, dc)
			if err != nil {
				c.Error(fmt.Sprintf("Unexpected error on try %d: %v", i, err))
				c.FailNow()
			}
			log.Printf("%s: Got IP: %s (effective network ID %d)", msg, endpoint.Ip, endpoint.EffectiveNetworkID)
			if firstIp == "" {
				firstIp = endpoint.Ip
			}

		}
		// Here we have reached the end...
		endpoint.Id = 0
		err = store.addEndpoint(endpoint, upToEndpointIpInt, dc)
		if err == nil {
			c.Error(fmt.Sprintf("Expected error, but got %+v", endpoint))
			c.FailNow()
		}

		endpoint.Id = 0
		_, err = store.deleteEndpoint(firstIp)
		if err != nil {
			c.Error(fmt.Sprintf("Unexpected error on try %d: %v", i, err))
			c.FailNow()
		}
		endpoint.Id = 0
		err = store.addEndpoint(endpoint, upToEndpointIpInt, dc)
		if err != nil {
			c.Error(fmt.Sprintf("Unexpected error on try %d: %v", i, err))
			c.Fail()
		}
		c.Assert(endpoint.Ip, check.Equals, firstIp)
		if c.Failed() {
			return
		}

		endpoint.Id = 0
		err = store.addEndpoint(endpoint, upToEndpointIpInt, dc)
		if err == nil {
			c.Error(fmt.Sprintf("Expected error, but got %+v", endpoint))
			c.FailNow()
		}

	}
}
func (s *DirectoryServerSuite) TestHandler_ServeHTTP_ReturnDirectoryListing(t *check.C) {
	// Create temp directory listing for this unit test.
	tmpDir, err := ioutil.TempDir("", "")
	if err != nil {
		t.Error(err)
	}
	_, err = ioutil.TempDir(tmpDir, "testdir_")
	if err != nil {
		t.Error(err)
	}
	tmpFile, err := ioutil.TempFile(tmpDir, "testfile_")
	if err != nil {
		t.Error(err)
	}
	err = tmpFile.Close()
	if err != nil {
		t.Error(err)
	}
	var dump bytes.Buffer
	for index := 0; index < 10000; index++ {
		dump.WriteString("A")
	}
	err = ioutil.WriteFile(tmpFile.Name(), []byte(dump.String()), 0600)
	if err != nil {
		t.Error(err)
	}

	responseBody := []byte(fmt.Sprintf(`{"instance_path": "%s"}`, tmpDir))
	fc := func(w http.ResponseWriter, r *http.Request) {
		w.Write(responseBody)
	}

	lc, hc, pc := startTestServer(http.HandlerFunc(fc))
	defer lc.Close()

	h := handler{
		deaHost:          hc,
		deaPort:          pc,
		streamingTimeout: 1,
		deaClient:        &DeaClient{Host: hc, Port: pc},
	}

	ld, hd, pd := startTestServer(h)
	defer ld.Close()

	response, err := http.Get(fmt.Sprintf("http://%s:%d/path", hd, pd))
	if err != nil {
		t.Error(err)
	}

	// Check status code.
	if response.StatusCode != 200 {
		t.Fail()
	}

	// Check headers.
	if response.Header.Get("Content-Type") != "text/plain" {
		t.Fail()
	}

	// Check body.
	body, err := getBody(response)
	if err != nil {
		t.Error(err)
	}

	pattern := "\\s*testdir_.*/\\s*-\\n\\s*testfile_.*\\s*9\\.8K"
	matched, _ := regexp.Match(pattern, body)
	if !matched {
		t.Fail()
	}

	// Clean up.
	if err = os.RemoveAll(tmpDir); err != nil {
		t.Error(err)
	}
}
Beispiel #26
0
// Test the integration with root and topology service
func (s *MySuite) TestIntegration(c *check.C) {
	myLog(c, "Entering TestIntegration()")

	dir, _ := os.Getwd()
	myLog(c, "In", dir)

	// 1. Start topology service
	myLog(c, "STARTING TOPOLOGY SERVICE")
	channelTop, topoAddr, err := topology.Run(s.rootUrl)
	if err != nil {
		c.Error(err)
	}
	msg := <-channelTop
	myLog(c, "Topology service said:", msg)

	// 2. Add some hosts to topology service and test.
	topoAddr = "http://" + topoAddr
	client, err := common.NewRestClient(topoAddr, common.DefaultRestTimeout)
	if err != nil {
		c.Error(err)
	}
	myLog(c, "Calling ", topoAddr)
	topIndex := &common.IndexResponse{}
	err = client.Get("/", &topIndex)
	if err != nil {
		c.Error(err)
	}

	c.Assert(topIndex.ServiceName, check.Equals, "topology")
	hostsRelUrl := topIndex.Links.FindByRel("host-list")
	hostsUrl := topoAddr + hostsRelUrl
	myLog(c, "Host list URL: ", hostsUrl)

	// Get list of hosts - should be empty for now.
	var hostList []common.HostMessage
	client.Get(hostsRelUrl, &hostList)
	myLog(c, "Host list: ", hostList)
	c.Assert(len(hostList), check.Equals, 0)
	newHostReq := common.HostMessage{Ip: "10.10.10.10", RomanaIp: "10.64.0.0/16", AgentPort: 9999, Name: "HOST1000"}

	host1 := common.HostMessage{}
	client.Post(hostsRelUrl, newHostReq, &host1)
	myLog(c, "Response: ", host1)
	c.Assert(host1.Ip, check.Equals, "10.10.10.10")
	c.Assert(host1.Id, check.Equals, "1")
	//
	newHostReq = common.HostMessage{Ip: "10.10.10.11", RomanaIp: "10.65.0.0/16", AgentPort: 9999, Name: "HOST2000"}
	host2 := common.HostMessage{}
	client.Post(hostsRelUrl, newHostReq, &host2)
	myLog(c, "Response: ", host2)

	c.Assert(host2.Ip, check.Equals, "10.10.10.11")
	c.Assert(host2.Id, check.Equals, "2")
	var hostList2 []common.HostMessage
	client.Get(hostsRelUrl, &hostList2)
	myLog(c, "Host list: ", hostList2)

	c.Assert(len(hostList2), check.Equals, 2)

	// 3. Start tenant service
	myLog(c, "STARTING TENANT SERVICE")
	channelTen, tenantAddr, err := tenant.Run(s.rootUrl)
	if err != nil {
		c.Error(err)
	}
	tenantAddr = "http://" + tenantAddr
	msg = <-channelTen
	myLog(c, "Tenant service said:", msg)
	client, err = common.NewRestClient(tenantAddr, common.DefaultRestTimeout)
	if err != nil {
		c.Error(err)
	}

	// 4. Add a tenant and a segment
	err = client.NewUrl(tenantAddr)
	if err != nil {
		c.Error(err)
	}

	// Add first tenant
	tIn := tenant.Tenant{Name: "t1"}
	tOut := tenant.Tenant{}
	err = client.Post("/tenants", tIn, &tOut)
	if err != nil {
		c.Error(err)
	}
	t1Id := tOut.Id
	myLog(c, "Tenant", tOut)

	// Add second tenant
	tIn = tenant.Tenant{Name: "t2"}
	tOut = tenant.Tenant{}
	err = client.Post("/tenants", tIn, &tOut)
	if err != nil {
		c.Error(err)
	}
	t2Id := tOut.Id
	myLog(c, "Tenant", tOut)

	// Find first tenant
	tOut2 := tenant.Tenant{}
	tenant1Path := fmt.Sprintf("/tenants/%d", t1Id)
	err = client.Get(tenant1Path, &tOut2)
	if err != nil {
		c.Error(err)
	}
	myLog(c, "Found", tOut2)

	// Add 2 segments to tenant 1
	sIn := tenant.Segment{Name: "s1", TenantId: t1Id}
	sOut := tenant.Segment{}
	err = client.Post(tenant1Path+"/segments", sIn, &sOut)
	if err != nil {
		c.Error(err)
	}
	myLog(c, "Added segment s1 to t1: ", sOut)
	sIn = tenant.Segment{Name: "s2", TenantId: t1Id}
	sOut = tenant.Segment{}
	err = client.Post(tenant1Path+"/segments", sIn, &sOut)
	if err != nil {
		c.Error(err)
	}
	myLog(c, "Added segment s2 to t1: ", sOut)

	// Add 2 segments to tenant 2
	tenant2Path := fmt.Sprintf("/tenants/%d", t2Id)

	sIn = tenant.Segment{Name: "s1", TenantId: t2Id}
	sOut = tenant.Segment{}
	err = client.Post(tenant2Path+"/segments", sIn, &sOut)
	if err != nil {
		c.Error(err)
	}
	myLog(c, "Added segment s1 to t2: ", sOut)

	sIn = tenant.Segment{Name: "s2", TenantId: t2Id}
	sOut = tenant.Segment{}
	err = client.Post(tenant2Path+"/segments", sIn, &sOut)
	if err != nil {
		c.Error(err)
	}
	myLog(c, "Added segment s2 to t2: ", sOut)

	// 4. Start IPAM service
	myLog(c, "STARTING IPAM SERVICE")
	channelIpam, ipamAddr, err := ipam.Run(s.rootUrl)
	if err != nil {
		c.Error(err)
	}
	ipamAddr = fmt.Sprintf("http://%s", ipamAddr)
	msg = <-channelIpam
	myLog(c, "IPAM service said: ", msg)
	client, err = common.NewRestClient(ipamAddr, common.DefaultRestTimeout)
	if err != nil {
		c.Error(err)
	}

	// Get first IP
	vmIn := ipam.Vm{Name: "vm1", TenantId: fmt.Sprintf("%d", tOut.Id), SegmentId: fmt.Sprintf("%d", sOut.Id), HostId: host2.Id}
	vmOut := ipam.Vm{}
	err = client.Post("/vms", vmIn, &vmOut)
	if err != nil {
		c.Error(err)
	}
	myLog(c, "Received:", vmOut)
	myLog(c, "IP:", vmOut.Ip)

	// Get second IP
	vmIn = ipam.Vm{Name: "vm2", TenantId: fmt.Sprintf("%d", tOut.Id), SegmentId: fmt.Sprintf("%d", sOut.Id), HostId: host2.Id}
	vmOut = ipam.Vm{}
	err = client.Post("/vms", vmIn, &vmOut)
	if err != nil {
		c.Error(err)
	}
	myLog(c, "Received:", vmOut)
	myLog(c, "IP:", vmOut.Ip)

	// Try legacy request
	vmOut = ipam.Vm{}
	legacyUrl := "/allocateIpByName?tenantName=t1&segmentName=s1&hostName=HOST2000&instanceName=bla"
	myLog(c, "Calling legacy URL", legacyUrl)

	err = client.Get(legacyUrl, &vmOut)

	if err != nil {
		myLog(c, "Error %s\n", err)
		c.Error(err)
	}
	myLog(c, "Legacy received:", vmOut)
	myLog(c, "Legacy IP:", vmOut.Ip)

	// 5. Start Agent service
	myLog(c, "STARTING Agent SERVICE")
	channelAgent, _, err := agent.Run(s.rootUrl)
	if err != nil {
		c.Error(err)
	}
	msg = <-channelAgent
	myLog(c, "Agent service said:", msg)

}