/
context.go
86 lines (69 loc) · 2.16 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright 2014 The Serviced Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package datastore
import (
"github.com/control-center/serviced/metrics"
)
// Context is the context of the application or request being made
type Context interface {
// Get a connection to the datastore
Connection() (Connection, error)
// Get the Metrics object from the context
Metrics() *metrics.Metrics
// Get and set the user for audit logging
SetUser(user string)
User() string
}
var savedDriver Driver
//Register a driver to use for the context
func Register(driver Driver) {
savedDriver = driver
ctx = newCtx(driver)
}
//Get returns the global Context
func Get() Context {
return ctx
}
// GetNew() returns a new global context.
// This function is not intended for production use, but is for the purpose
// of getting fresh contexts for performance testing with metrics for troubleshooting.
func GetNew() Context {
return newCtx(savedDriver)
}
// GetNewInstance returns a new instance of the context object, but with the metrics and connections
// from the global context object.
func GetNewInstance() Context {
return &context{savedDriver, ctx.Metrics(), "system"}
}
var ctx Context
//new Creates a new context with a Driver to a datastore
func newCtx(driver Driver) Context {
return &context{driver, metrics.NewMetrics(), "system"}
}
type context struct {
driver Driver
metrics *metrics.Metrics
user string
}
func (c *context) Connection() (Connection, error) {
return c.driver.GetConnection()
}
func (c *context) Metrics() *metrics.Metrics {
return c.metrics
}
func (c *context) SetUser(user string) {
c.user = user
}
func (c *context) User() string {
return c.user
}