2 * Copyright (C) 2017-2019 "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.
33 "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent.git/lib/xaapiv1"
34 common "gerrit.automotivelinux.org/gerrit/src/xds/xds-common.git"
35 "github.com/Sirupsen/logrus"
36 "github.com/joho/godotenv"
37 "github.com/urfave/cli"
40 var appAuthors = []cli.Author{
41 cli.Author{Name: "Sebastien Douheret", Email: "sebastien@iot.bzh"},
44 // AppName name of this application
45 var AppName = "xds-cli"
47 // AppNativeName native command name that this application can overload
48 var AppNativeName = "cli"
50 // AppVersion Version of this application
52 var AppVersion = "?.?.?"
54 // AppSubVersion is the git tag id added to version string
55 // Should be set by compilation -ldflags "-X main.AppSubVersion=xxx"
57 var AppSubVersion = "unknown-dev"
59 // Application details
61 appCopyright = "Copyright (C) 2017-2019 IoT.bzh - Apache-2.0"
62 defaultLogLevel = "error"
63 defaultConfigEnvFilename = "cli-config.env"
66 // Log Global variable that hold logger
67 var Log = logrus.New()
69 // EnvConfFileMap Global variable that hold environment vars loaded from config file
70 var EnvConfFileMap map[string]string
72 // HTTPCli Global variable that hold HTTP Client
73 var HTTPCli *common.HTTPClient
75 // IOSkClient Global variable that hold SocketIo client
76 var IOSkClient *IOSockClient
78 // exitError exists this program with the specified error
79 func exitError(code int, f string, a ...interface{}) {
81 err := fmt.Sprintf(f, a...)
82 fmt.Fprintf(os.Stderr, err+"\n")
86 // earlyDebug Used to log info before logger has been initialized
87 var earlyDebug []string
89 func earlyPrintf(format string, args ...interface{}) {
90 earlyDebug = append(earlyDebug, fmt.Sprintf(format, args...))
94 for _, str := range earlyDebug {
97 earlyDebug = []string{}
100 // LogSillyf Logging helper used for silly logging (printed on log.debug)
101 func LogSillyf(format string, args ...interface{}) {
102 sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
103 if sillyLog && sillyVal == "1" {
104 Log.Debugf("SILLY: "+format, args...)
111 // Allow to set app name from cli (useful for debugging)
113 AppName = os.Getenv("XDS_APPNAME")
116 panic("Invalid setup, AppName not define !")
118 if AppNativeName == "" {
119 AppNativeName = AppName[4:]
121 appUsage := fmt.Sprintf("command line tool for X(cross) Development System.")
122 appDescription := fmt.Sprintf("%s utility for X(cross) Development System\n", AppName)
124 Setting of global options is driven either by environment variables or by command
125 line options or using a config file knowning that the following priority order is used:
126 1. use option value (for example --url option),
127 2. else use variable 'XDS_xxx' (for example 'XDS_AGENT_URL' variable) when a
128 config file is specified with '--config|-c' option,
129 3. else use 'XDS_xxx' (for example 'XDS_AGENT_URL') environment variable.
132 # Get help of 'projects' sub-command
133 ` + AppName + ` projects --help
136 ` + AppName + ` sdks ls
139 ` + AppName + ` prj add --label="myProject" --type=cs --path=$HOME/xds-workspace/myProject
142 // Create a new App instance
146 app.Version = AppVersion + " (" + AppSubVersion + ")"
147 app.Authors = appAuthors
148 app.Copyright = appCopyright
149 app.Metadata = make(map[string]interface{})
150 app.Metadata["version"] = AppVersion
151 app.Metadata["git-tag"] = AppSubVersion
152 app.Metadata["logger"] = Log
153 // FIXME: Disable completion for now, because it's not working with options
154 // (eg. --label) and prevents to complete local path
155 // (IOW current function only completes command and sub-commands)
156 app.EnableBashCompletion = false
158 // Create env vars help
159 dynDesc := "\nENVIRONMENT VARIABLES:"
160 for _, f := range app.Flags {
161 var env, usage string
164 fs := f.(cli.StringFlag)
168 fb := f.(cli.BoolFlag)
172 exitError(1, "Un-implemented option type")
175 dynDesc += fmt.Sprintf("\n %s \t\t %s", env, usage)
178 app.Description = appDescription + dynDesc
180 // Declare global flags
181 app.Flags = []cli.Flag{
184 EnvVar: "XDS_CONFIG",
185 Usage: "env config file to source on startup",
189 EnvVar: "XDS_LOGLEVEL",
190 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)",
191 Value: defaultLogLevel,
196 Usage: "filename where logs will be redirected (default stderr)\n\t",
197 EnvVar: "XDS_LOGFILENAME",
201 EnvVar: "XDS_AGENT_URL",
202 Value: "localhost:8800",
203 Usage: "local XDS agent url",
206 Name: "url-server, us",
207 EnvVar: "XDS_SERVER_URL",
209 Usage: "overwrite remote XDS server url (default value set in xds-agent-config.json file)",
212 Name: "timestamp, ts",
213 EnvVar: "XDS_TIMESTAMP",
214 Usage: "prefix output with timestamp",
219 app.Commands = []cli.Command{}
221 initCmdProjects(&app.Commands)
222 initCmdSdks(&app.Commands)
223 initCmdExec(&app.Commands)
224 initCmdTargets(&app.Commands)
225 initCmdMisc(&app.Commands)
227 // Add --config option to all commands to support --config option either before or after command verb
228 // IOW support following both syntaxes:
229 // xds-cli exec --config myPrj.conf ...
230 // xds-cli --config myPrj.conf exec ...
231 for i, cmd := range app.Commands {
232 if len(cmd.Flags) > 0 {
233 app.Commands[i].Flags = append(cmd.Flags, cli.StringFlag{Hidden: true, Name: "config, c"})
235 for j, subCmd := range cmd.Subcommands {
236 app.Commands[i].Subcommands[j].Flags = append(subCmd.Flags, cli.StringFlag{Hidden: true, Name: "config, c"})
240 sort.Sort(cli.FlagsByName(app.Flags))
241 sort.Sort(cli.CommandsByName(app.Commands))
243 // Early and manual processing of --config option in order to set XDS_xxx
244 // variables before parsing of option by app cli
245 // 1/ from command line option: "--config myConfig.json"
246 // 2/ from environment variable XDS_CONFIG
247 // 3/ $HOME/.xds/cli/cli-config.env file
248 // 4/ /etc/xds/cli/cli-config.env file
249 searchIn := make([]string, 0, 4)
250 for idx, a := range os.Args[1:] {
251 if a == "-c" || a == "--config" || a == "-config" {
252 searchIn = append(searchIn, os.Args[idx+2])
256 searchIn = append(searchIn, os.Getenv("XDS_CONFIG"))
257 if usrHome := common.GetUserHome(); usrHome != "" {
258 searchIn = append(searchIn, path.Join(usrHome, ".xds", "cli", defaultConfigEnvFilename))
260 searchIn = append(searchIn, path.Join("/etc", "xds", "cli", defaultConfigEnvFilename))
262 // Use the first existing env config file
264 for _, p := range searchIn {
265 if pr, err := common.ResolveEnvVar(p); err == nil {
266 earlyPrintf("Check if confFile exists : %v", pr)
267 if common.Exists(pr) {
274 // Load config file if requested
276 earlyPrintf("Used confFile: %v", confFile)
277 // Load config file variables that will overwrite env variables
278 err := godotenv.Overload(confFile)
280 exitError(1, "Error loading env config file "+confFile)
283 // Keep confFile settings in a map
284 EnvConfFileMap, err = godotenv.Read(confFile)
286 exitError(1, "Error reading env config file "+confFile)
288 earlyPrintf("EnvConfFileMap: %v", EnvConfFileMap)
291 app.Before = func(ctx *cli.Context) error {
294 // Don't init anything when no argument or help option is set
298 for _, a := range ctx.Args() {
300 case "-h", "--h", "-help", "--help":
305 loglevel := ctx.String("log")
306 // Set logger level and formatter
307 if Log.Level, err = logrus.ParseLevel(loglevel); err != nil {
308 msg := fmt.Sprintf("Invalid log level : \"%v\"\n", loglevel)
309 return cli.NewExitError(msg, 1)
311 Log.Formatter = &logrus.TextFormatter{}
313 if ctx.String("logfile") != "stderr" {
314 logFile, _ := common.ResolveEnvVar(ctx.String("logfile"))
315 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
317 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
318 return cli.NewExitError(msgErr, 1)
320 Log.Infof("Logging to file: %s", logFile)
324 Log.Infof("%s version: %s", AppName, app.Version)
326 Log.Debugf("\nEnvironment: %v\n", os.Environ())
328 if err = XdsConnInit(ctx); err != nil {
329 // Directly call HandleExitCoder to avoid to print help (ShowAppHelp)
330 // Note that this function wil never return and program will exit
331 cli.HandleExitCoder(err)
337 // Close HTTP client and WS connection on exit
342 // Start signals monitoring routine
345 // Default callback to handle interrupt signal
346 // Maybe be overwritten by some subcommand (eg. targets commands)
347 err := OnSignals(func(sig os.Signal) {
348 Log.Debugf("Send signal %v (from main)", sig)
349 if IsInterruptSignal(sig) {
350 err := cli.NewExitError("Interrupted\n", int(syscall.EINTR))
351 cli.HandleExitCoder(err)
355 cli.NewExitError(err.Error(), 1)
363 // XdsConnInit Initialized HTTP and WebSocket connection to XDS agent
364 func XdsConnInit(ctx *cli.Context) error {
367 // Define HTTP and WS url
368 agentURL := ctx.String("url")
369 serverURL := ctx.String("url-server")
371 // Allow to only set port number
372 if match, _ := regexp.MatchString("^([0-9]+)$", agentURL); match {
373 agentURL = "http://localhost:" + ctx.String("url")
375 if match, _ := regexp.MatchString("^([0-9]+)$", serverURL); match {
376 serverURL = "http://localhost:" + ctx.String("url-server")
378 // Add http prefix if missing
379 if agentURL != "" && !strings.HasPrefix(agentURL, "http://") {
380 agentURL = "http://" + agentURL
382 if serverURL != "" && !strings.HasPrefix(serverURL, "http://") {
383 serverURL = "http://" + serverURL
386 lvl := common.HTTPLogLevelWarning
387 if Log.Level == logrus.DebugLevel {
388 lvl = common.HTTPLogLevelDebug
391 // Create HTTP client
392 Log.Debugln("Connect HTTP client on ", agentURL)
393 conf := common.HTTPClientConfig{
394 URLPrefix: "/api/v1",
395 HeaderClientKeyName: "Xds-Agent-Sid",
398 LogPrefix: "XDSAGENT: ",
402 HTTPCli, err = common.HTTPNewClient(agentURL, conf)
404 errmsg := err.Error()
405 m, err := regexp.MatchString("Get http.?://", errmsg)
406 if (m && err == nil) || strings.Contains(errmsg, "Failed to get device ID") {
407 i := strings.LastIndex(errmsg, ":")
408 newErr := "Cannot connection to " + agentURL
410 newErr += " (" + strings.TrimSpace(errmsg[i+1:]) + ")"
412 newErr += " (" + strings.TrimSpace(errmsg) + ")"
416 return cli.NewExitError(errmsg, 1)
418 HTTPCli.SetLogLevel(ctx.String("loglevel"))
419 Log.Infoln("HTTP session ID : ", HTTPCli.GetClientID())
421 // Create io Websocket client
422 Log.Debugln("Connecting IO.socket client on ", agentURL)
424 IOSkClient, err = NewIoSocketClient(agentURL, HTTPCli.GetClientID())
426 return cli.NewExitError(err.Error(), 1)
429 IOSkClient.On("error", func(err error) {
430 fmt.Println("ERROR Websocket: ", err.Error())
433 ctx.App.Metadata["httpCli"] = HTTPCli
434 ctx.App.Metadata["ioskCli"] = IOSkClient
436 // Display version in logs (debug helpers)
437 ver := xaapiv1.XDSVersion{}
438 if err := XdsVersionGet(&ver); err != nil {
439 return cli.NewExitError("ERROR while retrieving XDS version: "+err.Error(), 1)
441 Log.Infof("XDS Agent/Server version: %v", ver)
443 // Get current config and update connection to server when needed
444 xdsConf := xaapiv1.APIConfig{}
445 if err := XdsConfigGet(&xdsConf); err != nil {
446 return cli.NewExitError("ERROR while getting XDS config: "+err.Error(), 1)
448 if len(xdsConf.Servers) < 1 {
449 return cli.NewExitError("No XDS Server connected", 1)
451 svrCfg := xdsConf.Servers[XdsServerIndexGet()]
452 if (serverURL != "" && svrCfg.URL != serverURL) || !svrCfg.Connected {
453 Log.Infof("Update XDS Server config: serverURL=%v, svrCfg=%v", serverURL, svrCfg)
455 svrCfg.URL = serverURL
457 svrCfg.ConnRetry = 10
458 if err := XdsConfigSet(xdsConf); err != nil {
459 return cli.NewExitError("ERROR while updating XDS server URL: "+err.Error(), 1)
466 // XdsConnClose Terminate connection to XDS agent
467 func XdsConnClose() {
468 Log.Debugf("Closing HTTP client session...")
470 if httpCli, ok := app.Metadata["httpCli"]; ok {
471 c := httpCli.(*common.HTTPClient)
475 Log.Debugf("Closing WebSocket connection...")
477 if ioskCli, ok := app.Metadata["ioskCli"]; ok {
478 c := ioskCli.(*socketio_client.Client)
483 // NewTableWriter Create a writer that inserts padding around tab-delimited
484 func NewTableWriter() *tabwriter.Writer {
485 writer := new(tabwriter.Writer)
486 writer.Init(os.Stdout, 0, 8, 0, '\t', 0)