-
Notifications
You must be signed in to change notification settings - Fork 46
/
components.go
96 lines (83 loc) · 2.54 KB
/
components.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
/*
Copyright (c) Edgeless Systems GmbH
SPDX-License-Identifier: AGPL-3.0-only
*/
package components
import (
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"strings"
)
// Components is a list of Kubernetes components.
type Components []*Component
type legacyComponent struct {
URL string `json:"URL,omitempty"`
Hash string `json:"Hash,omitempty"`
InstallPath string `json:"InstallPath,omitempty"`
Extract bool `json:"Extract,omitempty"`
}
// UnmarshalJSON implements a custom JSON unmarshaler to ensure backwards compatibility
// with older components lists which had a different format for all keys.
func (c *Components) UnmarshalJSON(b []byte) error {
var legacyComponents []*legacyComponent
if err := json.Unmarshal(b, &legacyComponents); err != nil {
return err
}
var components []*Component
if err := json.Unmarshal(b, &components); err != nil {
return err
}
if len(legacyComponents) != len(components) {
return errors.New("failed to unmarshal data: inconsistent number of components in list") // just a check, should never happen
}
// If a value is not set in the new format,
// it might have been set in the old format.
// In this case, we copy the value from the old format.
comps := make(Components, len(components))
for idx := 0; idx < len(components); idx++ {
comps[idx] = components[idx]
if comps[idx].Url == "" {
comps[idx].Url = legacyComponents[idx].URL
}
if comps[idx].Hash == "" {
comps[idx].Hash = legacyComponents[idx].Hash
}
if comps[idx].InstallPath == "" {
comps[idx].InstallPath = legacyComponents[idx].InstallPath
}
if !comps[idx].Extract {
comps[idx].Extract = legacyComponents[idx].Extract
}
}
*c = comps
return nil
}
// GetHash returns the hash over all component hashes.
func (c Components) GetHash() string {
sha := sha256.New()
for _, component := range c {
sha.Write([]byte(component.Hash))
}
return fmt.Sprintf("sha256:%x", sha.Sum(nil))
}
// GetKubeadmComponent returns the kubeadm component.
func (c Components) GetKubeadmComponent() (*Component, error) {
for _, component := range c {
if strings.Contains(component.GetUrl(), "kubeadm") {
return component, nil
}
}
return nil, errors.New("kubeadm component not found")
}
// GetUpgradableComponents returns only those Components that should be passed to the upgrade-agent.
func (c Components) GetUpgradableComponents() Components {
var cs Components
for _, c := range c {
if strings.HasPrefix(c.Url, "data:") || strings.HasSuffix(c.InstallPath, "kubeadm") {
cs = append(cs, c)
}
}
return cs
}