forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.go
417 lines (352 loc) · 10.3 KB
/
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/lxc/lxd/client"
"github.com/lxc/lxd/lxc/config"
"github.com/lxc/lxd/lxc/utils"
"github.com/lxc/lxd/shared/api"
cli "github.com/lxc/lxd/shared/cmd"
"github.com/lxc/lxd/shared/i18n"
"github.com/lxc/lxd/shared/termios"
)
type cmdInit struct {
global *cmdGlobal
flagConfig []string
flagEphemeral bool
flagNetwork string
flagProfile []string
flagStorage string
flagTarget string
flagType string
flagNoProfiles bool
flagEmpty bool
flagVM bool
}
func (c *cmdInit) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("init", i18n.G("[[<remote>:]<image>] [<remote>:][<name>] [< config"))
cmd.Short = i18n.G("Create instances from images")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(`Create instances from images`))
cmd.Example = cli.FormatSection("", i18n.G(`lxc init ubuntu:22.04 u1
lxc init ubuntu:22.04 u1 < config.yaml
Create the instance with configuration from config.yaml`))
cmd.Hidden = true
cmd.RunE = c.Run
cmd.Flags().StringArrayVarP(&c.flagConfig, "config", "c", nil, i18n.G("Config key/value to apply to the new instance")+"``")
cmd.Flags().StringArrayVarP(&c.flagProfile, "profile", "p", nil, i18n.G("Profile to apply to the new instance")+"``")
cmd.Flags().BoolVarP(&c.flagEphemeral, "ephemeral", "e", false, i18n.G("Ephemeral instance"))
cmd.Flags().StringVarP(&c.flagNetwork, "network", "n", "", i18n.G("Network name")+"``")
cmd.Flags().StringVarP(&c.flagStorage, "storage", "s", "", i18n.G("Storage pool name")+"``")
cmd.Flags().StringVarP(&c.flagType, "type", "t", "", i18n.G("Instance type")+"``")
cmd.Flags().StringVar(&c.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
cmd.Flags().BoolVar(&c.flagNoProfiles, "no-profiles", false, i18n.G("Create the instance with no profiles applied"))
cmd.Flags().BoolVar(&c.flagEmpty, "empty", false, i18n.G("Create an empty instance"))
cmd.Flags().BoolVar(&c.flagVM, "vm", false, i18n.G("Create a virtual machine"))
return cmd
}
func (c *cmdInit) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 0, 2)
if exit {
return err
}
if len(args) == 0 && !c.flagEmpty {
_ = cmd.Usage()
return nil
}
_, _, err = c.create(c.global.conf, args)
return err
}
func (c *cmdInit) create(conf *config.Config, args []string) (lxd.InstanceServer, string, error) {
var name string
var image string
var remote string
var iremote string
var err error
var stdinData api.InstancePut
var devicesMap map[string]map[string]string
var configMap map[string]string
var profiles []string
// If stdin isn't a terminal, read text from it
if !termios.IsTerminal(getStdinFd()) {
contents, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return nil, "", err
}
err = yaml.Unmarshal(contents, &stdinData)
if err != nil {
return nil, "", err
}
}
if len(args) > 0 {
iremote, image, err = conf.ParseRemote(args[0])
if err != nil {
return nil, "", err
}
if len(args) == 1 {
remote, name, err = conf.ParseRemote("")
if err != nil {
return nil, "", err
}
} else if len(args) == 2 {
remote, name, err = conf.ParseRemote(args[1])
if err != nil {
return nil, "", err
}
}
}
if c.flagEmpty {
if len(args) > 1 {
return nil, "", fmt.Errorf(i18n.G("--empty cannot be combined with an image name"))
}
if len(args) == 0 {
remote, name, err = conf.ParseRemote("")
if err != nil {
return nil, "", err
}
} else if len(args) == 1 {
// Switch image / instance names
name = image
remote = iremote
image = ""
iremote = ""
}
}
d, err := conf.GetInstanceServer(remote)
if err != nil {
return nil, "", err
}
if c.flagTarget != "" {
d = d.UseTarget(c.flagTarget)
}
profiles = append(profiles, c.flagProfile...)
if !c.global.flagQuiet {
if name == "" {
fmt.Printf(i18n.G("Creating the instance") + "\n")
} else {
fmt.Printf(i18n.G("Creating %s")+"\n", name)
}
}
if len(stdinData.Devices) > 0 {
devicesMap = stdinData.Devices
} else {
devicesMap = map[string]map[string]string{}
}
if c.flagNetwork != "" {
network, _, err := d.GetNetwork(c.flagNetwork)
if err != nil {
return nil, "", fmt.Errorf("Failed loading network %q: %w", c.flagNetwork, err)
}
// Prepare the instance's NIC device entry.
var device map[string]string
if network.Managed && d.HasExtension("instance_nic_network") {
// If network is managed, use the network property rather than nictype, so that the
// network's inherited properties are loaded into the NIC when started.
device = map[string]string{
"name": "eth0",
"type": "nic",
"network": network.Name,
}
} else {
// If network is unmanaged default to using a macvlan connected to the specified interface.
device = map[string]string{
"name": "eth0",
"type": "nic",
"nictype": "macvlan",
"parent": c.flagNetwork,
}
if network.Type == "bridge" {
// If the network type is an unmanaged bridge, use bridged NIC type.
device["nictype"] = "bridged"
}
}
devicesMap["eth0"] = device
}
if len(stdinData.Config) > 0 {
configMap = stdinData.Config
} else {
configMap = map[string]string{}
}
for _, entry := range c.flagConfig {
if !strings.Contains(entry, "=") {
return nil, "", fmt.Errorf(i18n.G("Bad key=value pair: %s"), entry)
}
fields := strings.SplitN(entry, "=", 2)
configMap[fields[0]] = fields[1]
}
// Check if the specified storage pool exists.
if c.flagStorage != "" {
_, _, err := d.GetStoragePool(c.flagStorage)
if err != nil {
return nil, "", fmt.Errorf("Failed loading storage pool %q: %w", c.flagStorage, err)
}
devicesMap["root"] = map[string]string{
"type": "disk",
"path": "/",
"pool": c.flagStorage,
}
}
// Decide whether we are creating a container or a virtual machine.
instanceDBType := api.InstanceTypeContainer
if c.flagVM {
instanceDBType = api.InstanceTypeVM
}
// Setup instance creation request
req := api.InstancesPost{
Name: name,
InstanceType: c.flagType,
Type: instanceDBType,
}
req.Config = configMap
req.Devices = devicesMap
if !c.flagNoProfiles && len(profiles) == 0 {
if len(stdinData.Profiles) > 0 {
req.Profiles = stdinData.Profiles
} else {
req.Profiles = nil
}
} else {
req.Profiles = profiles
}
req.Ephemeral = c.flagEphemeral
var opInfo api.Operation
if !c.flagEmpty {
// Get the image server and image info
iremote, image = c.guessImage(conf, d, remote, iremote, image)
var imgRemote lxd.ImageServer
var imgInfo *api.Image
// Connect to the image server
if iremote == remote {
imgRemote = d
} else {
imgRemote, err = conf.GetImageServer(iremote)
if err != nil {
return nil, "", err
}
}
// Deal with the default image
if image == "" {
image = "default"
}
// Optimisation for simplestreams
if conf.Remotes[iremote].Protocol == "simplestreams" {
imgInfo = &api.Image{}
imgInfo.Fingerprint = image
imgInfo.Public = true
req.Source.Alias = image
} else {
// Attempt to resolve an image alias
alias, _, err := imgRemote.GetImageAlias(image)
if err == nil {
req.Source.Alias = image
image = alias.Target
}
// Get the image info
imgInfo, _, err = imgRemote.GetImage(image)
if err != nil {
return nil, "", err
}
if imgInfo.Type != "virtual-machine" && c.flagVM {
return nil, "", fmt.Errorf(i18n.G("Asked for a VM but image is of type container"))
}
req.Type = api.InstanceType(imgInfo.Type)
}
// Create the instance
op, err := d.CreateInstanceFromImage(imgRemote, *imgInfo, req)
if err != nil {
return nil, "", err
}
// Watch the background operation
progress := utils.ProgressRenderer{
Format: i18n.G("Retrieving image: %s"),
Quiet: c.global.flagQuiet,
}
_, err = op.AddHandler(progress.UpdateOp)
if err != nil {
progress.Done("")
return nil, "", err
}
err = utils.CancelableWait(op, &progress)
if err != nil {
progress.Done("")
return nil, "", err
}
progress.Done("")
// Extract the instance name
info, err := op.GetTarget()
if err != nil {
return nil, "", err
}
opInfo = *info
} else {
req.Source.Type = "none"
op, err := d.CreateInstance(req)
if err != nil {
return nil, "", err
}
err = op.Wait()
if err != nil {
return nil, "", err
}
opInfo = op.Get()
}
instances, ok := opInfo.Resources["instances"]
if !ok || len(instances) == 0 {
// Try using the older "containers" field
instances, ok = opInfo.Resources["containers"]
if !ok || len(instances) == 0 {
return nil, "", fmt.Errorf(i18n.G("Didn't get any affected image, instance or snapshot from server"))
}
}
if len(instances) == 1 && name == "" {
fields := strings.Split(instances[0], "/")
name = fields[len(fields)-1]
fmt.Printf(i18n.G("Instance name is: %s")+"\n", name)
}
// Validate the network setup
c.checkNetwork(d, name)
return d, name, nil
}
func (c *cmdInit) guessImage(conf *config.Config, d lxd.InstanceServer, remote string, iremote string, image string) (string, string) {
if remote != iremote {
return iremote, image
}
fields := strings.SplitN(image, "/", 2)
_, ok := conf.Remotes[fields[0]]
if !ok {
return iremote, image
}
_, _, err := d.GetImageAlias(image)
if err == nil {
return iremote, image
}
_, _, err = d.GetImage(image)
if err == nil {
return iremote, image
}
if len(fields) == 1 {
fmt.Fprintf(os.Stderr, i18n.G("The local image '%s' couldn't be found, trying '%s:' instead.")+"\n", image, fields[0])
return fields[0], "default"
}
fmt.Fprintf(os.Stderr, i18n.G("The local image '%s' couldn't be found, trying '%s:%s' instead.")+"\n", image, fields[0], fields[1])
return fields[0], fields[1]
}
func (c *cmdInit) checkNetwork(d lxd.InstanceServer, name string) {
ct, _, err := d.GetInstance(name)
if err != nil {
return
}
for _, d := range ct.ExpandedDevices {
if d["type"] == "nic" {
return
}
}
fmt.Fprintf(os.Stderr, "\n"+i18n.G("The instance you are starting doesn't have any network attached to it.")+"\n")
fmt.Fprintf(os.Stderr, " "+i18n.G("To create a new network, use: lxc network create")+"\n")
fmt.Fprintf(os.Stderr, " "+i18n.G("To attach a network to an instance, use: lxc network attach")+"\n\n")
}