示例#1
0
文件: node_test.go 项目: tsuru/tsuru
func (s *S) TestListUnitsByAppHandler(c *check.C) {
	a := app.App{Name: "myapp", Platform: "zend", TeamOwner: s.team.Name}
	err := app.CreateApp(&a, s.user)
	c.Assert(err, check.IsNil)
	err = a.AddUnits(2, "", nil)
	c.Assert(err, check.IsNil)
	req, err := http.NewRequest("GET", "/node/apps/myapp/containers", nil)
	c.Assert(err, check.IsNil)
	req.Header.Set("Authorization", "bearer "+s.token.GetValue())
	rec := httptest.NewRecorder()
	server := RunServer(true)
	server.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusOK)
	body, err := ioutil.ReadAll(rec.Body)
	c.Assert(err, check.IsNil)
	var result []provision.Unit
	var resultMap []map[string]interface{}
	err = json.Unmarshal(body, &result)
	c.Assert(err, check.IsNil)
	err = json.Unmarshal(body, &resultMap)
	c.Assert(err, check.IsNil)
	c.Assert(result[0].ID, check.Equals, "myapp-0")
	c.Assert(result[0].Type, check.Equals, "zend")
	c.Assert(result[1].ID, check.Equals, "myapp-1")
	c.Assert(result[1].Type, check.Equals, "zend")
	c.Assert(resultMap[0]["HostAddr"], check.Equals, "10.10.10.1")
	c.Assert(resultMap[1]["HostAddr"], check.Equals, "10.10.10.2")
	c.Assert(resultMap[0]["HostPort"], check.Equals, "1")
	c.Assert(resultMap[1]["HostPort"], check.Equals, "2")
	c.Assert(resultMap[0]["IP"], check.Equals, "10.10.10.1")
	c.Assert(resultMap[1]["IP"], check.Equals, "10.10.10.2")
}
示例#2
0
func (s *S) TestRebuildRoutesTCPRoutes(c *check.C) {
	a := app.App{Name: "my-test-app", TeamOwner: s.team.Name}
	err := app.CreateApp(&a, s.user)
	c.Assert(err, check.IsNil)
	err = provisiontest.ProvisionerInstance.AddUnits(&a, 3, "web", nil)
	c.Assert(err, check.IsNil)
	units, err := a.Units()
	c.Assert(err, check.IsNil)
	for _, u := range units {
		routertest.FakeRouter.RemoveRoute(a.Name, u.Address)
		routertest.FakeRouter.AddRoute(a.Name, &url.URL{Scheme: "tcp", Host: u.Address.Host})
	}
	changes, err := rebuild.RebuildRoutes(&a)
	c.Assert(err, check.IsNil)
	c.Assert(changes.Added, check.IsNil)
	c.Assert(changes.Removed, check.IsNil)
	routes, err := routertest.FakeRouter.Routes(a.Name)
	c.Assert(err, check.IsNil)
	c.Assert(routes, check.HasLen, 3)
	c.Assert(routertest.FakeRouter.HasRoute(a.Name, units[0].Address.Host), check.Equals, true)
	c.Assert(routertest.FakeRouter.HasRoute(a.Name, units[1].Address.Host), check.Equals, true)
	c.Assert(routertest.FakeRouter.HasRoute(a.Name, units[2].Address.Host), check.Equals, true)
	app, err := app.GetByName(a.Name)
	c.Assert(err, check.IsNil)
	addr, err := routertest.FakeRouter.Addr(app.Name)
	c.Assert(err, check.IsNil)
	c.Assert(app.Ip, check.Equals, addr)
}
示例#3
0
func (s *S) TestSaveUnitsForwardShouldMaintainData(c *gocheck.C) {
	a := app.App{
		Name:     "otherapp",
		Platform: "zend",
		Deploys:  10,
	}
	conn, err := db.Conn()
	c.Assert(err, gocheck.IsNil)
	defer conn.Close()
	err = conn.Apps().Insert(a)
	c.Assert(err, gocheck.IsNil)
	a.Deploys = 0
	defer conn.Apps().Remove(bson.M{"name": a.Name})
	container := container{
		ID:       "id",
		Type:     "python",
		HostAddr: "",
		AppName:  a.Name,
	}
	coll := collection()
	c.Assert(err, gocheck.IsNil)
	coll.Insert(&container)
	context := action.FWContext{Params: []interface{}{&a}}
	_, err = saveUnits.Forward(context)
	c.Assert(err, gocheck.IsNil)
	app, err := app.GetByName(a.Name)
	c.Assert(err, gocheck.IsNil)
	c.Assert(app.Units[0].Name, gocheck.Equals, "id")
	c.Assert(int(app.Deploys), gocheck.Equals, 10)
}
示例#4
0
func (s *S) TestRebuildRoutes(c *check.C) {
	a := app.App{Name: "my-test-app", TeamOwner: s.team.Name}
	err := app.CreateApp(&a, s.user)
	c.Assert(err, check.IsNil)
	err = provisiontest.ProvisionerInstance.AddUnits(&a, 3, "web", nil)
	c.Assert(err, check.IsNil)
	units, err := a.Units()
	c.Assert(err, check.IsNil)
	routertest.FakeRouter.RemoveRoute(a.Name, units[2].Address)
	routertest.FakeRouter.AddRoute(a.Name, &url.URL{Scheme: "http", Host: "invalid:1234"})
	changes, err := rebuild.RebuildRoutes(&a)
	c.Assert(err, check.IsNil)
	c.Assert(changes.Added, check.DeepEquals, []string{units[2].Address.String()})
	c.Assert(changes.Removed, check.DeepEquals, []string{"http://invalid:1234"})
	routes, err := routertest.FakeRouter.Routes(a.Name)
	c.Assert(err, check.IsNil)
	c.Assert(routes, check.HasLen, 3)
	c.Assert(routertest.FakeRouter.HasRoute(a.Name, units[0].Address.String()), check.Equals, true)
	c.Assert(routertest.FakeRouter.HasRoute(a.Name, units[1].Address.String()), check.Equals, true)
	c.Assert(routertest.FakeRouter.HasRoute(a.Name, units[2].Address.String()), check.Equals, true)
	app, err := app.GetByName(a.Name)
	c.Assert(err, check.IsNil)
	addr, err := routertest.FakeRouter.Addr(app.Name)
	c.Assert(err, check.IsNil)
	c.Assert(app.Ip, check.Equals, addr)
}
示例#5
0
文件: docker.go 项目: kennylixi/tsuru
func moveOneContainerInDB(a *app.App, oldContainer container, newUnit provision.Unit) error {
	appDBMutex.Lock()
	defer appDBMutex.Unlock()
	err := a.AddUnitsToDB([]provision.Unit{newUnit})
	if err != nil {
		return err
	}
	return a.RemoveUnitFromDB(oldContainer.ID)
}
示例#6
0
func (s *S) TestDeployRemoveContainersEvenWhenTheyreNotInTheAppsCollection(c *gocheck.C) {
	h := &tsrTesting.TestHandler{}
	gandalfServer := tsrTesting.StartGandalfTestServer(h)
	defer gandalfServer.Close()
	go s.stopContainers(3)
	err := newImage("tsuru/python", s.server.URL())
	c.Assert(err, gocheck.IsNil)
	cont1, err := s.newContainer(nil)
	defer s.removeTestContainer(cont1)
	c.Assert(err, gocheck.IsNil)
	cont2, err := s.newContainer(nil)
	defer s.removeTestContainer(cont2)
	c.Assert(err, gocheck.IsNil)
	defer rtesting.FakeRouter.RemoveBackend(cont1.AppName)
	var p dockerProvisioner
	a := app.App{
		Name:     "otherapp",
		Platform: "python",
		Units:    []app.Unit{{Name: "i-0800", State: "started"}},
	}
	conn, err := db.Conn()
	defer conn.Close()
	err = conn.Apps().Insert(a)
	c.Assert(err, gocheck.IsNil)
	defer conn.Apps().Remove(bson.M{"name": a.Name})
	p.Provision(&a)
	defer p.Destroy(&a)
	fexec := &etesting.FakeExecutor{}
	setExecut(fexec)
	defer setExecut(nil)
	var w bytes.Buffer
	err = app.Deploy(app.DeployOptions{
		App:          &a,
		Version:      "master",
		Commit:       "123",
		OutputStream: &w,
	})

	c.Assert(err, gocheck.IsNil)
	time.Sleep(1e9)
	defer p.Destroy(&a)
	q, err := getQueue()
	c.Assert(err, gocheck.IsNil)
	for _, u := range a.ProvisionedUnits() {
		message, err := q.Get(1e6)
		c.Assert(err, gocheck.IsNil)
		c.Assert(message.Action, gocheck.Equals, app.BindService)
		c.Assert(message.Args[0], gocheck.Equals, a.GetName())
		c.Assert(message.Args[1], gocheck.Equals, u.GetName())
	}
	coll := collection()
	defer coll.Close()
	n, err := coll.Find(bson.M{"appname": cont1.AppName}).Count()
	c.Assert(err, gocheck.IsNil)
	c.Assert(n, gocheck.Equals, 2)
}
示例#7
0
文件: app.go 项目: tsuru/tsuru
func minifyApp(app app.App) (miniApp, error) {
	units, err := app.Units()
	if err != nil {
		return miniApp{}, err
	}
	return miniApp{
		Name:  app.GetName(),
		Units: units,
		CName: app.GetCname(),
		Ip:    app.GetIp(),
		Lock:  app.GetLock(),
	}, nil
}
示例#8
0
func (s *S) TestRebuildRoutesBetweenRouters(c *check.C) {
	a := app.App{Name: "my-test-app", TeamOwner: s.team.Name}
	err := app.CreateApp(&a, s.user)
	c.Assert(err, check.IsNil)
	err = provisiontest.ProvisionerInstance.AddUnits(&a, 1, "web", nil)
	c.Assert(err, check.IsNil)
	oldIp := a.Ip
	a.Plan = app.Plan{Router: "fake-hc"}
	_, err = rebuild.RebuildRoutes(&a)
	c.Assert(err, check.IsNil)
	c.Assert(a.Ip, check.Not(check.Equals), oldIp)
	na, err := app.GetByName(a.Name)
	c.Assert(err, check.IsNil)
	c.Assert(na.Ip, check.Equals, a.Ip)
}
示例#9
0
func (s *S) TestBindServiceForward(c *gocheck.C) {
	a := app.App{Name: "cribcaged", Platform: "python"}
	opts := app.DeployOptions{App: &a}
	context := action.FWContext{Params: []interface{}{opts}}
	_, err := bindService.Forward(context)
	c.Assert(err, gocheck.IsNil)
	q, err := getQueue()
	c.Assert(err, gocheck.IsNil)
	for _, u := range a.Units() {
		message, err := q.Get(1e6)
		c.Assert(err, gocheck.IsNil)
		c.Assert(message.Action, gocheck.Equals, app.BindService)
		c.Assert(message.Args[0], gocheck.Equals, a.GetName())
		c.Assert(message.Args[1], gocheck.Equals, u.Name)
	}
}
示例#10
0
func (s *LogSuite) TestLogRemoveAll(c *check.C) {
	a := app.App{Name: "words"}
	request, err := http.NewRequest("DELETE", "/logs", nil)
	c.Assert(err, check.IsNil)
	recorder := httptest.NewRecorder()
	err = s.conn.Apps().Insert(a)
	c.Assert(err, check.IsNil)
	defer s.conn.Apps().Remove(bson.M{"name": a.Name})
	err = a.Log("last log msg", "tsuru", "")
	c.Assert(err, check.IsNil)
	err = logRemove(recorder, request, s.token)
	c.Assert(err, check.IsNil)
	count, err := s.logConn.Logs(a.Name).Find(nil).Count()
	c.Assert(err, check.IsNil)
	c.Assert(count, check.Equals, 0)
}
示例#11
0
文件: app.go 项目: RichardKnop/tsuru
func minifyApp(app app.App) miniApp {
	return miniApp{
		Name:  app.Name,
		Units: app.Units(),
		CName: app.CName,
		Ip:    app.Ip,
	}
}
示例#12
0
func (s *S) TestDeploy(c *gocheck.C) {
	h := &tsrTesting.TestHandler{}
	gandalfServer := tsrTesting.StartGandalfTestServer(h)
	defer gandalfServer.Close()
	go s.stopContainers(1)
	err := newImage("tsuru/python", s.server.URL())
	c.Assert(err, gocheck.IsNil)
	fexec := &etesting.FakeExecutor{}
	setExecut(fexec)
	defer setExecut(nil)
	p := dockerProvisioner{}
	app.Provisioner = &p
	a := app.App{
		Name:     "otherapp",
		Platform: "python",
		Units:    []app.Unit{{Name: "i-0800", State: "started"}},
	}
	conn, err := db.Conn()
	defer conn.Close()
	err = conn.Apps().Insert(a)
	c.Assert(err, gocheck.IsNil)
	defer conn.Apps().Remove(bson.M{"name": a.Name})
	p.Provision(&a)
	defer p.Destroy(&a)
	w := writer{b: make([]byte, 2048)}
	err = app.Deploy(app.DeployOptions{
		App:          &a,
		Version:      "master",
		Commit:       "123",
		OutputStream: &w,
	})

	c.Assert(err, gocheck.IsNil)
	w.b = nil
	time.Sleep(6e9)
	q, err := getQueue()
	for _, u := range a.ProvisionedUnits() {
		message, err := q.Get(1e6)
		c.Assert(err, gocheck.IsNil)
		c.Assert(message.Action, gocheck.Equals, app.BindService)
		c.Assert(message.Args[0], gocheck.Equals, a.GetName())
		c.Assert(message.Args[1], gocheck.Equals, u.GetName())
	}
}
示例#13
0
func (s *S) TestDeployEnqueuesBindService(c *gocheck.C) {
	h := &tsrTesting.TestHandler{}
	gandalfServer := tsrTesting.StartGandalfTestServer(h)
	defer gandalfServer.Close()
	go s.stopContainers(1)
	err := newImage("tsuru/python", s.server.URL())
	c.Assert(err, gocheck.IsNil)
	setExecut(&etesting.FakeExecutor{})
	defer setExecut(nil)
	p := dockerProvisioner{}
	app.Provisioner = &p
	a := app.App{
		Name:     "otherapp",
		Platform: "python",
	}
	conn, err := db.Conn()
	defer conn.Close()
	err = conn.Apps().Insert(a)
	c.Assert(err, gocheck.IsNil)
	defer conn.Apps().Remove(bson.M{"name": a.Name})
	p.Provision(&a)
	defer p.Destroy(&a)
	w := safe.NewBuffer(make([]byte, 2048))
	err = app.Deploy(app.DeployOptions{
		App:          &a,
		Version:      "master",
		Commit:       "123",
		OutputStream: w,
	})
	c.Assert(err, gocheck.IsNil)
	defer p.Destroy(&a)
	q, err := getQueue()
	c.Assert(err, gocheck.IsNil)
	for _, u := range a.Units() {
		message, err := q.Get(1e6)
		c.Assert(err, gocheck.IsNil)
		c.Assert(message.Action, gocheck.Equals, app.BindService)
		c.Assert(message.Args[0], gocheck.Equals, a.GetName())
		c.Assert(message.Args[1], gocheck.Equals, u.Name)
	}
}
func (s *S) TestDeploy(c *gocheck.C) {
	h := &tsrTesting.TestHandler{}
	gandalfServer := tsrTesting.StartGandalfTestServer(h)
	defer gandalfServer.Close()
	go s.stopContainers(1)
	err := newImage("tsuru/python", s.server.URL())
	c.Assert(err, gocheck.IsNil)
	setExecut(&etesting.FakeExecutor{})
	defer setExecut(nil)
	p := dockerProvisioner{}
	a := app.App{
		Name:     "otherapp",
		Platform: "python",
	}
	conn, err := db.Conn()
	defer conn.Close()
	err = conn.Apps().Insert(a)
	c.Assert(err, gocheck.IsNil)
	defer conn.Apps().Remove(bson.M{"name": a.Name})
	p.Provision(&a)
	defer p.Destroy(&a)
	w := safe.NewBuffer(make([]byte, 2048))
	var serviceBodies []string
	rollback := s.addServiceInstance(c, a.Name, func(w http.ResponseWriter, r *http.Request) {
		data, _ := ioutil.ReadAll(r.Body)
		serviceBodies = append(serviceBodies, string(data))
		w.WriteHeader(http.StatusOK)
	})
	defer rollback()
	err = app.Deploy(app.DeployOptions{
		App:          &a,
		Version:      "master",
		Commit:       "123",
		OutputStream: w,
	})
	c.Assert(err, gocheck.IsNil)
	units := a.Units()
	c.Assert(units, gocheck.HasLen, 1)
	c.Assert(serviceBodies, gocheck.HasLen, 1)
	c.Assert(serviceBodies[0], gocheck.Matches, ".*unit-host="+units[0].Ip)
}
示例#15
0
func (s *LogSuite) TestLogRemoveByApp(c *check.C) {
	a := app.App{
		Name:  "words",
		Teams: []string{s.team.Name},
	}
	err := s.conn.Apps().Insert(a)
	c.Assert(err, check.IsNil)
	defer s.conn.Apps().Remove(bson.M{"name": a.Name})
	err = a.Log("last log msg", "tsuru", "")
	c.Assert(err, check.IsNil)
	a2 := app.App{Name: "words2"}
	err = s.conn.Apps().Insert(a2)
	c.Assert(err, check.IsNil)
	defer s.conn.Apps().Remove(bson.M{"name": a2.Name})
	err = a2.Log("last log msg2", "tsuru", "")
	c.Assert(err, check.IsNil)
	url := fmt.Sprintf("/logs?app=%s", a.Name)
	request, err := http.NewRequest("DELETE", url, nil)
	c.Assert(err, check.IsNil)
	recorder := httptest.NewRecorder()
	err = logRemove(recorder, request, s.token)
	c.Assert(err, check.IsNil)
	count, err := s.logConn.Logs(a2.Name).Find(nil).Count()
	c.Assert(err, check.IsNil)
	c.Assert(count, check.Equals, 1)
}
示例#16
0
文件: app.go 项目: edulemasson/tsuru
func minifyApp(app app.App) (miniApp, error) {
	units, err := app.Units()
	if err != nil {
		return miniApp{}, err
	}
	return miniApp{
		Name:  app.Name,
		Units: units,
		CName: app.CName,
		Ip:    app.Ip,
		Lock:  app.Lock,
	}, nil
}
示例#17
0
func (s *S) TestRebuildRoutesRecreatesCnames(c *check.C) {
	a := app.App{Name: "my-test-app", TeamOwner: s.team.Name}
	err := app.CreateApp(&a, s.user)
	c.Assert(err, check.IsNil)
	err = provisiontest.ProvisionerInstance.AddUnits(&a, 1, "web", nil)
	c.Assert(err, check.IsNil)
	units, err := a.Units()
	c.Assert(err, check.IsNil)
	err = a.AddCName("my.cname.com")
	c.Assert(err, check.IsNil)
	c.Assert(routertest.FakeRouter.HasCName("my.cname.com"), check.Equals, true)
	err = routertest.FakeRouter.UnsetCName("my.cname.com", a.Name)
	c.Assert(err, check.IsNil)
	c.Assert(routertest.FakeRouter.HasCName("my.cname.com"), check.Equals, false)
	changes, err := rebuild.RebuildRoutes(&a)
	c.Assert(err, check.IsNil)
	c.Assert(changes, check.DeepEquals, &rebuild.RebuildRoutesResult{})
	routes, err := routertest.FakeRouter.Routes(a.Name)
	c.Assert(err, check.IsNil)
	c.Assert(routes, check.HasLen, 1)
	c.Assert(routertest.FakeRouter.HasRoute(a.Name, units[0].Address.String()), check.Equals, true)
	c.Assert(routertest.FakeRouter.HasCName("my.cname.com"), check.Equals, true)
}
示例#18
0
func (s *S) TestRebuildRoutesRecreatesBackend(c *check.C) {
	a := app.App{Name: "my-test-app", TeamOwner: s.team.Name}
	err := app.CreateApp(&a, s.user)
	c.Assert(err, check.IsNil)
	err = provisiontest.ProvisionerInstance.AddUnits(&a, 3, "web", nil)
	c.Assert(err, check.IsNil)
	units, err := a.Units()
	c.Assert(err, check.IsNil)
	routertest.FakeRouter.RemoveBackend(a.Name)
	changes, err := rebuild.RebuildRoutes(&a)
	c.Assert(err, check.IsNil)
	sort.Strings(changes.Added)
	c.Assert(changes.Added, check.DeepEquals, []string{
		units[0].Address.String(),
		units[1].Address.String(),
		units[2].Address.String(),
	})
	routes, err := routertest.FakeRouter.Routes(a.Name)
	c.Assert(err, check.IsNil)
	c.Assert(routes, check.HasLen, 3)
	c.Assert(routertest.FakeRouter.HasRoute(a.Name, units[0].Address.String()), check.Equals, true)
	c.Assert(routertest.FakeRouter.HasRoute(a.Name, units[1].Address.String()), check.Equals, true)
	c.Assert(routertest.FakeRouter.HasRoute(a.Name, units[2].Address.String()), check.Equals, true)
}
示例#19
0
func (s *S) TestRebuildRoutesAfterSwap(c *check.C) {
	a1 := app.App{Name: "my-test-app-1", TeamOwner: s.team.Name}
	err := app.CreateApp(&a1, s.user)
	c.Assert(err, check.IsNil)
	a2 := app.App{Name: "my-test-app-2", TeamOwner: s.team.Name}
	err = app.CreateApp(&a2, s.user)
	c.Assert(err, check.IsNil)
	err = provisiontest.ProvisionerInstance.AddUnits(&a1, 3, "web", nil)
	c.Assert(err, check.IsNil)
	err = provisiontest.ProvisionerInstance.AddUnits(&a2, 2, "web", nil)
	c.Assert(err, check.IsNil)
	units1, err := a1.Units()
	c.Assert(err, check.IsNil)
	units2, err := a2.Units()
	c.Assert(err, check.IsNil)
	routertest.FakeRouter.AddRoute(a1.Name, &url.URL{Scheme: "http", Host: "invalid:1234"})
	routertest.FakeRouter.RemoveRoute(a2.Name, units2[0].Address)
	err = routertest.FakeRouter.Swap(a1.Name, a2.Name, false)
	c.Assert(err, check.IsNil)
	changes1, err := rebuild.RebuildRoutes(&a1)
	c.Assert(err, check.IsNil)
	changes2, err := rebuild.RebuildRoutes(&a2)
	c.Assert(err, check.IsNil)
	c.Assert(changes1.Added, check.IsNil)
	c.Assert(changes1.Removed, check.DeepEquals, []string{"http://invalid:1234"})
	c.Assert(changes2.Added, check.DeepEquals, []string{units2[0].Address.String()})
	c.Assert(changes2.Removed, check.IsNil)
	routes1, err := routertest.FakeRouter.Routes(a1.Name)
	c.Assert(err, check.IsNil)
	routes2, err := routertest.FakeRouter.Routes(a2.Name)
	c.Assert(err, check.IsNil)
	sort.Sort(URLList(routes1))
	sort.Sort(URLList(routes2))
	c.Assert(routes1, check.DeepEquals, []*url.URL{
		units1[0].Address,
		units1[1].Address,
		units1[2].Address,
	})
	c.Assert(routes2, check.DeepEquals, []*url.URL{
		units2[0].Address,
		units2[1].Address,
	})
	c.Assert(routertest.FakeRouter.HasRoute(a1.Name, units2[0].Address.String()), check.Equals, true)
	c.Assert(routertest.FakeRouter.HasRoute(a1.Name, units2[1].Address.String()), check.Equals, true)
	c.Assert(routertest.FakeRouter.HasRoute(a2.Name, units1[0].Address.String()), check.Equals, true)
	c.Assert(routertest.FakeRouter.HasRoute(a2.Name, units1[1].Address.String()), check.Equals, true)
	c.Assert(routertest.FakeRouter.HasRoute(a2.Name, units1[2].Address.String()), check.Equals, true)
}
示例#20
0
文件: app.go 项目: RichardKnop/tsuru
func getEmailsForRevoking(app *app.App, t *auth.Team) []string {
	var i int
	teams := app.GetTeams()
	users := make([]string, len(t.Users))
	for _, email := range t.Users {
		found := false
		for _, team := range teams {
			for _, user := range team.Users {
				if user == email {
					found = true
					break
				}
			}
		}
		if !found {
			users[i] = email
			i++
		}
	}
	return users[:i]
}
示例#21
0
文件: log_test.go 项目: reoring/tsuru
func (s *S) TestAddLogsHandler(c *check.C) {
	a1 := app.App{Name: "myapp1", Platform: "zend", TeamOwner: s.team.Name}
	err := app.CreateApp(&a1, s.user)
	c.Assert(err, check.IsNil)
	a2 := app.App{Name: "myapp2", Platform: "zend", TeamOwner: s.team.Name}
	err = app.CreateApp(&a2, s.user)
	c.Assert(err, check.IsNil)
	baseTime, err := time.Parse(time.RFC3339, "2015-06-16T15:00:00.000Z")
	c.Assert(err, check.IsNil)
	baseTime = baseTime.Local()
	bodyStr := `
	{"date": "2015-06-16T15:00:00.000Z", "message": "msg1", "source": "web", "appname": "myapp1", "unit": "unit1"}
	{"date": "2015-06-16T15:00:01.000Z", "message": "msg2", "source": "web", "appname": "myapp2", "unit": "unit2"}
	{"date": "2015-06-16T15:00:02.000Z", "message": "msg3", "source": "web", "appname": "myapp1", "unit": "unit3"}
	{"date": "2015-06-16T15:00:03.000Z", "message": "msg4", "source": "web", "appname": "myapp2", "unit": "unit4"}
	{"date": "2015-06-16T15:00:04.000Z", "message": "msg5", "source": "worker", "appname": "myapp1", "unit": "unit3"}
	`
	token, err := nativeScheme.AppLogin(app.InternalAppName)
	c.Assert(err, check.IsNil)
	m := RunServer(true)
	srv := httptest.NewServer(m)
	defer srv.Close()
	testServerUrl, err := url.Parse(srv.URL)
	c.Assert(err, check.IsNil)
	wsUrl := fmt.Sprintf("ws://%s/logs", testServerUrl.Host)
	config, err := websocket.NewConfig(wsUrl, "ws://localhost/")
	c.Assert(err, check.IsNil)
	config.Header.Set("Authorization", "bearer "+token.GetValue())
	wsConn, err := websocket.DialConfig(config)
	c.Assert(err, check.IsNil)
	defer wsConn.Close()
	_, err = wsConn.Write([]byte(bodyStr))
	c.Assert(err, check.IsNil)
	timeout := time.After(5 * time.Second)
	for {
		var (
			logs1 []app.Applog
			logs2 []app.Applog
		)
		logs1, err = a1.LastLogs(3, app.Applog{})
		c.Assert(err, check.IsNil)
		logs2, err = a2.LastLogs(2, app.Applog{})
		c.Assert(err, check.IsNil)
		if len(logs1) == 3 && len(logs2) == 2 {
			break
		}
		select {
		case <-timeout:
			c.Fatal("timeout waiting for logs")
			break
		default:
		}
	}
	logs, err := a1.LastLogs(3, app.Applog{})
	c.Assert(err, check.IsNil)
	c.Assert(logs, check.DeepEquals, []app.Applog{
		{Date: baseTime, Message: "msg1", Source: "web", AppName: "myapp1", Unit: "unit1"},
		{Date: baseTime.Add(2 * time.Second), Message: "msg3", Source: "web", AppName: "myapp1", Unit: "unit3"},
		{Date: baseTime.Add(4 * time.Second), Message: "msg5", Source: "worker", AppName: "myapp1", Unit: "unit3"},
	})
	logs, err = a2.LastLogs(2, app.Applog{})
	c.Assert(err, check.IsNil)
	c.Assert(logs, check.DeepEquals, []app.Applog{
		{Date: baseTime.Add(time.Second), Message: "msg2", Source: "web", AppName: "myapp2", Unit: "unit2"},
		{Date: baseTime.Add(3 * time.Second), Message: "msg4", Source: "web", AppName: "myapp2", Unit: "unit4"},
	})
}
示例#22
0
文件: app.go 项目: reoring/tsuru
func createApp(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	var a app.App
	defer r.Body.Close()
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return err
	}
	if err = json.Unmarshal(body, &a); err != nil {
		return err
	}
	teamContexts := permission.ContextsForPermission(t, permission.PermAppCreate, permission.CtxTeam)
	if a.TeamOwner == "" && len(teamContexts) == 1 {
		a.TeamOwner = teamContexts[0].Value
	}
	canCreate := permission.Check(t, permission.PermAppCreate,
		permission.Context(permission.CtxTeam, a.TeamOwner),
	)
	if !canCreate {
		return permission.ErrUnauthorized
	}
	u, err := t.User()
	if err != nil {
		return err
	}
	platform, err := app.GetPlatform(a.Platform)
	if err != nil {
		return err
	}
	if platform.Disabled {
		canUsePlat := permission.Check(t, permission.PermPlatformUpdate) ||
			permission.Check(t, permission.PermPlatformCreate)
		if !canUsePlat {
			return app.InvalidPlatformError{}
		}
	}
	rec.Log(u.Email, "create-app", "app="+a.Name, "platform="+a.Platform, "plan="+a.Plan.Name)
	err = app.CreateApp(&a, u)
	if err != nil {
		log.Errorf("Got error while creating app: %s", err)
		if e, ok := err.(*errors.ValidationError); ok {
			return &errors.HTTP{Code: http.StatusBadRequest, Message: e.Message}
		}
		if _, ok := err.(app.NoTeamsError); ok {
			return &errors.HTTP{
				Code:    http.StatusBadRequest,
				Message: "In order to create an app, you should be member of at least one team",
			}
		}
		if e, ok := err.(*app.AppCreationError); ok {
			if e.Err == app.ErrAppAlreadyExists {
				return &errors.HTTP{Code: http.StatusConflict, Message: e.Error()}
			}
			if _, ok := e.Err.(*quota.QuotaExceededError); ok {
				return &errors.HTTP{
					Code:    http.StatusForbidden,
					Message: "Quota exceeded",
				}
			}
		}
		if e, ok := err.(app.InvalidPlatformError); ok {
			return &errors.HTTP{Code: http.StatusNotFound, Message: e.Error()}
		}
		return err
	}
	repo, _ := repository.Manager().GetRepository(a.Name)
	msg := map[string]string{
		"status":         "success",
		"repository_url": repo.ReadWriteURL,
		"ip":             a.Ip,
	}
	jsonMsg, err := json.Marshal(msg)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "%s", jsonMsg)
	return nil
}
示例#23
0
func moveOneContainerInDB(a *app.App, oldContainer container, newUnit provision.Unit) error {
	appDBMutex.Lock()
	defer appDBMutex.Unlock()
	return a.AddUnitsToDB([]provision.Unit{newUnit})
}
示例#24
0
文件: app.go 项目: tsuru/tsuru
// title: app create
// path: /apps
// method: POST
// consume: application/x-www-form-urlencoded
// produce: application/json
// responses:
//   201: App created
//   400: Invalid data
//   401: Unauthorized
//   403: Quota exceeded
//   409: App already exists
func createApp(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
	err = r.ParseForm()
	if err != nil {
		return &errors.HTTP{Code: http.StatusBadRequest, Message: err.Error()}
	}
	var ia inputApp
	dec := form.NewDecoder(nil)
	dec.IgnoreCase(true)
	dec.IgnoreUnknownKeys(true)
	dec.DecodeValues(&ia, r.Form)
	a := app.App{
		TeamOwner:   ia.TeamOwner,
		Platform:    ia.Platform,
		Plan:        app.Plan{Name: ia.Plan},
		Name:        ia.Name,
		Description: ia.Description,
		Pool:        ia.Pool,
		RouterOpts:  ia.RouterOpts,
	}
	if a.TeamOwner == "" {
		a.TeamOwner, err = permission.TeamForPermission(t, permission.PermAppCreate)
		if err != nil {
			if err != permission.ErrTooManyTeams {
				return err
			}
			teams, listErr := auth.ListTeams()
			if listErr != nil {
				return listErr
			}
			if len(teams) != 1 {
				return err
			}
			a.TeamOwner = teams[0].Name
		}
	}
	canCreate := permission.Check(t, permission.PermAppCreate,
		permission.Context(permission.CtxTeam, a.TeamOwner),
	)
	if !canCreate {
		return permission.ErrUnauthorized
	}
	u, err := t.User()
	if err != nil {
		return err
	}
	platform, err := app.GetPlatform(a.Platform)
	if err != nil {
		return err
	}
	if platform.Disabled {
		canUsePlat := permission.Check(t, permission.PermPlatformUpdate) ||
			permission.Check(t, permission.PermPlatformCreate)
		if !canUsePlat {
			return &errors.HTTP{Code: http.StatusBadRequest, Message: app.InvalidPlatformError.Error()}
		}
	}
	evt, err := event.New(&event.Opts{
		Target:     appTarget(a.Name),
		Kind:       permission.PermAppCreate,
		Owner:      t,
		CustomData: event.FormToCustomData(r.Form),
		Allowed:    event.Allowed(permission.PermAppReadEvents, contextsForApp(&a)...),
	})
	if err != nil {
		return err
	}
	defer func() { evt.Done(err) }()
	err = app.CreateApp(&a, u)
	if err != nil {
		log.Errorf("Got error while creating app: %s", err)
		if e, ok := err.(*errors.ValidationError); ok {
			return &errors.HTTP{Code: http.StatusBadRequest, Message: e.Message}
		}
		if _, ok := err.(app.NoTeamsError); ok {
			return &errors.HTTP{
				Code:    http.StatusBadRequest,
				Message: "In order to create an app, you should be member of at least one team",
			}
		}
		if e, ok := err.(*app.AppCreationError); ok {
			if e.Err == app.ErrAppAlreadyExists {
				return &errors.HTTP{Code: http.StatusConflict, Message: e.Error()}
			}
			if _, ok := e.Err.(*quota.QuotaExceededError); ok {
				return &errors.HTTP{
					Code:    http.StatusForbidden,
					Message: "Quota exceeded",
				}
			}
		}
		if err == app.InvalidPlatformError {
			return &errors.HTTP{Code: http.StatusBadRequest, Message: err.Error()}
		}
		return err
	}
	repo, err := repository.Manager().GetRepository(a.Name)
	if err != nil {
		return err
	}
	msg := map[string]string{
		"status":         "success",
		"repository_url": repo.ReadWriteURL,
		"ip":             a.Ip,
	}
	jsonMsg, err := json.Marshal(msg)
	if err != nil {
		return err
	}
	w.WriteHeader(http.StatusCreated)
	w.Header().Set("Content-Type", "application/json")
	w.Write(jsonMsg)
	return nil
}
示例#25
0
文件: migrate.go 项目: tsuru/tsuru
func setAllowed(evt *event.Event) (err error) {
	defer func() {
		if err != nil {
			fmt.Printf("setting global context to evt %q: %s\n", evt.String(), err)
			err = nil
		}
	}()
	switch evt.Target.Type {
	case event.TargetTypeApp:
		var a *app.App
		a, err = app.GetByName(evt.Target.Value)
		if err != nil {
			evt.Allowed = event.Allowed(permission.PermAppReadEvents)
			if evt.Cancelable {
				evt.Allowed = event.Allowed(permission.PermAppUpdateEvents)
			}
			return err
		}
		ctxs := append(permission.Contexts(permission.CtxTeam, a.Teams),
			permission.Context(permission.CtxApp, a.Name),
			permission.Context(permission.CtxPool, a.Pool),
		)
		evt.Allowed = event.Allowed(permission.PermAppReadEvents, ctxs...)
		if evt.Cancelable {
			evt.Allowed = event.Allowed(permission.PermAppUpdateEvents, ctxs...)
		}
	case event.TargetTypeTeam:
		evt.Allowed = event.Allowed(permission.PermTeamReadEvents, permission.Context(permission.CtxTeam, evt.Target.Value))
	case event.TargetTypeService:
		s := service.Service{Name: evt.Target.Value}
		err = s.Get()
		if err != nil {
			evt.Allowed = event.Allowed(permission.PermServiceReadEvents)
			return err
		}
		evt.Allowed = event.Allowed(permission.PermServiceReadEvents,
			append(permission.Contexts(permission.CtxTeam, s.OwnerTeams),
				permission.Context(permission.CtxService, s.Name),
			)...,
		)
	case event.TargetTypeServiceInstance:
		v := strings.SplitN(evt.Target.Value, "/", 2)
		if len(v) != 2 {
			evt.Allowed = event.Allowed(permission.PermServiceInstanceReadEvents)
			return nil
		}
		var si *service.ServiceInstance
		si, err = service.GetServiceInstance(v[0], v[1])
		if err != nil {
			evt.Allowed = event.Allowed(permission.PermServiceInstanceReadEvents)
			return err
		}
		evt.Allowed = event.Allowed(permission.PermServiceReadEvents,
			append(permission.Contexts(permission.CtxTeam, si.Teams),
				permission.Context(permission.CtxServiceInstance, evt.Target.Value),
			)...,
		)
	case event.TargetTypePool:
		evt.Allowed = event.Allowed(permission.PermPoolReadEvents, permission.Context(permission.CtxPool, evt.Target.Value))
	case event.TargetTypeUser:
		evt.Allowed = event.Allowed(permission.PermUserReadEvents, permission.Context(permission.CtxUser, evt.Target.Value))
	case event.TargetTypeIaas:
		evt.Allowed = event.Allowed(permission.PermMachineReadEvents, permission.Context(permission.CtxIaaS, evt.Target.Value))
	case event.TargetTypeContainer:
		var provisioners []provision.Provisioner
		provisioners, err = provision.Registry()
		if err != nil {
			return err
		}
		var a provision.App
		for _, p := range provisioners {
			if finderProv, ok := p.(provision.UnitFinderProvisioner); ok {
				a, err = finderProv.GetAppFromUnitID(evt.Target.Value)
				_, isNotFound := err.(*provision.UnitNotFoundError)
				if err == nil || !isNotFound {
					break
				}
			}
		}
		if err != nil {
			return err
		}
		evt.Allowed = event.Allowed(permission.PermAppReadEvents,
			append(permission.Contexts(permission.CtxTeam, a.GetTeamsName()),
				permission.Context(permission.CtxApp, a.GetName()),
				permission.Context(permission.CtxPool, a.GetPool()),
			)...,
		)
	case event.TargetTypeNode:
		var provisioners []provision.Provisioner
		provisioners, err = provision.Registry()
		if err != nil {
			return err
		}
		var ctxs []permission.PermissionContext
		for _, p := range provisioners {
			if nodeProvisioner, ok := p.(provision.NodeProvisioner); ok {
				var nodes []provision.Node
				nodes, err = nodeProvisioner.ListNodes([]string{evt.Target.Value})
				if err != nil {
					return err
				}
				ctxs = append(ctxs, permission.Context(permission.CtxPool, nodes[0].Pool()))
			}
		}
		evt.Allowed = event.Allowed(permission.PermPoolReadEvents, ctxs...)
	case event.TargetTypeRole:
		evt.Allowed = event.Allowed(permission.PermRoleReadEvents)
	default:
		evt.Allowed = event.Allowed(permission.PermDebug)
	}
	return nil
}