forked from juju/juju
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spaces.go
488 lines (428 loc) · 13.7 KB
/
spaces.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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package spaces
import (
"fmt"
"strings"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names/v4"
"github.com/DavinZhang/juju/apiserver/common"
"github.com/DavinZhang/juju/apiserver/common/networkingcommon"
apiservererrors "github.com/DavinZhang/juju/apiserver/errors"
"github.com/DavinZhang/juju/apiserver/facade"
"github.com/DavinZhang/juju/apiserver/params"
"github.com/DavinZhang/juju/core/network"
"github.com/DavinZhang/juju/core/permission"
"github.com/DavinZhang/juju/environs"
"github.com/DavinZhang/juju/environs/context"
"github.com/DavinZhang/juju/environs/space"
"github.com/DavinZhang/juju/state"
)
var logger = loggo.GetLogger("juju.apiserver.spaces")
// APIv2 provides the spaces API facade for versions < 3.
type APIv2 struct {
*APIv3
}
// APIv3 provides the spaces API facade for version 3.
type APIv3 struct {
*APIv4
}
// APIv4 provides the spaces API facade for version 4.
type APIv4 struct {
*APIv5
}
// APIv5 provides the spaces API facade for version 5.
type APIv5 struct {
*API
}
// API provides the spaces API facade for version 6.
type API struct {
reloadSpacesAPI ReloadSpaces
backing Backing
resources facade.Resources
auth facade.Authorizer
context context.ProviderCallContext
check BlockChecker
opFactory OpFactory
}
// NewAPIv2 is a wrapper that creates a V2 spaces API.
func NewAPIv2(st *state.State, res facade.Resources, auth facade.Authorizer) (*APIv2, error) {
api, err := NewAPIv3(st, res, auth)
if err != nil {
return nil, errors.Trace(err)
}
return &APIv2{api}, nil
}
// NewAPIv3 is a wrapper that creates a V3 spaces API.
func NewAPIv3(st *state.State, res facade.Resources, auth facade.Authorizer) (*APIv3, error) {
api, err := NewAPIv4(st, res, auth)
if err != nil {
return nil, errors.Trace(err)
}
return &APIv3{api}, nil
}
// NewAPIv4 is a wrapper that creates a V4 spaces API.
func NewAPIv4(st *state.State, res facade.Resources, auth facade.Authorizer) (*APIv4, error) {
api, err := NewAPIv5(st, res, auth)
if err != nil {
return nil, errors.Trace(err)
}
return &APIv4{api}, nil
}
// NewAPIv5 is a wrapper that creates a V5 spaces API.
func NewAPIv5(st *state.State, res facade.Resources, auth facade.Authorizer) (*APIv5, error) {
api, err := NewAPI(st, res, auth)
if err != nil {
return nil, errors.Trace(err)
}
return &APIv5{api}, nil
}
// NewAPI creates a new Space API server-side facade with a
// state.State backing.
func NewAPI(st *state.State, res facade.Resources, auth facade.Authorizer) (*API, error) {
stateShim, err := NewStateShim(st)
if err != nil {
return nil, errors.Trace(err)
}
check := common.NewBlockChecker(st)
ctx := context.CallContext(st)
reloadSpacesEnvirons, err := DefaultReloadSpacesEnvirons(st)
if err != nil {
return nil, errors.Trace(err)
}
reloadSpacesAuth := DefaultReloadSpacesAuthorizer(auth, check, stateShim)
reloadSpacesAPI := NewReloadSpacesAPI(
space.NewState(st),
reloadSpacesEnvirons,
EnvironSpacesAdapter{},
ctx,
reloadSpacesAuth,
)
return newAPIWithBacking(apiConfig{
ReloadSpacesAPI: reloadSpacesAPI,
Backing: stateShim,
Check: check,
Context: ctx,
Resources: res,
Authorizer: auth,
Factory: newOpFactory(st),
})
}
type apiConfig struct {
ReloadSpacesAPI ReloadSpaces
Backing Backing
Check BlockChecker
Context context.ProviderCallContext
Resources facade.Resources
Authorizer facade.Authorizer
Factory OpFactory
}
// newAPIWithBacking creates a new server-side Spaces API facade with
// the given Backing.
func newAPIWithBacking(cfg apiConfig) (*API, error) {
// Only clients can access the Spaces facade.
if !cfg.Authorizer.AuthClient() {
return nil, apiservererrors.ErrPerm
}
return &API{
reloadSpacesAPI: cfg.ReloadSpacesAPI,
backing: cfg.Backing,
resources: cfg.Resources,
auth: cfg.Authorizer,
context: cfg.Context,
check: cfg.Check,
opFactory: cfg.Factory,
}, nil
}
// CreateSpaces creates a new Juju network space, associating the
// specified subnets with it (optional; can be empty).
func (api *API) CreateSpaces(args params.CreateSpacesParams) (results params.ErrorResults, err error) {
isAdmin, err := api.auth.HasPermission(permission.AdminAccess, api.backing.ModelTag())
if err != nil && !errors.IsNotFound(err) {
return results, errors.Trace(err)
}
if !isAdmin {
return results, apiservererrors.ServerError(apiservererrors.ErrPerm)
}
if err := api.check.ChangeAllowed(); err != nil {
return results, errors.Trace(err)
}
if err = api.checkSupportsSpaces(); err != nil {
return results, apiservererrors.ServerError(errors.Trace(err))
}
results.Results = make([]params.ErrorResult, len(args.Spaces))
for i, space := range args.Spaces {
err := api.createOneSpace(space)
if err == nil {
continue
}
results.Results[i].Error = apiservererrors.ServerError(errors.Trace(err))
}
return results, nil
}
// CreateSpaces creates a new Juju network space, associating the
// specified subnets with it (optional; can be empty).
func (api *APIv4) CreateSpaces(args params.CreateSpacesParamsV4) (params.ErrorResults, error) {
isAdmin, err := api.auth.HasPermission(permission.AdminAccess, api.backing.ModelTag())
if err != nil && !errors.IsNotFound(err) {
return params.ErrorResults{}, errors.Trace(err)
}
if !isAdmin {
return params.ErrorResults{}, apiservererrors.ServerError(apiservererrors.ErrPerm)
}
if err := api.check.ChangeAllowed(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
if err := api.checkSupportsSpaces(); err != nil {
return params.ErrorResults{}, apiservererrors.ServerError(errors.Trace(err))
}
results := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Spaces)),
}
for i, space := range args.Spaces {
cidrs, err := convertOldSubnetTagToCIDR(space.SubnetTags)
if err != nil {
results.Results[i].Error = apiservererrors.ServerError(err)
continue
}
csParams := params.CreateSpaceParams{
CIDRs: cidrs,
SpaceTag: space.SpaceTag,
Public: space.Public,
ProviderId: space.ProviderId,
}
err = api.createOneSpace(csParams)
if err == nil {
continue
}
results.Results[i].Error = apiservererrors.ServerError(errors.Trace(err))
}
return results, nil
}
// createOneSpace creates one new Juju network space, associating the
// specified subnets with it (optional; can be empty).
func (api *API) createOneSpace(args params.CreateSpaceParams) error {
// Validate the args, assemble information for api.backing.AddSpaces
spaceTag, err := names.ParseSpaceTag(args.SpaceTag)
if err != nil {
return errors.Trace(err)
}
subnetIDs := make([]string, len(args.CIDRs))
for i, cidr := range args.CIDRs {
if !network.IsValidCIDR(cidr) {
return errors.New(fmt.Sprintf("%q is not a valid CIDR", cidr))
}
subnet, err := api.backing.SubnetByCIDR(cidr)
if err != nil {
return err
}
subnetIDs[i] = subnet.ID()
}
// Add the validated space.
_, err = api.backing.AddSpace(spaceTag.Id(), network.Id(args.ProviderId), subnetIDs, args.Public)
if err != nil {
return errors.Trace(err)
}
return nil
}
func convertOldSubnetTagToCIDR(subnetTags []string) ([]string, error) {
cidrs := make([]string, len(subnetTags))
// In lieu of keeping names.v2 around, split the expected
// string for the older api calls. Format: subnet-<CIDR>
for i, tag := range subnetTags {
split := strings.Split(tag, "-")
if len(split) != 2 || split[0] != "subnet" {
return nil, errors.New(fmt.Sprintf("%q is not valid SubnetTag", tag))
}
cidrs[i] = split[1]
}
return cidrs, nil
}
// ListSpaces lists all the available spaces and their associated subnets.
func (api *API) ListSpaces() (results params.ListSpacesResults, err error) {
canRead, err := api.auth.HasPermission(permission.ReadAccess, api.backing.ModelTag())
if err != nil && !errors.IsNotFound(err) {
return results, errors.Trace(err)
}
if !canRead {
return results, apiservererrors.ServerError(apiservererrors.ErrPerm)
}
err = api.checkSupportsSpaces()
if err != nil {
return results, apiservererrors.ServerError(errors.Trace(err))
}
spaces, err := api.backing.AllSpaces()
if err != nil {
return results, errors.Trace(err)
}
results.Results = make([]params.Space, len(spaces))
for i, space := range spaces {
result := params.Space{}
result.Id = space.Id()
result.Name = space.Name()
subnets, err := space.Subnets()
if err != nil {
err = errors.Annotatef(err, "fetching subnets")
result.Error = apiservererrors.ServerError(err)
results.Results[i] = result
continue
}
result.Subnets = make([]params.Subnet, len(subnets))
for i, subnet := range subnets {
result.Subnets[i] = networkingcommon.BackingSubnetToParamsSubnet(subnet)
}
results.Results[i] = result
}
return results, nil
}
func (api *APIv5) ShowSpace(_, _ struct{}) {}
// ShowSpace shows the spaces for a set of given entities.
func (api *API) ShowSpace(entities params.Entities) (params.ShowSpaceResults, error) {
canRead, err := api.auth.HasPermission(permission.ReadAccess, api.backing.ModelTag())
if err != nil && !errors.IsNotFound(err) {
return params.ShowSpaceResults{}, errors.Trace(err)
}
if !canRead {
return params.ShowSpaceResults{}, apiservererrors.ServerError(apiservererrors.ErrPerm)
}
err = api.checkSupportsSpaces()
if err != nil {
return params.ShowSpaceResults{}, apiservererrors.ServerError(errors.Trace(err))
}
results := make([]params.ShowSpaceResult, len(entities.Entities))
for i, entity := range entities.Entities {
spaceName, err := names.ParseSpaceTag(entity.Tag)
if err != nil {
results[i].Error = apiservererrors.ServerError(errors.Trace(err))
continue
}
var result params.ShowSpaceResult
space, err := api.backing.SpaceByName(spaceName.Id())
if err != nil {
newErr := errors.Annotatef(err, "fetching space %q", spaceName)
results[i].Error = apiservererrors.ServerError(newErr)
continue
}
result.Space.Name = space.Name()
result.Space.Id = space.Id()
subnets, err := space.Subnets()
if err != nil {
newErr := errors.Annotatef(err, "fetching subnets")
results[i].Error = apiservererrors.ServerError(newErr)
continue
}
result.Space.Subnets = make([]params.Subnet, len(subnets))
for i, subnet := range subnets {
result.Space.Subnets[i] = networkingcommon.BackingSubnetToParamsSubnet(subnet)
}
applications, err := api.applicationsBoundToSpace(space.Id())
if err != nil {
newErr := errors.Annotatef(err, "fetching applications")
results[i].Error = apiservererrors.ServerError(newErr)
continue
}
result.Applications = applications
machineCount, err := api.getMachineCountBySpaceID(space.Id())
if err != nil {
newErr := errors.Annotatef(err, "fetching machine count")
results[i].Error = apiservererrors.ServerError(newErr)
continue
}
result.MachineCount = machineCount
results[i] = result
}
return params.ShowSpaceResults{Results: results}, err
}
// ReloadSpaces is not available via the V2 API.
func (u *APIv2) ReloadSpaces(_, _ struct{}) {}
// ReloadSpaces refreshes spaces from substrate
func (api *API) ReloadSpaces() error {
return api.reloadSpacesAPI.ReloadSpaces()
}
// checkSupportsSpaces checks if the environment implements NetworkingEnviron
// and also if it supports spaces.
func (api *API) checkSupportsSpaces() error {
env, err := environs.GetEnviron(api.backing, environs.New)
if err != nil {
return errors.Annotate(err, "getting environ")
}
if !environs.SupportsSpaces(api.context, env) {
return errors.NotSupportedf("spaces")
}
return nil
}
func (api *API) getMachineCountBySpaceID(spaceID string) (int, error) {
var count int
machines, err := api.backing.AllMachines()
if err != nil {
return 0, errors.Trace(err)
}
for _, machine := range machines {
spacesSet, err := machine.AllSpaces()
if err != nil {
return 0, errors.Trace(err)
}
if spacesSet.Contains(spaceID) {
count++
}
}
return count, nil
}
func (api *API) applicationsBoundToSpace(spaceID string) ([]string, error) {
allBindings, err := api.backing.AllEndpointBindings()
if err != nil {
return nil, errors.Trace(err)
}
applications := set.NewStrings()
for app, bindings := range allBindings {
for _, boundSpace := range bindings.Map() {
if boundSpace == spaceID {
applications.Add(app)
break
}
}
}
return applications.SortedValues(), nil
}
// ensureSpacesAreMutable checks that the current user
// is allowed to edit the Space topology.
func (api *API) ensureSpacesAreMutable() error {
isAdmin, err := api.auth.HasPermission(permission.AdminAccess, api.backing.ModelTag())
if err != nil && !errors.IsNotFound(err) {
return errors.Trace(err)
}
if !isAdmin {
return apiservererrors.ServerError(apiservererrors.ErrPerm)
}
if err := api.check.ChangeAllowed(); err != nil {
return errors.Trace(err)
}
if err = api.ensureSpacesNotProviderSourced(); err != nil {
return apiservererrors.ServerError(errors.Trace(err))
}
return nil
}
// ensureSpacesNotProviderSourced checks if the environment implements
// NetworkingEnviron and also if it supports provider spaces.
// An error is returned if it is the provider and not the Juju operator
// that determines the space topology.
func (api *API) ensureSpacesNotProviderSourced() error {
env, err := environs.GetEnviron(api.backing, environs.New)
if err != nil {
return errors.Annotate(err, "retrieving environ")
}
netEnv, ok := env.(environs.NetworkingEnviron)
if !ok {
return errors.NotSupportedf("provider networking")
}
providerSourced, err := netEnv.SupportsSpaceDiscovery(api.context)
if err != nil {
return errors.Trace(err)
}
if providerSourced {
return errors.NotSupportedf("modifying provider-sourced spaces")
}
return nil
}