-
Notifications
You must be signed in to change notification settings - Fork 246
/
Copy pathazure.go
253 lines (220 loc) · 7.46 KB
/
azure.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// The azure provider fetches a configuration from the Azure OVF DVD.
package azure
import (
"encoding/base64"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
"github.com/coreos/ignition/v2/config/shared/errors"
"github.com/coreos/ignition/v2/config/v3_6_experimental/types"
execUtil "github.com/coreos/ignition/v2/internal/exec/util"
"github.com/coreos/ignition/v2/internal/log"
"github.com/coreos/ignition/v2/internal/platform"
"github.com/coreos/ignition/v2/internal/providers/util"
"github.com/coreos/ignition/v2/internal/resource"
"github.com/coreos/vcontext/report"
"golang.org/x/sys/unix"
)
const (
configPath = "/CustomData.bin"
)
// These constants come from <cdrom.h>.
const (
CDROM_DRIVE_STATUS = 0x5326
)
// These constants come from <cdrom.h>.
const (
CDS_NO_INFO = iota
CDS_NO_DISC
CDS_TRAY_OPEN
CDS_DRIVE_NOT_READY
CDS_DISC_OK
)
// Azure uses a UDF volume for the OVF configuration.
const (
CDS_FSTYPE_UDF = "udf"
)
var (
imdsUserdataURL = url.URL{
Scheme: "http",
Host: "169.254.169.254",
Path: "metadata/instance/compute/userData",
RawQuery: "api-version=2021-01-01&format=text",
}
)
func init() {
platform.Register(platform.Provider{
Name: "azure",
Fetch: fetchConfig,
})
}
// fetchConfig wraps fetchFromAzureMetadata to implement the provider fetch interface.
func fetchConfig(f *resource.Fetcher) (types.Config, report.Report, error) {
return fetchFromAzureMetadata(f)
}
// fetchFromAzureMetadata first tries to fetch userData from IMDS then fallback on customData in case
// of empty config.
func fetchFromAzureMetadata(f *resource.Fetcher) (types.Config, report.Report, error) {
// fetch-offline is not supported since we first try to get config from Azure IMDS.
// this config fetching can only happen during fetch stage.
if f.Offline {
return types.Config{}, report.Report{}, resource.ErrNeedNet
}
logger := f.Logger
// we first try to fetch config from IMDS, in case of failure we fallback on the custom data.
userData, err := fetchFromIMDS(f)
if err == nil {
logger.Info("config has been read from IMDS userdata")
return util.ParseConfig(logger, userData)
}
if err != errors.ErrEmpty {
return types.Config{}, report.Report{}, err
}
logger.Debug("failed to retrieve userdata from IMDS, falling back to custom data: %v", err)
return FetchFromOvfDevice(f, []string{CDS_FSTYPE_UDF})
}
// fetchFromIMDS requests the Azure IMDS to fetch userdata and decode it.
func fetchFromIMDS(f *resource.Fetcher) ([]byte, error) {
headers := make(http.Header)
headers.Set("Metadata", "true")
// Azure IMDS expects some codes <500 to still be retried...
// Here, we match the cloud-init set.
// https://github.com/canonical/cloud-init/commit/c1a2047cf291
// https://github.com/coreos/ignition/issues/1806
retryCodes := []int{
404, // not found
410, // gone
429, // rate-limited
}
data, err := f.FetchToBuffer(imdsUserdataURL, resource.FetchOptions{Headers: headers, RetryCodes: retryCodes})
if err != nil {
return nil, fmt.Errorf("fetching to buffer: %w", err)
}
n := len(data)
if n == 0 {
return nil, errors.ErrEmpty
}
// data is base64 encoded by the IMDS
userData := make([]byte, base64.StdEncoding.DecodedLen(n))
// we keep the number of bytes written to return [:l] only.
// otherwise last byte will be 0x00 which makes fail the JSON's unmarshalling.
l, err := base64.StdEncoding.Decode(userData, data)
if err != nil {
return nil, fmt.Errorf("decoding userdata: %w", err)
}
return userData[:l], nil
}
// FetchFromOvfDevice has the NewFetcher return signature. It is
// wrapped by this and AzureStack packages.
func FetchFromOvfDevice(f *resource.Fetcher, ovfFsTypes []string) (types.Config, report.Report, error) {
logger := f.Logger
checkedDevices := make(map[string]struct{})
for {
for _, ovfFsType := range ovfFsTypes {
devices, err := execUtil.GetBlockDevices(ovfFsType)
if err != nil {
return types.Config{}, report.Report{}, fmt.Errorf("failed to retrieve block devices with FSTYPE=%q: %v", ovfFsType, err)
}
for _, dev := range devices {
_, checked := checkedDevices[dev]
// verify that this is a CD-ROM drive. This helps
// to avoid reading data from an arbitrary block
// device attached to the VM by the user.
if !checked && isCdromPresent(logger, dev) {
rawConfig, err := getRawConfig(f, dev, ovfFsType)
if err != nil {
logger.Debug("failed to retrieve config from device %q: %v", dev, err)
} else {
logger.Info("config has been read from custom data")
return util.ParseConfig(logger, rawConfig)
}
}
checkedDevices[dev] = struct{}{}
}
}
// wait for the actual config drive to appear
// if it's not shown up yet
time.Sleep(time.Second)
}
}
// getRawConfig returns the config by mounting the given block device
func getRawConfig(f *resource.Fetcher, devicePath string, fstype string) ([]byte, error) {
logger := f.Logger
mnt, err := os.MkdirTemp("", "ignition-azure")
if err != nil {
return nil, fmt.Errorf("failed to create temp directory: %v", err)
}
defer os.Remove(mnt)
logger.Debug("mounting config device")
if err := logger.LogOp(
func() error { return unix.Mount(devicePath, mnt, fstype, unix.MS_RDONLY, "") },
"mounting %q at %q", devicePath, mnt,
); err != nil {
return nil, fmt.Errorf("failed to mount device %q at %q: %v", devicePath, mnt, err)
}
defer func() {
_ = logger.LogOp(
func() error { return unix.Unmount(mnt, 0) },
"unmounting %q at %q", devicePath, mnt,
)
}()
// detect the config drive by looking for a file which is always present
logger.Debug("checking for config drive")
if _, err := os.Stat(filepath.Join(mnt, "ovf-env.xml")); err != nil {
return nil, fmt.Errorf("device %q does not appear to be a config drive: %v", devicePath, err)
}
logger.Debug("reading config")
rawConfig, err := os.ReadFile(filepath.Join(mnt, configPath))
if err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("failed to read config from device %q: %v", devicePath, err)
}
return rawConfig, nil
}
// isCdromPresent verifies if the given config drive is CD-ROM
func isCdromPresent(logger *log.Logger, devicePath string) bool {
logger.Debug("opening config device: %q", devicePath)
device, err := os.Open(devicePath)
if err != nil {
logger.Info("failed to open config device: %v", err)
return false
}
defer device.Close()
logger.Debug("getting drive status for %q", devicePath)
status, _, errno := unix.Syscall(
unix.SYS_IOCTL,
uintptr(device.Fd()),
uintptr(CDROM_DRIVE_STATUS),
uintptr(0),
)
switch status {
case CDS_NO_INFO:
logger.Info("drive status: no info")
case CDS_NO_DISC:
logger.Info("drive status: no disc")
case CDS_TRAY_OPEN:
logger.Info("drive status: open")
case CDS_DRIVE_NOT_READY:
logger.Info("drive status: not ready")
case CDS_DISC_OK:
logger.Info("drive status: OK")
default:
logger.Err("failed to get drive status: %s", errno.Error())
}
return (status == CDS_DISC_OK)
}