forked from canonical/lxd
/
main_init.go
1263 lines (1103 loc) · 40.1 KB
/
main_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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/pem"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"golang.org/x/crypto/ssh/terminal"
"github.com/lxc/lxd/client"
"github.com/lxc/lxd/lxd/cluster"
"github.com/lxc/lxd/lxd/util"
"github.com/pkg/errors"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/cmd"
"github.com/lxc/lxd/shared/idmap"
"github.com/lxc/lxd/shared/logger"
)
// CmdInit implements the "lxd init" command line.
type CmdInit struct {
Context *cmd.Context
Args *Args
RunningInUserns bool
VarDir string
PasswordReader func(int) ([]byte, error)
}
// Run triggers the execution of the init command.
func (cmd *CmdInit) Run() error {
// Check that command line arguments don't conflict with each other
err := cmd.validateArgs()
if err != nil {
return err
}
// Connect to LXD
path := ""
if cmd.VarDir != "" {
path = filepath.Join(cmd.VarDir, "unix.socket")
}
client, err := lxd.ConnectLXDUnix(path, nil)
if err != nil {
return fmt.Errorf("Unable to talk to LXD: %s", err)
}
existingPools, err := client.GetStoragePoolNames()
if err != nil {
// We should consider this fatal since this means
// something's wrong with the daemon.
return err
}
data := &cmdInitData{}
// Kick off the appropriate way to fill the data (either
// preseed, auto or interactive).
if cmd.Args.Preseed {
err = cmd.fillDataPreseed(data, client)
} else {
// Copy the data from the current default profile, if it exists.
cmd.fillDataWithCurrentServerConfig(data, client)
// Copy the data from the current server config.
cmd.fillDataWithCurrentDefaultProfile(data, client)
// Figure what storage drivers among the supported ones are actually
// available on this system.
backendsAvailable := cmd.availableStoragePoolsDrivers()
if cmd.Args.Auto {
err = cmd.fillDataAuto(data, client, backendsAvailable, existingPools)
} else {
err = cmd.fillDataInteractive(data, client, backendsAvailable, existingPools)
}
}
if err != nil {
return err
}
// Apply the desired configuration.
err = cmd.apply(client, data)
if err != nil {
return err
}
cmd.Context.Output("LXD has been successfully configured.\n")
return nil
}
// Fill the given configuration data with parameters collected from
// the --auto command line.
func (cmd *CmdInit) fillDataAuto(data *cmdInitData, client lxd.ContainerServer, backendsAvailable []string, existingPools []string) error {
if cmd.Args.StorageBackend == "" {
cmd.Args.StorageBackend = "dir"
}
err := cmd.validateArgsAuto(backendsAvailable)
if err != nil {
return err
}
if cmd.Args.NetworkAddress != "" {
// If no port was provided, use the default one
if cmd.Args.NetworkPort == -1 {
cmd.Args.NetworkPort = 8443
}
networking := &cmdInitNetworkingParams{
Address: cmd.Args.NetworkAddress,
Port: cmd.Args.NetworkPort,
TrustPassword: cmd.Args.TrustPassword,
}
cmd.fillDataWithNetworking(data, networking)
}
if len(existingPools) == 0 {
storage := &cmdInitStorageParams{
Backend: cmd.Args.StorageBackend,
LoopSize: cmd.Args.StorageCreateLoop,
Device: cmd.Args.StorageCreateDevice,
Dataset: cmd.Args.StorageDataset,
Pool: "default",
}
err = cmd.fillDataWithStorage(data, storage, existingPools)
if err != nil {
return err
}
}
return nil
}
// Fill the given configuration data with parameters collected with
// interactive questions.
func (cmd *CmdInit) fillDataInteractive(data *cmdInitData, client lxd.ContainerServer, backendsAvailable []string, existingPools []string) error {
clustering, err := cmd.askClustering()
if err != nil {
return err
}
// Ask to create basic entities only if we are not joining an existing
// cluster.
var storage *cmdInitStorageParams
var defaultPrivileged int
var networking *cmdInitNetworkingParams
var imagesAutoUpdate bool
var bridge *cmdInitBridgeParams
if clustering == nil || clustering.TargetAddress == "" {
storage, err = cmd.askStorage(client, existingPools, backendsAvailable)
if err != nil {
return err
}
defaultPrivileged = cmd.askDefaultPrivileged()
// Ask about networking only if we skipped the clustering questions.
if clustering == nil {
networking = cmd.askNetworking()
}
imagesAutoUpdate = cmd.askImages()
bridge = cmd.askBridge(client)
}
if clustering != nil {
// Re-use the answers to the clustering questions.
networking = &cmdInitNetworkingParams{
Address: clustering.Address,
Port: clustering.Port,
TrustPassword: clustering.TrustPassword,
}
if clustering.TargetAddress != "" {
// Add the joining node's certificate the cluster trust pool
cert, err := util.LoadCert(cmd.VarDir)
if err != nil {
return err
}
err = cluster.SetupTrust(
string(cert.PublicKey()), clustering.TargetAddress,
string(clustering.TargetCert), clustering.TargetPassword)
if err != nil {
return errors.Wrap(err, "failed to add joining node's certificate to cluster")
}
// Client parameters to connect to the target cluster node.
args := &lxd.ConnectionArgs{
TLSClientCert: string(cert.PublicKey()),
TLSClientKey: string(cert.PrivateKey()),
TLSServerCert: string(clustering.TargetCert),
}
url := fmt.Sprintf("https://%s", clustering.TargetAddress)
client, err := lxd.ConnectLXD(url, args)
if err != nil {
return err
}
// Get the pools and networks defined on the target cluster
targetPools, err := client.GetStoragePools()
if err != nil {
return errors.Wrap(err, "failed to get cluster storage pools")
}
targetNetworks, err := client.GetNetworks()
if err != nil {
return errors.Wrap(err, "failed to get cluster networks")
}
// Ask for node-specific pools and networks config keys.
data.Pools, err = cmd.askClusteringStoragePools(targetPools)
if err != nil {
return err
}
data.Networks, err = cmd.askClusteringNetworks(targetNetworks)
if err != nil {
return err
}
}
}
_, err = exec.LookPath("dnsmasq")
if err != nil && bridge != nil {
return fmt.Errorf("LXD managed bridges require \"dnsmasq\". Install it and try again.")
}
cmd.fillDataWithClustering(data, clustering)
err = cmd.fillDataWithStorage(data, storage, existingPools)
if err != nil {
return err
}
err = cmd.fillDataWithDefaultPrivileged(data, defaultPrivileged)
if err != nil {
return err
}
cmd.fillDataWithNetworking(data, networking)
cmd.fillDataWithImages(data, imagesAutoUpdate)
err = cmd.fillDataWithBridge(data, bridge)
if err != nil {
return err
}
return nil
}
// Fill the given configuration data from the preseed YAML text stream.
func (cmd *CmdInit) fillDataPreseed(data *cmdInitData, client lxd.ContainerServer) error {
err := cmd.Context.InputYAML(data)
if err != nil {
return fmt.Errorf("Invalid preseed YAML content")
}
return nil
}
// Fill the given data with the current server configuration.
func (cmd *CmdInit) fillDataWithCurrentServerConfig(data *cmdInitData, client lxd.ContainerServer) error {
server, _, err := client.GetServer()
if err != nil {
return err
}
data.ServerPut = server.Writable()
return nil
}
// Fill the given data with the current default profile, if it exists.
func (cmd *CmdInit) fillDataWithCurrentDefaultProfile(data *cmdInitData, client lxd.ContainerServer) {
defaultProfile, _, err := client.GetProfile("default")
if err == nil {
// Copy the default profile configuration (that we have
// possibly modified above).
data.Profiles = []api.ProfilesPost{{Name: "default"}}
data.Profiles[0].ProfilePut = defaultProfile.ProfilePut
}
}
// Fill the given init data with clustering details matching the given
// clustering parameters.
func (cmd *CmdInit) fillDataWithClustering(data *cmdInitData, clustering *cmdInitClusteringParams) {
if clustering == nil {
return
}
data.Cluster.ServerName = clustering.Name
data.Cluster.Enabled = true
data.Cluster.ClusterAddress = clustering.TargetAddress
data.Cluster.ClusterCertificate = string(clustering.TargetCert)
data.ClusterPassword = clustering.TargetPassword
}
// Fill the given init data with a new storage pool structure matching the
// given storage parameters.
func (cmd *CmdInit) fillDataWithStorage(data *cmdInitData, storage *cmdInitStorageParams, existingPools []string) error {
if storage == nil {
return nil
}
// Pool configuration
storagePoolConfig := map[string]string{}
if storage.Config != nil {
storagePoolConfig = storage.Config
}
if storage.Device != "" {
storagePoolConfig["source"] = storage.Device
if storage.Dataset != "" {
storage.Pool = storage.Dataset
}
} else if storage.LoopSize != -1 {
if storage.Dataset != "" {
storage.Pool = storage.Dataset
}
} else {
storagePoolConfig["source"] = storage.Dataset
}
if storage.LoopSize > 0 {
storagePoolConfig["size"] = strconv.FormatInt(storage.LoopSize, 10) + "GB"
}
// Create the requested storage pool.
storageStruct := api.StoragePoolsPost{
Name: storage.Pool,
Driver: storage.Backend,
}
storageStruct.Config = storagePoolConfig
data.Pools = []api.StoragePoolsPost{storageStruct}
// When lxd init is rerun and there are already storage pools
// configured, do not try to set a root disk device in the
// default profile again. Let the user figure this out.
if len(existingPools) == 0 {
if len(data.Profiles) != 0 {
defaultProfile := data.Profiles[0]
foundRootDiskDevice := false
for k, v := range defaultProfile.Devices {
if v["path"] == "/" && v["source"] == "" {
foundRootDiskDevice = true
// Unconditionally overwrite because if the user ends up
// with a clean LXD but with a pool property key existing in
// the default profile it must be empty otherwise it would
// not have been possible to delete the storage pool in
// the first place.
defaultProfile.Devices[k]["pool"] = storage.Pool
logger.Debugf("Set pool property of existing root disk device \"%s\" in profile \"default\" to \"%s\".", storage.Pool)
break
}
}
if !foundRootDiskDevice {
err := cmd.profileDeviceAlreadyExists(&defaultProfile, "root")
if err != nil {
return err
}
defaultProfile.Devices["root"] = map[string]string{
"type": "disk",
"path": "/",
"pool": storage.Pool,
}
}
} else {
logger.Warnf("Did not find profile \"default\" so no default storage pool will be set. Manual intervention needed.")
}
}
return nil
}
// Fill the default profile in the given init data with options about whether
// to run in privileged mode.
func (cmd *CmdInit) fillDataWithDefaultPrivileged(data *cmdInitData, defaultPrivileged int) error {
if defaultPrivileged == -1 {
return nil
}
if len(data.Profiles) == 0 {
return fmt.Errorf("error: profile 'default' profile not found")
}
defaultProfile := data.Profiles[0]
if defaultPrivileged == 0 {
defaultProfile.Config["security.privileged"] = ""
} else if defaultPrivileged == 1 {
defaultProfile.Config["security.privileged"] = "true"
}
return nil
}
// Fill the given init data with server config details matching the
// given networking parameters.
func (cmd *CmdInit) fillDataWithNetworking(data *cmdInitData, networking *cmdInitNetworkingParams) {
if networking == nil {
return
}
data.Config["core.https_address"] = fmt.Sprintf("%s:%d", networking.Address, networking.Port)
if networking.TrustPassword != "" {
data.Config["core.trust_password"] = networking.TrustPassword
}
}
// Fill the given init data with server config details matching the
// given images auto update choice.
func (cmd *CmdInit) fillDataWithImages(data *cmdInitData, imagesAutoUpdate bool) {
if imagesAutoUpdate {
if val, ok := data.Config["images.auto_update_interval"]; ok && val == "0" {
data.Config["images.auto_update_interval"] = ""
}
} else {
data.Config["images.auto_update_interval"] = "0"
}
}
// Fill the given init data with a new bridge network device structure
// matching the given storage parameters.
func (cmd *CmdInit) fillDataWithBridge(data *cmdInitData, bridge *cmdInitBridgeParams) error {
if bridge == nil {
return nil
}
bridgeConfig := map[string]string{}
bridgeConfig["ipv4.address"] = bridge.IPv4
bridgeConfig["ipv6.address"] = bridge.IPv6
if bridge.IPv4Nat {
bridgeConfig["ipv4.nat"] = "true"
}
if bridge.IPv6Nat {
bridgeConfig["ipv6.nat"] = "true"
}
network := api.NetworksPost{
Name: bridge.Name}
network.Config = bridgeConfig
data.Networks = []api.NetworksPost{network}
if len(data.Profiles) == 0 {
return fmt.Errorf("error: profile 'default' profile not found")
}
// Attach the bridge as eth0 device of the default profile, if such
// device doesn't exists yet.
defaultProfile := data.Profiles[0]
err := cmd.profileDeviceAlreadyExists(&defaultProfile, "eth0")
if err != nil {
return err
}
defaultProfile.Devices["eth0"] = map[string]string{
"type": "nic",
"nictype": "bridged",
"parent": bridge.Name,
}
return nil
}
// Apply the configuration specified in the given init data.
func (cmd *CmdInit) apply(client lxd.ContainerServer, data *cmdInitData) error {
// Functions that should be invoked to revert back to initial
// state any change that was successfully applied, in case
// anything goes wrong after that change.
reverters := make([]reverter, 0)
// Functions to apply the desired changes.
changers := make([](func() (reverter, error)), 0)
// Server config changer
changers = append(changers, func() (reverter, error) {
return cmd.initConfig(client, data.Config)
})
// Storage pool changers
for i := range data.Pools {
pool := data.Pools[i] // Local variable for the closure
changers = append(changers, func() (reverter, error) {
return cmd.initPool(client, pool)
})
}
// Network changers
for i := range data.Networks {
network := data.Networks[i] // Local variable for the closure
changers = append(changers, func() (reverter, error) {
return cmd.initNetwork(client, network)
})
}
// Profile changers
for i := range data.Profiles {
profile := data.Profiles[i] // Local variable for the closure
changers = append(changers, func() (reverter, error) {
return cmd.initProfile(client, profile)
})
}
// Cluster changers
if data.Cluster.ServerName != "" {
changers = append(changers, func() (reverter, error) {
return cmd.initCluster(client, data.Cluster, data.ClusterPassword)
})
}
// Apply all changes. If anything goes wrong at any iteration
// of the loop, we'll try to revert any change performed in
// earlier iterations.
for _, changer := range changers {
reverter, err := changer()
if err != nil {
cmd.revert(reverters)
return err
}
// Save the revert function for later.
reverters = append(reverters, reverter)
}
return nil
}
// Try to revert the state to what it was before running the "lxd init" command.
func (cmd *CmdInit) revert(reverters []reverter) {
for _, reverter := range reverters {
err := reverter()
if err != nil {
logger.Warnf("Reverting to pre-init state failed: %s", err)
break
}
}
}
// Apply the server-level configuration in the given map.
func (cmd *CmdInit) initConfig(client lxd.ContainerServer, config map[string]interface{}) (reverter, error) {
server, etag, err := client.GetServer()
if err != nil {
return nil, err
}
// Build a function that can be used to revert the config to
// its original values.
reverter := func() error {
return client.UpdateServer(server.Writable(), "")
}
// The underlying code expects all values to be string, even if when
// using preseed the yaml.v2 package unmarshals them as integers.
for key, value := range config {
if number, ok := value.(int); ok {
value = strconv.Itoa(number)
}
config[key] = value
}
err = client.UpdateServer(api.ServerPut{Config: config}, etag)
if err != nil {
return nil, err
}
// Updating the server was successful, so return the reverter function
// in case it's needed later.
return reverter, nil
}
// Turn on clustering.
func (cmd *CmdInit) initCluster(client lxd.ContainerServer, put api.ClusterPut, password string) (reverter, error) {
var reverter func() error
var op *lxd.Operation
var err error
if put.ClusterAddress == "" {
op, err = client.UpdateCluster(put, "")
if err != nil {
return nil, err
}
} else {
// If a password was provided, try to make the joining node's
// certificate trusted by the cluster.
if password != "" {
server, _, err := client.GetServer()
if err != nil {
return nil, errors.Wrap(err, "failed to get joining node's server info")
}
err = cluster.SetupTrust(
server.Environment.Certificate, put.ClusterAddress, put.ClusterCertificate,
password)
if err != nil {
return nil, errors.Wrap(err, "failed to register joining node's certificate")
}
}
op, err = client.UpdateCluster(put, "")
if err != nil {
return nil, err
}
}
err = op.Wait()
if err != nil {
return nil, err
}
return reverter, nil
}
// Create or update a single pool, and return a revert function in case of success.
func (cmd *CmdInit) initPool(client lxd.ContainerServer, pool api.StoragePoolsPost) (reverter, error) {
var reverter func() error
currentPool, _, err := client.GetStoragePool(pool.Name)
if err == nil {
reverter, err = cmd.initPoolUpdate(client, pool, currentPool.Writable())
} else {
reverter, err = cmd.initPoolCreate(client, pool)
}
if err != nil {
return nil, err
}
return reverter, nil
}
// Create a single new pool, and return a revert function to delete it.
func (cmd *CmdInit) initPoolCreate(client lxd.ContainerServer, pool api.StoragePoolsPost) (reverter, error) {
reverter := func() error {
return client.DeleteStoragePool(pool.Name)
}
err := client.CreateStoragePool(pool)
return reverter, err
}
// Update a single pool, and return a function that can be used to
// revert it to its original state.
func (cmd *CmdInit) initPoolUpdate(client lxd.ContainerServer, pool api.StoragePoolsPost, currentPool api.StoragePoolPut) (reverter, error) {
reverter := func() error {
return client.UpdateStoragePool(pool.Name, currentPool, "")
}
err := client.UpdateStoragePool(pool.Name, api.StoragePoolPut{
Config: pool.Config,
}, "")
return reverter, err
}
// Create or update a single network, and return a revert function in case of success.
func (cmd *CmdInit) initNetwork(client lxd.ContainerServer, network api.NetworksPost) (reverter, error) {
var revert func() error
currentNetwork, _, err := client.GetNetwork(network.Name)
if err == nil {
// Sanity check, make sure the network type being updated
// is still "bridge", which is the only type the existing
// network can have.
if network.Type != "" && network.Type != "bridge" {
return nil, fmt.Errorf("Only 'bridge' type networks are supported")
}
revert, err = cmd.initNetworkUpdate(client, network, currentNetwork.Writable())
} else {
revert, err = cmd.initNetworkCreate(client, network)
}
if err != nil {
return nil, err
}
return revert, nil
}
// Create a single new network, and return a revert function to delete it.
func (cmd *CmdInit) initNetworkCreate(client lxd.ContainerServer, network api.NetworksPost) (reverter, error) {
reverter := func() error {
return client.DeleteNetwork(network.Name)
}
err := client.CreateNetwork(network)
return reverter, err
}
// Update a single network, and return a function that can be used to
// revert it to its original state.
func (cmd *CmdInit) initNetworkUpdate(client lxd.ContainerServer, network api.NetworksPost, currentNetwork api.NetworkPut) (reverter, error) {
reverter := func() error {
return client.UpdateNetwork(network.Name, currentNetwork, "")
}
err := client.UpdateNetwork(network.Name, api.NetworkPut{
Config: network.Config,
}, "")
return reverter, err
}
// Create or update a single profile, and return a revert function in case of success.
func (cmd *CmdInit) initProfile(client lxd.ContainerServer, profile api.ProfilesPost) (reverter, error) {
var reverter func() error
currentProfile, _, err := client.GetProfile(profile.Name)
if err == nil {
reverter, err = cmd.initProfileUpdate(client, profile, currentProfile.Writable())
} else {
reverter, err = cmd.initProfileCreate(client, profile)
}
if err != nil {
return nil, err
}
return reverter, nil
}
// Create a single new profile, and return a revert function to delete it.
func (cmd *CmdInit) initProfileCreate(client lxd.ContainerServer, profile api.ProfilesPost) (reverter, error) {
reverter := func() error {
return client.DeleteProfile(profile.Name)
}
err := client.CreateProfile(profile)
return reverter, err
}
// Update a single profile, and return a function that can be used to
// revert it to its original state.
func (cmd *CmdInit) initProfileUpdate(client lxd.ContainerServer, profile api.ProfilesPost, currentProfile api.ProfilePut) (reverter, error) {
reverter := func() error {
return client.UpdateProfile(profile.Name, currentProfile, "")
}
err := client.UpdateProfile(profile.Name, api.ProfilePut{
Config: profile.Config,
Description: profile.Description,
Devices: profile.Devices,
}, "")
return reverter, err
}
// Check that the arguments passed via command line are consistent,
// and no invalid combination is provided.
func (cmd *CmdInit) validateArgs() error {
if cmd.Args.Auto && cmd.Args.Preseed {
return fmt.Errorf("Non-interactive mode supported by only one of --auto or --preseed")
}
if !cmd.Args.Auto {
if cmd.Args.StorageBackend != "" || cmd.Args.StorageCreateDevice != "" || cmd.Args.StorageCreateLoop != -1 || cmd.Args.StorageDataset != "" || cmd.Args.NetworkAddress != "" || cmd.Args.NetworkPort != -1 || cmd.Args.TrustPassword != "" {
return fmt.Errorf("Init configuration is only valid with --auto")
}
}
return nil
}
// Check that the arguments passed along with --auto are valid and consistent.
// and no invalid combination is provided.
func (cmd *CmdInit) validateArgsAuto(availableStoragePoolsDrivers []string) error {
if !shared.StringInSlice(cmd.Args.StorageBackend, supportedStoragePoolDrivers) {
return fmt.Errorf("The requested backend '%s' isn't supported by lxd init.", cmd.Args.StorageBackend)
}
if !shared.StringInSlice(cmd.Args.StorageBackend, availableStoragePoolsDrivers) {
return fmt.Errorf("The requested backend '%s' isn't available on your system (missing tools).", cmd.Args.StorageBackend)
}
if cmd.Args.StorageBackend == "dir" {
if cmd.Args.StorageCreateLoop != -1 || cmd.Args.StorageCreateDevice != "" || cmd.Args.StorageDataset != "" {
return fmt.Errorf("None of --storage-pool, --storage-create-device or --storage-create-loop may be used with the 'dir' backend.")
}
} else {
if cmd.Args.StorageCreateLoop != -1 && cmd.Args.StorageCreateDevice != "" {
return fmt.Errorf("Only one of --storage-create-device or --storage-create-loop can be specified.")
}
}
if cmd.Args.NetworkAddress == "" {
if cmd.Args.NetworkPort != -1 {
return fmt.Errorf("--network-port cannot be used without --network-address.")
}
if cmd.Args.TrustPassword != "" {
return fmt.Errorf("--trust-password cannot be used without --network-address.")
}
}
return nil
}
// Return the available storage pools drivers (depending on installed tools).
func (cmd *CmdInit) availableStoragePoolsDrivers() []string {
drivers := []string{"dir"}
backingFs, err := util.FilesystemDetect(shared.VarPath())
if err != nil {
backingFs = "dir"
}
// Check available backends
for _, driver := range supportedStoragePoolDrivers {
if driver == "dir" {
continue
}
// btrfs can work in user namespaces too. (If
// source=/some/path/on/btrfs is used.)
if cmd.RunningInUserns && (backingFs != "btrfs" || driver != "btrfs") {
continue
}
// Initialize a core storage interface for the given driver.
_, err := storageCoreInit(driver)
if err != nil {
continue
}
drivers = append(drivers, driver)
}
return drivers
}
// Return an error if the given profile has already a device with the
// given name.
func (cmd *CmdInit) profileDeviceAlreadyExists(profile *api.ProfilesPost, deviceName string) error {
_, ok := profile.Devices[deviceName]
if ok {
return fmt.Errorf("Device already exists: %s", deviceName)
}
return nil
}
// Ask if the user wants to enable clustering
func (cmd *CmdInit) askClustering() (*cmdInitClusteringParams, error) {
askWants := "Would you like to use LXD clustering? (yes/no) [default=no]: "
if !cmd.Context.AskBool(askWants, "no") {
return nil, nil
}
params := &cmdInitClusteringParams{}
// Node name
hostname, err := os.Hostname()
if err != nil {
hostname = "lxd"
}
askName := fmt.Sprintf(
"What name should be used to identify this node in the cluster? [default=%s]: ",
hostname)
params.Name = cmd.Context.AskString(askName, hostname, nil)
// Network address
address := util.NetworkInterfaceAddress()
askAddress := fmt.Sprintf(
"What IP address or DNS name should be used to reach this node? [default=%s]: ",
address)
address = util.CanonicalNetworkAddress(cmd.Context.AskString(askAddress, address, nil))
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
portN, err := strconv.Atoi(port)
if err != nil {
return nil, err
}
params.Address = host
params.Port = int64(portN)
// Join existing cluster
if !cmd.Context.AskBool("Are you joining an existing cluster? (yes/no) [default=no]: ", "no") {
params.TrustPassword = cmd.Context.AskPassword(
"Trust password for new clients: ", cmd.PasswordReader)
return params, nil
}
// Target node address, password and certificate.
join:
targetAddress := cmd.Context.AskString("IP address or FQDN of an existing cluster node: ", "", nil)
params.TargetAddress = util.CanonicalNetworkAddress(targetAddress)
url := fmt.Sprintf("https://%s", params.TargetAddress)
certificate, err := shared.GetRemoteCertificate(url)
if err != nil {
cmd.Context.Output("Error connecting to existing cluster node: %v\n", err)
goto join
}
digest := shared.CertFingerprint(certificate)
params.TargetPassword = cmd.Context.AskPasswordOnce(
fmt.Sprintf("Trust password for node with fingerprint %s: ", digest), cmd.PasswordReader)
params.TargetCert = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certificate.Raw})
// Confirm wipe this node
askConfirm := ("All existing data is lost when joining a cluster, " +
"continue? (yes/no) [default=no] ")
if !cmd.Context.AskBool(askConfirm, "") {
return nil, fmt.Errorf("User did not confirm erasing data")
}
return params, nil
}
func (cmd *CmdInit) askClusteringStoragePools(targetPools []api.StoragePool) ([]api.StoragePoolsPost, error) {
pools := make([]api.StoragePoolsPost, len(targetPools))
for i, pool := range targetPools {
if pool.Status == "PENDING" {
continue // Skip pending pools
}
post := api.StoragePoolsPost{}
post.Name = pool.Name
post.Driver = pool.Driver
post.Config = pool.Config
// Only ask for the node-specific "source" key if it's defined
// in the target node.
if pool.Config["source"] != "" {
key := "source"
question := fmt.Sprintf(
`Enter local value for key "%s" of storage pool "%s": `, key, post.Name)
// Dummy validator for allowing empty strings.
validator := func(string) error { return nil }
post.Config[key] = cmd.Context.AskString(question, "", validator)
}
pools[i] = post
}
return pools, nil
}
func (cmd *CmdInit) askClusteringNetworks(targetNetworks []api.Network) ([]api.NetworksPost, error) {
networks := make([]api.NetworksPost, len(targetNetworks))
for i, network := range targetNetworks {
if !network.Managed || network.Status == "PENDING" {
continue // Skip not-managed or pending networks
}
post := api.NetworksPost{}
post.Name = network.Name
post.Config = network.Config
post.Type = network.Type
post.Managed = true
// Only ask for the node-specific "bridge.external_interfaces"
// key if it's defined in the target node.
if network.Config["bridge.external_interfaces"] != "" {
key := "bridge.external_interfaces"
question := fmt.Sprintf(
`Enter local value for key "%s" of network "%s": `, key, post.Name)
// Dummy validator for allowing empty strings.
validator := func(string) error { return nil }
post.Config[key] = cmd.Context.AskString(question, "", validator)
}
networks[i] = post
}
return networks, nil
}
// Ask if the user wants to create a new storage pool, and return
// the relevant parameters if so.
func (cmd *CmdInit) askStorage(client lxd.ContainerServer, existingPools []string, availableBackends []string) (*cmdInitStorageParams, error) {
if !cmd.Context.AskBool("Do you want to configure a new storage pool (yes/no) [default=yes]? ", "yes") {
return nil, nil
}
storage := &cmdInitStorageParams{
Config: map[string]string{},
}
backingFs, err := util.FilesystemDetect(shared.VarPath())
if err != nil {
backingFs = "dir"
}
defaultStorage := "dir"
if backingFs == "btrfs" && shared.StringInSlice("btrfs", availableBackends) {
defaultStorage = "btrfs"
} else if shared.StringInSlice("zfs", availableBackends) {
defaultStorage = "zfs"
} else if shared.StringInSlice("btrfs", availableBackends) {
defaultStorage = "btrfs"
}
for {
storage.LoopSize = -1
storage.Pool = cmd.Context.AskString("Name of the new storage pool [default=default]: ", "default", nil)
if shared.StringInSlice(storage.Pool, existingPools) {
fmt.Printf("The requested storage pool \"%s\" already exists. Please choose another name.\n", storage.Pool)
// Ask the user again if hew wants to create a
// storage pool.
continue
}
storage.Backend = cmd.Context.AskChoice(fmt.Sprintf("Name of the storage backend to use (%s) [default=%s]: ", strings.Join(availableBackends, ", "), defaultStorage), supportedStoragePoolDrivers, defaultStorage)
// XXX The following to checks don't make much sense, since
// AskChoice will always re-ask the question if the answer
// is not among supportedStoragePoolDrivers. It seems legacy
// code that we should drop?
if !shared.StringInSlice(storage.Backend, supportedStoragePoolDrivers) {
return nil, fmt.Errorf("The requested backend '%s' isn't supported by lxd init.", storage.Backend)
}
// XXX Instead of manually checking if the provided choice is
// among availableBackends, we could just pass to askChoice the
// availableBackends list instead of supportedStoragePoolDrivers.
if !shared.StringInSlice(storage.Backend, availableBackends) {
return nil, fmt.Errorf("The requested backend '%s' isn't available on your system (missing tools).", storage.Backend)
}
if storage.Backend == "dir" {
break
}
// Optimization for btrfs on btrfs
if storage.Backend == "btrfs" && backingFs == "btrfs" {
if cmd.Context.AskBool(fmt.Sprintf("Would you like to create a new btrfs subvolume under %s (yes/no) [default=yes]: ", shared.VarPath("")), "yes") {
storage.Dataset = shared.VarPath("storage-pools", storage.Pool)
break
}
}
question := fmt.Sprintf("Create a new %s pool (yes/no) [default=yes]? ", strings.ToUpper(storage.Backend))
if cmd.Context.AskBool(question, "yes") {