149 lines
4.5 KiB
Go

// query-cdc-probe performs bounded metadata-only CDC capability checks.
// It never writes records or returns customer fields, addresses or resume tokens.
package main
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"os"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type result struct {
At time.Time `json:"at"`
ReplicaSet bool `json:"replicaSet"`
Router bool `json:"router"`
MaxWireVersion int `json:"maxWireVersion"`
Sessions bool `json:"sessions"`
Open bool `json:"streamOpen"`
GetMore bool `json:"streamGetMore"`
Resume bool `json:"streamResume"`
Token bool `json:"resumeTokenObserved"`
Failure string `json:"failure,omitempty"`
}
func classification(err error) string {
if err == nil {
return ""
}
if errors.Is(err, context.DeadlineExceeded) {
return "deadline"
}
var command mongo.CommandError
if errors.As(err, &command) {
switch command.Code {
case 13, 18:
return "authorization"
case 40573:
return "unsupported-topology"
case 286, 280:
return "resume-unavailable"
}
return "mongo-command"
}
return "connection-or-driver"
}
func closeStream(stream *mongo.ChangeStream) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = stream.Close(ctx)
}
func probe(ctx context.Context, db *mongo.Database) result {
out := result{At: time.Now().UTC()}
var hello struct {
SetName string `bson:"setName"`
Msg string `bson:"msg"`
MaxWire int `bson:"maxWireVersion"`
Session *int `bson:"logicalSessionTimeoutMinutes"`
}
if err := db.Client().Database("admin").RunCommand(ctx, bson.D{{Key: "hello", Value: 1}}).Decode(&hello); err != nil {
out.Failure = classification(err)
return out
}
out.ReplicaSet = hello.SetName != ""
out.Router = hello.Msg == "isdbgrid"
out.MaxWireVersion = hello.MaxWire
out.Sessions = hello.Session != nil
// Impossible operation type: capability check without exporting events.
pipeline := mongo.Pipeline{{{Key: "$match", Value: bson.M{"operationType": "__metadata_only_cdc_probe__"}}}, {{Key: "$project", Value: bson.M{"_id": 1}}}}
stream, err := db.Watch(ctx, pipeline, options.ChangeStream().SetMaxAwaitTime(250*time.Millisecond).SetBatchSize(1))
if err != nil {
out.Failure = classification(err)
return out
}
out.Open = true
stream.TryNext(ctx)
if err = stream.Err(); err != nil {
closeStream(stream)
out.Failure = classification(err)
return out
}
out.GetMore = true
token := append(bson.Raw(nil), stream.ResumeToken()...)
out.Token = len(token) > 0
closeCtx, cancel := context.WithTimeout(context.Background(), time.Second)
_ = stream.Close(closeCtx)
cancel()
if !out.Token {
out.Failure = "resume-token-unavailable"
return out
}
resumed, err := db.Watch(ctx, pipeline, options.ChangeStream().SetResumeAfter(token).SetMaxAwaitTime(250*time.Millisecond).SetBatchSize(1))
if err != nil {
out.Failure = classification(err)
return out
}
resumed.TryNext(ctx)
err = resumed.Err()
closeCtx, cancel = context.WithTimeout(context.Background(), time.Second)
_ = resumed.Close(closeCtx)
cancel()
if err != nil {
out.Failure = classification(err)
return out
}
out.Resume = true
return out
}
func main() {
allow := flag.Bool("production-readonly", false, "allow metadata-only checks using explicitly supplied company credentials")
flag.Parse()
uri, name := os.Getenv("MONGO_URI"), os.Getenv("MONGO_DB")
out := result{At: time.Now().UTC()}
if !*allow || uri == "" || name == "" {
out.Failure = "explicit-readonly-configuration-required"
_ = json.NewEncoder(os.Stdout).Encode(out)
os.Exit(2)
}
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
defer cancel()
opts := options.Client().ApplyURI(uri).SetDirect(true).SetServerSelectionTimeout(5 * time.Second).SetConnectTimeout(4 * time.Second).SetMaxPoolSize(2)
if host := os.Getenv("MONGO_TLS_SERVER_NAME"); host != "" {
if opts.TLSConfig == nil {
opts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
}
opts.TLSConfig.ServerName = host
}
client, err := mongo.Connect(ctx, opts)
if err != nil {
out.Failure = classification(err)
} else {
out = probe(ctx, client.Database(name))
closeCtx, stop := context.WithTimeout(context.Background(), time.Second)
_ = client.Disconnect(closeCtx)
stop()
}
_ = json.NewEncoder(os.Stdout).Encode(out)
if !out.Resume {
os.Exit(1)
}
}