/
provision.go
212 lines (175 loc) · 5.24 KB
/
provision.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package userdata
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"time"
"github.com/avast/retry-go/v4"
daemon "github.com/confidential-containers/cloud-api-adaptor/src/cloud-api-adaptor/pkg/forwarder"
"github.com/confidential-containers/cloud-api-adaptor/src/cloud-providers/aws"
"github.com/confidential-containers/cloud-api-adaptor/src/cloud-providers/azure"
"gopkg.in/yaml.v2"
)
var logger = log.New(log.Writer(), "[userdata/provision] ", log.LstdFlags|log.Lmsgprefix)
type paths struct {
authJson string
cdhConfig string
daemonConfig string
}
type Config struct {
fetchTimeout int
paths paths
}
func NewConfig(authJsonPath, daemonConfigPath, cdhConfig string, fetchTimeout int) *Config {
cfgPaths := paths{authJsonPath, cdhConfig, daemonConfigPath}
return &Config{fetchTimeout, cfgPaths}
}
type WriteFile struct {
Path string `yaml:"path"`
Content string `yaml:"content"`
}
type CloudConfig struct {
WriteFiles []WriteFile `yaml:"write_files"`
}
type UserDataProvider interface {
GetUserData(ctx context.Context) ([]byte, error)
GetRetryDelay() time.Duration
}
type DefaultRetry struct{}
func (d DefaultRetry) GetRetryDelay() time.Duration {
return 5 * time.Second
}
type AzureUserDataProvider struct{ DefaultRetry }
func (a AzureUserDataProvider) GetUserData(ctx context.Context) ([]byte, error) {
url := azure.AzureUserDataImdsUrl
logger.Printf("provider: Azure, userDataUrl: %s\n", url)
return azure.GetUserData(ctx, url)
}
type AWSUserDataProvider struct{ DefaultRetry }
func (a AWSUserDataProvider) GetUserData(ctx context.Context) ([]byte, error) {
url := aws.AWSUserDataImdsUrl
logger.Printf("provider: AWS, userDataUrl: %s\n", url)
return aws.GetUserData(ctx, url)
}
func newProvider(ctx context.Context) (UserDataProvider, error) {
if azure.IsAzure(ctx) {
return AzureUserDataProvider{}, nil
}
if aws.IsAWS(ctx) {
return AWSUserDataProvider{}, nil
}
return nil, fmt.Errorf("unsupported user data provider")
}
func retrieveCloudConfig(ctx context.Context, provider UserDataProvider) (*CloudConfig, error) {
var cc CloudConfig
// Use retry.Do to retry the getUserData function until it succeeds
// This is needed because the VM's userData is not available immediately
err := retry.Do(
func() error {
ud, err := provider.GetUserData(ctx)
if err != nil {
return fmt.Errorf("failed to get user data: %w", err)
}
// We parse user data now, b/c we want to retry if it's not valid
parsed, err := parseUserData(ud)
if err != nil {
return fmt.Errorf("failed to parse user data: %w", err)
}
cc = *parsed
// Valid user data, stop retrying
return nil
},
retry.Context(ctx),
retry.Delay(provider.GetRetryDelay()),
retry.LastErrorOnly(true),
retry.DelayType(retry.FixedDelay),
retry.OnRetry(func(n uint, err error) {
logger.Printf("Retry attempt %d: %v\n", n, err)
}),
)
return &cc, err
}
func parseUserData(userData []byte) (*CloudConfig, error) {
var cc CloudConfig
err := yaml.UnmarshalStrict(userData, &cc)
if err != nil {
return nil, err
}
return &cc, nil
}
func parseDaemonConfig(content []byte) (*daemon.Config, error) {
var dc daemon.Config
err := json.Unmarshal(content, &dc)
if err != nil {
return nil, err
}
return &dc, nil
}
func findConfigEntry(path string, cc *CloudConfig) []byte {
for _, wf := range cc.WriteFiles {
if wf.Path != path {
continue
}
return []byte(wf.Content)
}
return nil
}
func writeFile(path string, bytes []byte) error {
// Ensure the parent directory exists
err := os.MkdirAll(filepath.Dir(path), 0755)
if err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
err = os.WriteFile(path, bytes, 0644)
if err != nil {
return fmt.Errorf("failed to write file: %w", err)
}
logger.Printf("Wrote %s\n", path)
return nil
}
func processCloudConfig(cfg *Config, cc *CloudConfig) error {
bytes := findConfigEntry(cfg.paths.daemonConfig, cc)
if bytes == nil {
return fmt.Errorf("failed to find daemon config entry in cloud config")
}
daemonConfig, err := parseDaemonConfig(bytes)
if err != nil {
return fmt.Errorf("failed to parse daemon config: %w", err)
}
if err = writeFile(cfg.paths.daemonConfig, bytes); err != nil {
return fmt.Errorf("failed to write daemon config file: %w", err)
}
if bytes := findConfigEntry(cfg.paths.cdhConfig, cc); bytes != nil {
if err = writeFile(cfg.paths.cdhConfig, bytes); err != nil {
return fmt.Errorf("failed to write cdh config file: %w", err)
}
}
if daemonConfig.AuthJson != "" {
bytes := []byte(daemonConfig.AuthJson)
if err = writeFile(cfg.paths.authJson, bytes); err != nil {
return fmt.Errorf("failed to write auth json file: %w", err)
}
}
return nil
}
func ProvisionFiles(cfg *Config) error {
bg := context.Background()
duration := time.Duration(cfg.fetchTimeout) * time.Second
ctx, cancel := context.WithTimeout(bg, duration)
defer cancel()
provider, err := newProvider(ctx)
if err != nil {
return fmt.Errorf("failed to create UserData provider: %w", err)
}
cc, err := retrieveCloudConfig(ctx, provider)
if err != nil {
return fmt.Errorf("failed to retrieve cloud config: %w", err)
}
if err = processCloudConfig(cfg, cc); err != nil {
return fmt.Errorf("failed to process cloud config: %w", err)
}
return nil
}