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
|
// Copyright 2021 Northern.tech AS
//
// 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 migrate
import (
"context"
"time"
"github.com/mendersoftware/go-lib-micro/store"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
mopts "go.mongodb.org/mongo-driver/mongo/options"
)
// this is a small internal data layer for the migration utils, may be shared by diff migrators
const (
DbMigrationsColl = "migration_info"
)
type MigrationEntry struct {
Version Version `bson:"version"`
Timestamp time.Time `bson:"timestamp"`
}
// GetMigrationInfo retrieves a list of migrations applied to the db.
// On success the function returns the MigrationEntries present in the db
// sorted by the version in decending order.
func GetMigrationInfo(ctx context.Context, sess *mongo.Client, db string) ([]MigrationEntry, error) {
c := sess.Database(db).Collection(DbMigrationsColl)
findOpts := mopts.Find()
findOpts.SetSort(bson.D{{
Key: "version.major", Value: -1,
}, {
Key: "version.minor", Value: -1,
}, {
Key: "version.patch", Value: -1,
}})
cursor, err := c.Find(ctx, bson.M{
"version": bson.M{"$exists": true},
}, findOpts)
if cursor == nil || err != nil {
return nil, errors.Wrap(err, "db: failed to get migration info")
}
var infoArray []MigrationEntry
err = cursor.All(ctx, &infoArray)
return infoArray, err
}
// UpdateMigrationInfo inserts a migration entry in the migration info collection.
func UpdateMigrationInfo(ctx context.Context, version Version, sess *mongo.Client, db string) error {
c := sess.Database(db).Collection(DbMigrationsColl)
entry := MigrationEntry{
Version: version,
Timestamp: time.Now(),
}
_, err := c.InsertOne(ctx, entry)
if err != nil {
return errors.Wrap(err, "db: failed to insert migration info")
}
// result.InsertedID (InsertOneResult)
return nil
}
func GetTenantDbs(ctx context.Context, client *mongo.Client, matcher store.TenantDbMatchFunc) ([]string, error) {
result, err := client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
return nil, err
}
tenantDbs := make([]string, len(result))
j := 0
for _, db := range result {
if matcher(db) {
tenantDbs[j] = db
j++
}
}
tenantDbs = tenantDbs[:j]
return tenantDbs, nil
}
|