/
provisioner.go
1313 lines (1241 loc) · 42.4 KB
/
provisioner.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
// Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package provisioner
import (
"fmt"
"sort"
"strings"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names"
"github.com/juju/utils/set"
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/cloudconfig/instancecfg"
"github.com/juju/juju/constraints"
"github.com/juju/juju/container"
"github.com/juju/juju/environs"
"github.com/juju/juju/environs/tags"
"github.com/juju/juju/instance"
"github.com/juju/juju/network"
"github.com/juju/juju/provider"
"github.com/juju/juju/state"
"github.com/juju/juju/state/multiwatcher"
"github.com/juju/juju/state/watcher"
"github.com/juju/juju/storage"
"github.com/juju/juju/storage/poolmanager"
"github.com/juju/juju/storage/provider/registry"
)
var logger = loggo.GetLogger("juju.apiserver.provisioner")
func init() {
common.RegisterStandardFacade("Provisioner", 1, NewProvisionerAPI)
}
// ProvisionerAPI provides access to the Provisioner API facade.
type ProvisionerAPI struct {
*common.Remover
*common.StatusSetter
*common.StatusGetter
*common.DeadEnsurer
*common.PasswordChanger
*common.LifeGetter
*common.StateAddresser
*common.APIAddresser
*common.EnvironWatcher
*common.EnvironMachinesWatcher
*common.InstanceIdGetter
*common.ToolsFinder
st *state.State
resources *common.Resources
authorizer common.Authorizer
getAuthFunc common.GetAuthFunc
}
// NewProvisionerAPI creates a new server-side ProvisionerAPI facade.
func NewProvisionerAPI(st *state.State, resources *common.Resources, authorizer common.Authorizer) (*ProvisionerAPI, error) {
if !authorizer.AuthMachineAgent() && !authorizer.AuthEnvironManager() {
return nil, common.ErrPerm
}
getAuthFunc := func() (common.AuthFunc, error) {
isEnvironManager := authorizer.AuthEnvironManager()
isMachineAgent := authorizer.AuthMachineAgent()
authEntityTag := authorizer.GetAuthTag()
return func(tag names.Tag) bool {
if isMachineAgent && tag == authEntityTag {
// A machine agent can always access its own machine.
return true
}
switch tag := tag.(type) {
case names.MachineTag:
parentId := state.ParentId(tag.Id())
if parentId == "" {
// All top-level machines are accessible by the
// environment manager.
return isEnvironManager
}
// All containers with the authenticated machine as a
// parent are accessible by it.
// TODO(dfc) sometimes authEntity tag is nil, which is fine because nil is
// only equal to nil, but it suggests someone is passing an authorizer
// with a nil tag.
return isMachineAgent && names.NewMachineTag(parentId) == authEntityTag
default:
return false
}
}, nil
}
env, err := st.Environment()
if err != nil {
return nil, err
}
urlGetter := common.NewToolsURLGetter(env.UUID(), st)
return &ProvisionerAPI{
Remover: common.NewRemover(st, false, getAuthFunc),
StatusSetter: common.NewStatusSetter(st, getAuthFunc),
StatusGetter: common.NewStatusGetter(st, getAuthFunc),
DeadEnsurer: common.NewDeadEnsurer(st, getAuthFunc),
PasswordChanger: common.NewPasswordChanger(st, getAuthFunc),
LifeGetter: common.NewLifeGetter(st, getAuthFunc),
StateAddresser: common.NewStateAddresser(st),
APIAddresser: common.NewAPIAddresser(st, resources),
EnvironWatcher: common.NewEnvironWatcher(st, resources, authorizer),
EnvironMachinesWatcher: common.NewEnvironMachinesWatcher(st, resources, authorizer),
InstanceIdGetter: common.NewInstanceIdGetter(st, getAuthFunc),
ToolsFinder: common.NewToolsFinder(st, st, urlGetter),
st: st,
resources: resources,
authorizer: authorizer,
getAuthFunc: getAuthFunc,
}, nil
}
func (p *ProvisionerAPI) getMachine(canAccess common.AuthFunc, tag names.MachineTag) (*state.Machine, error) {
if !canAccess(tag) {
return nil, common.ErrPerm
}
entity, err := p.st.FindEntity(tag)
if err != nil {
return nil, err
}
// The authorization function guarantees that the tag represents a
// machine.
return entity.(*state.Machine), nil
}
func (p *ProvisionerAPI) watchOneMachineContainers(arg params.WatchContainer) (params.StringsWatchResult, error) {
nothing := params.StringsWatchResult{}
canAccess, err := p.getAuthFunc()
if err != nil {
return nothing, common.ErrPerm
}
tag, err := names.ParseMachineTag(arg.MachineTag)
if err != nil {
return nothing, common.ErrPerm
}
if !canAccess(tag) {
return nothing, common.ErrPerm
}
machine, err := p.st.Machine(tag.Id())
if err != nil {
return nothing, err
}
var watch state.StringsWatcher
if arg.ContainerType != "" {
watch = machine.WatchContainers(instance.ContainerType(arg.ContainerType))
} else {
watch = machine.WatchAllContainers()
}
// Consume the initial event and forward it to the result.
if changes, ok := <-watch.Changes(); ok {
return params.StringsWatchResult{
StringsWatcherId: p.resources.Register(watch),
Changes: changes,
}, nil
}
return nothing, watcher.EnsureErr(watch)
}
// WatchContainers starts a StringsWatcher to watch containers deployed to
// any machine passed in args.
func (p *ProvisionerAPI) WatchContainers(args params.WatchContainers) (params.StringsWatchResults, error) {
result := params.StringsWatchResults{
Results: make([]params.StringsWatchResult, len(args.Params)),
}
for i, arg := range args.Params {
watcherResult, err := p.watchOneMachineContainers(arg)
result.Results[i] = watcherResult
result.Results[i].Error = common.ServerError(err)
}
return result, nil
}
// WatchAllContainers starts a StringsWatcher to watch all containers deployed to
// any machine passed in args.
func (p *ProvisionerAPI) WatchAllContainers(args params.WatchContainers) (params.StringsWatchResults, error) {
return p.WatchContainers(args)
}
// SetSupportedContainers updates the list of containers supported by the machines passed in args.
func (p *ProvisionerAPI) SetSupportedContainers(args params.MachineContainersParams) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Params)),
}
canAccess, err := p.getAuthFunc()
if err != nil {
return result, err
}
for i, arg := range args.Params {
tag, err := names.ParseMachineTag(arg.MachineTag)
if err != nil {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
machine, err := p.getMachine(canAccess, tag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
if len(arg.ContainerTypes) == 0 {
err = machine.SupportsNoContainers()
} else {
err = machine.SetSupportedContainers(arg.ContainerTypes)
}
if err != nil {
result.Results[i].Error = common.ServerError(err)
}
}
return result, nil
}
// ContainerManagerConfig returns information from the environment config that is
// needed for configuring the container manager.
func (p *ProvisionerAPI) ContainerManagerConfig(args params.ContainerManagerConfigParams) (params.ContainerManagerConfig, error) {
var result params.ContainerManagerConfig
config, err := p.st.EnvironConfig()
if err != nil {
return result, err
}
cfg := make(map[string]string)
cfg[container.ConfigName] = container.DefaultNamespace
switch args.Type {
case instance.LXC:
if useLxcClone, ok := config.LXCUseClone(); ok {
cfg["use-clone"] = fmt.Sprint(useLxcClone)
}
if useLxcCloneAufs, ok := config.LXCUseCloneAUFS(); ok {
cfg["use-aufs"] = fmt.Sprint(useLxcCloneAufs)
}
if lxcDefaultMTU, ok := config.LXCDefaultMTU(); ok {
logger.Debugf("using default MTU %v for all LXC containers NICs", lxcDefaultMTU)
cfg[container.ConfigLXCDefaultMTU] = fmt.Sprintf("%d", lxcDefaultMTU)
}
}
if !environs.AddressAllocationEnabled() {
// No need to even try checking the environ for support.
logger.Debugf("address allocation feature flag not enabled")
result.ManagerConfig = cfg
return result, nil
}
// Create an environment to verify networking support.
env, err := environs.New(config)
if err != nil {
return result, err
}
if netEnv, ok := environs.SupportsNetworking(env); ok {
// Passing network.AnySubnet below should be interpreted by
// the provider as "does ANY subnet support this".
supported, err := netEnv.SupportsAddressAllocation(network.AnySubnet)
if err == nil && supported {
cfg[container.ConfigIPForwarding] = "true"
} else if err != nil {
// We log the error, but it's safe to ignore as it's not
// critical.
logger.Debugf("address allocation not supported (%v)", err)
}
// AWS requires NAT in place in order for hosted containers to
// reach outside.
if config.Type() == provider.EC2 {
cfg[container.ConfigEnableNAT] = "true"
}
}
result.ManagerConfig = cfg
return result, nil
}
// ContainerConfig returns information from the environment config that is
// needed for container cloud-init.
func (p *ProvisionerAPI) ContainerConfig() (params.ContainerConfig, error) {
result := params.ContainerConfig{}
config, err := p.st.EnvironConfig()
if err != nil {
return result, err
}
result.UpdateBehavior = ¶ms.UpdateBehavior{
config.EnableOSRefreshUpdate(),
config.EnableOSUpgrade(),
}
result.ProviderType = config.Type()
result.AuthorizedKeys = config.AuthorizedKeys()
result.SSLHostnameVerification = config.SSLHostnameVerification()
result.Proxy = config.ProxySettings()
result.AptProxy = config.AptProxySettings()
result.PreferIPv6 = config.PreferIPv6()
result.AllowLXCLoopMounts, _ = config.AllowLXCLoopMounts()
return result, nil
}
// MachinesWithTransientErrors returns status data for machines with provisioning
// errors which are transient.
func (p *ProvisionerAPI) MachinesWithTransientErrors() (params.StatusResults, error) {
var results params.StatusResults
canAccessFunc, err := p.getAuthFunc()
if err != nil {
return results, err
}
// TODO (wallyworld) - add state.State API for more efficient machines query
machines, err := p.st.AllMachines()
if err != nil {
return results, err
}
for _, machine := range machines {
if !canAccessFunc(machine.Tag()) {
continue
}
if _, provisionedErr := machine.InstanceId(); provisionedErr == nil {
// Machine may have been provisioned but machiner hasn't set the
// status to Started yet.
continue
}
var result params.StatusResult
statusInfo, err := machine.Status()
if err != nil {
continue
}
result.Status = params.Status(statusInfo.Status)
result.Info = statusInfo.Message
result.Data = statusInfo.Data
if result.Status != params.StatusError {
continue
}
// Transient errors are marked as such in the status data.
if transient, ok := result.Data["transient"].(bool); !ok || !transient {
continue
}
result.Id = machine.Id()
result.Life = params.Life(machine.Life().String())
results.Results = append(results.Results, result)
}
return results, nil
}
// Series returns the deployed series for each given machine entity.
func (p *ProvisionerAPI) Series(args params.Entities) (params.StringResults, error) {
result := params.StringResults{
Results: make([]params.StringResult, len(args.Entities)),
}
canAccess, err := p.getAuthFunc()
if err != nil {
return result, err
}
for i, entity := range args.Entities {
tag, err := names.ParseMachineTag(entity.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
machine, err := p.getMachine(canAccess, tag)
if err == nil {
result.Results[i].Result = machine.Series()
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
}
// ProvisioningInfo returns the provisioning information for each given machine entity.
func (p *ProvisionerAPI) ProvisioningInfo(args params.Entities) (params.ProvisioningInfoResults, error) {
result := params.ProvisioningInfoResults{
Results: make([]params.ProvisioningInfoResult, len(args.Entities)),
}
canAccess, err := p.getAuthFunc()
if err != nil {
return result, err
}
for i, entity := range args.Entities {
tag, err := names.ParseMachineTag(entity.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
machine, err := p.getMachine(canAccess, tag)
if err == nil {
result.Results[i].Result, err = p.getProvisioningInfo(machine)
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
}
func (p *ProvisionerAPI) getProvisioningInfo(m *state.Machine) (*params.ProvisioningInfo, error) {
cons, err := m.Constraints()
if err != nil {
return nil, err
}
volumes, err := p.machineVolumeParams(m)
if err != nil {
return nil, errors.Trace(err)
}
// TODO(dimitern) For now, since network names and
// provider ids are the same, we return what we got
// from state. In the future, when networks can be
// added before provisioning, we should convert both
// slices from juju network names to provider-specific
// ids before returning them.
networks, err := m.RequestedNetworks()
if err != nil {
return nil, err
}
var jobs []multiwatcher.MachineJob
for _, job := range m.Jobs() {
jobs = append(jobs, job.ToParams())
}
tags, err := p.machineTags(m, jobs)
if err != nil {
return nil, errors.Trace(err)
}
return ¶ms.ProvisioningInfo{
Constraints: cons,
Series: m.Series(),
Placement: m.Placement(),
Networks: networks,
Jobs: jobs,
Volumes: volumes,
Tags: tags,
}, nil
}
// DistributionGroup returns, for each given machine entity,
// a slice of instance.Ids that belong to the same distribution
// group as that machine. This information may be used to
// distribute instances for high availability.
func (p *ProvisionerAPI) DistributionGroup(args params.Entities) (params.DistributionGroupResults, error) {
result := params.DistributionGroupResults{
Results: make([]params.DistributionGroupResult, len(args.Entities)),
}
canAccess, err := p.getAuthFunc()
if err != nil {
return result, err
}
for i, entity := range args.Entities {
tag, err := names.ParseMachineTag(entity.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
machine, err := p.getMachine(canAccess, tag)
if err == nil {
// If the machine is an environment manager, return
// environment manager instances. Otherwise, return
// instances with services in common with the machine
// being provisioned.
if machine.IsManager() {
result.Results[i].Result, err = environManagerInstances(p.st)
} else {
result.Results[i].Result, err = commonServiceInstances(p.st, machine)
}
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
}
// environManagerInstances returns all environ manager instances.
func environManagerInstances(st *state.State) ([]instance.Id, error) {
info, err := st.StateServerInfo()
if err != nil {
return nil, err
}
instances := make([]instance.Id, 0, len(info.MachineIds))
for _, id := range info.MachineIds {
machine, err := st.Machine(id)
if err != nil {
return nil, err
}
instanceId, err := machine.InstanceId()
if err == nil {
instances = append(instances, instanceId)
} else if !errors.IsNotProvisioned(err) {
return nil, err
}
}
return instances, nil
}
// commonServiceInstances returns instances with
// services in common with the specified machine.
func commonServiceInstances(st *state.State, m *state.Machine) ([]instance.Id, error) {
units, err := m.Units()
if err != nil {
return nil, err
}
instanceIdSet := make(set.Strings)
for _, unit := range units {
if !unit.IsPrincipal() {
continue
}
instanceIds, err := state.ServiceInstances(st, unit.ServiceName())
if err != nil {
return nil, err
}
for _, instanceId := range instanceIds {
instanceIdSet.Add(string(instanceId))
}
}
instanceIds := make([]instance.Id, instanceIdSet.Size())
// Sort values to simplify testing.
for i, instanceId := range instanceIdSet.SortedValues() {
instanceIds[i] = instance.Id(instanceId)
}
return instanceIds, nil
}
// Constraints returns the constraints for each given machine entity.
func (p *ProvisionerAPI) Constraints(args params.Entities) (params.ConstraintsResults, error) {
result := params.ConstraintsResults{
Results: make([]params.ConstraintsResult, len(args.Entities)),
}
canAccess, err := p.getAuthFunc()
if err != nil {
return result, err
}
for i, entity := range args.Entities {
tag, err := names.ParseMachineTag(entity.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
machine, err := p.getMachine(canAccess, tag)
if err == nil {
var cons constraints.Value
cons, err = machine.Constraints()
if err == nil {
result.Results[i].Constraints = cons
}
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
}
// machineVolumeParams retrieves VolumeParams for the volumes that should be
// provisioned with, and attached to, the machine. The client should ignore
// parameters that it does not know how to handle.
func (p *ProvisionerAPI) machineVolumeParams(m *state.Machine) ([]params.VolumeParams, error) {
volumeAttachments, err := m.VolumeAttachments()
if err != nil {
return nil, err
}
if len(volumeAttachments) == 0 {
return nil, nil
}
envConfig, err := p.st.EnvironConfig()
if err != nil {
return nil, err
}
poolManager := poolmanager.New(state.NewStateSettings(p.st))
allVolumeParams := make([]params.VolumeParams, 0, len(volumeAttachments))
for _, volumeAttachment := range volumeAttachments {
volumeTag := volumeAttachment.Volume()
volume, err := p.st.Volume(volumeTag)
if err != nil {
return nil, errors.Annotatef(err, "getting volume %q", volumeTag.Id())
}
storageInstance, err := common.MaybeAssignedStorageInstance(
volume.StorageInstance, p.st.StorageInstance,
)
if err != nil {
return nil, errors.Annotatef(err, "getting volume %q storage instance", volumeTag.Id())
}
volumeParams, err := common.VolumeParams(volume, storageInstance, envConfig, poolManager)
if err != nil {
return nil, errors.Annotatef(err, "getting volume %q parameters", volumeTag.Id())
}
provider, err := registry.StorageProvider(storage.ProviderType(volumeParams.Provider))
if err != nil {
return nil, errors.Annotate(err, "getting storage provider")
}
if provider.Dynamic() {
// Leave dynamic storage to the storage provisioner.
continue
}
volumeAttachmentParams, ok := volumeAttachment.Params()
if !ok {
// Attachment is already provisioned; this is an insane
// state, so we should not proceed with the volume.
return nil, errors.Errorf(
"volume %s already attached to machine %s",
volumeTag.Id(), m.Id(),
)
}
// Not provisioned yet, so ask the cloud provisioner do it.
volumeParams.Attachment = ¶ms.VolumeAttachmentParams{
volumeTag.String(),
m.Tag().String(),
"", // we're creating the volume, so it has no volume ID.
"", // we're creating the machine, so it has no instance ID.
volumeParams.Provider,
volumeAttachmentParams.ReadOnly,
}
allVolumeParams = append(allVolumeParams, volumeParams)
}
return allVolumeParams, nil
}
// storageConfig returns the provider type and config attributes for the
// specified poolName. If no such pool exists, we check to see if poolName is
// actually a provider type, in which case config will be empty.
func storageConfig(st *state.State, poolName string) (storage.ProviderType, map[string]interface{}, error) {
pm := poolmanager.New(state.NewStateSettings(st))
p, err := pm.Get(poolName)
// If not a storage pool, then maybe a provider type.
if errors.IsNotFound(err) {
providerType := storage.ProviderType(poolName)
if _, err1 := registry.StorageProvider(providerType); err1 != nil {
return "", nil, errors.Trace(err)
}
return providerType, nil, nil
}
if err != nil {
return "", nil, errors.Trace(err)
}
return p.Provider(), p.Attrs(), nil
}
// volumeAttachmentsToState converts a slice of storage.VolumeAttachment to a
// mapping of volume names to state.VolumeAttachmentInfo.
func volumeAttachmentsToState(in []params.VolumeAttachment) (map[names.VolumeTag]state.VolumeAttachmentInfo, error) {
m := make(map[names.VolumeTag]state.VolumeAttachmentInfo)
for _, v := range in {
if v.VolumeTag == "" {
return nil, errors.New("Tag is empty")
}
volumeTag, err := names.ParseVolumeTag(v.VolumeTag)
if err != nil {
return nil, errors.Trace(err)
}
m[volumeTag] = state.VolumeAttachmentInfo{
v.Info.DeviceName,
v.Info.ReadOnly,
}
}
return m, nil
}
func networkParamsToStateParams(networks []params.Network, ifaces []params.NetworkInterface) (
[]state.NetworkInfo, []state.NetworkInterfaceInfo, error,
) {
stateNetworks := make([]state.NetworkInfo, len(networks))
for i, net := range networks {
tag, err := names.ParseNetworkTag(net.Tag)
if err != nil {
return nil, nil, err
}
stateNetworks[i] = state.NetworkInfo{
Name: tag.Id(),
ProviderId: network.Id(net.ProviderId),
CIDR: net.CIDR,
VLANTag: net.VLANTag,
}
}
stateInterfaces := make([]state.NetworkInterfaceInfo, len(ifaces))
for i, iface := range ifaces {
tag, err := names.ParseNetworkTag(iface.NetworkTag)
if err != nil {
return nil, nil, err
}
stateInterfaces[i] = state.NetworkInterfaceInfo{
MACAddress: iface.MACAddress,
NetworkName: tag.Id(),
InterfaceName: iface.InterfaceName,
IsVirtual: iface.IsVirtual,
Disabled: iface.Disabled,
}
}
return stateNetworks, stateInterfaces, nil
}
// RequestedNetworks returns the requested networks for each given
// machine entity. Each entry in both lists is returned with its
// provider specific id.
func (p *ProvisionerAPI) RequestedNetworks(args params.Entities) (params.RequestedNetworksResults, error) {
result := params.RequestedNetworksResults{
Results: make([]params.RequestedNetworkResult, len(args.Entities)),
}
canAccess, err := p.getAuthFunc()
if err != nil {
return result, err
}
for i, entity := range args.Entities {
tag, err := names.ParseMachineTag(entity.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
machine, err := p.getMachine(canAccess, tag)
if err == nil {
var networks []string
networks, err = machine.RequestedNetworks()
if err == nil {
// TODO(dimitern) For now, since network names and
// provider ids are the same, we return what we got
// from state. In the future, when networks can be
// added before provisioning, we should convert both
// slices from juju network names to provider-specific
// ids before returning them.
result.Results[i].Networks = networks
}
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
}
// SetProvisioned sets the provider specific instance id, nonce and
// metadata for each given machine. Once set, the instance id cannot
// be changed.
//
// TODO(dimitern) This is not used anymore (as of 1.19.0) and is
// retained only for backwards-compatibility. It should be removed as
// deprecated. SetInstanceInfo is used instead.
func (p *ProvisionerAPI) SetProvisioned(args params.SetProvisioned) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Machines)),
}
canAccess, err := p.getAuthFunc()
if err != nil {
return result, err
}
for i, arg := range args.Machines {
tag, err := names.ParseMachineTag(arg.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
machine, err := p.getMachine(canAccess, tag)
if err == nil {
err = machine.SetProvisioned(arg.InstanceId, arg.Nonce, arg.Characteristics)
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
}
// SetInstanceInfo sets the provider specific machine id, nonce,
// metadata and network info for each given machine. Once set, the
// instance id cannot be changed.
func (p *ProvisionerAPI) SetInstanceInfo(args params.InstancesInfo) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Machines)),
}
canAccess, err := p.getAuthFunc()
if err != nil {
return result, err
}
setInstanceInfo := func(arg params.InstanceInfo) error {
tag, err := names.ParseMachineTag(arg.Tag)
if err != nil {
return common.ErrPerm
}
machine, err := p.getMachine(canAccess, tag)
if err != nil {
return err
}
networks, interfaces, err := networkParamsToStateParams(arg.Networks, arg.Interfaces)
if err != nil {
return err
}
volumes, err := common.VolumesToState(arg.Volumes)
if err != nil {
return err
}
volumeAttachments, err := common.VolumeAttachmentInfosToState(arg.VolumeAttachments)
if err != nil {
return err
}
if err = machine.SetInstanceInfo(
arg.InstanceId, arg.Nonce, arg.Characteristics,
networks, interfaces, volumes, volumeAttachments); err != nil {
return errors.Annotatef(
err,
"cannot record provisioning info for %q",
arg.InstanceId,
)
}
return nil
}
for i, arg := range args.Machines {
err := setInstanceInfo(arg)
result.Results[i].Error = common.ServerError(err)
}
return result, nil
}
// WatchMachineErrorRetry returns a NotifyWatcher that notifies when
// the provisioner should retry provisioning machines with transient errors.
func (p *ProvisionerAPI) WatchMachineErrorRetry() (params.NotifyWatchResult, error) {
result := params.NotifyWatchResult{}
if !p.authorizer.AuthEnvironManager() {
return result, common.ErrPerm
}
watch := newWatchMachineErrorRetry()
// Consume any initial event and forward it to the result.
if _, ok := <-watch.Changes(); ok {
result.NotifyWatcherId = p.resources.Register(watch)
} else {
return result, watcher.EnsureErr(watch)
}
return result, nil
}
// ReleaseContainerAddresses finds addresses allocated to a container
// and marks them as Dead, to be released and removed. It accepts
// container tags as arguments. If address allocation feature flag is
// not enabled, it will return a NotSupported error.
func (p *ProvisionerAPI) ReleaseContainerAddresses(args params.Entities) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
if !environs.AddressAllocationEnabled() {
return result, errors.NotSupportedf("address allocation")
}
canAccess, err := p.getAuthFunc()
if err != nil {
logger.Errorf("failed to get an authorisation function: %v", err)
return result, errors.Trace(err)
}
// Loop over the passed container tags.
for i, entity := range args.Entities {
tag, err := names.ParseMachineTag(entity.Tag)
if err != nil {
logger.Warningf("failed to parse machine tag %q: %v", entity.Tag, err)
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
// The auth function (canAccess) checks that the machine is a
// top level machine (we filter those out next) or that the
// machine has the host as a parent.
container, err := p.getMachine(canAccess, tag)
if err != nil {
logger.Warningf("failed to get machine %q: %v", tag, err)
result.Results[i].Error = common.ServerError(err)
continue
} else if !container.IsContainer() {
err = errors.Errorf("cannot mark addresses for removal for %q: not a container", tag)
result.Results[i].Error = common.ServerError(err)
continue
}
id := container.Id()
addresses, err := p.st.AllocatedIPAddresses(id)
if err != nil {
logger.Warningf("failed to get Id for container %q: %v", tag, err)
result.Results[i].Error = common.ServerError(err)
continue
}
deadErrors := []error{}
logger.Debugf("for container %q found addresses %v", tag, addresses)
for _, addr := range addresses {
err = addr.EnsureDead()
if err != nil {
deadErrors = append(deadErrors, err)
continue
}
}
if len(deadErrors) != 0 {
err = errors.Errorf("failed to mark all addresses for removal for %q: %v", tag, deadErrors)
result.Results[i].Error = common.ServerError(err)
}
}
return result, nil
}
// PrepareContainerInterfaceInfo allocates an address and returns
// information to configure networking for a container. It accepts
// container tags as arguments. If the address allocation feature flag
// is not enabled, it returns a NotSupported error.
func (p *ProvisionerAPI) PrepareContainerInterfaceInfo(args params.Entities) (
params.MachineNetworkConfigResults, error) {
return p.prepareOrGetContainerInterfaceInfo(args, true)
}
// GetContainerInterfaceInfo returns information to configure networking
// for a container. It accepts container tags as arguments. If the address
// allocation feature flag is not enabled, it returns a NotSupported error.
func (p *ProvisionerAPI) GetContainerInterfaceInfo(args params.Entities) (
params.MachineNetworkConfigResults, error) {
return p.prepareOrGetContainerInterfaceInfo(args, false)
}
// prepareOrGetContainerInterfaceInfo optionally allocates an address and returns information
// for configuring networking on a container. It accepts container tags as arguments.
func (p *ProvisionerAPI) prepareOrGetContainerInterfaceInfo(
args params.Entities, provisionContainer bool) (
params.MachineNetworkConfigResults, error) {
result := params.MachineNetworkConfigResults{
Results: make([]params.MachineNetworkConfigResult, len(args.Entities)),
}
if !environs.AddressAllocationEnabled() {
return result, errors.NotSupportedf("address allocation")
}
// Some preparations first.
environ, host, canAccess, err := p.prepareContainerAccessEnvironment()
if err != nil {
return result, errors.Trace(err)
}
instId, err := host.InstanceId()
if err != nil && errors.IsNotProvisioned(err) {
// If the host machine is not provisioned yet, we have nothing
// to do. NotProvisionedf will append " not provisioned" to
// the message.
err = errors.NotProvisionedf("cannot allocate addresses: host machine %q", host)
return result, err
}
subnet, subnetInfo, interfaceInfo, err := p.prepareAllocationNetwork(environ, host, instId)
if err != nil {
return result, errors.Annotate(err, "cannot allocate addresses")
}
// Loop over the passed container tags.
for i, entity := range args.Entities {
tag, err := names.ParseMachineTag(entity.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
// The auth function (canAccess) checks that the machine is a
// top level machine (we filter those out next) or that the
// machine has the host as a parent.
container, err := p.getMachine(canAccess, tag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
} else if !container.IsContainer() {
err = errors.Errorf("cannot allocate address for %q: not a container", tag)
result.Results[i].Error = common.ServerError(err)
continue
} else if ciid, cerr := container.InstanceId(); provisionContainer == true && cerr == nil {
// Since we want to configure and create NICs on the
// container before it starts, it must also be not
// provisioned yet.
err = errors.Errorf("container %q already provisioned as %q", container, ciid)
result.Results[i].Error = common.ServerError(err)
continue
} else if cerr != nil && !errors.IsNotProvisioned(cerr) {
// Any other error needs to be reported.
result.Results[i].Error = common.ServerError(cerr)
continue
}
var addresses []*state.IPAddress
if provisionContainer {
// Allocate and set address.
addr, err := p.allocateAddress(environ, subnet, host, container, instId)
addresses = append(addresses, addr)
if err != nil {
err = errors.Annotatef(err, "failed to allocate an address for %q", container)
result.Results[i].Error = common.ServerError(err)
continue
}
} else {
id := container.Id()
addresses, err = p.st.AllocatedIPAddresses(id)
if err != nil {
logger.Warningf("failed to get Id for container %q: %v", tag, err)
result.Results[i].Error = common.ServerError(err)
continue
}
// TODO(dooferlad): if we get more than 1 address back, we ignore everything after
// the first. The calling function expects exactly one result though,
// so we don't appear to have a way of allocating >1 address to a
// container...
if len(addresses) != 1 {
logger.Warningf("got %d addresses for container %q - expected 1: %v", len(addresses), tag, err)
result.Results[i].Error = common.ServerError(err)
continue
}
}
// Store it on the machine, construct and set an interface result.
dnsServers := make([]string, len(interfaceInfo.DNSServers))
for i, dns := range interfaceInfo.DNSServers {
dnsServers[i] = dns.Value
}
// TODO(dimitern): Support allocating one address per NIC on
// the host, effectively creating the same number of NICs in
// the container.
result.Results[i] = params.MachineNetworkConfigResult{
Config: []params.NetworkConfig{{
DeviceIndex: interfaceInfo.DeviceIndex,