forked from kubevirt/kubevirt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloud-init.go
264 lines (222 loc) · 7.12 KB
/
cloud-init.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
254
255
256
257
258
259
260
261
262
263
264
/*
* This file is part of the kubevirt project
*
* 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.
*
* Copyright 2017 Red Hat, Inc.
*
*/
package cloudinit
import (
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"kubevirt.io/kubevirt/pkg/api/v1"
diskutils "kubevirt.io/kubevirt/pkg/ephemeral-disk-utils"
"kubevirt.io/kubevirt/pkg/kubecli"
"kubevirt.io/kubevirt/pkg/log"
"kubevirt.io/kubevirt/pkg/precond"
)
type IsoCreationFunc func(isoOutFile string, inFiles []string) error
var cloudInitLocalDir = "/var/run/libvirt/cloud-init-dir"
var cloudInitOwner = "qemu"
var cloudInitIsoFunc = defaultIsoFunc
const NoCloudFile = "noCloud.iso"
// Supported DataSources
const (
dataSourceNoCloud = "noCloud"
)
func defaultIsoFunc(isoOutFile string, inFiles []string) error {
var args []string
args = append(args, "-output")
args = append(args, isoOutFile)
args = append(args, "-volid")
args = append(args, "cidata")
args = append(args, "-joliet")
args = append(args, "-rock")
args = append(args, inFiles...)
cmd := exec.Command("genisoimage", args...)
err := cmd.Start()
if err != nil {
log.Log.V(2).Reason(err).Errorf("genisoimage cmd failed to start while generating iso file %s", isoOutFile)
return err
}
done := make(chan error)
go func() { done <- cmd.Wait() }()
timeout := time.After(10 * time.Second)
for {
select {
case <-timeout:
log.Log.V(2).Errorf("Timed out generating cloud-init iso at path %s", isoOutFile)
cmd.Process.Kill()
case err := <-done:
if err != nil {
log.Log.V(2).Reason(err).Errorf("genisoimage returned non-zero exit code while generating iso file %s", isoOutFile)
return err
}
return nil
}
}
}
// The unit test suite uses this function
func SetIsoCreationFunction(isoFunc IsoCreationFunc) {
cloudInitIsoFunc = isoFunc
}
// The unit test suite uses this function
func SetLocalDataOwner(user string) {
cloudInitOwner = user
}
func SetLocalDirectory(dir string) error {
err := os.MkdirAll(dir, 0755)
if err != nil {
return errors.New(fmt.Sprintf("Unable to initalize cloudInit local cache directory (%s). %v", dir, err))
}
exists, err := diskutils.FileExists(dir)
if err != nil {
return errors.New(fmt.Sprintf("CloudInit local cache directory (%s) does not exist or is inaccessible. %v", dir, err))
} else if exists == false {
return errors.New(fmt.Sprintf("CloudInit local cache directory (%s) does not exist or is inaccessible.", dir))
}
cloudInitLocalDir = dir
return nil
}
func GetDomainBasePath(domain string, namespace string) string {
return fmt.Sprintf("%s/%s/%s", cloudInitLocalDir, namespace, domain)
}
func validateArgs(source *v1.CloudInitNoCloudSource) error {
precond.MustNotBeNil(source)
// TODO what if I only want the metadata to e.g. set up the network
if source.UserDataBase64 == "" {
return errors.New(fmt.Sprintf("userDataBase64 is required for no-cloud data source"))
}
return nil
}
func RemoveLocalData(domain string, namespace string) error {
domainBasePath := GetDomainBasePath(domain, namespace)
err := os.RemoveAll(domainBasePath)
if err != nil && os.IsNotExist(err) {
return nil
}
return err
}
func GetCloudInitNoCloudSource(vm *v1.VirtualMachine) *v1.CloudInitNoCloudSource {
precond.MustNotBeNil(vm)
// search various places cloud init spec may live.
// at the moment, cloud init only exists on disks.
for _, volume := range vm.Spec.Volumes {
if volume.CloudInitNoCloud != nil {
return volume.CloudInitNoCloud
}
}
return nil
}
func ResolveSecrets(source *v1.CloudInitNoCloudSource, namespace string, clientset kubecli.KubevirtClient) error {
precond.CheckNotNil(source)
precond.CheckNotEmpty(namespace)
precond.CheckNotNil(clientset)
if source.UserDataSecretRef == nil {
return nil
}
secretID := source.UserDataSecretRef.Name
secret, err := clientset.CoreV1().Secrets(namespace).Get(secretID, metav1.GetOptions{})
if err != nil {
return err
}
userDataBase64, ok := secret.Data["userdata"]
if ok == false {
return errors.New(fmt.Sprintf("no user-data value found in k8s secret %s %v", secretID, err))
}
userData, err := base64.StdEncoding.DecodeString(string(userDataBase64))
if err != nil {
return err
}
source.UserData = string(userData)
return nil
}
func GenerateLocalData(vmName string, namespace string, source *v1.CloudInitNoCloudSource) error {
precond.MustNotBeEmpty(vmName)
precond.MustNotBeNil(source)
domainBasePath := GetDomainBasePath(vmName, namespace)
err := os.MkdirAll(domainBasePath, 0755)
if err != nil {
log.Log.V(2).Reason(err).Errorf("unable to create cloud-init base path %s", domainBasePath)
return err
}
metaFile := fmt.Sprintf("%s/%s", domainBasePath, "meta-data")
userFile := fmt.Sprintf("%s/%s", domainBasePath, "user-data")
iso := fmt.Sprintf("%s/%s", domainBasePath, NoCloudFile)
isoStaging := fmt.Sprintf("%s/%s.staging", domainBasePath, NoCloudFile)
var userData []byte
if source.UserData != "" {
userData = []byte(source.UserData)
} else if source.UserDataBase64 != "" {
userData, err = base64.StdEncoding.DecodeString(source.UserDataBase64)
if err != nil {
return err
}
} else {
return errors.New(fmt.Sprintf("userDataBase64 or userData is required for no-cloud data source"))
}
metaData := []byte(fmt.Sprintf("{ \"instance-id\": \"%s.%s\", \"local-hostname\": \"%s\" }\n", vmName, namespace, vmName))
diskutils.RemoveFile(userFile)
diskutils.RemoveFile(metaFile)
diskutils.RemoveFile(isoStaging)
err = ioutil.WriteFile(userFile, userData, 0644)
if err != nil {
return err
}
err = ioutil.WriteFile(metaFile, metaData, 0644)
if err != nil {
return err
}
files := make([]string, 0, 2)
files = append(files, metaFile)
files = append(files, userFile)
err = cloudInitIsoFunc(isoStaging, files)
if err != nil {
return err
}
diskutils.RemoveFile(metaFile)
diskutils.RemoveFile(userFile)
err = diskutils.SetFileOwnership(cloudInitOwner, isoStaging)
if err != nil {
return err
}
isEqual, err := diskutils.FilesAreEqual(iso, isoStaging)
if err != nil {
return err
}
// Only replace the dynamically generated iso if it has a different checksum
if isEqual {
diskutils.RemoveFile(isoStaging)
} else {
diskutils.RemoveFile(iso)
err = os.Rename(isoStaging, iso)
if err != nil {
// This error is not something we need to block iso creation for.
log.Log.Reason(err).Errorf("Cloud-init failed to rename file %s to %s", isoStaging, iso)
return err
}
}
log.Log.V(2).Infof("generated nocloud iso file %s", iso)
return nil
}
// Lists all vms cloud-init has local data for
func ListVmWithLocalData() ([]*v1.VirtualMachine, error) {
return diskutils.ListVmWithEphemeralDisk(cloudInitLocalDir)
}