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.
32 "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent.git/lib/xaapiv1"
33 common "gerrit.automotivelinux.org/gerrit/src/xds/xds-common.git/golib"
34 "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-2018 IoT.bzh - Apache-2.0"
62 defaultLogLevel = "error"
65 // Log Global variable that hold logger
66 var Log = logrus.New()
68 // EnvConfFileMap Global variable that hold environment vars loaded from config file
69 var EnvConfFileMap map[string]string
71 // HTTPCli Global variable that hold HTTP Client
72 var HTTPCli *common.HTTPClient
74 // IOSkClient Global variable that hold SocketIo client
75 var IOSkClient *IOSockClient
77 // exitError exists this program with the specified error
78 func exitError(code int, f string, a ...interface{}) {
80 err := fmt.Sprintf(f, a...)
81 fmt.Fprintf(os.Stderr, err+"\n")
85 // earlyDebug Used to log info before logger has been initialized
86 var earlyDebug []string
88 func earlyPrintf(format string, args ...interface{}) {
89 earlyDebug = append(earlyDebug, fmt.Sprintf(format, args...))
93 for _, str := range earlyDebug {
96 earlyDebug = []string{}
99 // LogSillyf Logging helper used for silly logging (printed on log.debug)
100 func LogSillyf(format string, args ...interface{}) {
101 sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
102 if sillyLog && sillyVal == "1" {
103 Log.Debugf("SILLY: "+format, args...)
110 // Allow to set app name from cli (useful for debugging)
112 AppName = os.Getenv("XDS_APPNAME")
115 panic("Invalid setup, AppName not define !")
117 if AppNativeName == "" {
118 AppNativeName = AppName[4:]
120 appUsage := fmt.Sprintf("command line tool for X(cross) Development System.")
121 appDescription := fmt.Sprintf("%s utility for X(cross) Development System\n", AppName)
123 Setting of global options is driven either by environment variables or by command
124 line options or using a config file knowning that the following priority order is used:
125 1. use option value (for example --url option),
126 2. else use variable 'XDS_xxx' (for example 'XDS_AGENT_URL' variable) when a
127 config file is specified with '--config|-c' option,
128 3. else use 'XDS_xxx' (for example 'XDS_AGENT_URL') environment variable.
131 # Get help of 'projects' sub-command
132 ` + AppName + ` projects --help
135 ` + AppName + ` sdks ls
138 ` + AppName + ` prj add --label="myProject" --type=cs --path=$HOME/xds-workspace/myProject
141 // Create a new App instance
145 app.Version = AppVersion + " (" + AppSubVersion + ")"
146 app.Authors = appAuthors
147 app.Copyright = appCopyright
148 app.Metadata = make(map[string]interface{})
149 app.Metadata["version"] = AppVersion
150 app.Metadata["git-tag"] = AppSubVersion
151 app.Metadata["logger"] = Log
152 app.EnableBashCompletion = true
154 // Create env vars help
155 dynDesc := "\nENVIRONMENT VARIABLES:"
156 for _, f := range app.Flags {
157 var env, usage string
160 fs := f.(cli.StringFlag)
164 fb := f.(cli.BoolFlag)
168 exitError(1, "Un-implemented option type")
171 dynDesc += fmt.Sprintf("\n %s \t\t %s", env, usage)
174 app.Description = appDescription + dynDesc
176 // Declare global flags
177 app.Flags = []cli.Flag{
180 EnvVar: "XDS_CONFIG",
181 Usage: "env config file to source on startup",
185 EnvVar: "XDS_LOGLEVEL",
186 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)",
187 Value: defaultLogLevel,
192 Usage: "filename where logs will be redirected (default stderr)\n\t",
193 EnvVar: "XDS_LOGFILENAME",
197 EnvVar: "XDS_AGENT_URL",
198 Value: "localhost:8800",
199 Usage: "local XDS agent url",
202 Name: "url-server, us",
203 EnvVar: "XDS_SERVER_URL",
205 Usage: "overwrite remote XDS server url (default value set in xds-agent-config.json file)",
208 Name: "timestamp, ts",
209 EnvVar: "XDS_TIMESTAMP",
210 Usage: "prefix output with timestamp",
215 app.Commands = []cli.Command{}
217 initCmdProjects(&app.Commands)
218 initCmdSdks(&app.Commands)
219 initCmdExec(&app.Commands)
220 initCmdTargets(&app.Commands)
221 initCmdMisc(&app.Commands)
223 // Add --config option to all commands to support --config option either before or after command verb
224 // IOW support following both syntaxes:
225 // xds-cli exec --config myPrj.conf ...
226 // xds-cli --config myPrj.conf exec ...
227 for i, cmd := range app.Commands {
228 if len(cmd.Flags) > 0 {
229 app.Commands[i].Flags = append(cmd.Flags, cli.StringFlag{Hidden: true, Name: "config, c"})
231 for j, subCmd := range cmd.Subcommands {
232 app.Commands[i].Subcommands[j].Flags = append(subCmd.Flags, cli.StringFlag{Hidden: true, Name: "config, c"})
236 sort.Sort(cli.FlagsByName(app.Flags))
237 sort.Sort(cli.CommandsByName(app.Commands))
239 // Early and manual processing of --config option in order to set XDS_xxx
240 // variables before parsing of option by app cli
241 confFile := os.Getenv("XDS_CONFIG")
242 for idx, a := range os.Args[1:] {
243 if a == "-c" || a == "--config" || a == "-config" {
244 confFile = os.Args[idx+2]
249 // Load config file if requested
251 earlyPrintf("confFile detected: %v", confFile)
252 confFile, err := common.ResolveEnvVar(confFile)
254 exitError(1, "Error while resolving confFile: %v", err)
256 earlyPrintf("Resolved confFile: %v", confFile)
257 if !common.Exists(confFile) {
258 exitError(1, "Error env config file not found")
260 // Load config file variables that will overwrite env variables
261 err = godotenv.Overload(confFile)
263 exitError(1, "Error loading env config file "+confFile)
266 // Keep confFile settings in a map
267 EnvConfFileMap, err = godotenv.Read(confFile)
269 exitError(1, "Error reading env config file "+confFile)
271 earlyPrintf("EnvConfFileMap: %v", EnvConfFileMap)
274 app.Before = func(ctx *cli.Context) error {
277 // Don't init anything when no argument or help option is set
281 for _, a := range ctx.Args() {
283 case "-h", "--h", "-help", "--help":
288 loglevel := ctx.String("log")
289 // Set logger level and formatter
290 if Log.Level, err = logrus.ParseLevel(loglevel); err != nil {
291 msg := fmt.Sprintf("Invalid log level : \"%v\"\n", loglevel)
292 return cli.NewExitError(msg, 1)
294 Log.Formatter = &logrus.TextFormatter{}
296 if ctx.String("logfile") != "stderr" {
297 logFile, _ := common.ResolveEnvVar(ctx.String("logfile"))
298 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
300 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
301 return cli.NewExitError(msgErr, 1)
303 Log.Infof("Logging to file: %s", logFile)
307 Log.Infof("%s version: %s", AppName, app.Version)
309 Log.Debugf("\nEnvironment: %v\n", os.Environ())
311 if err = XdsConnInit(ctx); err != nil {
312 // Directly call HandleExitCoder to avoid to print help (ShowAppHelp)
313 // Note that this function wil never return and program will exit
314 cli.HandleExitCoder(err)
320 // Close HTTP client and WS connection on exit
325 // Start signals monitoring routine
328 // Default callback to handle interrupt signal
329 // Maybe be overwritten by some subcommand (eg. targets commands)
330 err := OnSignals(func(sig os.Signal) {
331 Log.Debugf("Send signal %v (from main)", sig)
332 if IsInterruptSignal(sig) {
333 err := cli.NewExitError("Interrupted\n", int(syscall.EINTR))
334 cli.HandleExitCoder(err)
338 cli.NewExitError(err.Error(), 1)
346 // XdsConnInit Initialized HTTP and WebSocket connection to XDS agent
347 func XdsConnInit(ctx *cli.Context) error {
350 // Define HTTP and WS url
351 agentURL := ctx.String("url")
352 serverURL := ctx.String("url-server")
354 // Allow to only set port number
355 if match, _ := regexp.MatchString("^([0-9]+)$", agentURL); match {
356 agentURL = "http://localhost:" + ctx.String("url")
358 if match, _ := regexp.MatchString("^([0-9]+)$", serverURL); match {
359 serverURL = "http://localhost:" + ctx.String("url-server")
361 // Add http prefix if missing
362 if agentURL != "" && !strings.HasPrefix(agentURL, "http://") {
363 agentURL = "http://" + agentURL
365 if serverURL != "" && !strings.HasPrefix(serverURL, "http://") {
366 serverURL = "http://" + serverURL
369 lvl := common.HTTPLogLevelWarning
370 if Log.Level == logrus.DebugLevel {
371 lvl = common.HTTPLogLevelDebug
374 // Create HTTP client
375 Log.Debugln("Connect HTTP client on ", agentURL)
376 conf := common.HTTPClientConfig{
377 URLPrefix: "/api/v1",
378 HeaderClientKeyName: "Xds-Agent-Sid",
381 LogPrefix: "XDSAGENT: ",
385 HTTPCli, err = common.HTTPNewClient(agentURL, conf)
387 errmsg := err.Error()
388 m, err := regexp.MatchString("Get http.?://", errmsg)
389 if (m && err == nil) || strings.Contains(errmsg, "Failed to get device ID") {
390 i := strings.LastIndex(errmsg, ":")
391 newErr := "Cannot connection to " + agentURL
393 newErr += " (" + strings.TrimSpace(errmsg[i+1:]) + ")"
395 newErr += " (" + strings.TrimSpace(errmsg) + ")"
399 return cli.NewExitError(errmsg, 1)
401 HTTPCli.SetLogLevel(ctx.String("loglevel"))
402 Log.Infoln("HTTP session ID : ", HTTPCli.GetClientID())
404 // Create io Websocket client
405 Log.Debugln("Connecting IO.socket client on ", agentURL)
407 IOSkClient, err = NewIoSocketClient(agentURL, HTTPCli.GetClientID())
409 return cli.NewExitError(err.Error(), 1)
412 IOSkClient.On("error", func(err error) {
413 fmt.Println("ERROR Websocket: ", err.Error())
416 ctx.App.Metadata["httpCli"] = HTTPCli
417 ctx.App.Metadata["ioskCli"] = IOSkClient
419 // Display version in logs (debug helpers)
420 ver := xaapiv1.XDSVersion{}
421 if err := XdsVersionGet(&ver); err != nil {
422 return cli.NewExitError("ERROR while retrieving XDS version: "+err.Error(), 1)
424 Log.Infof("XDS Agent/Server version: %v", ver)
426 // Get current config and update connection to server when needed
427 xdsConf := xaapiv1.APIConfig{}
428 if err := XdsConfigGet(&xdsConf); err != nil {
429 return cli.NewExitError("ERROR while getting XDS config: "+err.Error(), 1)
431 if len(xdsConf.Servers) < 1 {
432 return cli.NewExitError("No XDS Server connected", 1)
434 svrCfg := xdsConf.Servers[XdsServerIndexGet()]
435 if (serverURL != "" && svrCfg.URL != serverURL) || !svrCfg.Connected {
436 Log.Infof("Update XDS Server config: serverURL=%v, svrCfg=%v", serverURL, svrCfg)
438 svrCfg.URL = serverURL
440 svrCfg.ConnRetry = 10
441 if err := XdsConfigSet(xdsConf); err != nil {
442 return cli.NewExitError("ERROR while updating XDS server URL: "+err.Error(), 1)
449 // XdsConnClose Terminate connection to XDS agent
450 func XdsConnClose() {
451 Log.Debugf("Closing HTTP client session...")
453 if httpCli, ok := app.Metadata["httpCli"]; ok {
454 c := httpCli.(*common.HTTPClient)
458 Log.Debugf("Closing WebSocket connection...")
460 if ioskCli, ok := app.Metadata["ioskCli"]; ok {
461 c := ioskCli.(*socketio_client.Client)
466 // NewTableWriter Create a writer that inserts padding around tab-delimited
467 func NewTableWriter() *tabwriter.Writer {
468 writer := new(tabwriter.Writer)
469 writer.Init(os.Stdout, 0, 8, 0, '\t', 0)