forked from juju/juju
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloud.go
282 lines (255 loc) · 8.74 KB
/
cloud.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
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"fmt"
"github.com/juju/collections/set"
"github.com/juju/errors"
jujutxn "github.com/juju/txn"
"gopkg.in/juju/names.v2"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"gopkg.in/mgo.v2/txn"
"github.com/juju/juju/cloud"
"github.com/juju/juju/mongo/utils"
"github.com/juju/juju/permission"
)
// cloudGlobalKey will return the key for a given cloud.
func cloudGlobalKey(cloudName string) string {
return fmt.Sprintf("cloud#%s", cloudName)
}
// cloudDoc records information about the cloud that the controller operates in.
type cloudDoc struct {
DocID string `bson:"_id"`
Name string `bson:"name"`
Type string `bson:"type"`
AuthTypes []string `bson:"auth-types"`
Endpoint string `bson:"endpoint"`
IdentityEndpoint string `bson:"identity-endpoint,omitempty"`
StorageEndpoint string `bson:"storage-endpoint,omitempty"`
Regions map[string]cloudRegionSubdoc `bson:"regions,omitempty"`
CACertificates []string `bson:"ca-certificates,omitempty"`
}
// cloudRegionSubdoc records information about cloud regions.
type cloudRegionSubdoc struct {
Endpoint string `bson:"endpoint,omitempty"`
IdentityEndpoint string `bson:"identity-endpoint,omitempty"`
StorageEndpoint string `bson:"storage-endpoint,omitempty"`
}
// createCloudOp returns a txn.Op that will initialize
// the cloud definition for the controller.
func createCloudOp(cloud cloud.Cloud) txn.Op {
authTypes := make([]string, len(cloud.AuthTypes))
for i, authType := range cloud.AuthTypes {
authTypes[i] = string(authType)
}
regions := make(map[string]cloudRegionSubdoc)
for _, region := range cloud.Regions {
regions[utils.EscapeKey(region.Name)] = cloudRegionSubdoc{
region.Endpoint,
region.IdentityEndpoint,
region.StorageEndpoint,
}
}
return txn.Op{
C: cloudsC,
Id: cloud.Name,
Assert: txn.DocMissing,
Insert: &cloudDoc{
Name: cloud.Name,
Type: cloud.Type,
AuthTypes: authTypes,
Endpoint: cloud.Endpoint,
IdentityEndpoint: cloud.IdentityEndpoint,
StorageEndpoint: cloud.StorageEndpoint,
Regions: regions,
CACertificates: cloud.CACertificates,
},
}
}
// cloudModelRefCountKey returns a key for refcounting models
// for the specified cloud. Each time a model for the cloud is created,
// the refcount is incremented, and the opposite happens on removal.
func cloudModelRefCountKey(cloudName string) string {
return fmt.Sprintf("cloudModel#%s", cloudName)
}
// incApplicationOffersRefOp returns a txn.Op that increments the reference
// count for a cloud model.
func incCloudModelRefOp(mb modelBackend, cloudName string) (txn.Op, error) {
refcounts, closer := mb.db().GetCollection(globalRefcountsC)
defer closer()
cloudModelRefCountKey := cloudModelRefCountKey(cloudName)
incRefOp, err := nsRefcounts.CreateOrIncRefOp(refcounts, cloudModelRefCountKey, 1)
return incRefOp, errors.Trace(err)
}
// countCloudModelRefOp returns the number of models for a cloud,
// along with a txn.Op that ensures that that does not change.
func countCloudModelRefOp(mb modelBackend, cloudName string) (txn.Op, int, error) {
refcounts, closer := mb.db().GetCollection(globalRefcountsC)
defer closer()
key := cloudModelRefCountKey(cloudName)
return nsRefcounts.CurrentOp(refcounts, key)
}
// decCloudModelRefOp returns a txn.Op that decrements the reference
// count for a cloud model.
func decCloudModelRefOp(mb modelBackend, cloudName string) (txn.Op, error) {
refcounts, closer := mb.db().GetCollection(globalRefcountsC)
defer closer()
cloudModelRefCountKey := cloudModelRefCountKey(cloudName)
decRefOp, _, err := nsRefcounts.DyingDecRefOp(refcounts, cloudModelRefCountKey)
if err != nil {
return txn.Op{}, errors.Trace(err)
}
return decRefOp, nil
}
func (d cloudDoc) toCloud() cloud.Cloud {
authTypes := make([]cloud.AuthType, len(d.AuthTypes))
for i, authType := range d.AuthTypes {
authTypes[i] = cloud.AuthType(authType)
}
regionNames := make(set.Strings)
for name := range d.Regions {
regionNames.Add(name)
}
regions := make([]cloud.Region, len(d.Regions))
for i, name := range regionNames.SortedValues() {
region := d.Regions[name]
regions[i] = cloud.Region{
utils.UnescapeKey(name),
region.Endpoint,
region.IdentityEndpoint,
region.StorageEndpoint,
}
}
return cloud.Cloud{
Name: d.Name,
Type: d.Type,
AuthTypes: authTypes,
Endpoint: d.Endpoint,
IdentityEndpoint: d.IdentityEndpoint,
StorageEndpoint: d.StorageEndpoint,
Regions: regions,
CACertificates: d.CACertificates,
}
}
// Clouds returns the definitions for all clouds in the controller.
func (st *State) Clouds() (map[names.CloudTag]cloud.Cloud, error) {
coll, cleanup := st.db().GetCollection(cloudsC)
defer cleanup()
var doc cloudDoc
clouds := make(map[names.CloudTag]cloud.Cloud)
iter := coll.Find(nil).Iter()
for iter.Next(&doc) {
clouds[names.NewCloudTag(doc.Name)] = doc.toCloud()
}
if err := iter.Close(); err != nil {
return nil, errors.Annotate(err, "getting clouds")
}
return clouds, nil
}
// Cloud returns the controller's cloud definition.
func (st *State) Cloud(name string) (cloud.Cloud, error) {
coll, cleanup := st.db().GetCollection(cloudsC)
defer cleanup()
var doc cloudDoc
err := coll.FindId(name).One(&doc)
if err == mgo.ErrNotFound {
return cloud.Cloud{}, errors.NotFoundf("cloud %q", name)
}
if err != nil {
return cloud.Cloud{}, errors.Annotatef(err, "cannot get cloud %q", name)
}
return doc.toCloud(), nil
}
// AddCloud creates a cloud with the given name and details.
// Note that the Config is deliberately ignored - it's only
// relevant when bootstrapping.
func (st *State) AddCloud(c cloud.Cloud, owner string) error {
if err := validateCloud(c); err != nil {
return errors.Annotate(err, "invalid cloud")
}
ops := []txn.Op{createCloudOp(c)}
if err := st.db().RunTransaction(ops); err != nil {
if err == txn.ErrAborted {
err = errors.AlreadyExistsf("cloud %q", c.Name)
}
return err
}
// Ensure the owner has access to the cloud.
ownerTag := names.NewUserTag(owner)
err := st.CreateCloudAccess(c.Name, ownerTag, permission.AdminAccess)
if err != nil {
return errors.Annotatef(err, "granting %s permission to the cloud owner", permission.AdminAccess)
}
return nil
}
// validateCloud checks that the supplied cloud is valid.
func validateCloud(cloud cloud.Cloud) error {
if cloud.Name == "" {
return errors.NotValidf("empty Name")
}
if cloud.Type == "" {
return errors.NotValidf("empty Type")
}
if len(cloud.AuthTypes) == 0 {
return errors.NotValidf("empty auth-types")
}
// TODO(axw) we should ensure that the cloud auth-types is a subset
// of the auth-types supported by the provider. To do that, we'll
// need a new "policy".
return nil
}
// regionSettingsGlobalKey concatenates the cloud a hash and the region string.
func regionSettingsGlobalKey(cloud, region string) string {
return cloud + "#" + region
}
// RemoveCloud removes a cloud and any credentials for that cloud.
// If the cloud is in use, ie has models deployed to it, the operation fails.
func (st *State) RemoveCloud(name string) error {
buildTxn := func(attempt int) ([]txn.Op, error) {
if _, err := st.Cloud(name); err != nil {
// Fail with not found error on first attempt if cloud doesn't exist.
// On subsequent attempts, if cloud not found then
// it was deleted by someone else and that's a no-op.
if attempt > 1 && errors.IsNotFound(err) {
return nil, jujutxn.ErrNoOperations
}
return nil, errors.Trace(err)
}
return st.removeCloudOps(name)
}
return st.db().Run(buildTxn)
}
// removeCloudOp returns a list of txn.Ops that will remove
// the specified cloud and any associated credentials.
func (st *State) removeCloudOps(name string) ([]txn.Op, error) {
countOp, n, err := countCloudModelRefOp(st, name)
if err != nil {
return nil, errors.Trace(err)
}
if n != 0 {
return nil, errors.Errorf("cloud is used by %d model%s", n, plural(n))
}
ops := []txn.Op{{
C: cloudsC,
Id: name,
Remove: true,
}, countOp}
credPattern := bson.M{
"_id": bson.M{"$regex": "^" + name + "#"},
}
credOps, err := st.removeInCollectionOps(cloudCredentialsC, credPattern)
if err != nil {
return nil, errors.Trace(err)
}
ops = append(ops, credOps...)
permPattern := bson.M{
"_id": bson.M{"$regex": "^" + cloudGlobalKey(name) + "#"},
}
permOps, err := st.removeInCollectionOps(permissionsC, permPattern)
if err != nil {
return nil, errors.Trace(err)
}
ops = append(ops, permOps...)
return ops, nil
}