Add packaging files
[src/xds/xds-cli.git] / main.go
1 /*
2  * Copyright (C) 2017-2018 "IoT.bzh"
3  * Author Sebastien Douheret <sebastien@iot.bzh>
4  *
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
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  *
18  * xds-cli: command line tool used to control / interface X(cross) Development System.
19  */
20
21 package main
22
23 import (
24         "fmt"
25         "os"
26         "regexp"
27         "sort"
28         "strings"
29         "syscall"
30         "text/tabwriter"
31
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"
35
36         "github.com/joho/godotenv"
37         "github.com/urfave/cli"
38 )
39
40 var appAuthors = []cli.Author{
41         cli.Author{Name: "Sebastien Douheret", Email: "sebastien@iot.bzh"},
42 }
43
44 // AppName name of this application
45 var AppName = "xds-cli"
46
47 // AppNativeName native command name that this application can overload
48 var AppNativeName = "cli"
49
50 // AppVersion Version of this application
51 // (set by Makefile)
52 var AppVersion = "?.?.?"
53
54 // AppSubVersion is the git tag id added to version string
55 // Should be set by compilation -ldflags "-X main.AppSubVersion=xxx"
56 // (set by Makefile)
57 var AppSubVersion = "unknown-dev"
58
59 // Application details
60 const (
61         appCopyright    = "Copyright (C) 2017-2018 IoT.bzh - Apache-2.0"
62         defaultLogLevel = "error"
63 )
64
65 // Log Global variable that hold logger
66 var Log = logrus.New()
67
68 // EnvConfFileMap Global variable that hold environment vars loaded from config file
69 var EnvConfFileMap map[string]string
70
71 // HTTPCli Global variable that hold HTTP Client
72 var HTTPCli *common.HTTPClient
73
74 // IOSkClient Global variable that hold SocketIo client
75 var IOSkClient *IOSockClient
76
77 // exitError exists this program with the specified error
78 func exitError(code int, f string, a ...interface{}) {
79         earlyDisplay()
80         err := fmt.Sprintf(f, a...)
81         fmt.Fprintf(os.Stderr, err+"\n")
82         os.Exit(code)
83 }
84
85 // earlyDebug Used to log info before logger has been initialized
86 var earlyDebug []string
87
88 func earlyPrintf(format string, args ...interface{}) {
89         earlyDebug = append(earlyDebug, fmt.Sprintf(format, args...))
90 }
91
92 func earlyDisplay() {
93         for _, str := range earlyDebug {
94                 Log.Infof("%s", str)
95         }
96         earlyDebug = []string{}
97 }
98
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...)
104         }
105 }
106
107 // main
108 func main() {
109
110         // Allow to set app name from cli (useful for debugging)
111         if AppName == "" {
112                 AppName = os.Getenv("XDS_APPNAME")
113         }
114         if AppName == "" {
115                 panic("Invalid setup, AppName not define !")
116         }
117         if AppNativeName == "" {
118                 AppNativeName = AppName[4:]
119         }
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)
122         appDescription += `
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.
129
130     Examples:
131     # Get help of 'projects' sub-command
132     ` + AppName + ` projects --help
133
134     # List all SDKs
135     ` + AppName + ` sdks ls
136
137     # Add a new project
138     ` + AppName + ` prj add --label="myProject" --type=cs --path=$HOME/xds-workspace/myProject
139 `
140
141         // Create a new App instance
142         app := cli.NewApp()
143         app.Name = AppName
144         app.Usage = appUsage
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
153
154         // Create env vars help
155         dynDesc := "\nENVIRONMENT VARIABLES:"
156         for _, f := range app.Flags {
157                 var env, usage string
158                 switch f.(type) {
159                 case cli.StringFlag:
160                         fs := f.(cli.StringFlag)
161                         env = fs.EnvVar
162                         usage = fs.Usage
163                 case cli.BoolFlag:
164                         fb := f.(cli.BoolFlag)
165                         env = fb.EnvVar
166                         usage = fb.Usage
167                 default:
168                         exitError(1, "Un-implemented option type")
169                 }
170                 if env != "" {
171                         dynDesc += fmt.Sprintf("\n %s \t\t %s", env, usage)
172                 }
173         }
174         app.Description = appDescription + dynDesc
175
176         // Declare global flags
177         app.Flags = []cli.Flag{
178                 cli.StringFlag{
179                         Name:   "config, c",
180                         EnvVar: "XDS_CONFIG",
181                         Usage:  "env config file to source on startup",
182                 },
183                 cli.StringFlag{
184                         Name:   "log, l",
185                         EnvVar: "XDS_LOGLEVEL",
186                         Usage:  "logging level (supported levels: panic, fatal, error, warn, info, debug)",
187                         Value:  defaultLogLevel,
188                 },
189                 cli.StringFlag{
190                         Name:   "logfile",
191                         Value:  "stderr",
192                         Usage:  "filename where logs will be redirected (default stderr)\n\t",
193                         EnvVar: "XDS_LOGFILENAME",
194                 },
195                 cli.StringFlag{
196                         Name:   "url, u",
197                         EnvVar: "XDS_AGENT_URL",
198                         Value:  "localhost:8800",
199                         Usage:  "local XDS agent url",
200                 },
201                 cli.StringFlag{
202                         Name:   "url-server, us",
203                         EnvVar: "XDS_SERVER_URL",
204                         Value:  "",
205                         Usage:  "overwrite remote XDS server url (default value set in xds-agent-config.json file)",
206                 },
207                 cli.BoolFlag{
208                         Name:   "timestamp, ts",
209                         EnvVar: "XDS_TIMESTAMP",
210                         Usage:  "prefix output with timestamp",
211                 },
212         }
213
214         // Declare commands
215         app.Commands = []cli.Command{}
216
217         initCmdProjects(&app.Commands)
218         initCmdSdks(&app.Commands)
219         initCmdExec(&app.Commands)
220         initCmdTargets(&app.Commands)
221         initCmdMisc(&app.Commands)
222
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"})
230                 }
231                 for j, subCmd := range cmd.Subcommands {
232                         app.Commands[i].Subcommands[j].Flags = append(subCmd.Flags, cli.StringFlag{Hidden: true, Name: "config, c"})
233                 }
234         }
235
236         sort.Sort(cli.FlagsByName(app.Flags))
237         sort.Sort(cli.CommandsByName(app.Commands))
238
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]
245                         break
246                 }
247         }
248
249         // Load config file if requested
250         if confFile != "" {
251                 earlyPrintf("confFile detected: %v", confFile)
252                 confFile, err := common.ResolveEnvVar(confFile)
253                 if err != nil {
254                         exitError(1, "Error while resolving confFile: %v", err)
255                 }
256                 earlyPrintf("Resolved confFile: %v", confFile)
257                 if !common.Exists(confFile) {
258                         exitError(1, "Error env config file not found")
259                 }
260                 // Load config file variables that will overwrite env variables
261                 err = godotenv.Overload(confFile)
262                 if err != nil {
263                         exitError(1, "Error loading env config file "+confFile)
264                 }
265
266                 // Keep confFile settings in a map
267                 EnvConfFileMap, err = godotenv.Read(confFile)
268                 if err != nil {
269                         exitError(1, "Error reading env config file "+confFile)
270                 }
271                 earlyPrintf("EnvConfFileMap: %v", EnvConfFileMap)
272         }
273
274         app.Before = func(ctx *cli.Context) error {
275                 var err error
276
277                 // Don't init anything when no argument or help option is set
278                 if ctx.NArg() == 0 {
279                         return nil
280                 }
281                 for _, a := range ctx.Args() {
282                         switch a {
283                         case "-h", "--h", "-help", "--help":
284                                 return nil
285                         }
286                 }
287
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)
293                 }
294                 Log.Formatter = &logrus.TextFormatter{}
295
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)
299                         if err != nil {
300                                 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
301                                 return cli.NewExitError(msgErr, 1)
302                         }
303                         Log.Infof("Logging to file: %s", logFile)
304                         Log.Out = fdL
305                 }
306
307                 Log.Infof("%s version: %s", AppName, app.Version)
308                 earlyDisplay()
309                 Log.Debugf("\nEnvironment: %v\n", os.Environ())
310
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)
315                 }
316
317                 return nil
318         }
319
320         // Close HTTP client and WS connection on exit
321         defer func() {
322                 XdsConnClose()
323         }()
324
325         // Start signals monitoring routine
326         MonitorSignals()
327
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)
335                 }
336         })
337         if err != nil {
338                 cli.NewExitError(err.Error(), 1)
339                 return
340         }
341
342         // Run the cli app
343         app.Run(os.Args)
344 }
345
346 // XdsConnInit Initialized HTTP and WebSocket connection to XDS agent
347 func XdsConnInit(ctx *cli.Context) error {
348         var err error
349
350         // Define HTTP and WS url
351         agentURL := ctx.String("url")
352         serverURL := ctx.String("url-server")
353
354         // Allow to only set port number
355         if match, _ := regexp.MatchString("^([0-9]+)$", agentURL); match {
356                 agentURL = "http://localhost:" + ctx.String("url")
357         }
358         if match, _ := regexp.MatchString("^([0-9]+)$", serverURL); match {
359                 serverURL = "http://localhost:" + ctx.String("url-server")
360         }
361         // Add http prefix if missing
362         if agentURL != "" && !strings.HasPrefix(agentURL, "http://") {
363                 agentURL = "http://" + agentURL
364         }
365         if serverURL != "" && !strings.HasPrefix(serverURL, "http://") {
366                 serverURL = "http://" + serverURL
367         }
368
369         lvl := common.HTTPLogLevelWarning
370         if Log.Level == logrus.DebugLevel {
371                 lvl = common.HTTPLogLevelDebug
372         }
373
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",
379                 CsrfDisable:         true,
380                 LogOut:              Log.Out,
381                 LogPrefix:           "XDSAGENT: ",
382                 LogLevel:            lvl,
383         }
384
385         HTTPCli, err = common.HTTPNewClient(agentURL, conf)
386         if err != nil {
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
392                         if i > 0 {
393                                 newErr += " (" + strings.TrimSpace(errmsg[i+1:]) + ")"
394                         } else {
395                                 newErr += " (" + strings.TrimSpace(errmsg) + ")"
396                         }
397                         errmsg = newErr
398                 }
399                 return cli.NewExitError(errmsg, 1)
400         }
401         HTTPCli.SetLogLevel(ctx.String("loglevel"))
402         Log.Infoln("HTTP session ID : ", HTTPCli.GetClientID())
403
404         // Create io Websocket client
405         Log.Debugln("Connecting IO.socket client on ", agentURL)
406
407         IOSkClient, err = NewIoSocketClient(agentURL, HTTPCli.GetClientID())
408         if err != nil {
409                 return cli.NewExitError(err.Error(), 1)
410         }
411
412         IOSkClient.On("error", func(err error) {
413                 fmt.Println("ERROR Websocket: ", err.Error())
414         })
415
416         ctx.App.Metadata["httpCli"] = HTTPCli
417         ctx.App.Metadata["ioskCli"] = IOSkClient
418
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)
423         }
424         Log.Infof("XDS Agent/Server version: %v", ver)
425
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)
430         }
431         if len(xdsConf.Servers) < 1 {
432                 return cli.NewExitError("No XDS Server connected", 1)
433         }
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)
437                 if serverURL != "" {
438                         svrCfg.URL = serverURL
439                 }
440                 svrCfg.ConnRetry = 10
441                 if err := XdsConfigSet(xdsConf); err != nil {
442                         return cli.NewExitError("ERROR while updating XDS server URL: "+err.Error(), 1)
443                 }
444         }
445
446         return nil
447 }
448
449 // XdsConnClose Terminate connection to XDS agent
450 func XdsConnClose() {
451         Log.Debugf("Closing HTTP client session...")
452         /* TODO
453         if httpCli, ok := app.Metadata["httpCli"]; ok {
454                 c := httpCli.(*common.HTTPClient)
455         }
456         */
457
458         Log.Debugf("Closing WebSocket connection...")
459         /*
460                 if ioskCli, ok := app.Metadata["ioskCli"]; ok {
461                         c := ioskCli.(*socketio_client.Client)
462                 }
463         */
464 }
465
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)
470         return writer
471 }