2 * Copyright (C) 2017-2018 "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 "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent.git/lib/xaapiv1"
32 common "gerrit.automotivelinux.org/gerrit/src/xds/xds-common.git/golib"
33 "github.com/Sirupsen/logrus"
35 "github.com/joho/godotenv"
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-2018 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 // IOSkClient Global variable that hold SocketIo client
74 var IOSkClient *IOSockClient
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{}
98 // LogSillyf Logging helper used for silly logging (printed on log.debug)
99 func LogSillyf(format string, args ...interface{}) {
100 sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
101 if sillyLog && sillyVal == "1" {
102 Log.Debugf("SILLY: "+format, args...)
109 // Allow to set app name from cli (useful for debugging)
111 AppName = os.Getenv("XDS_APPNAME")
114 panic("Invalid setup, AppName not define !")
116 if AppNativeName == "" {
117 AppNativeName = AppName[4:]
119 appUsage := fmt.Sprintf("command line tool for X(cross) Development System.")
120 appDescription := fmt.Sprintf("%s utility for X(cross) Development System\n", AppName)
122 Setting of global options is driven either by environment variables or by command
123 line options or using a config file knowning that the following priority order is used:
124 1. use option value (for example --url option),
125 2. else use variable 'XDS_xxx' (for example 'XDS_AGENT_URL' variable) when a
126 config file is specified with '--config|-c' option,
127 3. else use 'XDS_xxx' (for example 'XDS_AGENT_URL') environment variable.
130 # Get help of 'projects' sub-command
131 ` + AppName + ` projects --help
134 ` + AppName + ` sdks ls
137 ` + AppName + ` prj add --label="myProject" --type=cs --path=$HOME/xds-workspace/myProject
140 // Create a new App instance
144 app.Version = AppVersion + " (" + AppSubVersion + ")"
145 app.Authors = appAuthors
146 app.Copyright = appCopyright
147 app.Metadata = make(map[string]interface{})
148 app.Metadata["version"] = AppVersion
149 app.Metadata["git-tag"] = AppSubVersion
150 app.Metadata["logger"] = Log
151 app.EnableBashCompletion = true
153 // Create env vars help
154 dynDesc := "\nENVIRONMENT VARIABLES:"
155 for _, f := range app.Flags {
156 var env, usage string
159 fs := f.(cli.StringFlag)
163 fb := f.(cli.BoolFlag)
167 exitError(1, "Un-implemented option type")
170 dynDesc += fmt.Sprintf("\n %s \t\t %s", env, usage)
173 app.Description = appDescription + dynDesc
175 // Declare global flags
176 app.Flags = []cli.Flag{
179 EnvVar: "XDS_CONFIG",
180 Usage: "env config file to source on startup",
184 EnvVar: "XDS_LOGLEVEL",
185 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)",
186 Value: defaultLogLevel,
191 Usage: "filename where logs will be redirected (default stderr)\n\t",
192 EnvVar: "XDS_LOGFILENAME",
196 EnvVar: "XDS_AGENT_URL",
197 Value: "localhost:8800",
198 Usage: "local XDS agent url",
201 Name: "url-server, us",
202 EnvVar: "XDS_SERVER_URL",
204 Usage: "overwrite remote XDS server url (default value set in xds-agent-config.json file)",
207 Name: "timestamp, ts",
208 EnvVar: "XDS_TIMESTAMP",
209 Usage: "prefix output with timestamp",
214 app.Commands = []cli.Command{}
216 initCmdProjects(&app.Commands)
217 initCmdSdks(&app.Commands)
218 initCmdExec(&app.Commands)
219 initCmdTargets(&app.Commands)
220 initCmdMisc(&app.Commands)
222 // Add --config option to all commands to support --config option either before or after command verb
223 // IOW support following both syntaxes:
224 // xds-cli exec --config myPrj.conf ...
225 // xds-cli --config myPrj.conf exec ...
226 for i, cmd := range app.Commands {
227 if len(cmd.Flags) > 0 {
228 app.Commands[i].Flags = append(cmd.Flags, cli.StringFlag{Hidden: true, Name: "config, c"})
230 for j, subCmd := range cmd.Subcommands {
231 app.Commands[i].Subcommands[j].Flags = append(subCmd.Flags, cli.StringFlag{Hidden: true, Name: "config, c"})
235 sort.Sort(cli.FlagsByName(app.Flags))
236 sort.Sort(cli.CommandsByName(app.Commands))
238 // Early and manual processing of --config option in order to set XDS_xxx
239 // variables before parsing of option by app cli
240 confFile := os.Getenv("XDS_CONFIG")
241 for idx, a := range os.Args[1:] {
242 if a == "-c" || a == "--config" || a == "-config" {
243 confFile = os.Args[idx+2]
248 // Load config file if requested
250 earlyPrintf("confFile detected: %v", confFile)
251 confFile, err := common.ResolveEnvVar(confFile)
253 exitError(1, "Error while resolving confFile: %v", err)
255 earlyPrintf("Resolved confFile: %v", confFile)
256 if !common.Exists(confFile) {
257 exitError(1, "Error env config file not found")
259 // Load config file variables that will overwrite env variables
260 err = godotenv.Overload(confFile)
262 exitError(1, "Error loading env config file "+confFile)
265 // Keep confFile settings in a map
266 EnvConfFileMap, err = godotenv.Read(confFile)
268 exitError(1, "Error reading env config file "+confFile)
270 earlyPrintf("EnvConfFileMap: %v", EnvConfFileMap)
273 app.Before = func(ctx *cli.Context) error {
276 // Don't init anything when no argument or help option is set
280 for _, a := range ctx.Args() {
282 case "-h", "--h", "-help", "--help":
287 loglevel := ctx.String("log")
288 // Set logger level and formatter
289 if Log.Level, err = logrus.ParseLevel(loglevel); err != nil {
290 msg := fmt.Sprintf("Invalid log level : \"%v\"\n", loglevel)
291 return cli.NewExitError(msg, 1)
293 Log.Formatter = &logrus.TextFormatter{}
295 if ctx.String("logfile") != "stderr" {
296 logFile, _ := common.ResolveEnvVar(ctx.String("logfile"))
297 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
299 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
300 return cli.NewExitError(msgErr, 1)
302 Log.Infof("Logging to file: %s", logFile)
306 Log.Infof("%s version: %s", AppName, app.Version)
308 Log.Debugf("\nEnvironment: %v\n", os.Environ())
310 if err = XdsConnInit(ctx); err != nil {
311 // Directly call HandleExitCoder to avoid to print help (ShowAppHelp)
312 // Note that this function wil never return and program will exit
313 cli.HandleExitCoder(err)
319 // Close HTTP client and WS connection on exit
324 // Start signals monitoring routine
331 // XdsConnInit Initialized HTTP and WebSocket connection to XDS agent
332 func XdsConnInit(ctx *cli.Context) error {
335 // Define HTTP and WS url
336 agentURL := ctx.String("url")
337 serverURL := ctx.String("url-server")
339 // Allow to only set port number
340 if match, _ := regexp.MatchString("^([0-9]+)$", agentURL); match {
341 agentURL = "http://localhost:" + ctx.String("url")
343 if match, _ := regexp.MatchString("^([0-9]+)$", serverURL); match {
344 serverURL = "http://localhost:" + ctx.String("url-server")
346 // Add http prefix if missing
347 if agentURL != "" && !strings.HasPrefix(agentURL, "http://") {
348 agentURL = "http://" + agentURL
350 if serverURL != "" && !strings.HasPrefix(serverURL, "http://") {
351 serverURL = "http://" + serverURL
354 lvl := common.HTTPLogLevelWarning
355 if Log.Level == logrus.DebugLevel {
356 lvl = common.HTTPLogLevelDebug
359 // Create HTTP client
360 Log.Debugln("Connect HTTP client on ", agentURL)
361 conf := common.HTTPClientConfig{
362 URLPrefix: "/api/v1",
363 HeaderClientKeyName: "Xds-Agent-Sid",
366 LogPrefix: "XDSAGENT: ",
370 HTTPCli, err = common.HTTPNewClient(agentURL, conf)
372 errmsg := err.Error()
373 m, err := regexp.MatchString("Get http.?://", errmsg)
374 if (m && err == nil) || strings.Contains(errmsg, "Failed to get device ID") {
375 i := strings.LastIndex(errmsg, ":")
376 newErr := "Cannot connection to " + agentURL
378 newErr += " (" + strings.TrimSpace(errmsg[i+1:]) + ")"
380 newErr += " (" + strings.TrimSpace(errmsg) + ")"
384 return cli.NewExitError(errmsg, 1)
386 HTTPCli.SetLogLevel(ctx.String("loglevel"))
387 Log.Infoln("HTTP session ID : ", HTTPCli.GetClientID())
389 // Create io Websocket client
390 Log.Debugln("Connecting IO.socket client on ", agentURL)
392 IOSkClient, err = NewIoSocketClient(agentURL, HTTPCli.GetClientID())
394 return cli.NewExitError(err.Error(), 1)
397 IOSkClient.On("error", func(err error) {
398 fmt.Println("ERROR Websocket: ", err.Error())
401 ctx.App.Metadata["httpCli"] = HTTPCli
402 ctx.App.Metadata["ioskCli"] = IOSkClient
404 // Display version in logs (debug helpers)
405 ver := xaapiv1.XDSVersion{}
406 if err := XdsVersionGet(&ver); err != nil {
407 return cli.NewExitError("ERROR while retrieving XDS version: "+err.Error(), 1)
409 Log.Infof("XDS Agent/Server version: %v", ver)
411 // Get current config and update connection to server when needed
412 xdsConf := xaapiv1.APIConfig{}
413 if err := XdsConfigGet(&xdsConf); err != nil {
414 return cli.NewExitError("ERROR while getting XDS config: "+err.Error(), 1)
416 if len(xdsConf.Servers) < 1 {
417 return cli.NewExitError("No XDS Server connected", 1)
419 svrCfg := xdsConf.Servers[XdsServerIndexGet()]
420 if (serverURL != "" && svrCfg.URL != serverURL) || !svrCfg.Connected {
421 Log.Infof("Update XDS Server config: serverURL=%v, svrCfg=%v", serverURL, svrCfg)
423 svrCfg.URL = serverURL
425 svrCfg.ConnRetry = 10
426 if err := XdsConfigSet(xdsConf); err != nil {
427 return cli.NewExitError("ERROR while updating XDS server URL: "+err.Error(), 1)
434 // XdsConnClose Terminate connection to XDS agent
435 func XdsConnClose() {
436 Log.Debugf("Closing HTTP client session...")
438 if httpCli, ok := app.Metadata["httpCli"]; ok {
439 c := httpCli.(*common.HTTPClient)
443 Log.Debugf("Closing WebSocket connection...")
445 if ioskCli, ok := app.Metadata["ioskCli"]; ok {
446 c := ioskCli.(*socketio_client.Client)
451 // NewTableWriter Create a writer that inserts padding around tab-delimited
452 func NewTableWriter() *tabwriter.Writer {
453 writer := new(tabwriter.Writer)
454 writer.Init(os.Stdout, 0, 8, 0, '\t', 0)