X-Git-Url: https://gerrit.automotivelinux.org/gerrit/gitweb?a=blobdiff_plain;f=main.go;h=c8effe627e94a7af7c1077c9fb5ca4a40309e26a;hb=f48c7c3164b0568de45d7ccc88b0ce7724a17cc4;hp=1c0d886dd11e7cae4ec6348d80add45f4de3a4f6;hpb=f95aa5f0e39b85198655e8399c161fc5e6cd8a59;p=src%2Fxds%2Fxds-cli.git diff --git a/main.go b/main.go index 1c0d886..c8effe6 100644 --- a/main.go +++ b/main.go @@ -29,6 +29,7 @@ import ( "text/tabwriter" "github.com/Sirupsen/logrus" + "github.com/iotbzh/xds-agent/lib/xaapiv1" common "github.com/iotbzh/xds-common/golib" "github.com/joho/godotenv" socketio_client "github.com/sebd71/go-socket.io-client" @@ -74,14 +75,28 @@ var IOsk *socketio_client.Client // exitError exists this program with the specified error func exitError(code int, f string, a ...interface{}) { + earlyDisplay() err := fmt.Sprintf(f, a...) fmt.Fprintf(os.Stderr, err+"\n") os.Exit(code) } +// earlyDebug Used to log info before logger has been initialized +var earlyDebug []string + +func earlyPrintf(format string, args ...interface{}) { + earlyDebug = append(earlyDebug, fmt.Sprintf(format, args...)) +} + +func earlyDisplay() { + for _, str := range earlyDebug { + Log.Infof("%s", str) + } + earlyDebug = []string{} +} + // main func main() { - var earlyDebug []string // Allow to set app name from cli (useful for debugging) if AppName == "" { @@ -99,9 +114,9 @@ func main() { Setting of global options is driven either by environment variables or by command line options or using a config file knowning that the following priority order is used: 1. use option value (for example --url option), - 2. else use variable 'XDS_xxx' (for example 'XDS_SERVER_URL' variable) when a + 2. else use variable 'XDS_xxx' (for example 'XDS_AGENT_URL' variable) when a config file is specified with '--config|-c' option, - 3. else use 'XDS_xxx' (for example 'XDS_SERVER_URL') environment variable. + 3. else use 'XDS_xxx' (for example 'XDS_AGENT_URL') environment variable. Examples: # Get help of 'projects' sub-command @@ -163,9 +178,15 @@ func main() { }, cli.StringFlag{ Name: "url, u", + EnvVar: "XDS_AGENT_URL", + Value: "localhost:8800", + Usage: "local XDS agent url", + }, + cli.StringFlag{ + Name: "url-server, us", EnvVar: "XDS_SERVER_URL", - Value: "localhost:8000", - Usage: "remote XDS server url", + Value: "", + Usage: "overwrite remote XDS server url (default value set in xds-agent-config.json file)", }, cli.BoolFlag{ Name: "timestamp, ts", @@ -182,6 +203,19 @@ func main() { initCmdExec(&app.Commands) initCmdMisc(&app.Commands) + // Add --config option to all commands to support --config option either before or after command verb + // IOW support following both syntaxes: + // xds-cli exec --config myprj.conf ... + // xds-cli --config myprj.conf exec ... + for i, cmd := range app.Commands { + if len(cmd.Flags) > 0 { + app.Commands[i].Flags = append(cmd.Flags, cli.StringFlag{Hidden: true, Name: "config, c"}) + } + for j, subCmd := range cmd.Subcommands { + app.Commands[i].Subcommands[j].Flags = append(subCmd.Flags, cli.StringFlag{Hidden: true, Name: "config, c"}) + } + } + sort.Sort(cli.FlagsByName(app.Flags)) sort.Sort(cli.CommandsByName(app.Commands)) @@ -197,7 +231,7 @@ func main() { // Load config file if requested if confFile != "" { - earlyDebug = append(earlyDebug, fmt.Sprintf("confFile detected: %v", confFile)) + earlyPrintf("confFile detected: %v", confFile) if !common.Exists(confFile) { exitError(1, "Error env config file not found") } @@ -212,7 +246,7 @@ func main() { if err != nil { exitError(1, "Error reading env config file "+confFile) } - earlyDebug = append(earlyDebug, fmt.Sprintf("EnvConfFileMap: %v", EnvConfFileMap)) + earlyPrintf("EnvConfFileMap: %v", EnvConfFileMap) } app.Before = func(ctx *cli.Context) error { @@ -238,9 +272,7 @@ func main() { Log.Formatter = &logrus.TextFormatter{} Log.Infof("%s version: %s", AppName, app.Version) - for _, str := range earlyDebug { - Log.Infof("%s", str) - } + earlyDisplay() Log.Debugf("\nEnvironment: %v\n", os.Environ()) if err = XdsConnInit(ctx); err != nil { @@ -265,20 +297,26 @@ func XdsConnInit(ctx *cli.Context) error { var err error // Define HTTP and WS url - baseURL := ctx.String("url") + agentURL := ctx.String("url") + serverURL := ctx.String("url-server") // Allow to only set port number - if match, _ := regexp.MatchString("^([0-9]+)$", baseURL); match { - baseURL = "http://localhost:" + ctx.String("url") + if match, _ := regexp.MatchString("^([0-9]+)$", agentURL); match { + agentURL = "http://localhost:" + ctx.String("url") + } + if match, _ := regexp.MatchString("^([0-9]+)$", serverURL); match { + serverURL = "http://localhost:" + ctx.String("url-server") } - // Add http prefix if missing - if !strings.HasPrefix(baseURL, "http://") { - baseURL = "http://" + baseURL + if agentURL != "" && !strings.HasPrefix(agentURL, "http://") { + agentURL = "http://" + agentURL + } + if serverURL != "" && !strings.HasPrefix(serverURL, "http://") { + serverURL = "http://" + serverURL } // Create HTTP client - Log.Debugln("Connect HTTP client on ", baseURL) + Log.Debugln("Connect HTTP client on ", agentURL) conf := common.HTTPClientConfig{ URLPrefix: "/api/v1", HeaderClientKeyName: "Xds-Agent-Sid", @@ -288,12 +326,12 @@ func XdsConnInit(ctx *cli.Context) error { LogLevel: common.HTTPLogLevelWarning, } - HTTPCli, err = common.HTTPNewClient(baseURL, conf) + HTTPCli, err = common.HTTPNewClient(agentURL, conf) if err != nil { errmsg := err.Error() if m, err := regexp.MatchString("Get http.?://", errmsg); m && err == nil { i := strings.LastIndex(errmsg, ":") - errmsg = "Cannot connection to " + baseURL + errmsg[i:] + errmsg = "Cannot connection to " + agentURL + errmsg[i:] } return cli.NewExitError(errmsg, 1) } @@ -301,7 +339,7 @@ func XdsConnInit(ctx *cli.Context) error { Log.Infoln("HTTP session ID : ", HTTPCli.GetClientID()) // Create io Websocket client - Log.Debugln("Connecting IO.socket client on ", baseURL) + Log.Debugln("Connecting IO.socket client on ", agentURL) opts := &socketio_client.Options{ Transport: "websocket", @@ -309,7 +347,7 @@ func XdsConnInit(ctx *cli.Context) error { } opts.Header["XDS-AGENT-SID"] = []string{HTTPCli.GetClientID()} - IOsk, err = socketio_client.NewClient(baseURL, opts) + IOsk, err = socketio_client.NewClient(agentURL, opts) if err != nil { return cli.NewExitError("IO.socket connection error: "+err.Error(), 1) } @@ -321,6 +359,30 @@ func XdsConnInit(ctx *cli.Context) error { ctx.App.Metadata["httpCli"] = HTTPCli ctx.App.Metadata["ioskCli"] = IOsk + // Display version in logs (debug helpers) + ver := xaapiv1.XDSVersion{} + if err := XdsVersionGet(&ver); err != nil { + return cli.NewExitError("ERROR while retrieving XDS version: "+err.Error(), 1) + } + Log.Infof("XDS Agent/Server version: %v", ver) + + // Get current config and update connection to server when needed + xdsConf := xaapiv1.APIConfig{} + if err := XdsConfigGet(&xdsConf); err != nil { + return cli.NewExitError("ERROR while getting XDS config: "+err.Error(), 1) + } + svrCfg := xdsConf.Servers[XdsServerIndexGet()] + if (serverURL != "" && svrCfg.URL != serverURL) || !svrCfg.Connected { + Log.Infof("Update XDS Server config: serverURL=%v, svrCfg=%v", serverURL, svrCfg) + if serverURL != "" { + svrCfg.URL = serverURL + } + svrCfg.ConnRetry = 10 + if err := XdsConfigSet(xdsConf); err != nil { + return cli.NewExitError("ERROR while updating XDS server URL: "+err.Error(), 1) + } + } + return nil }