/
facade.go
85 lines (74 loc) · 2.41 KB
/
facade.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
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package applicationscaler
import (
"github.com/juju/errors"
"github.com/juju/names/v5"
apiservererrors "github.com/juju/juju/apiserver/errors"
"github.com/juju/juju/apiserver/facade"
"github.com/juju/juju/rpc/params"
"github.com/juju/juju/state"
"github.com/juju/juju/state/watcher"
)
// Backend exposes functionality required by Facade.
type Backend interface {
// WatchScaledServices returns a watcher that sends service ids
// that might not have enough units.
WatchScaledServices() state.StringsWatcher
// RescaleService ensures that the named service has at least its
// configured minimum unit count.
RescaleService(name string) error
}
// Facade allows model-manager clients to watch and rescale services.
type Facade struct {
backend Backend
resources facade.Resources
}
// NewFacade creates a new authorized Facade.
func NewFacade(backend Backend, res facade.Resources, auth facade.Authorizer) (*Facade, error) {
if !auth.AuthController() {
return nil, apiservererrors.ErrPerm
}
return &Facade{
backend: backend,
resources: res,
}, nil
}
// Watch returns a watcher that sends the names of services whose
// unit count may be below their configured minimum.
func (facade *Facade) Watch() (params.StringsWatchResult, error) {
watch := facade.backend.WatchScaledServices()
if changes, ok := <-watch.Changes(); ok {
id := facade.resources.Register(watch)
return params.StringsWatchResult{
StringsWatcherId: id,
Changes: changes,
}, nil
}
return params.StringsWatchResult{}, watcher.EnsureErr(watch)
}
// Rescale causes any supplied services to be scaled up to their
// minimum size.
func (facade *Facade) Rescale(args params.Entities) params.ErrorResults {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
for i, entity := range args.Entities {
err := facade.rescaleOne(entity.Tag)
result.Results[i].Error = apiservererrors.ServerError(err)
}
return result
}
// rescaleOne scales up the supplied service, if necessary; or returns a
// suitable error.
func (facade *Facade) rescaleOne(tagString string) error {
tag, err := names.ParseTag(tagString)
if err != nil {
return errors.Trace(err)
}
ApplicationTag, ok := tag.(names.ApplicationTag)
if !ok {
return apiservererrors.ErrPerm
}
return facade.backend.RescaleService(ApplicationTag.Id())
}