forked from leesper/couchdb-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
358 lines (299 loc) · 8.34 KB
/
server.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package couchdb
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
var cookieAuthHeader *http.Header
// Server represents a CouchDB server instance.
type Server struct {
resource *Resource
}
// NewServer creates a CouchDB server instance in address urlStr.
func NewServer(urlStr string) (*Server, error) {
return newServer(urlStr, true)
}
// NewServerNoFullCommit creates a CouchDB server instance in address urlStr
// with X-Couch-Full-Commit disabled.
func NewServerNoFullCommit(urlStr string) (*Server, error) {
return newServer(urlStr, false)
}
func newServer(urlStr string, fullCommit bool) (*Server, error) {
res, err := NewResource(urlStr, nil)
if err != nil {
return nil, err
}
s := &Server{
resource: res,
}
if !fullCommit {
s.resource.header.Set("X-Couch-Full-Commit", "false")
}
return s, nil
}
// Config returns the entire CouchDB server configuration as JSON structure.
func (s *Server) Config(node string) (map[string]map[string]string, error) {
_, data, err := s.resource.GetJSON(fmt.Sprintf("_node/%s/_config", node), nil, nil)
if err != nil {
return nil, err
}
var config map[string]map[string]string
err = json.Unmarshal(data, &config)
if err != nil {
return nil, err
}
return config, nil
}
// Version returns the version info about CouchDB instance.
func (s *Server) Version() (string, error) {
var jsonMap map[string]interface{}
_, data, err := s.resource.GetJSON("", nil, nil)
if err != nil {
return "", err
}
err = json.Unmarshal(data, &jsonMap)
if err != nil {
return "", err
}
return jsonMap["version"].(string), nil
}
func (s *Server) String() string {
return fmt.Sprintf("Server %s", s.resource.base)
}
// ActiveTasks lists of running tasks.
func (s *Server) ActiveTasks() ([]interface{}, error) {
var tasks []interface{}
_, data, err := s.resource.GetJSON("_active_tasks", nil, nil)
if err != nil {
return nil, err
}
err = json.Unmarshal(data, &tasks)
if err != nil {
return nil, err
}
return tasks, nil
}
// DBs returns a list of all the databases in the CouchDB server instance.
func (s *Server) DBs() ([]string, error) {
var dbs []string
_, data, err := s.resource.GetJSON("_all_dbs", nil, nil)
if err != nil {
return nil, err
}
err = json.Unmarshal(data, &dbs)
if err != nil {
return nil, err
}
return dbs, nil
}
// Stats returns a JSON object containing the statistics for the running server.
func (s *Server) Stats(node, entry string) (map[string]interface{}, error) {
var stats map[string]interface{}
_, data, err := s.resource.GetJSON(fmt.Sprintf("_node/%s/_stats/%s", node, entry), nil, url.Values{})
if err != nil {
return nil, err
}
err = json.Unmarshal(data, &stats)
if err != nil {
return nil, err
}
return stats, nil
}
// Len returns the number of dbs in CouchDB server instance.
func (s *Server) Len() (int, error) {
dbs, err := s.DBs()
if err != nil {
return -1, err
}
return len(dbs), nil
}
// Create returns a database instance with the given name, returns true if created,
// if database already existed, returns false, *Database will be nil if failed.
func (s *Server) Create(name string) (*Database, error) {
_, _, err := s.resource.PutJSON(name, nil, nil, nil)
// ErrPreconditionFailed means database with the given name already existed
if err != nil && err != ErrPreconditionFailed {
return nil, err
}
db, getErr := s.Get(name)
if getErr != nil {
return nil, getErr
}
return db, err
}
// Delete deletes a database with the given name. Return false if failed.
func (s *Server) Delete(name string) error {
_, _, err := s.resource.DeleteJSON(name, nil, nil)
return err
}
// Get gets a database instance with the given name. Return nil if failed.
func (s *Server) Get(name string) (*Database, error) {
res, err := s.resource.NewResourceWithURL(name)
if err != nil {
return nil, err
}
db, err := NewDatabaseWithResource(res)
if err != nil {
return nil, err
}
_, _, err = db.resource.Head("", nil, nil)
if err != nil {
return nil, err
}
return db, nil
}
// Contains returns true if a db with given name exsited.
func (s *Server) Contains(name string) bool {
_, _, err := s.resource.Head(name, nil, nil)
return err == nil
}
// Membership displays the nodes that are part of the cluster as clusterNodes.
// The field allNodes displays all nodes this node knows about, including the
// ones that are part of cluster.
func (s *Server) Membership() ([]string, []string, error) {
var jsonMap map[string]*json.RawMessage
_, data, err := s.resource.GetJSON("_membership", nil, nil)
if err != nil {
return nil, nil, err
}
err = json.Unmarshal(data, &jsonMap)
if err != nil {
return nil, nil, err
}
var allNodes []string
var clusterNodes []string
err = json.Unmarshal(*jsonMap["all_nodes"], &allNodes)
if err != nil {
return nil, nil, err
}
err = json.Unmarshal(*jsonMap["cluster_nodes"], &clusterNodes)
if err != nil {
return nil, nil, err
}
return allNodes, clusterNodes, nil
}
// Replicate requests, configure or stop a replication operation.
func (s *Server) Replicate(source, target string, options map[string]interface{}) (map[string]interface{}, error) {
var result map[string]interface{}
body := map[string]interface{}{
"source": source,
"target": target,
}
if options != nil {
for k, v := range options {
body[k] = v
}
}
_, data, err := s.resource.PostJSON("_replicate", nil, body, nil)
if err != nil {
return nil, err
}
json.Unmarshal(data, &result)
return result, nil
}
// UUIDs requests one or more Universally Unique Identifiers from the CouchDB instance.
// The response is a JSON object providing a list of UUIDs.
// count - Number of UUIDs to return. Default is 1.
func (s *Server) UUIDs(count int) ([]string, error) {
if count <= 0 {
count = 1
}
values := url.Values{}
values.Set("count", strconv.Itoa(count))
_, data, err := s.resource.GetJSON("_uuids", nil, values)
if err != nil {
return nil, err
}
var jsonMap map[string]*json.RawMessage
err = json.Unmarshal(data, &jsonMap)
if err != nil {
return nil, err
}
var uuids []string
err = json.Unmarshal(*jsonMap["uuids"], &uuids)
if err != nil {
return nil, err
}
return uuids, nil
}
// newResource returns an url string representing a resource under server.
func (s *Server) newResource(resource string) string {
resourceURL, err := s.resource.base.Parse(resource)
if err != nil {
return ""
}
return resourceURL.String()
}
// AddUser adds regular user in authentication database.
// Returns id and rev of the registered user.
func (s *Server) AddUser(name, password string, roles []string) (string, string, error) {
var id, rev string
db, err := s.Get("_users")
if err != nil {
return "", "", err
}
if roles == nil {
roles = []string{}
}
userDoc := map[string]interface{}{
"_id": "org.couchdb.user:" + name,
"name": name,
"password": password,
"roles": roles,
"type": "user",
}
id, rev, err = db.Save(userDoc, nil)
if err != nil {
return id, rev, err
}
return id, rev, nil
}
// Login regular user in CouchDB, returns authentication token.
func (s *Server) Login(name, password string) (string, error) {
body := map[string]interface{}{
"name": name,
"password": password,
}
header, _, err := s.resource.PostJSON("_session", nil, body, nil)
if err != nil {
return "", err
}
tokenPart := strings.Split(header.Get("Set-Cookie"), ";")[0]
token := strings.Split(tokenPart, "=")[1]
setupCookieAuth(token)
return token, err
}
// VerifyToken returns error if user's token is invalid.
func (s *Server) VerifyToken(token string) error {
header := http.Header{}
header.Set("Cookie", strings.Join([]string{"AuthSession", token}, "="))
_, _, err := s.resource.GetJSON("_session", header, nil)
return err
}
// Logout regular user in CouchDB
func (s *Server) Logout(token string) error {
header := http.Header{}
header.Set("Cookie", strings.Join([]string{"AuthSession", token}, "="))
_, _, err := s.resource.DeleteJSON("_session", header, nil)
clearCookieAuth()
return err
}
// RemoveUser removes regular user in authentication database.
func (s *Server) RemoveUser(name string) error {
db, err := s.Get("_users")
if err != nil {
return err
}
docID := "org.couchdb.user:" + name
return db.Delete(docID)
}
func setupCookieAuth(token string) {
cookieAuthHeader = &http.Header{}
cookieAuthHeader.Add("Cookie", fmt.Sprintf("AuthSession=%s", token))
}
func clearCookieAuth() {
cookieAuthHeader = nil
}