...
1 package shared
2
3 import (
4 "context"
5 "reflect"
6 "time"
7
8 "golang.conradwood.net/apis/auth"
9 ge "golang.conradwood.net/apis/goeasyops"
10 "golang.conradwood.net/go-easyops/cmdline"
11 "golang.conradwood.net/go-easyops/common"
12 "golang.conradwood.net/go-easyops/utils"
13 "golang.yacloud.eu/apis/session"
14 )
15
16 const (
17 LOCALSTATENAME = "goeasysops_localstate"
18 )
19
20
21 type LocalState interface {
22 CreatorService() *auth.SignedUser
23 CallingService() *auth.SignedUser
24 Debug() bool
25 Trace() bool
26 User() *auth.SignedUser
27 SudoUser() *auth.SignedUser
28 Session() *session.Session
29 RequestID() string
30 RoutingTags() *ge.CTXRoutingTags
31 Info() string
32 Experiments() []*ge.Experiment
33 Services() []*ge.ServiceTrace
34 AuthTags() []string
35 }
36
37 type ContextBuilder interface {
38
43 Inbound2Outbound(ctx context.Context, svc *auth.SignedUser) (context.Context, bool)
44
47 Context() (context.Context, context.CancelFunc)
48
49
50 ContextWithAutoCancel() context.Context
51
52
55 WithUser(user *auth.SignedUser)
56
59 WithSudoUser(user *auth.SignedUser)
60
63 WithCreatorService(user *auth.SignedUser)
64
65
68 WithCallingService(user *auth.SignedUser)
69
70
73 WithSession(session *session.Session)
74
75
76 WithDebug()
77
78
79 WithTrace()
80
81 EnableExperiment(name string)
82
83 WithRoutingTags(*ge.CTXRoutingTags)
84
85 WithRequestID(reqid string)
86
87 WithTimeout(time.Duration)
88
89 WithParentContext(context context.Context)
90
91 WithAuthTag(tag string)
92 }
93
94 func PrettyUser(su *auth.SignedUser) string {
95 u := common.VerifySignedUser(su)
96 if u == nil {
97 return "NOUSER"
98 }
99 return u.Email
100 }
101
102 func Checksum(buf []byte) byte {
103 f := byte(0x37)
104 for _, b := range buf {
105 f = f + b
106 }
107 return f
108 }
109
110
111 func GetLocalState(ctx context.Context) LocalState {
112 if ctx == nil {
113 panic("cannot get localstate from nil context")
114 }
115 v := ctx.Value(LOCALSTATENAME)
116 if v == nil {
117
122 cmdline.DebugfContext("[go-easyops] context-builder warning, tried to extract localstate from context which is not a contextbuilder context\n")
123 }
124 res, ok := v.(LocalState)
125 if ok {
126 return res
127 }
128 cmdline.DebugfContext("could not get localstate from context (caller: %s)\n", utils.CallingFunction())
129 return newEmptyLocalState()
130
131 }
132
133 func isNil(v interface{}) bool {
134 return v == nil || (reflect.ValueOf(v).Kind() == reflect.Ptr && reflect.ValueOf(v).IsNil())
135 }
136
View as plain text