Skip to content

Commit

Permalink
TT-7953 use storage library (#244)
Browse files Browse the repository at this point in the history
* Integrated the storage library
  • Loading branch information
sredxny authored Mar 20, 2023
1 parent 5eb9165 commit 1c25e92
Show file tree
Hide file tree
Showing 11 changed files with 84 additions and 102 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ tyk.io.signing.key
*.swp
*~
.terraform**
.DS_Store
46 changes: 19 additions & 27 deletions backends/mongo.go
Original file line number Diff line number Diff line change
@@ -1,48 +1,45 @@
package backends

import (
"context"
"encoding/json"
"github.com/TykTechnologies/storage/persistent"
"github.com/TykTechnologies/storage/persistent/dbm"

"github.com/TykTechnologies/tyk-identity-broker/log"
"github.com/TykTechnologies/tyk-identity-broker/tap"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)

var mongoPrefix = "mongo-backend"
var mongoLogger = log.Get().WithField("prefix", mongoPrefix).Logger

type MongoBackend struct {
Db *mgo.Database
Store persistent.PersistentStorage
Collection string
}

func (m MongoBackend) Init(interface{}) {

}

func (m *MongoBackend) getCollection() *mgo.Collection {
session := m.Db.Session.Copy()
return session.DB("").C(m.Collection)
}

func (m MongoBackend) SetKey(key string, orgId string, value interface{}) error {
profilesCollection := m.getCollection()
defer profilesCollection.Database.Session.Close()

filter := bson.M{"ID": key}
profile := value.(tap.Profile)
filter := dbm.DBM{}
filter["ID"] = key
if orgId != "" {
filter["OrgID"] = orgId
}
// delete if exist, where matches the profile ID and org
err := profilesCollection.Remove(filter)

// delete if exists, where matches the profile ID and org
err := m.Store.Delete(context.Background(), profile, filter)
if err != nil {
if err.Error() != "not found" {
mongoLogger.WithError(err).Error("setting profile in mongo")
}
}

err = profilesCollection.Insert(value)
err = m.Store.Insert(context.Background(), profile)
if err != nil {
mongoLogger.WithError(err).Error("inserting profile in mongo")
}
Expand All @@ -51,16 +48,15 @@ func (m MongoBackend) SetKey(key string, orgId string, value interface{}) error
}

func (m MongoBackend) GetKey(key string, orgId string, val interface{}) error {
profilesCollection := m.getCollection()
defer profilesCollection.Database.Session.Close()

filter := bson.M{"ID": key}
filter := dbm.DBM{}
filter["ID"] = key
if orgId != "" {
filter["OrgID"] = orgId
}

p := tap.Profile{}
err := profilesCollection.Find(filter).One(&p)
err := m.Store.Query(context.Background(), p, &p, filter)
if err != nil {
if err.Error() != "not found" {
mongoLogger.WithError(err).Error("error reading profile from mongo, key:", key)
Expand All @@ -86,14 +82,12 @@ func (m MongoBackend) GetKey(key string, orgId string, val interface{}) error {
func (m MongoBackend) GetAll(orgId string) []interface{} {
var profiles []tap.Profile

filter := bson.M{}
filter := dbm.DBM{}
if orgId != "" {
filter["OrgID"] = orgId
}

profilesCollection := m.getCollection()
defer profilesCollection.Database.Session.Close()
err := profilesCollection.Find(filter).All(&profiles)
err := m.Store.Query(context.Background(), tap.Profile{}, &profiles, filter)
if err != nil {
mongoLogger.Error("error reading profiles from mongo: " + err.Error())
}
Expand All @@ -107,15 +101,13 @@ func (m MongoBackend) GetAll(orgId string) []interface{} {
}

func (m MongoBackend) DeleteKey(key string, orgId string) error {
profilesCollection := m.getCollection()
defer profilesCollection.Database.Session.Close()

filter := bson.M{"ID": key}
filter := dbm.DBM{}
filter["ID"] = key
if orgId != "" {
filter["OrgID"] = orgId
}

err := profilesCollection.Remove(filter)
err := m.Store.Delete(context.Background(), tap.Profile{}, filter)
if err != nil {
mongoLogger.WithError(err).Error("removing profile")
}
Expand Down
1 change: 1 addition & 0 deletions configuration/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ type MongoConf struct {
MaxDocumentSizeBytes int `json:"max_document_size_bytes" mapstructure:"max_document_size_bytes"`
CollectionCapMaxSizeBytes int `json:"collection_cap_max_size_bytes" mapstructure:"collection_cap_max_size_bytes"`
CollectionCapEnable bool `json:"collection_cap_enable" mapstructure:"collection_cap_enable"`
SessionConsistency string `json:"session_consistency" mapstructure:"session_consistency"`
}

// Storage object to configure the storage where the profiles lives in
Expand Down
29 changes: 11 additions & 18 deletions data_loader/data_loader.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
package data_loader

import (
"github.com/sirupsen/logrus"
"gopkg.in/mgo.v2"

"github.com/TykTechnologies/storage/persistent"
"github.com/TykTechnologies/tyk-identity-broker/configuration"
logger "github.com/TykTechnologies/tyk-identity-broker/log"
"github.com/TykTechnologies/tyk-identity-broker/tap"
"github.com/sirupsen/logrus"
)

var log = logger.Get()
Expand All @@ -26,16 +25,6 @@ func reloadDataLoaderLogger() {
dataLogger = dataLogger.Logger.WithField("prefix", dataLoaderLoggerTag)
}

func CreateMongoLoaderFromConnection(db *mgo.Database) DataLoader {
var dataLoader DataLoader

reloadDataLoaderLogger()
dataLogger.Info("Set mongo loader for TIB")
dataLoader = &MongoLoader{Db: db}

return dataLoader
}

func CreateDataLoader(config configuration.Configuration, ProfileFilename string) (DataLoader, error) {
var dataLoader DataLoader
var loaderConf interface{}
Expand All @@ -53,13 +42,17 @@ func CreateDataLoader(config configuration.Configuration, ProfileFilename string
dataLoader = &MongoLoader{}

mongoConf := config.Storage.MongoConf
dialInfo, err := MongoDialInfo(mongoConf.MongoURL, mongoConf.MongoUseSSL, mongoConf.MongoSSLInsecureSkipVerify)
if err != nil {
dataLogger.Error("Error getting mongo settings: " + err.Error())
return nil, err
// map from tib mongo conf structure to persistent.ClientOpts
connectionConf := persistent.ClientOpts{
ConnectionString: mongoConf.MongoURL,
UseSSL: mongoConf.MongoUseSSL,
SSLInsecureSkipVerify: mongoConf.MongoSSLInsecureSkipVerify,
SessionConsistency: mongoConf.SessionConsistency,
Type: persistent.OfficialMongo,
}

loaderConf = MongoLoaderConf{
DialInfo: dialInfo,
ClientOpts: &connectionConf,
}
default:
//default: FILE
Expand Down
52 changes: 14 additions & 38 deletions data_loader/mongo_loader.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package data_loader

import (
"crypto/tls"
"context"
"encoding/json"
"net"
"github.com/TykTechnologies/storage/persistent"
"time"

"gopkg.in/mgo.v2"

"github.com/TykTechnologies/tyk-identity-broker/tap"
)

Expand All @@ -17,13 +15,13 @@ var (

// MongoLoaderConf is the configuration struct for a MongoLoader
type MongoLoaderConf struct {
DialInfo *mgo.DialInfo
ClientOpts *persistent.ClientOpts
}

// MongoLoader implements DataLoader and will load TAP Profiles from a file
type MongoLoader struct {
config MongoLoaderConf
Db *mgo.Database
store persistent.PersistentStorage
SkipFlush bool
}

Expand All @@ -34,25 +32,25 @@ type ProfilesBackup struct {

// Init initialises the mongo loader
func (m *MongoLoader) Init(conf interface{}) error {
m.config = conf.(MongoLoaderConf)
mongoConfig := conf.(MongoLoaderConf)

var err error
session, err := mgo.DialWithInfo(m.config.DialInfo)
store, err := persistent.NewPersistentStorage(mongoConfig.ClientOpts)
if err != nil {
dataLogger.WithError(err).WithField("prefix", mongoPrefix).Error("failed to init MongoDB connection")
time.Sleep(5 * time.Second)
m.Init(conf)
}

m.Db = session.DB("")
m.store = store
return err
}

// LoadIntoStore will load, unmarshal and copy profiles into a an AuthRegisterBackend
func (m *MongoLoader) LoadIntoStore(store tap.AuthRegisterBackend) error {
var profiles []tap.Profile

err := m.Db.C(tap.ProfilesCollectionName).Find(nil).All(&profiles)
err := m.store.Query(context.Background(), tap.Profile{}, &profiles, nil)

if err != nil {
dataLogger.Error("error reading profiles from mongo: " + err.Error())
return err
Expand All @@ -72,18 +70,17 @@ func (m *MongoLoader) LoadIntoStore(store tap.AuthRegisterBackend) error {
// Flush creates a backup of the current loaded config
func (m *MongoLoader) Flush(store tap.AuthRegisterBackend) error {
//read all
//save the changes in the main profiles collection, so empty and store as we dont know what was removed, updated or added
//save the changes in the main profile's collection, so empty and store as we don't know what was removed, updated or added
updatedSet := store.GetAll("")
profilesCollection := m.Db.C(tap.ProfilesCollectionName)

//empty to store new changes
_, err := profilesCollection.RemoveAll(nil)
err := m.store.Delete(context.Background(), tap.Profile{}, nil)
if err != nil {
dataLogger.WithError(err).Error("emptying profiles collection")
return err
}

for i, p := range updatedSet {
for _, p := range updatedSet {
profile := tap.Profile{}
switch p := p.(type) {
case string:
Expand All @@ -92,14 +89,11 @@ func (m *MongoLoader) Flush(store tap.AuthRegisterBackend) error {
dataLogger.WithError(err).Error("un-marshaling interface for mongo flushing")
return err
}
updatedSet[i] = profile
default:
updatedSet[i] = p
profile = p.(tap.Profile)
}
}

if len(updatedSet) > 0 {
err = profilesCollection.Insert(updatedSet...)
m.store.Insert(context.Background(), profile)
if err != nil {
dataLogger.WithError(err).Error("error refreshing profiles records in mongo")
return err
Expand All @@ -108,21 +102,3 @@ func (m *MongoLoader) Flush(store tap.AuthRegisterBackend) error {

return nil
}

func MongoDialInfo(mongoURL string, useSSL bool, SSLInsecureSkipVerify bool) (dialInfo *mgo.DialInfo, err error) {
if dialInfo, err = mgo.ParseURL(mongoURL); err != nil {
return dialInfo, err
}

if useSSL {
dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
tlsConfig := &tls.Config{}
if SSLInsecureSkipVerify {
tlsConfig.InsecureSkipVerify = true
}
return tls.Dial("tcp", addr.String(), tlsConfig)
}
}

return dialInfo, err
}
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.16

require (
github.com/Jeffail/gabs v1.4.0
github.com/TykTechnologies/storage v0.0.0-20230308174156-ed14b745c68b
github.com/TykTechnologies/tyk v1.9.2-0.20211217130848-b04d51712be7
github.com/crewjam/saml v0.4.12
github.com/go-ldap/ldap/v3 v3.2.3
Expand All @@ -20,8 +21,7 @@ require (
github.com/stretchr/testify v1.8.1
github.com/x-cray/logrus-prefixed-formatter v0.5.2
golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43
golang.org/x/text v0.3.6
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22
golang.org/x/text v0.3.7
)

replace github.com/jeffail/tunny => github.com/Jeffail/tunny v0.0.0-20171107125207-452a8e97d6a3
Expand Down
Loading

0 comments on commit 1c25e92

Please sign in to comment.