/
root.go
93 lines (76 loc) · 2.53 KB
/
root.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package cmd
import (
"context"
"fmt"
"os"
"os/signal"
"path/filepath"
"syscall"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
// potentially injected by makefile
var (
version string
builddate string
githash string
)
var cfgFile string
var logLevel string
var logFormat string
type ShortFormatter struct {
LevelDesc []string
}
func (f *ShortFormatter) Format(entry *log.Entry) ([]byte, error) {
return []byte(fmt.Sprintf("%s %s\n", f.LevelDesc[entry.Level], entry.Message)), nil
}
func rootCommand() *cobra.Command {
rootCmd := &cobra.Command{
Use: "virter",
Version: version,
Short: "Virter manages local virtual machines",
Long: `Virter manages local virtual machines for development and testing. The
machines are controlled with libvirt, with qcow2 chained images for storage
and cloud-init for basic access configuration. This allows for fast cloning
and resetting, for a stable test environment.`,
}
defaultLogLevel := log.InfoLevel.String()
if envLogLevel, ok := os.LookupEnv("VIRTER_LOG_LEVEL"); ok {
defaultLogLevel = envLogLevel
}
configName := filepath.Join(configPath(), "virter.toml")
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", fmt.Sprintf("config file (default is %v)", configName))
rootCmd.PersistentFlags().StringVarP(&logLevel, "loglevel", "l", defaultLogLevel,
"Log level, default may be set with environment variable \"VIRTER_LOG_LEVEL\"")
rootCmd.PersistentFlags().StringVar(&logFormat, "logformat", "default", "Log format, current options: short")
rootCmd.AddCommand(versionCommand())
rootCmd.AddCommand(imageCommand())
rootCmd.AddCommand(vmCommand())
rootCmd.AddCommand(networkCommand())
rootCmd.AddCommand(registryCommand())
return rootCmd
}
func initLogging() {
level, err := log.ParseLevel(logLevel)
if err != nil {
log.Fatal(err)
}
log.SetLevel(level)
if logFormat == "short" {
shortFormatter := new(ShortFormatter)
shortFormatter.LevelDesc = []string{"PANC", "FATL", "ERRO", "WARN", "INFO", "DEBG"}
log.SetFormatter(shortFormatter)
}
}
// Execute adds all child commands to the root command and sets flags appropriately
func Execute() {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
cobra.OnInitialize(initLogging, initConfig, initSSHFromConfig)
if err := rootCommand().ExecuteContext(ctx); err != nil {
log.Fatal(err)
}
}
func suggestNone(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return nil, cobra.ShellCompDirectiveNoFileComp
}