/
context.go
58 lines (45 loc) · 1.44 KB
/
context.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
package action
import (
"context"
"github.com/go-logr/logr"
ctrl "sigs.k8s.io/controller-runtime"
runtimeclient "sigs.k8s.io/controller-runtime/pkg/client"
)
// assert that defaultContext is implementing Context
var _ Context = &defaultContext{}
var _ context.Context = &defaultContext{}
// resourceCtxKey is how we find runtimeclient.Object in a context.Context
type resourceCtxKey struct{}
// Context used to pass information between actions
type Context interface {
context.Context
Logger() logr.Logger
Resource() runtimeclient.Object
WithLoggerValues(values ...interface{}) Context
WithResource(obj runtimeclient.Object) Context
}
type defaultContext struct {
context.Context
}
func NewBackgroundContext() Context {
return &defaultContext{context.Background()}
}
func NewContext(ctx context.Context) Context {
return &defaultContext{ctx}
}
func (c *defaultContext) Logger() logr.Logger {
return ctrl.LoggerFrom(c)
}
func (c *defaultContext) WithLoggerValues(values ...interface{}) Context {
log := ctrl.LoggerFrom(c).WithValues(values...)
return &defaultContext{ctrl.LoggerInto(c, log)}
}
func (c *defaultContext) Resource() runtimeclient.Object {
if v, ok := c.Value(resourceCtxKey{}).(runtimeclient.Object); ok {
return v
}
panic("runtimeclient.Object not found on provided context")
}
func (c *defaultContext) WithResource(obj runtimeclient.Object) Context {
return &defaultContext{context.WithValue(c, resourceCtxKey{}, obj)}
}