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 *DirectoryServerSuite) TestHandler_ServeHTTP_StreamFileFromValidOffset(t *check.C) {
	response, body := fetchStreamingResponse(t, "/path?tail=&tail_offset=0")
	t.Check(response.StatusCode, check.Equals, 200)

	// Check transfer encoding.
	te := response.TransferEncoding
	if len(te) != 1 || te[0] != "chunked" {
		t.Fail()
	}

	matched, _ := regexp.MatchString("^blah0blah1blah2", body)
	if !matched {
		t.Fail()
	}
}
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 *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()
	}
}
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()
	}
}
Esempio n. 6
0
func (s *ConsulSuite) TestNominalConfiguration(c *check.C) {
	s.setupConsul(c)
	consulHost := s.composeProject.Container(c, "consul").NetworkSettings.IPAddress
	file := s.adaptFile(c, "fixtures/consul/simple.toml", struct{ ConsulHost string }{consulHost})
	defer os.Remove(file)
	cmd := exec.Command(traefikBinary, "--configFile="+file)
	err := cmd.Start()
	c.Assert(err, checker.IsNil)
	defer cmd.Process.Kill()

	whoami1 := s.composeProject.Container(c, "whoami1")
	whoami2 := s.composeProject.Container(c, "whoami2")
	whoami3 := s.composeProject.Container(c, "whoami3")
	whoami4 := s.composeProject.Container(c, "whoami4")

	backend1 := map[string]string{
		"traefik/backends/backend1/circuitbreaker/expression": "NetworkErrorRatio() > 0.5",
		"traefik/backends/backend1/servers/server1/url":       "http://" + whoami1.NetworkSettings.IPAddress + ":80",
		"traefik/backends/backend1/servers/server1/weight":    "10",
		"traefik/backends/backend1/servers/server2/url":       "http://" + whoami2.NetworkSettings.IPAddress + ":80",
		"traefik/backends/backend1/servers/server2/weight":    "1",
	}
	backend2 := map[string]string{
		"traefik/backends/backend2/loadbalancer/method":    "drr",
		"traefik/backends/backend2/servers/server1/url":    "http://" + whoami3.NetworkSettings.IPAddress + ":80",
		"traefik/backends/backend2/servers/server1/weight": "1",
		"traefik/backends/backend2/servers/server2/url":    "http://" + whoami4.NetworkSettings.IPAddress + ":80",
		"traefik/backends/backend2/servers/server2/weight": "2",
	}
	frontend1 := map[string]string{
		"traefik/frontends/frontend1/backend":            "backend2",
		"traefik/frontends/frontend1/entrypoints":        "http",
		"traefik/frontends/frontend1/priority":           "1",
		"traefik/frontends/frontend1/routes/test_1/rule": "Host:test.localhost",
	}
	frontend2 := map[string]string{
		"traefik/frontends/frontend2/backend":            "backend1",
		"traefik/frontends/frontend2/entrypoints":        "http",
		"traefik/frontends/frontend2/priority":           "10",
		"traefik/frontends/frontend2/routes/test_2/rule": "Path:/test",
	}
	for key, value := range backend1 {
		err := s.kv.Put(key, []byte(value), nil)
		c.Assert(err, checker.IsNil)
	}
	for key, value := range backend2 {
		err := s.kv.Put(key, []byte(value), nil)
		c.Assert(err, checker.IsNil)
	}
	for key, value := range frontend1 {
		err := s.kv.Put(key, []byte(value), nil)
		c.Assert(err, checker.IsNil)
	}
	for key, value := range frontend2 {
		err := s.kv.Put(key, []byte(value), nil)
		c.Assert(err, checker.IsNil)
	}

	// wait for consul
	err = utils.Try(60*time.Second, func() error {
		_, err := s.kv.Exists("traefik/frontends/frontend2/routes/test_2/rule")
		if err != nil {
			return err
		}
		return nil
	})
	c.Assert(err, checker.IsNil)

	// wait for traefik
	err = utils.TryRequest("http://127.0.0.1:8081/api/providers", 60*time.Second, func(res *http.Response) error {
		body, err := ioutil.ReadAll(res.Body)
		if err != nil {
			return err
		}
		if !strings.Contains(string(body), "Path:/test") {
			return errors.New("Incorrect traefik config")
		}
		return nil
	})
	c.Assert(err, checker.IsNil)

	client := &http.Client{}
	req, err := http.NewRequest("GET", "http://127.0.0.1:8000/", nil)
	c.Assert(err, checker.IsNil)
	req.Host = "test.localhost"
	response, err := client.Do(req)

	c.Assert(err, checker.IsNil)
	c.Assert(response.StatusCode, checker.Equals, 200)

	body, err := ioutil.ReadAll(response.Body)
	c.Assert(err, checker.IsNil)
	if !strings.Contains(string(body), whoami3.NetworkSettings.IPAddress) &&
		!strings.Contains(string(body), whoami4.NetworkSettings.IPAddress) {
		c.Fail()
	}

	req, err = http.NewRequest("GET", "http://127.0.0.1:8000/test", nil)
	c.Assert(err, checker.IsNil)
	response, err = client.Do(req)

	c.Assert(err, checker.IsNil)
	c.Assert(response.StatusCode, checker.Equals, 200)

	body, err = ioutil.ReadAll(response.Body)
	c.Assert(err, checker.IsNil)
	if !strings.Contains(string(body), whoami1.NetworkSettings.IPAddress) &&
		!strings.Contains(string(body), whoami2.NetworkSettings.IPAddress) {
		c.Fail()
	}

	req, err = http.NewRequest("GET", "http://127.0.0.1:8000/test2", nil)
	resp, err := client.Do(req)
	c.Assert(err, checker.IsNil)
	c.Assert(resp.StatusCode, checker.Equals, 404)

	req, err = http.NewRequest("GET", "http://127.0.0.1:8000/", nil)
	req.Host = "test2.localhost"
	resp, err = client.Do(req)
	c.Assert(err, checker.IsNil)
	c.Assert(resp.StatusCode, checker.Equals, 404)
}
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)
	}
}
Esempio n. 8
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()
		}

	}
}