@@ -22,13 +22,25 @@ import (
2222 "fmt"
2323 "io/ioutil"
2424 "net/http"
25+ "strconv"
26+ "strings"
27+
28+ "github.com/dgraph-io/dgo"
29+ "github.com/dgraph-io/dgo/protos/api"
30+ "google.golang.org/grpc"
2531)
2632
2733// StateResponse represents the structure of the JSON object returned by calling
2834// the /state endpoint in zero.
2935type StateResponse struct {
3036 Groups map [string ]struct {
31- Members map [string ]interface {} `json:"members"`
37+ Members map [string ]struct {
38+ Addr string `json:"addr"`
39+ GroupID int `json:"groupId"`
40+ ID string `json:"id"`
41+ LastUpdate string `json:"lastUpdate"`
42+ Leader bool `json:"leader"`
43+ } `json:"members"`
3244 Tablets map [string ]struct {
3345 GroupID int `json:"groupId"`
3446 Predicate string `json:"predicate"`
@@ -64,3 +76,39 @@ func GetState() (*StateResponse, error) {
6476 }
6577 return & st , nil
6678}
79+
80+ func GetClientToGroup (groupID string ) (* dgo.Dgraph , error ) {
81+ state , err := GetState ()
82+ if err != nil {
83+ return nil , err
84+ }
85+
86+ group , ok := state .Groups [groupID ]
87+ if ! ok {
88+ return nil , fmt .Errorf ("group %s does not exist" , groupID )
89+ }
90+
91+ if len (group .Members ) == 0 {
92+ return nil , fmt .Errorf ("the group %s has no members" , groupID )
93+ }
94+
95+ member := group .Members ["1" ]
96+ parts := strings .Split (member .Addr , ":" )
97+ if len (parts ) != 2 {
98+ return nil , fmt .Errorf ("the member has an invalid address: %v" , member .Addr )
99+ }
100+ // internalPort is used for communication between alpha nodes
101+ internalPort , err := strconv .Atoi (parts [1 ])
102+ if err != nil {
103+ return nil , fmt .Errorf ("unable to parse the port number from %s" , parts [1 ])
104+ }
105+
106+ // externalPort is for handling connections from clients
107+ externalPort := internalPort + 2000
108+
109+ conn , err := grpc .Dial (fmt .Sprintf ("localhost:%d" , externalPort ), grpc .WithInsecure ())
110+ if err != nil {
111+ return nil , err
112+ }
113+ return dgo .NewDgraphClient (api .NewDgraphClient (conn )), nil
114+ }
0 commit comments