-
Notifications
You must be signed in to change notification settings - Fork 54
/
connection.go
237 lines (216 loc) · 5.5 KB
/
connection.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package gremlin
import (
"encoding/base64"
"encoding/json"
"errors"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/gorilla/websocket"
)
// Clients include the necessary info to connect to the server and the underlying socket
type Client struct {
Remote *url.URL
Ws *websocket.Conn
Auth []OptAuth
}
func NewClient(urlStr string, options ...OptAuth) (*Client, error) {
r, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
dialer := websocket.Dialer{}
ws, _, err := dialer.Dial(urlStr, http.Header{})
if err != nil {
return nil, err
}
return &Client{Remote: r, Ws: ws, Auth: options}, nil
}
// Client executes the provided request
func (c *Client) ExecQuery(query string) ([]byte, error) {
req := Query(query)
return c.Exec(req)
}
func (c *Client) Exec(req *Request) ([]byte, error) {
requestMessage, err := GraphSONSerializer(req)
if err != nil {
return nil, err
}
// Open a TCP connection
if err = c.Ws.WriteMessage(websocket.BinaryMessage, requestMessage); err != nil {
print("error", err)
return nil, err
}
return c.ReadResponse()
}
func (c *Client) ReadResponse() (data []byte, err error) {
// Data buffer
var message []byte
var dataItems []json.RawMessage
inBatchMode := false
// Receive data
for {
if _, message, err = c.Ws.ReadMessage(); err != nil {
return
}
var res *Response
if err = json.Unmarshal(message, &res); err != nil {
return
}
var items []json.RawMessage
switch res.Status.Code {
case StatusNoContent:
return
case StatusAuthenticate:
return c.Authenticate(res.RequestId)
case StatusPartialContent:
inBatchMode = true
if err = json.Unmarshal(res.Result.Data, &items); err != nil {
return
}
dataItems = append(dataItems, items...)
case StatusSuccess:
if inBatchMode {
if err = json.Unmarshal(res.Result.Data, &items); err != nil {
return
}
dataItems = append(dataItems, items...)
data, err = json.Marshal(dataItems)
} else {
data = res.Result.Data
}
return
default:
if msg, exists := ErrorMsg[res.Status.Code]; exists {
err = errors.New(msg)
} else {
err = errors.New("An unknown error occured")
}
return
}
}
return
}
// AuthInfo includes all info related with SASL authentication with the Gremlin server
// ChallengeId is the requestID in the 407 status (AUTHENTICATE) response given by the server.
// We have to send an authentication request with that same RequestID in order to solve the challenge.
type AuthInfo struct {
ChallengeId string
User string
Pass string
}
type OptAuth func(*AuthInfo) error
// Constructor for different authentication possibilities
func NewAuthInfo(options ...OptAuth) (*AuthInfo, error) {
auth := &AuthInfo{}
for _, op := range options {
err := op(auth)
if err != nil {
return nil, err
}
}
return auth, nil
}
// Sets authentication info from environment variables GREMLIN_USER and GREMLIN_PASS
func OptAuthEnv() OptAuth {
return func(auth *AuthInfo) error {
user, ok := os.LookupEnv("GREMLIN_USER")
if !ok {
return errors.New("Variable GREMLIN_USER is not set")
}
pass, ok := os.LookupEnv("GREMLIN_PASS")
if !ok {
return errors.New("Variable GREMLIN_PASS is not set")
}
auth.User = user
auth.Pass = pass
return nil
}
}
// Sets authentication information from username and password
func OptAuthUserPass(user, pass string) OptAuth {
return func(auth *AuthInfo) error {
auth.User = user
auth.Pass = pass
return nil
}
}
// Authenticates the connection
func (c *Client) Authenticate(requestId string) ([]byte, error) {
auth, err := NewAuthInfo(c.Auth...)
if err != nil {
return nil, err
}
var sasl []byte
sasl = append(sasl, 0)
sasl = append(sasl, []byte(auth.User)...)
sasl = append(sasl, 0)
sasl = append(sasl, []byte(auth.Pass)...)
saslEnc := base64.StdEncoding.EncodeToString(sasl)
args := &RequestArgs{Sasl: saslEnc}
authReq := &Request{
RequestId: requestId,
Processor: "trasversal",
Op: "authentication",
Args: args,
}
return c.Exec(authReq)
}
var servers []*url.URL
func NewCluster(s ...string) (err error) {
servers = nil
// If no arguments use environment variable
if len(s) == 0 {
connString := strings.TrimSpace(os.Getenv("GREMLIN_SERVERS"))
if connString == "" {
err = errors.New("No servers set. Configure servers to connect to using the GREMLIN_SERVERS environment variable.")
return
}
servers, err = SplitServers(connString)
return
}
// Else use the supplied servers
for _, v := range s {
var u *url.URL
if u, err = url.Parse(v); err != nil {
return
}
servers = append(servers, u)
}
return
}
func SplitServers(connString string) (servers []*url.URL, err error) {
serverStrings := strings.Split(connString, ",")
if len(serverStrings) < 1 {
err = errors.New("Connection string is not in expected format. An example of the expected format is 'ws://server1:8182, ws://server2:8182'.")
return
}
for _, serverString := range serverStrings {
var u *url.URL
if u, err = url.Parse(strings.TrimSpace(serverString)); err != nil {
return
}
servers = append(servers, u)
}
return
}
func CreateConnection() (conn net.Conn, server *url.URL, err error) {
connEstablished := false
for _, s := range servers {
c, err := net.DialTimeout("tcp", s.Host, 1*time.Second)
if err != nil {
continue
}
connEstablished = true
conn = c
server = s
break
}
if !connEstablished {
err = errors.New("Could not establish connection. Please check your connection string and ensure at least one server is up.")
}
return
}