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{}) {
78 err := fmt.Sprintf(f, a...)
79 fmt.Fprintf(os.Stderr, err+"\n")
85 var earlyDebug []string
87 // Allow to set app name from cli (useful for debugging)
89 AppName = os.Getenv("XDS_APPNAME")
92 panic("Invalid setup, AppName not define !")
94 if AppNativeName == "" {
95 AppNativeName = AppName[4:]
97 appUsage := fmt.Sprintf("command line tool for X(cross) Development System.")
98 appDescription := fmt.Sprintf("%s utility for X(cross) Development System\n", AppName)
100 Setting of global options is driven either by environment variables or by command
101 line options or using a config file knowning that the following priority order is used:
102 1. use option value (for example --url option),
103 2. else use variable 'XDS_xxx' (for example 'XDS_AGENT_URL' variable) when a
104 config file is specified with '--config|-c' option,
105 3. else use 'XDS_xxx' (for example 'XDS_AGENT_URL') environment variable.
108 # Get help of 'projects' sub-command
109 ` + AppName + ` projects --help
112 ` + AppName + ` sdks ls
115 ` + AppName + ` prj add --label="myProject" --type=cs --path=$HOME/xds-workspace/myProject
118 // Create a new App instance
122 app.Version = AppVersion + " (" + AppSubVersion + ")"
123 app.Authors = appAuthors
124 app.Copyright = appCopyright
125 app.Metadata = make(map[string]interface{})
126 app.Metadata["version"] = AppVersion
127 app.Metadata["git-tag"] = AppSubVersion
128 app.Metadata["logger"] = Log
130 // Create env vars help
131 dynDesc := "\nENVIRONMENT VARIABLES:"
132 for _, f := range app.Flags {
133 var env, usage string
136 fs := f.(cli.StringFlag)
140 fb := f.(cli.BoolFlag)
144 exitError(1, "Un-implemented option type")
147 dynDesc += fmt.Sprintf("\n %s \t\t %s", env, usage)
150 app.Description = appDescription + dynDesc
152 // Declare global flags
153 app.Flags = []cli.Flag{
156 EnvVar: "XDS_CONFIG",
157 Usage: "env config file to source on startup",
161 EnvVar: "XDS_LOGLEVEL",
162 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)",
163 Value: defaultLogLevel,
167 EnvVar: "XDS_AGENT_URL",
168 Value: "localhost:8800",
169 Usage: "local XDS agent url",
172 Name: "url-server, us",
173 EnvVar: "XDS_SERVER_URL",
175 Usage: "overwrite remote XDS server url (default value set in xds-agent-config.json file)",
178 Name: "timestamp, ts",
179 EnvVar: "XDS_TIMESTAMP",
180 Usage: "prefix output with timestamp",
185 app.Commands = []cli.Command{}
187 initCmdProjects(&app.Commands)
188 initCmdSdks(&app.Commands)
189 initCmdExec(&app.Commands)
190 initCmdMisc(&app.Commands)
192 sort.Sort(cli.FlagsByName(app.Flags))
193 sort.Sort(cli.CommandsByName(app.Commands))
195 // Early and manual processing of --config option in order to set XDS_xxx
196 // variables before parsing of option by app cli
197 confFile := os.Getenv("XDS_CONFIG")
198 for idx, a := range os.Args[1:] {
199 if a == "-c" || a == "--config" || a == "-config" {
200 confFile = os.Args[idx+2]
205 // Load config file if requested
207 earlyDebug = append(earlyDebug, fmt.Sprintf("confFile detected: %v", confFile))
208 if !common.Exists(confFile) {
209 exitError(1, "Error env config file not found")
211 // Load config file variables that will overwrite env variables
212 err := godotenv.Overload(confFile)
214 exitError(1, "Error loading env config file "+confFile)
217 // Keep confFile settings in a map
218 EnvConfFileMap, err = godotenv.Read(confFile)
220 exitError(1, "Error reading env config file "+confFile)
222 earlyDebug = append(earlyDebug, fmt.Sprintf("EnvConfFileMap: %v", EnvConfFileMap))
225 app.Before = func(ctx *cli.Context) error {
228 // Don't init anything when no argument or help option is set
232 for _, a := range ctx.Args() {
234 case "-h", "--h", "-help", "--help":
239 loglevel := ctx.String("log")
240 // Set logger level and formatter
241 if Log.Level, err = logrus.ParseLevel(loglevel); err != nil {
242 msg := fmt.Sprintf("Invalid log level : \"%v\"\n", loglevel)
243 return cli.NewExitError(msg, 1)
245 Log.Formatter = &logrus.TextFormatter{}
247 Log.Infof("%s version: %s", AppName, app.Version)
248 for _, str := range earlyDebug {
251 Log.Debugf("\nEnvironment: %v\n", os.Environ())
253 if err = XdsConnInit(ctx); err != nil {
254 // Directly call HandleExitCoder to avoid to print help (ShowAppHelp)
255 // Note that this function wil never return and program will exit
256 cli.HandleExitCoder(err)
262 // Close HTTP client and WS connection on exit
270 // XdsConnInit Initialized HTTP and WebSocket connection to XDS agent
271 func XdsConnInit(ctx *cli.Context) error {
274 // Define HTTP and WS url
275 agentURL := ctx.String("url")
276 serverURL := ctx.String("url-server")
278 // Allow to only set port number
279 if match, _ := regexp.MatchString("^([0-9]+)$", agentURL); match {
280 agentURL = "http://localhost:" + ctx.String("url")
282 if match, _ := regexp.MatchString("^([0-9]+)$", serverURL); match {
283 serverURL = "http://localhost:" + ctx.String("url-server")
285 // Add http prefix if missing
286 if agentURL != "" && !strings.HasPrefix(agentURL, "http://") {
287 agentURL = "http://" + agentURL
289 if serverURL != "" && !strings.HasPrefix(serverURL, "http://") {
290 serverURL = "http://" + serverURL
293 // Create HTTP client
294 Log.Debugln("Connect HTTP client on ", agentURL)
295 conf := common.HTTPClientConfig{
296 URLPrefix: "/api/v1",
297 HeaderClientKeyName: "Xds-Agent-Sid",
300 LogPrefix: "XDSAGENT: ",
301 LogLevel: common.HTTPLogLevelWarning,
304 HTTPCli, err = common.HTTPNewClient(agentURL, conf)
306 errmsg := err.Error()
307 if m, err := regexp.MatchString("Get http.?://", errmsg); m && err == nil {
308 i := strings.LastIndex(errmsg, ":")
309 errmsg = "Cannot connection to " + agentURL + errmsg[i:]
311 return cli.NewExitError(errmsg, 1)
313 HTTPCli.SetLogLevel(ctx.String("loglevel"))
314 Log.Infoln("HTTP session ID : ", HTTPCli.GetClientID())
316 // Create io Websocket client
317 Log.Debugln("Connecting IO.socket client on ", agentURL)
319 opts := &socketio_client.Options{
320 Transport: "websocket",
321 Header: make(map[string][]string),
323 opts.Header["XDS-AGENT-SID"] = []string{HTTPCli.GetClientID()}
325 IOsk, err = socketio_client.NewClient(agentURL, opts)
327 return cli.NewExitError("IO.socket connection error: "+err.Error(), 1)
330 IOsk.On("error", func(err error) {
331 fmt.Println("ERROR Websocket: ", err.Error())
334 ctx.App.Metadata["httpCli"] = HTTPCli
335 ctx.App.Metadata["ioskCli"] = IOsk
337 // Display version in logs (debug helpers)
338 ver := xaapiv1.XDSVersion{}
339 if err := XdsVersionGet(&ver); err != nil {
340 return cli.NewExitError("ERROR while retrieving XDS version: "+err.Error(), 1)
342 Log.Infof("XDS Agent/Server version: %v", ver)
344 // Get current config and update connection to server when needed
345 xdsConf := xaapiv1.APIConfig{}
346 if err := XdsConfigGet(&xdsConf); err != nil {
347 return cli.NewExitError("ERROR while getting XDS config: "+err.Error(), 1)
349 svrCfg := xdsConf.Servers[XdsServerIndexGet()]
350 if serverURL != "" && (svrCfg.URL != serverURL || !svrCfg.Connected) {
351 svrCfg.URL = serverURL
352 svrCfg.ConnRetry = 10
353 if err := XdsConfigSet(xdsConf); err != nil {
354 return cli.NewExitError("ERROR while updating XDS server URL: "+err.Error(), 1)
361 // XdsConnClose Terminate connection to XDS agent
362 func XdsConnClose() {
363 Log.Debugf("Closing HTTP client session...")
365 if httpCli, ok := app.Metadata["httpCli"]; ok {
366 c := httpCli.(*common.HTTPClient)
370 Log.Debugf("Closing WebSocket connection...")
372 if ioskCli, ok := app.Metadata["ioskCli"]; ok {
373 c := ioskCli.(*socketio_client.Client)
378 // NewTableWriter Create a writer that inserts padding around tab-delimited
379 func NewTableWriter() *tabwriter.Writer {
380 writer := new(tabwriter.Writer)
381 writer.Init(os.Stdout, 0, 8, 0, '\t', 0)