github.com/wormhole-foundation/wormhole-explorer/common@v0.0.0-20240604151348-09585b5b97c5/health/mongo.go (about) 1 package health 2 3 import ( 4 "context" 5 "fmt" 6 7 "github.com/pkg/errors" 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/mongo" 10 ) 11 12 type mongoStatus struct { 13 Ok int32 `bson:"ok"` 14 Host string `bson:"host"` 15 Version string `bson:"version"` 16 Process string `bson:"process"` 17 Pid int32 `bson:"pid"` 18 Uptime int32 `bson:"uptime"` 19 Connections *mongoConnections `bson:"connections"` 20 } 21 22 // mongoConnections represents a mongo server connection. 23 type mongoConnections struct { 24 Current int32 `bson:"current"` 25 Available int32 `bson:"available"` 26 TotalCreated int32 `bson:"totalCreated"` 27 } 28 29 func Mongo(db *mongo.Database) Check { 30 return func(ctx context.Context) error { 31 command := bson.D{{Key: "serverStatus", Value: 1}} 32 result := db.RunCommand(ctx, command) 33 if result.Err() != nil { 34 return errors.WithStack(result.Err()) 35 } 36 37 var mongoStatus mongoStatus 38 err := result.Decode(&mongoStatus) 39 if err != nil { 40 return errors.WithStack(err) 41 } 42 // check mongo server status 43 mongoStatusCheck := (mongoStatus.Ok == 1 && mongoStatus.Pid > 0 && mongoStatus.Uptime > 0) 44 if !mongoStatusCheck { 45 return fmt.Errorf("mongo server not ready (Ok = %v, Pid = %v, Uptime = %v)", mongoStatus.Ok, mongoStatus.Pid, mongoStatus.Uptime) 46 } 47 48 // check mongo connections 49 if mongoStatus.Connections.Available <= 0 { 50 return fmt.Errorf("mongo server without available connections (availableConection = %v)", mongoStatus.Connections.Available) 51 } 52 return nil 53 } 54 }