-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigrator.go
99 lines (88 loc) · 2.22 KB
/
migrator.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
package main
import (
"context"
"os"
"os/signal"
"syscall"
"github.com/evergreen-ci/evergreen-migrations/migrations"
"github.com/mongodb/grip"
"github.com/pkg/errors"
"github.com/urfave/cli"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
urlFlag = "url"
dbFlag = "db"
scriptFlag = "script"
collectionFlag = "collection"
batchSizeFlag = "batch-size"
skipDBAuthFlag = "skip-db-auth"
awsAuthMechanism = "MONGODB-AWS"
mongoExternalAuthSource = "$external"
)
func main() {
app := cli.NewApp()
app.Name = "migrator"
app.Usage = "Run migrations against a database"
app.Flags = []cli.Flag{
cli.StringFlag{
Name: urlFlag,
Usage: "Database URL",
Required: true,
},
cli.StringFlag{
Name: dbFlag,
Usage: "Database name",
Required: true,
},
cli.StringFlag{
Name: scriptFlag,
Usage: "Name of the script to run",
Required: true,
},
cli.StringFlag{
Name: collectionFlag,
Usage: "Collection to run the script against",
},
cli.IntFlag{
Name: batchSizeFlag,
Usage: "Batch size for the script to process at once",
},
cli.BoolFlag{
Name: skipDBAuthFlag,
Usage: "Connect to the database without authorization, for local testing",
},
}
app.Action = func(c *cli.Context) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
exitCh := make(chan os.Signal, 1)
signal.Notify(exitCh, syscall.SIGTERM)
<-exitCh
cancel()
}()
clientOps := options.Client().ApplyURI(c.String(urlFlag))
if !c.Bool(skipDBAuthFlag) {
clientOps.SetAuth(options.Credential{
AuthMechanism: awsAuthMechanism,
AuthSource: mongoExternalAuthSource,
})
}
client, err := mongo.Connect(ctx, clientOps)
if err != nil {
return errors.Wrap(err, "getting mongo client")
}
migration, err := migrations.Registry.Migration(c.String(scriptFlag), migrations.MigrationOptions{
Database: c.String(dbFlag),
Collection: c.String(collectionFlag),
BatchSize: c.Int(batchSizeFlag),
})
if err != nil {
return errors.Wrap(err, "getting migration script")
}
return migration.Execute(ctx, client)
}
grip.EmergencyFatal(app.Run(os.Args))
}