func (s *DeploySuite) TestDeployList(c *check.C) { user, _ := s.token.User() app1 := app.App{Name: "g1", Platform: "python", Teams: []string{s.team.Name}} err := app.CreateApp(&app1, user) c.Assert(err, check.IsNil) defer app.Delete(&app1) app2 := app.App{Name: "ge", Platform: "python", Teams: []string{s.team.Name}} err = app.CreateApp(&app2, user) c.Assert(err, check.IsNil) defer app.Delete(&app2) var result []app.DeployData request, err := http.NewRequest("GET", "/deploys", nil) c.Assert(err, check.IsNil) recorder := httptest.NewRecorder() timestamp := time.Date(2013, time.November, 1, 0, 0, 0, 0, time.Local) duration := time.Since(timestamp) err = s.conn.Deploys().Insert(app.DeployData{App: "g1", Timestamp: timestamp.Add(time.Minute), Duration: duration}) c.Assert(err, check.IsNil) err = s.conn.Deploys().Insert(app.DeployData{App: "ge", Timestamp: timestamp.Add(time.Second), Duration: duration}) c.Assert(err, check.IsNil) defer s.conn.Deploys().RemoveAll(nil) request.Header.Set("Authorization", "bearer "+s.token.GetValue()) server := RunServer(true) server.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusOK) err = json.Unmarshal(recorder.Body.Bytes(), &result) c.Assert(err, check.IsNil) c.Assert(result[0].ID, check.NotNil) c.Assert(result[0].App, check.Equals, "g1") c.Assert(result[0].Timestamp.In(time.UTC), check.DeepEquals, timestamp.Add(time.Minute).In(time.UTC)) c.Assert(result[0].Duration, check.DeepEquals, duration) c.Assert(result[1].App, check.Equals, "ge") c.Assert(result[1].Timestamp.In(time.UTC), check.DeepEquals, timestamp.Add(time.Second).In(time.UTC)) c.Assert(result[1].Duration, check.DeepEquals, duration) }
func (s *DeploySuite) TestDeployList(c *check.C) { user, _ := s.token.User() app1 := app.App{Name: "g1", Platform: "python", TeamOwner: s.team.Name} err := app.CreateApp(&app1, user) c.Assert(err, check.IsNil) app2 := app.App{Name: "ge", Platform: "python", TeamOwner: s.team.Name} err = app.CreateApp(&app2, user) c.Assert(err, check.IsNil) var result []app.DeployData request, err := http.NewRequest("GET", "/deploys", nil) c.Assert(err, check.IsNil) recorder := httptest.NewRecorder() timestamp := time.Date(2013, time.November, 1, 0, 0, 0, 0, time.Local) deps := []app.DeployData{ {App: "g1", Timestamp: timestamp.Add(time.Minute)}, {App: "ge", Timestamp: timestamp.Add(time.Second)}, } insertDeploysAsEvents(deps, c) request.Header.Set("Authorization", "bearer "+s.token.GetValue()) server := 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") err = json.Unmarshal(recorder.Body.Bytes(), &result) c.Assert(err, check.IsNil) c.Assert(result, check.HasLen, 2) c.Assert(result[0].ID, check.NotNil) c.Assert(result[0].App, check.Equals, "g1") c.Assert(result[0].Timestamp.In(time.UTC), check.DeepEquals, timestamp.Add(time.Minute).In(time.UTC)) c.Assert(result[1].App, check.Equals, "ge") c.Assert(result[1].Timestamp.In(time.UTC), check.DeepEquals, timestamp.Add(time.Second).In(time.UTC)) }
func (s *DeploySuite) TestDeployRollbackHandlerWithInexistVersion(c *check.C) { user, _ := s.token.User() a := app.App{Name: "otherapp", Platform: "python", TeamOwner: s.team.Name} err := app.CreateApp(&a, user) c.Assert(err, check.IsNil) b := app.App{Name: "otherapp2", Platform: "python", TeamOwner: s.team.Name} err = app.CreateApp(&b, user) c.Assert(err, check.IsNil) v := url.Values{} v.Set("origin", "rollback") v.Set("image", "v3") u := fmt.Sprintf("/apps/%s/deploy/rollback", a.Name) request, err := http.NewRequest("POST", u, strings.NewReader(v.Encode())) c.Assert(err, check.IsNil) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") recorder := httptest.NewRecorder() request.Header.Set("Authorization", "bearer "+s.token.GetValue()) server := RunServer(true) server.ServeHTTP(recorder, request) c.Assert(recorder.Header().Get("Content-Type"), check.Equals, "application/x-json-stream") c.Assert(recorder.Code, check.Equals, http.StatusOK) var body map[string]string err = json.Unmarshal(recorder.Body.Bytes(), &body) c.Assert(err, check.IsNil) c.Assert(body, check.DeepEquals, map[string]string{"Message": "", "Error": `invalid version: "v3"`}) }
func (s *ConsumptionSuite) TestRemoveServiceHandlerWIthAssociatedAppsWithNoUnbindAllListAllApp(c *check.C) { var called int32 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "DELETE" && r.URL.Path == "/resources/my-mysql/bind" { atomic.StoreInt32(&called, 1) } })) defer ts.Close() srvc := service.Service{Name: "mysql", Endpoint: map[string]string{"production": ts.URL}} err := srvc.Create() c.Assert(err, check.IsNil) defer s.conn.Services().Remove(bson.M{"_id": "mysql"}) p := app.Platform{Name: "zend"} s.conn.Platforms().Insert(p) s.pool = "test1" opts := provision.AddPoolOptions{Name: "test1", Default: true} err = provision.AddPool(opts) c.Assert(err, check.IsNil) a := app.App{ Name: "app", Platform: "zend", TeamOwner: s.team.Name, } ab := app.App{ Name: "app2", Platform: "zend", TeamOwner: s.team.Name, } err = app.CreateApp(&a, s.user) c.Assert(err, check.IsNil) err = app.CreateApp(&ab, s.user) c.Assert(err, check.IsNil) units, _ := s.provisioner.AddUnits(&a, 1, "web", nil) units, _ = s.provisioner.AddUnits(&ab, 1, "web", nil) instance := service.ServiceInstance{ Name: "my-mysql", ServiceName: "mysql", Teams: []string{s.team.Name}, Apps: []string{"app", "app2"}, Units: []string{units[0].ID}, } err = instance.Create() c.Assert(err, check.IsNil) defer s.conn.ServiceInstances().Remove(bson.M{"name": "my-mysql"}) recorder, request := makeRequestToRemoveInstanceHandlerWithNoUnbind("mysql", "my-mysql", c) err = removeServiceInstance(recorder, request, s.token) c.Assert(err, check.IsNil) b, err := ioutil.ReadAll(recorder.Body) c.Assert(err, check.IsNil) var msg io.SimpleJsonMessage json.Unmarshal(b, &msg) c.Assert(msg.Error, check.Equals, service.ErrServiceInstanceBound.Error()) expectedMsg := "app,app2" c.Assert(msg.Message, check.Equals, expectedMsg) }
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) }
func (s *DeploySuite) TestDeployWithCommitUserToken(c *check.C) { user, _ := s.token.User() a := app.App{ Name: "otherapp", Platform: "python", TeamOwner: s.team.Name, Plan: app.Plan{Router: "fake"}, } err := app.CreateApp(&a, user) c.Assert(err, check.IsNil) defer app.Delete(&a, nil) url := fmt.Sprintf("/apps/%s/repository/clone?:appname=%s", a.Name, a.Name) request, err := http.NewRequest("POST", url, strings.NewReader("archive-url=http://something.tar.gz&user=fulano&commit=123")) c.Assert(err, check.IsNil) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") recorder := httptest.NewRecorder() request.Header.Set("Authorization", "bearer "+s.token.GetValue()) server := RunServer(true) server.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusOK) c.Assert(recorder.Header().Get("Content-Type"), check.Equals, "text") c.Assert(recorder.Code, check.Equals, http.StatusOK) c.Assert(recorder.Body.String(), check.Equals, "Archive deploy called\nOK\n") deploys, err := s.conn.Deploys().Find(bson.M{"commit": "123"}).Count() c.Assert(err, check.IsNil) c.Assert(deploys, check.Equals, 0) }
func (s *S) TestAssignRoleCheckGandalf(c *check.C) { role, err := permission.NewRole("test", "app", "") c.Assert(err, check.IsNil) err = role.AddPermissions("app.deploy") c.Assert(err, check.IsNil) emptyToken := customUserWithPermission(c, "user2") a := app.App{Name: "myapp", TeamOwner: s.team.Name} err = app.CreateApp(&a, s.user) c.Assert(err, check.IsNil) roleBody := bytes.NewBufferString(fmt.Sprintf("email=%s&context=myapp", emptyToken.GetUserName())) req, err := http.NewRequest("POST", "/roles/test/user", roleBody) c.Assert(err, check.IsNil) token := customUserWithPermission(c, "user1", permission.Permission{ Scheme: permission.PermRoleUpdateAssign, Context: permission.Context(permission.CtxGlobal, ""), }, permission.Permission{ Scheme: permission.PermAppDeploy, Context: permission.Context(permission.CtxApp, "myapp"), }) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Authorization", "bearer "+token.GetValue()) recorder := httptest.NewRecorder() server := RunServer(true) server.ServeHTTP(recorder, req) c.Assert(err, check.IsNil) c.Assert(recorder.Code, check.Equals, http.StatusOK) emptyUser, err := emptyToken.User() c.Assert(err, check.IsNil) users, err := repositorytest.Granted("myapp") c.Assert(err, check.IsNil) c.Assert(users, check.DeepEquals, []string{s.user.Email, emptyToken.GetUserName()}) c.Assert(emptyUser.Roles, check.HasLen, 1) }
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") }
func (s *DeploySuite) TestDeployInfoByUserWithoutAccess(c *check.C) { user := &auth.User{Email: "*****@*****.**", Password: "******"} app.AuthScheme = nativeScheme _, err := nativeScheme.Create(user) c.Assert(err, check.IsNil) team := &auth.Team{Name: "team"} err = s.conn.Teams().Insert(team) c.Assert(err, check.IsNil) a := app.App{Name: "g1", Platform: "python", TeamOwner: team.Name} err = app.CreateApp(&a, user) c.Assert(err, check.IsNil) token, err := nativeScheme.Login(map[string]string{"email": user.Email, "password": "******"}) c.Assert(err, check.IsNil) recorder := httptest.NewRecorder() timestamp := time.Now() depData := []app.DeployData{ {App: "g1", Timestamp: timestamp.Add(-3600 * time.Second), Commit: "e293e3e3me03ejm3puejmp3ej3iejop32", Error: "", Origin: "git"}, {App: "g1", Timestamp: timestamp, Commit: "e82nn93nd93mm12o2ueh83dhbd3iu112", Error: "", Origin: "git", Diff: "fake-diff"}, } evts := insertDeploysAsEvents(depData, c) url := fmt.Sprintf("/deploys/%s", evts[1].UniqueID.Hex()) request, err := http.NewRequest("GET", url, nil) c.Assert(err, check.IsNil) request.Header.Set("Authorization", "bearer "+token.GetValue()) server := RunServer(true) server.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusNotFound) body := recorder.Body.String() c.Assert(body, check.Equals, "Deploy not found.\n") }
func (s *DeploySuite) TestDeployInfoDiff(c *check.C) { user, _ := s.token.User() a := app.App{Name: "g1", Platform: "python", TeamOwner: s.team.Name} err := app.CreateApp(&a, user) c.Assert(err, check.IsNil) recorder := httptest.NewRecorder() timestamp := time.Now() depData := []app.DeployData{ {App: "g1", Timestamp: timestamp.Add(-3600 * time.Second), Commit: "e293e3e3me03ejm3puejmp3ej3iejop32", Error: "", Origin: "git"}, {App: "g1", Timestamp: timestamp, Commit: "e82nn93nd93mm12o2ueh83dhbd3iu112", Error: "", Origin: "git", Diff: "fake-diff"}, } lastDeploy := depData[1] evts := insertDeploysAsEvents(depData, c) url := fmt.Sprintf("/deploys/%s", evts[1].UniqueID.Hex()) request, err := http.NewRequest("GET", url, nil) c.Assert(err, check.IsNil) request.Header.Set("Authorization", "bearer "+s.token.GetValue()) server := 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") lastDeploy.ID = evts[1].UniqueID var result app.DeployData err = json.Unmarshal(recorder.Body.Bytes(), &result) c.Assert(err, check.IsNil) result.Timestamp = lastDeploy.Timestamp result.RemoveDate = lastDeploy.RemoveDate result.Duration = 0 result.Log = "" c.Assert(result, check.DeepEquals, lastDeploy) }
func (s *DeploySuite) TestDeployListByAppWithImage(c *check.C) { user, _ := s.token.User() a := app.App{Name: "myblog", Platform: "python", TeamOwner: s.team.Name} err := app.CreateApp(&a, user) c.Assert(err, check.IsNil) timestamp := time.Date(2013, time.November, 1, 0, 0, 0, 0, time.Local) deploys := []app.DeployData{ {App: "myblog", Timestamp: timestamp, Image: "registry.tsuru.globoi.com/tsuru/app-example:v2", CanRollback: true}, {App: "yourblog", Timestamp: timestamp, Image: "127.0.0.1:5000/tsuru/app-tsuru-dashboard:v1", CanRollback: true}, } insertDeploysAsEvents(deploys, c) recorder := httptest.NewRecorder() request, err := http.NewRequest("GET", "/deploys?app=myblog", nil) c.Assert(err, check.IsNil) request.Header.Set("Authorization", "bearer "+s.token.GetValue()) server := 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 result []app.DeployData err = json.Unmarshal(recorder.Body.Bytes(), &result) c.Assert(err, check.IsNil) c.Assert(result, check.HasLen, 1) c.Assert(result[0].Image, check.Equals, "v2") c.Assert(result[0].App, check.Equals, "myblog") c.Assert(result[0].Timestamp.In(time.UTC), check.DeepEquals, timestamp.In(time.UTC)) }
func (s *S) BenchmarkScanLogs(c *check.C) { c.StopTimer() var apps []app.App for i := 0; i < 200; i++ { a := app.App{Name: fmt.Sprintf("myapp-%d", i), Platform: "zend", TeamOwner: s.team.Name} apps = append(apps, a) err := app.CreateApp(&a, s.user) c.Assert(err, check.IsNil) defer app.Delete(&a, nil) } baseMsg := `{"date": "2015-06-16T15:00:00.000Z", "message": "msg-%d", "source": "web", "appname": "%s", "unit": "unit1"}` + "\n" for i := range apps { // Remove overhead for first message from app from benchmark. err := scanLogs(strings.NewReader(fmt.Sprintf(baseMsg, 0, apps[i].Name))) c.Assert(err, check.IsNil) } r, w := io.Pipe() go func() { for i := 0; i < c.N; i++ { msg := fmt.Sprintf(baseMsg, i, apps[i%len(apps)].Name) _, err := w.Write([]byte(msg)) c.Assert(err, check.IsNil) } w.Close() }() c.StartTimer() err := scanLogs(r) c.Assert(err, check.IsNil) c.StopTimer() }
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) }
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) }
func (s *DeploySuite) TestDeployWithTokenForInternalAppName(c *check.C) { token, err := nativeScheme.AppLogin(app.InternalAppName) c.Assert(err, check.IsNil) a := app.App{ Name: "otherapp", Platform: "python", TeamOwner: s.team.Name, Plan: app.Plan{Router: "fake"}, } user, _ := s.token.User() err = app.CreateApp(&a, user) c.Assert(err, check.IsNil) defer app.Delete(&a, nil) url := fmt.Sprintf("/apps/%s/repository/clone?:appname=%s", a.Name, a.Name) request, err := http.NewRequest("POST", url, strings.NewReader("archive-url=http://something.tar.gz&user=fulano")) c.Assert(err, check.IsNil) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") recorder := httptest.NewRecorder() request.Header.Set("Authorization", "bearer "+token.GetValue()) server := RunServer(true) server.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusOK) c.Assert(recorder.Header().Get("Content-Type"), check.Equals, "text") c.Assert(recorder.Code, check.Equals, http.StatusOK) c.Assert(recorder.Body.String(), check.Equals, "Archive deploy called\nOK\n") }
func (s *DeploySuite) TestDeployRollbackHandlerWithOnlyVersionImage(c *check.C) { user, _ := s.token.User() a := app.App{Name: "otherapp", Platform: "python", Teams: []string{s.team.Name}} err := app.CreateApp(&a, user) c.Assert(err, check.IsNil) defer app.Delete(&a, nil) defer s.logConn.Logs(a.Name).DropCollection() timestamp := time.Date(2013, time.November, 1, 0, 0, 0, 0, time.Local) duration := time.Since(timestamp) deploys := []app.DeployData{ {App: "otherapp", Timestamp: timestamp, Duration: duration, Image: "registry.tsuru.globoi.com/tsuru/app-example:v2", CanRollback: true}, {App: "otherapp", Timestamp: timestamp, Duration: duration, Image: "127.0.0.1:5000/tsuru/app-tsuru-dashboard:v1", CanRollback: true}, } for _, deploy := range deploys { err = s.conn.Deploys().Insert(deploy) c.Assert(err, check.IsNil) } defer s.conn.Deploys().RemoveAll(nil) url := fmt.Sprintf("/apps/%s/deploy/rollback", a.Name) request, err := http.NewRequest("POST", url, strings.NewReader("image=v1")) c.Assert(err, check.IsNil) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") recorder := httptest.NewRecorder() request.Header.Set("Authorization", "bearer "+s.token.GetValue()) server := 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.Code, check.Equals, http.StatusOK) c.Assert(recorder.Body.String(), check.Equals, "{\"Message\":\"Image deploy called\"}\n") }
func (s *S) TestAppShellUnauthorizedError(c *check.C) { a := app.App{ Name: "someapp", Platform: "zend", TeamOwner: s.team.Name, } err := app.CreateApp(&a, s.user) c.Assert(err, check.IsNil) err = s.provisioner.AddUnits(&a, 1, "web", nil) c.Assert(err, check.IsNil) m := RunServer(true) server := httptest.NewServer(m) defer server.Close() testServerURL, err := url.Parse(server.URL) c.Assert(err, check.IsNil) url := fmt.Sprintf("ws://%s/apps/%s/shell?width=140&height=38&term=xterm", testServerURL.Host, a.Name) config, err := websocket.NewConfig(url, "ws://localhost/") c.Assert(err, check.IsNil) wsConn, err := websocket.DialConfig(config) c.Assert(err, check.IsNil) defer wsConn.Close() _, err = wsConn.Write([]byte("echo test")) c.Assert(err, check.IsNil) var result string err = tsurutest.WaitCondition(5*time.Second, func() bool { part, readErr := ioutil.ReadAll(wsConn) if readErr != nil { return false } result += string(part) return result == "Error: no token provided or session expired, please login again\n" }) c.Assert(err, check.IsNil) }
func (s *DeploySuite) TestDeployListByAppWithImage(c *check.C) { user, _ := s.token.User() a := app.App{Name: "myblog", Platform: "python", Teams: []string{s.team.Name}} err := app.CreateApp(&a, user) c.Assert(err, check.IsNil) defer app.Delete(&a, nil) defer s.logConn.Logs(a.Name).DropCollection() timestamp := time.Date(2013, time.November, 1, 0, 0, 0, 0, time.Local) duration := time.Since(timestamp) deploys := []app.DeployData{ {App: "myblog", Timestamp: timestamp, Duration: duration, Image: "registry.tsuru.globoi.com/tsuru/app-example:v2", CanRollback: true}, {App: "yourblog", Timestamp: timestamp, Duration: duration, Image: "127.0.0.1:5000/tsuru/app-tsuru-dashboard:v1", CanRollback: true}, } for _, deploy := range deploys { err = s.conn.Deploys().Insert(deploy) c.Assert(err, check.IsNil) } defer s.conn.Deploys().RemoveAll(nil) recorder := httptest.NewRecorder() request, err := http.NewRequest("GET", "/deploys?app=myblog", nil) request.Header.Set("Authorization", "bearer "+s.token.GetValue()) server := RunServer(true) server.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusOK) var result []app.DeployData err = json.Unmarshal(recorder.Body.Bytes(), &result) c.Assert(err, check.IsNil) c.Assert(result, check.HasLen, 1) c.Assert(result[0].Image, check.Equals, "v2") c.Assert(result[0].App, check.Equals, "myblog") c.Assert(result[0].Timestamp.In(time.UTC), check.DeepEquals, timestamp.In(time.UTC)) c.Assert(result[0].Duration, check.DeepEquals, duration) }
func (s *DeploySuite) TestDeployInfoByAdminUser(c *check.C) { a := app.App{Name: "g1", Platform: "python", Teams: []string{s.team.Name}} user, _ := s.token.User() err := app.CreateApp(&a, user) c.Assert(err, check.IsNil) defer app.Delete(&a, nil) recorder := httptest.NewRecorder() timestamp := time.Now() duration := time.Duration(10e9) previousDeploy := app.DeployData{App: "g1", Timestamp: timestamp.Add(-3600 * time.Second), Duration: duration, Commit: "e293e3e3me03ejm3puejmp3ej3iejop32", Error: ""} err = s.conn.Deploys().Insert(previousDeploy) c.Assert(err, check.IsNil) lastDeploy := app.DeployData{App: "g1", Timestamp: timestamp, Duration: duration, Commit: "e82nn93nd93mm12o2ueh83dhbd3iu112", Error: ""} err = s.conn.Deploys().Insert(lastDeploy) c.Assert(err, check.IsNil) defer s.conn.Deploys().RemoveAll(nil) var d map[string]interface{} err = s.conn.Deploys().Find(bson.M{"commit": lastDeploy.Commit}).One(&d) c.Assert(err, check.IsNil) lastDeployId := d["_id"].(bson.ObjectId).Hex() url := fmt.Sprintf("/deploys/%s", lastDeployId) request, err := http.NewRequest("GET", url, nil) c.Assert(err, check.IsNil) request.Header.Set("Authorization", "bearer "+s.token.GetValue()) server := RunServer(true) server.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusOK) var result app.DeployData err = json.Unmarshal(recorder.Body.Bytes(), &result) c.Assert(err, check.IsNil) lastDeploy.ID = d["_id"].(bson.ObjectId) result.Timestamp = lastDeploy.Timestamp result.RemoveDate = lastDeploy.RemoveDate c.Assert(result, check.DeepEquals, lastDeploy) }
func (s *S) benchmarkAddPermissionToRole(c *check.C, body string) []string { c.StopTimer() a := app.App{Name: "myapp", TeamOwner: s.team.Name} err := app.CreateApp(&a, s.user) c.Assert(err, check.IsNil) role, err := permission.NewRole("test", "team") c.Assert(err, check.IsNil) err = role.AddPermissions("app.create") c.Assert(err, check.IsNil) nUsers := 100 var userEmails []string for i := 0; i < nUsers; i++ { email := fmt.Sprintf("*****@*****.**", i) userEmails = append(userEmails, email) user := &auth.User{Email: email, Password: "******"} _, err = nativeScheme.Create(user) c.Assert(err, check.IsNil) err = user.AddRole("test", s.team.Name) c.Assert(err, check.IsNil) } recorder := httptest.NewRecorder() m := RunServer(true) c.StartTimer() for i := 0; i < c.N; i++ { b := bytes.NewBufferString(body) request, err := http.NewRequest("POST", "/roles/test/permissions", b) c.Assert(err, check.IsNil) request.Header.Add("Authorization", "bearer "+s.token.GetValue()) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") m.ServeHTTP(recorder, request) } c.StopTimer() c.Assert(recorder.Code, check.Equals, http.StatusOK) return userEmails }
func (s *DeploySuite) TestDeployUploadFile(c *check.C) { user, _ := s.token.User() a := app.App{Name: "otherapp", Platform: "python", Teams: []string{s.team.Name}} err := app.CreateApp(&a, user) c.Assert(err, check.IsNil) defer app.Delete(&a, nil) url := fmt.Sprintf("/apps/%s/repository/clone?:appname=%s", a.Name, a.Name) var body bytes.Buffer writer := multipart.NewWriter(&body) file, err := writer.CreateFormFile("file", "archive.tar.gz") c.Assert(err, check.IsNil) file.Write([]byte("hello world!")) writer.Close() request, err := http.NewRequest("POST", url, &body) c.Assert(err, check.IsNil) request.Header.Set("Content-Type", "multipart/form-data; boundary="+writer.Boundary()) recorder := httptest.NewRecorder() request.Header.Set("Authorization", "bearer "+s.token.GetValue()) server := RunServer(true) server.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusOK) c.Assert(recorder.Header().Get("Content-Type"), check.Equals, "text") c.Assert(recorder.Code, check.Equals, http.StatusOK) c.Assert(recorder.Body.String(), check.Equals, "Upload deploy called\nOK\n") }
func (s *S) TestAddPermissionsToARoleSyncGitRepository(c *check.C) { _, err := permission.NewRole("test", "team") c.Assert(err, check.IsNil) user := &auth.User{Email: "*****@*****.**", Password: "******"} _, err = nativeScheme.Create(user) c.Assert(err, check.IsNil) err = user.AddRole("test", s.team.Name) c.Assert(err, check.IsNil) a := app.App{Name: "myapp", TeamOwner: s.team.Name} err = app.CreateApp(&a, s.user) c.Assert(err, check.IsNil) users, err := repositorytest.Granted("myapp") c.Assert(err, check.IsNil) c.Assert(users, check.DeepEquals, []string{s.user.Email}) rec := httptest.NewRecorder() b := bytes.NewBufferString(`permission=app.update&permission=app.deploy`) req, err := http.NewRequest("POST", "/roles/test/permissions", b) c.Assert(err, check.IsNil) token := userWithPermission(c, permission.Permission{ Scheme: permission.PermRoleUpdate, Context: permission.Context(permission.CtxGlobal, ""), }) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Authorization", "bearer "+token.GetValue()) server := RunServer(true) server.ServeHTTP(rec, req) c.Assert(rec.Code, check.Equals, http.StatusOK) users, err = repositorytest.Granted("myapp") c.Assert(err, check.IsNil) c.Assert(users, check.DeepEquals, []string{s.user.Email, user.Email}) }
func (s *S) TestRemovePermissionsFromRoleSyncGitRepository(c *check.C) { r, err := permission.NewRole("test", "team") c.Assert(err, check.IsNil) defer permission.DestroyRole(r.Name) err = r.AddPermissions("app.deploy") c.Assert(err, check.IsNil) user := &auth.User{Email: "*****@*****.**", Password: "******"} _, err = nativeScheme.Create(user) c.Assert(err, check.IsNil) err = user.AddRole("test", s.team.Name) c.Assert(err, check.IsNil) a := app.App{Name: "myapp", TeamOwner: s.team.Name} err = app.CreateApp(&a, s.user) err = repository.Manager().GrantAccess(a.Name, user.Email) c.Assert(err, check.IsNil) rec := httptest.NewRecorder() req, err := http.NewRequest("DELETE", "/roles/test/permissions/app.deploy", nil) c.Assert(err, check.IsNil) token := userWithPermission(c, permission.Permission{ Scheme: permission.PermRoleUpdate, Context: permission.Context(permission.CtxGlobal, ""), }) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Authorization", "bearer "+token.GetValue()) server := RunServer(true) server.ServeHTTP(rec, req) c.Assert(rec.Code, check.Equals, http.StatusOK) r, err = permission.FindRole("test") c.Assert(err, check.IsNil) c.Assert(r.SchemeNames, check.DeepEquals, []string{}) users, err := repositorytest.Granted(a.Name) c.Assert(err, check.IsNil) c.Assert(users, check.DeepEquals, []string{s.user.Email}) }
func (s *S) TestChangePlan(c *check.C) { config.Set("docker:router", "fake") defer config.Unset("docker:router") plans := []app.Plan{ {Name: "hiperplan", Memory: 536870912, Swap: 536870912, CpuShare: 100}, {Name: "superplan", Memory: 268435456, Swap: 268435456, CpuShare: 100}, } for _, plan := range plans { err := plan.Save() c.Assert(err, check.IsNil) defer app.PlanRemove(plan.Name) } a := app.App{Name: "someapp", Platform: "zend", TeamOwner: s.team.Name, Plan: plans[1]} err := app.CreateApp(&a, s.user) c.Assert(err, check.IsNil) defer s.logConn.Logs(a.Name).DropCollection() request, err := http.NewRequest("POST", "/apps/someapp/plan", strings.NewReader(`{"name":"hiperplan"}`)) c.Assert(err, check.IsNil) request.Header.Set("Authorization", "bearer "+s.token.GetValue()) recorder := httptest.NewRecorder() m := RunServer(true) m.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusOK) app, err := app.GetByName(a.Name) c.Assert(err, check.IsNil) c.Assert(app.Plan, check.DeepEquals, plans[0]) c.Assert(s.provisioner.Restarts(&a, ""), check.Equals, 1) }
func (s *S) TestSwarmNodeUnits(c *check.C) { srv, err := testing.NewServer("127.0.0.1:0", nil, nil) c.Assert(err, check.IsNil) defer srv.Stop() opts := provision.AddNodeOptions{Address: srv.URL()} err = s.p.AddNode(opts) c.Assert(err, check.IsNil) nodes, err := s.p.ListNodes(nil) c.Assert(err, check.IsNil) c.Assert(nodes, check.HasLen, 1) units, err := nodes[0].Units() c.Assert(err, check.IsNil) c.Assert(units, check.HasLen, 0) a := &app.App{Name: "myapp", TeamOwner: s.team.Name, Deploys: 1} err = app.CreateApp(a, s.user) c.Assert(err, check.IsNil) imgName := "myapp:v1" err = image.SaveImageCustomData(imgName, map[string]interface{}{ "processes": map[string]interface{}{ "web": "python myapp.py", }, }) c.Assert(err, check.IsNil) err = image.AppendAppImageName(a.GetName(), imgName) c.Assert(err, check.IsNil) err = s.p.AddUnits(a, 1, "web", nil) c.Assert(err, check.IsNil) units, err = nodes[0].Units() c.Assert(err, check.IsNil) c.Assert(units, check.HasLen, 1) }
func (s *S) TestUnits(c *check.C) { a := &app.App{Name: "myapp", TeamOwner: s.team.Name} err := app.CreateApp(a, s.user) c.Assert(err, check.IsNil) units, err := s.p.Units(a) c.Assert(err, check.IsNil) c.Assert(units, check.IsNil) }
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 } u, err := t.User() if err != nil { return err } 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 }
func (s *S) TestActionUpdateServicesForwardUpdateExisting(c *check.C) { srv, err := testing.NewServer("127.0.0.1:0", nil, nil) c.Assert(err, check.IsNil) metadata := map[string]string{"m1": "v1", labelNodePoolName.String(): "p1"} opts := provision.AddNodeOptions{ Address: srv.URL(), Metadata: metadata, } err = s.p.AddNode(opts) c.Assert(err, check.IsNil) cli, err := chooseDBSwarmNode() c.Assert(err, check.IsNil) _, err = cli.CreateService(docker.CreateServiceOptions{ ServiceSpec: swarm.ServiceSpec{ TaskTemplate: swarm.TaskSpec{ ContainerSpec: swarm.ContainerSpec{ Command: []string{"oldcmd"}, }, }, Annotations: swarm.Annotations{ Name: "myapp-web", }, }, }) c.Assert(err, check.IsNil) a := &app.App{Name: "myapp", Platform: "whitespace", TeamOwner: s.team.Name} err = app.CreateApp(a, s.user) c.Assert(err, check.IsNil) imgName := "app:v1" err = image.SaveImageCustomData(imgName, map[string]interface{}{ "processes": map[string]interface{}{ "web": "python myapp.py", }, }) c.Assert(err, check.IsNil) args := &pipelineArgs{ client: cli, app: a, newImage: imgName, newImageSpec: processSpec{"web": processState{}}, currentImageSpec: processSpec{}, } processes, err := updateServices.Forward(action.FWContext{Params: []interface{}{args}}) c.Assert(err, check.IsNil) c.Assert(processes, check.DeepEquals, []string{"web"}) service, err := cli.InspectService("myapp-web") c.Assert(err, check.IsNil) c.Assert(service.Spec.TaskTemplate.ContainerSpec.Command, check.DeepEquals, []string{ "/bin/sh", "-lc", fmt.Sprintf( "[ -d /home/application/current ] && cd /home/application/current; %s && exec python myapp.py", extraRegisterCmds(a), ), }) }
func (s *DeploySuite) TestDeployShouldReturnForbiddenWhenTokenIsntFromTheApp(c *check.C) { user, _ := s.token.User() app1 := app.App{Name: "otherapp", Platform: "python", TeamOwner: s.team.Name} err := app.CreateApp(&app1, user) c.Assert(err, check.IsNil) app2 := app.App{Name: "superapp", Platform: "python", TeamOwner: s.team.Name} err = app.CreateApp(&app2, user) c.Assert(err, check.IsNil) token, err := nativeScheme.AppLogin(app2.Name) c.Assert(err, check.IsNil) url := fmt.Sprintf("/apps/%s/repository/clone?:appname=%s", app1.Name, app2.Name) request, err := http.NewRequest("POST", url, strings.NewReader("archive-url=http://something.tar.gz&user=fulano")) c.Assert(err, check.IsNil) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") recorder := httptest.NewRecorder() request.Header.Set("Authorization", "bearer "+token.GetValue()) server := RunServer(true) server.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusUnauthorized) c.Assert(recorder.Body.String(), check.Equals, "invalid app token\n") }
func (s *S) TestListUnitsByAppNoContent(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) req, err := http.NewRequest("GET", "/node/apps/myapp/containers", nil) c.Assert(err, check.IsNil) req.Header.Set("Authorization", s.token.GetValue()) rec := httptest.NewRecorder() m := RunServer(true) m.ServeHTTP(rec, req) c.Assert(rec.Code, check.Equals, http.StatusNoContent) }