Skip to content

Commit 1b01d5b

Browse files
author
Samuel Vandamme
committed
+ Upgrade to latest version
1 parent 66e0088 commit 1b01d5b

File tree

6 files changed

+125
-25
lines changed

6 files changed

+125
-25
lines changed

src/coscale/api/api.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ type LoginData struct {
198198
}
199199

200200
// Login to the Api, returns the token and an error.
201-
func (api *Api) login() error {
201+
func (api *Api) Login() error {
202202

203203
data := map[string][]string{
204204
"accessToken": {api.accessToken},
@@ -222,7 +222,7 @@ func (api *Api) login() error {
222222
func (api *Api) makeRawCall(method string, uri string, data map[string][]string, timeout time.Duration) ([]byte, error) {
223223
// Not authenticated yet, try login.
224224
if api.token == "" {
225-
if err := api.login(); err != nil {
225+
if err := api.Login(); err != nil {
226226
return nil, err
227227
}
228228
}
@@ -233,7 +233,7 @@ func (api *Api) makeRawCall(method string, uri string, data map[string][]string,
233233
if _, ok := err.(UnauthorizedError); ok {
234234
// unauthorizedError: the token might have experied. Performing login again
235235
// and retrying the request.
236-
if err := api.login(); err != nil {
236+
if err := api.Login(); err != nil {
237237
api.token = ""
238238
return nil, err
239239
}

src/coscale/api/event.go

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
package api
22

3-
import (
4-
"fmt"
5-
"time"
6-
)
3+
import "fmt"
74

85
type Event struct {
96
ID int64
@@ -62,11 +59,10 @@ func (api *Api) DeleteEvent(event *Event) error {
6259
}
6360

6461
func (api *Api) InsertEventData(id int64, message, subject, attribute string, timestamp, stopTime int64) (string, error) {
65-
now := int64(time.Now().Unix())
6662
data := map[string][]string{
6763
"message": {message},
68-
"timestamp": {fmt.Sprintf("%d", timestamp - now)},
69-
"stopTime": {fmt.Sprintf("%d", stopTime - now)},
64+
"timestamp": {fmt.Sprintf("%d", timestamp)},
65+
"stopTime": {fmt.Sprintf("%d", stopTime)},
7066
"subject": {subject},
7167
"attribute": {attribute},
7268
}

src/coscale/cli.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
"os"
77
)
88

9-
//main command of Coscale cli-cmd
9+
//main command of Coscale coscale-cli
1010
func main() {
1111

1212
var subCommands = []*command.Command{
@@ -17,6 +17,7 @@ func main() {
1717
command.MetricGroupObject,
1818
command.DataObject,
1919
command.AlertObject,
20+
command.CheckObject,
2021
}
2122
var usage = os.Args[0] + ` <object> <action> [--<field>='<data>']`
2223
var app = command.NewCommand(os.Args[0], usage, subCommands)

src/coscale/command/check.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package command
2+
3+
import (
4+
"coscale/api"
5+
"os"
6+
)
7+
8+
// CheckObjectName is the name of the check-config subcommand
9+
var CheckObjectName = "check-config"
10+
11+
// CheckObject is the check-config subcommand and is used to check to api configuration
12+
var CheckObject = &Command{
13+
Name: CheckObjectName,
14+
UsageLine: `check-config is used to check to api configuration file`,
15+
Run: func(cmd *Command, args []string) {
16+
// check for getting the config file path
17+
file, err := GetConfigPath()
18+
if err != nil {
19+
cmd.PrintResult("", err)
20+
}
21+
// check if the file actually exists
22+
if _, err := os.Stat(file); err != nil {
23+
cmd.PrintResult("", err)
24+
}
25+
// check if the configuration file can be parsed
26+
config, err := api.ReadApiConfiguration(file)
27+
if err != nil {
28+
cmd.PrintResult("", err)
29+
}
30+
// check if we can loggin with this configuration
31+
api := api.NewApi(config.BaseUrl, config.AccessToken, config.AppId, false)
32+
err = api.Login()
33+
if err != nil {
34+
cmd.PrintResult("", err)
35+
}
36+
cmd.PrintResult(`{"msg":"Configuration successfuly checked!"}`, nil)
37+
},
38+
}

src/coscale/command/command.go

Lines changed: 72 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
11
package command
22

33
import (
4+
"bytes"
45
"coscale/api"
6+
"errors"
57
"flag"
68
"fmt"
79
"io"
810
"os"
11+
"os/exec"
912
"path/filepath"
13+
"runtime"
1014
"strings"
1115
"text/template"
16+
"time"
1217
"unicode"
1318
"unicode/utf8"
1419
)
@@ -102,14 +107,14 @@ func (c *Command) PrintUsage() {
102107
os.Exit(2)
103108
}
104109

105-
//return a Api object
110+
// GetApi returns a Api object
106111
func (c *Command) GetApi(baseUrl, accessToken, appId string, rawOutput bool) *api.Api {
107112
if accessToken == "" || appId == "" {
108-
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
113+
configPath, err := GetConfigPath()
109114
if err != nil {
110115
os.Exit(EXIT_FLAG_ERROR)
111116
}
112-
config, err := api.ReadApiConfiguration(dir + "/api.conf")
117+
config, err := api.ReadApiConfiguration(configPath)
113118
if err != nil {
114119
c.PrintUsage()
115120
}
@@ -142,26 +147,27 @@ func (c *Command) ParseArgs(args []string) {
142147

143148
func (c *Command) PrintResult(result string, err error) {
144149
if err == nil {
145-
fmt.Fprint(os.Stdout, result)
150+
fmt.Fprintln(os.Stdout, result)
146151
os.Exit(EXIT_SUCCESS)
147152
} else if api.IsAuthenticationError(err) {
148-
fmt.Fprint(os.Stderr, `{"msg":"Authentication failed!"}`)
153+
fmt.Fprintln(os.Stderr, `{"msg":"Authentication failed!"}`)
149154
os.Exit(EXIT_AUTHENTICATION_ERROR)
150155
} else {
151-
fmt.Fprintf(os.Stderr, GetErrorJson(err))
156+
fmt.Fprintln(os.Stderr, GetErrorJson(err))
152157
os.Exit(EXIT_SUCCESS_ERROR)
153158
}
154159
}
155160

156161
// GetErrorJson return only the json string from a error message from api
157162
func GetErrorJson(err error) string {
158-
if strings.Index(err.Error(), `{`) > -1 {
163+
index := strings.Index(err.Error(), `{`)
164+
if index > -1 {
159165
return err.Error()[strings.Index(err.Error(), `{`):]
160166
}
161-
return err.Error()
167+
return fmt.Sprintf(`{"msg":"%s"}`, err.Error())
162168
}
163169

164-
var usageTemplate = `cli-cmd a tool for CoScale Api.
170+
var usageTemplate = `coscale-cli a tool for CoScale Api.
165171
166172
Usage:
167173
{{.UsageLine}}
@@ -178,16 +184,68 @@ Usage:
178184
The json objects are returned formatted by default, but can be returned on 1 line by using:
179185
--rawOutput
180186
181-
The CoScale api configuration (authentication) by default will be taken from api.conf file,
182-
placed in the same folder with the cli-cmd. api.conf file it is the same configuration file
183-
used by the CoScale agent. If the api.conf file doesn't exists, the informations also can be
184-
provided on the command line using:
187+
By default the CoScale api credentials (authentication) will be taken from api.conf
188+
located in the same directory as the coscale-cli binary. If the file does not exist,
189+
the credentials can also be provided on the command line using:
185190
--api-url
186191
Base url for the api (optional, default = "https://api.coscale.com/").
187192
--app-id
188193
The application id.
189194
--access-token
190195
A valid access token for the given application.
191196
192-
Use "cli-cmd [object] <help>" for more information about a command.
197+
Use "coscale-cli [object] <help>" for more information about a command.
193198
`
199+
200+
// GetConfigPath is used to return the absolut path of the api configuration file
201+
func GetConfigPath() (string, error) {
202+
configFile := "/api.conf"
203+
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
204+
if err != nil {
205+
os.Exit(EXIT_FLAG_ERROR)
206+
}
207+
configPath := dir + configFile
208+
if _, err := os.Stat(configPath); err == nil {
209+
return configPath, nil
210+
}
211+
var cmdName string
212+
if runtime.GOOS == "windows" {
213+
cmdName = "where"
214+
} else {
215+
cmdName = "which"
216+
}
217+
response, err := GetCommandOutput(cmdName, 2*time.Second, os.Args[0])
218+
path := bytes.Split(response, []byte("\n"))[0]
219+
if err != nil {
220+
return "", err
221+
}
222+
return filepath.Dir(string(path)) + configFile, nil
223+
}
224+
225+
// GetCommandOutput returns stdout of command as a string
226+
func GetCommandOutput(command string, timeout time.Duration, arg ...string) ([]byte, error) {
227+
var err error
228+
var stdOut bytes.Buffer
229+
var stdErr bytes.Buffer
230+
var c = make(chan []byte)
231+
cmd := exec.Command(command, arg...)
232+
cmd.Stdout = &stdOut
233+
cmd.Stderr = &stdErr
234+
if err = cmd.Start(); err != nil {
235+
return nil, fmt.Errorf("%s %s", err.Error(), stdErr.String())
236+
}
237+
go func() {
238+
err = cmd.Wait()
239+
c <- stdOut.Bytes()
240+
}()
241+
time.AfterFunc(timeout, func() {
242+
cmd.Process.Kill()
243+
err = errors.New("Maxruntime exceeded")
244+
c <- nil
245+
})
246+
response := <-c
247+
if err != nil {
248+
fmt.Errorf("%s %s", err.Error(), stdErr.String())
249+
}
250+
return response, nil
251+
}

src/coscale/command/event.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,13 @@ Optional:
167167
if err != nil {
168168
cmd.PrintResult("", err)
169169
}
170+
// be sure that the time values are negative
171+
if timestamp > 0 {
172+
timestamp = -timestamp
173+
}
174+
if stopTime > 0 {
175+
stopTime = -stopTime
176+
}
170177
cmd.PrintResult(cmd.Capi.InsertEventData(eventObj.ID, message, subject, attribute, timestamp, stopTime))
171178
},
172179
},

0 commit comments

Comments
 (0)