/
modelgeneration.go
461 lines (399 loc) · 13.5 KB
/
modelgeneration.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
// Copyright 2019 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package modelgeneration
import (
"fmt"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/loggo"
"gopkg.in/juju/names.v3"
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/apiserver/facade"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/core/model"
"github.com/juju/juju/permission"
)
var logger = loggo.GetLogger("juju.apiserver.modelgeneration")
// API is the concrete implementation of the API endpoint.
type API struct {
check *common.BlockChecker
authorizer facade.Authorizer
apiUser names.UserTag
isControllerAdmin bool
st State
model Model
modelCache ModelCache
}
type APIV3 struct {
*API
}
type APIV2 struct {
*APIV3
}
type APIV1 struct {
*APIV2
}
// NewModelGenerationFacadeV4 provides the signature required for facade registration.
func NewModelGenerationFacadeV4(ctx facade.Context) (*API, error) {
authorizer := ctx.Auth()
st := &stateShim{State: ctx.State()}
m, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
mc, err := ctx.Controller().Model(st.ModelUUID())
if err != nil {
return nil, errors.Trace(err)
}
return NewModelGenerationAPI(st, authorizer, m, &modelCacheShim{Model: mc})
}
// NewModelGenerationFacadeV3 provides the signature required for facade registration.
func NewModelGenerationFacadeV3(ctx facade.Context) (*APIV3, error) {
v4, err := NewModelGenerationFacadeV4(ctx)
if err != nil {
return nil, err
}
return &APIV3{v4}, nil
} // NewModelGenerationFacadeV2 provides the signature required for facade registration.
func NewModelGenerationFacadeV2(ctx facade.Context) (*APIV2, error) {
v3, err := NewModelGenerationFacadeV3(ctx)
if err != nil {
return nil, err
}
return &APIV2{v3}, nil
}
// NewModelGenerationFacade provides the signature required for facade registration.
func NewModelGenerationFacade(ctx facade.Context) (*APIV1, error) {
v2, err := NewModelGenerationFacadeV2(ctx)
if err != nil {
return nil, err
}
return &APIV1{v2}, nil
}
// NewModelGenerationAPI creates a new API endpoint for dealing with model generations.
func NewModelGenerationAPI(
st State,
authorizer facade.Authorizer,
m Model,
mc ModelCache,
) (*API, error) {
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
// Since we know this is a user tag (because AuthClient is true),
// we just do the type assertion to the UserTag.
apiUser, _ := authorizer.GetAuthTag().(names.UserTag)
// Pretty much all of the user manager methods have special casing for admin
// users, so look once when we start and remember if the user is an admin.
isAdmin, err := authorizer.HasPermission(permission.SuperuserAccess, st.ControllerTag())
if err != nil {
return nil, errors.Trace(err)
}
return &API{
authorizer: authorizer,
isControllerAdmin: isAdmin,
apiUser: apiUser,
st: st,
model: m,
modelCache: mc,
}, nil
}
func (api *API) hasAdminAccess() (bool, error) {
canWrite, err := api.authorizer.HasPermission(permission.AdminAccess, api.model.ModelTag())
if errors.IsNotFound(err) {
return false, nil
}
return canWrite, err
}
// AddBranch adds a new branch with the input name to the model.
func (api *API) AddBranch(arg params.BranchArg) (params.ErrorResult, error) {
result := params.ErrorResult{}
isModelAdmin, err := api.hasAdminAccess()
if err != nil {
return result, errors.Trace(err)
}
if !isModelAdmin && !api.isControllerAdmin {
return result, common.ErrPerm
}
if err := model.ValidateBranchName(arg.BranchName); err != nil {
result.Error = common.ServerError(err)
} else {
result.Error = common.ServerError(api.model.AddBranch(arg.BranchName, api.apiUser.Name()))
}
return result, nil
}
// TrackBranch marks the input units and/or applications as tracking the input
// branch, causing them to realise changes made under that branch.
func (api *APIV2) TrackBranch(arg params.BranchTrackArg) (params.ErrorResults, error) {
// For backwards compatibility, ensure we always set the NumUnits to 0
arg.NumUnits = 0
return api.API.TrackBranch(arg)
}
// TrackBranch marks the input units and/or applications as tracking the input
// branch, causing them to realise changes made under that branch.
func (api *API) TrackBranch(arg params.BranchTrackArg) (params.ErrorResults, error) {
isModelAdmin, err := api.hasAdminAccess()
if err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
if !isModelAdmin && !api.isControllerAdmin {
return params.ErrorResults{}, common.ErrPerm
}
// Ensure we guard against the numUnits being greater than 0 and the number
// units/applications greater than 1. This is because we don't know how to
// topographically distribute between all the applications and units,
// especially if an error occurs whilst assigning the units.
if arg.NumUnits > 0 && len(arg.Entities) > 1 {
return params.ErrorResults{}, errors.Errorf("number of units and unit IDs can not be specified at the same time")
}
branch, err := api.model.Branch(arg.BranchName)
if err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(arg.Entities)),
}
for i, entity := range arg.Entities {
tag, err := names.ParseTag(entity.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
switch tag.Kind() {
case names.ApplicationTagKind:
result.Results[i].Error = common.ServerError(branch.AssignUnits(tag.Id(), arg.NumUnits))
case names.UnitTagKind:
result.Results[i].Error = common.ServerError(branch.AssignUnit(tag.Id()))
default:
result.Results[i].Error = common.ServerError(
errors.Errorf("expected names.UnitTag or names.ApplicationTag, got %T", tag))
}
}
return result, nil
}
// CommitBranch commits the input branch, making its changes applicable to
// the whole model and marking it complete.
func (api *API) CommitBranch(arg params.BranchArg) (params.IntResult, error) {
result := params.IntResult{}
isModelAdmin, err := api.hasAdminAccess()
if err != nil {
return result, errors.Trace(err)
}
if !isModelAdmin && !api.isControllerAdmin {
return result, common.ErrPerm
}
branch, err := api.model.Branch(arg.BranchName)
if err != nil {
return intResultsError(err)
}
if genId, err := branch.Commit(api.apiUser.Name()); err != nil {
result.Error = common.ServerError(err)
} else {
result.Result = genId
}
return result, nil
}
// AbortBranch aborts the input branch, marking it complete. However no
// changes are made applicable to the whole model. No units may be assigned
// to the branch when aborting.
func (api *API) AbortBranch(arg params.BranchArg) (params.ErrorResult, error) {
result := params.ErrorResult{}
isModelAdmin, err := api.hasAdminAccess()
if err != nil {
return result, errors.Trace(err)
}
if !isModelAdmin && !api.isControllerAdmin {
return result, common.ErrPerm
}
branch, err := api.model.Branch(arg.BranchName)
if err != nil {
result.Error = common.ServerError(err)
return result, nil
}
if err := branch.Abort(api.apiUser.Name()); err != nil {
result.Error = common.ServerError(err)
}
return result, nil
}
// BranchInfo will return details of branch identified by the input argument,
// including units on the branch and the configuration disjoint with the
// master generation.
// An error is returned if no in-flight branch matching in input is found.
func (api *API) BranchInfo(
args params.BranchInfoArgs) (params.GenerationResults, error) {
result := params.GenerationResults{}
isModelAdmin, err := api.hasAdminAccess()
if err != nil {
return result, errors.Trace(err)
}
if !isModelAdmin && !api.isControllerAdmin {
return result, common.ErrPerm
}
// From clients, we expect a single branch name or none,
// but we accommodate any number - they all must exist to avoid an error.
// If no branch is supplied, get them all.
var branches []Generation
if len(args.BranchNames) > 0 {
branches = make([]Generation, len(args.BranchNames))
for i, name := range args.BranchNames {
if branches[i], err = api.model.Branch(name); err != nil {
return generationResultsError(err)
}
}
} else {
if branches, err = api.model.Branches(); err != nil {
return generationResultsError(err)
}
}
results := make([]params.Generation, len(branches))
for i, b := range branches {
if results[i], err = api.oneBranchInfo(b, args.Detailed); err != nil {
return generationResultsError(err)
}
}
result.Generations = results
return result, nil
}
// ShowCommit will return details a commit given by its generationId
// An error is returned if either no branch can be found corresponding to the generation id.
// Or the generation id given is below 1.
func (api *APIV3) ShowCommit(arg params.GenerationId) (params.GenerationCommitResult, error) {
result := params.GenerationCommitResult{}
isModelAdmin, err := api.hasAdminAccess()
if err != nil {
return result, errors.Trace(err)
}
if !isModelAdmin && !api.isControllerAdmin {
return result, common.ErrPerm
}
if arg.GenerationId < 1 {
err := errors.Errorf("supplied generation id has to be higher than 0")
return generationCommitResultError(err)
}
branch, err := api.model.CommittedBranch(arg.GenerationId)
if err != nil {
result.Error = common.ServerError(err)
return result, nil
}
generationCommit, err := api.getGenerationCommit(branch)
if err != nil {
return generationCommitResultError(err)
}
result.GenerationCommit = generationCommit
return result, nil
}
// ListCommits will return the commits, hence only branches with generation_id higher than 0
func (api *APIV3) ListCommits() (params.GenerationCommitResults, error) {
result := params.GenerationCommitResults{}
isModelAdmin, err := api.hasAdminAccess()
if err != nil {
return result, errors.Trace(err)
}
if !isModelAdmin && !api.isControllerAdmin {
return result, common.ErrPerm
}
var branches []Generation
if branches, err = api.model.CommittedBranches(); err != nil {
return generationCommitResultsError(err)
}
results := make([]params.GenerationCommit, len(branches))
for i, b := range branches {
gen := params.GenerationCommit{
BranchName: b.BranchName(),
Completed: b.Completed(),
CompletedBy: b.CompletedBy(),
GenerationId: b.GenerationId(),
}
results[i] = gen
}
result.GenerationCommits = results
return result, nil
}
func (api *API) oneBranchInfo(branch Generation, detailed bool) (params.Generation, error) {
deltas := branch.Config()
var apps []params.GenerationApplication
for appName, tracking := range branch.AssignedUnits() {
app, err := api.st.Application(appName)
if err != nil {
return params.Generation{}, errors.Trace(err)
}
allUnits, err := app.UnitNames()
if err != nil {
return params.Generation{}, errors.Trace(err)
}
branchApp := params.GenerationApplication{
ApplicationName: appName,
UnitProgress: fmt.Sprintf("%d/%d", len(tracking), len(allUnits)),
}
// Determine the effective charm configuration changes.
defaults, err := app.DefaultCharmConfig()
if err != nil {
return params.Generation{}, errors.Trace(err)
}
branchApp.ConfigChanges = deltas[appName].EffectiveChanges(defaults)
// TODO (manadart 2019-04-12): Charm URL.
// TODO (manadart 2019-04-12): Resources.
// Only include unit names if detailed info was requested.
if detailed {
trackingSet := set.NewStrings(tracking...)
branchApp.UnitsTracking = trackingSet.SortedValues()
branchApp.UnitsPending = set.NewStrings(allUnits...).Difference(trackingSet).SortedValues()
}
apps = append(apps, branchApp)
}
return params.Generation{
BranchName: branch.BranchName(),
Created: branch.Created(),
CreatedBy: branch.CreatedBy(),
Applications: apps,
}, nil
}
func (api *APIV3) getGenerationCommit(branch Generation) (params.GenerationCommit, error) {
generation, err := api.oneBranchInfo(branch, true)
if err != nil {
return params.GenerationCommit{}, errors.Trace(err)
}
return params.GenerationCommit{
BranchName: branch.BranchName(),
Completed: branch.Completed(),
CompletedBy: branch.CompletedBy(),
GenerationId: branch.GenerationId(),
Created: branch.Created(),
CreatedBy: branch.CreatedBy(),
Applications: generation.Applications,
}, nil
}
// HasActiveBranch returns a true result if the input model has an "in-flight"
// branch matching the input name.
func (api *API) HasActiveBranch(arg params.BranchArg) (params.BoolResult, error) {
result := params.BoolResult{}
isModelAdmin, err := api.hasAdminAccess()
if err != nil {
return result, errors.Trace(err)
}
if !isModelAdmin && !api.isControllerAdmin {
return result, common.ErrPerm
}
if _, err := api.modelCache.Branch(arg.BranchName); err != nil {
if errors.IsNotFound(err) {
result.Result = false
} else {
result.Error = common.ServerError(err)
}
} else {
result.Result = true
}
return result, nil
}
func generationResultsError(err error) (params.GenerationResults, error) {
return params.GenerationResults{Error: common.ServerError(err)}, nil
}
func generationCommitResultsError(err error) (params.GenerationCommitResults, error) {
return params.GenerationCommitResults{Error: common.ServerError(err)}, nil
}
func generationCommitResultError(err error) (params.GenerationCommitResult, error) {
return params.GenerationCommitResult{Error: common.ServerError(err)}, nil
}
func intResultsError(err error) (params.IntResult, error) {
return params.IntResult{Error: common.ServerError(err)}, nil
}