-
Notifications
You must be signed in to change notification settings - Fork 77
/
spec.go
103 lines (85 loc) · 2.23 KB
/
spec.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
94
95
96
97
98
99
100
101
102
103
package cluster
import (
"fmt"
"github.com/creasty/defaults"
"github.com/jellydator/validation"
)
// Spec defines cluster config spec section
type Spec struct {
Hosts Hosts `yaml:"hosts,omitempty"`
K0s *K0s `yaml:"k0s,omitempty"`
k0sLeader *Host
}
// UnmarshalYAML sets in some sane defaults when unmarshaling the data from yaml
func (s *Spec) UnmarshalYAML(unmarshal func(interface{}) error) error {
type spec Spec
ys := (*spec)(s)
ys.K0s = &K0s{}
if err := unmarshal(ys); err != nil {
return err
}
return defaults.Set(s)
}
// MarshalYAML implements yaml.Marshaler interface
func (s *Spec) MarshalYAML() (interface{}, error) {
k0s, err := s.K0s.MarshalYAML()
if err != nil {
return nil, err
}
if k0s == nil {
return Spec{Hosts: s.Hosts}, nil
}
return s, nil
}
// SetDefaults sets defaults
func (s *Spec) SetDefaults() {
if s.K0s == nil {
s.K0s = &K0s{}
_ = defaults.Set(s.K0s)
}
}
// K0sLeader returns a controller host that is selected to be a "leader",
// or an initial node, a node that creates join tokens for other controllers.
func (s *Spec) K0sLeader() *Host {
if s.k0sLeader == nil {
controllers := s.Hosts.Controllers()
// Pick the first controller that reports to be running and persist the choice
for _, h := range controllers {
if !h.Reset && h.Metadata.K0sBinaryVersion != nil && h.Metadata.K0sRunningVersion != nil {
s.k0sLeader = h
break
}
}
// Still nil? Fall back to first "controller" host, do not persist selection.
if s.k0sLeader == nil {
return controllers.First()
}
}
return s.k0sLeader
}
func (s *Spec) Validate() error {
return validation.ValidateStruct(s,
validation.Field(&s.Hosts, validation.Required),
validation.Field(&s.Hosts),
validation.Field(&s.K0s),
)
}
// KubeAPIURL returns an url to the cluster's kube api
func (s *Spec) KubeAPIURL() string {
var caddr string
if a := s.K0s.Config.DigString("spec", "api", "externalAddress"); a != "" {
caddr = a
} else {
leader := s.K0sLeader()
if leader.PrivateAddress != "" {
caddr = leader.PrivateAddress
} else {
caddr = leader.Address()
}
}
cport := 6443
if p, ok := s.K0s.Config.Dig("spec", "api", "port").(int); ok {
cport = p
}
return fmt.Sprintf("https://%s:%d", caddr, cport)
}