1 // xds-cli: command line tool used to control / interface X(cross) Development System.
12 "github.com/Sirupsen/logrus"
13 common "github.com/iotbzh/xds-common/golib"
14 socketio_client "github.com/sebd71/go-socket.io-client"
15 "github.com/urfave/cli"
18 var appAuthors = []cli.Author{
19 cli.Author{Name: "Sebastien Douheret", Email: "sebastien@iot.bzh"},
22 // AppName name of this application
23 var AppName = "xds-cli"
25 // AppNativeName native command name that this application can overload
26 var AppNativeName = "cli"
28 // AppVersion Version of this application
30 var AppVersion = "?.?.?"
32 // AppSubVersion is the git tag id added to version string
33 // Should be set by compilation -ldflags "-X main.AppSubVersion=xxx"
35 var AppSubVersion = "unknown-dev"
37 // Application details
39 appCopyright = "Apache-2.0"
40 defaultLogLevel = "error"
43 // Log Global variable that hold logger
44 var Log = logrus.New()
46 // HTTPCli Global variable that hold HTTP Client
47 var HTTPCli *common.HTTPClient
49 // IOsk Global variable that hold SocketIo client
50 var IOsk *socketio_client.Client
52 // exitError exists this program with the specified error
53 func exitError(code int, f string, a ...interface{}) {
54 err := fmt.Sprintf(f, a...)
55 fmt.Fprintf(os.Stderr, err+"\n")
62 // Allow to set app name from cli (useful for debugging)
64 AppName = os.Getenv("XDS_APPNAME")
67 panic("Invalid setup, AppName not define !")
69 if AppNativeName == "" {
70 AppNativeName = AppName[4:]
72 appUsage := fmt.Sprintf("command line tool for X(cross) Development System.")
73 appDescription := fmt.Sprintf("%s utility for X(cross) Development System\n", AppName)
76 xds-cli configuration is driven either by environment variables or by command line
77 options or using a config file knowning that the following priority order is used:
78 1. use option value (for example use project ID set by --id option),
79 2. else use variable 'XDS_xxx' (for example 'XDS_PROJECT_ID' variable) when a
80 config file is specified with '--config|-c' option,
81 3. else use 'XDS_xxx' (for example 'XDS_PROJECT_ID') environment variable.
84 // Create a new App instance
88 app.Version = AppVersion + " (" + AppSubVersion + ")"
89 app.Authors = appAuthors
90 app.Copyright = appCopyright
91 app.Metadata = make(map[string]interface{})
92 app.Metadata["version"] = AppVersion
93 app.Metadata["git-tag"] = AppSubVersion
94 app.Metadata["logger"] = Log
96 // Create env vars help
97 dynDesc := "\nENVIRONMENT VARIABLES:"
98 for _, f := range app.Flags {
102 fs := f.(cli.StringFlag)
106 fb := f.(cli.BoolFlag)
110 exitError(1, "Un-implemented option type")
113 dynDesc += fmt.Sprintf("\n %s \t\t %s", env, usage)
116 app.Description = appDescription + dynDesc
118 // Declare global flags
119 app.Flags = []cli.Flag{
122 EnvVar: "XDS_CONFIG",
123 Usage: "env config file to source on startup",
127 EnvVar: "XDS_LOGLEVEL",
128 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)",
129 Value: defaultLogLevel,
133 EnvVar: "XDS_SERVER_URL",
134 Value: "localhost:8000",
135 Usage: "remote XDS server url",
138 Name: "timestamp, ts",
139 EnvVar: "XDS_TIMESTAMP",
140 Usage: "prefix output with timestamp",
145 app.Commands = []cli.Command{}
147 initCmdProjects(&app.Commands)
148 initCmdSdks(&app.Commands)
149 initCmdExec(&app.Commands)
150 initCmdMisc(&app.Commands)
152 sort.Sort(cli.FlagsByName(app.Flags))
153 sort.Sort(cli.CommandsByName(app.Commands))
155 app.Before = func(ctx *cli.Context) error {
157 loglevel := ctx.String("log")
158 // Set logger level and formatter
159 if Log.Level, err = logrus.ParseLevel(loglevel); err != nil {
160 msg := fmt.Sprintf("Invalid log level : \"%v\"\n", loglevel)
161 return cli.NewExitError(msg, 1)
163 Log.Formatter = &logrus.TextFormatter{}
165 Log.Infof("%s version: %s", AppName, app.Version)
166 // SEB Add again Log.Debugf("Environment: %v", os.Environ())
168 if err = XdsConnInit(ctx); err != nil {
169 // Directly call HandleExitCoder to avoid to print help (ShowAppHelp)
170 // Note that this function wil never return and program will exit
171 cli.HandleExitCoder(err)
177 // Close HTTP client and WS connection on exit
185 // XdsConnInit Initialized HTTP and WebSocket connection to XDS agent
186 func XdsConnInit(ctx *cli.Context) error {
189 // Define HTTP and WS url
190 baseURL := ctx.String("url")
191 if !strings.HasPrefix(ctx.String("url"), "http://") {
192 baseURL = "http://" + ctx.String("url")
195 // Create HTTP client
196 Log.Debugln("Connect HTTP client on ", baseURL)
197 conf := common.HTTPClientConfig{
198 URLPrefix: "/api/v1",
199 HeaderClientKeyName: "Xds-Agent-Sid",
202 LogPrefix: "XDSAGENT: ",
203 LogLevel: common.HTTPLogLevelWarning,
206 HTTPCli, err = common.HTTPNewClient(baseURL, conf)
208 errmsg := err.Error()
209 if m, err := regexp.MatchString("Get http.?://", errmsg); m && err == nil {
210 i := strings.LastIndex(errmsg, ":")
211 errmsg = "Cannot connection to " + baseURL + errmsg[i:]
213 return cli.NewExitError(errmsg, 1)
215 HTTPCli.SetLogLevel(ctx.String("loglevel"))
217 // Create io Websocket client
218 Log.Debugln("Connecting IO.socket client on ", baseURL)
220 opts := &socketio_client.Options{
221 Transport: "websocket",
222 Header: make(map[string][]string),
224 opts.Header["XDS-AGENT-SID"] = []string{HTTPCli.GetClientID()}
226 IOsk, err = socketio_client.NewClient(baseURL, opts)
228 return cli.NewExitError("IO.socket connection error: "+err.Error(), 1)
231 IOsk.On("error", func(err error) {
232 fmt.Println("ERROR Websocket: ", err.Error())
235 ctx.App.Metadata["httpCli"] = HTTPCli
236 ctx.App.Metadata["ioskCli"] = IOsk
241 // XdsConnClose Terminate connection to XDS agent
242 func XdsConnClose() {
243 Log.Debugf("Closing HTTP client session...")
245 if httpCli, ok := app.Metadata["httpCli"]; ok {
246 c := httpCli.(*common.HTTPClient)
250 Log.Debugf("Closing WebSocket connection...")
252 if ioskCli, ok := app.Metadata["ioskCli"]; ok {
253 c := ioskCli.(*socketio_client.Client)
258 // NewTableWriter Create a writer that inserts padding around tab-delimited
259 func NewTableWriter() *tabwriter.Writer {
260 writer := new(tabwriter.Writer)
261 writer.Init(os.Stdout, 0, 8, 0, '\t', 0)