talm

Форк
0
/
main.go 
128 строк · 3.9 Кб
1
//go:generate go run tools/generate_presets.go
2

3
package main
4

5
import (
6
	"context"
7
	"fmt"
8
	"io/ioutil"
9
	"os"
10
	"path/filepath"
11
	"strings"
12
	"time"
13

14
	"gopkg.in/yaml.v3"
15

16
	"github.com/aenix-io/talm/pkg/commands"
17
	"github.com/siderolabs/talos/cmd/talosctl/cmd/common"
18
	"github.com/siderolabs/talos/pkg/machinery/constants"
19
	"github.com/spf13/cobra"
20
)
21

22
var Version = "dev"
23

24
// rootCmd represents the base command when called without any subcommands.
25
var rootCmd = &cobra.Command{
26
	Use:               "talm",
27
	Short:             "Manage Talos the GitOps Way!",
28
	Long:              ``,
29
	Version:           Version,
30
	SilenceErrors:     true,
31
	SilenceUsage:      true,
32
	DisableAutoGenTag: true,
33
}
34

35
func main() {
36
	if err := Execute(); err != nil {
37
		os.Exit(1)
38
	}
39
}
40

41
func Execute() error {
42
	rootCmd.PersistentFlags().StringVar(
43
		&commands.GlobalArgs.Talosconfig,
44
		"talosconfig",
45
		"",
46
		fmt.Sprintf("The path to the Talos configuration file. Defaults to '%s' env variable if set, otherwise '%s' and '%s' in order.",
47
			constants.TalosConfigEnvVar,
48
			filepath.Join("$HOME", constants.TalosDir, constants.TalosconfigFilename),
49
			filepath.Join(constants.ServiceAccountMountPath, constants.TalosconfigFilename),
50
		),
51
	)
52
	rootCmd.PersistentFlags().StringVar(&commands.Config.RootDir, "root", ".", "root directory of the project")
53
	rootCmd.PersistentFlags().StringVar(&commands.GlobalArgs.CmdContext, "context", "", "Context to be used in command")
54
	rootCmd.PersistentFlags().StringSliceVarP(&commands.GlobalArgs.Nodes, "nodes", "n", []string{}, "target the specified nodes")
55
	rootCmd.PersistentFlags().StringSliceVarP(&commands.GlobalArgs.Endpoints, "endpoints", "e", []string{}, "override default endpoints in Talos configuration")
56
	rootCmd.PersistentFlags().StringVar(&commands.GlobalArgs.Cluster, "cluster", "", "Cluster to connect to if a proxy endpoint is used.")
57
	rootCmd.PersistentFlags().Bool("version", false, "Print the version number of the application")
58

59
	cmd, err := rootCmd.ExecuteContextC(context.Background())
60
	if err != nil && !common.SuppressErrors {
61
		fmt.Fprintln(os.Stderr, err.Error())
62

63
		errorString := err.Error()
64
		// TODO: this is a nightmare, but arg-flag related validation returns simple `fmt.Errorf`, no way to distinguish
65
		//       these errors
66
		if strings.Contains(errorString, "arg(s)") || strings.Contains(errorString, "flag") || strings.Contains(errorString, "command") {
67
			fmt.Fprintln(os.Stderr)
68
			fmt.Fprintln(os.Stderr, cmd.UsageString())
69
		}
70
	}
71

72
	return err
73
}
74

75
func init() {
76
	cobra.OnInitialize(initConfig)
77

78
	for _, cmd := range commands.Commands {
79
		rootCmd.AddCommand(cmd)
80
	}
81
}
82

83
func initConfig() {
84
	cmd, _, _ := rootCmd.Find(os.Args[1:])
85
	if cmd == nil {
86
		return
87
	}
88
	if strings.HasPrefix(cmd.Use, "init") {
89
		if strings.HasPrefix(Version, "v") {
90
			commands.Config.InitOptions.Version = strings.TrimPrefix(Version, `v`)
91
		} else {
92
			commands.Config.InitOptions.Version = "0.1.0"
93
		}
94
	} else {
95
		configFile := filepath.Join(commands.Config.RootDir, "Chart.yaml")
96
		if err := loadConfig(configFile); err != nil {
97
			fmt.Fprintf(os.Stderr, "Error loading configuration: %v\n", err)
98
			os.Exit(1)
99
		}
100
	}
101
}
102

103
func loadConfig(filename string) error {
104
	data, err := ioutil.ReadFile(filename)
105
	if err != nil {
106
		return fmt.Errorf("error reading configuration file: %w", err)
107
	}
108

109
	if err := yaml.Unmarshal(data, &commands.Config); err != nil {
110
		return fmt.Errorf("error unmarshalling configuration: %w", err)
111
	}
112
	if commands.GlobalArgs.Talosconfig == "" {
113
		commands.GlobalArgs.Talosconfig = commands.Config.GlobalOptions.Talosconfig
114
	}
115
	if commands.Config.TemplateOptions.KubernetesVersion == "" {
116
		commands.Config.TemplateOptions.KubernetesVersion = constants.DefaultKubernetesVersion
117
	}
118
	if commands.Config.ApplyOptions.Timeout == "" {
119
		commands.Config.ApplyOptions.Timeout = constants.ConfigTryTimeout.String()
120
	} else {
121
		var err error
122
		commands.Config.ApplyOptions.TimeoutDuration, err = time.ParseDuration(commands.Config.ApplyOptions.Timeout)
123
		if err != nil {
124
			panic(err)
125
		}
126
	}
127
	return nil
128
}
129

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.