/
register.go
63 lines (54 loc) · 1.72 KB
/
register.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
// Copyright 2022 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package resourceshookcontext
import (
"reflect"
"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/state"
)
// Register is called to expose a package of facades onto a given registry.
func Register(registry facade.FacadeRegistry) {
registry.MustRegister("ResourcesHookContext", 1, func(ctx facade.Context) (facade.Facade, error) {
return newStateFacade(ctx)
}, reflect.TypeOf((*UnitFacade)(nil)))
}
// newStateFacade provides the signature to register this resource facade
func newStateFacade(ctx facade.Context) (*UnitFacade, error) {
authorizer := ctx.Auth()
st := ctx.State()
if !authorizer.AuthUnitAgent() && !authorizer.AuthApplicationAgent() {
return nil, apiservererrors.ErrPerm
}
var (
unit *state.Unit
err error
)
switch tag := authorizer.GetAuthTag().(type) {
case names.UnitTag:
unit, err = st.Unit(tag.Id())
if err != nil {
return nil, errors.Trace(err)
}
case names.ApplicationTag:
// Allow application access for K8s units. As they are all homogeneous any of the units will suffice.
app, err := st.Application(tag.Id())
if err != nil {
return nil, errors.Trace(err)
}
allUnits, err := app.AllUnits()
if err != nil {
return nil, errors.Trace(err)
}
if len(allUnits) <= 0 {
return nil, errors.Errorf("failed to get units for app: %s", app.Name())
}
unit = allUnits[0]
default:
return nil, errors.Errorf("expected names.UnitTag or names.ApplicationTag, got %T", tag)
}
res := st.Resources()
return NewUnitFacade(&resourcesUnitDataStore{res, unit}), nil
}