-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend.go
118 lines (99 loc) · 2.46 KB
/
backend.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
package secretsengine
import (
"context"
"strings"
"sync"
grafanclient "github.com/grafana/grafana-api-golang-client"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
)
const grafanaCloudKeyType = "GrafanaCloudKey"
// CreateGrafanaAPIKeyInput grafana cloud data structure to create api credentials.
type CreateGrafanaAPIKeyInput struct {
Name string `json:"name"`
Role string `json:"role"`
SecondsToLive int `json:"secondsToLive"`
Stack string `json:"-"`
}
// Factory returns a new backend as logical.Backend.
func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {
b := backend()
if err := b.Setup(ctx, conf); err != nil {
return nil, err
}
return b, nil
}
type grafanaCloudBackend struct {
*framework.Backend
lock sync.RWMutex
client *grafanclient.Client
}
func backend() *grafanaCloudBackend {
b := grafanaCloudBackend{}
b.Backend = &framework.Backend{
Help: strings.TrimSpace(backendHelp),
PathsSpecial: &logical.Paths{
LocalStorage: []string{},
SealWrapStorage: []string{
"config",
"roles/*",
},
},
Paths: framework.PathAppend(
pathRole(&b),
[]*framework.Path{
pathConfig(&b),
pathCredentials(&b),
},
),
Secrets: []*framework.Secret{
b.grafanaCloudKey(),
},
BackendType: logical.TypeLogical,
Invalidate: b.invalidate,
}
return &b
}
func (b *grafanaCloudBackend) invalidate(ctx context.Context, key string) {
if key == "config" {
b.reset()
}
}
func (b *grafanaCloudBackend) reset() {
b.lock.Lock()
defer b.lock.Unlock()
b.client = nil
}
func (b *grafanaCloudBackend) getClient(ctx context.Context, s logical.Storage) (*grafanclient.Client, error) {
b.lock.RLock()
unlockFunc := b.lock.RUnlock
defer func() { unlockFunc() }()
if b.client != nil {
return b.client, nil
}
b.lock.RUnlock()
b.lock.Lock()
unlockFunc = b.lock.Unlock
config, err := getConfig(ctx, s)
if err != nil {
return nil, err
}
if config == nil {
config = new(grafanaCloudConfig)
}
const apiSuffix = "api"
baseURL := strings.ToLower(config.URL)
if strings.HasSuffix(baseURL, apiSuffix) {
baseURL = strings.TrimSuffix(baseURL, apiSuffix)
} else if strings.HasSuffix(baseURL, apiSuffix+"/") {
baseURL = strings.TrimSuffix(baseURL, apiSuffix+"/")
}
b.client, err = grafanclient.New(baseURL, grafanclient.Config{
APIKey: config.Key,
})
if err != nil {
return nil, err
}
return b.client, nil
}
const backendHelp = ``