forked from juju/juju
-
Notifications
You must be signed in to change notification settings - Fork 0
/
environs.go
2064 lines (1870 loc) · 60.5 KB
/
environs.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 dummy implements an environment provider for testing
// purposes, registered with environs under the name "dummy".
//
// The configuration YAML for the testing environment
// must specify a "controller" property with a boolean
// value. If this is true, a controller will be started
// when the environment is bootstrapped.
//
// The configuration data also accepts a "broken" property
// of type boolean. If this is non-empty, any operation
// after the environment has been opened will return
// the error "broken environment", and will also log that.
//
// The DNS name of instances is the same as the Id,
// with ".dns" appended.
package dummy
import (
stdcontext "context"
"crypto/tls"
"fmt"
"net"
"net/http/httptest"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/juju/clock"
"github.com/juju/errors"
"github.com/juju/jsonschema"
"github.com/juju/loggo"
"github.com/juju/names/v4"
"github.com/juju/pubsub/v2"
"github.com/juju/retry"
"github.com/juju/schema"
gitjujutesting "github.com/juju/testing"
jc "github.com/juju/testing/checkers"
"github.com/juju/utils/v2/arch"
"github.com/juju/version/v2"
"github.com/juju/worker/v2"
"github.com/prometheus/client_golang/prometheus"
gc "gopkg.in/check.v1"
"gopkg.in/juju/environschema.v1"
"github.com/juju/juju/agent"
"github.com/juju/juju/api"
"github.com/juju/juju/apiserver"
"github.com/juju/juju/apiserver/apiserverhttp"
"github.com/juju/juju/apiserver/observer"
"github.com/juju/juju/apiserver/stateauthenticator"
"github.com/juju/juju/cloud"
"github.com/juju/juju/cloudconfig/instancecfg"
corearch "github.com/juju/juju/core/arch"
"github.com/juju/juju/core/auditlog"
"github.com/juju/juju/core/cache"
"github.com/juju/juju/core/constraints"
"github.com/juju/juju/core/container"
"github.com/juju/juju/core/instance"
corelease "github.com/juju/juju/core/lease"
"github.com/juju/juju/core/lxdprofile"
"github.com/juju/juju/core/model"
"github.com/juju/juju/core/network"
"github.com/juju/juju/core/network/firewall"
"github.com/juju/juju/core/presence"
"github.com/juju/juju/core/status"
"github.com/juju/juju/environs"
environscloudspec "github.com/juju/juju/environs/cloudspec"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/environs/context"
"github.com/juju/juju/environs/instances"
"github.com/juju/juju/mongo"
"github.com/juju/juju/mongo/mongotest"
"github.com/juju/juju/pubsub/centralhub"
"github.com/juju/juju/state"
"github.com/juju/juju/state/stateenvirons"
"github.com/juju/juju/storage"
"github.com/juju/juju/testing"
coretools "github.com/juju/juju/tools"
jujuversion "github.com/juju/juju/version"
"github.com/juju/juju/worker/gate"
"github.com/juju/juju/worker/lease"
"github.com/juju/juju/worker/modelcache"
"github.com/juju/juju/worker/multiwatcher"
)
var logger = loggo.GetLogger("juju.provider.dummy")
var transientErrorInjection chan error
const BootstrapInstanceId = "localhost"
var errNotPrepared = errors.New("model is not prepared")
// SampleCloudSpec returns an environscloudspec.CloudSpec that can be used to
// open a dummy Environ.
func SampleCloudSpec() environscloudspec.CloudSpec {
cred := cloud.NewCredential(cloud.UserPassAuthType, map[string]string{"username": "dummy", "password": "secret"})
return environscloudspec.CloudSpec{
Type: "dummy",
Name: "dummy",
Endpoint: "dummy-endpoint",
IdentityEndpoint: "dummy-identity-endpoint",
Region: "dummy-region",
StorageEndpoint: "dummy-storage-endpoint",
Credential: &cred,
}
}
// SampleConfig returns an environment configuration with all required
// attributes set.
func SampleConfig() testing.Attrs {
return testing.Attrs{
"type": "dummy",
"name": "only",
"uuid": testing.ModelTag.Id(),
"authorized-keys": testing.FakeAuthKeys,
"firewall-mode": config.FwInstance,
"ssl-hostname-verification": true,
"development": false,
"default-series": jujuversion.DefaultSupportedLTS(),
"default-space": "",
"secret": "pork",
"controller": true,
}
}
// PatchTransientErrorInjectionChannel sets the transientInjectionError
// channel which can be used to inject errors into StartInstance for
// testing purposes
// The injected errors will use the string received on the channel
// and the instance's state will eventually go to error, while the
// received string will appear in the info field of the machine's status
func PatchTransientErrorInjectionChannel(c chan error) func() {
return gitjujutesting.PatchValue(&transientErrorInjection, c)
}
// mongoInfo returns a mongo.MongoInfo which allows clients to connect to the
// shared dummy state, if it exists.
func mongoInfo() mongo.MongoInfo {
if gitjujutesting.MgoServer.Addr() == "" {
panic("dummy environ state tests must be run with MgoTestPackage")
}
mongoPort := strconv.Itoa(gitjujutesting.MgoServer.Port())
addrs := []string{net.JoinHostPort("localhost", mongoPort)}
return mongo.MongoInfo{
Info: mongo.Info{
Addrs: addrs,
CACert: testing.CACert,
DisableTLS: !gitjujutesting.MgoServer.SSLEnabled(),
},
}
}
// Operation represents an action on the dummy provider.
type Operation interface{}
type OpBootstrap struct {
Context environs.BootstrapContext
Env string
Args environs.BootstrapParams
}
type OpFinalizeBootstrap struct {
Context environs.BootstrapContext
Env string
InstanceConfig *instancecfg.InstanceConfig
}
type OpDestroy struct {
Env string
Cloud string
CloudRegion string
Error error
}
type OpNetworkInterfaces struct {
Env string
InstanceId instance.Id
Info network.InterfaceInfos
}
type OpSubnets struct {
Env string
InstanceId instance.Id
SubnetIds []network.Id
Info []network.SubnetInfo
}
type OpStartInstance struct {
Env string
MachineId string
MachineNonce string
PossibleTools coretools.List
Instance instances.Instance
Constraints constraints.Value
SubnetsToZones map[network.Id][]string
NetworkInfo network.InterfaceInfos
RootDisk *storage.VolumeParams
Volumes []storage.Volume
VolumeAttachments []storage.VolumeAttachment
Jobs []model.MachineJob
APIInfo *api.Info
Secret string
AgentEnvironment map[string]string
}
type OpStopInstances struct {
Env string
Ids []instance.Id
}
type OpOpenPorts struct {
Env string
MachineId string
InstanceId instance.Id
Rules firewall.IngressRules
}
type OpClosePorts struct {
Env string
MachineId string
InstanceId instance.Id
Rules firewall.IngressRules
}
type OpPutFile struct {
Env string
FileName string
}
// environProvider represents the dummy provider. There is only ever one
// instance of this type (dummy)
type environProvider struct {
mu sync.Mutex
ops chan<- Operation
newStatePolicy state.NewPolicyFunc
supportsRulesWithIPV6CIDRs bool
supportsSpaces bool
supportsSpaceDiscovery bool
apiPort int
controllerState *environState
state map[string]*environState
}
// APIPort returns the random api port used by the given provider instance.
func APIPort(p environs.EnvironProvider) int {
return p.(*environProvider).apiPort
}
// environState represents the state of an environment.
// It can be shared between several environ values,
// so that a given environment can be opened several times.
type environState struct {
name string
ops chan<- Operation
newStatePolicy state.NewPolicyFunc
mu sync.Mutex
maxId int // maximum instance id allocated so far.
maxAddr int // maximum allocated address last byte
insts map[instance.Id]*dummyInstance
globalRules firewall.IngressRules
bootstrapped bool
mux *apiserverhttp.Mux
httpServer *httptest.Server
apiServer *apiserver.Server
apiState *state.State
apiStatePool *state.StatePool
hub *pubsub.StructuredHub
presence *fakePresence
leaseManager *lease.Manager
creator string
multiWatcherWorker worker.Worker
modelCacheWorker worker.Worker
controller *cache.Controller
}
// environ represents a client's connection to a given environment's
// state.
type environ struct {
storage.ProviderRegistry
name string
modelUUID string
cloud environscloudspec.CloudSpec
ecfgMutex sync.Mutex
ecfgUnlocked *environConfig
spacesMutex sync.RWMutex
}
var _ environs.Environ = (*environ)(nil)
var _ environs.Networking = (*environ)(nil)
// discardOperations discards all Operations written to it.
var discardOperations = make(chan Operation)
func init() {
environs.RegisterProvider("dummy", &dummy)
// Prime the first ops channel, so that naive clients can use
// the testing environment by simply importing it.
go func() {
for range discardOperations {
}
}()
}
// dummy is the dummy environmentProvider singleton.
var dummy = environProvider{
ops: discardOperations,
state: make(map[string]*environState),
newStatePolicy: stateenvirons.GetNewPolicyFunc(),
supportsSpaces: true,
supportsSpaceDiscovery: false,
supportsRulesWithIPV6CIDRs: true,
}
// Reset resets the entire dummy environment and forgets any registered
// operation listener. All opened environments after Reset will share
// the same underlying state.
func Reset(c *gc.C) {
logger.Infof("reset model")
dummy.mu.Lock()
dummy.ops = discardOperations
oldState := dummy.state
dummy.controllerState = nil
dummy.state = make(map[string]*environState)
dummy.newStatePolicy = stateenvirons.GetNewPolicyFunc()
dummy.supportsSpaces = true
dummy.supportsSpaceDiscovery = false
dummy.supportsRulesWithIPV6CIDRs = true
dummy.mu.Unlock()
// NOTE(axw) we must destroy the old states without holding
// the provider lock, or we risk deadlocking. Destroying
// state involves closing the embedded API server, which
// may require waiting on RPC calls that interact with the
// EnvironProvider (e.g. EnvironProvider.Open).
for _, s := range oldState {
if s.httpServer != nil {
logger.Debugf("closing httpServer")
s.httpServer.Close()
}
s.destroy()
}
if mongoAlive() {
err := retry.Call(retry.CallArgs{
Func: gitjujutesting.MgoServer.Reset,
// Only interested in retrying the intermittent
// 'unexpected message'.
IsFatalError: func(err error) bool {
return !strings.HasSuffix(err.Error(), "unexpected message")
},
Delay: time.Millisecond,
Clock: clock.WallClock,
Attempts: 5,
NotifyFunc: func(lastError error, attempt int) {
logger.Infof("retrying MgoServer.Reset() after attempt %d: %v", attempt, lastError)
},
})
c.Assert(err, jc.ErrorIsNil)
}
}
func (s *environState) destroy() {
s.mu.Lock()
defer s.mu.Unlock()
s.destroyLocked()
}
func (s *environState) destroyLocked() {
if !s.bootstrapped {
return
}
apiServer := s.apiServer
apiStatePool := s.apiStatePool
leaseManager := s.leaseManager
multiWatcherWorker := s.multiWatcherWorker
modelCacheWorker := s.modelCacheWorker
s.apiServer = nil
s.apiStatePool = nil
s.apiState = nil
s.controller = nil
s.leaseManager = nil
s.bootstrapped = false
s.hub = nil
s.multiWatcherWorker = nil
s.modelCacheWorker = nil
// Release the lock while we close resources. In particular,
// we must not hold the lock while the API server is being
// closed, as it may need to interact with the Environ while
// shutting down.
s.mu.Unlock()
defer s.mu.Lock()
// The apiServer depends on the modelCache, so stop the apiserver first.
if apiServer != nil {
logger.Debugf("stopping apiServer")
if err := apiServer.Stop(); err != nil && mongoAlive() {
panic(err)
}
}
if modelCacheWorker != nil {
logger.Debugf("stopping modelCache worker")
if err := worker.Stop(modelCacheWorker); err != nil {
panic(err)
}
}
if multiWatcherWorker != nil {
logger.Debugf("stopping multiWatcherWorker worker")
if err := worker.Stop(multiWatcherWorker); err != nil {
panic(err)
}
}
if leaseManager != nil {
if err := worker.Stop(leaseManager); err != nil && mongoAlive() {
panic(err)
}
}
if apiStatePool != nil {
logger.Debugf("closing apiStatePool")
if err := apiStatePool.Close(); err != nil && mongoAlive() {
panic(err)
}
}
if mongoAlive() {
logger.Debugf("resetting MgoServer")
_ = gitjujutesting.MgoServer.Reset()
}
}
// mongoAlive reports whether the mongo server is
// still alive (i.e. has not been deliberately destroyed).
// If it has been deliberately destroyed, we will
// expect some errors when closing things down.
func mongoAlive() bool {
return gitjujutesting.MgoServer.Addr() != ""
}
// GetStateInAPIServer returns the state connection used by the API server
// This is so code in the test suite can trigger Syncs, etc that the API server
// will see, which will then trigger API watchers, etc.
func (e *environ) GetStateInAPIServer() *state.State {
st, err := e.state()
if err != nil {
panic(err)
}
return st.apiState
}
// GetStatePoolInAPIServer returns the StatePool used by the API
// server. As for GetStatePoolInAPIServer, this is so code in the
// test suite can trigger Syncs etc.
func (e *environ) GetStatePoolInAPIServer() *state.StatePool {
st, err := e.state()
if err != nil {
panic(err)
}
return st.apiStatePool
}
// GetHubInAPIServer returns the central hub used by the API server.
func (e *environ) GetHubInAPIServer() *pubsub.StructuredHub {
st, err := e.state()
if err != nil {
panic(err)
}
return st.hub
}
// GetLeaseManagerInAPIServer returns the channel used to update the
// cache.Controller used by the API server
func (e *environ) GetLeaseManagerInAPIServer() corelease.Manager {
st, err := e.state()
if err != nil {
panic(err)
}
return st.leaseManager
}
// GetController returns the cache.Controller used by the API server.
func (e *environ) GetController() *cache.Controller {
st, err := e.state()
if err != nil {
panic(err)
}
return st.controller
}
// newState creates the state for a new environment with the given name.
func newState(name string, ops chan<- Operation, newStatePolicy state.NewPolicyFunc) *environState {
buf := make([]byte, 8192)
buf = buf[:runtime.Stack(buf, false)]
s := &environState{
name: name,
ops: ops,
newStatePolicy: newStatePolicy,
insts: make(map[instance.Id]*dummyInstance),
creator: string(buf),
}
return s
}
// listenAPI starts an HTTP server listening for API connections.
func (s *environState) listenAPI() int {
certPool, err := api.CreateCertPool(testing.CACert)
if err != nil {
panic(err)
}
tlsConfig := api.NewTLSConfig(certPool)
tlsConfig.ServerName = "juju-apiserver"
tlsConfig.Certificates = []tls.Certificate{*testing.ServerTLSCert}
s.mux = apiserverhttp.NewMux()
s.httpServer = httptest.NewUnstartedServer(s.mux)
s.httpServer.TLS = tlsConfig
return s.httpServer.Listener.Addr().(*net.TCPAddr).Port
}
// SetSupportsSpaces allows to enable and disable SupportsSpaces for tests.
func SetSupportsSpaces(supports bool) bool {
dummy.mu.Lock()
defer dummy.mu.Unlock()
current := dummy.supportsSpaces
dummy.supportsSpaces = supports
return current
}
// SetSupportsRulesWithIPV6CIDRs allows to toggle support for IPV6 CIDRs in firewall rules.
func SetSupportsRulesWithIPV6CIDRs(supports bool) bool {
dummy.mu.Lock()
defer dummy.mu.Unlock()
current := dummy.supportsRulesWithIPV6CIDRs
dummy.supportsRulesWithIPV6CIDRs = supports
return current
}
// SetSupportsSpaceDiscovery allows to enable and disable
// SupportsSpaceDiscovery for tests.
func SetSupportsSpaceDiscovery(supports bool) bool {
dummy.mu.Lock()
defer dummy.mu.Unlock()
current := dummy.supportsSpaceDiscovery
dummy.supportsSpaceDiscovery = supports
return current
}
// Listen directs subsequent operations on any dummy environment
// to channel c (if not nil).
func Listen(c chan<- Operation) {
dummy.mu.Lock()
defer dummy.mu.Unlock()
if c == nil {
c = discardOperations
}
dummy.ops = c
for _, st := range dummy.state {
st.mu.Lock()
st.ops = c
st.mu.Unlock()
}
}
var configSchema = environschema.Fields{
"controller": {
Description: "Whether the model should start a controller",
Type: environschema.Tbool,
},
"broken": {
Description: "Whitespace-separated Environ methods that should return an error when called",
Type: environschema.Tstring,
},
"secret": {
Description: "A secret",
Type: environschema.Tstring,
},
}
var configFields = func() schema.Fields {
fs, _, err := configSchema.ValidationSchema()
if err != nil {
panic(err)
}
return fs
}()
var configDefaults = schema.Defaults{
"broken": "",
"secret": "pork",
"controller": false,
}
type environConfig struct {
*config.Config
attrs map[string]interface{}
}
func (c *environConfig) controller() bool {
return c.attrs["controller"].(bool)
}
func (c *environConfig) broken() string {
return c.attrs["broken"].(string)
}
func (c *environConfig) secret() string {
return c.attrs["secret"].(string)
}
func (p *environProvider) newConfig(cfg *config.Config) (*environConfig, error) {
valid, err := p.Validate(cfg, nil)
if err != nil {
return nil, err
}
return &environConfig{valid, valid.UnknownAttrs()}, nil
}
func (p *environProvider) Schema() environschema.Fields {
fields, err := config.Schema(configSchema)
if err != nil {
panic(err)
}
return fields
}
var _ config.ConfigSchemaSource = (*environProvider)(nil)
// ConfigSchema returns extra config attributes specific
// to this provider only.
func (p *environProvider) ConfigSchema() schema.Fields {
return configFields
}
// ConfigDefaults returns the default values for the
// provider specific config attributes.
func (p *environProvider) ConfigDefaults() schema.Defaults {
return configDefaults
}
func (*environProvider) CredentialSchemas() map[cloud.AuthType]cloud.CredentialSchema {
return map[cloud.AuthType]cloud.CredentialSchema{
cloud.EmptyAuthType: {},
cloud.UserPassAuthType: {
{
"username", cloud.CredentialAttr{Description: "The username to authenticate with."},
}, {
"password", cloud.CredentialAttr{
Description: "The password for the specified username.",
Hidden: true,
},
},
},
}
}
func (*environProvider) DetectCredentials(cloudName string) (*cloud.CloudCredential, error) {
return cloud.NewEmptyCloudCredential(), nil
}
func (*environProvider) FinalizeCredential(_ environs.FinalizeCredentialContext, args environs.FinalizeCredentialParams) (*cloud.Credential, error) {
return &args.Credential, nil
}
func (*environProvider) DetectRegions() ([]cloud.Region, error) {
return []cloud.Region{{Name: "dummy"}}, nil
}
func (p *environProvider) Validate(cfg, old *config.Config) (valid *config.Config, err error) {
// Check for valid changes for the base config values.
if err := config.Validate(cfg, old); err != nil {
return nil, err
}
validated, err := cfg.ValidateUnknownAttrs(configFields, configDefaults)
if err != nil {
return nil, err
}
// Apply the coerced unknown values back into the config.
return cfg.Apply(validated)
}
func (e *environ) state() (*environState, error) {
dummy.mu.Lock()
defer dummy.mu.Unlock()
state, ok := dummy.state[e.modelUUID]
if !ok {
return nil, errNotPrepared
}
return state, nil
}
// Version is part of the EnvironProvider interface.
func (*environProvider) Version() int {
return 0
}
func (p *environProvider) Open(_ stdcontext.Context, args environs.OpenParams) (environs.Environ, error) {
p.mu.Lock()
defer p.mu.Unlock()
ecfg, err := p.newConfig(args.Config)
if err != nil {
return nil, err
}
env := &environ{
ProviderRegistry: StorageProviders(),
name: ecfg.Name(),
modelUUID: args.Config.UUID(),
cloud: args.Cloud,
ecfgUnlocked: ecfg,
}
if err := env.checkBroken("Open"); err != nil {
return nil, err
}
return env, nil
}
// CloudSchema returns the schema used to validate input for add-cloud. Since
// this provider does not support custom clouds, this always returns nil.
func (p *environProvider) CloudSchema() *jsonschema.Schema {
return nil
}
// Ping tests the connection to the cloud, to verify the endpoint is valid.
func (p *environProvider) Ping(ctx context.ProviderCallContext, endpoint string) error {
return errors.NotImplementedf("Ping")
}
// PrepareConfig is specified in the EnvironProvider interface.
func (p *environProvider) PrepareConfig(args environs.PrepareConfigParams) (*config.Config, error) {
if _, err := dummy.newConfig(args.Config); err != nil {
return nil, err
}
return args.Config, nil
}
// Override for testing - the data directory with which the state api server is initialised.
var DataDir = ""
var LogDir = ""
func (e *environ) ecfg() *environConfig {
e.ecfgMutex.Lock()
ecfg := e.ecfgUnlocked
e.ecfgMutex.Unlock()
return ecfg
}
func (e *environ) checkBroken(method string) error {
for _, m := range strings.Fields(e.ecfg().broken()) {
if m == method {
return fmt.Errorf("dummy.%s is broken", method)
}
}
return nil
}
// PrecheckInstance is specified in the environs.InstancePrechecker interface.
func (*environ) PrecheckInstance(ctx context.ProviderCallContext, args environs.PrecheckInstanceParams) error {
if args.Placement != "" && args.Placement != "valid" {
return fmt.Errorf("%s placement is invalid", args.Placement)
}
return nil
}
// Create is part of the Environ interface.
func (e *environ) Create(ctx context.ProviderCallContext, args environs.CreateParams) error {
dummy.mu.Lock()
defer dummy.mu.Unlock()
dummy.state[e.modelUUID] = newState(e.name, dummy.ops, dummy.newStatePolicy)
return nil
}
// PrepareForBootstrap is part of the Environ interface.
func (e *environ) PrepareForBootstrap(ctx environs.BootstrapContext, controllerName string) error {
dummy.mu.Lock()
defer dummy.mu.Unlock()
ecfg := e.ecfgUnlocked
if ecfg.controller() && dummy.controllerState != nil {
// Because of global variables, we can only have one dummy
// controller per process. Panic if there is an attempt to
// bootstrap while there is another active controller.
old := dummy.controllerState
panic(fmt.Errorf("cannot share a state between two dummy environs; old %q; new %q: %s", old.name, e.name, old.creator))
}
// The environment has not been prepared, so create it and record it.
// We don't start listening for State or API connections until
// Bootstrap has been called.
envState := newState(e.name, dummy.ops, dummy.newStatePolicy)
if ecfg.controller() {
dummy.apiPort = envState.listenAPI()
dummy.controllerState = envState
}
dummy.state[e.modelUUID] = envState
return nil
}
func (e *environ) Bootstrap(ctx environs.BootstrapContext, callCtx context.ProviderCallContext, args environs.BootstrapParams) (*environs.BootstrapResult, error) {
availableTools, err := args.AvailableTools.Match(coretools.Filter{OSType: "ubuntu"})
if err != nil {
return nil, err
}
arch := availableTools.Arches()[0]
defer delay()
if err := e.checkBroken("Bootstrap"); err != nil {
return nil, err
}
if _, ok := args.ControllerConfig.CACert(); !ok {
return nil, errors.New("no CA certificate in controller configuration")
}
logger.Infof("would pick agent binaries from %s", availableTools)
estate, err := e.state()
if err != nil {
return nil, err
}
estate.mu.Lock()
defer estate.mu.Unlock()
if estate.bootstrapped {
return nil, errors.New("model is already bootstrapped")
}
// Create an instance for the bootstrap node.
logger.Infof("creating bootstrap instance")
series := config.PreferredSeries(e.Config())
i := &dummyInstance{
id: BootstrapInstanceId,
addresses: network.NewProviderAddresses("localhost"),
machineId: agent.BootstrapControllerId,
series: series,
firewallMode: e.Config().FirewallMode(),
state: estate,
controller: true,
}
estate.insts[i.id] = i
estate.bootstrapped = true
estate.ops <- OpBootstrap{Context: ctx, Env: e.name, Args: args}
finalize := func(ctx environs.BootstrapContext, icfg *instancecfg.InstanceConfig, _ environs.BootstrapDialOpts) (err error) {
if e.ecfg().controller() {
icfg.Bootstrap.BootstrapMachineInstanceId = BootstrapInstanceId
if err := instancecfg.FinishInstanceConfig(icfg, e.Config()); err != nil {
return err
}
adminUser := names.NewUserTag("admin@local")
var cloudCredentialTag names.CloudCredentialTag
if icfg.Bootstrap.ControllerCloudCredentialName != "" {
id := fmt.Sprintf(
"%s/%s/%s",
icfg.Bootstrap.ControllerCloud.Name,
adminUser.Id(),
icfg.Bootstrap.ControllerCloudCredentialName,
)
if !names.IsValidCloudCredential(id) {
return errors.NotValidf("cloud credential ID %q", id)
}
cloudCredentialTag = names.NewCloudCredentialTag(id)
}
cloudCredentials := make(map[names.CloudCredentialTag]cloud.Credential)
if icfg.Bootstrap.ControllerCloudCredential != nil && icfg.Bootstrap.ControllerCloudCredentialName != "" {
cloudCredentials[cloudCredentialTag] = *icfg.Bootstrap.ControllerCloudCredential
}
session, err := mongo.DialWithInfo(mongoInfo(), mongotest.DialOpts())
if err != nil {
return err
}
defer session.Close()
// Since the admin user isn't setup until after here,
// the password in the info structure is empty, so the admin
// user is constructed with an empty password here.
// It is set just below.
controller, err := state.Initialize(state.InitializeParams{
Clock: clock.WallClock,
ControllerConfig: icfg.Controller.Config,
ControllerModelArgs: state.ModelArgs{
Type: state.ModelTypeIAAS,
Owner: adminUser,
Config: icfg.Bootstrap.ControllerModelConfig,
Constraints: icfg.Bootstrap.BootstrapMachineConstraints,
CloudName: icfg.Bootstrap.ControllerCloud.Name,
CloudRegion: icfg.Bootstrap.ControllerCloudRegion,
CloudCredential: cloudCredentialTag,
StorageProviderRegistry: e,
},
Cloud: icfg.Bootstrap.ControllerCloud,
CloudCredentials: cloudCredentials,
MongoSession: session,
NewPolicy: estate.newStatePolicy,
AdminPassword: icfg.APIInfo.Password,
})
if err != nil {
return err
}
st := controller.SystemState()
defer func() {
if err != nil {
controller.Close()
}
}()
if err := st.SetModelConstraints(args.ModelConstraints); err != nil {
return errors.Trace(err)
}
if err := st.SetAdminMongoPassword(icfg.APIInfo.Password); err != nil {
return errors.Trace(err)
}
if err := st.MongoSession().DB("admin").Login("admin", icfg.APIInfo.Password); err != nil {
return err
}
env, err := st.Model()
if err != nil {
return errors.Trace(err)
}
owner, err := st.User(env.Owner())
if err != nil {
return errors.Trace(err)
}
// We log this out for test purposes only. No one in real life can use
// a dummy provider for anything other than testing, so logging the password
// here is fine.
logger.Debugf("setting password for %q to %q", owner.Name(), icfg.APIInfo.Password)
_ = owner.SetPassword(icfg.APIInfo.Password)
statePool := controller.StatePool()
stateAuthenticator, err := stateauthenticator.NewAuthenticator(statePool, clock.WallClock)
if err != nil {
return errors.Trace(err)
}
stateAuthenticator.AddHandlers(estate.mux)
machineTag := names.NewMachineTag("0")
estate.httpServer.StartTLS()
estate.presence = &fakePresence{make(map[string]presence.Status)}
estate.hub = centralhub.New(machineTag, centralhub.PubsubNoOpMetrics{})
estate.leaseManager, err = leaseManager(
icfg.Controller.Config.ControllerUUID(),
st,
)
if err != nil {
return errors.Trace(err)
}
multiWatcherWorker, err := multiwatcher.NewWorker(multiwatcher.Config{
Clock: clock.WallClock,
Logger: loggo.GetLogger("dummy.multiwatcher"),
Backing: state.NewAllWatcherBacking(statePool),
PrometheusRegisterer: noopRegisterer{},
})
if err != nil {
return errors.Trace(err)
}
estate.multiWatcherWorker = multiWatcherWorker
initialized := gate.NewLock()
modelCache, err := modelcache.NewWorker(modelcache.Config{
StatePool: statePool,
Hub: estate.hub,
InitializedGate: initialized,
Logger: loggo.GetLogger("dummy.modelcache"),
WatcherFactory: multiWatcherWorker.WatchController,
PrometheusRegisterer: noopRegisterer{},
Cleanup: func() {},
}.WithDefaultRestartStrategy())
if err != nil {
return errors.Trace(err)
}
select {
case <-initialized.Unlocked():
case <-time.After(10 * time.Second):
return errors.New("model cache not initialized after 10 seconds")
}
estate.modelCacheWorker = modelCache
err = modelcache.ExtractCacheController(modelCache, &estate.controller)
if err != nil {
_ = worker.Stop(modelCache)
_ = worker.Stop(multiWatcherWorker)
return errors.Trace(err)
}
estate.apiServer, err = apiserver.NewServer(apiserver.ServerConfig{
StatePool: statePool,
Controller: estate.controller,
MultiwatcherFactory: multiWatcherWorker,
Authenticator: stateAuthenticator,
Clock: clock.WallClock,