@@ -17,6 +17,8 @@ package util
1717
1818import (
1919 "context"
20+ "fmt"
21+ "os"
2022
2123 "go.mongodb.org/mongo-driver/bson"
2224 "go.mongodb.org/mongo-driver/mongo"
@@ -29,6 +31,7 @@ const (
2931 ErrNotYetInitialized = int32 (94 )
3032 ErrNoReplicationEnabled = int32 (76 )
3133 ErrNotPrimaryOrSecondary = int32 (13436 )
34+ ErrNotUnauthorized = int32 (13 )
3235)
3336
3437// MyState returns the replica set and the instance's state if available.
@@ -37,6 +40,12 @@ func MyState(ctx context.Context, client *mongo.Client) (string, int, error) {
3740
3841 err := client .Database ("admin" ).RunCommand (ctx , bson.M {"replSetGetStatus" : 1 }).Decode (& status )
3942 if err != nil {
43+ if e , ok := err .(mongo.CommandError ); ok {
44+ if e .Code == ErrNotUnauthorized {
45+ fmt .Fprintf (os .Stderr , "unauthorized to run command replSetGetStatus: %v\n " , err )
46+ os .Exit (1 )
47+ }
48+ }
4049 return "" , 0 , err
4150 }
4251
@@ -48,6 +57,12 @@ func MyRole(ctx context.Context, client *mongo.Client) (*proto.HelloResponse, er
4857 var role proto.HelloResponse
4958 err := client .Database ("admin" ).RunCommand (ctx , bson.M {"isMaster" : 1 }).Decode (& role )
5059 if err != nil {
60+ if e , ok := err .(mongo.CommandError ); ok {
61+ if e .Code == ErrNotUnauthorized {
62+ fmt .Fprintf (os .Stderr , "unauthorized to run command isMaster: %v\n " , err )
63+ os .Exit (1 )
64+ }
65+ }
5166 return nil , err
5267 }
5368
@@ -57,6 +72,12 @@ func MyRole(ctx context.Context, client *mongo.Client) (*proto.HelloResponse, er
5772func ReplicasetConfig (ctx context.Context , client * mongo.Client ) (* proto.ReplicasetConfig , error ) {
5873 var rs proto.ReplicasetConfig
5974 if err := client .Database ("admin" ).RunCommand (ctx , bson.M {"replSetGetConfig" : 1 }).Decode (& rs ); err != nil {
75+ if e , ok := err .(mongo.CommandError ); ok {
76+ if e .Code == ErrNotUnauthorized {
77+ fmt .Fprintf (os .Stderr , "unauthorized to run command replSetGetConfig: %v\n " , err )
78+ os .Exit (1 )
79+ }
80+ }
6081 return nil , err
6182 }
6283
0 commit comments