-
Notifications
You must be signed in to change notification settings - Fork 494
/
base.go
416 lines (382 loc) · 12.8 KB
/
base.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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package applicationoffers
import (
"fmt"
"sort"
"github.com/juju/errors"
"github.com/juju/utils/set"
"gopkg.in/juju/names.v2"
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/apiserver/facade"
"github.com/juju/juju/apiserver/params"
jujucrossmodel "github.com/juju/juju/core/crossmodel"
"github.com/juju/juju/environs"
"github.com/juju/juju/permission"
)
// BaseAPI provides various boilerplate methods used by the facade business logic.
type BaseAPI struct {
Authorizer facade.Authorizer
GetApplicationOffers func(interface{}) jujucrossmodel.ApplicationOffers
ControllerModel Backend
StatePool StatePool
getEnviron environFromModelFunc
}
// checkPermission ensures that the logged in user holds the given permission on an entity.
func (api *BaseAPI) checkPermission(tag names.Tag, perm permission.Access) error {
allowed, err := api.Authorizer.HasPermission(perm, tag)
if err != nil {
return errors.Trace(err)
}
if !allowed {
return common.ErrPerm
}
return nil
}
// checkAdmin ensures that the logged in user is a model or controller admin.
func (api *BaseAPI) checkAdmin(backend Backend) error {
allowed, err := api.Authorizer.HasPermission(permission.AdminAccess, backend.ModelTag())
if err != nil {
return errors.Trace(err)
}
if !allowed {
allowed, err = api.Authorizer.HasPermission(permission.SuperuserAccess, backend.ControllerTag())
}
if err != nil {
return errors.Trace(err)
}
if !allowed {
return common.ErrPerm
}
return nil
}
// modelForName looks up the model details for the named model.
func (api *BaseAPI) modelForName(modelName, ownerName string) (Model, bool, error) {
user := api.Authorizer.GetAuthTag()
if ownerName == "" {
ownerName = user.Id()
}
var model Model
models, err := api.ControllerModel.AllModels()
if err != nil {
return nil, false, err
}
for _, m := range models {
if m.Name() == modelName && m.Owner().Id() == ownerName {
model = m
break
}
}
return model, model != nil, nil
}
// applicationOffersFromModel gets details about remote applications that match given filters.
func (api *BaseAPI) applicationOffersFromModel(
modelUUID string,
requiredAccess permission.Access,
filters ...jujucrossmodel.ApplicationOfferFilter,
) ([]params.ApplicationOfferDetails, error) {
// Get the relevant backend for the specified model.
backend, releaser, err := api.StatePool.Get(modelUUID)
if err != nil {
return nil, errors.Trace(err)
}
defer releaser()
// If requireAdmin is true, the user must be a controller superuser
// or model admin to proceed.
isAdmin := false
err = api.checkAdmin(backend)
if err != nil && err != common.ErrPerm {
return nil, errors.Trace(err)
}
isAdmin = err == nil
if requiredAccess == permission.AdminAccess && !isAdmin {
return nil, common.ErrPerm
}
offers, err := api.GetApplicationOffers(backend).ListOffers(filters...)
if err != nil {
return nil, errors.Trace(err)
}
var results []params.ApplicationOfferDetails
for _, appOffer := range offers {
userAccess := permission.AdminAccess
// If the user is not a model admin, they need at least read
// access on an offer to see it.
if !isAdmin {
if userAccess, err = api.checkOfferAccess(backend, appOffer.OfferName, requiredAccess); err != nil {
return nil, errors.Trace(err)
}
if userAccess == permission.NoAccess {
continue
}
isAdmin = userAccess == permission.AdminAccess
}
offerParams, app, err := api.makeOfferParams(backend, &appOffer, userAccess)
// Just because we can't compose the result for one offer, log
// that and move on to the next one.
if err != nil {
logger.Warningf("cannot get application offer: %v", err)
continue
}
offer := params.ApplicationOfferDetails{
ApplicationOffer: *offerParams,
}
// Only admins can see some sensitive details of the offer.
if isAdmin {
curl, _ := app.CharmURL()
status, err := backend.RemoteConnectionStatus(offer.OfferName)
if err != nil {
logger.Warningf("cannot get offer connection status: %v", err)
continue
}
offer.ApplicationName = app.Name()
offer.CharmName = curl.Name
offer.ConnectedCount = status.ConnectionCount()
}
results = append(results, offer)
}
return results, nil
}
// checkOfferAccess returns the level of access the authenticated user has to the offer,
// so long as it is greater than the requested perm.
func (api *BaseAPI) checkOfferAccess(backend Backend, offerName string, perm permission.Access) (permission.Access, error) {
apiUser := api.Authorizer.GetAuthTag().(names.UserTag)
access, err := backend.GetOfferAccess(names.NewApplicationOfferTag(offerName), apiUser)
if err != nil && !errors.IsNotFound(err) {
return permission.NoAccess, errors.Trace(err)
}
if !access.EqualOrGreaterOfferAccessThan(permission.ReadAccess) {
return permission.NoAccess, nil
}
return access, nil
}
type offerModel struct {
model Model
err error
}
// getModelsFromOffers returns a slice of models corresponding to the
// specified offer URLs. Each result item has either a model or an error.
func (api *BaseAPI) getModelsFromOffers(offerURLs ...string) ([]offerModel, error) {
// Cache the models found so far so we don't look them up more than once.
modelsCache := make(map[string]Model)
oneModel := func(offerURL string) (Model, error) {
url, err := jujucrossmodel.ParseApplicationURL(offerURL)
if err != nil {
return nil, errors.Trace(err)
}
modelPath := fmt.Sprintf("%s/%s", url.User, url.ModelName)
if model, ok := modelsCache[modelPath]; ok {
return model, nil
}
model, ok, err := api.modelForName(url.ModelName, url.User)
if err != nil {
return nil, errors.Trace(err)
}
if !ok {
return nil, errors.NotFoundf("model %q", modelPath)
}
return model, nil
}
result := make([]offerModel, len(offerURLs))
for i, offerURL := range offerURLs {
var om offerModel
om.model, om.err = oneModel(offerURL)
result[i] = om
}
return result, nil
}
// getModelFilters splits the specified filters per model and returns
// the model and filter details for each.
func (api *BaseAPI) getModelFilters(filters params.OfferFilters) (
models map[string]Model,
filtersPerModel map[string][]jujucrossmodel.ApplicationOfferFilter,
_ error,
) {
models = make(map[string]Model)
filtersPerModel = make(map[string][]jujucrossmodel.ApplicationOfferFilter)
// Group the filters per model and then query each model with the relevant filters
// for that model.
modelUUIDs := make(map[string]string)
for _, f := range filters.Filters {
if f.ModelName == "" {
return nil, nil, errors.New("application offer filter must specify a model name")
}
var (
modelUUID string
ok bool
)
if modelUUID, ok = modelUUIDs[f.ModelName]; !ok {
var err error
model, ok, err := api.modelForName(f.ModelName, f.OwnerName)
if err != nil {
return nil, nil, errors.Trace(err)
}
if !ok {
err := errors.NotFoundf("model %q", f.ModelName)
return nil, nil, errors.Trace(err)
}
// Record the UUID and model for next time.
modelUUID = model.UUID()
modelUUIDs[f.ModelName] = modelUUID
models[modelUUID] = model
}
// Record the filter and model details against the model UUID.
filters := filtersPerModel[modelUUID]
filters = append(filters, makeOfferFilterFromParams(f))
filtersPerModel[modelUUID] = filters
}
return models, filtersPerModel, nil
}
// getApplicationOffersDetails gets details about remote applications that match given filter.
func (api *BaseAPI) getApplicationOffersDetails(
filters params.OfferFilters,
requiredPermission permission.Access,
) ([]params.ApplicationOfferDetails, error) {
// If there are no filters specified, that's an error since the
// caller is expected to specify at the least one or more models
// to avoid an unbounded query across all models.
if len(filters.Filters) == 0 {
return nil, errors.New("at least one offer filter is required")
}
// Gather all the filter details for doing a query for each model.
models, filtersPerModel, err := api.getModelFilters(filters)
if err != nil {
return nil, errors.Trace(err)
}
// Ensure the result is deterministic.
var allUUIDs []string
for modelUUID := range filtersPerModel {
allUUIDs = append(allUUIDs, modelUUID)
}
sort.Strings(allUUIDs)
// Do the per model queries.
var result []params.ApplicationOfferDetails
for _, modelUUID := range allUUIDs {
filters := filtersPerModel[modelUUID]
offers, err := api.applicationOffersFromModel(modelUUID, requiredPermission, filters...)
if err != nil {
return nil, errors.Trace(err)
}
model := models[modelUUID]
for _, offerDetails := range offers {
offerDetails.OfferURL = jujucrossmodel.MakeURL(model.Owner().Name(), model.Name(), offerDetails.OfferName, "")
result = append(result, offerDetails)
}
}
return result, nil
}
func makeOfferFilterFromParams(filter params.OfferFilter) jujucrossmodel.ApplicationOfferFilter {
offerFilter := jujucrossmodel.ApplicationOfferFilter{
OfferName: filter.OfferName,
ApplicationName: filter.ApplicationName,
ApplicationDescription: filter.ApplicationDescription,
}
// TODO(wallyworld) - add support for Endpoint filter attribute
return offerFilter
}
func (api *BaseAPI) makeOfferParams(backend Backend, offer *jujucrossmodel.ApplicationOffer, access permission.Access) (
*params.ApplicationOffer, Application, error,
) {
app, err := backend.Application(offer.ApplicationName)
if err != nil {
return nil, nil, errors.Trace(err)
}
appBindings, err := app.EndpointBindings()
if err != nil {
return nil, nil, errors.Trace(err)
}
result := params.ApplicationOffer{
SourceModelTag: backend.ModelTag().String(),
OfferName: offer.OfferName,
ApplicationDescription: offer.ApplicationDescription,
Access: string(access),
}
spaceNames := set.NewStrings()
for alias, ep := range offer.Endpoints {
result.Endpoints = append(result.Endpoints, params.RemoteEndpoint{
Name: alias,
Interface: ep.Interface,
Role: ep.Role,
Scope: ep.Scope,
Limit: ep.Limit,
})
spaceName, ok := appBindings[ep.Name]
if !ok {
// There should always be some binding (even if it's to the default space).
// This isn't currently the case so add the default binding here.
logger.Warningf("no binding for %q endpoint on application %q", ep.Name, offer.ApplicationName)
if result.Bindings == nil {
result.Bindings = make(map[string]string)
}
result.Bindings[ep.Name] = environs.DefaultSpaceName
}
spaceNames.Add(spaceName)
}
spaces, err := api.collectRemoteSpaces(backend, spaceNames.SortedValues())
if errors.IsNotSupported(err) {
// Provider doesn't support ProviderSpaceInfo; continue
// without any space information, we shouldn't short-circuit
// cross-model connections.
return &result, app, nil
}
if err != nil {
return nil, nil, errors.Trace(err)
}
// Ensure bindings only contains entries for which we have spaces.
for epName, spaceName := range appBindings {
space, ok := spaces[spaceName]
if !ok {
continue
}
if result.Bindings == nil {
result.Bindings = make(map[string]string)
}
result.Bindings[epName] = spaceName
result.Spaces = append(result.Spaces, space)
}
return &result, app, nil
}
// collectRemoteSpaces gets provider information about the spaces from
// the state passed in. (This state will be for a different model than
// this API instance, which is why the results are *remote* spaces.)
// These can be used by the provider later on to decide whether a
// connection can be made via cloud-local addresses. If the provider
// doesn't support getting ProviderSpaceInfo the NotSupported error
// will be returned.
func (api *BaseAPI) collectRemoteSpaces(backend Backend, spaceNames []string) (map[string]params.RemoteSpace, error) {
env, err := api.getEnviron(backend.ModelUUID())
if err != nil {
return nil, errors.Trace(err)
}
netEnv, ok := environs.SupportsNetworking(env)
if !ok {
logger.Debugf("cloud provider doesn't support networking, not getting space info")
return nil, nil
}
results := make(map[string]params.RemoteSpace)
for _, name := range spaceNames {
space := environs.DefaultSpaceInfo
if name != environs.DefaultSpaceName {
dbSpace, err := backend.Space(name)
if err != nil {
return nil, errors.Trace(err)
}
space, err = spaceInfoFromState(dbSpace)
if err != nil {
return nil, errors.Trace(err)
}
}
providerSpace, err := netEnv.ProviderSpaceInfo(space)
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
if providerSpace == nil {
logger.Warningf("no provider space info for %q", name)
continue
}
remoteSpace := paramsFromProviderSpaceInfo(providerSpace)
// Use the name from state in case provider and state disagree.
remoteSpace.Name = name
results[name] = remoteSpace
}
return results, nil
}