-
Notifications
You must be signed in to change notification settings - Fork 142
/
stores.go
375 lines (328 loc) · 12.4 KB
/
stores.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/*
Copyright NetFoundry Inc.
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
https://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 db
import (
"context"
"errors"
"github.com/michaelquigley/pfxlog"
"github.com/openziti/foundation/v2/errorz"
"github.com/openziti/storage/ast"
"github.com/openziti/storage/boltz"
"github.com/openziti/ziti/controller/change"
"go.etcd.io/bbolt"
"go4.org/sort"
"reflect"
"sync"
"time"
)
func NewStoreDefinition[E boltz.ExtEntity](strategy boltz.EntityStrategy[E]) boltz.StoreDefinition[E] {
entityType := strategy.NewEntity().GetEntityType()
return boltz.StoreDefinition[E]{
EntityType: entityType,
EntityStrategy: strategy,
BasePath: []string{RootBucket},
EntityNotFoundF: func(id string) error {
return boltz.NewNotFoundError(boltz.GetSingularEntityType(entityType), "id", id)
},
}
}
func (store *Stores) AddCheckable(checkable boltz.Checkable) {
store.lock.Lock()
defer store.lock.Unlock()
store.checkables = append(store.checkables, checkable)
}
func (stores *Stores) GetStoreList() []boltz.Store {
var result []boltz.Store
for _, store := range stores.storeMap {
result = append(result, store)
}
return result
}
func (stores *Stores) CheckIntegrity(db boltz.Db, ctx context.Context, fix bool, errorHandler func(error, bool)) error {
if fix {
changeCtx := boltz.NewMutateContext(ctx)
return db.Update(changeCtx, func(changeCtx boltz.MutateContext) error {
return stores.CheckIntegrityInTx(db, changeCtx, fix, errorHandler)
})
}
return db.View(func(tx *bbolt.Tx) error {
changeCtx := boltz.NewTxMutateContext(ctx, tx)
return stores.CheckIntegrityInTx(db, changeCtx, fix, errorHandler)
})
}
func (stores *Stores) CheckIntegrityInTx(db boltz.Db, ctx boltz.MutateContext, fix bool, errorHandler func(error, bool)) error {
if fix {
pfxlog.Logger().Info("creating database snapshot before attempting to fix data integrity issues")
if err := db.Snapshot(ctx.Tx()); err != nil {
return err
}
}
for _, checkable := range stores.checkables {
if err := checkable.CheckIntegrity(ctx, fix, errorHandler); err != nil {
return err
}
}
return nil
}
type Stores struct {
EventualEventer EventualEventer
internal *stores
Router RouterStore
Service ServiceStore
Terminator TerminatorStore
ApiSession ApiSessionStore
ApiSessionCertificate ApiSessionCertificateStore
AuthPolicy AuthPolicyStore
EventualEvent EventualEventStore
ExternalJwtSigner ExternalJwtSignerStore
Ca CaStore
Config ConfigStore
ConfigType ConfigTypeStore
EdgeRouter EdgeRouterStore
EdgeRouterPolicy EdgeRouterPolicyStore
EdgeService EdgeServiceStore
Identity IdentityStore
IdentityType IdentityTypeStore
Index boltz.Store
Session SessionStore
Revocation RevocationStore
ServiceEdgeRouterPolicy ServiceEdgeRouterPolicyStore
ServicePolicy ServicePolicyStore
TransitRouter TransitRouterStore
Enrollment EnrollmentStore
Authenticator AuthenticatorStore
PostureCheck PostureCheckStore
PostureCheckType PostureCheckTypeStore
Mfa MfaStore
storeMap map[reflect.Type]boltz.Store
lock sync.Mutex
checkables []boltz.Checkable
}
func (stores *Stores) buildStoreMap() {
stores.storeMap = map[reflect.Type]boltz.Store{}
val := reflect.ValueOf(stores).Elem()
for i := 0; i < val.NumField(); i++ {
f := val.Field(i)
if f.CanInterface() {
if store, ok := f.Interface().(boltz.Store); ok && store.GetEntityType() != "indexes" {
entityType := store.GetEntityReflectType()
stores.storeMap[entityType] = store
stores.AddCheckable(store)
}
}
}
}
func (stores *Stores) GetEntityCounts(db boltz.Db) (map[string]int64, error) {
result := map[string]int64{}
for _, store := range stores.storeMap {
err := db.View(func(tx *bbolt.Tx) error {
key := store.GetEntityType()
if store.IsChildStore() {
if _, ok := store.(TransitRouterStore); ok {
// skip transit routers, since count will be == fabric routers
return nil
} else {
key = store.GetEntityType() + ".edge"
}
}
_, count, err := store.QueryIds(tx, "true limit 1")
if err != nil {
return err
}
result[key] = count
return nil
})
if err != nil {
return nil, err
}
}
return result, nil
}
func (stores *Stores) getStoresForInit() []initializableStore {
var result []initializableStore
for _, crudStore := range stores.storeMap {
if store, ok := crudStore.(initializableStore); ok {
result = append(result, store)
}
}
return result
}
func (stores *Stores) GetStoreForEntity(entity boltz.Entity) boltz.Store {
key := reflect.TypeOf(entity)
return stores.storeMap[key]
}
func (stores *Stores) GetStores() []boltz.Store {
var result []boltz.Store
for _, store := range stores.storeMap {
result = append(result, store)
}
return result
}
type stores struct {
EventualEventer EventualEventer
terminator *terminatorStoreImpl
router *routerStoreImpl
service *serviceStoreImpl
apiSession *apiSessionStoreImpl
authPolicy *AuthPolicyStoreImpl
eventualEvent *eventualEventStoreImpl
ca *caStoreImpl
config *configStoreImpl
configType *configTypeStoreImpl
edgeRouter *edgeRouterStoreImpl
edgeRouterPolicy *edgeRouterPolicyStoreImpl
edgeService *edgeServiceStoreImpl
externalJwtSigner *externalJwtSignerStoreImpl
identity *identityStoreImpl
identityType *IdentityTypeStoreImpl
revocation *revocationStoreImpl
serviceEdgeRouterPolicy *serviceEdgeRouterPolicyStoreImpl
servicePolicy *servicePolicyStoreImpl
session *sessionStoreImpl
transitRouter *transitRouterStoreImpl
enrollment *enrollmentStoreImpl
authenticator *authenticatorStoreImpl
postureCheck *postureCheckStoreImpl
postureCheckType *postureCheckTypeStoreImpl
apiSessionCertificate *ApiSessionCertificateStoreImpl
mfa *MfaStoreImpl
}
type DbProvider interface {
GetDb() boltz.Db
}
type DbProviderF func() boltz.Db
func (f DbProviderF) GetDb() boltz.Db {
return f()
}
func InitStores(db boltz.Db) (*Stores, error) {
dbProvider := DbProviderF(func() boltz.Db {
return db
})
errorHolder := &errorz.ErrorHolderImpl{}
internalStores := &stores{}
internalStores.eventualEvent = newEventualEventStore(internalStores)
internalStores.EventualEventer = NewEventualEventerBbolt(dbProvider, internalStores.eventualEvent, 2*time.Second, 1000)
internalStores.router = newRouterStore(internalStores)
internalStores.service = newServiceStore(internalStores)
internalStores.terminator = newTerminatorStore(internalStores)
internalStores.apiSession = newApiSessionStore(internalStores)
internalStores.apiSessionCertificate = newApiSessionCertificateStore(internalStores)
internalStores.authenticator = newAuthenticatorStore(internalStores)
internalStores.authPolicy = newAuthPolicyStore(internalStores)
internalStores.ca = newCaStore(internalStores)
internalStores.config = newConfigsStore(internalStores)
internalStores.configType = newConfigTypesStore(internalStores)
internalStores.edgeRouter = newEdgeRouterStore(internalStores)
internalStores.edgeRouterPolicy = newEdgeRouterPolicyStore(internalStores)
internalStores.edgeService = newEdgeServiceStore(internalStores)
internalStores.externalJwtSigner = newExternalJwtSignerStore(internalStores)
internalStores.transitRouter = newTransitRouterStore(internalStores)
internalStores.identity = newIdentityStore(internalStores)
internalStores.identityType = newIdentityTypeStore(internalStores)
internalStores.enrollment = newEnrollmentStore(internalStores)
internalStores.revocation = newRevocationStore(internalStores)
internalStores.serviceEdgeRouterPolicy = newServiceEdgeRouterPolicyStore(internalStores)
internalStores.servicePolicy = newServicePolicyStore(internalStores)
internalStores.session = newSessionStore(internalStores)
internalStores.postureCheck = newPostureCheckStore(internalStores)
internalStores.postureCheckType = newPostureCheckTypeStore(internalStores)
internalStores.mfa = newMfaStore(internalStores)
externalStores := &Stores{
internal: internalStores,
Terminator: internalStores.terminator,
Router: internalStores.router,
Service: internalStores.service,
ApiSession: internalStores.apiSession,
ApiSessionCertificate: internalStores.apiSessionCertificate,
AuthPolicy: internalStores.authPolicy,
EventualEvent: internalStores.eventualEvent,
Ca: internalStores.ca,
Config: internalStores.config,
ConfigType: internalStores.configType,
EdgeRouter: internalStores.edgeRouter,
EdgeRouterPolicy: internalStores.edgeRouterPolicy,
EdgeService: internalStores.edgeService,
ExternalJwtSigner: internalStores.externalJwtSigner,
TransitRouter: internalStores.transitRouter,
Identity: internalStores.identity,
IdentityType: internalStores.identityType,
Revocation: internalStores.revocation,
ServiceEdgeRouterPolicy: internalStores.serviceEdgeRouterPolicy,
ServicePolicy: internalStores.servicePolicy,
Session: internalStores.session,
Authenticator: internalStores.authenticator,
Enrollment: internalStores.enrollment,
PostureCheck: internalStores.postureCheck,
PostureCheckType: internalStores.postureCheckType,
Mfa: internalStores.mfa,
storeMap: make(map[reflect.Type]boltz.Store),
}
externalStores.EventualEventer = internalStores.EventualEventer
// The Index store is used for querying indexes. It's a convenient store with only a single value (id), which
// is only ever queried using an index set cursor
indexStoreDef := boltz.StoreDefinition[boltz.ExtEntity]{
EntityType: "indexes",
BasePath: []string{RootBucket},
EntityNotFoundF: func(id string) error {
panic(errors.New("programming error"))
},
}
indexStore := boltz.NewBaseStore(indexStoreDef)
indexStore.AddIdSymbol("id", ast.NodeTypeString)
externalStores.Index = indexStore
externalStores.buildStoreMap()
storeList := externalStores.getStoresForInit()
sort.Slice(storeList, func(i, j int) bool {
if storeList[i].IsChildStore() == storeList[j].IsChildStore() {
return storeList[i].GetEntityType() < storeList[j].GetEntityType()
}
return !storeList[i].IsChildStore()
})
mutateCtx := change.New().SetSourceType("system.initialization").SetChangeAuthorType(change.AuthorTypeController).NewMutateContext()
err := dbProvider.GetDb().Update(mutateCtx, func(ctx boltz.MutateContext) error {
for _, store := range storeList {
store.initializeLocal()
}
for _, store := range storeList {
store.initializeLinked()
}
for _, store := range storeList {
store.initializeIndexes(ctx.Tx(), errorHolder)
}
return nil
})
errorHolder.SetError(err)
if errorHolder.HasError() {
return nil, errorHolder.GetError()
}
if err = RunMigrations(db, externalStores); err != nil {
return nil, err
}
return externalStores, nil
}
func newBaseStore[E boltz.ExtEntity](stores *stores, strategy boltz.EntityStrategy[E]) *baseStore[E] {
return &baseStore[E]{
stores: stores,
BaseStore: boltz.NewBaseStore(NewStoreDefinition[E](strategy)),
}
}
func newChildBaseStore[E boltz.ExtEntity](stores *stores, parentMapper func(entity boltz.Entity) boltz.Entity, strategy boltz.EntityStrategy[E], parent boltz.Store, path string) *baseStore[E] {
def := NewStoreDefinition[E](strategy)
def.BasePath = []string{path}
def.Parent = parent
def.ParentMapper = parentMapper
return &baseStore[E]{
stores: stores,
BaseStore: boltz.NewBaseStore[E](def),
}
}