From 5f50292a71acc7f8410bbc9b0568f4fff1532658 Mon Sep 17 00:00:00 2001 From: CarlosRoGuerra Date: Wed, 9 Jun 2021 17:18:00 -0300 Subject: [PATCH 01/20] change: form to json --- tsuru/client/apps.go | 119 ++++++++++-------- tsuru/client/apps_test.go | 257 ++++++++++++++++++++++---------------- 2 files changed, 218 insertions(+), 158 deletions(-) diff --git a/tsuru/client/apps.go b/tsuru/client/apps.go index 80b7a81f3..d11b7c2f3 100644 --- a/tsuru/client/apps.go +++ b/tsuru/client/apps.go @@ -21,9 +21,8 @@ import ( "text/template" "time" - "github.com/ajg/form" "github.com/tsuru/gnuflag" - "github.com/tsuru/go-tsuruclient/pkg/client" + tsuruClient "github.com/tsuru/go-tsuruclient/pkg/client" "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tablecli" "github.com/tsuru/tsuru/cmd" @@ -162,52 +161,55 @@ func (c *AppCreate) Flags() *gnuflag.FlagSet { return c.fs } -func (c *AppCreate) Run(context *cmd.Context, client *cmd.Client) error { +func (c *AppCreate) Run(ctx *cmd.Context, client *cmd.Client) error { + ctx.RawOutput() var platform string - appName := context.Args[0] - if len(context.Args) > 1 { - platform = context.Args[1] - } - v, err := form.EncodeToValues(map[string]interface{}{"routeropts": c.routerOpts}) - if err != nil { - return err - } - v.Set("name", appName) - v.Set("platform", platform) - v.Set("plan", c.plan) - v.Set("teamOwner", c.teamOwner) - v.Set("pool", c.pool) - v.Set("description", c.description) - for _, tag := range c.tags { - v.Add("tag", tag) - } - v.Set("router", c.router) - b := strings.NewReader(v.Encode()) - u, err := cmd.GetURL("/apps") - if err != nil { - return err - } - request, err := http.NewRequest("POST", u, b) - if err != nil { - return err - } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - response, err := client.Do(request) + appName := ctx.Args[0] + if len(ctx.Args) > 1 { + platform = ctx.Args[1] + } + var inputApp tsuru.InputApp + inputApp.Name = appName + inputApp.Platform = platform + inputApp.Plan = c.plan + inputApp.TeamOwner = c.teamOwner + inputApp.Pool = c.pool + inputApp.Description = c.description + inputApp.Tags = c.tags + inputApp.Router = c.router + inputApp.Routeropts = c.routerOpts + + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - defer response.Body.Close() - result, err := ioutil.ReadAll(response.Body) + _, response, err := apiClient.AppApi.AppCreate(context.TODO(), inputApp) if err != nil { return err } - out := make(map[string]string) - err = json.Unmarshal(result, &out) + err = cmd.StreamJSONResponse(ctx.Stdout, response) + if err != nil { return err } - fmt.Fprintf(context.Stdout, "App %q has been created!\n", appName) - fmt.Fprintln(context.Stdout, "Use app info to check the status of the app and its units.") + // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + // response, err := client.Do(request) + // if err != nil { + // return err + // } + //defer response.Body.Close() + + //result, err := ioutil.ReadAll(response.Body) + //if err != nil { + // return err + //} + //out := make(map[string]string) + //err = json.Unmarshal(result, &out) + + fmt.Fprintf(ctx.Stdout, "App %q has been created!\n", appName) + fmt.Fprintln(ctx.Stdout, "Use app info to check the status of the app and its units.") return nil } @@ -267,7 +269,7 @@ func (c *AppUpdate) Flags() *gnuflag.FlagSet { func (c *AppUpdate) Run(ctx *cmd.Context, cli *cmd.Client) error { ctx.RawOutput() - apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, }) if err != nil { @@ -1029,7 +1031,7 @@ func (f *appFilter) queryString(cli *cmd.Client) (url.Values, error) { } func currentUserEmail(cli *cmd.Client) (string, error) { - apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, }) if err != nil { @@ -1394,21 +1396,40 @@ func addCName(cnames []string, g cmd.AppNameMixIn, client *cmd.Client) error { if err != nil { return err } - u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/cname", appName)) + // u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/cname", appName)) + // if err != nil { + // return err + // } + // v := url.Values{} + // for _, cname := range cnames { + // v.Add("cname", cname) + // } + // b := strings.NewReader(v.Encode()) + // request, err := http.NewRequest("POST", u, b) + // if err != nil { + // return err + // } + var appCname tsuru.AppCName + appCname.Cname = cnames + + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - v := url.Values{} - for _, cname := range cnames { - v.Add("cname", cname) - } - b := strings.NewReader(v.Encode()) - request, err := http.NewRequest("POST", u, b) + _, err = apiClient.AppApi.AppCnameAdd(context.TODO(), appName, appCname) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + + //err = cmd.StreamJSONResponse(, response) + + //if err != nil { + // return err + //} + // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + // _, err = client.Do(request) return err } diff --git a/tsuru/client/apps_test.go b/tsuru/client/apps_test.go index 586ca4757..355bc9032 100644 --- a/tsuru/client/apps_test.go +++ b/tsuru/client/apps_test.go @@ -45,19 +45,23 @@ Use app info to check the status of the app and its units.` + "\n" trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - name := r.FormValue("name") == "ble" - platform := r.FormValue("platform") == "django" - teamOwner := r.FormValue("teamOwner") == "" - plan := r.FormValue("plan") == "" - pool := r.FormValue("pool") == "" - description := r.FormValue("description") == "" - r.ParseForm() - tags := r.Form["tag"] == nil - router := r.FormValue("router") == "" - method := r.Method == "POST" - contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" url := strings.HasSuffix(r.URL.Path, "/apps") - return method && url && name && platform && teamOwner && plan && pool && description && tags && contentType && router + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + var appResult map[string]interface{} + err = json.Unmarshal(data, &appResult) + c.Assert(err, check.IsNil) + name := appResult["name"] == "ble" + platform := appResult["platform"] == "django" + teamOwner := appResult["teamOwner"] == nil + plan := appResult["plan"] == nil + pool := appResult["pool"] == nil + description := appResult["description"] == nil + tags := appResult["tags"] == nil + router := appResult["router"] == nil + method := r.Method == "POST" + //contentType := r.Header.Get("Content-Type") == "application/json" + return method && url && name && platform && teamOwner && plan && pool && description && tags && router }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) @@ -80,18 +84,22 @@ Use app info to check the status of the app and its units.` + "\n" trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - name := r.FormValue("name") == "ble" - platform := r.FormValue("platform") == "" - teamOwner := r.FormValue("teamOwner") == "" - plan := r.FormValue("plan") == "" - pool := r.FormValue("pool") == "" - description := r.FormValue("description") == "" - r.ParseForm() - tags := r.Form["tag"] == nil - router := r.FormValue("router") == "" - method := r.Method == "POST" - contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" url := strings.HasSuffix(r.URL.Path, "/apps") + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + var appResult map[string]interface{} + err = json.Unmarshal(data, &appResult) + c.Assert(err, check.IsNil) + name := appResult["name"] == "ble" + platform := appResult["platform"] == nil + teamOwner := appResult["teamOwner"] == nil + plan := appResult["plan"] == nil + pool := appResult["pool"] == nil + description := appResult["description"] == nil + tags := appResult["tags"] == nil + router := appResult["router"] == nil + method := r.Method == "POST" + contentType := r.Header.Get("Content-Type") == "application/json" return method && url && name && platform && teamOwner && plan && pool && description && tags && contentType && router }, } @@ -115,18 +123,22 @@ Use app info to check the status of the app and its units.` + "\n" trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - name := r.FormValue("name") == "ble" - platform := r.FormValue("platform") == "django" - teamOwner := r.FormValue("teamOwner") == "team" - plan := r.FormValue("plan") == "" - pool := r.FormValue("pool") == "" - description := r.FormValue("description") == "" - r.ParseForm() - tags := r.Form["tag"] == nil - router := r.FormValue("router") == "" - method := r.Method == "POST" url := strings.HasSuffix(r.URL.Path, "/apps") - contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + var appResult map[string]interface{} + err = json.Unmarshal(data, &appResult) + c.Assert(err, check.IsNil) + name := appResult["name"] == "ble" + platform := appResult["platform"] == "django" + teamOwner := appResult["teamOwner"] == "team" + plan := appResult["plan"] == nil + pool := appResult["pool"] == nil + description := appResult["description"] == nil + tags := appResult["tags"] == nil + router := appResult["router"] == nil + method := r.Method == "POST" + contentType := r.Header.Get("Content-Type") == "application/json" return method && url && name && platform && teamOwner && plan && pool && description && tags && contentType && router }, } @@ -151,18 +163,22 @@ Use app info to check the status of the app and its units.` + "\n" trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - name := r.FormValue("name") == "ble" - platform := r.FormValue("platform") == "django" - teamOwner := r.FormValue("teamOwner") == "" - plan := r.FormValue("plan") == "myplan" - pool := r.FormValue("pool") == "" - router := r.FormValue("router") == "" - description := r.FormValue("description") == "" - r.ParseForm() - tags := r.Form["tag"] == nil - method := r.Method == "POST" url := strings.HasSuffix(r.URL.Path, "/apps") - contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + var appResult map[string]interface{} + err = json.Unmarshal(data, &appResult) + c.Assert(err, check.IsNil) + name := appResult["name"] == "ble" + platform := appResult["platform"] == "django" + teamOwner := appResult["teamOwner"] == nil + plan := appResult["plan"] == "myplan" + pool := appResult["pool"] == nil + description := appResult["description"] == nil + tags := appResult["tags"] == nil + router := appResult["router"] == nil + method := r.Method == "POST" + contentType := r.Header.Get("Content-Type") == "application/json" return method && url && name && platform && teamOwner && plan && pool && description && tags && contentType && router }, } @@ -187,19 +203,23 @@ Use app info to check the status of the app and its units.` + "\n" trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - name := r.FormValue("name") == "ble" - platform := r.FormValue("platform") == "django" - teamowner := r.FormValue("teamowner") == "" - plan := r.FormValue("plan") == "" - pool := r.FormValue("pool") == "mypool" - router := r.FormValue("router") == "" - description := r.FormValue("description") == "" - r.ParseForm() - tags := r.Form["tag"] == nil - method := r.Method == "POST" url := strings.HasSuffix(r.URL.Path, "/apps") - contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" - return method && url && name && platform && teamowner && plan && pool && description && tags && contentType && router + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + var appResult map[string]interface{} + err = json.Unmarshal(data, &appResult) + c.Assert(err, check.IsNil) + name := appResult["name"] == "ble" + platform := appResult["platform"] == "django" + teamOwner := appResult["teamOwner"] == nil + plan := appResult["plan"] == nil + pool := appResult["pool"] == "mypool" + description := appResult["description"] == nil + tags := appResult["tags"] == nil + router := appResult["router"] == nil + method := r.Method == "POST" + contentType := r.Header.Get("Content-Type") == "application/json" + return method && url && name && platform && teamOwner && plan && pool && description && tags && contentType && router }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) @@ -223,21 +243,23 @@ Use app info to check the status of the app and its units.` + "\n" trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - name := r.FormValue("name") == "ble" - platform := r.FormValue("platform") == "django" - teamowner := r.FormValue("teamowner") == "" - plan := r.FormValue("plan") == "" - pool := r.FormValue("pool") == "" - description := r.FormValue("description") == "" - r.ParseForm() - tags := r.Form["tag"] == nil - router := r.FormValue("router") == "" - c.Assert(r.FormValue("routeropts.a"), check.Equals, "1") - c.Assert(r.FormValue("routeropts.b"), check.Equals, "2") - method := r.Method == "POST" url := strings.HasSuffix(r.URL.Path, "/apps") - contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" - return method && url && name && platform && teamowner && plan && pool && description && tags && contentType && router + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + var appResult map[string]interface{} + err = json.Unmarshal(data, &appResult) + c.Assert(err, check.IsNil) + method := r.Method == "POST" + contentType := r.Header.Get("Content-Type") == "application/json" + c.Assert(appResult, check.DeepEquals, map[string]interface{}{ + "name": "ble", + "platform": "django", + "routeropts": map[string]interface{}{ + "a": "1", + "b": "2"}, + "metadata": map[string]interface{}{}, + }) + return method && url && contentType }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) @@ -261,18 +283,22 @@ Use app info to check the status of the app and its units.` + "\n" trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - name := r.FormValue("name") == "ble" - platform := r.FormValue("platform") == "django" - teamowner := r.FormValue("teamowner") == "" - plan := r.FormValue("plan") == "" - pool := r.FormValue("pool") == "" - router := r.FormValue("router") == "" - description := r.FormValue("description") == "" - r.ParseForm() - tags := r.Form["tag"] == nil - method := r.Method == "POST" url := strings.HasSuffix(r.URL.Path, "/apps") - contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + var appResult map[string]interface{} + err = json.Unmarshal(data, &appResult) + c.Assert(err, check.IsNil) + name := appResult["name"] == "ble" + platform := appResult["platform"] == "django" + teamowner := appResult["teamOwner"] == nil + plan := appResult["plan"] == nil + pool := appResult["pool"] == nil + description := appResult["description"] == nil + tags := appResult["tags"] == nil + router := appResult["router"] == nil + method := r.Method == "POST" + contentType := r.Header.Get("Content-Type") == "application/json" return method && url && name && platform && teamowner && plan && pool && description && tags && contentType && router }, } @@ -310,19 +336,23 @@ Use app info to check the status of the app and its units.` + "\n" trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - r.ParseForm() - name := r.FormValue("name") == "ble" - platform := r.FormValue("platform") == "django" - teamOwner := r.FormValue("teamOwner") == "" - plan := r.FormValue("plan") == "" - pool := r.FormValue("pool") == "" - description := r.FormValue("description") == "" - tags := len(r.Form["tag"]) == 2 && r.Form["tag"][0] == "tag1" && r.Form["tag"][1] == "tag2" - router := r.FormValue("router") == "" - method := r.Method == "POST" - contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" url := strings.HasSuffix(r.URL.Path, "/apps") - return method && url && name && platform && teamOwner && plan && pool && description && tags && contentType && router + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + var appResult map[string]interface{} + err = json.Unmarshal(data, &appResult) + c.Assert(err, check.IsNil) + c.Assert(appResult, check.DeepEquals, map[string]interface{}{ + "name": "ble", + "platform": "django", + "tags": []interface{}{ + "tag1", + "tag2"}, + "metadata": map[string]interface{}{}, + }) + method := r.Method == "POST" + contentType := r.Header.Get("Content-Type") == "application/json" + return method && contentType && url }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) @@ -346,19 +376,21 @@ Use app info to check the status of the app and its units.` + "\n" trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - r.ParseForm() - name := r.FormValue("name") == "ble" - platform := r.FormValue("platform") == "django" - teamOwner := r.FormValue("teamOwner") == "" - plan := r.FormValue("plan") == "" - pool := r.FormValue("pool") == "" - description := r.FormValue("description") == "" - tags := len(r.Form["tag"]) == 1 && r.Form["tag"][0] == "" - router := r.FormValue("router") == "" - method := r.Method == "POST" - contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" url := strings.HasSuffix(r.URL.Path, "/apps") - return method && url && name && platform && teamOwner && plan && pool && description && tags && contentType && router + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + var appResult map[string]interface{} + err = json.Unmarshal(data, &appResult) + c.Assert(err, check.IsNil) + c.Assert(appResult, check.DeepEquals, map[string]interface{}{ + "name": "ble", + "platform": "django", + "tags": []interface{}{""}, + "metadata": map[string]interface{}{}, + }) + method := r.Method == "POST" + contentType := r.Header.Get("Content-Type") == "application/json" + return method && url && contentType }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) @@ -2641,11 +2673,18 @@ func (s *S) TestAddCName(c *check.C) { Transport: cmdtest.Transport{Message: "Restarted", Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { called = true - cname := req.FormValue("cname") == "death.evergrey.mycompany.com" + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + cNameResult := make(map[string]interface{}) + err = json.Unmarshal(data, &cNameResult) + c.Assert(err, check.IsNil) + c.Assert(cNameResult, check.DeepEquals, map[string]interface{}{ + "cname": []interface{}{"death.evergrey.mycompany.com"}, + }) method := req.Method == "POST" url := strings.HasSuffix(req.URL.Path, "/apps/death/cname") - contentType := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" - return method && url && cname && contentType + contentType := req.Header.Get("Content-Type") == "application/json" + return method && url && contentType }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) From ced8e542e631141167a7b01015ab23b7c5e5b0ad Mon Sep 17 00:00:00 2001 From: CarlosRoGuerra Date: Mon, 14 Jun 2021 14:25:52 -0300 Subject: [PATCH 02/20] change: form to json --- tsuru/.DS_Store | Bin 0 -> 6148 bytes tsuru/client/apps.go | 137 +++++++++++++++++++++++----------- tsuru/client/apps_test.go | 101 ++++++++++++++++++++----- tsuru/client/services.go | 39 +++++----- tsuru/client/services_test.go | 99 +++++++++++++++--------- 5 files changed, 257 insertions(+), 119 deletions(-) create mode 100644 tsuru/.DS_Store diff --git a/tsuru/.DS_Store b/tsuru/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..7642cd60bd235aed0fedcfd7b68778ca8eddbfdf GIT binary patch literal 6148 zcmeHK%}(1u5Z(!+k>#ln9UdypokRxLJcwM?kgN!X`B{*p!Avwc{zV3G?H1V&mav#bY;gi$>##R~D-87MFyz zT(hkAmi5)^r$evsi$UJ@v!1=-#bFfq*>M~e{liFhljuB>``MmfMA-=jAEs#n0owM1 zqc|G&?3JBV7Je+FOx4phPLE?5ro(nRkYTRkO>t#^@rypx5u5Hwsra;n=-I2IQL|Nd zKDWkoXVm<-y$yEb(|9a|Sl`+`_%^t>yt=-*y}SSQpcjF|_p0QB!3jKqF~!HZm&qiR zKfyoAnZyzj1H=F^Fs}@l{Y=#6bprI>!~iky#~8r&)cvtaU)YgQ8$usqr-h40RMk fEFQ&cpi02+paJL_EH#1$gnk4R4b%_=f0cn32kl}m literal 0 HcmV?d00001 diff --git a/tsuru/client/apps.go b/tsuru/client/apps.go index d11b7c2f3..de763a1b6 100644 --- a/tsuru/client/apps.go +++ b/tsuru/client/apps.go @@ -1460,31 +1460,48 @@ func (c *UnitAdd) Flags() *gnuflag.FlagSet { return c.fs } -func (c *UnitAdd) Run(context *cmd.Context, client *cmd.Client) error { - context.RawOutput() +func (c *UnitAdd) Run(ctx *cmd.Context, client *cmd.Client) error { + ctx.RawOutput() appName, err := c.AppName() if err != nil { return err } - u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/units", appName)) - if err != nil { - return err - } - val := url.Values{} - val.Add("units", context.Args[0]) - val.Add("process", c.process) - val.Set("version", c.version) - request, err := http.NewRequest("PUT", u, bytes.NewBufferString(val.Encode())) + // u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/units", appName)) + // if err != nil { + // return err + // } + // val := url.Values{} + // val.Add("units", context.Args[0]) + // val.Add("process", c.process) + // val.Set("version", c.version) + // request, err := http.NewRequest("PUT", u, bytes.NewBufferString(val.Encode())) + // if err != nil { + // return err + // } + var unitDelta tsuru.UnitsDelta + + unitDelta.Units = ctx.Args[0] + unitDelta.Process = c.process + unitDelta.Version = c.version + + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - response, err := client.Do(request) + + response, err := apiClient.AppApi.UnitsAdd(context.TODO(), appName, unitDelta) if err != nil { return err } - defer response.Body.Close() - return cmd.StreamJSONResponse(context.Stdout, response) + // request.Header.Add("Content-Type", "application/x-www-form-urlencoded") + // response, err := client.Do(request) + // if err != nil { + // return err + // } + //defer response.Body.Close() + return cmd.StreamJSONResponse(ctx.Stdout, response) } type UnitRemove struct { @@ -1567,8 +1584,8 @@ func (c *UnitSet) Flags() *gnuflag.FlagSet { return c.fs } -func (c *UnitSet) Run(context *cmd.Context, client *cmd.Client) error { - context.RawOutput() +func (c *UnitSet) Run(ctx *cmd.Context, client *cmd.Client) error { + ctx.RawOutput() appName, err := c.AppName() if err != nil { return err @@ -1631,62 +1648,94 @@ func (c *UnitSet) Run(context *cmd.Context, client *cmd.Client) error { } } - desiredUnits, err := strconv.Atoi(context.Args[0]) + desiredUnits, err := strconv.Atoi(ctx.Args[0]) if err != nil { return err } if existingUnits < desiredUnits { - u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/units", appName)) - if err != nil { - return err - } + // u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/units", appName)) + // if err != nil { + // return err + // } unitsToAdd := desiredUnits - existingUnits - val := url.Values{} - val.Add("units", strconv.Itoa(unitsToAdd)) - val.Add("process", c.process) - val.Add("version", strconv.Itoa(c.version)) - request, err := http.NewRequest(http.MethodPut, u, bytes.NewBufferString(val.Encode())) + // val := url.Values{} + // val.Add("units", strconv.Itoa(unitsToAdd)) + // val.Add("process", c.process) + // val.Add("version", strconv.Itoa(c.version)) + // request, err := http.NewRequest(http.MethodPut, u, bytes.NewBufferString(val.Encode())) + // if err != nil { + // return err + // } + var unitDelta tsuru.UnitsDelta + unitDelta.Units = strconv.Itoa(unitsToAdd) + unitDelta.Process = c.process + unitDelta.Version = strconv.Itoa(c.version) + + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - response, err := client.Do(request) + response, err := apiClient.AppApi.UnitsAdd(context.TODO(), appName, unitDelta) if err != nil { return err } + // request.Header.Add("Content-Type", "application/x-www-form-urlencoded") + // response, err := client.Do(request) + // if err != nil { + // return err + // } - defer response.Body.Close() - return cmd.StreamJSONResponse(context.Stdout, response) + // defer response.Body.Close() + return cmd.StreamJSONResponse(ctx.Stdout, response) } if existingUnits > desiredUnits { unitsToRemove := existingUnits - desiredUnits - val := url.Values{} - val.Add("units", strconv.Itoa(unitsToRemove)) - val.Add("process", c.process) - val.Add("version", strconv.Itoa(c.version)) - u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/units?%s", appName, val.Encode())) + // val := url.Values{} + // val.Add("units", strconv.Itoa(unitsToRemove)) + // val.Add("process", c.process) + // val.Add("version", strconv.Itoa(c.version)) + // u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/units?%s", appName, val.Encode())) + // if err != nil { + // return err + // } + + var unitDelta tsuru.UnitsDelta + unitDelta.Units = strconv.Itoa(unitsToRemove) + unitDelta.Process = c.process + unitDelta.Version = strconv.Itoa(c.version) + + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request, err := http.NewRequest(http.MethodDelete, u, nil) + response, err := apiClient.AppApi.UnitsRemove(context.TODO(), appName, unitDelta) if err != nil { return err } - response, err := client.Do(request) - if err != nil { - return err - } + // request, err := http.NewRequest(http.MethodDelete, u, nil) + // if err != nil { + // return err + // } - defer response.Body.Close() - return cmd.StreamJSONResponse(context.Stdout, response) + // response, err := client.Do(request) + // if err != nil { + // return err + // } + + // defer response.Body.Close() + return cmd.StreamJSONResponse(ctx.Stdout, response) } - fmt.Fprintf(context.Stdout, "The process %s, version %d already has %d units.\n", c.process, c.version, existingUnits) + fmt.Fprintf(ctx.Stdout, "The process %s, version %d already has %d units.\n", c.process, c.version, existingUnits) return nil } diff --git a/tsuru/client/apps_test.go b/tsuru/client/apps_test.go index 355bc9032..5aa5aa083 100644 --- a/tsuru/client/apps_test.go +++ b/tsuru/client/apps_test.go @@ -2713,7 +2713,7 @@ func (s *S) TestAddCNameFailure(c *check.C) { context.Args = command.Flags().Args() err = command.Run(&context, client) c.Assert(err, check.NotNil) - c.Assert(err.Error(), check.Equals, "Invalid cname") + c.Assert(err.Error(), check.Equals, "412 Precondition Failed: Invalid cname") } func (s *S) TestAddCNameInfo(c *check.C) { @@ -2905,8 +2905,17 @@ func (s *S) TestUnitAdd(c *check.C) { Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { called = true - c.Assert(req.FormValue("process"), check.Equals, "p1") - c.Assert(req.FormValue("units"), check.Equals, "3") + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + var result map[string]interface{} + err = json.Unmarshal(data, &result) + c.Assert(err, check.IsNil) + c.Assert(result, check.DeepEquals, map[string]interface{}{ + "units": "3", + "process": "p1", + }) + // c.Assert(req.FormValue("process"), check.Equals, "p1") + // c.Assert(req.FormValue("units"), check.Equals, "3") return strings.HasSuffix(req.URL.Path, "/apps/radio/units") && req.Method == "PUT" }, } @@ -2935,9 +2944,19 @@ func (s *S) TestUnitAddWithVersion(c *check.C) { Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { called = true - c.Assert(req.FormValue("process"), check.Equals, "p1") - c.Assert(req.FormValue("units"), check.Equals, "3") - c.Assert(req.FormValue("version"), check.Equals, "9") + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + var result map[string]interface{} + err = json.Unmarshal(data, &result) + c.Assert(err, check.IsNil) + c.Assert(result, check.DeepEquals, map[string]interface{}{ + "units": "3", + "process": "p1", + "version": "9", + }) + // c.Assert(req.FormValue("process"), check.Equals, "p1") + // c.Assert(req.FormValue("units"), check.Equals, "3") + // c.Assert(req.FormValue("version"), check.Equals, "9") return strings.HasSuffix(req.URL.Path, "/apps/radio/units") && req.Method == "PUT" }, } @@ -3059,8 +3078,16 @@ func (s *S) TestUnitSetAddUnits(c *check.C) { { CondFunc: func(req *http.Request) bool { calledPut = true - c.Assert(req.FormValue("process"), check.Equals, "web") - c.Assert(req.FormValue("units"), check.Equals, "7") + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + var result map[string]interface{} + err = json.Unmarshal(data, &result) + c.Assert(err, check.IsNil) + c.Assert(result, check.DeepEquals, map[string]interface{}{ + "units": "7", + "process": "web", + "version": "0", + }) return strings.HasSuffix(req.URL.Path, "/apps/app1/units") && req.Method == http.MethodPut }, Transport: cmdtest.Transport{Message: string(resultPut), Status: http.StatusOK}, @@ -3102,8 +3129,16 @@ func (s *S) TestUnitSetAddUnitsFailure(c *check.C) { { CondFunc: func(req *http.Request) bool { calledPut = true - c.Assert(req.FormValue("process"), check.Equals, "web") - c.Assert(req.FormValue("units"), check.Equals, "7") + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + var result map[string]interface{} + err = json.Unmarshal(data, &result) + c.Assert(err, check.IsNil) + c.Assert(result, check.DeepEquals, map[string]interface{}{ + "units": "7", + "process": "web", + "version": "0", + }) return strings.HasSuffix(req.URL.Path, "/apps/app1/units") && req.Method == http.MethodPut }, Transport: cmdtest.Transport{Message: "Failed to put.", Status: http.StatusInternalServerError}, @@ -3116,7 +3151,7 @@ func (s *S) TestUnitSetAddUnitsFailure(c *check.C) { command.Flags().Parse(true, []string{"-a", "app1", "-p", "web"}) err := command.Run(&context, client) c.Assert(err, check.NotNil) - c.Assert(err.Error(), check.Equals, "Failed to put.") + c.Assert(err.Error(), check.Equals, "500 Internal Server Error: Failed to put.") c.Assert(calledGet, check.Equals, true) c.Assert(calledPut, check.Equals, true) } @@ -3149,8 +3184,18 @@ func (s *S) TestUnitSetRemoveUnits(c *check.C) { { CondFunc: func(req *http.Request) bool { calledDelete = true - c.Assert(req.FormValue("process"), check.Equals, "web") - c.Assert(req.FormValue("units"), check.Equals, "2") + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + var result map[string]interface{} + err = json.Unmarshal(data, &result) + c.Assert(err, check.IsNil) + c.Assert(result, check.DeepEquals, map[string]interface{}{ + "units": "2", + "process": "web", + "version": "0", + }) + // c.Assert(req.FormValue("process"), check.Equals, "web") + // c.Assert(req.FormValue("units"), check.Equals, "2") return strings.HasSuffix(req.URL.Path, "/apps/app1/units") && req.Method == http.MethodDelete }, Transport: cmdtest.Transport{Message: string(resultDelete), Status: http.StatusOK}, @@ -3192,8 +3237,18 @@ func (s *S) TestUnitSetRemoveUnitsFailure(c *check.C) { { CondFunc: func(req *http.Request) bool { calledDelete = true - c.Assert(req.FormValue("process"), check.Equals, "web") - c.Assert(req.FormValue("units"), check.Equals, "2") + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + var result map[string]interface{} + err = json.Unmarshal(data, &result) + c.Assert(err, check.IsNil) + c.Assert(result, check.DeepEquals, map[string]interface{}{ + "units": "2", + "process": "web", + "version": "0", + }) + // c.Assert(req.FormValue("process"), check.Equals, "web") + // c.Assert(req.FormValue("units"), check.Equals, "2") return strings.HasSuffix(req.URL.Path, "/apps/app1/units") && req.Method == http.MethodDelete }, Transport: cmdtest.Transport{Message: "Failed to delete.", Status: http.StatusInternalServerError}, @@ -3206,7 +3261,7 @@ func (s *S) TestUnitSetRemoveUnitsFailure(c *check.C) { command.Flags().Parse(true, []string{"-a", "app1", "-p", "web"}) err := command.Run(&context, client) c.Assert(err, check.NotNil) - c.Assert(err.Error(), check.Equals, "Failed to delete.") + c.Assert(err.Error(), check.Equals, "500 Internal Server Error: Failed to delete.") c.Assert(calledGet, check.Equals, true) c.Assert(calledDelete, check.Equals, true) } @@ -3319,8 +3374,18 @@ func (s *S) TestUnitSetNoProcessSpecifiedAndSingleExists(c *check.C) { { CondFunc: func(req *http.Request) bool { calledPut = true - c.Assert(req.FormValue("process"), check.Equals, "worker") - c.Assert(req.FormValue("units"), check.Equals, "8") + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + var result map[string]interface{} + err = json.Unmarshal(data, &result) + c.Assert(err, check.IsNil) + c.Assert(result, check.DeepEquals, map[string]interface{}{ + "units": "8", + "process": "worker", + "version": "0", + }) + // c.Assert(req.FormValue("process"), check.Equals, "worker") + // c.Assert(req.FormValue("units"), check.Equals, "8") return strings.HasSuffix(req.URL.Path, "/apps/app1/units") && req.Method == http.MethodPut }, Transport: cmdtest.Transport{Message: string(resultPut), Status: http.StatusOK}, diff --git a/tsuru/client/services.go b/tsuru/client/services.go index 1d66af2bd..f200dbb6e 100644 --- a/tsuru/client/services.go +++ b/tsuru/client/services.go @@ -130,39 +130,36 @@ This example shows how to add a new instance of **mongodb** service, named } } -func (c *ServiceInstanceAdd) Run(ctx *cmd.Context, client *cmd.Client) error { +func (c *ServiceInstanceAdd) Run(ctx *cmd.Context, cli *cmd.Client) error { + ctx.RawOutput() serviceName, instanceName := ctx.Args[0], ctx.Args[1] var plan string if len(ctx.Args) > 2 { plan = ctx.Args[2] } - parameters := make(map[string]interface{}) - for k, v := range c.params { - parameters[k] = v - } - v, err := form.EncodeToValues(map[string]interface{}{"parameters": parameters}) - if err != nil { - return err - } // This is kept as this to keep backwards compatibility with older API versions - v.Set("name", instanceName) - v.Set("plan", plan) - v.Set("owner", c.teamOwner) - v.Set("description", c.description) - v.Set("pool", c.pool) - for _, tag := range c.tags { - v.Add("tag", tag) - } - u, err := cmd.GetURL(fmt.Sprintf("/services/%s/instances", serviceName)) + var instanceAdd tsuru.ServiceInstance + instanceAdd.Name = instanceName + instanceAdd.PlanName = plan + instanceAdd.Description = c.description + instanceAdd.TeamOwner = c.teamOwner + instanceAdd.Pool = c.pool + instanceAdd.Parameters = c.params + instanceAdd.Tags = c.tags + + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: cli.HTTPClient, + }) if err != nil { return err } - request, err := http.NewRequest("POST", u, strings.NewReader(v.Encode())) + _, err = apiClient.ServiceApi.InstanceCreate(context.TODO(), serviceName, instanceAdd) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + //err = cmd.StreamJSONResponse(ctx.Stdout, response) + //request.Header.Set("Content-Type", "application/json") + // _, err = cli.Do(request) if err != nil { return err } diff --git a/tsuru/client/services_test.go b/tsuru/client/services_test.go index 234ad8183..b90610164 100644 --- a/tsuru/client/services_test.go +++ b/tsuru/client/services_test.go @@ -11,7 +11,6 @@ import ( "net/http" "strings" - "github.com/ajg/form" "github.com/tsuru/tsuru/cmd" "github.com/tsuru/tsuru/cmd/cmdtest" "github.com/tsuru/tsuru/io" @@ -394,34 +393,52 @@ func (s *S) TestServiceInstanceAddRun(c *check.C) { trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - err := r.ParseForm() + //err := r.ParseForm() + data, err := ioutil.ReadAll(r.Body) c.Assert(err, check.IsNil) - instance := service.ServiceInstance{ - PlanName: r.FormValue("plan"), - TeamOwner: r.FormValue("owner"), - } - dec := form.NewDecoder(nil) - dec.IgnoreCase(true) - dec.IgnoreUnknownKeys(true) - dec.UseJSONTags(false) - err = dec.DecodeValues(&instance, r.Form) + // instance := service.ServiceInstance{ + // PlanName: r.FormValue("plan"), + // TeamOwner: r.FormValue("owner"), + // } + // dec := form.NewDecoder(nil) + // dec.IgnoreCase(true) + // dec.IgnoreUnknownKeys(true) + // dec.UseJSONTags(false) + var result map[string]interface{} + err = json.Unmarshal(data, &result) c.Assert(err, check.IsNil) - instance.Tags = append(instance.Tags, r.Form["tag"]...) - c.Assert(err, check.IsNil) - c.Assert(instance, check.DeepEquals, service.ServiceInstance{ - Name: "my_app_db", - PlanName: "small", - TeamOwner: "my team", - Description: "desc", - Tags: []string{"my tag 1", "my tag 2"}, - Parameters: map[string]interface{}{ + c.Assert(result, check.DeepEquals, map[string]interface{}{ + "name": "my_app_db", + "plan_name": "small", + "team_owner": "my team", + "description": "desc", + "tags": []interface{}{ + "my tag 1", "my tag 2"}, + "parameters": map[string]interface{}{ "param1": "value1", "param2": "value2", }, - Pool: "pool-one", + "pool": "pool-one", }) + //err = json.Unmarshal(data, &instance) + //err = dec.DecodeValues(&instance, r.Form) + //c.Assert(err, check.IsNil) + // instance.Tags = append(instance.Tags, r.Form["tag"]...) + // c.Assert(err, check.IsNil) + // c.Assert(instance, check.DeepEquals, service.ServiceInstance{ + // Name: "my_app_db", + // PlanName: "small", + // TeamOwner: "my team", + // Description: "desc", + // Tags: []string{"my tag 1", "my tag 2"}, + // Parameters: map[string]interface{}{ + // "param1": "value1", + // "param2": "value2", + // }, + // Pool: "pool-one", + // }) c.Assert(r.Method, check.DeepEquals, "POST") - c.Assert(r.Header.Get("Content-Type"), check.DeepEquals, "application/x-www-form-urlencoded") + c.Assert(r.Header.Get("Content-Type"), check.DeepEquals, "application/json") return strings.HasSuffix(r.URL.Path, "/services/mysql/instances") }, } @@ -456,22 +473,32 @@ func (s *S) TestServiceInstanceAddRunWithEmptyTag(c *check.C) { trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - err := r.ParseForm() - c.Assert(err, check.IsNil) - instance := service.ServiceInstance{ - PlanName: r.FormValue("plan"), - TeamOwner: r.FormValue("owner"), - } - dec := form.NewDecoder(nil) - dec.IgnoreCase(true) - dec.IgnoreUnknownKeys(true) - dec.UseJSONTags(false) - err = dec.DecodeValues(&instance, r.Form) + data, err := ioutil.ReadAll(r.Body) c.Assert(err, check.IsNil) - instance.Tags = append(instance.Tags, r.Form["tag"]...) + var result map[string]interface{} + err = json.Unmarshal(data, &result) c.Assert(err, check.IsNil) - c.Assert(len(instance.Tags), check.Equals, 1) - c.Assert(instance.Tags[0], check.DeepEquals, "") + c.Assert(result, check.DeepEquals, map[string]interface{}{ + "name": "my_app_db", + "plan_name": "small", + "tags": []interface{}{""}, + }) + // err := r.ParseForm() + // c.Assert(err, check.IsNil) + // instance := service.ServiceInstance{ + // PlanName: r.FormValue("plan"), + // TeamOwner: r.FormValue("owner"), + // } + // dec := form.NewDecoder(nil) + // dec.IgnoreCase(true) + // dec.IgnoreUnknownKeys(true) + // dec.UseJSONTags(false) + // err = dec.DecodeValues(&instance, r.Form) + // c.Assert(err, check.IsNil) + // instance.Tags = append(instance.Tags, r.Form["tag"]...) + // c.Assert(err, check.IsNil) + // c.Assert(len(instance.Tags), check.Equals, 1) + // c.Assert(instance.Tags[0], check.DeepEquals, "") return true }, } From 8371153e0e8dc4c5787e910fd4b4be31613f4211 Mon Sep 17 00:00:00 2001 From: CarlosRoGuerra Date: Mon, 21 Jun 2021 15:15:15 -0300 Subject: [PATCH 03/20] change: form to json --- tsuru/client/apps.go | 31 ++++---- tsuru/client/apps_test.go | 95 ++++++++++--------------- tsuru/client/auth.go | 112 +++++++++++++++++++---------- tsuru/client/auth_test.go | 33 +++++++-- tsuru/client/env.go | 68 +++++++++++------- tsuru/client/env_test.go | 124 ++++++++++++++++++-------------- tsuru/client/services.go | 34 ++++++--- tsuru/client/services_test.go | 22 ++++-- tsuru/client/volume.go | 129 +++++++++++++++++++++------------- tsuru/client/volume_test.go | 77 +++++++++++++++----- 10 files changed, 454 insertions(+), 271 deletions(-) diff --git a/tsuru/client/apps.go b/tsuru/client/apps.go index de763a1b6..8bce8ede6 100644 --- a/tsuru/client/apps.go +++ b/tsuru/client/apps.go @@ -168,24 +168,23 @@ func (c *AppCreate) Run(ctx *cmd.Context, client *cmd.Client) error { if len(ctx.Args) > 1 { platform = ctx.Args[1] } - var inputApp tsuru.InputApp - inputApp.Name = appName - inputApp.Platform = platform - inputApp.Plan = c.plan - inputApp.TeamOwner = c.teamOwner - inputApp.Pool = c.pool - inputApp.Description = c.description - inputApp.Tags = c.tags - inputApp.Router = c.router - inputApp.Routeropts = c.routerOpts - apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: client.HTTPClient, }) if err != nil { return err } - _, response, err := apiClient.AppApi.AppCreate(context.TODO(), inputApp) + _, response, err := apiClient.AppApi.AppCreate(context.TODO(), tsuru.InputApp{ + Name: appName, + Platform: platform, + Pool: c.pool, + Description: c.description, + Plan: c.plan, + TeamOwner: c.teamOwner, + Tags: c.tags, + Router: c.router, + Routeropts: c.routerOpts, + }) if err != nil { return err } @@ -1198,6 +1197,14 @@ func (c *AppStop) Run(context *cmd.Context, client *cmd.Client) error { if err != nil { return err } + // apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + // HTTPClient: client.HTTPClient, + // }) + // if err != nil { + // return err + // } + // _, err = apiClient.AppApi.AppRestart() + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") response, err := client.Do(request) if err != nil { diff --git a/tsuru/client/apps_test.go b/tsuru/client/apps_test.go index 5aa5aa083..4faafdfda 100644 --- a/tsuru/client/apps_test.go +++ b/tsuru/client/apps_test.go @@ -51,17 +51,14 @@ Use app info to check the status of the app and its units.` + "\n" var appResult map[string]interface{} err = json.Unmarshal(data, &appResult) c.Assert(err, check.IsNil) - name := appResult["name"] == "ble" - platform := appResult["platform"] == "django" - teamOwner := appResult["teamOwner"] == nil - plan := appResult["plan"] == nil - pool := appResult["pool"] == nil - description := appResult["description"] == nil - tags := appResult["tags"] == nil - router := appResult["router"] == nil + c.Assert(appResult, check.DeepEquals, map[string]interface{}{ + "name": "ble", + "platform": "django", + "metadata": map[string]interface{}{}, + }) method := r.Method == "POST" - //contentType := r.Header.Get("Content-Type") == "application/json" - return method && url && name && platform && teamOwner && plan && pool && description && tags && router + contentType := r.Header.Get("Content-Type") == "application/json" + return method && url && contentType }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) @@ -90,17 +87,13 @@ Use app info to check the status of the app and its units.` + "\n" var appResult map[string]interface{} err = json.Unmarshal(data, &appResult) c.Assert(err, check.IsNil) - name := appResult["name"] == "ble" - platform := appResult["platform"] == nil - teamOwner := appResult["teamOwner"] == nil - plan := appResult["plan"] == nil - pool := appResult["pool"] == nil - description := appResult["description"] == nil - tags := appResult["tags"] == nil - router := appResult["router"] == nil + c.Assert(appResult, check.DeepEquals, map[string]interface{}{ + "name": "ble", + "metadata": map[string]interface{}{}, + }) method := r.Method == "POST" contentType := r.Header.Get("Content-Type") == "application/json" - return method && url && name && platform && teamOwner && plan && pool && description && tags && contentType && router + return method && url && contentType }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) @@ -129,17 +122,14 @@ Use app info to check the status of the app and its units.` + "\n" var appResult map[string]interface{} err = json.Unmarshal(data, &appResult) c.Assert(err, check.IsNil) - name := appResult["name"] == "ble" - platform := appResult["platform"] == "django" - teamOwner := appResult["teamOwner"] == "team" - plan := appResult["plan"] == nil - pool := appResult["pool"] == nil - description := appResult["description"] == nil - tags := appResult["tags"] == nil - router := appResult["router"] == nil - method := r.Method == "POST" + c.Assert(appResult, check.DeepEquals, map[string]interface{}{ + "name": "ble", + "platform": "django", + "teamOwner": "team", + "metadata": map[string]interface{}{}, + }) contentType := r.Header.Get("Content-Type") == "application/json" - return method && url && name && platform && teamOwner && plan && pool && description && tags && contentType && router + return url && contentType }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) @@ -169,17 +159,15 @@ Use app info to check the status of the app and its units.` + "\n" var appResult map[string]interface{} err = json.Unmarshal(data, &appResult) c.Assert(err, check.IsNil) - name := appResult["name"] == "ble" - platform := appResult["platform"] == "django" - teamOwner := appResult["teamOwner"] == nil - plan := appResult["plan"] == "myplan" - pool := appResult["pool"] == nil - description := appResult["description"] == nil - tags := appResult["tags"] == nil - router := appResult["router"] == nil + c.Assert(appResult, check.DeepEquals, map[string]interface{}{ + "name": "ble", + "platform": "django", + "plan": "myplan", + "metadata": map[string]interface{}{}, + }) method := r.Method == "POST" contentType := r.Header.Get("Content-Type") == "application/json" - return method && url && name && platform && teamOwner && plan && pool && description && tags && contentType && router + return method && url && contentType }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) @@ -209,17 +197,15 @@ Use app info to check the status of the app and its units.` + "\n" var appResult map[string]interface{} err = json.Unmarshal(data, &appResult) c.Assert(err, check.IsNil) - name := appResult["name"] == "ble" - platform := appResult["platform"] == "django" - teamOwner := appResult["teamOwner"] == nil - plan := appResult["plan"] == nil - pool := appResult["pool"] == "mypool" - description := appResult["description"] == nil - tags := appResult["tags"] == nil - router := appResult["router"] == nil + c.Assert(appResult, check.DeepEquals, map[string]interface{}{ + "name": "ble", + "platform": "django", + "pool": "mypool", + "metadata": map[string]interface{}{}, + }) method := r.Method == "POST" contentType := r.Header.Get("Content-Type") == "application/json" - return method && url && name && platform && teamOwner && plan && pool && description && tags && contentType && router + return method && url && contentType }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) @@ -289,17 +275,14 @@ Use app info to check the status of the app and its units.` + "\n" var appResult map[string]interface{} err = json.Unmarshal(data, &appResult) c.Assert(err, check.IsNil) - name := appResult["name"] == "ble" - platform := appResult["platform"] == "django" - teamowner := appResult["teamOwner"] == nil - plan := appResult["plan"] == nil - pool := appResult["pool"] == nil - description := appResult["description"] == nil - tags := appResult["tags"] == nil - router := appResult["router"] == nil + c.Assert(appResult, check.DeepEquals, map[string]interface{}{ + "name": "ble", + "platform": "django", + "metadata": map[string]interface{}{}, + }) method := r.Method == "POST" contentType := r.Header.Get("Content-Type") == "application/json" - return method && url && name && platform && teamowner && plan && pool && description && tags && contentType && router + return method && url && contentType }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) diff --git a/tsuru/client/auth.go b/tsuru/client/auth.go index 44962b892..f48f373ea 100644 --- a/tsuru/client/auth.go +++ b/tsuru/client/auth.go @@ -19,7 +19,7 @@ import ( "github.com/antihax/optional" "github.com/tsuru/gnuflag" - "github.com/tsuru/go-tsuruclient/pkg/client" + tsuruClient "github.com/tsuru/go-tsuruclient/pkg/client" "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tablecli" "github.com/tsuru/tsuru/cmd" @@ -36,47 +36,66 @@ func (c *UserCreate) Info() *cmd.Info { } } -func (c *UserCreate) Run(context *cmd.Context, client *cmd.Client) error { - context.RawOutput() - u, err := cmd.GetURL("/users") +func (c *UserCreate) Run(ctx *cmd.Context, client *cmd.Client) error { + ctx.RawOutput() + _, err := cmd.GetURL("/users") if err != nil { return err } - email := context.Args[0] - fmt.Fprint(context.Stdout, "Password: ") - password, err := cmd.PasswordFromReader(context.Stdin) + email := ctx.Args[0] + fmt.Fprint(ctx.Stdout, "Password: ") + password, err := cmd.PasswordFromReader(ctx.Stdin) if err != nil { return err } - fmt.Fprint(context.Stdout, "\nConfirm: ") - confirm, err := cmd.PasswordFromReader(context.Stdin) + fmt.Fprint(ctx.Stdout, "\nConfirm: ") + confirm, err := cmd.PasswordFromReader(ctx.Stdin) if err != nil { return err } - fmt.Fprintln(context.Stdout) + fmt.Fprintln(ctx.Stdout) if password != confirm { return errors.New("Passwords didn't match.") } - v := url.Values{} - v.Set("email", email) - v.Set("password", password) - b := strings.NewReader(v.Encode()) - request, err := http.NewRequest("POST", u, b) + // v := url.Values{} + // v.Set("email", email) + // v.Set("password", password) + //b := strings.NewReader(v.Encode()) + // request, err := http.NewRequest("POST", u, b) + // if err != nil { + // return err + // } + // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + // resp, err := client.Do(request) + // if resp != nil { + // if resp.StatusCode == http.StatusNotFound || + // resp.StatusCode == http.StatusMethodNotAllowed { + // return errors.New("User creation is disabled.") + // } + // } + // if err != nil { + // return err + // } + + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - resp, err := client.Do(request) - if resp != nil { - if resp.StatusCode == http.StatusNotFound || - resp.StatusCode == http.StatusMethodNotAllowed { - return errors.New("User creation is disabled.") - } + response, err := apiClient.UserApi.UserCreate(context.TODO(), tsuru.UserData{ + Email: email, + Password: password, + }) + if err != nil { + return err } + err = cmd.StreamJSONResponse(ctx.Stdout, response) + if err != nil { return err } - fmt.Fprintf(context.Stdout, `User "%s" successfully created!`+"\n", email) + fmt.Fprintf(ctx.Stdout, `User "%s" successfully created!`+"\n", email) return nil } @@ -182,7 +201,7 @@ func (c *TeamCreate) Flags() *gnuflag.FlagSet { } func (c *TeamCreate) Run(ctx *cmd.Context, cli *cmd.Client) error { - apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, }) if err != nil { @@ -230,7 +249,7 @@ func (t *TeamUpdate) Info() *cmd.Info { } func (t *TeamUpdate) Run(ctx *cmd.Context, cli *cmd.Client) error { - apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, }) if err != nil { @@ -258,7 +277,7 @@ func (c *TeamRemove) Run(ctx *cmd.Context, cli *cmd.Client) error { if !c.Confirm(ctx, question) { return nil } - apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, }) if err != nil { @@ -296,7 +315,7 @@ func (c *TeamList) Info() *cmd.Info { } func (c *TeamList) Run(ctx *cmd.Context, cli *cmd.Client) error { - apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, }) if err != nil { @@ -478,27 +497,28 @@ Tags: {{.Tags}} type ChangePassword struct{} -func (c *ChangePassword) Run(context *cmd.Context, client *cmd.Client) error { +func (c *ChangePassword) Run(ctx *cmd.Context, client *cmd.Client) error { + ctx.RawOutput() u, err := cmd.GetURL("/users/password") if err != nil { return err } - fmt.Fprint(context.Stdout, "Current password: ") - old, err := cmd.PasswordFromReader(context.Stdin) + fmt.Fprint(ctx.Stdout, "Current password: ") + old, err := cmd.PasswordFromReader(ctx.Stdin) if err != nil { return err } - fmt.Fprint(context.Stdout, "\nNew password: ") - new, err := cmd.PasswordFromReader(context.Stdin) + fmt.Fprint(ctx.Stdout, "\nNew password: ") + new, err := cmd.PasswordFromReader(ctx.Stdin) if err != nil { return err } - fmt.Fprint(context.Stdout, "\nConfirm: ") - confirm, err := cmd.PasswordFromReader(context.Stdin) + fmt.Fprint(ctx.Stdout, "\nConfirm: ") + confirm, err := cmd.PasswordFromReader(ctx.Stdin) if err != nil { return err } - fmt.Fprintln(context.Stdout) + fmt.Fprintln(ctx.Stdout) v := url.Values{} v.Set("old", old) v.Set("new", new) @@ -512,7 +532,23 @@ func (c *ChangePassword) Run(context *cmd.Context, client *cmd.Client) error { if err != nil { return err } - fmt.Fprintln(context.Stdout, "Password successfully updated!") + + // apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + // HTTPClient: client.HTTPClient, + // }) + // if err != nil { + // return err + // } + // response, err := apiClient.UserApi.ChangePassword() + // if err != nil { + // return err + // } + // err = cmd.StreamJSONResponse(ctx.Stdout, response) + + if err != nil { + return err + } + fmt.Fprintln(ctx.Stdout, "Password successfully updated!") return nil } @@ -718,7 +754,7 @@ func (c *ListUsers) Run(ctx *cmd.Context, cli *cmd.Client) error { return errors.New("You should provide a role to filter by context value.") } - apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, }) if err != nil { @@ -779,7 +815,7 @@ func (UserInfo) Info() *cmd.Info { } func (UserInfo) Run(ctx *cmd.Context, cli *cmd.Client) error { - apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, }) if err != nil { diff --git a/tsuru/client/auth_test.go b/tsuru/client/auth_test.go index 9dba791e4..42747e75e 100644 --- a/tsuru/client/auth_test.go +++ b/tsuru/client/auth_test.go @@ -410,11 +410,20 @@ func (s *S) TestUserCreateShouldNotDependOnTsuruTokenFile(c *check.C) { Status: http.StatusCreated, }, CondFunc: func(r *http.Request) bool { - contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" - password := r.FormValue("password") == "foo123" - email := r.FormValue("email") == "foo@foo.com" + contentType := r.Header.Get("Content-Type") == "application/json" + // password := r.FormValue("password") == "foo123" + // email := r.FormValue("email") == "foo@foo.com" url := r.URL.Path == "/1.0/users" - return contentType && password && email && url + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + var createResult map[string]interface{} + err = json.Unmarshal(data, &createResult) + c.Assert(err, check.IsNil) + c.Assert(createResult, check.DeepEquals, map[string]interface{}{ + "password": "foo123", + "email": "foo@foo.com", + }) + return contentType && url }, } client := cmd.NewClient(&http.Client{Transport: &transport}, nil, manager) @@ -487,7 +496,8 @@ func (s *S) TestUserCreateNotFound(c *check.C) { command := UserCreate{} err := command.Run(&context, client) c.Assert(err, check.NotNil) - c.Assert(err.Error(), check.Equals, "User creation is disabled.") + c.Assert(err.Error(), check.Equals, "404 Not Found: Not found") + // c.Assert(err.Error(), check.Equals, "User creation is disabled.") } func (s *S) TestUserCreateMethodNotAllowed(c *check.C) { @@ -507,7 +517,8 @@ func (s *S) TestUserCreateMethodNotAllowed(c *check.C) { command := UserCreate{} err := command.Run(&context, client) c.Assert(err, check.NotNil) - c.Assert(err.Error(), check.Equals, "User creation is disabled.") + c.Assert(err.Error(), check.Equals, "405 Method Not Allowed: Not found") + // c.Assert(err.Error(), check.Equals, "User creation is disabled.") } func (s *S) TestUserCreateInfo(c *check.C) { @@ -627,6 +638,16 @@ func (s *S) TestChangePassword(c *check.C) { contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" url := strings.HasSuffix(r.URL.Path, "/users/password") called = true + // data, err := ioutil.ReadAll(r.Body) + // c.Assert(err, check.IsNil) + // var changePassResult map[string]interface{} + // err = json.Unmarshal(data, &changePassResult) + // c.Assert(err, check.IsNil) + // c.Assert(changePassResult, check.DeepEquals, map[string]interface{}{ + // "old": "gopher", + // "new": "bbrothers", + // "confirm": "bbrothers", + // }) return method && url && contentType && old && new && confirm }, } diff --git a/tsuru/client/env.go b/tsuru/client/env.go index f7abd6eb0..ffeb8dd42 100644 --- a/tsuru/client/env.go +++ b/tsuru/client/env.go @@ -5,6 +5,7 @@ package client import ( + "context" "encoding/json" "errors" "fmt" @@ -15,11 +16,11 @@ import ( "strconv" "strings" - "github.com/ajg/form" "github.com/tsuru/gnuflag" + tsuruClient "github.com/tsuru/go-tsuruclient/pkg/client" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" tsuruAPIApp "github.com/tsuru/tsuru/app" "github.com/tsuru/tsuru/cmd" - apiTypes "github.com/tsuru/tsuru/types/api" ) const EnvSetValidationMessage = `You must specify environment variables in the form "NAME=value". @@ -86,47 +87,62 @@ func (c *EnvSet) Info() *cmd.Info { } } -func (c *EnvSet) Run(context *cmd.Context, client *cmd.Client) error { - context.RawOutput() +func (c *EnvSet) Run(ctx *cmd.Context, client *cmd.Client) error { + ctx.RawOutput() appName, err := c.AppName() if err != nil { return err } - if len(context.Args) < 1 { + if len(ctx.Args) < 1 { return errors.New(EnvSetValidationMessage) } - envs := make([]apiTypes.Env, len(context.Args)) - for i := range context.Args { - parts := strings.SplitN(context.Args[i], "=", 2) + envs := make([]tsuru.Env, len(ctx.Args)) + for i := range ctx.Args { + parts := strings.SplitN(ctx.Args[i], "=", 2) if len(parts) != 2 { return errors.New(EnvSetValidationMessage) } - envs[i] = apiTypes.Env{Name: parts[0], Value: parts[1]} + envs[i] = tsuru.Env{Name: parts[0], Value: parts[1]} } - e := apiTypes.Envs{ - Envs: envs, - NoRestart: c.noRestart, - Private: c.private, - } - url, err := cmd.GetURL(fmt.Sprintf("/apps/%s/env", appName)) - if err != nil { - return err - } - v, err := form.EncodeToValues(&e) - if err != nil { - return err - } - request, err := http.NewRequest("POST", url, strings.NewReader(v.Encode())) + // e := apiTypes.Envs{ + // Envs: envs, + // NoRestart: c.noRestart, + // Private: c.private, + // } + + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - response, err := client.Do(request) + response, err := apiClient.AppApi.EnvSet(context.TODO(), appName, tsuru.EnvSetData{ + Envs: envs, + Norestart: c.noRestart, + Private: c.private, + }) if err != nil { return err } - return cmd.StreamJSONResponse(context.Stdout, response) + // url, err := cmd.GetURL(fmt.Sprintf("/apps/%s/env", appName)) + // if err != nil { + // return err + // } + // v, err := form.EncodeToValues(&e) + // if err != nil { + // return err + // } + // request, err := http.NewRequest("POST", url, strings.NewReader(v.Encode())) + // if err != nil { + // return err + // } + // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + // response, err := client.Do(request) + // if err != nil { + // return err + // } + return cmd.StreamJSONResponse(ctx.Stdout, response) } func (c *EnvSet) Flags() *gnuflag.FlagSet { diff --git a/tsuru/client/env_test.go b/tsuru/client/env_test.go index 0cd3b51cb..a2e64e073 100644 --- a/tsuru/client/env_test.go +++ b/tsuru/client/env_test.go @@ -7,14 +7,14 @@ package client import ( "bytes" "encoding/json" + "io/ioutil" "net/http" "strings" - "github.com/ajg/form" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tsuru/cmd" "github.com/tsuru/tsuru/cmd/cmdtest" "github.com/tsuru/tsuru/io" - apiTypes "github.com/tsuru/tsuru/types/api" "gopkg.in/check.v1" ) @@ -149,18 +149,24 @@ func (s *S) TestEnvSetRun(c *check.C) { CondFunc: func(req *http.Request) bool { err = req.ParseForm() c.Assert(err, check.IsNil) - var e apiTypes.Envs - dec := form.NewDecoder(nil) - dec.IgnoreUnknownKeys(true) - dec.UseJSONTags(false) - err = dec.DecodeValues(&e, req.Form) + //var e tsuru.Env + // dec := form.NewDecoder(nil) + // dec.IgnoreUnknownKeys(true) + // dec.UseJSONTags(false) c.Assert(err, check.IsNil) + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + var envResult map[string]interface{} + err = json.Unmarshal(data, &envResult) + c.Assert(err, check.IsNil) + c.Assert(envResult, check.DeepEquals, map[string]interface{}{"envs": []interface{}{map[string]interface{}{"name": "DATABASE_HOST", + "value": "somehost"}}}) path := strings.HasSuffix(req.URL.Path, "/apps/someapp/env") method := req.Method == "POST" - contentType := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" - name := e.Envs[0].Name == "DATABASE_HOST" - value := e.Envs[0].Value == "somehost" - return path && method && contentType && name && value + contentType := req.Header.Get("Content-Type") == "application/json" + //name := e.Env[0].Name == "DATABASE_HOST" + //value := e.Env[0].Value == "somehost" + return path && method && contentType }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) @@ -209,26 +215,30 @@ variable 2`}, Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { private := false - want := []apiTypes.Env{ - {Name: "LINE1", Value: `multiline -variable 1`, Alias: "", Private: &private}, - {Name: "LINE2", Value: `multiline -variable 2`, Alias: "", Private: &private}, + want := []tsuru.Env{ + {Name: "LINE1", Value: "multiline\nvariable 1", Alias: "", Private: private}, + {Name: "LINE2", Value: "multiline\nvariable 2", Alias: "", Private: private}, } err = req.ParseForm() + // c.Assert(err, check.IsNil) + var e tsuru.EnvSetData + // dec := form.NewDecoder(nil) + // dec.IgnoreUnknownKeys(true) + // dec.UseJSONTags(false) + // err = dec.DecodeValues(&e, req.Form) + // c.Assert(err, check.IsNil) + data, err := ioutil.ReadAll(req.Body) c.Assert(err, check.IsNil) - var e apiTypes.Envs - dec := form.NewDecoder(nil) - dec.IgnoreUnknownKeys(true) - dec.UseJSONTags(false) - err = dec.DecodeValues(&e, req.Form) + ///var envResult map[string]interface{} + err = json.Unmarshal(data, &e) c.Assert(err, check.IsNil) c.Assert(e.Envs, check.DeepEquals, want) + //c.Assert(e.Envs, check.DeepEquals, want) private = !e.Private - noRestart := !e.NoRestart + noRestart := !e.Norestart path := strings.HasSuffix(req.URL.Path, "/apps/someapp/env") method := req.Method == "POST" - contentType := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" + contentType := req.Header.Get("Content-Type") == "application/json" return path && contentType && method && private && noRestart }, } @@ -263,29 +273,36 @@ func (s *S) TestEnvSetValues(c *check.C) { Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { private := false - want := []apiTypes.Env{ - {Name: "DATABASE_HOST", Value: "some host", Alias: "", Private: &private}, - {Name: "DATABASE_USER", Value: "root", Alias: "", Private: &private}, - {Name: "DATABASE_PASSWORD", Value: ".1234..abc", Alias: "", Private: &private}, - {Name: "http_proxy", Value: "http://myproxy.com:3128/", Alias: "", Private: &private}, - {Name: "VALUE_WITH_EQUAL_SIGN", Value: "http://wholikesquerystrings.me/?tsuru=awesome", Alias: "", Private: &private}, - {Name: "BASE64_STRING", Value: "t5urur0ck5==", Alias: "", Private: &private}, - {Name: "SOME_PASSWORD", Value: "js87$%32??", Alias: "", Private: &private}, + want := []tsuru.Env{ + {Name: "DATABASE_HOST", Value: "some host", Alias: "", Private: private}, + {Name: "DATABASE_USER", Value: "root", Alias: "", Private: private}, + {Name: "DATABASE_PASSWORD", Value: ".1234..abc", Alias: "", Private: private}, + {Name: "http_proxy", Value: "http://myproxy.com:3128/", Alias: "", Private: private}, + {Name: "VALUE_WITH_EQUAL_SIGN", Value: "http://wholikesquerystrings.me/?tsuru=awesome", Alias: "", Private: private}, + {Name: "BASE64_STRING", Value: "t5urur0ck5==", Alias: "", Private: private}, + {Name: "SOME_PASSWORD", Value: "js87$%32??", Alias: "", Private: private}, } err = req.ParseForm() c.Assert(err, check.IsNil) - var e apiTypes.Envs - dec := form.NewDecoder(nil) - dec.IgnoreUnknownKeys(true) - dec.UseJSONTags(false) - err = dec.DecodeValues(&e, req.Form) + var e tsuru.EnvSetData + //dec := form.NewDecoder(nil) + //dec.IgnoreUnknownKeys(true) + //dec.UseJSONTags(false) + ///err = dec.DecodeValues(&e, req.Form) + c.Assert(err, check.IsNil) + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + //var envResult map[string]interface{} + err = json.Unmarshal(data, &e) c.Assert(err, check.IsNil) c.Assert(e.Envs, check.DeepEquals, want) + //c.Assert(err, check.IsNil) + //c.Assert(e.Envs, check.DeepEquals, want) private = !e.Private - noRestart := !e.NoRestart + noRestart := !e.Norestart path := strings.HasSuffix(req.URL.Path, "/apps/someapp/env") method := req.Method == "POST" - contentType := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" + contentType := req.Header.Get("Content-Type") == "application/json" return path && contentType && method && private && noRestart }, } @@ -320,28 +337,31 @@ func (s *S) TestEnvSetValuesAndPrivateAndNoRestart(c *check.C) { Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { private := false - want := []apiTypes.Env{ - {Name: "DATABASE_HOST", Value: "some host", Alias: "", Private: &private}, - {Name: "DATABASE_USER", Value: "root", Alias: "", Private: &private}, - {Name: "DATABASE_PASSWORD", Value: ".1234..abc", Alias: "", Private: &private}, - {Name: "http_proxy", Value: "http://myproxy.com:3128/", Alias: "", Private: &private}, - {Name: "VALUE_WITH_EQUAL_SIGN", Value: "http://wholikesquerystrings.me/?tsuru=awesome", Private: &private}, - {Name: "BASE64_STRING", Value: "t5urur0ck5==", Alias: "", Private: &private}, + want := []tsuru.Env{ + {Name: "DATABASE_HOST", Value: "some host", Alias: "", Private: private}, + {Name: "DATABASE_USER", Value: "root", Alias: "", Private: private}, + {Name: "DATABASE_PASSWORD", Value: ".1234..abc", Alias: "", Private: private}, + {Name: "http_proxy", Value: "http://myproxy.com:3128/", Alias: "", Private: private}, + {Name: "VALUE_WITH_EQUAL_SIGN", Value: "http://wholikesquerystrings.me/?tsuru=awesome", Private: private}, + {Name: "BASE64_STRING", Value: "t5urur0ck5==", Alias: "", Private: private}, } err = req.ParseForm() c.Assert(err, check.IsNil) - var e apiTypes.Envs - dec := form.NewDecoder(nil) - dec.IgnoreUnknownKeys(true) - dec.UseJSONTags(false) - err = dec.DecodeValues(&e, req.Form) + var e tsuru.EnvSetData + // dec := form.NewDecoder(nil) + // dec.IgnoreUnknownKeys(true) + // dec.UseJSONTags(false) + // err = dec.DecodeValues(&e, req.Form) + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + err = json.Unmarshal(data, &e) c.Assert(err, check.IsNil) c.Assert(e.Envs, check.DeepEquals, want) private = e.Private - noRestart := e.NoRestart + noRestart := e.Norestart path := strings.HasSuffix(req.URL.Path, "/apps/someapp/env") method := req.Method == "POST" - contentType := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" + contentType := req.Header.Get("Content-Type") == "application/json" return path && contentType && method && private && noRestart }, } diff --git a/tsuru/client/services.go b/tsuru/client/services.go index f200dbb6e..54f4be49f 100644 --- a/tsuru/client/services.go +++ b/tsuru/client/services.go @@ -283,22 +283,36 @@ func (sb *ServiceInstanceBind) Run(ctx *cmd.Context, client *cmd.Client) error { } serviceName := ctx.Args[0] instanceName := ctx.Args[1] - u, err := cmd.GetURL("/services/" + serviceName + "/instances/" + instanceName + "/" + appName) - if err != nil { - return err - } - v := url.Values{} - v.Set("noRestart", strconv.FormatBool(sb.noRestart)) - request, err := http.NewRequest("PUT", u, strings.NewReader(v.Encode())) + // u, err := cmd.GetURL("/services/" + serviceName + "/instances/" + instanceName + "/" + appName) + // if err != nil { + // return err + // } + // v := url.Values{} + // v.Set("noRestart", strconv.FormatBool(sb.noRestart)) + // request, err := http.NewRequest("PUT", u, strings.NewReader(v.Encode())) + // if err != nil { + // return err + // } + // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + // resp, err := client.Do(request) + // if err != nil { + // return err + // } + var serviceBind tsuru.ServiceInstanceBind + + serviceBind.NoRestart = sb.noRestart + + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - resp, err := client.Do(request) + response, err := apiClient.ServiceApi.ServiceInstanceBind(context.TODO(), serviceName, instanceName, appName, serviceBind) if err != nil { return err } - return cmd.StreamJSONResponse(ctx.Stdout, resp) + return cmd.StreamJSONResponse(ctx.Stdout, response) } func (sb *ServiceInstanceBind) Info() *cmd.Info { diff --git a/tsuru/client/services_test.go b/tsuru/client/services_test.go index b90610164..dfa096656 100644 --- a/tsuru/client/services_test.go +++ b/tsuru/client/services_test.go @@ -250,8 +250,15 @@ func (s *S) TestServiceInstanceBind(c *check.C) { called = true method := req.Method == "PUT" path := strings.HasSuffix(req.URL.Path, "/services/mysql/instances/my-mysql/g1") - noRestart := req.FormValue("noRestart") == "true" - return method && path && noRestart + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + var bindResult map[string]interface{} + err = json.Unmarshal(data, &bindResult) + c.Assert(err, check.IsNil) + c.Assert(bindResult, check.DeepEquals, map[string]interface{}{ + "noRestart": true, + }) + return method && path }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) @@ -279,8 +286,13 @@ func (s *S) TestServiceInstanceBindWithoutEnvironmentVariables(c *check.C) { CondFunc: func(req *http.Request) bool { method := req.Method == "PUT" path := strings.HasSuffix(req.URL.Path, "/services/mysql/instances/my-mysql/g1") - noRestart := req.FormValue("noRestart") == "false" - return method && path && noRestart + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + var bindResult map[string]interface{} + err = json.Unmarshal(data, &bindResult) + c.Assert(err, check.IsNil) + c.Assert(bindResult, check.DeepEquals, map[string]interface{}{}) + return method && path }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) @@ -304,7 +316,7 @@ func (s *S) TestServiceInstanceBindWithRequestFailure(c *check.C) { command.Flags().Parse(true, []string{"-a", "g1"}) err := command.Run(&ctx, client) c.Assert(err, check.NotNil) - c.Assert(err.Error(), check.Equals, trans.Message) + c.Assert(err.Error(), check.Equals, "403 Forbidden: "+trans.Message) } func (s *S) TestServiceInstanceBindInfo(c *check.C) { diff --git a/tsuru/client/volume.go b/tsuru/client/volume.go index 130a44643..4513b5dc3 100644 --- a/tsuru/client/volume.go +++ b/tsuru/client/volume.go @@ -5,6 +5,7 @@ package client import ( + "context" "encoding/json" "fmt" "io/ioutil" @@ -14,6 +15,8 @@ import ( "github.com/ajg/form" "github.com/tsuru/gnuflag" + tsuruClient "github.com/tsuru/go-tsuruclient/pkg/client" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tablecli" "github.com/tsuru/tsuru/cmd" volumeTypes "github.com/tsuru/tsuru/types/volume" @@ -53,32 +56,54 @@ func (c *VolumeCreate) Flags() *gnuflag.FlagSet { } func (c *VolumeCreate) Run(ctx *cmd.Context, client *cmd.Client) error { + ctx.RawOutput() volumeName, planName := ctx.Args[0], ctx.Args[1] - vol := volumeTypes.Volume{ + // vol := volumeTypes.Volume{ + // Name: volumeName, + // Plan: volumeTypes.VolumePlan{Name: planName}, + // Pool: c.pool, + // TeamOwner: c.team, + // Opts: map[string]string(c.opt), + // } + // val, err := form.EncodeToValues(vol) + // if err != nil { + // return err + // } + // body := strings.NewReader(val.Encode()) + // u, err := cmd.GetURLVersion("1.4", "/volumes") + // if err != nil { + // return err + // } + // request, err := http.NewRequest("POST", u, body) + // if err != nil { + // return err + // } + // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + // _, err = client.Do(request) + // if err != nil { + // return err + // } + + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) + if err != nil { + return err + } + response, err := apiClient.VolumeApi.VolumeCreate(context.TODO(), tsuru.Volume{ Name: volumeName, - Plan: volumeTypes.VolumePlan{Name: planName}, + Plan: tsuru.VolumePlan{Name: planName}, Pool: c.pool, TeamOwner: c.team, Opts: map[string]string(c.opt), - } - val, err := form.EncodeToValues(vol) - if err != nil { - return err - } - body := strings.NewReader(val.Encode()) - u, err := cmd.GetURLVersion("1.4", "/volumes") - if err != nil { - return err - } - request, err := http.NewRequest("POST", u, body) - if err != nil { - return err - } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + }) + if err != nil { return err } + + err = cmd.StreamJSONResponse(ctx.Stdout, response) + fmt.Fprint(ctx.Stdout, "Volume successfully created.\n") return nil } @@ -417,36 +442,46 @@ func (c *VolumeBind) Run(ctx *cmd.Context, client *cmd.Client) error { if err != nil { return err } - bind := struct { - App string - MountPoint string - ReadOnly bool - NoRestart bool - }{ + // bind := struct { + // App string + // MountPoint string + // ReadOnly bool + // NoRestart bool + // }{ + bind := tsuru.VolumeBindData{ App: appName, - MountPoint: ctx.Args[1], - ReadOnly: c.readOnly, - NoRestart: c.noRestart, - } - val, err := form.EncodeToValues(bind) - if err != nil { - return err - } - body := strings.NewReader(val.Encode()) - u, err := cmd.GetURLVersion("1.4", fmt.Sprintf("/volumes/%s/bind", volumeName)) - if err != nil { - return err - } - request, err := http.NewRequest("POST", u, body) - if err != nil { - return err - } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - resp, err := client.Do(request) - if err != nil { - return err - } - err = cmd.StreamJSONResponse(ctx.Stdout, resp) + Mountpoint: ctx.Args[1], + Readonly: c.readOnly, + Norestart: c.noRestart, + } + // val, err := form.EncodeToValues(bind) + // if err != nil { + // return err + // } + // body := strings.NewReader(val.Encode()) + // u, err := cmd.GetURLVersion("1.4", fmt.Sprintf("/volumes/%s/bind", volumeName)) + // if err != nil { + // return err + // } + // request, err := http.NewRequest("POST", u, body) + // if err != nil { + // return err + // } + // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + // resp, err := client.Do(request) + // if err != nil { + // return err + // } + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) + + response, err := apiClient.VolumeApi.VolumeBind(context.TODO(), volumeName, bind) + if err != nil { + return err + } + + err = cmd.StreamJSONResponse(ctx.Stdout, response) if err != nil { return err } diff --git a/tsuru/client/volume_test.go b/tsuru/client/volume_test.go index b56a5f318..0ea8b2b41 100644 --- a/tsuru/client/volume_test.go +++ b/tsuru/client/volume_test.go @@ -6,10 +6,13 @@ package client import ( "bytes" + "encoding/json" + "io/ioutil" "net/http" "strings" "github.com/ajg/form" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tsuru/cmd" "github.com/tsuru/tsuru/cmd/cmdtest" volumeTypes "github.com/tsuru/tsuru/types/volume" @@ -213,16 +216,19 @@ func (s *S) TestVolumeCreate(c *check.C) { Transport: cmdtest.Transport{Message: "", Status: http.StatusCreated}, CondFunc: func(r *http.Request) bool { r.ParseForm() - dec := form.NewDecoder(nil) - dec.IgnoreCase(true) - dec.IgnoreUnknownKeys(true) - dec.UseJSONTags(false) - var vol volumeTypes.Volume - err := dec.DecodeValues(&vol, r.Form) + // dec := form.NewDecoder(nil) + // dec.IgnoreCase(true) + // dec.IgnoreUnknownKeys(true) + // dec.UseJSONTags(false) + var vol tsuru.Volume + //err := dec.DecodeValues(&vol, r.Form) + data, err := ioutil.ReadAll(r.Body) c.Assert(err, check.IsNil) - c.Assert(vol, check.DeepEquals, volumeTypes.Volume{ + err = json.Unmarshal(data, &vol) + c.Assert(err, check.IsNil) + c.Assert(vol, check.DeepEquals, tsuru.Volume{ Name: "vol1", - Plan: volumeTypes.VolumePlan{Name: "plan1"}, + Plan: tsuru.VolumePlan{Name: "plan1"}, TeamOwner: "team1", Pool: "pool1", Opts: map[string]string{"a": "1", "b": "2"}, @@ -307,9 +313,20 @@ func (s *S) TestVolumeBind(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - r.ParseForm() - c.Assert(r.FormValue("App"), check.Equals, "myapp") - c.Assert(r.FormValue("MountPoint"), check.Equals, "/mnt") + // r.ParseForm() + // c.Assert(r.FormValue("App"), check.Equals, "myapp") + // c.Assert(r.FormValue("MountPoint"), check.Equals, "/mnt") + var vol tsuru.VolumeBindData + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + err = json.Unmarshal(data, &vol) + c.Assert(err, check.IsNil) + c.Assert(vol, check.DeepEquals, tsuru.VolumeBindData{ + App: "myapp", + Mountpoint: "/mnt", + Norestart: false, + Readonly: false, + }) return strings.HasSuffix(r.URL.Path, "/volumes/vol1/bind") && r.Method == "POST" }, } @@ -332,10 +349,21 @@ func (s *S) TestVolumeBindNoRestart(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - r.ParseForm() - c.Assert(r.FormValue("App"), check.Equals, "myapp") - c.Assert(r.FormValue("MountPoint"), check.Equals, "/mnt") - c.Assert(r.FormValue("NoRestart"), check.Equals, "true") + // r.ParseForm() + // c.Assert(r.FormValue("App"), check.Equals, "myapp") + // c.Assert(r.FormValue("MountPoint"), check.Equals, "/mnt") + // c.Assert(r.FormValue("NoRestart"), check.Equals, "true") + var vol tsuru.VolumeBindData + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + err = json.Unmarshal(data, &vol) + c.Assert(err, check.IsNil) + c.Assert(vol, check.DeepEquals, tsuru.VolumeBindData{ + App: "myapp", + Mountpoint: "/mnt", + Norestart: true, + Readonly: false, + }) return strings.HasSuffix(r.URL.Path, "/volumes/vol1/bind") && r.Method == "POST" }, } @@ -358,10 +386,21 @@ func (s *S) TestVolumeBindRO(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - r.ParseForm() - c.Assert(r.FormValue("App"), check.Equals, "myapp") - c.Assert(r.FormValue("MountPoint"), check.Equals, "/mnt") - c.Assert(r.FormValue("ReadOnly"), check.Equals, "true") + // r.ParseForm() + // c.Assert(r.FormValue("App"), check.Equals, "myapp") + // c.Assert(r.FormValue("MountPoint"), check.Equals, "/mnt") + // c.Assert(r.FormValue("ReadOnly"), check.Equals, "true") + var vol tsuru.VolumeBindData + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + err = json.Unmarshal(data, &vol) + c.Assert(err, check.IsNil) + c.Assert(vol, check.DeepEquals, tsuru.VolumeBindData{ + App: "myapp", + Mountpoint: "/mnt", + Norestart: false, + Readonly: true, + }) return strings.HasSuffix(r.URL.Path, "/volumes/vol1/bind") && r.Method == "POST" }, } From f1631eaa8d75057f71c6f0b4ca97db0901ac24ee Mon Sep 17 00:00:00 2001 From: CarlosRoGuerra Date: Tue, 22 Jun 2021 16:27:32 -0300 Subject: [PATCH 04/20] change: form to json --- tsuru/client/event.go | 38 +++++++++---- tsuru/client/event_test.go | 11 +++- tsuru/client/router.go | 109 +++++++++++++++++++++++++----------- tsuru/client/router_test.go | 35 ++++++------ 4 files changed, 127 insertions(+), 66 deletions(-) diff --git a/tsuru/client/event.go b/tsuru/client/event.go index 8bf90f528..2f341861d 100644 --- a/tsuru/client/event.go +++ b/tsuru/client/event.go @@ -5,6 +5,7 @@ package client import ( + "context" "encoding/json" "fmt" "io/ioutil" @@ -18,6 +19,8 @@ import ( "github.com/ajg/form" "github.com/ghodss/yaml" "github.com/tsuru/gnuflag" + "github.com/tsuru/go-tsuruclient/pkg/client" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tablecli" "github.com/tsuru/tsuru-client/tsuru/formatter" "github.com/tsuru/tsuru/cmd" @@ -351,25 +354,36 @@ func (c *EventCancel) Info() *cmd.Info { } } -func (c *EventCancel) Run(context *cmd.Context, client *cmd.Client) error { - if !c.Confirm(context, "Are you sure you want to cancel this event?") { +func (c *EventCancel) Run(ctx *cmd.Context, cli *cmd.Client) error { + if !c.Confirm(ctx, "Are you sure you want to cancel this event?") { return nil } - u, err := cmd.GetURLVersion("1.1", fmt.Sprintf("/events/%s/cancel", context.Args[0])) - if err != nil { - return err - } - v := url.Values{} - v.Set("reason", strings.Join(context.Args[1:], " ")) - request, err := http.NewRequest("POST", u, strings.NewReader(v.Encode())) + // u, err := cmd.GetURLVersion("1.1", fmt.Sprintf("/events/%s/cancel", ctx.Args[0])) + // if err != nil { + // return err + // } + // v := url.Values{} + // v.Set("reason", strings.Join(ctx.Args[1:], " ")) + // request, err := http.NewRequest("POST", u, strings.NewReader(v.Encode())) + // if err != nil { + // return err + // } + // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + //_, err = client.Do(request) + + apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: cli.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + _, err = apiClient.EventApi.EventCancel(context.TODO(), ctx.Args[0], tsuru.EventCancelArgs{ + Reason: strings.Join(ctx.Args[1:], " "), + }) + if err != nil { return err } - fmt.Fprintln(context.Stdout, "Cancellation successfully requested.") + fmt.Fprintln(ctx.Stdout, "Cancellation successfully requested.") return nil } diff --git a/tsuru/client/event_test.go b/tsuru/client/event_test.go index 0c0bc09ab..3168c4ade 100644 --- a/tsuru/client/event_test.go +++ b/tsuru/client/event_test.go @@ -6,10 +6,13 @@ package client import ( "bytes" + "encoding/json" "fmt" + "io/ioutil" "net/http" "os" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tsuru/cmd" "github.com/tsuru/tsuru/cmd/cmdtest" "gopkg.in/check.v1" @@ -554,7 +557,13 @@ func (s *S) TestEventCancel(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: runningEvt, Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { - c.Assert(req.FormValue("reason"), check.Equals, "my reason") + var eventCancel tsuru.EventCancelArgs + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + err = json.Unmarshal(data, &eventCancel) + c.Assert(err, check.IsNil) + c.Assert(eventCancel, check.Equals, tsuru.EventCancelArgs{Reason: "my reason"}) + //c.Assert(req.FormValue("reason"), check.Equals, "my reason") return req.URL.Path == "/1.1/events/998e3908413daf5fd9891aac/cancel" && req.Method == "POST" }, } diff --git a/tsuru/client/router.go b/tsuru/client/router.go index 3204d40a1..a32aad5f2 100644 --- a/tsuru/client/router.go +++ b/tsuru/client/router.go @@ -13,7 +13,6 @@ import ( "sort" "strings" - "github.com/ajg/form" "github.com/pkg/errors" "github.com/tsuru/gnuflag" "github.com/tsuru/go-tsuruclient/pkg/client" @@ -348,33 +347,54 @@ func (c *AppRoutersAdd) Flags() *gnuflag.FlagSet { return c.fs } -func (c *AppRoutersAdd) Run(context *cmd.Context, client *cmd.Client) error { +func (c *AppRoutersAdd) Run(ctx *cmd.Context, cli *cmd.Client) error { + ctx.RawOutput() appName, err := c.AppName() if err != nil { return err } - url, err := cmd.GetURLVersion("1.5", fmt.Sprintf("/apps/%s/routers", appName)) - if err != nil { - return err - } - r := appTypes.AppRouter{ - Name: context.Args[0], - Opts: c.opts, + // url, err := cmd.GetURLVersion("1.5", fmt.Sprintf("/apps/%s/routers", appName)) + // if err != nil { + // return err + // } + // r := appTypes.AppRouter{ + // Name: ctx.Args[0], + // Opts: c.opts, + // } + // val, err := form.EncodeToValues(r) + // if err != nil { + // return err + // } + // request, err := http.NewRequest("POST", url, strings.NewReader(val.Encode())) + // if err != nil { + // return err + // } + opts := make(map[string]interface{}, len(c.opts)) + for k, v := range c.opts { + opts[k] = v } - val, err := form.EncodeToValues(r) - if err != nil { - return err - } - request, err := http.NewRequest("POST", url, strings.NewReader(val.Encode())) + apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: cli.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + _, err = apiClient.AppApi.AppRouterAdd(context.TODO(), appName, tsuru.AppRouter{ + Name: ctx.Args[0], + Opts: opts, + }) + if err != nil { return err } - fmt.Fprintln(context.Stdout, "Router successfully added.") + + // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + // _, err = client.Do(request) + // if err != nil { + // return err + // } + fmt.Fprintln(ctx.Stdout, "Router successfully added.") return nil } @@ -404,34 +424,55 @@ func (c *AppRoutersUpdate) Flags() *gnuflag.FlagSet { return c.fs } -func (c *AppRoutersUpdate) Run(context *cmd.Context, client *cmd.Client) error { +func (c *AppRoutersUpdate) Run(ctx *cmd.Context, cli *cmd.Client) error { + ctx.RawOutput() appName, err := c.AppName() if err != nil { return err } - routerName := context.Args[0] - url, err := cmd.GetURLVersion("1.5", fmt.Sprintf("/apps/%s/routers/%s", appName, routerName)) - if err != nil { - return err - } - r := appTypes.AppRouter{ - Name: routerName, - Opts: c.opts, + routerName := ctx.Args[0] + // url, err := cmd.GetURLVersion("1.5", fmt.Sprintf("/apps/%s/routers/%s", appName, routerName)) + // if err != nil { + // return err + // } + // r := appTypes.AppRouter{ + // Name: routerName, + // Opts: c.opts, + // } + // val, err := form.EncodeToValues(r) + // if err != nil { + // return err + // } + // request, err := http.NewRequest("PUT", url, strings.NewReader(val.Encode())) + // if err != nil { + // return err + // } + // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + // _, err = client.Do(request) + // if err != nil { + // return err + // } + + opts := make(map[string]interface{}, len(c.opts)) + for k, v := range c.opts { + opts[k] = v } - val, err := form.EncodeToValues(r) - if err != nil { - return err - } - request, err := http.NewRequest("PUT", url, strings.NewReader(val.Encode())) + apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: cli.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + _, err = apiClient.AppApi.AppRouterUpdate(context.TODO(), appName, routerName, tsuru.AppRouter{ + Name: ctx.Args[0], + Opts: opts, + }) + if err != nil { return err } - fmt.Fprintln(context.Stdout, "Router successfully updated.") + + fmt.Fprintln(ctx.Stdout, "Router successfully updated.") return nil } diff --git a/tsuru/client/router_test.go b/tsuru/client/router_test.go index 10bd9282a..42b47362c 100644 --- a/tsuru/client/router_test.go +++ b/tsuru/client/router_test.go @@ -9,7 +9,6 @@ import ( "encoding/json" "io/ioutil" "net/http" - "net/url" "strings" "github.com/tsuru/go-tsuruclient/pkg/tsuru" @@ -129,15 +128,14 @@ func (s *S) TestAppRoutersAddRun(c *check.C) { CondFunc: func(req *http.Request) bool { err := req.ParseForm() c.Assert(err, check.IsNil) - c.Assert(req.Form, check.DeepEquals, url.Values{ - "Opts.a": []string{"b"}, - "Opts.x": []string{"y"}, - "Name": []string{"myrouter"}, - "Address": []string{""}, - "Addresses": []string{""}, - "Type": []string{""}, - "Status": []string{""}, - "StatusDetail": []string{""}, + var routerAdd tsuru.AppRouter + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + err = json.Unmarshal(data, &routerAdd) + c.Assert(err, check.IsNil) + c.Assert(routerAdd, check.DeepEquals, tsuru.AppRouter{ + Opts: map[string]interface{}{"a": "b", "x": "y"}, + Name: "myrouter", }) return strings.HasSuffix(req.URL.Path, "/1.5/apps/myapp/routers") && req.Method == "POST" }, @@ -163,15 +161,14 @@ func (s *S) TestAppRoutersUpdateRun(c *check.C) { CondFunc: func(req *http.Request) bool { err := req.ParseForm() c.Assert(err, check.IsNil) - c.Assert(req.Form, check.DeepEquals, url.Values{ - "Opts.a": []string{"b"}, - "Opts.x": []string{"y"}, - "Name": []string{"myrouter"}, - "Address": []string{""}, - "Addresses": []string{""}, - "Type": []string{""}, - "Status": []string{""}, - "StatusDetail": []string{""}, + var routerUpdt tsuru.AppRouter + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + err = json.Unmarshal(data, &routerUpdt) + c.Assert(err, check.IsNil) + c.Assert(routerUpdt, check.DeepEquals, tsuru.AppRouter{ + Opts: map[string]interface{}{"a": "b", "x": "y"}, + Name: "myrouter", }) return strings.HasSuffix(req.URL.Path, "/1.5/apps/myapp/routers/myrouter") && req.Method == "PUT" }, From 44a5f3e99f9cb72b44c72bb83973f42a3c9895e8 Mon Sep 17 00:00:00 2001 From: CarlosRoGuerra Date: Thu, 24 Jun 2021 14:50:09 -0300 Subject: [PATCH 05/20] change: form to json --- tsuru/client/apps.go | 158 +++++++++------------------------- tsuru/client/auth.go | 90 ++++++++----------- tsuru/client/auth_test.go | 14 --- tsuru/client/env.go | 40 +++------ tsuru/client/env_test.go | 25 ------ tsuru/client/event.go | 12 --- tsuru/client/router.go | 99 ++++++++------------- tsuru/client/services.go | 50 ++++------- tsuru/client/services_test.go | 43 +-------- tsuru/client/volume.go | 87 +++++-------------- tsuru/client/volume_test.go | 16 ---- 11 files changed, 164 insertions(+), 470 deletions(-) diff --git a/tsuru/client/apps.go b/tsuru/client/apps.go index 8bce8ede6..2812be1d4 100644 --- a/tsuru/client/apps.go +++ b/tsuru/client/apps.go @@ -161,6 +161,20 @@ func (c *AppCreate) Flags() *gnuflag.FlagSet { return c.fs } +func (c *AppCreate) InputApp(appName string, platform string) tsuru.InputApp { + inputApp := tsuru.InputApp{ + Name: appName, + Platform: platform, + Pool: c.pool, + Description: c.description, + Plan: c.plan, + TeamOwner: c.teamOwner, + Tags: c.tags, + Router: c.router, + Routeropts: c.routerOpts, + } + return inputApp +} func (c *AppCreate) Run(ctx *cmd.Context, client *cmd.Client) error { ctx.RawOutput() var platform string @@ -174,17 +188,8 @@ func (c *AppCreate) Run(ctx *cmd.Context, client *cmd.Client) error { if err != nil { return err } - _, response, err := apiClient.AppApi.AppCreate(context.TODO(), tsuru.InputApp{ - Name: appName, - Platform: platform, - Pool: c.pool, - Description: c.description, - Plan: c.plan, - TeamOwner: c.teamOwner, - Tags: c.tags, - Router: c.router, - Routeropts: c.routerOpts, - }) + inputApp := c.InputApp(appName, platform) + _, response, err := apiClient.AppApi.AppCreate(context.TODO(), inputApp) if err != nil { return err } @@ -193,19 +198,6 @@ func (c *AppCreate) Run(ctx *cmd.Context, client *cmd.Client) error { if err != nil { return err } - // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - // response, err := client.Do(request) - // if err != nil { - // return err - // } - //defer response.Body.Close() - - //result, err := ioutil.ReadAll(response.Body) - //if err != nil { - // return err - //} - //out := make(map[string]string) - //err = json.Unmarshal(result, &out) fmt.Fprintf(ctx.Stdout, "App %q has been created!\n", appName) fmt.Fprintln(ctx.Stdout, "Use app info to check the status of the app and its units.") @@ -1403,19 +1395,6 @@ func addCName(cnames []string, g cmd.AppNameMixIn, client *cmd.Client) error { if err != nil { return err } - // u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/cname", appName)) - // if err != nil { - // return err - // } - // v := url.Values{} - // for _, cname := range cnames { - // v.Add("cname", cname) - // } - // b := strings.NewReader(v.Encode()) - // request, err := http.NewRequest("POST", u, b) - // if err != nil { - // return err - // } var appCname tsuru.AppCName appCname.Cname = cnames @@ -1429,14 +1408,6 @@ func addCName(cnames []string, g cmd.AppNameMixIn, client *cmd.Client) error { if err != nil { return err } - - //err = cmd.StreamJSONResponse(, response) - - //if err != nil { - // return err - //} - // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - // _, err = client.Do(request) return err } @@ -1466,30 +1437,20 @@ func (c *UnitAdd) Flags() *gnuflag.FlagSet { } return c.fs } - +func (c *UnitAdd) unitDelta(ctx *cmd.Context, AppName string) tsuru.UnitsDelta { + unitDelta := tsuru.UnitsDelta{ + Units: ctx.Args[0], + Process: c.process, + Version: c.version, + } + return unitDelta +} func (c *UnitAdd) Run(ctx *cmd.Context, client *cmd.Client) error { ctx.RawOutput() appName, err := c.AppName() if err != nil { return err } - // u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/units", appName)) - // if err != nil { - // return err - // } - // val := url.Values{} - // val.Add("units", context.Args[0]) - // val.Add("process", c.process) - // val.Set("version", c.version) - // request, err := http.NewRequest("PUT", u, bytes.NewBufferString(val.Encode())) - // if err != nil { - // return err - // } - var unitDelta tsuru.UnitsDelta - - unitDelta.Units = ctx.Args[0] - unitDelta.Process = c.process - unitDelta.Version = c.version apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: client.HTTPClient, @@ -1498,16 +1459,12 @@ func (c *UnitAdd) Run(ctx *cmd.Context, client *cmd.Client) error { return err } + unitDelta := c.unitDelta(ctx, appName) + response, err := apiClient.AppApi.UnitsAdd(context.TODO(), appName, unitDelta) if err != nil { return err } - // request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - // response, err := client.Do(request) - // if err != nil { - // return err - // } - //defer response.Body.Close() return cmd.StreamJSONResponse(ctx.Stdout, response) } @@ -1590,6 +1547,14 @@ func (c *UnitSet) Flags() *gnuflag.FlagSet { } return c.fs } +func (c *UnitSet) unitDelta(units int) tsuru.UnitsDelta { + unitDelta := tsuru.UnitsDelta{ + Units: strconv.Itoa(units), + Process: c.process, + Version: strconv.Itoa(c.version), + } + return unitDelta +} func (c *UnitSet) Run(ctx *cmd.Context, client *cmd.Client) error { ctx.RawOutput() @@ -1661,24 +1626,10 @@ func (c *UnitSet) Run(ctx *cmd.Context, client *cmd.Client) error { } if existingUnits < desiredUnits { - // u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/units", appName)) - // if err != nil { - // return err - // } unitsToAdd := desiredUnits - existingUnits - // val := url.Values{} - // val.Add("units", strconv.Itoa(unitsToAdd)) - // val.Add("process", c.process) - // val.Add("version", strconv.Itoa(c.version)) - // request, err := http.NewRequest(http.MethodPut, u, bytes.NewBufferString(val.Encode())) - // if err != nil { - // return err - // } - var unitDelta tsuru.UnitsDelta - unitDelta.Units = strconv.Itoa(unitsToAdd) - unitDelta.Process = c.process - unitDelta.Version = strconv.Itoa(c.version) + + unitsDelta := c.unitDelta(unitsToAdd) apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: client.HTTPClient, @@ -1687,35 +1638,17 @@ func (c *UnitSet) Run(ctx *cmd.Context, client *cmd.Client) error { return err } - response, err := apiClient.AppApi.UnitsAdd(context.TODO(), appName, unitDelta) + response, err := apiClient.AppApi.UnitsAdd(context.TODO(), appName, unitsDelta) if err != nil { return err } - // request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - // response, err := client.Do(request) - // if err != nil { - // return err - // } - - // defer response.Body.Close() return cmd.StreamJSONResponse(ctx.Stdout, response) } if existingUnits > desiredUnits { unitsToRemove := existingUnits - desiredUnits - // val := url.Values{} - // val.Add("units", strconv.Itoa(unitsToRemove)) - // val.Add("process", c.process) - // val.Add("version", strconv.Itoa(c.version)) - // u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/units?%s", appName, val.Encode())) - // if err != nil { - // return err - // } - - var unitDelta tsuru.UnitsDelta - unitDelta.Units = strconv.Itoa(unitsToRemove) - unitDelta.Process = c.process - unitDelta.Version = strconv.Itoa(c.version) + + unitsDelta := c.unitDelta(unitsToRemove) apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: client.HTTPClient, @@ -1724,22 +1657,11 @@ func (c *UnitSet) Run(ctx *cmd.Context, client *cmd.Client) error { return err } - response, err := apiClient.AppApi.UnitsRemove(context.TODO(), appName, unitDelta) + response, err := apiClient.AppApi.UnitsRemove(context.TODO(), appName, unitsDelta) if err != nil { return err } - // request, err := http.NewRequest(http.MethodDelete, u, nil) - // if err != nil { - // return err - // } - - // response, err := client.Do(request) - // if err != nil { - // return err - // } - - // defer response.Body.Close() return cmd.StreamJSONResponse(ctx.Stdout, response) } diff --git a/tsuru/client/auth.go b/tsuru/client/auth.go index f48f373ea..8dae6d079 100644 --- a/tsuru/client/auth.go +++ b/tsuru/client/auth.go @@ -35,7 +35,13 @@ func (c *UserCreate) Info() *cmd.Info { MinArgs: 1, } } - +func (c *UserCreate) userData(ctx *cmd.Context, password string) tsuru.UserData { + userData := tsuru.UserData{ + Email: ctx.Args[0], + Password: password, + } + return userData +} func (c *UserCreate) Run(ctx *cmd.Context, client *cmd.Client) error { ctx.RawOutput() _, err := cmd.GetURL("/users") @@ -57,36 +63,14 @@ func (c *UserCreate) Run(ctx *cmd.Context, client *cmd.Client) error { if password != confirm { return errors.New("Passwords didn't match.") } - // v := url.Values{} - // v.Set("email", email) - // v.Set("password", password) - //b := strings.NewReader(v.Encode()) - // request, err := http.NewRequest("POST", u, b) - // if err != nil { - // return err - // } - // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - // resp, err := client.Do(request) - // if resp != nil { - // if resp.StatusCode == http.StatusNotFound || - // resp.StatusCode == http.StatusMethodNotAllowed { - // return errors.New("User creation is disabled.") - // } - // } - // if err != nil { - // return err - // } - apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: client.HTTPClient, }) if err != nil { return err } - response, err := apiClient.UserApi.UserCreate(context.TODO(), tsuru.UserData{ - Email: email, - Password: password, - }) + userData := c.userData(ctx, password) + response, err := apiClient.UserApi.UserCreate(context.TODO(), userData) if err != nil { return err } @@ -199,7 +183,13 @@ func (c *TeamCreate) Flags() *gnuflag.FlagSet { } return c.fs } - +func (c *TeamCreate) teamCreate(name string) tsuru.TeamCreateArgs { + team := tsuru.TeamCreateArgs{ + Name: name, + Tags: c.tags, + } + return team +} func (c *TeamCreate) Run(ctx *cmd.Context, cli *cmd.Client) error { apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, @@ -208,10 +198,9 @@ func (c *TeamCreate) Run(ctx *cmd.Context, cli *cmd.Client) error { return err } team := ctx.Args[0] - _, err = apiClient.TeamApi.TeamCreate(context.TODO(), tsuru.TeamCreateArgs{ - Name: team, - Tags: c.tags, - }) + + teamCreate := c.teamCreate(team) + _, err = apiClient.TeamApi.TeamCreate(context.TODO(), teamCreate) if err != nil { return parseErrBody(err) } @@ -247,7 +236,13 @@ func (t *TeamUpdate) Info() *cmd.Info { MaxArgs: 1, } } - +func (t *TeamUpdate) teamUpdate() tsuru.TeamUpdateArgs { + teamUpdate := tsuru.TeamUpdateArgs{ + Newname: t.newName, + Tags: t.tags, + } + return teamUpdate +} func (t *TeamUpdate) Run(ctx *cmd.Context, cli *cmd.Client) error { apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, @@ -256,10 +251,9 @@ func (t *TeamUpdate) Run(ctx *cmd.Context, cli *cmd.Client) error { return err } team := ctx.Args[0] - _, err = apiClient.TeamApi.TeamUpdate(context.TODO(), team, tsuru.TeamUpdateArgs{ - Newname: t.newName, - Tags: t.tags, - }) + + teamUpdate := t.teamUpdate() + _, err = apiClient.TeamApi.TeamUpdate(context.TODO(), team, teamUpdate) if err != nil { return parseErrBody(err) } @@ -532,19 +526,6 @@ func (c *ChangePassword) Run(ctx *cmd.Context, client *cmd.Client) error { if err != nil { return err } - - // apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ - // HTTPClient: client.HTTPClient, - // }) - // if err != nil { - // return err - // } - // response, err := apiClient.UserApi.ChangePassword() - // if err != nil { - // return err - // } - // err = cmd.StreamJSONResponse(ctx.Stdout, response) - if err != nil { return err } @@ -746,6 +727,13 @@ type ListUsers struct { fs *gnuflag.FlagSet } +func (c *ListUsers) listUsers() tsuru.UsersListOpts { + userList := &tsuru.UsersListOpts{ + Context: optional.NewString(c.context), + Role: optional.NewString(c.role), + } + return *userList +} func (c *ListUsers) Run(ctx *cmd.Context, cli *cmd.Client) error { if c.userEmail != "" && c.role != "" { return errors.New("You cannot filter by user email and role at same time. Enter for more information.") @@ -760,10 +748,8 @@ func (c *ListUsers) Run(ctx *cmd.Context, cli *cmd.Client) error { if err != nil { return err } - users, _, err := apiClient.UserApi.UsersList(context.TODO(), c.userEmail, &tsuru.UsersListOpts{ - Context: optional.NewString(c.context), - Role: optional.NewString(c.role), - }) + userList := c.listUsers() + users, _, err := apiClient.UserApi.UsersList(context.TODO(), c.userEmail, &userList) if err != nil { return err } diff --git a/tsuru/client/auth_test.go b/tsuru/client/auth_test.go index 42747e75e..bd2cb343f 100644 --- a/tsuru/client/auth_test.go +++ b/tsuru/client/auth_test.go @@ -411,8 +411,6 @@ func (s *S) TestUserCreateShouldNotDependOnTsuruTokenFile(c *check.C) { }, CondFunc: func(r *http.Request) bool { contentType := r.Header.Get("Content-Type") == "application/json" - // password := r.FormValue("password") == "foo123" - // email := r.FormValue("email") == "foo@foo.com" url := r.URL.Path == "/1.0/users" data, err := ioutil.ReadAll(r.Body) c.Assert(err, check.IsNil) @@ -497,7 +495,6 @@ func (s *S) TestUserCreateNotFound(c *check.C) { err := command.Run(&context, client) c.Assert(err, check.NotNil) c.Assert(err.Error(), check.Equals, "404 Not Found: Not found") - // c.Assert(err.Error(), check.Equals, "User creation is disabled.") } func (s *S) TestUserCreateMethodNotAllowed(c *check.C) { @@ -518,7 +515,6 @@ func (s *S) TestUserCreateMethodNotAllowed(c *check.C) { err := command.Run(&context, client) c.Assert(err, check.NotNil) c.Assert(err.Error(), check.Equals, "405 Method Not Allowed: Not found") - // c.Assert(err.Error(), check.Equals, "User creation is disabled.") } func (s *S) TestUserCreateInfo(c *check.C) { @@ -638,16 +634,6 @@ func (s *S) TestChangePassword(c *check.C) { contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" url := strings.HasSuffix(r.URL.Path, "/users/password") called = true - // data, err := ioutil.ReadAll(r.Body) - // c.Assert(err, check.IsNil) - // var changePassResult map[string]interface{} - // err = json.Unmarshal(data, &changePassResult) - // c.Assert(err, check.IsNil) - // c.Assert(changePassResult, check.DeepEquals, map[string]interface{}{ - // "old": "gopher", - // "new": "bbrothers", - // "confirm": "bbrothers", - // }) return method && url && contentType && old && new && confirm }, } diff --git a/tsuru/client/env.go b/tsuru/client/env.go index ffeb8dd42..f9e3c9815 100644 --- a/tsuru/client/env.go +++ b/tsuru/client/env.go @@ -86,7 +86,14 @@ func (c *EnvSet) Info() *cmd.Info { MinArgs: 1, } } - +func (c *EnvSet) envSet(envs []tsuru.Env) tsuru.EnvSetData { + envSet := tsuru.EnvSetData{ + Envs: envs, + Norestart: c.noRestart, + Private: c.private, + } + return envSet +} func (c *EnvSet) Run(ctx *cmd.Context, client *cmd.Client) error { ctx.RawOutput() appName, err := c.AppName() @@ -105,11 +112,6 @@ func (c *EnvSet) Run(ctx *cmd.Context, client *cmd.Client) error { envs[i] = tsuru.Env{Name: parts[0], Value: parts[1]} } - // e := apiTypes.Envs{ - // Envs: envs, - // NoRestart: c.noRestart, - // Private: c.private, - // } apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: client.HTTPClient, @@ -117,31 +119,13 @@ func (c *EnvSet) Run(ctx *cmd.Context, client *cmd.Client) error { if err != nil { return err } - response, err := apiClient.AppApi.EnvSet(context.TODO(), appName, tsuru.EnvSetData{ - Envs: envs, - Norestart: c.noRestart, - Private: c.private, - }) + envSet := c.envSet(envs) + + response, err := apiClient.AppApi.EnvSet(context.TODO(), appName, envSet) if err != nil { return err } - // url, err := cmd.GetURL(fmt.Sprintf("/apps/%s/env", appName)) - // if err != nil { - // return err - // } - // v, err := form.EncodeToValues(&e) - // if err != nil { - // return err - // } - // request, err := http.NewRequest("POST", url, strings.NewReader(v.Encode())) - // if err != nil { - // return err - // } - // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - // response, err := client.Do(request) - // if err != nil { - // return err - // } + return cmd.StreamJSONResponse(ctx.Stdout, response) } diff --git a/tsuru/client/env_test.go b/tsuru/client/env_test.go index a2e64e073..7445480d9 100644 --- a/tsuru/client/env_test.go +++ b/tsuru/client/env_test.go @@ -149,10 +149,6 @@ func (s *S) TestEnvSetRun(c *check.C) { CondFunc: func(req *http.Request) bool { err = req.ParseForm() c.Assert(err, check.IsNil) - //var e tsuru.Env - // dec := form.NewDecoder(nil) - // dec.IgnoreUnknownKeys(true) - // dec.UseJSONTags(false) c.Assert(err, check.IsNil) data, err := ioutil.ReadAll(req.Body) c.Assert(err, check.IsNil) @@ -164,8 +160,6 @@ func (s *S) TestEnvSetRun(c *check.C) { path := strings.HasSuffix(req.URL.Path, "/apps/someapp/env") method := req.Method == "POST" contentType := req.Header.Get("Content-Type") == "application/json" - //name := e.Env[0].Name == "DATABASE_HOST" - //value := e.Env[0].Value == "somehost" return path && method && contentType }, } @@ -220,20 +214,12 @@ variable 2`}, {Name: "LINE2", Value: "multiline\nvariable 2", Alias: "", Private: private}, } err = req.ParseForm() - // c.Assert(err, check.IsNil) var e tsuru.EnvSetData - // dec := form.NewDecoder(nil) - // dec.IgnoreUnknownKeys(true) - // dec.UseJSONTags(false) - // err = dec.DecodeValues(&e, req.Form) - // c.Assert(err, check.IsNil) data, err := ioutil.ReadAll(req.Body) c.Assert(err, check.IsNil) - ///var envResult map[string]interface{} err = json.Unmarshal(data, &e) c.Assert(err, check.IsNil) c.Assert(e.Envs, check.DeepEquals, want) - //c.Assert(e.Envs, check.DeepEquals, want) private = !e.Private noRestart := !e.Norestart path := strings.HasSuffix(req.URL.Path, "/apps/someapp/env") @@ -285,19 +271,12 @@ func (s *S) TestEnvSetValues(c *check.C) { err = req.ParseForm() c.Assert(err, check.IsNil) var e tsuru.EnvSetData - //dec := form.NewDecoder(nil) - //dec.IgnoreUnknownKeys(true) - //dec.UseJSONTags(false) - ///err = dec.DecodeValues(&e, req.Form) c.Assert(err, check.IsNil) data, err := ioutil.ReadAll(req.Body) c.Assert(err, check.IsNil) - //var envResult map[string]interface{} err = json.Unmarshal(data, &e) c.Assert(err, check.IsNil) c.Assert(e.Envs, check.DeepEquals, want) - //c.Assert(err, check.IsNil) - //c.Assert(e.Envs, check.DeepEquals, want) private = !e.Private noRestart := !e.Norestart path := strings.HasSuffix(req.URL.Path, "/apps/someapp/env") @@ -348,10 +327,6 @@ func (s *S) TestEnvSetValuesAndPrivateAndNoRestart(c *check.C) { err = req.ParseForm() c.Assert(err, check.IsNil) var e tsuru.EnvSetData - // dec := form.NewDecoder(nil) - // dec.IgnoreUnknownKeys(true) - // dec.UseJSONTags(false) - // err = dec.DecodeValues(&e, req.Form) data, err := ioutil.ReadAll(req.Body) c.Assert(err, check.IsNil) err = json.Unmarshal(data, &e) diff --git a/tsuru/client/event.go b/tsuru/client/event.go index 2f341861d..65d2047e1 100644 --- a/tsuru/client/event.go +++ b/tsuru/client/event.go @@ -358,18 +358,6 @@ func (c *EventCancel) Run(ctx *cmd.Context, cli *cmd.Client) error { if !c.Confirm(ctx, "Are you sure you want to cancel this event?") { return nil } - // u, err := cmd.GetURLVersion("1.1", fmt.Sprintf("/events/%s/cancel", ctx.Args[0])) - // if err != nil { - // return err - // } - // v := url.Values{} - // v.Set("reason", strings.Join(ctx.Args[1:], " ")) - // request, err := http.NewRequest("POST", u, strings.NewReader(v.Encode())) - // if err != nil { - // return err - // } - // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - //_, err = client.Do(request) apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, diff --git a/tsuru/client/router.go b/tsuru/client/router.go index a32aad5f2..645ad92e0 100644 --- a/tsuru/client/router.go +++ b/tsuru/client/router.go @@ -347,53 +347,36 @@ func (c *AppRoutersAdd) Flags() *gnuflag.FlagSet { return c.fs } +func (c *AppRoutersAdd) routerAdd(ctx *cmd.Context) tsuru.AppRouter { + opts := make(map[string]interface{}, len(c.opts)) + for k, v := range c.opts { + opts[k] = v + } + appRouter := tsuru.AppRouter{ + Name: ctx.Args[0], + Opts: opts, + } + return appRouter +} func (c *AppRoutersAdd) Run(ctx *cmd.Context, cli *cmd.Client) error { ctx.RawOutput() appName, err := c.AppName() if err != nil { return err } - // url, err := cmd.GetURLVersion("1.5", fmt.Sprintf("/apps/%s/routers", appName)) - // if err != nil { - // return err - // } - // r := appTypes.AppRouter{ - // Name: ctx.Args[0], - // Opts: c.opts, - // } - // val, err := form.EncodeToValues(r) - // if err != nil { - // return err - // } - // request, err := http.NewRequest("POST", url, strings.NewReader(val.Encode())) - // if err != nil { - // return err - // } - opts := make(map[string]interface{}, len(c.opts)) - for k, v := range c.opts { - opts[k] = v - } apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, }) if err != nil { return err } - _, err = apiClient.AppApi.AppRouterAdd(context.TODO(), appName, tsuru.AppRouter{ - Name: ctx.Args[0], - Opts: opts, - }) + appRouter := c.routerAdd(ctx) + _, err = apiClient.AppApi.AppRouterAdd(context.TODO(), appName, appRouter) if err != nil { return err } - // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - // _, err = client.Do(request) - // if err != nil { - // return err - // } fmt.Fprintln(ctx.Stdout, "Router successfully added.") return nil } @@ -424,6 +407,17 @@ func (c *AppRoutersUpdate) Flags() *gnuflag.FlagSet { return c.fs } +func (c *AppRoutersUpdate) routerUpdate(ctx *cmd.Context) tsuru.AppRouter { + opts := make(map[string]interface{}, len(c.opts)) + for k, v := range c.opts { + opts[k] = v + } + routerUpdate := tsuru.AppRouter{ + Name: ctx.Args[0], + Opts: opts, + } + return routerUpdate +} func (c *AppRoutersUpdate) Run(ctx *cmd.Context, cli *cmd.Client) error { ctx.RawOutput() appName, err := c.AppName() @@ -431,42 +425,14 @@ func (c *AppRoutersUpdate) Run(ctx *cmd.Context, cli *cmd.Client) error { return err } routerName := ctx.Args[0] - // url, err := cmd.GetURLVersion("1.5", fmt.Sprintf("/apps/%s/routers/%s", appName, routerName)) - // if err != nil { - // return err - // } - // r := appTypes.AppRouter{ - // Name: routerName, - // Opts: c.opts, - // } - // val, err := form.EncodeToValues(r) - // if err != nil { - // return err - // } - // request, err := http.NewRequest("PUT", url, strings.NewReader(val.Encode())) - // if err != nil { - // return err - // } - // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - // _, err = client.Do(request) - // if err != nil { - // return err - // } - - opts := make(map[string]interface{}, len(c.opts)) - for k, v := range c.opts { - opts[k] = v - } apiClient, err := client.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, }) if err != nil { return err } - _, err = apiClient.AppApi.AppRouterUpdate(context.TODO(), appName, routerName, tsuru.AppRouter{ - Name: ctx.Args[0], - Opts: opts, - }) + AppRouterUpdate := c.routerUpdate(ctx) + _, err = apiClient.AppApi.AppRouterUpdate(context.TODO(), appName, routerName, AppRouterUpdate) if err != nil { return err @@ -516,6 +482,13 @@ type appVersionRouterBase struct { routable bool } +func (c *appVersionRouterBase) setRoutable(ctx *cmd.Context) tsuru.SetRoutableArgs { + setRoutable := tsuru.SetRoutableArgs{ + Version: ctx.Args[0], + IsRoutable: c.routable, + } + return setRoutable +} func (c *appVersionRouterBase) Run(ctx *cmd.Context, cli *cmd.Client) error { appName, err := c.AppName() if err != nil { @@ -528,10 +501,8 @@ func (c *appVersionRouterBase) Run(ctx *cmd.Context, cli *cmd.Client) error { if err != nil { return err } - _, err = apiClient.AppApi.AppSetRoutable(context.TODO(), appName, tsuru.SetRoutableArgs{ - Version: ctx.Args[0], - IsRoutable: c.routable, - }) + setRoutable := c.setRoutable(ctx) + _, err = apiClient.AppApi.AppSetRoutable(context.TODO(), appName, setRoutable) if err != nil { return err } diff --git a/tsuru/client/services.go b/tsuru/client/services.go index 54f4be49f..cf9f3f741 100644 --- a/tsuru/client/services.go +++ b/tsuru/client/services.go @@ -129,7 +129,18 @@ This example shows how to add a new instance of **mongodb** service, named MaxArgs: 3, } } - +func (c *ServiceInstanceAdd) instanceAdd(instanceName, plan string) tsuru.ServiceInstance { + instanceAdd := tsuru.ServiceInstance{ + Name: instanceName, + PlanName: plan, + Description: c.description, + TeamOwner: c.teamOwner, + Pool: c.pool, + Parameters: c.params, + Tags: c.tags, + } + return instanceAdd +} func (c *ServiceInstanceAdd) Run(ctx *cmd.Context, cli *cmd.Client) error { ctx.RawOutput() serviceName, instanceName := ctx.Args[0], ctx.Args[1] @@ -138,14 +149,8 @@ func (c *ServiceInstanceAdd) Run(ctx *cmd.Context, cli *cmd.Client) error { plan = ctx.Args[2] } // This is kept as this to keep backwards compatibility with older API versions - var instanceAdd tsuru.ServiceInstance - instanceAdd.Name = instanceName - instanceAdd.PlanName = plan - instanceAdd.Description = c.description - instanceAdd.TeamOwner = c.teamOwner - instanceAdd.Pool = c.pool - instanceAdd.Parameters = c.params - instanceAdd.Tags = c.tags + + instanceAdd := c.instanceAdd(instanceName, plan) apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: cli.HTTPClient, @@ -157,9 +162,6 @@ func (c *ServiceInstanceAdd) Run(ctx *cmd.Context, cli *cmd.Client) error { if err != nil { return err } - //err = cmd.StreamJSONResponse(ctx.Stdout, response) - //request.Header.Set("Content-Type", "application/json") - // _, err = cli.Do(request) if err != nil { return err } @@ -283,24 +285,6 @@ func (sb *ServiceInstanceBind) Run(ctx *cmd.Context, client *cmd.Client) error { } serviceName := ctx.Args[0] instanceName := ctx.Args[1] - // u, err := cmd.GetURL("/services/" + serviceName + "/instances/" + instanceName + "/" + appName) - // if err != nil { - // return err - // } - // v := url.Values{} - // v.Set("noRestart", strconv.FormatBool(sb.noRestart)) - // request, err := http.NewRequest("PUT", u, strings.NewReader(v.Encode())) - // if err != nil { - // return err - // } - // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - // resp, err := client.Do(request) - // if err != nil { - // return err - // } - var serviceBind tsuru.ServiceInstanceBind - - serviceBind.NoRestart = sb.noRestart apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: client.HTTPClient, @@ -308,7 +292,7 @@ func (sb *ServiceInstanceBind) Run(ctx *cmd.Context, client *cmd.Client) error { if err != nil { return err } - response, err := apiClient.ServiceApi.ServiceInstanceBind(context.TODO(), serviceName, instanceName, appName, serviceBind) + response, err := apiClient.ServiceApi.ServiceInstanceBind(context.TODO(), serviceName, instanceName, appName, tsuru.ServiceInstanceBind{NoRestart: sb.noRestart}) if err != nil { return err } @@ -552,9 +536,7 @@ func (c *ServicePlanList) Run(ctx *cmd.Context, client *cmd.Client) error { return err } serviceName := ctx.Args[0] - plans, _, err := apiClient.ServiceApi.ServicePlans(context.Background(), serviceName, &tsuru.ServicePlansOpts{ - Pool: optional.NewString(c.pool), - }) + plans, _, err := apiClient.ServiceApi.ServicePlans(context.Background(), serviceName, &tsuru.ServicePlansOpts{Pool: optional.NewString(c.pool)}) if err != nil { return err } diff --git a/tsuru/client/services_test.go b/tsuru/client/services_test.go index dfa096656..0c2b84983 100644 --- a/tsuru/client/services_test.go +++ b/tsuru/client/services_test.go @@ -405,17 +405,8 @@ func (s *S) TestServiceInstanceAddRun(c *check.C) { trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - //err := r.ParseForm() data, err := ioutil.ReadAll(r.Body) c.Assert(err, check.IsNil) - // instance := service.ServiceInstance{ - // PlanName: r.FormValue("plan"), - // TeamOwner: r.FormValue("owner"), - // } - // dec := form.NewDecoder(nil) - // dec.IgnoreCase(true) - // dec.IgnoreUnknownKeys(true) - // dec.UseJSONTags(false) var result map[string]interface{} err = json.Unmarshal(data, &result) c.Assert(err, check.IsNil) @@ -432,23 +423,7 @@ func (s *S) TestServiceInstanceAddRun(c *check.C) { }, "pool": "pool-one", }) - //err = json.Unmarshal(data, &instance) - //err = dec.DecodeValues(&instance, r.Form) - //c.Assert(err, check.IsNil) - // instance.Tags = append(instance.Tags, r.Form["tag"]...) - // c.Assert(err, check.IsNil) - // c.Assert(instance, check.DeepEquals, service.ServiceInstance{ - // Name: "my_app_db", - // PlanName: "small", - // TeamOwner: "my team", - // Description: "desc", - // Tags: []string{"my tag 1", "my tag 2"}, - // Parameters: map[string]interface{}{ - // "param1": "value1", - // "param2": "value2", - // }, - // Pool: "pool-one", - // }) + c.Assert(r.Method, check.DeepEquals, "POST") c.Assert(r.Header.Get("Content-Type"), check.DeepEquals, "application/json") return strings.HasSuffix(r.URL.Path, "/services/mysql/instances") @@ -495,22 +470,6 @@ func (s *S) TestServiceInstanceAddRunWithEmptyTag(c *check.C) { "plan_name": "small", "tags": []interface{}{""}, }) - // err := r.ParseForm() - // c.Assert(err, check.IsNil) - // instance := service.ServiceInstance{ - // PlanName: r.FormValue("plan"), - // TeamOwner: r.FormValue("owner"), - // } - // dec := form.NewDecoder(nil) - // dec.IgnoreCase(true) - // dec.IgnoreUnknownKeys(true) - // dec.UseJSONTags(false) - // err = dec.DecodeValues(&instance, r.Form) - // c.Assert(err, check.IsNil) - // instance.Tags = append(instance.Tags, r.Form["tag"]...) - // c.Assert(err, check.IsNil) - // c.Assert(len(instance.Tags), check.Equals, 1) - // c.Assert(instance.Tags[0], check.DeepEquals, "") return true }, } diff --git a/tsuru/client/volume.go b/tsuru/client/volume.go index 4513b5dc3..4ad54b28b 100644 --- a/tsuru/client/volume.go +++ b/tsuru/client/volume.go @@ -54,49 +54,27 @@ func (c *VolumeCreate) Flags() *gnuflag.FlagSet { } return c.fs } - +func (c *VolumeCreate) volumeCreate(volumeName, planName string) tsuru.Volume { + volumeCreate := tsuru.Volume{ + Name: volumeName, + Plan: tsuru.VolumePlan{Name: planName}, + Pool: c.pool, + TeamOwner: c.team, + Opts: map[string]string(c.opt), + } + return volumeCreate +} func (c *VolumeCreate) Run(ctx *cmd.Context, client *cmd.Client) error { ctx.RawOutput() volumeName, planName := ctx.Args[0], ctx.Args[1] - // vol := volumeTypes.Volume{ - // Name: volumeName, - // Plan: volumeTypes.VolumePlan{Name: planName}, - // Pool: c.pool, - // TeamOwner: c.team, - // Opts: map[string]string(c.opt), - // } - // val, err := form.EncodeToValues(vol) - // if err != nil { - // return err - // } - // body := strings.NewReader(val.Encode()) - // u, err := cmd.GetURLVersion("1.4", "/volumes") - // if err != nil { - // return err - // } - // request, err := http.NewRequest("POST", u, body) - // if err != nil { - // return err - // } - // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - // _, err = client.Do(request) - // if err != nil { - // return err - // } - apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: client.HTTPClient, }) if err != nil { return err } - response, err := apiClient.VolumeApi.VolumeCreate(context.TODO(), tsuru.Volume{ - Name: volumeName, - Plan: tsuru.VolumePlan{Name: planName}, - Pool: c.pool, - TeamOwner: c.team, - Opts: map[string]string(c.opt), - }) + volumeCreate := c.volumeCreate(volumeName, planName) + response, err := apiClient.VolumeApi.VolumeCreate(context.TODO(), volumeCreate) if err != nil { return err @@ -434,7 +412,15 @@ func (c *VolumeBind) Flags() *gnuflag.FlagSet { } return c.fs } - +func (c *VolumeBind) volumeBind(appName string, ctx *cmd.Context) tsuru.VolumeBindData { + bind := tsuru.VolumeBindData{ + App: appName, + Mountpoint: ctx.Args[1], + Readonly: c.readOnly, + Norestart: c.noRestart, + } + return bind +} func (c *VolumeBind) Run(ctx *cmd.Context, client *cmd.Client) error { ctx.RawOutput() volumeName := ctx.Args[0] @@ -442,36 +428,7 @@ func (c *VolumeBind) Run(ctx *cmd.Context, client *cmd.Client) error { if err != nil { return err } - // bind := struct { - // App string - // MountPoint string - // ReadOnly bool - // NoRestart bool - // }{ - bind := tsuru.VolumeBindData{ - App: appName, - Mountpoint: ctx.Args[1], - Readonly: c.readOnly, - Norestart: c.noRestart, - } - // val, err := form.EncodeToValues(bind) - // if err != nil { - // return err - // } - // body := strings.NewReader(val.Encode()) - // u, err := cmd.GetURLVersion("1.4", fmt.Sprintf("/volumes/%s/bind", volumeName)) - // if err != nil { - // return err - // } - // request, err := http.NewRequest("POST", u, body) - // if err != nil { - // return err - // } - // request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - // resp, err := client.Do(request) - // if err != nil { - // return err - // } + bind := c.volumeBind(appName, ctx) apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: client.HTTPClient, }) diff --git a/tsuru/client/volume_test.go b/tsuru/client/volume_test.go index 0ea8b2b41..0f4840021 100644 --- a/tsuru/client/volume_test.go +++ b/tsuru/client/volume_test.go @@ -216,12 +216,7 @@ func (s *S) TestVolumeCreate(c *check.C) { Transport: cmdtest.Transport{Message: "", Status: http.StatusCreated}, CondFunc: func(r *http.Request) bool { r.ParseForm() - // dec := form.NewDecoder(nil) - // dec.IgnoreCase(true) - // dec.IgnoreUnknownKeys(true) - // dec.UseJSONTags(false) var vol tsuru.Volume - //err := dec.DecodeValues(&vol, r.Form) data, err := ioutil.ReadAll(r.Body) c.Assert(err, check.IsNil) err = json.Unmarshal(data, &vol) @@ -313,9 +308,6 @@ func (s *S) TestVolumeBind(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - // r.ParseForm() - // c.Assert(r.FormValue("App"), check.Equals, "myapp") - // c.Assert(r.FormValue("MountPoint"), check.Equals, "/mnt") var vol tsuru.VolumeBindData data, err := ioutil.ReadAll(r.Body) c.Assert(err, check.IsNil) @@ -349,10 +341,6 @@ func (s *S) TestVolumeBindNoRestart(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - // r.ParseForm() - // c.Assert(r.FormValue("App"), check.Equals, "myapp") - // c.Assert(r.FormValue("MountPoint"), check.Equals, "/mnt") - // c.Assert(r.FormValue("NoRestart"), check.Equals, "true") var vol tsuru.VolumeBindData data, err := ioutil.ReadAll(r.Body) c.Assert(err, check.IsNil) @@ -386,10 +374,6 @@ func (s *S) TestVolumeBindRO(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - // r.ParseForm() - // c.Assert(r.FormValue("App"), check.Equals, "myapp") - // c.Assert(r.FormValue("MountPoint"), check.Equals, "/mnt") - // c.Assert(r.FormValue("ReadOnly"), check.Equals, "true") var vol tsuru.VolumeBindData data, err := ioutil.ReadAll(r.Body) c.Assert(err, check.IsNil) From e64ca5825cb335d006369c121dd86fd6372eeb58 Mon Sep 17 00:00:00 2001 From: CarlosRobertoGuerra <61809228+CarlosRoGuerra@users.noreply.github.com> Date: Thu, 8 Jul 2021 08:42:28 -0300 Subject: [PATCH 06/20] change:form to json-> appStart,appStop,appRestart in apps.go, volumeUpdate in volume.go and changePassword in auth.go --- go.mod | 6 +-- go.sum | 28 ++++++----- tsuru/client/apps.go | 96 ++++++++++++++++++------------------- tsuru/client/apps_test.go | 27 +++++++++-- tsuru/client/auth.go | 24 ++++++---- tsuru/client/auth_test.go | 36 +++++++++----- tsuru/client/event_test.go | 1 - tsuru/client/volume.go | 31 ++++++------ tsuru/client/volume_test.go | 17 +++---- 9 files changed, 150 insertions(+), 116 deletions(-) diff --git a/go.mod b/go.mod index f2e10bd97..7aaf6c1b7 100644 --- a/go.mod +++ b/go.mod @@ -21,14 +21,14 @@ require ( github.com/sethvargo/go-password v0.1.1 github.com/tsuru/config v0.0.0-20201023175036-375aaee8b560 github.com/tsuru/gnuflag v0.0.0-20151217162021-86b8c1b864aa - github.com/tsuru/go-tsuruclient v0.0.0-20210426181646-b7774d33597a + github.com/tsuru/go-tsuruclient v0.0.0-20210706193529-586e01e63f2c github.com/tsuru/tablecli v0.0.0-20190131152944-7ded8a3383c6 - github.com/tsuru/tsuru v0.0.0-20210504215419-6e4b785e561c + github.com/tsuru/tsuru v0.0.0-20210706143918-b89a484dc93f golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee google.golang.org/api v0.7.0 // indirect google.golang.org/appengine v1.6.1 // indirect gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b - gopkg.in/yaml.v2 v2.3.0 + gopkg.in/yaml.v2 v2.4.0 k8s.io/apimachinery v0.18.9 k8s.io/client-go v11.0.1-0.20190805182715-88a2adca7e76+incompatible // indirect ) diff --git a/go.sum b/go.sum index 6504aee77..9d84097a1 100644 --- a/go.sum +++ b/go.sum @@ -240,7 +240,6 @@ github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51 github.com/gorilla/mux v0.0.0-20160920230813-757bef944d0f/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.0 h1:tOSd0UKHQd6urX6ApfOn4XdBMY6Sh1MfxV3kmaazO+U= github.com/gorilla/mux v1.7.0/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/pat v0.0.0-20131205071617-ae2e162c4b2a/go.mod h1:YeAe0gNeiNT5hoiZRI4yiOky6jVdNvfO2N6Kav/HmxY= github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= @@ -433,20 +432,18 @@ github.com/tsuru/config v0.0.0-20201023175036-375aaee8b560 h1:fniQ/BmYAHdnNmY333 github.com/tsuru/config v0.0.0-20201023175036-375aaee8b560/go.mod h1:mj6t8JKWU51GScTT50XRmDj65T5XhTyNvO5FUNV5zS4= github.com/tsuru/docker-cluster v0.0.0-20190325123005-f372d8d4e354 h1:KSHCFvKvCMQN9qafzgxNGalC4K/8otSjZ3UTVCJk8bc= github.com/tsuru/docker-cluster v0.0.0-20190325123005-f372d8d4e354/go.mod h1:Inv1W7alFRlGqinfekVO0/RzmQyyRSlfENxNCVxaoMY= -github.com/tsuru/gandalf v0.0.0-20180117164358-86866cf0af24/go.mod h1:0VdaaU608jbG/69upNjUOIVQMcRQW00FgCz3EtzIsKQ= github.com/tsuru/gnuflag v0.0.0-20151217162021-86b8c1b864aa h1:JlLQP1xa13a994p/Aau2e3K9xXYaHNoNvTDVIMHSUa4= github.com/tsuru/gnuflag v0.0.0-20151217162021-86b8c1b864aa/go.mod h1:UibOSvkMFKRe/eiwktAPAvQG8L+p8nYsECJvu3Dgw7I= -github.com/tsuru/go-gandalfclient v0.0.0-20200928142220-6d227717b7c3/go.mod h1:p0UnkpWhQqUX4s3bzKPAYZ/rkz6NIS/PxsR8W4Opf3Q= -github.com/tsuru/go-tsuruclient v0.0.0-20210426181646-b7774d33597a h1:bblOOxOJvfo+MDWGTbTakKKYz2/aFi2X1tm8+ryB3D8= -github.com/tsuru/go-tsuruclient v0.0.0-20210426181646-b7774d33597a/go.mod h1:wYe4ngw/l34brrJ8IZqGmhTWNTycnQsxcAPxGNSY8YY= +github.com/tsuru/go-tsuruclient v0.0.0-20210706193529-586e01e63f2c h1:+DMQy5EgzmOaZuuvdwKiLQbWgQoKGdg32Gn4iMxC6ps= +github.com/tsuru/go-tsuruclient v0.0.0-20210706193529-586e01e63f2c/go.mod h1:P2AL93lzpzJlgOvu37SOhee4pnLWod1GMJ8YYQq2b7o= github.com/tsuru/monsterqueue v0.0.0-20160909010522-70e946ec66c3 h1:+aJngj5cQjYyx/qSjffQceop25t97hLS0+t8bvx9hg4= github.com/tsuru/monsterqueue v0.0.0-20160909010522-70e946ec66c3/go.mod h1:3KR1vkjfm5b7Lhu5OXuO0NMIyZNG0d0d9xh6ufWYVxg= github.com/tsuru/tablecli v0.0.0-20180215113938-82de88f75181/go.mod h1:ztYpOhW+u1k21FEqp7nZNgpWbr0dUKok5lgGCZi+1AQ= github.com/tsuru/tablecli v0.0.0-20190131152944-7ded8a3383c6 h1:1XDdWFAjIbCSG1OjN9v9KdWhuM8UtYlFcfHe/Ldkchk= github.com/tsuru/tablecli v0.0.0-20190131152944-7ded8a3383c6/go.mod h1:ztYpOhW+u1k21FEqp7nZNgpWbr0dUKok5lgGCZi+1AQ= github.com/tsuru/tsuru v0.0.0-20180820205921-0e7f7f02eac5/go.mod h1:8EIA5MXZUPRxQR1lf8kQkcJVss0q+lv0L8f2nb23siQ= -github.com/tsuru/tsuru v0.0.0-20210504215419-6e4b785e561c h1:bQGQXW79KktbqRSktGwOJNAVSLNDoSqEGqGLSeThKnU= -github.com/tsuru/tsuru v0.0.0-20210504215419-6e4b785e561c/go.mod h1:9h1mRbZ+XD4D5hvetn6ar1K2Ub2BSIuoJuFboh/W9oA= +github.com/tsuru/tsuru v0.0.0-20210706143918-b89a484dc93f h1:OF4h90L8GanZmExQCZpNqUuCzbHCSEFc9+M2BmtMIzo= +github.com/tsuru/tsuru v0.0.0-20210706143918-b89a484dc93f/go.mod h1:9TcRS2OOBSemfiUWrNEC0oVO+6Vyz+XC97HzbcQ9tUA= github.com/uber-go/atomic v1.4.0/go.mod h1:/Ct5t2lcmbJ4OSe/waGBoaVvVqtO0bmtfVNex1PFV8g= github.com/uber/jaeger-client-go v2.17.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk= github.com/uber/jaeger-client-go v2.25.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk= @@ -478,6 +475,7 @@ github.com/xanzy/go-cloudstack/v2 v2.8.0 h1:fT6EK104RkcSpGrdlsrFZbCFob3vyXeXm60H github.com/xanzy/go-cloudstack/v2 v2.8.0/go.mod h1:+SiI2stR3n/P6IKCjrlD2e2EWzk+rQqK4SxC4V9QhnY= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= go.mongodb.org/mongo-driver v1.0.3/go.mod h1:u7ryQJ+DOzQmeO7zB6MHyr8jkEQvC8vH7qLUO4lqsUM= @@ -499,6 +497,7 @@ golang.org/x/crypto v0.0.0-20190320223903-b7391e95e576/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190617133340-57b3e21c3d56/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200221231518-2aa609cf4a9d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= @@ -510,6 +509,7 @@ golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvx golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -531,8 +531,8 @@ golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191004110552-13f9640d40b9/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 h1:4nGaVu0QrbjT/AK2PRLuQfQuh6DJve+pELhqTdAj3x0= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/oauth2 v0.0.0-20180402223937-921ae394b943/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -545,10 +545,11 @@ golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9 h1:SQFwaSi55rU7vdNs9Yr0Z324VNlrF+0wMqRXT4St8ck= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20200826173525-f9321e4c35a6 h1:DvY3Zkh7KabQE/kfzMvYvKirSiguP9Q/veMtkYyf0o8= golang.org/x/sys v0.0.0-20200826173525-f9321e4c35a6/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -577,7 +578,10 @@ golang.org/x/tools v0.0.0-20190614205625-5aca471b1d59/go.mod h1:/rFqwRUd4F7ZHNgw golang.org/x/tools v0.0.0-20190617190820-da514acc4774/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190920225731-5eefd052ad72/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -629,6 +633,8 @@ gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= diff --git a/tsuru/client/apps.go b/tsuru/client/apps.go index 2812be1d4..d2a928a00 100644 --- a/tsuru/client/apps.go +++ b/tsuru/client/apps.go @@ -1170,39 +1170,34 @@ func (c *AppStop) Info() *cmd.Info { MinArgs: 0, } } +func (c *AppStop) StoptApp() tsuru.AppStartStop { + stopApp := tsuru.AppStartStop{ + Process: c.process, + Version: c.version, + } + return stopApp +} -func (c *AppStop) Run(context *cmd.Context, client *cmd.Client) error { - context.RawOutput() +func (c *AppStop) Run(ctx *cmd.Context, client *cmd.Client) error { + ctx.RawOutput() appName, err := c.AppName() if err != nil { return err } - u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/stop", appName)) - if err != nil { - return err - } - qs := url.Values{} - qs.Set("process", c.process) - qs.Set("version", c.version) - body := strings.NewReader(qs.Encode()) - request, err := http.NewRequest("POST", u, body) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - // apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ - // HTTPClient: client.HTTPClient, - // }) - // if err != nil { - // return err - // } - // _, err = apiClient.AppApi.AppRestart() + appStop := c.StoptApp() + + response, err := apiClient.AppApi.AppStop(context.TODO(), appName, appStop) - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - response, err := client.Do(request) if err != nil { return err } - return cmd.StreamJSONResponse(context.Stdout, response) + return cmd.StreamJSONResponse(ctx.Stdout, response) } func (c *AppStop) Flags() *gnuflag.FlagSet { @@ -1230,31 +1225,32 @@ func (c *AppStart) Info() *cmd.Info { MinArgs: 0, } } +func (c *AppStart) StartApp() tsuru.AppStartStop { + startApp := tsuru.AppStartStop{ + Process: c.process, + Version: c.version, + } + return startApp +} -func (c *AppStart) Run(context *cmd.Context, client *cmd.Client) error { - context.RawOutput() +func (c *AppStart) Run(ctx *cmd.Context, client *cmd.Client) error { + ctx.RawOutput() appName, err := c.AppName() if err != nil { return err } - u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/start", appName)) - if err != nil { - return err - } - qs := url.Values{} - qs.Set("process", c.process) - qs.Set("version", c.version) - body := strings.NewReader(qs.Encode()) - request, err := http.NewRequest("POST", u, body) + appStart := c.StartApp() + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - response, err := client.Do(request) + response, err := apiClient.AppApi.AppStart(context.TODO(), appName, appStart) if err != nil { return err } - return cmd.StreamJSONResponse(context.Stdout, response) + return cmd.StreamJSONResponse(ctx.Stdout, response) } func (c *AppStart) Flags() *gnuflag.FlagSet { @@ -1274,30 +1270,32 @@ type AppRestart struct { fs *gnuflag.FlagSet } -func (c *AppRestart) Run(context *cmd.Context, client *cmd.Client) error { - context.RawOutput() - appName, err := c.AppName() - if err != nil { - return err +func (c *AppRestart) RestartApp() tsuru.AppStartStop { + restartApp := tsuru.AppStartStop{ + Process: c.process, + Version: c.version, } - u, err := cmd.GetURL(fmt.Sprintf("/apps/%s/restart", appName)) + return restartApp +} +func (c *AppRestart) Run(ctx *cmd.Context, client *cmd.Client) error { + ctx.RawOutput() + appName, err := c.AppName() if err != nil { return err } - qs := url.Values{} - qs.Set("process", c.process) - qs.Set("version", c.version) - body := strings.NewReader(qs.Encode()) - request, err := http.NewRequest("POST", u, body) + + appRestart := c.RestartApp() + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - response, err := client.Do(request) + response, err := apiClient.AppApi.AppRestart(context.TODO(), appName, appRestart) if err != nil { return err } - return cmd.StreamJSONResponse(context.Stdout, response) + return cmd.StreamJSONResponse(ctx.Stdout, response) } func (c *AppRestart) Info() *cmd.Info { diff --git a/tsuru/client/apps_test.go b/tsuru/client/apps_test.go index 4faafdfda..5d7925a2e 100644 --- a/tsuru/client/apps_test.go +++ b/tsuru/client/apps_test.go @@ -2622,7 +2622,14 @@ func (s *S) TestAppRestart(c *check.C) { Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { called = true - c.Assert(req.FormValue("process"), check.Equals, "web") + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + var restartResult map[string]interface{} + err = json.Unmarshal(data, &restartResult) + c.Assert(err, check.IsNil) + c.Assert(restartResult, check.DeepEquals, map[string]interface{}{ + "process": "web", + }) return strings.HasSuffix(req.URL.Path, "/apps/handful_of_nothing/restart") && req.Method == "POST" }, } @@ -2790,7 +2797,14 @@ func (s *S) TestAppStart(c *check.C) { Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { called = true - c.Assert(req.FormValue("process"), check.Equals, "worker") + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + var startResult map[string]interface{} + err = json.Unmarshal(data, &startResult) + c.Assert(err, check.IsNil) + c.Assert(startResult, check.DeepEquals, map[string]interface{}{ + "process": "worker", + }) return strings.HasSuffix(req.URL.Path, "/apps/handful_of_nothing/start") && req.Method == "POST" }, } @@ -2855,7 +2869,14 @@ func (s *S) TestAppStop(c *check.C) { Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { called = true - c.Assert(req.FormValue("process"), check.Equals, "worker") + data, err := ioutil.ReadAll(req.Body) + c.Assert(err, check.IsNil) + var stopResult map[string]interface{} + err = json.Unmarshal(data, &stopResult) + c.Assert(err, check.IsNil) + c.Assert(stopResult, check.DeepEquals, map[string]interface{}{ + "process": "worker", + }) return strings.HasSuffix(req.URL.Path, "/apps/handful_of_nothing/stop") && req.Method == "POST" }, } diff --git a/tsuru/client/auth.go b/tsuru/client/auth.go index 8dae6d079..214dbf9c8 100644 --- a/tsuru/client/auth.go +++ b/tsuru/client/auth.go @@ -491,12 +491,17 @@ Tags: {{.Tags}} type ChangePassword struct{} +func (c *ChangePassword) ChangePassword(old, new, confirm string) tsuru.ChangePasswordData { + changePass := tsuru.ChangePasswordData{ + Old: old, + New: new, + Confirm: confirm, + } + return changePass +} func (c *ChangePassword) Run(ctx *cmd.Context, client *cmd.Client) error { ctx.RawOutput() - u, err := cmd.GetURL("/users/password") - if err != nil { - return err - } + fmt.Fprint(ctx.Stdout, "Current password: ") old, err := cmd.PasswordFromReader(ctx.Stdin) if err != nil { @@ -517,15 +522,14 @@ func (c *ChangePassword) Run(ctx *cmd.Context, client *cmd.Client) error { v.Set("old", old) v.Set("new", new) v.Set("confirm", confirm) - request, err := http.NewRequest("PUT", u, strings.NewReader(v.Encode())) - if err != nil { - return err - } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } + changePassword := c.ChangePassword(old, new, confirm) + _, err = apiClient.UserApi.ChangePassword(context.TODO(), changePassword) if err != nil { return err } diff --git a/tsuru/client/auth_test.go b/tsuru/client/auth_test.go index bd2cb343f..d6d57670d 100644 --- a/tsuru/client/auth_test.go +++ b/tsuru/client/auth_test.go @@ -627,14 +627,21 @@ func (s *S) TestChangePassword(c *check.C) { trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - old := r.FormValue("old") == "gopher" - new := r.FormValue("new") == "bbrothers" - confirm := r.FormValue("confirm") == "bbrothers" + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + var changePassResult map[string]interface{} + err = json.Unmarshal(data, &changePassResult) + c.Assert(err, check.IsNil) + c.Assert(changePassResult, check.DeepEquals, map[string]interface{}{ + "old": "gopher", + "new": "bbrothers", + "confirm": "bbrothers", + }) method := r.Method == "PUT" - contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" + contentType := r.Header.Get("Content-Type") == "application/json" url := strings.HasSuffix(r.URL.Path, "/users/password") called = true - return method && url && contentType && old && new && confirm + return method && url && contentType }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) @@ -659,20 +666,27 @@ func (s *S) TestChangePasswordWrongConfirmation(c *check.C) { trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "New password and password confirmation didn't match.", Status: http.StatusBadRequest}, CondFunc: func(r *http.Request) bool { - old := r.FormValue("old") == "gopher" - new := r.FormValue("new") == "bbrothers" - confirm := r.FormValue("confirm") == "brothers" + data, err := ioutil.ReadAll(r.Body) + c.Assert(err, check.IsNil) + var changePassResult map[string]interface{} + err = json.Unmarshal(data, &changePassResult) + c.Assert(err, check.IsNil) + c.Assert(changePassResult, check.DeepEquals, map[string]interface{}{ + "old": "gopher", + "new": "bbrothers", + "confirm": "brothers", + }) method := r.Method == "PUT" - contentType := r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" + contentType := r.Header.Get("Content-Type") == "application/json" url := strings.HasSuffix(r.URL.Path, "/users/password") - return method && url && contentType && old && new && confirm + return method && url && contentType }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) command := ChangePassword{} err := command.Run(&context, client) c.Assert(err, check.NotNil) - c.Assert(err.Error(), check.Equals, "New password and password confirmation didn't match.") + c.Assert(err.Error(), check.Equals, "400 Bad Request: New password and password confirmation didn't match.") } func (s *S) TestChangePasswordInfo(c *check.C) { diff --git a/tsuru/client/event_test.go b/tsuru/client/event_test.go index 3168c4ade..553f3ed67 100644 --- a/tsuru/client/event_test.go +++ b/tsuru/client/event_test.go @@ -563,7 +563,6 @@ func (s *S) TestEventCancel(c *check.C) { err = json.Unmarshal(data, &eventCancel) c.Assert(err, check.IsNil) c.Assert(eventCancel, check.Equals, tsuru.EventCancelArgs{Reason: "my reason"}) - //c.Assert(req.FormValue("reason"), check.Equals, "my reason") return req.URL.Path == "/1.1/events/998e3908413daf5fd9891aac/cancel" && req.Method == "POST" }, } diff --git a/tsuru/client/volume.go b/tsuru/client/volume.go index 4ad54b28b..c002d4dac 100644 --- a/tsuru/client/volume.go +++ b/tsuru/client/volume.go @@ -118,31 +118,28 @@ func (c *VolumeUpdate) Flags() *gnuflag.FlagSet { } return c.fs } - -func (c *VolumeUpdate) Run(ctx *cmd.Context, client *cmd.Client) error { - volumeName, planName := ctx.Args[0], ctx.Args[1] - vol := volumeTypes.Volume{ +func (c *VolumeUpdate) volumeUpdate(volumeName, planName string) tsuru.Volume { + volumeCreate := tsuru.Volume{ Name: volumeName, - Plan: volumeTypes.VolumePlan{Name: planName}, + Plan: tsuru.VolumePlan{Name: planName}, Pool: c.pool, TeamOwner: c.team, Opts: map[string]string(c.opt), } - val, err := form.EncodeToValues(vol) - if err != nil { - return err - } - body := strings.NewReader(val.Encode()) - u, err := cmd.GetURLVersion("1.4", "/volumes/"+volumeName) - if err != nil { - return err - } - request, err := http.NewRequest("POST", u, body) + return volumeCreate +} + +func (c *VolumeUpdate) Run(ctx *cmd.Context, client *cmd.Client) error { + volumeName, planName := ctx.Args[0], ctx.Args[1] + + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + volumeUpdate := c.volumeUpdate(volumeName, planName) + _, err = apiClient.VolumeApi.VolumeUpdate(context.TODO(), volumeName, volumeUpdate) if err != nil { return err } diff --git a/tsuru/client/volume_test.go b/tsuru/client/volume_test.go index 0f4840021..6fc3e2e73 100644 --- a/tsuru/client/volume_test.go +++ b/tsuru/client/volume_test.go @@ -11,11 +11,9 @@ import ( "net/http" "strings" - "github.com/ajg/form" "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tsuru/cmd" "github.com/tsuru/tsuru/cmd/cmdtest" - volumeTypes "github.com/tsuru/tsuru/types/volume" "gopkg.in/check.v1" ) @@ -250,17 +248,14 @@ func (s *S) TestVolumeUpdate(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - r.ParseForm() - dec := form.NewDecoder(nil) - dec.IgnoreCase(true) - dec.IgnoreUnknownKeys(true) - dec.UseJSONTags(false) - var vol volumeTypes.Volume - err := dec.DecodeValues(&vol, r.Form) + var vol tsuru.Volume + data, err := ioutil.ReadAll(r.Body) c.Assert(err, check.IsNil) - c.Assert(vol, check.DeepEquals, volumeTypes.Volume{ + err = json.Unmarshal(data, &vol) + c.Assert(err, check.IsNil) + c.Assert(vol, check.DeepEquals, tsuru.Volume{ Name: "vol1", - Plan: volumeTypes.VolumePlan{Name: "plan1"}, + Plan: tsuru.VolumePlan{Name: "plan1"}, TeamOwner: "team1", Pool: "pool1", Opts: map[string]string{"a": "1", "b": "2"}, From 898957adc164217ffe55d4988684c95bb4cc7bca Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Tue, 13 Jul 2021 17:04:02 -0300 Subject: [PATCH 07/20] change: Use json.NewDescoder in tsuru client tests --- .vscode/launch.json | 7 +++ tsuru/client/apps_test.go | 114 ++++++++-------------------------- tsuru/client/auth_test.go | 12 +--- tsuru/client/env_test.go | 7 +-- tsuru/client/services_test.go | 16 ++--- tsuru/client/volume.go | 8 +-- tsuru/client/volume_test.go | 24 ++----- 7 files changed, 52 insertions(+), 136 deletions(-) create mode 100644 .vscode/launch.json diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 000000000..5c7247b40 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,7 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [] +} \ No newline at end of file diff --git a/tsuru/client/apps_test.go b/tsuru/client/apps_test.go index 5d7925a2e..471e35784 100644 --- a/tsuru/client/apps_test.go +++ b/tsuru/client/apps_test.go @@ -46,10 +46,8 @@ Use app info to check the status of the app and its units.` + "\n" Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { url := strings.HasSuffix(r.URL.Path, "/apps") - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var appResult map[string]interface{} - err = json.Unmarshal(data, &appResult) + err := json.NewDecoder(r.Body).Decode(&appResult) c.Assert(err, check.IsNil) c.Assert(appResult, check.DeepEquals, map[string]interface{}{ "name": "ble", @@ -82,10 +80,8 @@ Use app info to check the status of the app and its units.` + "\n" Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { url := strings.HasSuffix(r.URL.Path, "/apps") - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var appResult map[string]interface{} - err = json.Unmarshal(data, &appResult) + err := json.NewDecoder(r.Body).Decode(&appResult) c.Assert(err, check.IsNil) c.Assert(appResult, check.DeepEquals, map[string]interface{}{ "name": "ble", @@ -117,10 +113,8 @@ Use app info to check the status of the app and its units.` + "\n" Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { url := strings.HasSuffix(r.URL.Path, "/apps") - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var appResult map[string]interface{} - err = json.Unmarshal(data, &appResult) + err := json.NewDecoder(r.Body).Decode(&appResult) c.Assert(err, check.IsNil) c.Assert(appResult, check.DeepEquals, map[string]interface{}{ "name": "ble", @@ -154,10 +148,8 @@ Use app info to check the status of the app and its units.` + "\n" Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { url := strings.HasSuffix(r.URL.Path, "/apps") - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var appResult map[string]interface{} - err = json.Unmarshal(data, &appResult) + err := json.NewDecoder(r.Body).Decode(&appResult) c.Assert(err, check.IsNil) c.Assert(appResult, check.DeepEquals, map[string]interface{}{ "name": "ble", @@ -192,10 +184,8 @@ Use app info to check the status of the app and its units.` + "\n" Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { url := strings.HasSuffix(r.URL.Path, "/apps") - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var appResult map[string]interface{} - err = json.Unmarshal(data, &appResult) + err := json.NewDecoder(r.Body).Decode(&appResult) c.Assert(err, check.IsNil) c.Assert(appResult, check.DeepEquals, map[string]interface{}{ "name": "ble", @@ -230,10 +220,8 @@ Use app info to check the status of the app and its units.` + "\n" Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { url := strings.HasSuffix(r.URL.Path, "/apps") - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var appResult map[string]interface{} - err = json.Unmarshal(data, &appResult) + err := json.NewDecoder(r.Body).Decode(&appResult) c.Assert(err, check.IsNil) method := r.Method == "POST" contentType := r.Header.Get("Content-Type") == "application/json" @@ -270,10 +258,8 @@ Use app info to check the status of the app and its units.` + "\n" Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { url := strings.HasSuffix(r.URL.Path, "/apps") - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var appResult map[string]interface{} - err = json.Unmarshal(data, &appResult) + err := json.NewDecoder(r.Body).Decode(&appResult) c.Assert(err, check.IsNil) c.Assert(appResult, check.DeepEquals, map[string]interface{}{ "name": "ble", @@ -320,10 +306,8 @@ Use app info to check the status of the app and its units.` + "\n" Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { url := strings.HasSuffix(r.URL.Path, "/apps") - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var appResult map[string]interface{} - err = json.Unmarshal(data, &appResult) + err := json.NewDecoder(r.Body).Decode(&appResult) c.Assert(err, check.IsNil) c.Assert(appResult, check.DeepEquals, map[string]interface{}{ "name": "ble", @@ -360,10 +344,8 @@ Use app info to check the status of the app and its units.` + "\n" Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { url := strings.HasSuffix(r.URL.Path, "/apps") - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var appResult map[string]interface{} - err = json.Unmarshal(data, &appResult) + err := json.NewDecoder(r.Body).Decode(&appResult) c.Assert(err, check.IsNil) c.Assert(appResult, check.DeepEquals, map[string]interface{}{ "name": "ble", @@ -469,10 +451,8 @@ func (s *S) TestAppUpdate(c *check.C) { CondFunc: func(req *http.Request) bool { url := strings.HasSuffix(req.URL.Path, "/apps/ble") method := req.Method == "PUT" - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "description": "description of my app", @@ -505,10 +485,8 @@ func (s *S) TestAppUpdateImageReset(c *check.C) { CondFunc: func(req *http.Request) bool { url := strings.HasSuffix(req.URL.Path, "/apps/img") method := req.Method == "PUT" - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "imageReset": true, @@ -538,10 +516,8 @@ func (s *S) TestAppUpdateWithoutTags(c *check.C) { CondFunc: func(req *http.Request) bool { url := strings.HasSuffix(req.URL.Path, "/apps/ble") method := req.Method == "PUT" - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "description": "description", @@ -571,10 +547,8 @@ func (s *S) TestAppUpdateWithEmptyTag(c *check.C) { CondFunc: func(req *http.Request) bool { url := strings.HasSuffix(req.URL.Path, "/apps/ble") method := req.Method == "PUT" - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "description": "description", @@ -605,10 +579,8 @@ func (s *S) TestAppUpdateWithCPUAndMemory(c *check.C) { CondFunc: func(req *http.Request) bool { url := strings.HasSuffix(req.URL.Path, "/apps/ble") method := req.Method == "PUT" - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "planoverride": map[string]interface{}{ @@ -2622,10 +2594,8 @@ func (s *S) TestAppRestart(c *check.C) { Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { called = true - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var restartResult map[string]interface{} - err = json.Unmarshal(data, &restartResult) + err := json.NewDecoder(req.Body).Decode(&restartResult) c.Assert(err, check.IsNil) c.Assert(restartResult, check.DeepEquals, map[string]interface{}{ "process": "web", @@ -2663,10 +2633,8 @@ func (s *S) TestAddCName(c *check.C) { Transport: cmdtest.Transport{Message: "Restarted", Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { called = true - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) - cNameResult := make(map[string]interface{}) - err = json.Unmarshal(data, &cNameResult) + var cNameResult map[string]interface{} + err := json.NewDecoder(req.Body).Decode(&cNameResult) c.Assert(err, check.IsNil) c.Assert(cNameResult, check.DeepEquals, map[string]interface{}{ "cname": []interface{}{"death.evergrey.mycompany.com"}, @@ -2797,10 +2765,8 @@ func (s *S) TestAppStart(c *check.C) { Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { called = true - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var startResult map[string]interface{} - err = json.Unmarshal(data, &startResult) + err := json.NewDecoder(req.Body).Decode(&startResult) c.Assert(err, check.IsNil) c.Assert(startResult, check.DeepEquals, map[string]interface{}{ "process": "worker", @@ -2869,10 +2835,8 @@ func (s *S) TestAppStop(c *check.C) { Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { called = true - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var stopResult map[string]interface{} - err = json.Unmarshal(data, &stopResult) + err := json.NewDecoder(req.Body).Decode(&stopResult) c.Assert(err, check.IsNil) c.Assert(stopResult, check.DeepEquals, map[string]interface{}{ "process": "worker", @@ -2909,17 +2873,13 @@ func (s *S) TestUnitAdd(c *check.C) { Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { called = true - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "units": "3", "process": "p1", }) - // c.Assert(req.FormValue("process"), check.Equals, "p1") - // c.Assert(req.FormValue("units"), check.Equals, "3") return strings.HasSuffix(req.URL.Path, "/apps/radio/units") && req.Method == "PUT" }, } @@ -2948,19 +2908,14 @@ func (s *S) TestUnitAddWithVersion(c *check.C) { Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { called = true - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "units": "3", "process": "p1", "version": "9", }) - // c.Assert(req.FormValue("process"), check.Equals, "p1") - // c.Assert(req.FormValue("units"), check.Equals, "3") - // c.Assert(req.FormValue("version"), check.Equals, "9") return strings.HasSuffix(req.URL.Path, "/apps/radio/units") && req.Method == "PUT" }, } @@ -3082,10 +3037,8 @@ func (s *S) TestUnitSetAddUnits(c *check.C) { { CondFunc: func(req *http.Request) bool { calledPut = true - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "units": "7", @@ -3133,10 +3086,8 @@ func (s *S) TestUnitSetAddUnitsFailure(c *check.C) { { CondFunc: func(req *http.Request) bool { calledPut = true - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "units": "7", @@ -3188,18 +3139,14 @@ func (s *S) TestUnitSetRemoveUnits(c *check.C) { { CondFunc: func(req *http.Request) bool { calledDelete = true - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "units": "2", "process": "web", "version": "0", }) - // c.Assert(req.FormValue("process"), check.Equals, "web") - // c.Assert(req.FormValue("units"), check.Equals, "2") return strings.HasSuffix(req.URL.Path, "/apps/app1/units") && req.Method == http.MethodDelete }, Transport: cmdtest.Transport{Message: string(resultDelete), Status: http.StatusOK}, @@ -3241,18 +3188,15 @@ func (s *S) TestUnitSetRemoveUnitsFailure(c *check.C) { { CondFunc: func(req *http.Request) bool { calledDelete = true - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "units": "2", "process": "web", "version": "0", }) - // c.Assert(req.FormValue("process"), check.Equals, "web") - // c.Assert(req.FormValue("units"), check.Equals, "2") + return strings.HasSuffix(req.URL.Path, "/apps/app1/units") && req.Method == http.MethodDelete }, Transport: cmdtest.Transport{Message: "Failed to delete.", Status: http.StatusInternalServerError}, @@ -3378,18 +3322,14 @@ func (s *S) TestUnitSetNoProcessSpecifiedAndSingleExists(c *check.C) { { CondFunc: func(req *http.Request) bool { calledPut = true - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "units": "8", "process": "worker", "version": "0", }) - // c.Assert(req.FormValue("process"), check.Equals, "worker") - // c.Assert(req.FormValue("units"), check.Equals, "8") return strings.HasSuffix(req.URL.Path, "/apps/app1/units") && req.Method == http.MethodPut }, Transport: cmdtest.Transport{Message: string(resultPut), Status: http.StatusOK}, diff --git a/tsuru/client/auth_test.go b/tsuru/client/auth_test.go index d6d57670d..fbac42481 100644 --- a/tsuru/client/auth_test.go +++ b/tsuru/client/auth_test.go @@ -412,10 +412,8 @@ func (s *S) TestUserCreateShouldNotDependOnTsuruTokenFile(c *check.C) { CondFunc: func(r *http.Request) bool { contentType := r.Header.Get("Content-Type") == "application/json" url := r.URL.Path == "/1.0/users" - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var createResult map[string]interface{} - err = json.Unmarshal(data, &createResult) + err := json.NewDecoder(r.Body).Decode(&createResult) c.Assert(err, check.IsNil) c.Assert(createResult, check.DeepEquals, map[string]interface{}{ "password": "foo123", @@ -627,10 +625,8 @@ func (s *S) TestChangePassword(c *check.C) { trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var changePassResult map[string]interface{} - err = json.Unmarshal(data, &changePassResult) + err := json.NewDecoder(r.Body).Decode(&changePassResult) c.Assert(err, check.IsNil) c.Assert(changePassResult, check.DeepEquals, map[string]interface{}{ "old": "gopher", @@ -666,10 +662,8 @@ func (s *S) TestChangePasswordWrongConfirmation(c *check.C) { trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "New password and password confirmation didn't match.", Status: http.StatusBadRequest}, CondFunc: func(r *http.Request) bool { - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var changePassResult map[string]interface{} - err = json.Unmarshal(data, &changePassResult) + err := json.NewDecoder(r.Body).Decode(&changePassResult) c.Assert(err, check.IsNil) c.Assert(changePassResult, check.DeepEquals, map[string]interface{}{ "old": "gopher", diff --git a/tsuru/client/env_test.go b/tsuru/client/env_test.go index 7445480d9..f526e35e5 100644 --- a/tsuru/client/env_test.go +++ b/tsuru/client/env_test.go @@ -147,13 +147,8 @@ func (s *S) TestEnvSetRun(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { - err = req.ParseForm() - c.Assert(err, check.IsNil) - c.Assert(err, check.IsNil) - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var envResult map[string]interface{} - err = json.Unmarshal(data, &envResult) + err := json.NewDecoder(req.Body).Decode(&envResult) c.Assert(err, check.IsNil) c.Assert(envResult, check.DeepEquals, map[string]interface{}{"envs": []interface{}{map[string]interface{}{"name": "DATABASE_HOST", "value": "somehost"}}}) diff --git a/tsuru/client/services_test.go b/tsuru/client/services_test.go index 0c2b84983..3ad44c8a9 100644 --- a/tsuru/client/services_test.go +++ b/tsuru/client/services_test.go @@ -250,10 +250,8 @@ func (s *S) TestServiceInstanceBind(c *check.C) { called = true method := req.Method == "PUT" path := strings.HasSuffix(req.URL.Path, "/services/mysql/instances/my-mysql/g1") - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var bindResult map[string]interface{} - err = json.Unmarshal(data, &bindResult) + err := json.NewDecoder(req.Body).Decode(&bindResult) c.Assert(err, check.IsNil) c.Assert(bindResult, check.DeepEquals, map[string]interface{}{ "noRestart": true, @@ -286,10 +284,8 @@ func (s *S) TestServiceInstanceBindWithoutEnvironmentVariables(c *check.C) { CondFunc: func(req *http.Request) bool { method := req.Method == "PUT" path := strings.HasSuffix(req.URL.Path, "/services/mysql/instances/my-mysql/g1") - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) var bindResult map[string]interface{} - err = json.Unmarshal(data, &bindResult) + err := json.NewDecoder(req.Body).Decode(&bindResult) c.Assert(err, check.IsNil) c.Assert(bindResult, check.DeepEquals, map[string]interface{}{}) return method && path @@ -405,10 +401,8 @@ func (s *S) TestServiceInstanceAddRun(c *check.C) { trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(r.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "name": "my_app_db", @@ -460,10 +454,8 @@ func (s *S) TestServiceInstanceAddRunWithEmptyTag(c *check.C) { trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) var result map[string]interface{} - err = json.Unmarshal(data, &result) + err := json.NewDecoder(r.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "name": "my_app_db", diff --git a/tsuru/client/volume.go b/tsuru/client/volume.go index c002d4dac..16f8aec04 100644 --- a/tsuru/client/volume.go +++ b/tsuru/client/volume.go @@ -427,14 +427,14 @@ func (c *VolumeBind) Run(ctx *cmd.Context, client *cmd.Client) error { } bind := c.volumeBind(appName, ctx) apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ - HTTPClient: client.HTTPClient, - }) - + HTTPClient: client.HTTPClient}) + if err != nil { + return err + } response, err := apiClient.VolumeApi.VolumeBind(context.TODO(), volumeName, bind) if err != nil { return err } - err = cmd.StreamJSONResponse(ctx.Stdout, response) if err != nil { return err diff --git a/tsuru/client/volume_test.go b/tsuru/client/volume_test.go index 6fc3e2e73..e8509fc95 100644 --- a/tsuru/client/volume_test.go +++ b/tsuru/client/volume_test.go @@ -7,7 +7,6 @@ package client import ( "bytes" "encoding/json" - "io/ioutil" "net/http" "strings" @@ -213,11 +212,8 @@ func (s *S) TestVolumeCreate(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusCreated}, CondFunc: func(r *http.Request) bool { - r.ParseForm() var vol tsuru.Volume - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) - err = json.Unmarshal(data, &vol) + err := json.NewDecoder(r.Body).Decode(&vol) c.Assert(err, check.IsNil) c.Assert(vol, check.DeepEquals, tsuru.Volume{ Name: "vol1", @@ -248,10 +244,8 @@ func (s *S) TestVolumeUpdate(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - var vol tsuru.Volume - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) - err = json.Unmarshal(data, &vol) + var vol map[string]interface{} + err := json.NewDecoder(r.Body).Decode(&vol) c.Assert(err, check.IsNil) c.Assert(vol, check.DeepEquals, tsuru.Volume{ Name: "vol1", @@ -304,9 +298,7 @@ func (s *S) TestVolumeBind(c *check.C) { Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { var vol tsuru.VolumeBindData - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) - err = json.Unmarshal(data, &vol) + err := json.NewDecoder(r.Body).Decode(&vol) c.Assert(err, check.IsNil) c.Assert(vol, check.DeepEquals, tsuru.VolumeBindData{ App: "myapp", @@ -337,9 +329,7 @@ func (s *S) TestVolumeBindNoRestart(c *check.C) { Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { var vol tsuru.VolumeBindData - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) - err = json.Unmarshal(data, &vol) + err := json.NewDecoder(r.Body).Decode(&vol) c.Assert(err, check.IsNil) c.Assert(vol, check.DeepEquals, tsuru.VolumeBindData{ App: "myapp", @@ -370,9 +360,7 @@ func (s *S) TestVolumeBindRO(c *check.C) { Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { var vol tsuru.VolumeBindData - data, err := ioutil.ReadAll(r.Body) - c.Assert(err, check.IsNil) - err = json.Unmarshal(data, &vol) + err := json.NewDecoder(r.Body).Decode(&vol) c.Assert(err, check.IsNil) c.Assert(vol, check.DeepEquals, tsuru.VolumeBindData{ App: "myapp", From cbcc43e953af3c211de643f91245857330849370 Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Mon, 26 Jul 2021 16:48:47 -0300 Subject: [PATCH 08/20] fix:volumeUpdate in volume.go;Add: ServiceInstanceUpdate to json --- go.sum | 1 - tsuru/client/services.go | 37 ++++++++++++++--------------------- tsuru/client/services_test.go | 33 ++++++++++++++++++------------- tsuru/client/volume.go | 6 +++--- tsuru/client/volume_test.go | 7 ++++--- 5 files changed, 41 insertions(+), 43 deletions(-) diff --git a/go.sum b/go.sum index 9d84097a1..8ae957bd2 100644 --- a/go.sum +++ b/go.sum @@ -631,7 +631,6 @@ gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= diff --git a/tsuru/client/services.go b/tsuru/client/services.go index cf9f3f741..3eeb56429 100644 --- a/tsuru/client/services.go +++ b/tsuru/client/services.go @@ -16,7 +16,6 @@ import ( "strconv" "strings" - "github.com/ajg/form" "github.com/antihax/optional" osb "github.com/pmorie/go-open-service-broker-client/v2" "github.com/tsuru/gnuflag" @@ -217,33 +216,27 @@ parameter may be used multiple times.`, MinArgs: 2, } } +func (c *ServiceInstanceUpdate) instanceUpdate() tsuru.ServiceInstanceUpdateData { + instanceUpdate := tsuru.ServiceInstanceUpdateData{ + Description: c.description, + Teamowner: c.teamOwner, + Plan: c.plan, + Tags: c.tags, + Parameters: c.params, + } + return instanceUpdate +} func (c *ServiceInstanceUpdate) Run(ctx *cmd.Context, client *cmd.Client) error { serviceName, instanceName := ctx.Args[0], ctx.Args[1] - u, err := cmd.GetURL(fmt.Sprintf("/services/%s/instances/%s", serviceName, instanceName)) - if err != nil { - return err - } - parameters := make(map[string]interface{}) - for k, v := range c.params { - parameters[k] = v - } - v, err := form.EncodeToValues(map[string]interface{}{"parameters": parameters}) - if err != nil { - return err - } - v.Set("teamowner", c.teamOwner) - v.Set("description", c.description) - v.Set("plan", c.plan) - for _, tag := range c.tags { - v.Add("tag", tag) - } - request, err := http.NewRequest("PUT", u, strings.NewReader(v.Encode())) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + instanceUpdate := c.instanceUpdate() + _, err = apiClient.ServiceApi.InstanceUpdate(context.TODO(), serviceName, instanceName, instanceUpdate) if err != nil { return err } diff --git a/tsuru/client/services_test.go b/tsuru/client/services_test.go index 3ad44c8a9..ac320a953 100644 --- a/tsuru/client/services_test.go +++ b/tsuru/client/services_test.go @@ -544,18 +544,18 @@ func (s *S) TestServiceInstanceUpdateRun(c *check.C) { trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - r.ParseForm() - c.Check(r.FormValue("description"), check.Equals, "desc") - c.Check(r.Form["tag"], check.HasLen, 2) - c.Check(r.Form["tag"][0], check.Equals, "tag1") - c.Check(r.Form["tag"][1], check.Equals, "tag2") - c.Check(r.FormValue("plan"), check.Equals, "new-plan") - c.Check(r.Method, check.Equals, http.MethodPut) - c.Check(r.Header.Get("Content-Type"), check.Equals, "application/x-www-form-urlencoded") - c.Check(strings.HasSuffix(r.URL.Path, "/services/service/instances/service-instance"), check.Equals, true) - c.Check(r.FormValue("teamowner"), check.Equals, "new-team") - c.Check(r.FormValue("parameters.param1"), check.Equals, "value1") - c.Check(r.FormValue("parameters.param2"), check.Equals, "value2") + var result map[string]interface{} + err := json.NewDecoder(r.Body).Decode(&result) + c.Assert(err, check.IsNil) + c.Assert(result, check.DeepEquals, map[string]interface{}{ + "description": "desc", + "teamowner": "new-team", + "plan": "new-plan", + "tags": []interface{}{"tag1", "tag2"}, + "parameters": map[string]interface{}{ + "param1": "value1", + "param2": "value2"}, + }) return true }, } @@ -583,8 +583,13 @@ func (s *S) TestServiceInstanceUpdateRunWithEmptyTag(c *check.C) { trans := cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: result, Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - r.ParseForm() - return len(r.Form["tag"]) == 1 && r.Form["tag"][0] == "" + var result map[string]interface{} + err := json.NewDecoder(r.Body).Decode(&result) + c.Assert(err, check.IsNil) + c.Assert(result, check.DeepEquals, map[string]interface{}{ + "tags": []interface{}{""}, + }) + return true }, } client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager) diff --git a/tsuru/client/volume.go b/tsuru/client/volume.go index 16f8aec04..0b5be314f 100644 --- a/tsuru/client/volume.go +++ b/tsuru/client/volume.go @@ -118,15 +118,15 @@ func (c *VolumeUpdate) Flags() *gnuflag.FlagSet { } return c.fs } -func (c *VolumeUpdate) volumeUpdate(volumeName, planName string) tsuru.Volume { - volumeCreate := tsuru.Volume{ +func (c *VolumeUpdate) volumeUpdate(volumeName, planName string) tsuru.VolumeUpdateData { + volumeUpdate := tsuru.VolumeUpdateData{ Name: volumeName, Plan: tsuru.VolumePlan{Name: planName}, Pool: c.pool, TeamOwner: c.team, Opts: map[string]string(c.opt), } - return volumeCreate + return volumeUpdate } func (c *VolumeUpdate) Run(ctx *cmd.Context, client *cmd.Client) error { diff --git a/tsuru/client/volume_test.go b/tsuru/client/volume_test.go index e8509fc95..6e23e084c 100644 --- a/tsuru/client/volume_test.go +++ b/tsuru/client/volume_test.go @@ -244,17 +244,18 @@ func (s *S) TestVolumeUpdate(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(r *http.Request) bool { - var vol map[string]interface{} + var vol tsuru.VolumeUpdateData err := json.NewDecoder(r.Body).Decode(&vol) c.Assert(err, check.IsNil) - c.Assert(vol, check.DeepEquals, tsuru.Volume{ + c.Assert(vol, check.DeepEquals, tsuru.VolumeUpdateData{ Name: "vol1", Plan: tsuru.VolumePlan{Name: "plan1"}, TeamOwner: "team1", + Status: "", Pool: "pool1", Opts: map[string]string{"a": "1", "b": "2"}, }) - return strings.HasSuffix(r.URL.Path, "/volumes/vol1") && r.Method == "POST" + return strings.HasSuffix(r.URL.Path, "/volumes/vol1") && r.Method == "PUT" }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) From e70f3c031c3887ab41ef06dce3b7e90ec125a893 Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Mon, 26 Jul 2021 16:57:12 -0300 Subject: [PATCH 09/20] fix:volumeUpdate in volume.go;Add: ServiceInstanceUpdate to json --- go.sum | 2 ++ 1 file changed, 2 insertions(+) diff --git a/go.sum b/go.sum index 8ae957bd2..2173fad79 100644 --- a/go.sum +++ b/go.sum @@ -436,6 +436,8 @@ github.com/tsuru/gnuflag v0.0.0-20151217162021-86b8c1b864aa h1:JlLQP1xa13a994p/A github.com/tsuru/gnuflag v0.0.0-20151217162021-86b8c1b864aa/go.mod h1:UibOSvkMFKRe/eiwktAPAvQG8L+p8nYsECJvu3Dgw7I= github.com/tsuru/go-tsuruclient v0.0.0-20210706193529-586e01e63f2c h1:+DMQy5EgzmOaZuuvdwKiLQbWgQoKGdg32Gn4iMxC6ps= github.com/tsuru/go-tsuruclient v0.0.0-20210706193529-586e01e63f2c/go.mod h1:P2AL93lzpzJlgOvu37SOhee4pnLWod1GMJ8YYQq2b7o= +github.com/tsuru/go-tsuruclient v0.0.0-20210726185852-a34d558923df h1:EcC/XZqcMWU8yWz2TRsXUsbBJ4PKFZGmrKPT3vqgXiM= +github.com/tsuru/go-tsuruclient v0.0.0-20210726185852-a34d558923df/go.mod h1:P2AL93lzpzJlgOvu37SOhee4pnLWod1GMJ8YYQq2b7o= github.com/tsuru/monsterqueue v0.0.0-20160909010522-70e946ec66c3 h1:+aJngj5cQjYyx/qSjffQceop25t97hLS0+t8bvx9hg4= github.com/tsuru/monsterqueue v0.0.0-20160909010522-70e946ec66c3/go.mod h1:3KR1vkjfm5b7Lhu5OXuO0NMIyZNG0d0d9xh6ufWYVxg= github.com/tsuru/tablecli v0.0.0-20180215113938-82de88f75181/go.mod h1:ztYpOhW+u1k21FEqp7nZNgpWbr0dUKok5lgGCZi+1AQ= From 06f0328c28638ab92bec99d37fab357d49943917 Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Mon, 26 Jul 2021 17:09:48 -0300 Subject: [PATCH 10/20] fix:volumeUpdate in volume.go;Add: ServiceInstanceUpdate to json --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 7aaf6c1b7..5e0045200 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/sethvargo/go-password v0.1.1 github.com/tsuru/config v0.0.0-20201023175036-375aaee8b560 github.com/tsuru/gnuflag v0.0.0-20151217162021-86b8c1b864aa - github.com/tsuru/go-tsuruclient v0.0.0-20210706193529-586e01e63f2c + github.com/tsuru/go-tsuruclient v0.0.0-20210726185852-a34d558923df github.com/tsuru/tablecli v0.0.0-20190131152944-7ded8a3383c6 github.com/tsuru/tsuru v0.0.0-20210706143918-b89a484dc93f golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee From 1427bf6da6eac85d5d2c53fe0ebfb79bef930a97 Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Mon, 26 Jul 2021 17:21:21 -0300 Subject: [PATCH 11/20] fix:volumeUpdate in volume.go;Add: ServiceInstanceUpdate to json --- tsuru/admin/cluster.go | 13 ------------- tsuru/admin/cluster_test.go | 7 ------- 2 files changed, 20 deletions(-) diff --git a/tsuru/admin/cluster.go b/tsuru/admin/cluster.go index 89e47ab5e..a806532f8 100644 --- a/tsuru/admin/cluster.go +++ b/tsuru/admin/cluster.go @@ -84,7 +84,6 @@ func (c *ClusterAdd) Run(ctx *cmd.Context, cli *cmd.Client) error { CustomData: c.customData, Default: c.isDefault, Provisioner: provisioner, - CreateData: c.createData, } var data []byte if c.cacert != "" { @@ -318,18 +317,6 @@ func (c *ClusterUpdate) updateCreateData(cluster *tsuru.Cluster) error { if cluster == nil { return fmt.Errorf("cannot update a nil cluster") } - if cluster.CreateData == nil { - cluster.CreateData = make(map[string]string) - } - for key, value := range c.addCreateData { - cluster.CreateData[key] = value - } - for _, key := range c.removeCreateData { - if _, hasKey := cluster.CreateData[key]; !hasKey { - return fmt.Errorf("cannot unset create data entry: key %q not found", key) - } - delete(cluster.CreateData, key) - } return nil } diff --git a/tsuru/admin/cluster_test.go b/tsuru/admin/cluster_test.go index 4d3530d96..e7e9a1288 100644 --- a/tsuru/admin/cluster_test.go +++ b/tsuru/admin/cluster_test.go @@ -49,7 +49,6 @@ func (s *S) TestClusterAddRun(c *check.C) { Pools: []string{"p1", "p2"}, Default: true, Provisioner: "myprov", - CreateData: map[string]string{"iaas": "dockermachine"}, }) return true }, @@ -199,7 +198,6 @@ func (s *S) TestClusterUpdateMergeCluster(c *check.C) { Clientkey: []byte("client key"), Pools: []string{"pool1", "pool2"}, CustomData: map[string]string{"key": "value"}, - CreateData: map[string]string{"key": "value"}, Default: false, } } @@ -281,7 +279,6 @@ func (s *S) TestClusterUpdateMergeCluster(c *check.C) { Clientkey: []byte("client key"), Pools: []string{"pool1", "pool2"}, CustomData: map[string]string{"key": "value"}, - CreateData: map[string]string{"key": "value"}, Default: false, }, }, @@ -299,7 +296,6 @@ func (s *S) TestClusterUpdateMergeCluster(c *check.C) { Clientkey: []byte("client key"), Pools: []string{}, CustomData: map[string]string{"key": "value"}, - CreateData: map[string]string{"key": "value"}, Default: true, }, }, @@ -319,7 +315,6 @@ func (s *S) TestClusterUpdateMergeCluster(c *check.C) { Clientkey: nil, Pools: []string{"pool1", "pool2"}, CustomData: map[string]string{"key": "value"}, - CreateData: map[string]string{"key": "value"}, Default: false, }, }, @@ -338,7 +333,6 @@ func (s *S) TestClusterUpdateMergeCluster(c *check.C) { Clientkey: []byte("client key"), Pools: []string{"pool1", "pool2"}, CustomData: map[string]string{}, - CreateData: map[string]string{}, Default: false, }, }, @@ -358,7 +352,6 @@ func (s *S) TestClusterUpdateMergeCluster(c *check.C) { Clientkey: []byte("ANOTHER CLIENT KEY"), Pools: []string{"pool1", "pool2"}, CustomData: map[string]string{"key": "value"}, - CreateData: map[string]string{"key": "value"}, Default: false, }, }, From 0ff04cd11623b39477eb8fcde2670481a90739d5 Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Tue, 27 Jul 2021 14:46:44 -0300 Subject: [PATCH 12/20] change:var name changePassword to changedPassword in auth.go --- tsuru/client/auth.go | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/tsuru/client/auth.go b/tsuru/client/auth.go index 214dbf9c8..6acba8fad 100644 --- a/tsuru/client/auth.go +++ b/tsuru/client/auth.go @@ -74,6 +74,14 @@ func (c *UserCreate) Run(ctx *cmd.Context, client *cmd.Client) error { if err != nil { return err } + + if response != nil { + if response.StatusCode == http.StatusNotFound || + response.StatusCode == http.StatusMethodNotAllowed { + return errors.New("User creation is disabled.") + } + } + err = cmd.StreamJSONResponse(ctx.Stdout, response) if err != nil { @@ -491,7 +499,7 @@ Tags: {{.Tags}} type ChangePassword struct{} -func (c *ChangePassword) ChangePassword(old, new, confirm string) tsuru.ChangePasswordData { +func (c *ChangePassword) ChangedPassword(old, new, confirm string) tsuru.ChangePasswordData { changePass := tsuru.ChangePasswordData{ Old: old, New: new, @@ -518,18 +526,15 @@ func (c *ChangePassword) Run(ctx *cmd.Context, client *cmd.Client) error { return err } fmt.Fprintln(ctx.Stdout) - v := url.Values{} - v.Set("old", old) - v.Set("new", new) - v.Set("confirm", confirm) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: client.HTTPClient, }) if err != nil { return err } - changePassword := c.ChangePassword(old, new, confirm) - _, err = apiClient.UserApi.ChangePassword(context.TODO(), changePassword) + changedPassword := c.ChangedPassword(old, new, confirm) + _, err = apiClient.UserApi.ChangePassword(context.TODO(), changedPassword) if err != nil { return err } From 147ae47b1f4fbf21040ba1f7617f68fec4965391 Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Tue, 3 Aug 2021 15:45:13 -0300 Subject: [PATCH 13/20] change form to json --- tsuru/admin/cluster.go | 33 ++---------------------------- tsuru/admin/cluster_test.go | 17 +-------------- tsuru/client/apps.go | 7 +------ tsuru/installer/components_test.go | 2 +- 4 files changed, 5 insertions(+), 54 deletions(-) diff --git a/tsuru/admin/cluster.go b/tsuru/admin/cluster.go index a806532f8..72f75a71b 100644 --- a/tsuru/admin/cluster.go +++ b/tsuru/admin/cluster.go @@ -30,7 +30,6 @@ type ClusterAdd struct { addresses cmd.StringSliceFlag pools cmd.StringSliceFlag customData cmd.MapFlag - createData cmd.MapFlag isDefault bool } @@ -51,8 +50,6 @@ func (c *ClusterAdd) Flags() *gnuflag.FlagSet { c.fs.Var(&c.pools, "pool", desc) desc = "Custom provisioner specific data." c.fs.Var(&c.customData, "custom", desc) - desc = "Create data, if set an iaas will be called with this data to create a new machine." - c.fs.Var(&c.createData, "create-data", desc) } return c.fs } @@ -60,7 +57,7 @@ func (c *ClusterAdd) Flags() *gnuflag.FlagSet { func (c *ClusterAdd) Info() *cmd.Info { return &cmd.Info{ Name: "cluster-add", - Usage: "cluster add [--addr address...] [--pool poolname]... [--cacert cacertfile] [--clientcert clientcertfile] [--clientkey clientkeyfile] [--custom key=value]... [--create-data key=value]... [--default]", + Usage: "cluster add [--addr address...] [--pool poolname]... [--cacert cacertfile] [--clientcert clientcertfile] [--clientkey clientkeyfile] [--custom key=value]... [--default]", Desc: `Creates a provisioner cluster definition.`, MinArgs: 2, MaxArgs: 2, @@ -133,8 +130,6 @@ type ClusterUpdate struct { removePool cmd.StringSliceFlag addCustomData cmd.MapFlag removeCustomData cmd.StringSliceFlag - addCreateData cmd.MapFlag - removeCreateData cmd.StringSliceFlag } func (c *ClusterUpdate) Flags() *gnuflag.FlagSet { @@ -164,10 +159,6 @@ func (c *ClusterUpdate) Flags() *gnuflag.FlagSet { c.fs.Var(&c.addCustomData, "add-custom", desc) desc = "Remove custom provisioner specific data." c.fs.Var(&c.removeCustomData, "remove-custom", desc) - desc = "Create data, if set an iaas will be called with this data to re-create the machine." - c.fs.Var(&c.addCreateData, "add-create-data", desc) - desc = "Remove create data" - c.fs.Var(&c.removeCreateData, "remove-create-data", desc) } return c.fs } @@ -175,7 +166,7 @@ func (c *ClusterUpdate) Flags() *gnuflag.FlagSet { func (c *ClusterUpdate) Info() *cmd.Info { return &cmd.Info{ Name: "cluster-update", - Usage: "cluster update [--addr address]... [--add-pool poolname]... [--remove-pool poolname]... [--cacert cacertfile] [--remove-cacert] [--clientcert clientcertfile] [--remove-clientcert] [--clientkey clientkeyfile] [--remove-clientkey] [--add-custom key=value]... [--remove-custom key]... [--add-create-data key=value]... [--remove-create-data key]... [--default=true|false]", + Usage: "cluster update [--addr address]... [--add-pool poolname]... [--remove-pool poolname]... [--cacert cacertfile] [--remove-cacert] [--clientcert clientcertfile] [--remove-clientcert] [--clientkey clientkeyfile] [--remove-clientkey] [--add-custom key=value]... [--remove-custom key]... [--default=true|false]", Desc: `Updates a provisioner cluster definition.`, MinArgs: 2, MaxArgs: 2, @@ -222,9 +213,6 @@ func (c *ClusterUpdate) mergeCluster(cluster *tsuru.Cluster) error { if err := c.updateClientKey(cluster); err != nil { return err } - if err := c.updateCreateData(cluster); err != nil { - return err - } if err := c.updateCustomData(cluster); err != nil { return err } @@ -312,14 +300,6 @@ func (c *ClusterUpdate) updateCustomData(cluster *tsuru.Cluster) error { } return nil } - -func (c *ClusterUpdate) updateCreateData(cluster *tsuru.Cluster) error { - if cluster == nil { - return fmt.Errorf("cannot update a nil cluster") - } - return nil -} - func (c *ClusterUpdate) updatePools(cluster *tsuru.Cluster) error { if cluster == nil { return fmt.Errorf("cannot update a nil cluster") @@ -521,15 +501,6 @@ func (c *ProvisionerInfo) Run(ctx *cmd.Context, cli *cmd.Client) error { tbl.Sort() fmt.Fprint(ctx.Stdout, tbl.String()) - fmt.Fprintf(ctx.Stdout, "\nCreate Data:\n") - tbl = tablecli.NewTable() - tbl.LineSeparator = true - tbl.Headers = tablecli.Row{"Name", "Usage"} - for key, value := range provisioner.ClusterHelp.CreateDataHelp { - tbl.AddRow(tablecli.Row{key, value}) - } - tbl.Sort() - fmt.Fprint(ctx.Stdout, tbl.String()) return nil } diff --git a/tsuru/admin/cluster_test.go b/tsuru/admin/cluster_test.go index e7e9a1288..730c3c76a 100644 --- a/tsuru/admin/cluster_test.go +++ b/tsuru/admin/cluster_test.go @@ -75,7 +75,7 @@ func (s *S) TestClusterAddRun(c *check.C) { "--pool", "p2", "--custom", "a=b", "--custom", "c=d", - "--create-data", "iaas=dockermachine", + "iaas=dockermachine", "--default", }) c.Assert(err, check.IsNil) @@ -239,13 +239,6 @@ func (s *S) TestClusterUpdateMergeCluster(c *check.C) { cluster: getCluster(), errorString: "cannot unset custom data entry: key \"some-not-found-key\" not found", }, - { - command: ClusterUpdate{ - removeCreateData: cmd.StringSliceFlag{"some-not-found-key"}, - }, - cluster: getCluster(), - errorString: "cannot unset create data entry: key \"some-not-found-key\" not found", - }, { command: ClusterUpdate{ isDefault: "true", @@ -320,7 +313,6 @@ func (s *S) TestClusterUpdateMergeCluster(c *check.C) { }, { command: ClusterUpdate{ - removeCreateData: cmd.StringSliceFlag{"key"}, removeCustomData: cmd.StringSliceFlag{"key"}, }, cluster: getCluster(), @@ -547,12 +539,5 @@ Custom Data: +------+--------+ | key2 | value2 | +------+--------+ - -Create Data: -+-------------+---------------+ -| Name | Usage | -+-------------+---------------+ -| create key2 | create value2 | -+-------------+---------------+ `) } diff --git a/tsuru/client/apps.go b/tsuru/client/apps.go index 0c31f116b..661754ea4 100644 --- a/tsuru/client/apps.go +++ b/tsuru/client/apps.go @@ -189,12 +189,7 @@ func (c *AppCreate) Run(ctx *cmd.Context, client *cmd.Client) error { return err } inputApp := c.InputApp(appName, platform) - _, response, err := apiClient.AppApi.AppCreate(context.TODO(), inputApp) - if err != nil { - return err - } - err = cmd.StreamJSONResponse(ctx.Stdout, response) - + _, _, err = apiClient.AppApi.AppCreate(context.TODO(), inputApp) if err != nil { return err } diff --git a/tsuru/installer/components_test.go b/tsuru/installer/components_test.go index b9348fc97..fea302590 100644 --- a/tsuru/installer/components_test.go +++ b/tsuru/installer/components_test.go @@ -47,7 +47,7 @@ func (s *S) TestTsuruAPIBootstrapLocalEnviroment(c *check.C) { c.Assert(string(b), check.Equals, "{\"name\":\"admin\"}\n") } if r.URL.Path == "/1.0/apps" { - c.Assert(string(b), check.Equals, "description=&name=tsuru-dashboard&plan=&platform=python&pool=&router=&routeropts=&teamOwner=admin") + c.Assert(string(b), check.Equals, "{\"name\":\"tsuru-dashboard\",\"platform\":\"python\",\"teamOwner\":\"admin\",\"metadata\":{}}\n") buf, err := json.Marshal(map[string]string{}) c.Assert(err, check.IsNil) w.Write(buf) From 8a4b8afd2bc85dd52d705aae683ba8dde1552a8f Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Tue, 3 Aug 2021 16:21:03 -0300 Subject: [PATCH 14/20] change form to json --- tsuru/client/volume.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tsuru/client/volume.go b/tsuru/client/volume.go index 0b5be314f..f074a51fe 100644 --- a/tsuru/client/volume.go +++ b/tsuru/client/volume.go @@ -79,9 +79,11 @@ func (c *VolumeCreate) Run(ctx *cmd.Context, client *cmd.Client) error { if err != nil { return err } - err = cmd.StreamJSONResponse(ctx.Stdout, response) + if err != nil { + return err + } fmt.Fprint(ctx.Stdout, "Volume successfully created.\n") return nil } From 792f0ee0a96300ae5f22d353e7ecebcebf324c11 Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Tue, 3 Aug 2021 16:24:55 -0300 Subject: [PATCH 15/20] change form to json --- tsuru/client/services_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tsuru/client/services_test.go b/tsuru/client/services_test.go index ac320a953..80127bc20 100644 --- a/tsuru/client/services_test.go +++ b/tsuru/client/services_test.go @@ -285,7 +285,7 @@ func (s *S) TestServiceInstanceBindWithoutEnvironmentVariables(c *check.C) { method := req.Method == "PUT" path := strings.HasSuffix(req.URL.Path, "/services/mysql/instances/my-mysql/g1") var bindResult map[string]interface{} - err := json.NewDecoder(req.Body).Decode(&bindResult) + err = json.NewDecoder(req.Body).Decode(&bindResult) c.Assert(err, check.IsNil) c.Assert(bindResult, check.DeepEquals, map[string]interface{}{}) return method && path From 24d08e5b36ce1cf45ed7ae05aaa2e10651b7a667 Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Tue, 3 Aug 2021 16:44:53 -0300 Subject: [PATCH 16/20] change form to json --- tsuru/client/apps_test.go | 10 +++++----- tsuru/client/env_test.go | 21 ++++----------------- tsuru/client/services_test.go | 2 +- 3 files changed, 10 insertions(+), 23 deletions(-) diff --git a/tsuru/client/apps_test.go b/tsuru/client/apps_test.go index 2ee4d6814..3d2f19678 100644 --- a/tsuru/client/apps_test.go +++ b/tsuru/client/apps_test.go @@ -2595,7 +2595,7 @@ func (s *S) TestAppRestart(c *check.C) { CondFunc: func(req *http.Request) bool { called = true var restartResult map[string]interface{} - err := json.NewDecoder(req.Body).Decode(&restartResult) + err = json.NewDecoder(req.Body).Decode(&restartResult) c.Assert(err, check.IsNil) c.Assert(restartResult, check.DeepEquals, map[string]interface{}{ "process": "web", @@ -2766,7 +2766,7 @@ func (s *S) TestAppStart(c *check.C) { CondFunc: func(req *http.Request) bool { called = true var startResult map[string]interface{} - err := json.NewDecoder(req.Body).Decode(&startResult) + err = json.NewDecoder(req.Body).Decode(&startResult) c.Assert(err, check.IsNil) c.Assert(startResult, check.DeepEquals, map[string]interface{}{ "process": "worker", @@ -2836,7 +2836,7 @@ func (s *S) TestAppStop(c *check.C) { CondFunc: func(req *http.Request) bool { called = true var stopResult map[string]interface{} - err := json.NewDecoder(req.Body).Decode(&stopResult) + err = json.NewDecoder(req.Body).Decode(&stopResult) c.Assert(err, check.IsNil) c.Assert(stopResult, check.DeepEquals, map[string]interface{}{ "process": "worker", @@ -2874,7 +2874,7 @@ func (s *S) TestUnitAdd(c *check.C) { CondFunc: func(req *http.Request) bool { called = true var result map[string]interface{} - err := json.NewDecoder(req.Body).Decode(&result) + err = json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "units": "3", @@ -2909,7 +2909,7 @@ func (s *S) TestUnitAddWithVersion(c *check.C) { CondFunc: func(req *http.Request) bool { called = true var result map[string]interface{} - err := json.NewDecoder(req.Body).Decode(&result) + err = json.NewDecoder(req.Body).Decode(&result) c.Assert(err, check.IsNil) c.Assert(result, check.DeepEquals, map[string]interface{}{ "units": "3", diff --git a/tsuru/client/env_test.go b/tsuru/client/env_test.go index f526e35e5..7777d3992 100644 --- a/tsuru/client/env_test.go +++ b/tsuru/client/env_test.go @@ -7,7 +7,6 @@ package client import ( "bytes" "encoding/json" - "io/ioutil" "net/http" "strings" @@ -148,7 +147,7 @@ func (s *S) TestEnvSetRun(c *check.C) { Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { var envResult map[string]interface{} - err := json.NewDecoder(req.Body).Decode(&envResult) + err = json.NewDecoder(req.Body).Decode(&envResult) c.Assert(err, check.IsNil) c.Assert(envResult, check.DeepEquals, map[string]interface{}{"envs": []interface{}{map[string]interface{}{"name": "DATABASE_HOST", "value": "somehost"}}}) @@ -208,11 +207,8 @@ variable 2`}, {Name: "LINE1", Value: "multiline\nvariable 1", Alias: "", Private: private}, {Name: "LINE2", Value: "multiline\nvariable 2", Alias: "", Private: private}, } - err = req.ParseForm() var e tsuru.EnvSetData - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) - err = json.Unmarshal(data, &e) + err = json.NewDecoder(req.Body).Decode(&e) c.Assert(err, check.IsNil) c.Assert(e.Envs, check.DeepEquals, want) private = !e.Private @@ -263,13 +259,8 @@ func (s *S) TestEnvSetValues(c *check.C) { {Name: "BASE64_STRING", Value: "t5urur0ck5==", Alias: "", Private: private}, {Name: "SOME_PASSWORD", Value: "js87$%32??", Alias: "", Private: private}, } - err = req.ParseForm() - c.Assert(err, check.IsNil) var e tsuru.EnvSetData - c.Assert(err, check.IsNil) - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) - err = json.Unmarshal(data, &e) + err = json.NewDecoder(req.Body).Decode(&e) c.Assert(err, check.IsNil) c.Assert(e.Envs, check.DeepEquals, want) private = !e.Private @@ -319,12 +310,8 @@ func (s *S) TestEnvSetValuesAndPrivateAndNoRestart(c *check.C) { {Name: "VALUE_WITH_EQUAL_SIGN", Value: "http://wholikesquerystrings.me/?tsuru=awesome", Private: private}, {Name: "BASE64_STRING", Value: "t5urur0ck5==", Alias: "", Private: private}, } - err = req.ParseForm() - c.Assert(err, check.IsNil) var e tsuru.EnvSetData - data, err := ioutil.ReadAll(req.Body) - c.Assert(err, check.IsNil) - err = json.Unmarshal(data, &e) + err = json.NewDecoder(req.Body).Decode(&e) c.Assert(err, check.IsNil) c.Assert(e.Envs, check.DeepEquals, want) private = e.Private diff --git a/tsuru/client/services_test.go b/tsuru/client/services_test.go index 80127bc20..8f7a59a63 100644 --- a/tsuru/client/services_test.go +++ b/tsuru/client/services_test.go @@ -251,7 +251,7 @@ func (s *S) TestServiceInstanceBind(c *check.C) { method := req.Method == "PUT" path := strings.HasSuffix(req.URL.Path, "/services/mysql/instances/my-mysql/g1") var bindResult map[string]interface{} - err := json.NewDecoder(req.Body).Decode(&bindResult) + err = json.NewDecoder(req.Body).Decode(&bindResult) c.Assert(err, check.IsNil) c.Assert(bindResult, check.DeepEquals, map[string]interface{}{ "noRestart": true, From 698f07f13c4fdcd9c9114ef309cc353ed0825798 Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Fri, 13 Aug 2021 18:25:35 -0300 Subject: [PATCH 17/20] add: certificate and permission to client --- go.mod | 2 +- go.sum | 2 + tsuru/client/certificate.go | 52 +++++---- tsuru/client/certificate_test.go | 34 +++++- tsuru/client/permission.go | 188 ++++++++++++++++++------------- tsuru/client/permission_test.go | 127 ++++++++++++++++----- 6 files changed, 268 insertions(+), 137 deletions(-) diff --git a/go.mod b/go.mod index 5e0045200..7439968e3 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/sethvargo/go-password v0.1.1 github.com/tsuru/config v0.0.0-20201023175036-375aaee8b560 github.com/tsuru/gnuflag v0.0.0-20151217162021-86b8c1b864aa - github.com/tsuru/go-tsuruclient v0.0.0-20210726185852-a34d558923df + github.com/tsuru/go-tsuruclient v0.0.0-20210813191311-aa50779317a0 github.com/tsuru/tablecli v0.0.0-20190131152944-7ded8a3383c6 github.com/tsuru/tsuru v0.0.0-20210706143918-b89a484dc93f golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee diff --git a/go.sum b/go.sum index 2173fad79..e50c333fe 100644 --- a/go.sum +++ b/go.sum @@ -438,6 +438,8 @@ github.com/tsuru/go-tsuruclient v0.0.0-20210706193529-586e01e63f2c h1:+DMQy5Egzm github.com/tsuru/go-tsuruclient v0.0.0-20210706193529-586e01e63f2c/go.mod h1:P2AL93lzpzJlgOvu37SOhee4pnLWod1GMJ8YYQq2b7o= github.com/tsuru/go-tsuruclient v0.0.0-20210726185852-a34d558923df h1:EcC/XZqcMWU8yWz2TRsXUsbBJ4PKFZGmrKPT3vqgXiM= github.com/tsuru/go-tsuruclient v0.0.0-20210726185852-a34d558923df/go.mod h1:P2AL93lzpzJlgOvu37SOhee4pnLWod1GMJ8YYQq2b7o= +github.com/tsuru/go-tsuruclient v0.0.0-20210813191311-aa50779317a0 h1:RQ5VuJs7sHVCjGiibwkbml4mlxCmJxowTcldXbg/eQo= +github.com/tsuru/go-tsuruclient v0.0.0-20210813191311-aa50779317a0/go.mod h1:P2AL93lzpzJlgOvu37SOhee4pnLWod1GMJ8YYQq2b7o= github.com/tsuru/monsterqueue v0.0.0-20160909010522-70e946ec66c3 h1:+aJngj5cQjYyx/qSjffQceop25t97hLS0+t8bvx9hg4= github.com/tsuru/monsterqueue v0.0.0-20160909010522-70e946ec66c3/go.mod h1:3KR1vkjfm5b7Lhu5OXuO0NMIyZNG0d0d9xh6ufWYVxg= github.com/tsuru/tablecli v0.0.0-20180215113938-82de88f75181/go.mod h1:ztYpOhW+u1k21FEqp7nZNgpWbr0dUKok5lgGCZi+1AQ= diff --git a/tsuru/client/certificate.go b/tsuru/client/certificate.go index bfcea708e..3c6dacb33 100644 --- a/tsuru/client/certificate.go +++ b/tsuru/client/certificate.go @@ -5,6 +5,7 @@ package client import ( + "context" "crypto/x509" "crypto/x509/pkix" "encoding/json" @@ -18,7 +19,10 @@ import ( "strings" "github.com/tsuru/gnuflag" + tsuruClient "github.com/tsuru/go-tsuruclient/pkg/client" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tablecli" + "github.com/tsuru/tsuru-client/tsuru/formatter" "github.com/tsuru/tsuru/cmd" ) @@ -47,8 +51,15 @@ func (c *CertificateSet) Flags() *gnuflag.FlagSet { } return c.fs } - -func (c *CertificateSet) Run(context *cmd.Context, client *cmd.Client) error { +func (c *CertificateSet) CertificateAdd(cert []byte, key []byte) tsuru.CertificateSetData { + certificate := tsuru.CertificateSetData{ + Cname: c.cname, + Certificate: cert, + Key: key, + } + return certificate +} +func (c *CertificateSet) Run(ctx *cmd.Context, client *cmd.Client) error { appName, err := c.AppName() if err != nil { return err @@ -56,33 +67,27 @@ func (c *CertificateSet) Run(context *cmd.Context, client *cmd.Client) error { if c.cname == "" { return errors.New("You must set cname.") } - cert, err := ioutil.ReadFile(context.Args[0]) + cert, err := ioutil.ReadFile(ctx.Args[0]) if err != nil { return err } - key, err := ioutil.ReadFile(context.Args[1]) + key, err := ioutil.ReadFile(ctx.Args[1]) if err != nil { return err } - v := url.Values{} - v.Set("cname", c.cname) - v.Set("certificate", string(cert)) - v.Set("key", string(key)) - u, err := cmd.GetURLVersion("1.2", fmt.Sprintf("/apps/%s/certificate", appName)) + certificate := c.CertificateAdd(cert, key) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request, err := http.NewRequest(http.MethodPut, u, strings.NewReader(v.Encode())) - if err != nil { - return err - } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - response, err := client.Do(request) + response, err := apiClient.AppApi.CertificateSet(context.TODO(), appName, certificate) if err != nil { return err } defer response.Body.Close() - fmt.Fprintln(context.Stdout, "Successfully created the certificated.") + fmt.Fprintln(ctx.Stdout, "Successfully created the certificated.") return nil } @@ -110,7 +115,7 @@ func (c *CertificateUnset) Flags() *gnuflag.FlagSet { return c.fs } -func (c *CertificateUnset) Run(context *cmd.Context, client *cmd.Client) error { +func (c *CertificateUnset) Run(ctx *cmd.Context, client *cmd.Client) error { appName, err := c.AppName() if err != nil { return err @@ -120,21 +125,18 @@ func (c *CertificateUnset) Run(context *cmd.Context, client *cmd.Client) error { } v := url.Values{} v.Set("cname", c.cname) - u, err := cmd.GetURLVersion("1.2", fmt.Sprintf("/apps/%s/certificate?%s", appName, v.Encode())) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request, err := http.NewRequest(http.MethodDelete, u, nil) - if err != nil { - return err - } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - response, err := client.Do(request) + response, err := apiClient.AppApi.CertificatUnset(context.TODO(), appName) if err != nil { return err } defer response.Body.Close() - fmt.Fprintln(context.Stdout, "Certificate removed.") + fmt.Fprintln(ctx.Stdout, "Certificate removed.") return nil } diff --git a/tsuru/client/certificate_test.go b/tsuru/client/certificate_test.go index ab98826a8..0fabb1755 100644 --- a/tsuru/client/certificate_test.go +++ b/tsuru/client/certificate_test.go @@ -10,15 +10,24 @@ import ( "io/ioutil" "net/http" "os" + "strconv" "strings" "time" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tsuru-client/tsuru/formatter" "github.com/tsuru/tsuru/cmd" "github.com/tsuru/tsuru/cmd/cmdtest" check "gopkg.in/check.v1" ) +func convert(b []byte) string { + s := make([]string, len(b)) + for i := range b { + s[i] = strconv.Itoa(int(b[i])) + } + return strings.Join(s, ",") +} func (s *S) TestCertificateSetRunSuccessfully(c *check.C) { var stdout, stderr bytes.Buffer context := cmd.Context{ @@ -34,10 +43,23 @@ func (s *S) TestCertificateSetRunSuccessfully(c *check.C) { CondFunc: func(req *http.Request) bool { url := strings.HasSuffix(req.URL.Path, "/apps/secret/certificate") method := req.Method == http.MethodPut - cname := req.FormValue("cname") == "app.io" - certificate := req.FormValue("certificate") == s.mustReadFileString(c, "./testdata/cert/server.crt") - key := req.FormValue("key") == s.mustReadFileString(c, "./testdata/cert/server.key") - return url && method && cname && certificate && key + var cert tsuru.CertificateSetData + err := json.NewDecoder(req.Body).Decode(&cert) + c.Assert(err, check.IsNil) + certifica, err := ioutil.ReadFile("./testdata/cert/server.crt") + if err != nil { + return false + } + key, err := ioutil.ReadFile("./testdata/cert/server.key") + if err != nil { + return false + } + c.Assert(cert, check.DeepEquals, tsuru.CertificateSetData{ + Cname: "app.io", + Certificate: certifica, + Key: key, + }) + return url && method }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) @@ -82,9 +104,9 @@ func (s *S) TestCertificateUnsetRunSuccessfully(c *check.C) { requestCount++ url := strings.HasSuffix(req.URL.Path, "/apps/secret/certificate") method := req.Method == http.MethodDelete - cname := req.FormValue("cname") == "app.io" + //cname := req.FormValue("cname") == "app.io" - return url && method && cname + return url && method }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) diff --git a/tsuru/client/permission.go b/tsuru/client/permission.go index 1a716d678..14322e9e2 100644 --- a/tsuru/client/permission.go +++ b/tsuru/client/permission.go @@ -5,6 +5,7 @@ package client import ( + "context" "encoding/json" "errors" "fmt" @@ -15,6 +16,8 @@ import ( "strings" "github.com/tsuru/gnuflag" + tsuruClient "github.com/tsuru/go-tsuruclient/pkg/client" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tablecli" "github.com/tsuru/tsuru/cmd" "github.com/tsuru/tsuru/permission" @@ -228,28 +231,31 @@ func (c *RoleAdd) Flags() *gnuflag.FlagSet { return c.fs } -func (c *RoleAdd) Run(context *cmd.Context, client *cmd.Client) error { - roleName := context.Args[0] - contextType := context.Args[1] - description := c.description - params := url.Values{} - params.Set("name", roleName) - params.Set("context", contextType) - params.Set("description", description) - addr, err := cmd.GetURL("/roles") - if err != nil { - return err +func (c *RoleAdd) RoleSet(roleName, contextType, description string) tsuru.RoleAddData { + RoleAdd := tsuru.RoleAddData{ + Name: roleName, + Contexttype: contextType, + Description: description, } - request, err := http.NewRequest("POST", addr, strings.NewReader(params.Encode())) + return RoleAdd +} +func (c *RoleAdd) Run(ctx *cmd.Context, client *cmd.Client) error { + roleName := ctx.Args[0] + contextType := ctx.Args[1] + description := c.description + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + roleAdd := c.RoleSet(roleName, contextType, description) + _, err = apiClient.AuthApi.CreateRole(context.TODO(), roleAdd) + if err != nil { return err } - fmt.Fprintf(context.Stdout, "Role successfully created!\n") + fmt.Fprintf(ctx.Stdout, "Role successfully created!\n") return nil } @@ -306,27 +312,31 @@ func (c *RolePermissionAdd) Info() *cmd.Info { MinArgs: 2, } } - -func (c *RolePermissionAdd) Run(context *cmd.Context, client *cmd.Client) error { - roleName := context.Args[0] +func (c *RolePermissionAdd) RolePermAdd(rolename string, permission []string) tsuru.PermissionData { + rolePermAdd := tsuru.PermissionData{ + Name: rolename, + Permission: permission, + } + return rolePermAdd +} +func (c *RolePermissionAdd) Run(ctx *cmd.Context, client *cmd.Client) error { + roleName := ctx.Args[0] params := url.Values{} - for _, p := range context.Args[1:] { + for _, p := range ctx.Args[1:] { params.Add("permission", p) } - addr, err := cmd.GetURL(fmt.Sprintf("/roles/%s/permissions", roleName)) + rolePermAdd := c.RolePermAdd(roleName, params["permission"]) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request, err := http.NewRequest("POST", addr, strings.NewReader(params.Encode())) + _, err = apiClient.AuthApi.PermissionAdd(context.TODO(), roleName, rolePermAdd) if err != nil { return err } - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) - if err != nil { - return err - } - fmt.Fprintf(context.Stdout, "Permission successfully added!\n") + fmt.Fprintf(ctx.Stdout, "Permission successfully added!\n") return nil } @@ -370,13 +380,22 @@ func (c *RoleAssign) Info() *cmd.Info { MinArgs: 2, } } - -func (c *RoleAssign) Run(context *cmd.Context, client *cmd.Client) error { - roleName := context.Args[0] - roleTarget := context.Args[1] +func (c *RoleAssign) RoleAssignData(roleName, contextValue, roleTarget, suffix, version string) tsuru.RoleAssignData { + roleAdd := tsuru.RoleAssignData{ + Name: roleName, + Contextvalue: contextValue, + Roletarget: roleTarget, + Sufix: suffix, + Version: version, + } + return roleAdd +} +func (c *RoleAssign) Run(ctx *cmd.Context, client *cmd.Client) error { + roleName := ctx.Args[0] + roleTarget := ctx.Args[1] var contextValue string - if len(context.Args) > 2 { - contextValue = context.Args[2] + if len(ctx.Args) > 2 { + contextValue = ctx.Args[2] } params := url.Values{} var suffix, version string @@ -394,20 +413,19 @@ func (c *RoleAssign) Run(context *cmd.Context, client *cmd.Client) error { params.Set("token_id", roleTarget) } params.Set("context", contextValue) - addr, err := cmd.GetURLVersion(version, fmt.Sprintf("/roles/%s/%s", roleName, suffix)) - if err != nil { - return err - } - request, err := http.NewRequest("POST", addr, strings.NewReader(params.Encode())) + roleAssginAdd := c.RoleAssignData(roleName, contextValue, roleTarget, suffix, version) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + _, err = apiClient.AuthApi.RoleAssign(context.TODO(), roleName, roleAssginAdd) + if err != nil { return err } - fmt.Fprintf(context.Stdout, "Role successfully assigned!\n") + fmt.Fprintf(ctx.Stdout, "Role successfully assigned!\n") return nil } @@ -422,12 +440,12 @@ func (c *RoleDissociate) Info() *cmd.Info { } } -func (c *RoleDissociate) Run(context *cmd.Context, client *cmd.Client) error { - roleName := context.Args[0] - emailOrToken := context.Args[1] +func (c *RoleDissociate) Run(ctx *cmd.Context, client *cmd.Client) error { + roleName := ctx.Args[0] + emailOrToken := ctx.Args[1] var contextValue string - if len(context.Args) > 2 { - contextValue = context.Args[2] + if len(ctx.Args) > 2 { + contextValue = ctx.Args[2] } params := url.Values{} var suffix, version string @@ -439,20 +457,25 @@ func (c *RoleDissociate) Run(context *cmd.Context, client *cmd.Client) error { version = "1.6" } params.Set("context", contextValue) - addr, err := cmd.GetURLVersion(version, fmt.Sprintf("/roles/%s/%s?%s", roleName, suffix, params.Encode())) + resp, err := cmd.GetURLVersion(version, fmt.Sprintf("/roles/%s/%s?%s", roleName, suffix, params.Encode())) if err != nil { return err } - request, err := http.NewRequest(http.MethodDelete, addr, nil) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + if strings.Contains(emailOrToken, "@") { + _, err = apiClient.AuthApi.DissociateRole(context.TODO(), roleName, resp) + } else { + _, err = apiClient.AuthApi.DissociateRoleFromToken(context.TODO(), roleName, emailOrToken, contextValue) + } if err != nil { return err } - fmt.Fprintf(context.Stdout, "Role successfully dissociated!\n") + fmt.Fprintf(ctx.Stdout, "Role successfully dissociated!\n") return nil } @@ -521,32 +544,39 @@ func (c *RoleDefaultAdd) Info() *cmd.Info { info.Usage = fmt.Sprintf("%s %s", info.Usage, strings.Join(usage, " ")) return info } - -func (c *RoleDefaultAdd) Run(context *cmd.Context, client *cmd.Client) error { +func (c *RoleDefaultAdd) RoleDefAdd(roleMap map[string][]string) tsuru.RoleDefaultData { + userData := tsuru.RoleDefaultData{ + Rolesmap: roleMap, + } + return userData +} +func (c *RoleDefaultAdd) Run(ctx *cmd.Context, client *cmd.Client) error { params := url.Values{} for name, values := range c.roles { for _, val := range []string(*values) { params.Add(name, val) } } - encodedParams := params.Encode() - if encodedParams == "" { - return fmt.Errorf("You must choose which event to add default roles.") - } - addr, err := cmd.GetURL("/role/default") - if err != nil { - return err + rolname := []string{} + roleMap := make(map[string][]string) + for k := range params { + rolname = append(rolname, k) + for _, n := range params[k] { + roleMap[k] = append(roleMap[k], n) + } } - request, err := http.NewRequest("POST", addr, strings.NewReader(encodedParams)) + rolDef := c.RoleDefAdd(roleMap) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + _, err = apiClient.AuthApi.DefaultRoleAdd(context.TODO(), rolDef) if err != nil { return err } - fmt.Fprintf(context.Stdout, "Roles successfully added as default!\n") + fmt.Fprintf(ctx.Stdout, "Roles successfully added as default!\n") return nil } @@ -696,30 +726,36 @@ func (c *RoleUpdate) Flags() *gnuflag.FlagSet { } return c.fs } - -func (c *RoleUpdate) Run(context *cmd.Context, client *cmd.Client) error { +func (c *RoleUpdate) RoleUpdate(name string) tsuru.RoleUpdateData { + userData := tsuru.RoleUpdateData{ + Name: name, + ContextType: c.contextType, + Description: c.description, + NewName: c.newName, + } + return userData +} +func (c *RoleUpdate) Run(ctx *cmd.Context, client *cmd.Client) error { if (c.newName == "") && (c.description == "") && (c.contextType == "") { return errors.New("Neither the description, context or new name were set. You must define at least one.") } params := url.Values{} - params.Set("name", context.Args[0]) + params.Set("name", ctx.Args[0]) params.Set("newName", c.newName) params.Set("description", c.description) params.Set("contextType", c.contextType) - url, err := cmd.GetURLVersion("1.4", "/roles") - if err != nil { - return err - } - request, err := http.NewRequest("PUT", url, strings.NewReader(params.Encode())) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + roleUpdate := c.RoleUpdate(ctx.Args[0]) + _, err = apiClient.AuthApi.UpdateRole(context.TODO(), roleUpdate) if err != nil { - context.Stderr.Write([]byte("Failed to update role\n")) + ctx.Stderr.Write([]byte("Failed to update role\n")) return err } - context.Stdout.Write([]byte("Role successfully updated\n")) + ctx.Stdout.Write([]byte("Role successfully updated\n")) return nil } diff --git a/tsuru/client/permission_test.go b/tsuru/client/permission_test.go index d93dab520..520fca66c 100644 --- a/tsuru/client/permission_test.go +++ b/tsuru/client/permission_test.go @@ -6,11 +6,13 @@ package client import ( "bytes" + "encoding/json" "net/http" "reflect" "sort" "strings" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tsuru/cmd" "github.com/tsuru/tsuru/cmd/cmdtest" "gopkg.in/check.v1" @@ -69,8 +71,14 @@ func (s *S) TestRoleAddRun(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(""), Status: http.StatusCreated}, CondFunc: func(req *http.Request) bool { - return strings.HasSuffix(req.URL.Path, "/roles") && req.Method == http.MethodPost && - req.FormValue("name") == "myrole" && req.FormValue("context") == "app" + var rol tsuru.RoleAddData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleAddData{ + Name: "myrole", + Contexttype: "app", + }) + return strings.HasSuffix(req.URL.Path, "/roles") && req.Method == http.MethodPost }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) @@ -185,8 +193,17 @@ func (s *S) TestRoleAssignRun(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(""), Status: http.StatusCreated}, CondFunc: func(req *http.Request) bool { - return strings.HasSuffix(req.URL.Path, "/roles/myrole/user") && req.Method == http.MethodPost && - req.FormValue("email") == "me@me.com" && req.FormValue("context") == "myapp" + var rol tsuru.RoleAssignData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleAssignData{ + Name: "myrole", + Roletarget: "me@me.com", + Sufix: "user", + Version: "1.0", + Contextvalue: "myapp", + }) + return strings.HasSuffix(req.URL.Path, "/roles/myrole/user") && req.Method == http.MethodPost }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) @@ -206,10 +223,16 @@ func (s *S) TestRoleAssignRunWithToken(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(""), Status: http.StatusCreated}, CondFunc: func(req *http.Request) bool { - c.Assert(req.URL.Path, check.Equals, "/1.6/roles/myrole/token") - c.Assert(req.Method, check.Equals, http.MethodPost) - c.Assert(req.FormValue("token_id"), check.Equals, "mytoken") - c.Assert(req.FormValue("context"), check.Equals, "myapp") + var rol tsuru.RoleAssignData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleAssignData{ + Name: "myrole", + Roletarget: "mytoken", + Sufix: "token", + Version: "1.6", + Contextvalue: "myapp", + }) return true }, } @@ -230,10 +253,16 @@ func (s *S) TestRoleAssignRunWithGroup(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(""), Status: http.StatusCreated}, CondFunc: func(req *http.Request) bool { - c.Assert(req.URL.Path, check.Equals, "/1.9/roles/myrole/group") - c.Assert(req.Method, check.Equals, http.MethodPost) - c.Assert(req.FormValue("group_name"), check.Equals, "grp1") - c.Assert(req.FormValue("context"), check.Equals, "myapp") + var rol tsuru.RoleAssignData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleAssignData{ + Name: "myrole", + Roletarget: "group:grp1", + Sufix: "group", + Version: "1.9", + Contextvalue: "myapp", + }) return true }, } @@ -306,10 +335,13 @@ func (s *S) TestRolePermissionAddRun(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(""), Status: http.StatusCreated}, CondFunc: func(req *http.Request) bool { - req.ParseForm() - sort.Strings(req.Form["permission"]) + //req.ParseForm() + //sort.Strings(req.Form["permission"]) + var perm tsuru.PermissionData + err := json.NewDecoder(req.Body).Decode(&perm) + c.Assert(err, check.IsNil) return strings.HasSuffix(req.URL.Path, "/roles/myrole/permissions") && req.Method == http.MethodPost && - reflect.DeepEqual(req.Form["permission"], []string{"app.create", "app.deploy"}) + reflect.DeepEqual(perm.Permission, []string{"app.create", "app.deploy"}) }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) @@ -414,11 +446,14 @@ func (s *S) TestRoleDefaultAdd(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(""), Status: http.StatusCreated}, CondFunc: func(req *http.Request) bool { - req.ParseForm() - sort.Strings(req.Form["user-create"]) - return strings.HasSuffix(req.URL.Path, "/role/default") && req.Method == http.MethodPost && - reflect.DeepEqual(req.Form["user-create"], []string{"r1", "r2"}) && - reflect.DeepEqual(req.Form["team-create"], []string{"r3"}) + var rolDefault tsuru.RoleDefaultData + err := json.NewDecoder(req.Body).Decode(&rolDefault) + c.Assert(err, check.IsNil) + c.Assert(rolDefault, check.DeepEquals, tsuru.RoleDefaultData{ + Rolesmap: map[string][]string{"team-create": {"r3"}, + "user-create": {"r1", "r2"}}, + }) + return strings.HasSuffix(req.URL.Path, "/role/default") && req.Method == http.MethodPost }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) @@ -500,10 +535,19 @@ func (s *S) TestRoleUpdate(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { - path := req.URL.Path == "/1.4/roles" + path := req.URL.Path == "/1.0/roles" method := req.Method == http.MethodPut - contentType := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" - return path && method && contentType && req.FormValue("name") == "team-member" && req.FormValue("description") == "a developer" + contentType := req.Header.Get("Content-Type") == "application/json" + var rol tsuru.RoleUpdateData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleUpdateData{ + Name: "team-member", + ContextType: "", + Description: "a developer", + NewName: "", + }) + return path && method && contentType }, } manager := cmd.Manager{} @@ -528,8 +572,17 @@ func (s *S) TestRoleUpdateWithoutFlags(c *check.C) { CondFunc: func(req *http.Request) bool { path := strings.HasSuffix(req.URL.Path, "/roles") method := req.Method == http.MethodPut - contentType := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" - return path && method && contentType && req.FormValue("name") == "team-member" && req.FormValue("description") == "a developer" + contentType := req.Header.Get("Content-Type") == "application/json" + var rol tsuru.RoleUpdateData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleUpdateData{ + Name: "team-member", + ContextType: "", + Description: "a developer", + NewName: "", + }) + return path && method && contentType }, } manager := cmd.Manager{} @@ -552,8 +605,17 @@ func (s *S) TestRoleUpdateMultipleFlags(c *check.C) { CondFunc: func(req *http.Request) bool { path := strings.HasSuffix(req.URL.Path, "/roles") method := req.Method == http.MethodPut - contentType := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" - return path && method && contentType && req.FormValue("name") == "team-member" && req.FormValue("description") == "a developer" && req.FormValue("contextType") == "team" && req.FormValue("newName") == "newName" + contentType := req.Header.Get("Content-Type") == "application/json" + var rol tsuru.RoleUpdateData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleUpdateData{ + Name: "team-member", + ContextType: "team", + Description: "a developer", + NewName: "newName", + }) + return path && method && contentType }, } manager := cmd.Manager{} @@ -577,8 +639,15 @@ func (s *S) TestRoleUpdateWithInvalidContent(c *check.C) { CondFunc: func(req *http.Request) bool { path := strings.HasSuffix(req.URL.Path, "/roles") method := req.Method == http.MethodPut - contentType := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" - return path && method && contentType && req.FormValue("name") == "invalid-role" && req.FormValue("description") == "a developer" + contentType := req.Header.Get("Content-Type") == "application/json" + var rol tsuru.RoleUpdateData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleUpdateData{ + Name: "invalid-role", + Description: "a developer", + }) + return path && method && contentType }, } manager := cmd.Manager{} From 93fd277ecce57cfb954e1b42296eaac125073062 Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Fri, 13 Aug 2021 19:06:10 -0300 Subject: [PATCH 18/20] add: certificate and permission to client --- tsuru/client/certificate_test.go | 8 -------- tsuru/client/permission.go | 7 ++----- 2 files changed, 2 insertions(+), 13 deletions(-) diff --git a/tsuru/client/certificate_test.go b/tsuru/client/certificate_test.go index 0fabb1755..5a2b6cee5 100644 --- a/tsuru/client/certificate_test.go +++ b/tsuru/client/certificate_test.go @@ -10,7 +10,6 @@ import ( "io/ioutil" "net/http" "os" - "strconv" "strings" "time" @@ -21,13 +20,6 @@ import ( check "gopkg.in/check.v1" ) -func convert(b []byte) string { - s := make([]string, len(b)) - for i := range b { - s[i] = strconv.Itoa(int(b[i])) - } - return strings.Join(s, ",") -} func (s *S) TestCertificateSetRunSuccessfully(c *check.C) { var stdout, stderr bytes.Buffer context := cmd.Context{ diff --git a/tsuru/client/permission.go b/tsuru/client/permission.go index 14322e9e2..05aed14a6 100644 --- a/tsuru/client/permission.go +++ b/tsuru/client/permission.go @@ -557,14 +557,11 @@ func (c *RoleDefaultAdd) Run(ctx *cmd.Context, client *cmd.Client) error { params.Add(name, val) } } - rolname := []string{} roleMap := make(map[string][]string) for k := range params { - rolname = append(rolname, k) - for _, n := range params[k] { - roleMap[k] = append(roleMap[k], n) - } + roleMap[k] = append(roleMap[k], params[k]...) } + rolDef := c.RoleDefAdd(roleMap) apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ HTTPClient: client.HTTPClient, From 8d5a611ce9df84c6f433e6e79e5fdeb32cc7f144 Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Tue, 19 Oct 2021 16:49:07 -0300 Subject: [PATCH 19/20] refactor: form to json --- .vscode/launch.json | 7 ------- tsuru/client/auth.go | 3 --- tsuru/client/permission.go | 2 +- 3 files changed, 1 insertion(+), 11 deletions(-) delete mode 100644 .vscode/launch.json diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 5c7247b40..000000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [] -} \ No newline at end of file diff --git a/tsuru/client/auth.go b/tsuru/client/auth.go index 6acba8fad..2c17f1ed3 100644 --- a/tsuru/client/auth.go +++ b/tsuru/client/auth.go @@ -74,16 +74,13 @@ func (c *UserCreate) Run(ctx *cmd.Context, client *cmd.Client) error { if err != nil { return err } - if response != nil { if response.StatusCode == http.StatusNotFound || response.StatusCode == http.StatusMethodNotAllowed { return errors.New("User creation is disabled.") } } - err = cmd.StreamJSONResponse(ctx.Stdout, response) - if err != nil { return err } diff --git a/tsuru/client/permission.go b/tsuru/client/permission.go index 05aed14a6..866d63c27 100644 --- a/tsuru/client/permission.go +++ b/tsuru/client/permission.go @@ -618,7 +618,7 @@ func (c *RoleDefaultRemove) Run(context *cmd.Context, client *cmd.Client) error } encodedParams := params.Encode() if encodedParams == "" { - return fmt.Errorf("You must choose which event to remove default roles.") + return fmt.Errorf("You must choose which event to remove default roles") } addr, err := cmd.GetURL(fmt.Sprintf("/role/default?%s", encodedParams)) if err != nil { From 811c43b1b2d65301134a48c719c99556cf722cda Mon Sep 17 00:00:00 2001 From: Carlos Roberto Date: Wed, 20 Oct 2021 12:31:15 -0300 Subject: [PATCH 20/20] refactor: json to form --- go.mod | 4 ++-- go.sum | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/go.mod b/go.mod index 7439968e3..d93c80622 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,7 @@ require ( github.com/containerd/containerd v1.4.1 // indirect github.com/digitalocean/godo v1.1.1 // indirect github.com/docker/distribution v2.7.1+incompatible // indirect - github.com/docker/docker v20.10.2+incompatible + github.com/docker/docker v20.10.9+incompatible github.com/docker/go-connections v0.4.0 github.com/docker/machine v0.16.1 github.com/exoscale/egoscale v0.9.31 // indirect @@ -21,7 +21,7 @@ require ( github.com/sethvargo/go-password v0.1.1 github.com/tsuru/config v0.0.0-20201023175036-375aaee8b560 github.com/tsuru/gnuflag v0.0.0-20151217162021-86b8c1b864aa - github.com/tsuru/go-tsuruclient v0.0.0-20210813191311-aa50779317a0 + github.com/tsuru/go-tsuruclient v0.0.0-20210820124232-e0cdf446d41d github.com/tsuru/tablecli v0.0.0-20190131152944-7ded8a3383c6 github.com/tsuru/tsuru v0.0.0-20210706143918-b89a484dc93f golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee diff --git a/go.sum b/go.sum index e50c333fe..87adec1d0 100644 --- a/go.sum +++ b/go.sum @@ -440,6 +440,8 @@ github.com/tsuru/go-tsuruclient v0.0.0-20210726185852-a34d558923df h1:EcC/XZqcMW github.com/tsuru/go-tsuruclient v0.0.0-20210726185852-a34d558923df/go.mod h1:P2AL93lzpzJlgOvu37SOhee4pnLWod1GMJ8YYQq2b7o= github.com/tsuru/go-tsuruclient v0.0.0-20210813191311-aa50779317a0 h1:RQ5VuJs7sHVCjGiibwkbml4mlxCmJxowTcldXbg/eQo= github.com/tsuru/go-tsuruclient v0.0.0-20210813191311-aa50779317a0/go.mod h1:P2AL93lzpzJlgOvu37SOhee4pnLWod1GMJ8YYQq2b7o= +github.com/tsuru/go-tsuruclient v0.0.0-20210820124232-e0cdf446d41d h1:ba6b5LWPGQZrwputbBvrn58zI8P927BwZ7VRu6bU8R4= +github.com/tsuru/go-tsuruclient v0.0.0-20210820124232-e0cdf446d41d/go.mod h1:P2AL93lzpzJlgOvu37SOhee4pnLWod1GMJ8YYQq2b7o= github.com/tsuru/monsterqueue v0.0.0-20160909010522-70e946ec66c3 h1:+aJngj5cQjYyx/qSjffQceop25t97hLS0+t8bvx9hg4= github.com/tsuru/monsterqueue v0.0.0-20160909010522-70e946ec66c3/go.mod h1:3KR1vkjfm5b7Lhu5OXuO0NMIyZNG0d0d9xh6ufWYVxg= github.com/tsuru/tablecli v0.0.0-20180215113938-82de88f75181/go.mod h1:ztYpOhW+u1k21FEqp7nZNgpWbr0dUKok5lgGCZi+1AQ=