-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathcommands.go
235 lines (194 loc) · 6.3 KB
/
commands.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
package application
import (
"context"
"encoding/base64"
"fmt"
"github.com/sirupsen/logrus"
"sigs.k8s.io/yaml"
"github.com/liquidmetal-dev/flintlock/api/events"
"github.com/liquidmetal-dev/flintlock/client/cloudinit"
"github.com/liquidmetal-dev/flintlock/client/cloudinit/instance"
coreerrs "github.com/liquidmetal-dev/flintlock/core/errors"
"github.com/liquidmetal-dev/flintlock/core/models"
"github.com/liquidmetal-dev/flintlock/core/ports"
"github.com/liquidmetal-dev/flintlock/pkg/defaults"
"github.com/liquidmetal-dev/flintlock/pkg/log"
"github.com/liquidmetal-dev/flintlock/pkg/validation"
)
const (
MetadataInterfaceName = "eth0"
)
func (a *app) CreateMicroVM(ctx context.Context, mvm *models.MicroVM) (*models.MicroVM, error) {
logger := log.GetLogger(ctx).WithField("component", "app")
logger.Debug("creating microvm")
if mvm == nil {
return nil, coreerrs.ErrSpecRequired
}
logger.Trace("validating model")
validator := validation.NewValidator()
if validErr := validator.ValidateStruct(mvm); validErr != nil {
return nil, fmt.Errorf("an error occurred when attempting to validate microvm spec: %w", validErr)
}
if mvm.ID.IsEmpty() {
name, err := a.ports.IdentifierService.GenerateRandom()
if err != nil {
return nil, fmt.Errorf("generating random name for microvm: %w", err)
}
vmid, err := models.NewVMID(name, defaults.MicroVMNamespace, "")
if err != nil {
return nil, fmt.Errorf("creating vmid: %w", err)
}
mvm.ID = *vmid
}
if mvm.Spec.Provider == "" {
mvm.Spec.Provider = a.cfg.DefaultProvider
}
provider, ok := a.ports.MicrovmProviders[mvm.Spec.Provider]
if !ok {
return nil, fmt.Errorf("microvm provider %s isn't available", mvm.Spec.Provider)
}
logger = logger.WithField("microvm-provider", mvm.Spec.Provider)
uid, err := a.ports.IdentifierService.GenerateRandom()
if err != nil {
return nil, fmt.Errorf("generating random ID for microvm: %w", err)
}
mvm.ID.SetUID(uid)
logger = logger.WithField("vmid", mvm.ID)
foundMvm, err := a.ports.Repo.Get(ctx, ports.RepositoryGetOptions{
Name: mvm.ID.Name(),
Namespace: mvm.ID.Namespace(),
UID: mvm.ID.UID(),
})
if err != nil {
if !coreerrs.IsSpecNotFound(err) {
return nil, fmt.Errorf("checking to see if spec exists: %w", err)
}
}
if foundMvm != nil {
return nil, specAlreadyExistsError{
name: mvm.ID.Name(),
namespace: mvm.ID.Namespace(),
uid: mvm.ID.UID(),
}
}
if !provider.Capabilities().Has(models.MacvtapCapability) {
for _, netInt := range mvm.Spec.NetworkInterfaces {
if netInt.Type == models.IfaceTypeMacvtap {
return nil, errMacvtapNotSupported
}
}
}
if !provider.Capabilities().Has(models.VirtioFSCapability) {
for _, volume := range mvm.Spec.AdditionalVolumes {
if volume.Source.VirtioFS != nil {
return nil, errVirtioFSNotSupported
}
}
}
err = a.addInstanceData(mvm, logger)
if err != nil {
return nil, fmt.Errorf("adding instance data: %w", err)
}
if provider.Capabilities().Has(models.MetadataServiceCapability) {
a.addMetadataInterface(mvm)
}
// Set the timestamp when the VMspec was created.
mvm.Spec.CreatedAt = a.ports.Clock().Unix()
mvm.Status.State = models.PendingState
mvm.Status.Retry = 0
createdMVM, err := a.ports.Repo.Save(ctx, mvm)
if err != nil {
return nil, fmt.Errorf("saving microvm spec: %w", err)
}
if err := a.ports.EventService.Publish(ctx, defaults.TopicMicroVMEvents, &events.MicroVMSpecCreated{
ID: mvm.ID.Name(),
Namespace: mvm.ID.Namespace(),
UID: mvm.ID.UID(),
}); err != nil {
return nil, fmt.Errorf("publishing microvm created event: %w", err)
}
return createdMVM, nil
}
func (a *app) DeleteMicroVM(ctx context.Context, uid string) error {
logger := log.GetLogger(ctx).WithField("component", "app")
logger.Trace("deleting microvm")
if uid == "" {
return errUIDRequired
}
foundMvm, err := a.ports.Repo.Get(ctx, ports.RepositoryGetOptions{
UID: uid,
})
if err != nil {
return fmt.Errorf("checking to see if spec exists: %w", err)
}
if foundMvm == nil {
return specNotFoundError{
uid: uid,
}
}
// Set the timestamp when the VMspec was deleted.
foundMvm.Spec.DeletedAt = a.ports.Clock().Unix()
foundMvm.Status.Retry = 0
foundMvm.Status.State = models.DeletingState
_, err = a.ports.Repo.Save(ctx, foundMvm)
if err != nil {
return fmt.Errorf("marking microvm spec for deletion: %w", err)
}
if err := a.ports.EventService.Publish(ctx, defaults.TopicMicroVMEvents, &events.MicroVMSpecUpdated{
ID: foundMvm.ID.Name(),
Namespace: foundMvm.ID.Namespace(),
UID: foundMvm.ID.UID(),
}); err != nil {
return fmt.Errorf("publishing microvm updated event: %w", err)
}
return nil
}
func (a *app) addInstanceData(vm *models.MicroVM, logger *logrus.Entry) error {
instanceData := instance.New()
meta := vm.Spec.Metadata[cloudinit.InstanceDataKey]
if meta != "" {
logger.Info("Instance metadata exists")
data, err := base64.StdEncoding.DecodeString(meta)
if err != nil {
return fmt.Errorf("decoding existing instance metadata: %w", err)
}
err = yaml.Unmarshal(data, &instanceData)
if err != nil {
return fmt.Errorf("unmarshalling exists instance metadata: %w", err)
}
}
existingInstanceID := instanceData[instance.InstanceIDKey]
if existingInstanceID != "" {
logger.Infof("Instance id already set in meta-data: %s", existingInstanceID)
return nil
}
logger.Infof("Setting instance_id in meta-data: %s", vm.ID.UID())
instanceData[instance.InstanceIDKey] = vm.ID.UID()
updatedData, err := yaml.Marshal(&instanceData)
if err != nil {
return fmt.Errorf("marshalling updated instance data: %w", err)
}
vm.Spec.Metadata[cloudinit.InstanceDataKey] = base64.StdEncoding.EncodeToString(updatedData)
return nil
}
func (a *app) addMetadataInterface(mvm *models.MicroVM) {
for i := range mvm.Spec.NetworkInterfaces {
netInt := mvm.Spec.NetworkInterfaces[i]
if netInt.GuestDeviceName == MetadataInterfaceName {
return
}
}
interfaces := []models.NetworkInterface{
{
GuestDeviceName: MetadataInterfaceName,
Type: models.IfaceTypeTap,
AllowMetadataRequests: true,
GuestMAC: "AA:FF:00:00:00:01",
StaticAddress: &models.StaticAddress{
Address: "169.254.0.1/16",
},
},
}
interfaces = append(interfaces, mvm.Spec.NetworkInterfaces...)
mvm.Spec.NetworkInterfaces = interfaces
}