Skip to content

Commit 66cf741

Browse files
cristianciuteafryckbos
authored andcommitted
Added get server group by path (#14)
* added get server group by path
1 parent 7c23937 commit 66cf741

File tree

11 files changed

+164
-51
lines changed

11 files changed

+164
-51
lines changed

src/coscale/api/api.go

Lines changed: 36 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -129,21 +129,25 @@ type Api struct {
129129
// AccessToken is a UUID giving access permissions on the application.
130130
AccessToken string
131131
// AppID is a UUID defining the application.
132-
AppID string
133-
rawOutput bool
134-
token string
132+
AppID string
133+
rawOutput bool
134+
token string
135+
// Set aditional query parameters.
136+
query string
135137
validConfig bool
138+
// Print aditional util information.
139+
verbose bool
136140
}
137141

138142
// NewApi creates a new Api connector using an email and a password.
139-
func NewApi(baseUrl string, accessToken string, appID string, rawOutput bool) *Api {
140-
api := &Api{baseUrl, accessToken, appID, rawOutput, "", true}
143+
func NewApi(baseUrl string, accessToken string, appID string, rawOutput, verbose bool) *Api {
144+
api := &Api{baseUrl, accessToken, appID, rawOutput, "", "", true, verbose}
141145
return api
142146
}
143147

144148
// NewFakeApi creates a new Api connector using an email and a password.
145149
func NewFakeApi() *Api {
146-
api := &Api{"", "", "", true, "", false}
150+
api := &Api{"", "", "", true, "", "", false, false}
147151
return api
148152
}
149153

@@ -185,9 +189,21 @@ type RequestErrorResponse struct {
185189

186190
// Do an http request.
187191
func (api *Api) doHttpRequest(method string, uri string, token string, data map[string][]string, timeout time.Duration) ([]byte, error) {
192+
if method == "GET" && len(api.query) > 0 {
193+
if strings.ContainsAny(uri, "?") {
194+
uri = fmt.Sprintf("%s&%s", uri, api.query)
195+
} else {
196+
uri = fmt.Sprintf("%s?%s", uri, api.query)
197+
}
198+
}
188199
requestBody := url.Values(data).Encode()
189200
req, err := http.NewRequest(method, uri, strings.NewReader(requestBody))
190201

202+
// Print the requested url.
203+
if api.verbose {
204+
fmt.Println(method, uri)
205+
}
206+
191207
if err != nil {
192208
return nil, err
193209
}
@@ -236,6 +252,12 @@ func (api *Api) doHttpRequest(method string, uri string, token string, data map[
236252
return body, nil
237253
}
238254

255+
// SetQueryString set aditional query parameters only for the next call.
256+
func (api *Api) SetQueryString(query string) {
257+
// URL Encoded.
258+
api.query = query
259+
}
260+
239261
// LoginData contains the required fields for the login API function.
240262
type LoginData struct {
241263
// Token should contain the AccessToken.
@@ -300,22 +322,27 @@ func (api *Api) makeCall(method string, uri string, data map[string][]string, js
300322
if err != nil {
301323
return err
302324
}
325+
return api.HandleResponse(b, jsonOut, target)
326+
}
327+
328+
// HandleResponse is used the Handle the response from the API.
329+
func (api *Api) HandleResponse(response []byte, jsonOut bool, target interface{}) error {
303330
if target != nil {
304331
if jsonOut {
305332
//if the output will be json, check if we need to format it or no
306333
var result string
307334
if api.rawOutput {
308-
result = string(b)
335+
result = string(response)
309336
} else {
310337
var out bytes.Buffer
311-
json.Indent(&out, b, "", " ")
338+
json.Indent(&out, response, "", " ")
312339
result = out.String()
313340
}
314341
if t, ok := target.(*string); ok {
315342
*t = result
316343
}
317344
} else {
318-
return json.Unmarshal(b, target)
345+
return json.Unmarshal(response, target)
319346
}
320347
}
321348
return nil

src/coscale/api/common.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,8 @@ func (api *Api) GetObjectByName(objectName string, name string) (string, error)
6363
return result, nil
6464
}
6565

66-
// GetObejctRefByName will put in result a reference to the oject specified by objectName and name
67-
func (api *Api) GetObejctRefByName(objectName string, name string, result Object) error {
66+
// GetObjectRefByName will put in result a reference to the oject specified by objectName and name
67+
func (api *Api) GetObjectRefByName(objectName string, name string, result Object) error {
6868
// URL Encoded.
6969
name = url.QueryEscape(name)
7070

@@ -79,8 +79,8 @@ func (api *Api) GetObejctRefByName(objectName string, name string, result Object
7979
return nil
8080
}
8181

82-
// GetObejctRefByNameFromGroup will return the object specified by objectName from objectGroup that have a certain name
83-
func (api *Api) GetObejctRefByNameFromGroup(objectGroup, objectName string, groupID int64, name string, result Object) error {
82+
// GetObjectRefByNameFromGroup will return the object specified by objectName from objectGroup that have a certain name
83+
func (api *Api) GetObjectRefByNameFromGroup(objectGroup, objectName string, groupID int64, name string, result Object) error {
8484
// URL Encoded.
8585
name = url.QueryEscape(name)
8686

src/coscale/api/server.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package api
33
import (
44
"fmt"
55
"strconv"
6+
"strings"
67
)
78

89
// Server describes the server object on the API.
@@ -83,6 +84,48 @@ func (api *Api) UpdateServer(server *Server) (string, error) {
8384
return api.GetObject("server", server.ID)
8485
}
8586

87+
// GetServerGroupByPath returns a server group by the hierarchy.
88+
func (api *Api) GetServerGroupByPath(path string) (string, error) {
89+
90+
var serverGroup *ServerGroup
91+
92+
groupNames := strings.Split(path, "/")
93+
for i, groupName := range groupNames {
94+
95+
var query string
96+
97+
if i == 0 {
98+
query = "selectByRoot=true"
99+
} else if serverGroup != nil && serverGroup.ID > 0 {
100+
query = fmt.Sprintf("selectByParent_id=%d", serverGroup.ID)
101+
} else {
102+
return "[]", nil
103+
}
104+
105+
api.SetQueryString(query)
106+
result, err := api.GetObjectByName("servergroup", groupName)
107+
if err != nil {
108+
return "", err
109+
}
110+
// For the last group just return it.
111+
if i == len(groupNames)-1 {
112+
return result, nil
113+
}
114+
115+
tmp := make([]*ServerGroup, 1)
116+
err = api.HandleResponse([]byte(result), false, &tmp)
117+
if err != nil {
118+
return "", err
119+
}
120+
if len(tmp) != 1 {
121+
return "[]", nil
122+
}
123+
serverGroup = tmp[0]
124+
}
125+
126+
return "[]", nil
127+
}
128+
86129
// CreateServerGroup creates a new ServerGroup using the API.
87130
func (api *Api) CreateServerGroup(name, description, Type, state string, parentID int64) (string, error) {
88131
data := map[string][]string{

src/coscale/command/alert.go

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ Optional:
265265
if id != -1 {
266266
err = cmd.Capi.GetObjectRef("alerttype", id, alertTypeObj)
267267
} else if name != DEFAULT_STRING_FLAG_VALUE {
268-
err = cmd.Capi.GetObejctRefByName("alerttype", name, alertTypeObj)
268+
err = cmd.Capi.GetObjectRefByName("alerttype", name, alertTypeObj)
269269
} else {
270270
cmd.PrintUsage()
271271
os.Exit(EXIT_FLAG_ERROR)
@@ -357,7 +357,7 @@ Mandatory:
357357
if id != -1 {
358358
cmd.PrintResult(cmd.Capi.GetTriggers(id))
359359
} else if name != DEFAULT_STRING_FLAG_VALUE {
360-
err = cmd.Capi.GetObejctRefByName("alerttype", name, alertTypeObj)
360+
err = cmd.Capi.GetObjectRefByName("alerttype", name, alertTypeObj)
361361
} else {
362362
cmd.PrintUsage()
363363
os.Exit(EXIT_FLAG_ERROR)
@@ -449,7 +449,7 @@ Optional:
449449
var metricObj = &api.Metric{}
450450
var err error
451451
if metricID == -1 {
452-
err = cmd.Capi.GetObejctRefByName("metric", metric, metricObj)
452+
err = cmd.Capi.GetObjectRefByName("metric", metric, metricObj)
453453
if err != nil {
454454
cmd.PrintResult("", err)
455455
}
@@ -460,7 +460,7 @@ Optional:
460460
// Get the server id
461461
var serverObj = &api.Server{}
462462
if serverID == -1 && server != DEFAULT_STRING_FLAG_VALUE {
463-
err = cmd.Capi.GetObejctRefByName("server", server, serverObj)
463+
err = cmd.Capi.GetObjectRefByName("server", server, serverObj)
464464
if err != nil {
465465
cmd.PrintResult("", err)
466466
}
@@ -471,7 +471,7 @@ Optional:
471471
// Get the servergroup id
472472
var serverGroupObj = &api.ServerGroup{}
473473
if serverGroupID == -1 && serverGroup != DEFAULT_STRING_FLAG_VALUE {
474-
err = cmd.Capi.GetObejctRefByName("servergroup", serverGroup, serverGroupObj)
474+
err = cmd.Capi.GetObjectRefByName("servergroup", serverGroup, serverGroupObj)
475475
if err != nil {
476476
cmd.PrintResult("", err)
477477
}
@@ -485,7 +485,7 @@ Optional:
485485
// get the alert type for the trigger
486486
var alertTypeObj = &api.AlertType{}
487487
if typeID == -1 {
488-
err = cmd.Capi.GetObejctRefByName("alerttype", typeName, alertTypeObj)
488+
err = cmd.Capi.GetObjectRefByName("alerttype", typeName, alertTypeObj)
489489
if err != nil {
490490
cmd.PrintResult("", err)
491491
}
@@ -580,7 +580,7 @@ Optional:
580580
var metricObj = &api.Metric{}
581581
var err error
582582
if metricID == -1 && metric != DEFAULT_STRING_FLAG_VALUE {
583-
err = cmd.Capi.GetObejctRefByName("metric", metric, metricObj)
583+
err = cmd.Capi.GetObjectRefByName("metric", metric, metricObj)
584584
if err != nil {
585585
cmd.PrintResult("", err)
586586
}
@@ -591,7 +591,7 @@ Optional:
591591
// Get the server id
592592
var serverObj = &api.Server{}
593593
if serverID == -1 && server != DEFAULT_STRING_FLAG_VALUE {
594-
err = cmd.Capi.GetObejctRefByName("server", server, serverObj)
594+
err = cmd.Capi.GetObjectRefByName("server", server, serverObj)
595595
if err != nil {
596596
cmd.PrintResult("", err)
597597
}
@@ -602,7 +602,7 @@ Optional:
602602
// Get the servergroup id
603603
var serverGroupObj = &api.ServerGroup{}
604604
if serverGroupID == -1 && serverGroup != DEFAULT_STRING_FLAG_VALUE {
605-
err = cmd.Capi.GetObejctRefByName("servergroup", serverGroup, serverGroupObj)
605+
err = cmd.Capi.GetObjectRefByName("servergroup", serverGroup, serverGroupObj)
606606
if err != nil {
607607
cmd.PrintResult("", err)
608608
}
@@ -613,7 +613,7 @@ Optional:
613613
// get the alert type for the trigger
614614
var alertTypeObj = &api.AlertType{}
615615
if typeID == -1 {
616-
err = cmd.Capi.GetObejctRefByName("alerttype", typeName, alertTypeObj)
616+
err = cmd.Capi.GetObjectRefByName("alerttype", typeName, alertTypeObj)
617617
if err != nil {
618618
cmd.PrintUsage()
619619
os.Exit(EXIT_FLAG_ERROR)
@@ -627,7 +627,7 @@ Optional:
627627
if id != -1 {
628628
err = cmd.Capi.GetObjectRefFromGroup("alerttype", "trigger", typeID, id, alertTriggerObj)
629629
} else if name != DEFAULT_STRING_FLAG_VALUE {
630-
err = cmd.Capi.GetObejctRefByNameFromGroup("alerttype", "trigger", typeID, name, alertTriggerObj)
630+
err = cmd.Capi.GetObjectRefByNameFromGroup("alerttype", "trigger", typeID, name, alertTriggerObj)
631631
} else {
632632
cmd.PrintUsage()
633633
os.Exit(EXIT_FLAG_ERROR)
@@ -713,7 +713,7 @@ Mandatory:
713713
// get the alert type for the trigger
714714
var alertTypeObj = &api.AlertType{}
715715
if typeID == -1 {
716-
err = cmd.Capi.GetObejctRefByName("alerttype", Type, alertTypeObj)
716+
err = cmd.Capi.GetObjectRefByName("alerttype", Type, alertTypeObj)
717717
if err != nil {
718718
cmd.PrintResult("", err)
719719
}
@@ -724,7 +724,7 @@ Mandatory:
724724
// Get the existing trigger.
725725
var alertTriggerObj = &api.AlertTrigger{}
726726
if id == -1 {
727-
err = cmd.Capi.GetObejctRefByNameFromGroup("alerttype", "trigger", typeID, name, alertTriggerObj)
727+
err = cmd.Capi.GetObjectRefByNameFromGroup("alerttype", "trigger", typeID, name, alertTriggerObj)
728728
if err != nil {
729729
cmd.PrintResult("", err)
730730
}

src/coscale/command/check.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ var CheckObject = &Command{
2828
cmd.PrintResult("", err)
2929
}
3030
// check if we can loggin with this configuration
31-
api := api.NewApi(config.BaseUrl, config.AccessToken, config.AppId, false)
31+
api := api.NewApi(config.BaseUrl, config.AccessToken, config.AppId, false, false)
3232
err = api.Login()
3333
if err != nil {
3434
cmd.PrintResult("", err)

src/coscale/command/command.go

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ func (c *Command) PrintFullUsage() {
131131
}
132132

133133
// GetApi returns a Api object
134-
func (c *Command) GetApi(baseUrl, accessToken, appId string, rawOutput bool) *api.Api {
134+
func (c *Command) GetApi(baseUrl, accessToken, appId string, rawOutput, verbose bool) *api.Api {
135135
if accessToken == "" || appId == "" {
136136
configPath, err := GetConfigPath()
137137
if err != nil {
@@ -145,25 +145,27 @@ func (c *Command) GetApi(baseUrl, accessToken, appId string, rawOutput bool) *ap
145145
accessToken = config.AccessToken
146146
appId = config.AppId
147147
}
148-
return api.NewApi(baseUrl, accessToken, appId, rawOutput)
148+
return api.NewApi(baseUrl, accessToken, appId, rawOutput, verbose)
149149
}
150150

151151
// ParseArgs takes the API configuration from the args and stores them in the Command.
152152
func (c *Command) ParseArgs(args []string) {
153153
//add the flags for the api configuration
154154
var baseUrl, accessToken, appId string
155-
var rawOutput bool
155+
var rawOutput, verbose bool
156156
c.Flag.StringVar(&baseUrl, "api-url", "https://api.coscale.com", "Base url for the api.")
157157
c.Flag.StringVar(&appId, "app-id", "", "The application id.")
158158
c.Flag.StringVar(&accessToken, "access-token", "", "A valid access token for the given application.")
159159
c.Flag.BoolVar(&rawOutput, "rawOutput", false, "The returned json objects are returned formatted by default.")
160+
c.Flag.BoolVar(&verbose, "verbose", false, "Print the URLs of the API calls.")
161+
160162
c.Flag.Parse(args)
161163
unknownArgs := c.Flag.Args()
162164
if len(unknownArgs) > 0 && unknownArgs[0] != "help" {
163165
fmt.Fprintf(os.Stderr, "Unknown field %s\n", unknownArgs[0])
164166
os.Exit(EXIT_FLAG_ERROR)
165167
}
166-
c.Capi = c.GetApi(strings.Trim(baseUrl, "/"), accessToken, appId, rawOutput)
168+
c.Capi = c.GetApi(strings.Trim(baseUrl, "/"), accessToken, appId, rawOutput, verbose)
167169
}
168170

169171
// PrintResult formats the result or error and exits the process with the appropriate exit code.
@@ -206,14 +208,18 @@ the credentials can also be provided on the command line using:
206208
The application id.
207209
--access-token
208210
A valid access token for the given application.
211+
212+
213+
--verbose
214+
Print the URLs of the API calls.
209215
`
210216

211217
var usageTemplate = `coscale-cli a tool for CoScale Api.
212218
213219
Usage:
214220
{{.UsageLine}}
215221
{{if .Runnable}}
216-
{{.Name | printf "Action \"%s\" usage:"}}
222+
{{.Name | printf "Action \"%s\" usage:"}}
217223
218224
{{.Long | trim}}{{else}}
219225
{{.Name | printf "Actions for command \"%s\":"}}

0 commit comments

Comments
 (0)