2 * Copyright (C) 2017 "IoT.bzh"
3 * Author Sebastien Douheret <sebastien@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 * xds-cli: command line tool used to control / interface X(cross) Development System.
31 "github.com/Sirupsen/logrus"
32 "github.com/iotbzh/xds-agent/lib/xaapiv1"
33 common "github.com/iotbzh/xds-common/golib"
34 "github.com/joho/godotenv"
35 socketio_client "github.com/sebd71/go-socket.io-client"
36 "github.com/urfave/cli"
39 var appAuthors = []cli.Author{
40 cli.Author{Name: "Sebastien Douheret", Email: "sebastien@iot.bzh"},
43 // AppName name of this application
44 var AppName = "xds-cli"
46 // AppNativeName native command name that this application can overload
47 var AppNativeName = "cli"
49 // AppVersion Version of this application
51 var AppVersion = "?.?.?"
53 // AppSubVersion is the git tag id added to version string
54 // Should be set by compilation -ldflags "-X main.AppSubVersion=xxx"
56 var AppSubVersion = "unknown-dev"
58 // Application details
60 appCopyright = "Copyright (C) 2017 IoT.bzh - Apache-2.0"
61 defaultLogLevel = "error"
64 // Log Global variable that hold logger
65 var Log = logrus.New()
67 // EnvConfFileMap Global variable that hold environment vars loaded from config file
68 var EnvConfFileMap map[string]string
70 // HTTPCli Global variable that hold HTTP Client
71 var HTTPCli *common.HTTPClient
73 // IOsk Global variable that hold SocketIo client
74 var IOsk *socketio_client.Client
76 // exitError exists this program with the specified error
77 func exitError(code int, f string, a ...interface{}) {
79 err := fmt.Sprintf(f, a...)
80 fmt.Fprintf(os.Stderr, err+"\n")
84 // earlyDebug Used to log info before logger has been initialized
85 var earlyDebug []string
87 func earlyPrintf(format string, args ...interface{}) {
88 earlyDebug = append(earlyDebug, fmt.Sprintf(format, args...))
92 for _, str := range earlyDebug {
95 earlyDebug = []string{}
101 // Allow to set app name from cli (useful for debugging)
103 AppName = os.Getenv("XDS_APPNAME")
106 panic("Invalid setup, AppName not define !")
108 if AppNativeName == "" {
109 AppNativeName = AppName[4:]
111 appUsage := fmt.Sprintf("command line tool for X(cross) Development System.")
112 appDescription := fmt.Sprintf("%s utility for X(cross) Development System\n", AppName)
114 Setting of global options is driven either by environment variables or by command
115 line options or using a config file knowning that the following priority order is used:
116 1. use option value (for example --url option),
117 2. else use variable 'XDS_xxx' (for example 'XDS_AGENT_URL' variable) when a
118 config file is specified with '--config|-c' option,
119 3. else use 'XDS_xxx' (for example 'XDS_AGENT_URL') environment variable.
122 # Get help of 'projects' sub-command
123 ` + AppName + ` projects --help
126 ` + AppName + ` sdks ls
129 ` + AppName + ` prj add --label="myProject" --type=cs --path=$HOME/xds-workspace/myProject
132 // Create a new App instance
136 app.Version = AppVersion + " (" + AppSubVersion + ")"
137 app.Authors = appAuthors
138 app.Copyright = appCopyright
139 app.Metadata = make(map[string]interface{})
140 app.Metadata["version"] = AppVersion
141 app.Metadata["git-tag"] = AppSubVersion
142 app.Metadata["logger"] = Log
144 // Create env vars help
145 dynDesc := "\nENVIRONMENT VARIABLES:"
146 for _, f := range app.Flags {
147 var env, usage string
150 fs := f.(cli.StringFlag)
154 fb := f.(cli.BoolFlag)
158 exitError(1, "Un-implemented option type")
161 dynDesc += fmt.Sprintf("\n %s \t\t %s", env, usage)
164 app.Description = appDescription + dynDesc
166 // Declare global flags
167 app.Flags = []cli.Flag{
170 EnvVar: "XDS_CONFIG",
171 Usage: "env config file to source on startup",
175 EnvVar: "XDS_LOGLEVEL",
176 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)",
177 Value: defaultLogLevel,
181 EnvVar: "XDS_AGENT_URL",
182 Value: "localhost:8800",
183 Usage: "local XDS agent url",
186 Name: "url-server, us",
187 EnvVar: "XDS_SERVER_URL",
189 Usage: "overwrite remote XDS server url (default value set in xds-agent-config.json file)",
192 Name: "timestamp, ts",
193 EnvVar: "XDS_TIMESTAMP",
194 Usage: "prefix output with timestamp",
199 app.Commands = []cli.Command{}
201 initCmdProjects(&app.Commands)
202 initCmdSdks(&app.Commands)
203 initCmdExec(&app.Commands)
204 initCmdMisc(&app.Commands)
206 // Add --config option to all commands to support --config option either before or after command verb
207 // IOW support following both syntaxes:
208 // xds-cli exec --config myprj.conf ...
209 // xds-cli --config myprj.conf exec ...
210 for i, cmd := range app.Commands {
211 if len(cmd.Flags) > 0 {
212 app.Commands[i].Flags = append(cmd.Flags, cli.StringFlag{Hidden: true, Name: "config, c"})
214 for j, subCmd := range cmd.Subcommands {
215 app.Commands[i].Subcommands[j].Flags = append(subCmd.Flags, cli.StringFlag{Hidden: true, Name: "config, c"})
219 sort.Sort(cli.FlagsByName(app.Flags))
220 sort.Sort(cli.CommandsByName(app.Commands))
222 // Early and manual processing of --config option in order to set XDS_xxx
223 // variables before parsing of option by app cli
224 confFile := os.Getenv("XDS_CONFIG")
225 for idx, a := range os.Args[1:] {
226 if a == "-c" || a == "--config" || a == "-config" {
227 confFile = os.Args[idx+2]
232 // Load config file if requested
234 earlyPrintf("confFile detected: %v", confFile)
235 confFile, err := common.ResolveEnvVar(confFile)
237 exitError(1, "Error while resolving confFile: %v", err)
239 earlyPrintf("Resolved confFile: %v", confFile)
240 if !common.Exists(confFile) {
241 exitError(1, "Error env config file not found")
243 // Load config file variables that will overwrite env variables
244 err = godotenv.Overload(confFile)
246 exitError(1, "Error loading env config file "+confFile)
249 // Keep confFile settings in a map
250 EnvConfFileMap, err = godotenv.Read(confFile)
252 exitError(1, "Error reading env config file "+confFile)
254 earlyPrintf("EnvConfFileMap: %v", EnvConfFileMap)
257 app.Before = func(ctx *cli.Context) error {
260 // Don't init anything when no argument or help option is set
264 for _, a := range ctx.Args() {
266 case "-h", "--h", "-help", "--help":
271 loglevel := ctx.String("log")
272 // Set logger level and formatter
273 if Log.Level, err = logrus.ParseLevel(loglevel); err != nil {
274 msg := fmt.Sprintf("Invalid log level : \"%v\"\n", loglevel)
275 return cli.NewExitError(msg, 1)
277 Log.Formatter = &logrus.TextFormatter{}
279 Log.Infof("%s version: %s", AppName, app.Version)
281 Log.Debugf("\nEnvironment: %v\n", os.Environ())
283 if err = XdsConnInit(ctx); err != nil {
284 // Directly call HandleExitCoder to avoid to print help (ShowAppHelp)
285 // Note that this function wil never return and program will exit
286 cli.HandleExitCoder(err)
292 // Close HTTP client and WS connection on exit
300 // XdsConnInit Initialized HTTP and WebSocket connection to XDS agent
301 func XdsConnInit(ctx *cli.Context) error {
304 // Define HTTP and WS url
305 agentURL := ctx.String("url")
306 serverURL := ctx.String("url-server")
308 // Allow to only set port number
309 if match, _ := regexp.MatchString("^([0-9]+)$", agentURL); match {
310 agentURL = "http://localhost:" + ctx.String("url")
312 if match, _ := regexp.MatchString("^([0-9]+)$", serverURL); match {
313 serverURL = "http://localhost:" + ctx.String("url-server")
315 // Add http prefix if missing
316 if agentURL != "" && !strings.HasPrefix(agentURL, "http://") {
317 agentURL = "http://" + agentURL
319 if serverURL != "" && !strings.HasPrefix(serverURL, "http://") {
320 serverURL = "http://" + serverURL
323 // Create HTTP client
324 Log.Debugln("Connect HTTP client on ", agentURL)
325 conf := common.HTTPClientConfig{
326 URLPrefix: "/api/v1",
327 HeaderClientKeyName: "Xds-Agent-Sid",
330 LogPrefix: "XDSAGENT: ",
331 LogLevel: common.HTTPLogLevelDebug,
334 HTTPCli, err = common.HTTPNewClient(agentURL, conf)
336 errmsg := err.Error()
337 m, err := regexp.MatchString("Get http.?://", errmsg)
338 if (m && err == nil) || strings.Contains(errmsg, "Failed to get device ID") {
339 i := strings.LastIndex(errmsg, ":")
340 newErr := "Cannot connection to " + agentURL
342 newErr += " (" + strings.TrimSpace(errmsg[i+1:]) + ")"
344 newErr += " (" + strings.TrimSpace(errmsg) + ")"
348 return cli.NewExitError(errmsg, 1)
350 HTTPCli.SetLogLevel(ctx.String("loglevel"))
351 Log.Infoln("HTTP session ID : ", HTTPCli.GetClientID())
353 // Create io Websocket client
354 Log.Debugln("Connecting IO.socket client on ", agentURL)
356 opts := &socketio_client.Options{
357 Transport: "websocket",
358 Header: make(map[string][]string),
360 opts.Header["XDS-AGENT-SID"] = []string{HTTPCli.GetClientID()}
362 IOsk, err = socketio_client.NewClient(agentURL, opts)
364 return cli.NewExitError("IO.socket connection error: "+err.Error(), 1)
367 IOsk.On("error", func(err error) {
368 fmt.Println("ERROR Websocket: ", err.Error())
371 ctx.App.Metadata["httpCli"] = HTTPCli
372 ctx.App.Metadata["ioskCli"] = IOsk
374 // Display version in logs (debug helpers)
375 ver := xaapiv1.XDSVersion{}
376 if err := XdsVersionGet(&ver); err != nil {
377 return cli.NewExitError("ERROR while retrieving XDS version: "+err.Error(), 1)
379 Log.Infof("XDS Agent/Server version: %v", ver)
381 // Get current config and update connection to server when needed
382 xdsConf := xaapiv1.APIConfig{}
383 if err := XdsConfigGet(&xdsConf); err != nil {
384 return cli.NewExitError("ERROR while getting XDS config: "+err.Error(), 1)
386 svrCfg := xdsConf.Servers[XdsServerIndexGet()]
387 if (serverURL != "" && svrCfg.URL != serverURL) || !svrCfg.Connected {
388 Log.Infof("Update XDS Server config: serverURL=%v, svrCfg=%v", serverURL, svrCfg)
390 svrCfg.URL = serverURL
392 svrCfg.ConnRetry = 10
393 if err := XdsConfigSet(xdsConf); err != nil {
394 return cli.NewExitError("ERROR while updating XDS server URL: "+err.Error(), 1)
401 // XdsConnClose Terminate connection to XDS agent
402 func XdsConnClose() {
403 Log.Debugf("Closing HTTP client session...")
405 if httpCli, ok := app.Metadata["httpCli"]; ok {
406 c := httpCli.(*common.HTTPClient)
410 Log.Debugf("Closing WebSocket connection...")
412 if ioskCli, ok := app.Metadata["ioskCli"]; ok {
413 c := ioskCli.(*socketio_client.Client)
418 // NewTableWriter Create a writer that inserts padding around tab-delimited
419 func NewTableWriter() *tabwriter.Writer {
420 writer := new(tabwriter.Writer)
421 writer.Init(os.Stdout, 0, 8, 0, '\t', 0)