-
Notifications
You must be signed in to change notification settings - Fork 0
/
root.go
355 lines (316 loc) · 10.4 KB
/
root.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package apiserver
import (
"reflect"
"sync"
"time"
"github.com/juju/errors"
"github.com/juju/names"
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/rpc"
"github.com/juju/juju/rpc/rpcreflect"
"github.com/juju/juju/state"
)
var (
// maxClientPingInterval defines the timeframe until the ping timeout
// closes the monitored connection. TODO(mue): Idea by Roger:
// Move to API (e.g. params) so that the pinging there may
// depend on the interval.
maxClientPingInterval = 3 * time.Minute
// mongoPingInterval defines the interval at which an API server
// will ping the mongo session to make sure that it's still
// alive. When the ping returns an error, the server will be
// terminated.
mongoPingInterval = 10 * time.Second
)
type objectKey struct {
name string
version int
objId string
}
// apiHandler represents a single client's connection to the state
// after it has logged in. It contains an rpc.MethodFinder which it
// uses to dispatch Api calls appropriately.
type apiHandler struct {
state *state.State
closeState bool
rpcConn *rpc.Conn
resources *common.Resources
entity state.Entity
// An empty envUUID means that the user has logged in through the
// root of the API server rather than the /environment/:env-uuid/api
// path, logins processed with v2 or later will only offer the
// user manager and environment manager api endpoints from here.
envUUID string
}
var _ = (*apiHandler)(nil)
// newApiHandler returns a new apiHandler.
func newApiHandler(srv *Server, st *state.State, rpcConn *rpc.Conn, reqNotifier *requestNotifier, envUUID string) (*apiHandler, error) {
r := &apiHandler{
state: st,
closeState: st.EnvironUUID() != srv.state.EnvironUUID(),
resources: common.NewResources(),
rpcConn: rpcConn,
envUUID: envUUID,
}
if err := r.resources.RegisterNamed("machineID", common.StringResource(srv.tag.Id())); err != nil {
return nil, errors.Trace(err)
}
if err := r.resources.RegisterNamed("dataDir", common.StringResource(srv.dataDir)); err != nil {
return nil, errors.Trace(err)
}
if err := r.resources.RegisterNamed("logDir", common.StringResource(srv.logDir)); err != nil {
return nil, errors.Trace(err)
}
return r, nil
}
func (r *apiHandler) getResources() *common.Resources {
return r.resources
}
func (r *apiHandler) getRpcConn() *rpc.Conn {
return r.rpcConn
}
// Kill implements rpc.Killer, cleaning up any resources that need
// cleaning up to ensure that all outstanding requests return.
func (r *apiHandler) Kill() {
r.resources.StopAll()
}
// Cleanup implements rpc.Cleaner, closing the handler's State instance
// if required.
func (r *apiHandler) Cleanup() {
if r.closeState {
r.state.Close()
}
}
// srvCaller is our implementation of the rpcreflect.MethodCaller interface.
// It lives just long enough to encapsulate the methods that should be
// available for an RPC call and allow the RPC code to instantiate an object
// and place a call on its method.
type srvCaller struct {
objMethod rpcreflect.ObjMethod
goType reflect.Type
creator func(id string) (reflect.Value, error)
}
// ParamsType defines the parameters that should be supplied to this function.
// See rpcreflect.MethodCaller for more detail.
func (s *srvCaller) ParamsType() reflect.Type {
return s.objMethod.Params
}
// ReturnType defines the object that is returned from the function.`
// See rpcreflect.MethodCaller for more detail.
func (s *srvCaller) ResultType() reflect.Type {
return s.objMethod.Result
}
// Call takes the object Id and an instance of ParamsType to create an object and place
// a call on its method. It then returns an instance of ResultType.
func (s *srvCaller) Call(objId string, arg reflect.Value) (reflect.Value, error) {
objVal, err := s.creator(objId)
if err != nil {
return reflect.Value{}, err
}
return s.objMethod.Call(objVal, arg)
}
// apiRoot implements basic method dispatching to the facade registry.
type apiRoot struct {
state *state.State
closeState bool
resources *common.Resources
authorizer common.Authorizer
objectMutex sync.RWMutex
objectCache map[objectKey]reflect.Value
}
// newApiRoot returns a new apiRoot.
func newApiRoot(st *state.State, closeState bool, resources *common.Resources, authorizer common.Authorizer) *apiRoot {
r := &apiRoot{
state: st,
closeState: closeState,
resources: resources,
authorizer: authorizer,
objectCache: make(map[objectKey]reflect.Value),
}
return r
}
// Kill implements rpc.Killer, stopping the root's resources.
func (r *apiRoot) Kill() {
r.resources.StopAll()
}
// Cleanup implements rpc.Cleaner, closing the root's State instance if
// required.
func (r *apiRoot) Cleanup() {
if r.closeState {
r.state.Close()
}
}
// FindMethod looks up the given rootName and version in our facade registry
// and returns a MethodCaller that will be used by the RPC code to place calls on
// that facade.
// FindMethod uses the global registry apiserver/common.Facades.
// For more information about how FindMethod should work, see rpc/server.go and
// rpc/rpcreflect/value.go
func (r *apiRoot) FindMethod(rootName string, version int, methodName string) (rpcreflect.MethodCaller, error) {
goType, objMethod, err := r.lookupMethod(rootName, version, methodName)
if err != nil {
return nil, err
}
creator := func(id string) (reflect.Value, error) {
objKey := objectKey{name: rootName, version: version, objId: id}
r.objectMutex.RLock()
objValue, ok := r.objectCache[objKey]
r.objectMutex.RUnlock()
if ok {
return objValue, nil
}
r.objectMutex.Lock()
defer r.objectMutex.Unlock()
if objValue, ok := r.objectCache[objKey]; ok {
return objValue, nil
}
// Now that we have the write lock, check one more time in case
// someone got the write lock before us.
factory, err := common.Facades.GetFactory(rootName, version)
if err != nil {
// We don't check for IsNotFound here, because it
// should have already been handled in the GetType
// check.
return reflect.Value{}, err
}
obj, err := factory(r.state, r.resources, r.authorizer, id)
if err != nil {
return reflect.Value{}, err
}
objValue = reflect.ValueOf(obj)
if !objValue.Type().AssignableTo(goType) {
return reflect.Value{}, errors.Errorf(
"internal error, %s(%d) claimed to return %s but returned %T",
rootName, version, goType, obj)
}
if goType.Kind() == reflect.Interface {
// If the original function wanted to return an
// interface type, the indirection in the factory via
// an interface{} strips the original interface
// information off. So here we have to create the
// interface again, and assign it.
asInterface := reflect.New(goType).Elem()
asInterface.Set(objValue)
objValue = asInterface
}
r.objectCache[objKey] = objValue
return objValue, nil
}
return &srvCaller{
creator: creator,
objMethod: objMethod,
}, nil
}
func (r *apiRoot) lookupMethod(rootName string, version int, methodName string) (reflect.Type, rpcreflect.ObjMethod, error) {
noMethod := rpcreflect.ObjMethod{}
goType, err := common.Facades.GetType(rootName, version)
if err != nil {
if errors.IsNotFound(err) {
return nil, noMethod, &rpcreflect.CallNotImplementedError{
RootMethod: rootName,
Version: version,
}
}
return nil, noMethod, err
}
rpcType := rpcreflect.ObjTypeOf(goType)
objMethod, err := rpcType.Method(methodName)
if err != nil {
if err == rpcreflect.ErrMethodNotFound {
return nil, noMethod, &rpcreflect.CallNotImplementedError{
RootMethod: rootName,
Version: version,
Method: methodName,
}
}
return nil, noMethod, err
}
return goType, objMethod, nil
}
// AnonRoot dispatches API calls to those available to an anonymous connection
// which has not logged in.
type anonRoot struct {
*apiHandler
adminApis map[int]interface{}
}
// NewAnonRoot creates a new AnonRoot which dispatches to the given Admin API implementation.
func newAnonRoot(h *apiHandler, adminApis map[int]interface{}) *anonRoot {
r := &anonRoot{
apiHandler: h,
adminApis: adminApis,
}
return r
}
func (r *anonRoot) FindMethod(rootName string, version int, methodName string) (rpcreflect.MethodCaller, error) {
if rootName != "Admin" {
return nil, &rpcreflect.CallNotImplementedError{
RootMethod: rootName,
Version: version,
}
}
if api, ok := r.adminApis[version]; ok {
return rpcreflect.ValueOf(reflect.ValueOf(api)).FindMethod(rootName, 0, methodName)
}
return nil, &rpcreflect.CallNotImplementedError{
RootMethod: rootName,
Method: methodName,
Version: version,
}
}
// AuthMachineAgent returns whether the current client is a machine agent.
func (r *apiHandler) AuthMachineAgent() bool {
_, isMachine := r.GetAuthTag().(names.MachineTag)
return isMachine
}
// AuthUnitAgent returns whether the current client is a unit agent.
func (r *apiHandler) AuthUnitAgent() bool {
_, isUnit := r.GetAuthTag().(names.UnitTag)
return isUnit
}
// AuthOwner returns whether the authenticated user's tag matches the
// given entity tag.
func (r *apiHandler) AuthOwner(tag names.Tag) bool {
return r.entity.Tag() == tag
}
// AuthEnvironManager returns whether the authenticated user is a
// machine with running the ManageEnviron job.
func (r *apiHandler) AuthEnvironManager() bool {
return isMachineWithJob(r.entity, state.JobManageEnviron)
}
// AuthClient returns whether the authenticated entity is a client
// user.
func (r *apiHandler) AuthClient() bool {
_, isUser := r.GetAuthTag().(names.UserTag)
return isUser
}
// GetAuthTag returns the tag of the authenticated entity.
func (r *apiHandler) GetAuthTag() names.Tag {
return r.entity.Tag()
}
// GetAuthEntity returns the authenticated entity.
func (r *apiHandler) GetAuthEntity() state.Entity {
return r.entity
}
// DescribeFacades returns the list of available Facades and their Versions
func DescribeFacades() []params.FacadeVersions {
facades := common.Facades.List()
result := make([]params.FacadeVersions, len(facades))
for i, facade := range facades {
result[i].Name = facade.Name
result[i].Versions = facade.Versions
}
return result
}
type stateResource struct {
state *state.State
}
func (s stateResource) Stop() error {
logger.Debugf("close state connection: %s", s.state.EnvironUUID())
return s.state.Close()
}
func (s stateResource) String() string {
return s.state.EnvironUUID()
}