Exemplo n.º 1
0
func (s *HandlersSuite) TestHealingHistoryHandlerFilterNode(c *check.C) {
	evt1, err := newHealingEvent(cluster.Node{Address: "addr1"})
	c.Assert(err, check.IsNil)
	evt1.update(cluster.Node{Address: "addr2"}, nil)
	evt2, err := newHealingEvent(cluster.Node{Address: "addr3"})
	evt2.update(cluster.Node{}, errors.New("some error"))
	evt3, err := newHealingEvent(container{ID: "1234"})
	evt3.update(container{ID: "9876"}, nil)
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("GET", "/docker/healing?filter=node", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	body := recorder.Body.Bytes()
	healings := []healingEvent{}
	err = json.Unmarshal(body, &healings)
	c.Assert(err, check.IsNil)
	c.Assert(healings, check.HasLen, 2)
	c.Assert(healings[0].Action, check.Equals, "node-healing")
	c.Assert(healings[0].ID, check.Equals, evt2.ID)
	c.Assert(healings[1].Action, check.Equals, "node-healing")
	c.Assert(healings[1].ID, check.Equals, evt1.ID)
}
Exemplo n.º 2
0
func (s *HandlersSuite) TestAutoScaleListRulesWithDBConfig(c *check.C) {
	config.Set("docker:auto-scale:scale-down-ratio", 2.0)
	defer config.Unset("docker:auto-scale:max-container-count")
	config.Set("docker:scheduler:total-memory-metadata", "maxmemory")
	defer config.Unset("docker:scheduler:total-memory-metadata")
	rules := []autoScaleRule{
		{MetadataFilter: "", Enabled: true, MaxContainerCount: 10, ScaleDownRatio: 1.2},
		{MetadataFilter: "pool1", Enabled: true, ScaleDownRatio: 1.1, MaxMemoryRatio: 2.0},
	}
	for _, r := range rules {
		err := r.update()
		c.Assert(err, check.IsNil)
	}
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("GET", "/docker/autoscale/rules", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	var reqRules []autoScaleRule
	err = json.Unmarshal(recorder.Body.Bytes(), &reqRules)
	c.Assert(err, check.IsNil)
	c.Assert(reqRules, check.DeepEquals, rules)
}
Exemplo n.º 3
0
func (s *HandlersSuite) TestAutoScaleRunHandler(c *check.C) {
	mainDockerProvisioner.cluster, _ = cluster.New(&segregatedScheduler{}, &cluster.MapStorage{},
		cluster.Node{Address: "localhost:1999", Metadata: map[string]string{
			"pool": "pool1",
		}},
	)
	config.Set("docker:auto-scale:enabled", true)
	defer config.Unset("docker:auto-scale:enabled")
	config.Set("docker:auto-scale:max-container-count", 2)
	defer config.Unset("docker:auto-scale:max-container-count")
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("POST", "/docker/autoscale/run", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	c.Assert(recorder.Header().Get("Content-Type"), check.Equals, "application/x-json-stream")
	body := recorder.Body.String()
	parts := strings.Split(body, "\n")
	c.Assert(parts, check.DeepEquals, []string{
		`{"Message":"running scaler *docker.countScaler for \"pool\": \"pool1\"\n"}`,
		`{"Message":"nothing to do for \"pool\": \"pool1\"\n"}`,
		``,
	})
	c.Assert(eventtest.EventDesc{
		Target: event.Target{Type: event.TargetTypePool},
		Owner:  s.token.GetUserName(),
		Kind:   "node.autoscale.update.run",
	}, eventtest.HasEvent)
}
Exemplo n.º 4
0
func (s *HandlersSuite) TestMoveContainersHandler(c *check.C) {
	recorder := httptest.NewRecorder()
	v := url.Values{}
	v.Set("from", "localhost")
	v.Set("to", "127.0.0.1")
	b := strings.NewReader(v.Encode())
	request, err := http.NewRequest("POST", "/docker/containers/move", b)
	c.Assert(err, check.IsNil)
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	mainDockerProvisioner.Cluster().Register(cluster.Node{Address: "http://localhost:2375"})
	mainDockerProvisioner.Cluster().Register(cluster.Node{Address: "http://127.0.0.1:2375"})
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	c.Assert(recorder.Header().Get("Content-Type"), check.Equals, "application/x-json-stream")
	validJson := fmt.Sprintf("[%s]", strings.Replace(strings.Trim(recorder.Body.String(), "\n "), "\n", ",", -1))
	var result []tsuruIo.SimpleJsonMessage
	err = json.Unmarshal([]byte(validJson), &result)
	c.Assert(err, check.IsNil)
	c.Assert(result, check.DeepEquals, []tsuruIo.SimpleJsonMessage{
		{Message: "No units to move in localhost\n"},
		{Message: "Containers moved successfully!\n"},
	})
	c.Assert(eventtest.EventDesc{
		Target: event.Target{Type: event.TargetTypeNode, Value: "localhost"},
		Owner:  s.token.GetUserName(),
		Kind:   "node.update.move.containers",
		StartCustomData: []map[string]interface{}{
			{"name": "from", "value": "localhost"},
			{"name": "to", "value": "127.0.0.1"},
		},
	}, eventtest.HasEvent)
}
Exemplo n.º 5
0
func (s *HandlersSuite) TestUpdateNodeHandler(c *check.C) {
	mainDockerProvisioner.cluster, _ = cluster.New(&segregatedScheduler{}, &cluster.MapStorage{},
		cluster.Node{Address: "localhost:1999", Metadata: map[string]string{
			"m1": "v1",
			"m2": "v2",
		}},
	)
	opts := provision.AddPoolOptions{Name: "pool1"}
	err := provision.AddPool(opts)
	defer provision.RemovePool("pool1")
	json := `{"address": "localhost:1999", "m1": "", "m2": "v9", "m3": "v8"}`
	b := bytes.NewBufferString(json)
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("PUT", "/docker/node", b)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	nodes, err := mainDockerProvisioner.getCluster().Nodes()
	c.Assert(err, check.IsNil)
	c.Assert(nodes, check.HasLen, 1)
	c.Assert(nodes[0].Metadata, check.DeepEquals, map[string]string{
		"m2": "v9",
		"m3": "v8",
	})
}
Exemplo n.º 6
0
func (s *HandlersSuite) TestAutoScaleRunHandler(c *check.C) {
	mainDockerProvisioner.cluster, _ = cluster.New(&segregatedScheduler{}, &cluster.MapStorage{},
		cluster.Node{Address: "localhost:1999", Metadata: map[string]string{
			"pool": "pool1",
		}},
	)
	config.Set("docker:auto-scale:group-by-metadata", "pool")
	config.Set("docker:auto-scale:max-container-count", 2)
	defer config.Unset("docker:auto-scale:max-container-count")
	defer config.Unset("docker:auto-scale:group-by-metadata")
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("POST", "/docker/autoscale/run", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	body := recorder.Body.String()
	parts := strings.Split(body, "\n")
	c.Assert(parts, check.DeepEquals, []string{
		`{"Message":"[node autoscale] running scaler *docker.countScaler for \"pool\": \"pool1\"\n"}`,
		`{"Message":"[node autoscale] nothing to do for \"pool\": \"pool1\"\n"}`,
		``,
	})
}
Exemplo n.º 7
0
func (s *HandlersSuite) TestDockerLogsInfoHandler(c *check.C) {
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("GET", "/docker/logs", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	c.Assert(recorder.Header().Get("Content-Type"), check.Equals, "application/json")
	var conf map[string]container.DockerLogConfig
	err = json.Unmarshal(recorder.Body.Bytes(), &conf)
	c.Assert(err, check.IsNil)
	c.Assert(conf, check.DeepEquals, map[string]container.DockerLogConfig{
		"": {},
	})
	newConf := container.DockerLogConfig{Driver: "syslog"}
	err = newConf.Save("p1")
	c.Assert(err, check.IsNil)
	request, err = http.NewRequest("GET", "/docker/logs", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	recorder = httptest.NewRecorder()
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	var conf2 map[string]container.DockerLogConfig
	err = json.Unmarshal(recorder.Body.Bytes(), &conf2)
	c.Assert(err, check.IsNil)
	c.Assert(conf2, check.DeepEquals, map[string]container.DockerLogConfig{
		"":   {},
		"p1": {Driver: "syslog", LogOpts: map[string]string{}},
	})
}
Exemplo n.º 8
0
func (s *HandlersSuite) TestAutoScaleListRulesWithLegacyConfig(c *check.C) {
	config.Set("docker:auto-scale:metadata-filter", "mypool")
	config.Set("docker:auto-scale:max-container-count", 4)
	config.Set("docker:auto-scale:scale-down-ratio", 1.5)
	config.Set("docker:auto-scale:prevent-rebalance", true)
	config.Set("docker:scheduler:max-used-memory", 0.9)
	defer config.Unset("docker:auto-scale:metadata-filter")
	defer config.Unset("docker:auto-scale:max-container-count")
	defer config.Unset("docker:auto-scale:scale-down-ratio")
	defer config.Unset("docker:auto-scale:prevent-rebalance")
	defer config.Unset("docker:scheduler:max-used-memory")
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("GET", "/docker/autoscale/rules", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	var rules []autoScaleRule
	err = json.Unmarshal(recorder.Body.Bytes(), &rules)
	c.Assert(err, check.IsNil)
	c.Assert(rules, check.DeepEquals, []autoScaleRule{
		{MetadataFilter: "mypool", Enabled: true, MaxContainerCount: 4, ScaleDownRatio: 1.5, PreventRebalance: true, MaxMemoryRatio: 0.9},
	})
}
Exemplo n.º 9
0
func (s *HandlersSuite) TestAutoScaleSetRuleInvalidRule(c *check.C) {
	rule := autoScaleRule{MetadataFilter: "pool1", Enabled: true, ScaleDownRatio: 0.9, MaxMemoryRatio: 2.0}
	v, err := form.EncodeToValues(&rule)
	c.Assert(err, check.IsNil)
	body := strings.NewReader(v.Encode())
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("POST", "/docker/autoscale/rules", body)
	c.Assert(err, check.IsNil)
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusInternalServerError)
	c.Assert(recorder.Body.String(), check.Matches, "(?s).*invalid rule, scale down ratio needs to be greater than 1.0, got 0.9.*")
	c.Assert(eventtest.EventDesc{
		Target: event.Target{Type: event.TargetTypePool, Value: "pool1"},
		Owner:  s.token.GetUserName(),
		Kind:   "node.autoscale.update",
		StartCustomData: []map[string]interface{}{
			{"name": "MetadataFilter", "value": "pool1"},
			{"name": "Enabled", "value": "true"},
			{"name": "ScaleDownRatio", "value": "0.9"},
			{"name": "MaxMemoryRatio", "value": "2"},
		},
		ErrorMatches: `.*invalid rule, scale down ratio needs to be greater than 1.0, got 0.9.*`,
	}, eventtest.HasEvent)
}
Exemplo n.º 10
0
func (s *S) TestRebalanceContainersDryBodyHandler(c *check.C) {
	p, err := s.startMultipleServersCluster()
	c.Assert(err, check.IsNil)
	mainDockerProvisioner = p
	defer s.stopMultipleServersCluster(p)
	err = s.newFakeImage(p, "tsuru/app-myapp", nil)
	c.Assert(err, check.IsNil)
	appInstance := provisiontest.NewFakeApp("myapp", "python", 0)
	defer p.Destroy(appInstance)
	p.Provision(appInstance)
	coll := p.collection()
	defer coll.Close()
	coll.Insert(container{ID: "container-id", AppName: appInstance.GetName(), Version: "container-version", Image: "tsuru/python", ProcessName: "web"})
	defer coll.RemoveAll(bson.M{"appname": appInstance.GetName()})
	imageId, err := appCurrentImageName(appInstance.GetName())
	c.Assert(err, check.IsNil)
	units, err := addContainersWithHost(&changeUnitsPipelineArgs{
		toHost:      "localhost",
		toAdd:       map[string]*containersToAdd{"web": {Quantity: 5}},
		app:         appInstance,
		imageId:     imageId,
		provisioner: p,
	})
	c.Assert(err, check.IsNil)
	conn, err := db.Conn()
	c.Assert(err, check.IsNil)
	defer conn.Close()
	appStruct := &app.App{
		Name:     appInstance.GetName(),
		Platform: appInstance.GetPlatform(),
	}
	err = conn.Apps().Insert(appStruct)
	c.Assert(err, check.IsNil)
	defer conn.Apps().Remove(bson.M{"name": appStruct.Name})
	err = conn.Apps().Update(
		bson.M{"name": appStruct.Name},
		bson.M{"$set": bson.M{"units": units}},
	)
	c.Assert(err, check.IsNil)
	recorder := httptest.NewRecorder()
	b := bytes.NewBufferString(`{"dry": "true"}`)
	request, err := http.NewRequest("POST", "/docker/containers/rebalance", b)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	body, err := ioutil.ReadAll(recorder.Body)
	c.Assert(err, check.IsNil)
	validJson := fmt.Sprintf("[%s]", strings.Replace(strings.Trim(string(body), "\n "), "\n", ",", -1))
	var result []tsuruIo.SimpleJsonMessage
	err = json.Unmarshal([]byte(validJson), &result)
	c.Assert(err, check.IsNil)
	c.Assert(len(result), check.Equals, 8)
	c.Assert(result[0].Message, check.Equals, "Rebalancing 6 units...\n")
	c.Assert(result[1].Message, check.Matches, "(?s)Would move unit .*")
	c.Assert(result[7].Message, check.Equals, "Containers rebalanced successfully!\n")
}
Exemplo n.º 11
0
func (s *HandlersSuite) TestHealingHistoryHandler(c *check.C) {
	evt1, err := event.NewInternal(&event.Opts{
		Target:       event.Target{Type: event.TargetTypeNode, Value: "addr1"},
		InternalKind: "healer",
		CustomData:   map[string]interface{}{"node": cluster.Node{Address: "addr1"}},
		Allowed:      event.Allowed(permission.PermPool),
	})
	c.Assert(err, check.IsNil)
	evt1.DoneCustomData(nil, cluster.Node{Address: "addr2"})
	time.Sleep(10 * time.Millisecond)
	evt2, err := event.NewInternal(&event.Opts{
		Target:       event.Target{Type: event.TargetTypeNode, Value: "addr3"},
		InternalKind: "healer",
		CustomData:   map[string]interface{}{"node": cluster.Node{Address: "addr3"}},
		Allowed:      event.Allowed(permission.PermPool),
	})
	c.Assert(err, check.IsNil)
	evt2.DoneCustomData(errors.New("some error"), cluster.Node{})
	time.Sleep(10 * time.Millisecond)
	evt3, err := event.NewInternal(&event.Opts{
		Target:       event.Target{Type: event.TargetTypeContainer, Value: "1234"},
		InternalKind: "healer",
		CustomData:   container.Container{ID: "1234"},
		Allowed:      event.Allowed(permission.PermApp),
	})
	c.Assert(err, check.IsNil)
	evt3.DoneCustomData(nil, container.Container{ID: "9876"})
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("GET", "/docker/healing", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	c.Assert(recorder.Header().Get("Content-Type"), check.Equals, "application/json")
	body := recorder.Body.Bytes()
	var healings []healer.HealingEvent
	err = json.Unmarshal(body, &healings)
	c.Assert(err, check.IsNil)
	c.Assert(healings, check.HasLen, 3)
	c.Assert(healings[2].StartTime.UTC().Format(time.Stamp), check.Equals, evt1.StartTime.UTC().Format(time.Stamp))
	c.Assert(healings[2].EndTime.UTC().Format(time.Stamp), check.Equals, evt1.EndTime.UTC().Format(time.Stamp))
	c.Assert(healings[2].FailingNode.Address, check.Equals, "addr1")
	c.Assert(healings[2].CreatedNode.Address, check.Equals, "addr2")
	c.Assert(healings[2].Error, check.Equals, "")
	c.Assert(healings[2].Successful, check.Equals, true)
	c.Assert(healings[2].Action, check.Equals, "node-healing")
	c.Assert(healings[1].FailingNode.Address, check.Equals, "addr3")
	c.Assert(healings[1].CreatedNode.Address, check.Equals, "")
	c.Assert(healings[1].Error, check.Equals, "some error")
	c.Assert(healings[1].Successful, check.Equals, false)
	c.Assert(healings[1].Action, check.Equals, "node-healing")
	c.Assert(healings[0].FailingContainer.ID, check.Equals, "1234")
	c.Assert(healings[0].CreatedContainer.ID, check.Equals, "9876")
	c.Assert(healings[0].Successful, check.Equals, true)
	c.Assert(healings[0].Error, check.Equals, "")
	c.Assert(healings[0].Action, check.Equals, "container-healing")
}
Exemplo n.º 12
0
func (s *HandlersSuite) TestAutoScaleHistoryNoContent(c *check.C) {
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("GET", "/docker/autoscale", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusNoContent)
}
Exemplo n.º 13
0
func (s *HandlersSuite) TestMoveContainersEmptyBodyHandler(c *check.C) {
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("POST", "/docker/containers/move", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusBadRequest)
}
Exemplo n.º 14
0
func (c *apiCmd) Run(context *cmd.Context, client *cmd.Client) error {
	err := config.Check([]config.Checker{CheckProvisioner, CheckBeanstalkd})
	if err != nil {
		return err
	}
	if c.checkOnly {
		return nil
	}
	api.RunServer(c.dry)
	return nil
}
Exemplo n.º 15
0
func (s *HandlersSuite) TestBsEnvSetHandlerUpdateExisting(c *check.C) {
	coll, err := bsCollection()
	c.Assert(err, check.IsNil)
	defer coll.Close()
	err = coll.Insert(bsConfig{ID: bsUniqueID,
		Image: "myimg",
		Envs: []bsEnv{
			{Name: "VAR1", Value: "VAL1"},
			{Name: "VAR2", Value: "VAL2"},
		},
		Pools: []bsPoolEnvs{
			{
				Name: "POOL1",
				Envs: []bsEnv{
					{Name: "VAR3", Value: "VAL3"},
					{Name: "VAR4", Value: "VAL4"},
				},
			},
		},
	})
	c.Assert(err, check.IsNil)
	recorder := httptest.NewRecorder()
	json := `{
		"image": "ignored",
		"envs": [
			{"name": "VAR1", "value": ""},
			{"name": "VAR3", "value": "VAL3"}
		],
		"pools": [
			{
				"name": "POOL1",
				"envs": [
					{"name": "VAR3", "value": ""}
				]
			}
		]
	}`
	body := bytes.NewBufferString(json)
	request, err := http.NewRequest("POST", "/docker/bs/env", body)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusNoContent)
	conf, err := loadBsConfig()
	c.Assert(err, check.IsNil)
	c.Assert(conf.Image, check.Equals, "myimg")
	sort.Sort(bsEnvList(conf.Envs))
	c.Assert(conf.Envs, check.DeepEquals, []bsEnv{{Name: "VAR2", Value: "VAL2"}, {Name: "VAR3", Value: "VAL3"}})
	c.Assert(conf.Pools, check.DeepEquals, []bsPoolEnvs{
		{Name: "POOL1", Envs: []bsEnv{{Name: "VAR4", Value: "VAL4"}}},
	})
}
Exemplo n.º 16
0
func (s *HandlersSuite) TestMoveContainersEmptyToHandler(c *check.C) {
	recorder := httptest.NewRecorder()
	b := bytes.NewBufferString(`{"from": "fromhost", "to": ""}`)
	request, err := http.NewRequest("POST", "/docker/containers/move", b)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusInternalServerError)
	body, err := ioutil.ReadAll(recorder.Body)
	c.Assert(err, check.IsNil)
	c.Assert(string(body), check.Equals, "Invalid params: from: fromhost - to: \n")
}
Exemplo n.º 17
0
func (s *HandlersSuite) TestMoveContainersEmptyBodyHandler(c *check.C) {
	recorder := httptest.NewRecorder()
	b := bytes.NewBufferString(``)
	request, err := http.NewRequest("POST", "/docker/containers/move", b)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusInternalServerError)
	body, err := ioutil.ReadAll(recorder.Body)
	c.Assert(err, check.IsNil)
	c.Assert(string(body), check.Equals, "unexpected end of JSON input\n")
}
Exemplo n.º 18
0
func (s *HandlersSuite) TestMoveContainerNotFound(c *check.C) {
	recorder := httptest.NewRecorder()
	mainDockerProvisioner.Cluster().Register(cluster.Node{Address: "http://127.0.0.1:2375"})
	v := url.Values{}
	v.Set("to", "127.0.0.1")
	b := strings.NewReader(v.Encode())
	request, err := http.NewRequest("POST", "/docker/container/myid/move", b)
	c.Assert(err, check.IsNil)
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusNotFound)
}
Exemplo n.º 19
0
func (s *HandlersSuite) TestBsUpgradeHandler(c *check.C) {
	err := saveBsImage("tsuru/bs@sha256:abcef384829283eff")
	c.Assert(err, check.IsNil)
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("POST", "/docker/bs/upgrade", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusNoContent)
	conf, err := loadBsConfig()
	c.Assert(err, check.IsNil)
	c.Assert(conf.Image, check.Equals, "")
}
Exemplo n.º 20
0
func (s *HandlersSuite) TestMoveContainersEmptyToHandler(c *check.C) {
	recorder := httptest.NewRecorder()
	v := url.Values{}
	v.Set("from", "fromhost")
	v.Set("to", "")
	b := strings.NewReader(v.Encode())
	request, err := http.NewRequest("POST", "/docker/containers/move", b)
	c.Assert(err, check.IsNil)
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusInternalServerError)
	c.Assert(recorder.Body.String(), check.Equals, "Invalid params: from: fromhost - to: \n")
}
Exemplo n.º 21
0
func (s *HandlersSuite) TestAutoScaleConfigHandler(c *check.C) {
	config.Set("docker:auto-scale:enabled", true)
	defer config.Unset("docker:auto-scale:enabled")
	expected, err := json.Marshal(mainDockerProvisioner.initAutoScaleConfig())
	c.Assert(err, check.IsNil)
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("GET", "/docker/autoscale/config", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	c.Assert(recorder.Header().Get("Content-Type"), check.Equals, "application/json")
	c.Assert(recorder.Body.String(), check.Equals, string(expected)+"\n")
}
Exemplo n.º 22
0
func (s *HandlersSuite) TestAutoScaleListRulesEmpty(c *check.C) {
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("GET", "/docker/autoscale/rules", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	var rules []autoScaleRule
	err = json.Unmarshal(recorder.Body.Bytes(), &rules)
	c.Assert(err, check.IsNil)
	c.Assert(rules, check.DeepEquals, []autoScaleRule{
		{Enabled: true, ScaleDownRatio: 1.333, Error: "invalid rule, either memory information or max container count must be set"},
	})
}
Exemplo n.º 23
0
func (s *HandlersSuite) TestAutoScaleHistoryHandler(c *check.C) {
	evt1, err := event.NewInternal(&event.Opts{
		Target:       event.Target{Type: poolMetadataName, Value: "poolx"},
		InternalKind: autoScaleEventKind,
		Allowed:      event.Allowed(permission.PermPool),
	})
	c.Assert(err, check.IsNil)
	evt1.Logf("my evt1")
	err = evt1.DoneCustomData(nil, evtCustomData{
		Result: &scalerResult{ToAdd: 1, Reason: "r1"},
	})
	c.Assert(err, check.IsNil)
	time.Sleep(100 * time.Millisecond)
	evt2, err := event.NewInternal(&event.Opts{
		Target:       event.Target{Type: poolMetadataName, Value: "pooly"},
		InternalKind: autoScaleEventKind,
		Allowed:      event.Allowed(permission.PermPool),
	})
	c.Assert(err, check.IsNil)
	evt2.Logf("my evt2")
	err = evt2.DoneCustomData(nil, evtCustomData{
		Result: &scalerResult{ToRebalance: true, Reason: "r2"},
	})
	c.Assert(err, check.IsNil)
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("GET", "/docker/autoscale", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	c.Assert(recorder.Header().Get("Content-Type"), check.Equals, "application/json")
	body := recorder.Body.Bytes()
	history := []autoScaleEvent{}
	err = json.Unmarshal(body, &history)
	c.Assert(err, check.IsNil)
	c.Assert(history, check.HasLen, 2)
	c.Assert(evt1.StartTime.Sub(history[1].StartTime) < time.Second, check.Equals, true)
	c.Assert(evt2.StartTime.Sub(history[0].StartTime) < time.Second, check.Equals, true)
	c.Assert(history[1].MetadataValue, check.Equals, "poolx")
	c.Assert(history[0].MetadataValue, check.Equals, "pooly")
	c.Assert(history[1].Action, check.Equals, "add")
	c.Assert(history[0].Action, check.Equals, "rebalance")
	c.Assert(history[1].Reason, check.Equals, "r1")
	c.Assert(history[0].Reason, check.Equals, "r2")
	c.Assert(history[1].Log, check.Equals, "my evt1\n")
	c.Assert(history[0].Log, check.Equals, "my evt2\n")
}
Exemplo n.º 24
0
func (s *HandlersSuite) TestAutoScaleDeleteRuleNotFound(c *check.C) {
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("DELETE", "/docker/autoscale/rules/mypool", nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusNotFound)
	c.Assert(recorder.Body.String(), check.Equals, "rule not found\n")
	c.Assert(eventtest.EventDesc{
		Target:       event.Target{Type: event.TargetTypePool, Value: "mypool"},
		Owner:        s.token.GetUserName(),
		Kind:         "node.autoscale.delete",
		ErrorMatches: `rule not found`,
	}, eventtest.HasEvent)
}
Exemplo n.º 25
0
func (s *HandlersSuite) TestBsEnvSetHandler(c *check.C) {
	recorder := httptest.NewRecorder()
	json := `{
		"image": "ignored",
		"envs": [
			{"name": "VAR1", "value": "VALUE1"},
			{"name": "VAR2", "value": "VALUE2"}
		],
		"pools": [
			{
				"name": "POOL1",
				"envs": [
					{"name": "VAR3", "value": "VALUE3"},
					{"name": "VAR4", "value": "VALUE4"}
				]
			},
			{
				"name": "POOL2",
				"envs": [
					{"name": "VAR5", "value": "VALUE5"},
					{"name": "VAR6", "value": "VALUE6"}
				]
			}
		]
	}`
	body := bytes.NewBufferString(json)
	request, err := http.NewRequest("POST", "/docker/bs/env", body)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusNoContent)
	conf, err := loadBsConfig()
	c.Assert(err, check.IsNil)
	c.Assert(conf.Image, check.Equals, "")
	sort.Sort(bsEnvList(conf.Envs))
	c.Assert(conf.Envs, check.DeepEquals, []bsEnv{{Name: "VAR1", Value: "VALUE1"}, {Name: "VAR2", Value: "VALUE2"}})
	c.Assert(conf.Pools, check.HasLen, 2)
	sort.Sort(bsPoolEnvsList(conf.Pools))
	sort.Sort(bsEnvList(conf.Pools[0].Envs))
	sort.Sort(bsEnvList(conf.Pools[1].Envs))
	c.Assert(conf.Pools, check.DeepEquals, []bsPoolEnvs{
		{Name: "POOL1", Envs: []bsEnv{{Name: "VAR3", Value: "VALUE3"}, {Name: "VAR4", Value: "VALUE4"}}},
		{Name: "POOL2", Envs: []bsEnv{{Name: "VAR5", Value: "VALUE5"}, {Name: "VAR6", Value: "VALUE6"}}},
	})
}
Exemplo n.º 26
0
func (s *HandlersSuite) TestMoveContainerHandler(c *check.C) {
	recorder := httptest.NewRecorder()
	b := bytes.NewBufferString(`{"to": "127.0.0.1"}`)
	request, err := http.NewRequest("POST", "/docker/container/myid/move", b)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	body, err := ioutil.ReadAll(recorder.Body)
	c.Assert(err, check.IsNil)
	var result tsuruIo.SimpleJsonMessage
	err = json.Unmarshal(body, &result)
	c.Assert(err, check.IsNil)
	expected := tsuruIo.SimpleJsonMessage{Message: "Error trying to move container: unit not found\n"}
	c.Assert(result, check.DeepEquals, expected)
}
Exemplo n.º 27
0
func (c *apiCmd) Run(context *cmd.Context, client *cmd.Client) error {
	err := config.CheckWithWarnings([]config.Checker{
		checkProvisioner,
		checkBeanstalkd,
		checkBasicConfig,
		checkGandalf,
		checkPubSub,
		checkQueue,
	}, context.Stderr)
	if err != nil {
		return err
	}
	if c.checkOnly {
		return nil
	}
	api.RunServer(c.dry)
	return nil
}
Exemplo n.º 28
0
func (s *S) TestDockerLogsUpdateHandlerWithRestartSomeApps(c *check.C) {
	appPools := [][]string{{"app1", "POOL1"}, {"app2", "POOL2"}, {"app3", "POOL2"}}
	for _, appPool := range appPools {
		opts := provision.AddPoolOptions{Name: appPool[1]}
		provision.AddPool(opts)
		err := s.newFakeImage(s.p, "tsuru/app-"+appPool[0], nil)
		c.Assert(err, check.IsNil)
		appInstance := provisiontest.NewFakeApp(appPool[0], "python", 0)
		appStruct := &app.App{
			Name:     appInstance.GetName(),
			Platform: appInstance.GetPlatform(),
			Pool:     opts.Name,
		}
		err = s.storage.Apps().Insert(appStruct)
		c.Assert(err, check.IsNil)
		err = s.p.Provision(appStruct)
		c.Assert(err, check.IsNil)
	}
	values := url.Values{
		"pool":                   []string{"POOL2"},
		"restart":                []string{"true"},
		"Driver":                 []string{"awslogs"},
		"LogOpts.awslogs-region": []string{"sa-east1"},
	}
	recorder := httptest.NewRecorder()
	reader := strings.NewReader(values.Encode())
	request, err := http.NewRequest("POST", "/docker/logs", reader)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	responseParts := strings.Split(recorder.Body.String(), "\n")
	c.Assert(responseParts, check.HasLen, 17)
	c.Assert(responseParts[0], check.Equals, "{\"Message\":\"Log config successfully updated.\\n\"}")
	c.Assert(responseParts[1], check.Equals, "{\"Message\":\"Restarting 2 applications: [app2, app3]\\n\"}")
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	entries, err := container.LogLoadAll()
	c.Assert(err, check.IsNil)
	c.Assert(entries, check.DeepEquals, map[string]container.DockerLogConfig{
		"":      {},
		"POOL2": {Driver: "awslogs", LogOpts: map[string]string{"awslogs-region": "sa-east1"}},
	})
}
Exemplo n.º 29
0
func (s *HandlersSuite) TestBsEnvSetHandlerForbiddenVar(c *check.C) {
	recorder := httptest.NewRecorder()
	json := `{
		"image": "ignored",
		"envs": [
			{"name": "TSURU_ENDPOINT", "value": "VAL"}
		]
	}`
	body := bytes.NewBufferString(json)
	request, err := http.NewRequest("POST", "/docker/bs/env", body)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusBadRequest)
	c.Assert(recorder.Body.String(), check.Equals, "cannot set TSURU_ENDPOINT variable\n")
	_, err = loadBsConfig()
	c.Assert(err, check.ErrorMatches, "not found")
}
Exemplo n.º 30
0
func (s *HandlersSuite) TestMoveContainersHandler(c *check.C) {
	recorder := httptest.NewRecorder()
	b := bytes.NewBufferString(`{"from": "localhost", "to": "127.0.0.1"}`)
	request, err := http.NewRequest("POST", "/docker/containers/move", b)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	body, err := ioutil.ReadAll(recorder.Body)
	c.Assert(err, check.IsNil)
	validJson := fmt.Sprintf("[%s]", strings.Replace(strings.Trim(string(body), "\n "), "\n", ",", -1))
	var result []tsuruIo.SimpleJsonMessage
	err = json.Unmarshal([]byte(validJson), &result)
	c.Assert(err, check.IsNil)
	c.Assert(result, check.DeepEquals, []tsuruIo.SimpleJsonMessage{
		{Message: "No units to move in localhost\n"},
		{Message: "Containers moved successfully!\n"},
	})
}