-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
64 lines (54 loc) · 1.29 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
59
60
61
62
63
64
package function
import (
"context"
"encoding/json"
"os"
"github.com/itsmurugappan/kubernetes-resource-builder/pkg/kubernetes"
)
type fnCtx struct {
c context.Context
}
type jobSpecKey struct{}
type nsKey struct{}
func Context(ctx context.Context) *fnCtx {
return &fnCtx{ctx}
}
func BuildContext() context.Context {
return withNamespace(
withSpec(
kubernetes.WithContext(
context.Background(),
),
),
)
}
func withSpec(ctx context.Context) context.Context {
raw, present := os.LookupEnv("JOB_SPEC")
if !present {
panic("'JOB_SPEC' not provided as a env variable")
}
containerSpec := kubernetes.ContainerSpec{}
if err := json.Unmarshal([]byte(raw), &containerSpec); err != nil {
panic(err)
}
return context.WithValue(ctx, jobSpecKey{}, &containerSpec)
}
func withNamespace(ctx context.Context) context.Context {
ns, present := os.LookupEnv("FUNCTION_NAMESPACE")
if !present {
ns, _ = kubernetes.GetCurrentNamespace()
}
return context.WithValue(ctx, nsKey{}, &ns)
}
func specFromContext(ctx context.Context) *kubernetes.ContainerSpec {
if spec, ok := ctx.Value(jobSpecKey{}).(*kubernetes.ContainerSpec); ok {
return spec
}
return nil
}
func nsFromContext(ctx context.Context) *string {
if spec, ok := ctx.Value(nsKey{}).(*string); ok {
return spec
}
return nil
}