talm

Форк
0
/
root.go 
134 строки · 4.2 Кб
1
// This Source Code Form is subject to the terms of the Mozilla Public
2
// License, v. 2.0. If a copy of the MPL was not distributed with this
3
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4

5
package commands
6

7
import (
8
	"context"
9
	"errors"
10
	"fmt"
11
	"time"
12

13
	"github.com/aenix-io/talm/pkg/modeline"
14
	"github.com/spf13/cobra"
15
	"google.golang.org/grpc"
16

17
	"github.com/siderolabs/talos/cmd/talosctl/pkg/talos/global"
18
	_ "github.com/siderolabs/talos/pkg/grpc/codec" // register codec
19
	"github.com/siderolabs/talos/pkg/machinery/client"
20
)
21

22
var kubernetesFlag bool
23

24
// GlobalArgs is the common arguments for the root command.
25
var GlobalArgs global.Args
26

27
var Config struct {
28
	RootDir       string
29
	GlobalOptions struct {
30
		Talosconfig string `yaml:"talosconfig"`
31
	} `yaml:"globalOptions"`
32
	TemplateOptions struct {
33
		Offline           bool     `yaml:"offline"`
34
		ValueFiles        []string `yaml:"valueFiles"`
35
		Values            []string `yaml:"values"`
36
		StringValues      []string `yaml:"stringValues"`
37
		FileValues        []string `yaml:"fileValues"`
38
		JsonValues        []string `yaml:"jsonValues"`
39
		LiteralValues     []string `yaml:"literalValues"`
40
		TalosVersion      string   `yaml:"talosVersion"`
41
		WithSecrets       string   `yaml:"withSecrets"`
42
		KubernetesVersion string   `yaml:"kubernetesVersion"`
43
		Full              bool     `yaml:"full"`
44
	} `yaml:"templateOptions"`
45
	ApplyOptions struct {
46
		DryRun           bool   `yaml:"preserve"`
47
		Timeout          string `yaml:"timeout"`
48
		TimeoutDuration  time.Duration
49
		CertFingerprints []string `yaml:"certFingerprints"`
50
	} `yaml:"applyOptions"`
51
	UpgradeOptions struct {
52
		Preserve bool `yaml:"preserve"`
53
		Stage    bool `yaml:"stage"`
54
		Force    bool `yaml:"force"`
55
	} `yaml:"upgradeOptions"`
56
	InitOptions struct {
57
		Version string
58
	}
59
}
60

61
const pathAutoCompleteLimit = 500
62

63
// WithClientNoNodes wraps common code to initialize Talos client and provide cancellable context.
64
//
65
// WithClientNoNodes doesn't set any node information on the request context.
66
func WithClientNoNodes(action func(context.Context, *client.Client) error, dialOptions ...grpc.DialOption) error {
67
	return GlobalArgs.WithClientNoNodes(action, dialOptions...)
68
}
69

70
// WithClient builds upon WithClientNoNodes to provide set of nodes on request context based on config & flags.
71
func WithClient(action func(context.Context, *client.Client) error, dialOptions ...grpc.DialOption) error {
72
	return WithClientNoNodes(
73
		func(ctx context.Context, cli *client.Client) error {
74
			if len(GlobalArgs.Nodes) < 1 {
75
				configContext := cli.GetConfigContext()
76
				if configContext == nil {
77
					return errors.New("failed to resolve config context")
78
				}
79

80
				GlobalArgs.Nodes = configContext.Nodes
81
			}
82

83
			ctx = client.WithNodes(ctx, GlobalArgs.Nodes...)
84

85
			return action(ctx, cli)
86
		},
87
		dialOptions...,
88
	)
89

90
}
91

92
// WithClientMaintenance wraps common code to initialize Talos client in maintenance (insecure mode).
93
func WithClientMaintenance(enforceFingerprints []string, action func(context.Context, *client.Client) error) error {
94
	return GlobalArgs.WithClientMaintenance(enforceFingerprints, action)
95
}
96

97
// Commands is a list of commands published by the package.
98
var Commands []*cobra.Command
99

100
func addCommand(cmd *cobra.Command) {
101
	Commands = append(Commands, cmd)
102
}
103

104
func processModelineAndUpdateGlobals(configFile string, nodesFromArgs bool, endpointsFromArgs bool, owerwrite bool) error {
105
	modelineConfig, err := modeline.ReadAndParseModeline(configFile)
106
	if err != nil {
107
		fmt.Printf("Warning: modeline parsing failed: %v\n", err)
108
		return err
109
	}
110

111
	// Update global settings if modeline was successfully parsed
112
	if modelineConfig != nil {
113
		if !nodesFromArgs && len(modelineConfig.Nodes) > 0 {
114
			if owerwrite {
115
				GlobalArgs.Nodes = modelineConfig.Nodes
116
			} else {
117
				GlobalArgs.Nodes = append(GlobalArgs.Nodes, modelineConfig.Nodes...)
118
			}
119
		}
120
		if !endpointsFromArgs && len(modelineConfig.Endpoints) > 0 {
121
			if owerwrite {
122
				GlobalArgs.Endpoints = modelineConfig.Endpoints
123
			} else {
124
				GlobalArgs.Endpoints = append(GlobalArgs.Endpoints, modelineConfig.Endpoints...)
125
			}
126
		}
127
	}
128

129
	if len(GlobalArgs.Nodes) < 1 {
130
		return errors.New("nodes are not set for the command: please use `--nodes` flag or configuration file to set the nodes to run the command against")
131
	}
132

133
	return nil
134
}
135

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

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

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

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