func (s *ConsumptionSuite) TestServiceInstanceProxyError(c *check.C) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadGateway) w.Write([]byte("some error")) })) defer ts.Close() se := service.Service{Name: "foo", Endpoint: map[string]string{"production": ts.URL}} err := se.Create() c.Assert(err, check.IsNil) defer s.conn.Services().Remove(bson.M{"_id": se.Name}) si := service.ServiceInstance{Name: "foo-instance", ServiceName: "foo", Teams: []string{s.team.Name}} err = si.Create() c.Assert(err, check.IsNil) defer service.DeleteInstance(&si) url := fmt.Sprintf("/services/%s/proxy/%s?callback=/mypath", si.ServiceName, si.Name) request, err := http.NewRequest("GET", url, nil) c.Assert(err, check.IsNil) reqAuth := "bearer " + s.token.GetValue() request.Header.Set("Authorization", reqAuth) m := RunServer(true) recorder := httptest.NewRecorder() m.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusBadGateway) c.Assert(recorder.Body.Bytes(), check.DeepEquals, []byte("some error")) }
func (s *ConsumptionSuite) TestGrantRevokeServiceToTeam(c *check.C) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("{'AA': 2}")) })) defer ts.Close() se := service.Service{Name: "go", Endpoint: map[string]string{"production": ts.URL}} err := se.Create() c.Assert(err, check.IsNil) defer s.conn.Services().Remove(bson.M{"_id": se.Name}) si := service.ServiceInstance{Name: "si-test", ServiceName: "go", Teams: []string{s.team.Name}} err = si.Create() c.Assert(err, check.IsNil) defer service.DeleteInstance(&si) team := auth.Team{Name: "test"} s.conn.Teams().Insert(team) defer s.conn.Teams().Remove(bson.M{"name": team.Name}) url := fmt.Sprintf("/services/%s/instances/permission/%s/%s?:instance=%s&:team=%s&:service=%s", si.ServiceName, si.Name, team.Name, si.Name, team.Name, si.ServiceName) request, err := http.NewRequest("PUT", url, nil) c.Assert(err, check.IsNil) recorder := httptest.NewRecorder() err = serviceInstanceGrantTeam(recorder, request, s.token) c.Assert(err, check.IsNil) sinst, err := service.GetServiceInstance(si.ServiceName, si.Name) c.Assert(err, check.IsNil) c.Assert(sinst.Teams, check.DeepEquals, []string{s.team.Name, team.Name}) request, err = http.NewRequest("DELETE", url, nil) c.Assert(err, check.IsNil) err = serviceInstanceRevokeTeam(recorder, request, s.token) c.Assert(err, check.IsNil) sinst, err = service.GetServiceInstance(si.ServiceName, si.Name) c.Assert(err, check.IsNil) c.Assert(sinst.Teams, check.DeepEquals, []string{s.team.Name}) }
func (s *ConsumptionSuite) TestServiceInstanceStatusHandler(c *check.C) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) w.Write([]byte(`Service instance "my_nosql" is up`)) })) defer ts.Close() srv := service.Service{Name: "mongodb", OwnerTeams: []string{s.team.Name}, Endpoint: map[string]string{"production": ts.URL}} err := srv.Create() c.Assert(err, check.IsNil) defer srv.Delete() si := service.ServiceInstance{Name: "my_nosql", ServiceName: srv.Name, Teams: []string{s.team.Name}} err = si.Create() c.Assert(err, check.IsNil) defer service.DeleteInstance(&si) recorder, request := makeRequestToStatusHandler("mongodb", "my_nosql", c) err = serviceInstanceStatus(recorder, request, s.token) c.Assert(err, check.IsNil) b, err := ioutil.ReadAll(recorder.Body) c.Assert(string(b), check.Equals, "Service instance \"my_nosql\" is up") action := rectest.Action{ Action: "service-instance-status", User: s.user.Email, Extra: []interface{}{srv.Name, "my_nosql"}, } c.Assert(action, rectest.IsRecorded) }
func (s *ConsumptionSuite) TestServiceInstanceProxy(c *check.C) { var proxyedRequest *http.Request ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { proxyedRequest = r w.Header().Set("X-Response-Custom", "custom response header") w.WriteHeader(http.StatusCreated) w.Write([]byte("a message")) })) defer ts.Close() se := service.Service{Name: "foo", Endpoint: map[string]string{"production": ts.URL}} err := se.Create() c.Assert(err, check.IsNil) defer s.conn.Services().Remove(bson.M{"_id": se.Name}) si := service.ServiceInstance{Name: "foo-instance", ServiceName: "foo", Teams: []string{s.team.Name}} err = si.Create() c.Assert(err, check.IsNil) defer service.DeleteInstance(&si) url := fmt.Sprintf("/services/%s/proxy/%s?callback=/mypath", si.ServiceName, si.Name) request, err := http.NewRequest("GET", url, nil) reqAuth := "bearer " + s.token.GetValue() request.Header.Set("Authorization", reqAuth) request.Header.Set("X-Custom", "my request header") m := RunServer(true) recorder := httptest.NewRecorder() m.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusCreated) c.Assert(recorder.Header().Get("X-Response-Custom"), check.Equals, "custom response header") c.Assert(recorder.Body.String(), check.Equals, "a message") c.Assert(proxyedRequest, check.NotNil) c.Assert(proxyedRequest.Header.Get("X-Custom"), check.Equals, "my request header") c.Assert(proxyedRequest.Header.Get("Authorization"), check.Not(check.Equals), reqAuth) c.Assert(proxyedRequest.URL.String(), check.Equals, "/mypath") }
func removeServiceInstance(w http.ResponseWriter, r *http.Request, t auth.Token) error { unbindAll := r.URL.Query().Get("unbindall") serviceName := r.URL.Query().Get(":service") instanceName := r.URL.Query().Get(":instance") permissionValue := serviceName + "/" + instanceName keepAliveWriter := io.NewKeepAliveWriter(w, 30*time.Second, "") defer keepAliveWriter.Stop() writer := &io.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)} serviceInstance, err := getServiceInstanceOrError(serviceName, instanceName) if err != nil { writer.Encode(io.SimpleJsonMessage{Error: err.Error()}) return nil } allowed := permission.Check(t, permission.PermServiceInstanceDelete, append(permission.Contexts(permission.CtxTeam, serviceInstance.Teams), permission.Context(permission.CtxServiceInstance, permissionValue), )..., ) if !allowed { writer.Encode(io.SimpleJsonMessage{Error: permission.ErrUnauthorized.Error()}) return nil } rec.Log(t.GetUserName(), "remove-service-instance", serviceName, instanceName) if unbindAll == "true" { if len(serviceInstance.Apps) > 0 { for _, appName := range serviceInstance.Apps { _, app, instErr := getServiceInstance(serviceInstance.ServiceName, serviceInstance.Name, appName) if instErr != nil { writer.Encode(io.SimpleJsonMessage{Error: instErr.Error()}) return nil } fmt.Fprintf(writer, "Unbind app %q ...\n", app.GetName()) instErr = serviceInstance.UnbindApp(app, true, writer) if instErr != nil { writer.Encode(io.SimpleJsonMessage{Error: instErr.Error()}) return nil } fmt.Fprintf(writer, "\nInstance %q is not bound to the app %q anymore.\n", serviceInstance.Name, app.GetName()) } serviceInstance, err = getServiceInstanceOrError(serviceName, instanceName) if err != nil { writer.Encode(io.SimpleJsonMessage{Error: err.Error()}) return nil } } } err = service.DeleteInstance(serviceInstance) if err != nil { var msg string if err == service.ErrServiceInstanceBound { msg = strings.Join(serviceInstance.Apps, ",") } writer.Encode(io.SimpleJsonMessage{Message: msg, Error: err.Error()}) return nil } writer.Write([]byte("service instance successfuly removed")) return nil }
func (s *ProvisionSuite) TestServiceProxyPost(c *check.C) { var ( proxyedRequest *http.Request proxyedBody []byte ) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var err error proxyedBody, err = ioutil.ReadAll(r.Body) c.Assert(err, check.IsNil) proxyedRequest = r w.Header().Set("X-Response-Custom", "custom response header") w.WriteHeader(http.StatusCreated) w.Write([]byte("a message")) })) defer ts.Close() se := service.Service{ Name: "foo", Endpoint: map[string]string{"production": ts.URL}, OwnerTeams: []string{s.team.Name}, } err := se.Create() c.Assert(err, check.IsNil) defer s.conn.Services().Remove(bson.M{"_id": se.Name}) si := service.ServiceInstance{Name: "foo-instance", ServiceName: "foo", Teams: []string{s.team.Name}} err = si.Create() c.Assert(err, check.IsNil) defer service.DeleteInstance(&si, "") url := fmt.Sprintf("/services/proxy/service/%s?callback=/mypath", se.Name) body := strings.NewReader("my=awesome&body=1") request, err := http.NewRequest("POST", url, body) c.Assert(err, check.IsNil) reqAuth := "bearer " + s.token.GetValue() request.Header.Set("Authorization", reqAuth) request.Header.Set("X-Custom", "my request header") request.Header.Set("Content-Type", "application/x-www-form-urlencoded") recorder := &closeNotifierResponseRecorder{httptest.NewRecorder()} s.m.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusCreated) c.Assert(recorder.Header().Get("X-Response-Custom"), check.Equals, "custom response header") c.Assert(recorder.Body.String(), check.Equals, "a message") c.Assert(proxyedRequest, check.NotNil) c.Assert(proxyedRequest.Method, check.Equals, "POST") c.Assert(proxyedRequest.Header.Get("X-Custom"), check.Equals, "my request header") c.Assert(proxyedRequest.Header.Get("Authorization"), check.Not(check.Equals), reqAuth) c.Assert(proxyedRequest.URL.String(), check.Equals, "/mypath") c.Assert(string(proxyedBody), check.Equals, "my=awesome&body=1") c.Assert(eventtest.EventDesc{ Target: serviceTarget("foo"), Owner: s.token.GetUserName(), Kind: "service.update.proxy", StartCustomData: []map[string]interface{}{ {"name": ":service", "value": "foo"}, {"name": "callback", "value": "/mypath"}, {"name": "method", "value": "POST"}, {"name": "my", "value": "awesome"}, {"name": "body", "value": "1"}, }, }, eventtest.HasEvent) }
func (s *ConsumptionSuite) TestServiceInfoHandler(c *check.C) { srv := service.Service{Name: "mongodb", Teams: []string{s.team.Name}} err := srv.Create() c.Assert(err, check.IsNil) defer srv.Delete() si1 := service.ServiceInstance{ Name: "my_nosql", ServiceName: srv.Name, Apps: []string{}, Teams: []string{s.team.Name}, } err = si1.Create() c.Assert(err, check.IsNil) defer service.DeleteInstance(&si1) si2 := service.ServiceInstance{ Name: "your_nosql", ServiceName: srv.Name, Apps: []string{"wordpress"}, Teams: []string{s.team.Name}, } err = si2.Create() c.Assert(err, check.IsNil) defer service.DeleteInstance(&si2) request, err := http.NewRequest("GET", "/services/mongodb?:name=mongodb", nil) c.Assert(err, check.IsNil) recorder := httptest.NewRecorder() err = serviceInfo(recorder, request, s.token) c.Assert(err, check.IsNil) body, err := ioutil.ReadAll(recorder.Body) c.Assert(err, check.IsNil) var instances []service.ServiceInstance err = json.Unmarshal(body, &instances) c.Assert(err, check.IsNil) expected := []service.ServiceInstance{si1, si2} c.Assert(instances, check.DeepEquals, expected) action := rectest.Action{ Action: "service-info", User: s.user.Email, Extra: []interface{}{"mongodb"}, } c.Assert(action, rectest.IsRecorded) }
func removeServiceInstance(w http.ResponseWriter, r *http.Request, t auth.Token) error { u, err := t.User() if err != nil { return err } unbindAll := r.URL.Query().Get("unbindall") serviceName := r.URL.Query().Get(":service") instanceName := r.URL.Query().Get(":instance") rec.Log(u.Email, "remove-service-instance", instanceName) si, err := getServiceInstanceOrError(serviceName, instanceName, u) keepAliveWriter := io.NewKeepAliveWriter(w, 30*time.Second, "") defer keepAliveWriter.Stop() writer := &io.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)} if err != nil { writer.Encode(io.SimpleJsonMessage{Error: err.Error()}) return nil } if unbindAll == "true" { if len(si.Apps) > 0 { for _, appName := range si.Apps { _, app, instErr := getServiceInstance(si.ServiceName, si.Name, appName, u) if instErr != nil { writer.Encode(io.SimpleJsonMessage{Error: instErr.Error()}) return nil } fmt.Fprintf(writer, "Unbind app %q ...\n", app.GetName()) instErr = si.UnbindApp(app, writer) if instErr != nil { writer.Encode(io.SimpleJsonMessage{Error: instErr.Error()}) return nil } fmt.Fprintf(writer, "\nInstance %q is not bound to the app %q anymore.\n", si.Name, app.GetName()) } si, err = getServiceInstanceOrError(serviceName, instanceName, u) if err != nil { writer.Encode(io.SimpleJsonMessage{Error: err.Error()}) return nil } } } err = service.DeleteInstance(si) if err != nil { var msg string if err == service.ErrServiceInstanceBound { msg = strings.Join(si.Apps, ",") } writer.Encode(io.SimpleJsonMessage{Message: msg, Error: err.Error()}) return nil } writer.Write([]byte("service instance successfuly removed")) return nil }
func (s *ProvisionSuite) TestServicesAndInstancesByOwnerTeams(c *gocheck.C) { srvc := service.Service{Name: "mysql", OwnerTeams: []string{s.team.Name}} err := srvc.Create() c.Assert(err, gocheck.IsNil) defer srvc.Delete() srvc2 := service.Service{Name: "mongodb"} err = srvc2.Create() c.Assert(err, gocheck.IsNil) defer srvc2.Delete() sInstance := service.ServiceInstance{Name: "foo", ServiceName: "mysql"} err = sInstance.Create() c.Assert(err, gocheck.IsNil) defer service.DeleteInstance(&sInstance) sInstance2 := service.ServiceInstance{Name: "bar", ServiceName: "mongodb"} err = sInstance2.Create() defer service.DeleteInstance(&sInstance2) results := servicesAndInstancesByOwner(s.user) expected := []service.ServiceModel{ {Service: "mysql", Instances: []string{"foo"}}, } c.Assert(results, gocheck.DeepEquals, expected) }
func (s *ConsumptionSuite) TestServiceInfoHandlerShouldReturnOnlyInstancesOfTheSameTeamOfTheUser(c *check.C) { srv := service.Service{Name: "mongodb", Teams: []string{s.team.Name}} err := srv.Create() c.Assert(err, check.IsNil) defer srv.Delete() si1 := service.ServiceInstance{ Name: "my_nosql", ServiceName: srv.Name, Apps: []string{}, Teams: []string{s.team.Name}, } err = si1.Create() c.Assert(err, check.IsNil) defer service.DeleteInstance(&si1) si2 := service.ServiceInstance{ Name: "your_nosql", ServiceName: srv.Name, Apps: []string{"wordpress"}, Teams: []string{}, } err = si2.Create() c.Assert(err, check.IsNil) defer service.DeleteInstance(&si2) request, err := http.NewRequest("GET", fmt.Sprintf("/services/%s?:name=%s", "mongodb", "mongodb"), nil) c.Assert(err, check.IsNil) recorder := httptest.NewRecorder() err = serviceInfo(recorder, request, s.token) c.Assert(err, check.IsNil) body, err := ioutil.ReadAll(recorder.Body) c.Assert(err, check.IsNil) var instances []service.ServiceInstance err = json.Unmarshal(body, &instances) c.Assert(err, check.IsNil) expected := []service.ServiceInstance{si1} c.Assert(instances, check.DeepEquals, expected) }
func (s *ProvisionSuite) TestDeleteHandlerReturns403WhenTheServiceHasInstance(c *check.C) { se := service.Service{Name: "mysql", OwnerTeams: []string{s.team.Name}} err := se.Create() c.Assert(err, check.IsNil) defer s.conn.Services().Remove(bson.M{"_id": se.Name}) instance := service.ServiceInstance{Name: "my-mysql", ServiceName: se.Name} err = instance.Create() c.Assert(err, check.IsNil) defer service.DeleteInstance(&instance) u := fmt.Sprintf("/services/%s", se.Name) recorder, request := s.makeRequest("DELETE", u, "", c) s.m.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusForbidden) c.Assert(recorder.Body.String(), check.Equals, "This service cannot be removed because it has instances.\nPlease remove these instances before removing the service.\n") }
func (s *ConsumptionSuite) TestServiceInstanceStatusHandlerShouldReturnForbiddenWhenUserDontHaveAccess(c *check.C) { srv := service.Service{Name: "mongodb", OwnerTeams: []string{s.team.Name}} err := srv.Create() c.Assert(err, check.IsNil) defer srv.Delete() si := service.ServiceInstance{Name: "my_nosql", ServiceName: srv.Name} err = si.Create() c.Assert(err, check.IsNil) defer service.DeleteInstance(&si) recorder, request := makeRequestToStatusHandler("mongodb", "my_nosql", c) err = serviceInstanceStatus(recorder, request, s.token) c.Assert(err, check.NotNil) e, ok := err.(*errors.HTTP) c.Assert(ok, check.Equals, true) c.Assert(e.Code, check.Equals, http.StatusForbidden) }
func removeServiceInstance(w http.ResponseWriter, r *http.Request, t *auth.Token) error { u, err := t.User() if err != nil { return err } name := r.URL.Query().Get(":name") rec.Log(u.Email, "remove-service-instance", name) si, err := getServiceInstanceOrError(name, u) if err != nil { return err } err = service.DeleteInstance(si) if err != nil { return err } w.Write([]byte("service instance successfuly removed")) return nil }
func (s *ProvisionSuite) TestDeleteHandlerReturns403WhenTheServiceHasInstance(c *gocheck.C) { se := service.Service{Name: "mysql", OwnerTeams: []string{s.team.Name}} err := se.Create() c.Assert(err, gocheck.IsNil) defer s.conn.Services().Remove(bson.M{"_id": se.Name}) instance := service.ServiceInstance{Name: "my-mysql", ServiceName: se.Name} err = instance.Create() c.Assert(err, gocheck.IsNil) defer service.DeleteInstance(&instance) request, err := http.NewRequest("DELETE", fmt.Sprintf("/services/%s?:name=%s", se.Name, se.Name), nil) c.Assert(err, gocheck.IsNil) recorder := httptest.NewRecorder() err = serviceDelete(recorder, request, s.token) c.Assert(err, gocheck.NotNil) e, ok := err.(*errors.HTTP) c.Assert(ok, gocheck.Equals, true) c.Assert(e.Code, gocheck.Equals, http.StatusForbidden) c.Assert(e, gocheck.ErrorMatches, "^This service cannot be removed because it has instances.\nPlease remove these instances before removing the service.$") }
func (s *DeploySuite) TestDeployListByService(c *check.C) { user, _ := s.token.User() a := app.App{Name: "g1", Platform: "python", Teams: []string{s.team.Name}} err := app.CreateApp(&a, user) c.Assert(err, check.IsNil) defer app.Delete(&a, nil) var result []app.DeployData srv := service.Service{Name: "redis", Teams: []string{s.team.Name}} err = srv.Create() c.Assert(err, check.IsNil) instance := service.ServiceInstance{ Name: "redis-g1", ServiceName: "redis", Apps: []string{"g1", "qwerty"}, Teams: []string{s.team.Name}, } err = instance.Create() c.Assert(err, check.IsNil) defer func() { srv.Delete() service.DeleteInstance(&instance) }() request, err := http.NewRequest("GET", "/deploys?service=redis", 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, Duration: duration}) c.Assert(err, check.IsNil) err = s.conn.Deploys().Insert(app.DeployData{App: "ge", Timestamp: timestamp, 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, check.HasLen, 1) c.Assert(result[0].App, check.Equals, "g1") c.Assert(result[0].Timestamp.In(time.UTC), check.DeepEquals, timestamp.In(time.UTC)) c.Assert(result[0].Duration, check.DeepEquals, duration) }
func (s *ProvisionSuite) TestServiceListGetAllServicesFromUsersTeam(c *check.C) { srv := service.Service{Name: "mongodb", OwnerTeams: []string{s.team.Name}} srv.Create() defer s.conn.Services().Remove(bson.M{"_id": srv.Name}) si := service.ServiceInstance{Name: "my_nosql", ServiceName: srv.Name, Teams: []string{s.team.Name}} si.Create() defer service.DeleteInstance(&si, "") recorder, request := s.makeRequestToServicesHandler(c) request.Header.Set("Authorization", "bearer "+s.token.GetValue()) s.m.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusOK) services := make([]service.ServiceModel, 1) err := json.Unmarshal(recorder.Body.Bytes(), &services) c.Assert(err, check.IsNil) expected := []service.ServiceModel{ {Service: "mongodb", Instances: []string{"my_nosql"}}, } c.Assert(services, check.DeepEquals, expected) c.Assert(recorder.Header().Get("Content-Type"), check.Equals, "application/json") }
func (s *ProvisionSuite) TestServicesHandlerShoudGetAllServicesFromUsersTeam(c *gocheck.C) { srv := service.Service{Name: "mongodb", OwnerTeams: []string{s.team.Name}} srv.Create() defer s.conn.Services().Remove(bson.M{"_id": srv.Name}) si := service.ServiceInstance{Name: "my_nosql", ServiceName: srv.Name, Teams: []string{s.team.Name}} si.Create() defer service.DeleteInstance(&si) recorder, request := s.makeRequestToServicesHandler(c) err := serviceList(recorder, request, s.token) c.Assert(err, gocheck.IsNil) b, err := ioutil.ReadAll(recorder.Body) c.Assert(err, gocheck.IsNil) services := make([]service.ServiceModel, 1) err = json.Unmarshal(b, &services) expected := []service.ServiceModel{ {Service: "mongodb", Instances: []string{"my_nosql"}}, } c.Assert(services, gocheck.DeepEquals, expected) action := testing.Action{Action: "list-services", User: s.user.Email} c.Assert(action, testing.IsRecorded) }
func (s *ConsumptionSuite) TestServiceProxyNoContent(c *gocheck.C) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) })) defer ts.Close() se := service.Service{Name: "foo", Endpoint: map[string]string{"production": ts.URL}} err := se.Create() c.Assert(err, gocheck.IsNil) defer s.conn.Services().Remove(bson.M{"_id": se.Name}) si := service.ServiceInstance{Name: "foo-instance", ServiceName: "foo", Teams: []string{s.team.Name}} err = si.Create() c.Assert(err, gocheck.IsNil) defer service.DeleteInstance(&si) url := fmt.Sprintf("/services/proxy/%s?:instance=%s&callback=/mypath", si.Name, si.Name) request, err := http.NewRequest("GET", url, nil) c.Assert(err, gocheck.IsNil) recorder := httptest.NewRecorder() err = serviceProxy(recorder, request, s.token) c.Assert(err, gocheck.IsNil) c.Assert(recorder.Code, gocheck.Equals, http.StatusNoContent) }
func (s *DeploySuite) TestDeployListByAppAndService(c *check.C) { srv := service.Service{Name: "redis", Teams: []string{s.team.Name}} err := srv.Create() c.Assert(err, check.IsNil) instance := service.ServiceInstance{ Name: "redis-myblog", ServiceName: "redis", Apps: []string{"yourblog"}, Teams: []string{s.team.Name}, } err = instance.Create() c.Assert(err, check.IsNil) defer func() { srv.Delete() service.DeleteInstance(&instance) }() 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}, {App: "yourblog", Timestamp: timestamp, Duration: duration}, } 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&service=redis", nil) request.Header.Set("Authorization", "bearer "+s.token.GetValue()) server := RunServer(true) server.ServeHTTP(recorder, request) c.Assert(recorder.Code, check.Equals, http.StatusNoContent) }
// title: remove service instance // path: /services/{name}/instances/{instance} // method: DELETE // produce: application/x-json-stream // responses: // 200: Service removed // 401: Unauthorized // 404: Service instance not found func removeServiceInstance(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { r.ParseForm() unbindAll := r.URL.Query().Get("unbindall") serviceName := r.URL.Query().Get(":service") instanceName := r.URL.Query().Get(":instance") serviceInstance, err := getServiceInstanceOrError(serviceName, instanceName) if err != nil { return err } keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "") defer keepAliveWriter.Stop() writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)} w.Header().Set("Content-Type", "application/x-json-stream") allowed := permission.Check(t, permission.PermServiceInstanceDelete, contextsForServiceInstance(serviceInstance, serviceName)..., ) if !allowed { return permission.ErrUnauthorized } evt, err := event.New(&event.Opts{ Target: serviceInstanceTarget(serviceName, instanceName), Kind: permission.PermServiceInstanceDelete, Owner: t, CustomData: event.FormToCustomData(r.Form), Allowed: event.Allowed(permission.PermServiceInstanceReadEvents, contextsForServiceInstance(serviceInstance, serviceName)...), }) if err != nil { return err } defer func() { evt.Done(err) }() unbindAllBool, _ := strconv.ParseBool(unbindAll) if unbindAllBool { if len(serviceInstance.Apps) > 0 { for _, appName := range serviceInstance.Apps { _, app, instErr := getServiceInstance(serviceInstance.ServiceName, serviceInstance.Name, appName) if instErr != nil { return instErr } fmt.Fprintf(writer, "Unbind app %q ...\n", app.GetName()) instErr = serviceInstance.UnbindApp(app, true, writer) if instErr != nil { return instErr } fmt.Fprintf(writer, "\nInstance %q is not bound to the app %q anymore.\n", serviceInstance.Name, app.GetName()) } serviceInstance, err = getServiceInstanceOrError(serviceName, instanceName) if err != nil { return err } } } requestIDHeader, _ := config.GetString("request-id-header") requestID := context.GetRequestID(r, requestIDHeader) err = service.DeleteInstance(serviceInstance, requestID) if err != nil { if err == service.ErrServiceInstanceBound { writer.Write([]byte(strings.Join(serviceInstance.Apps, ","))) } return err } writer.Write([]byte("service instance successfully removed")) return nil }