Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 1b5e92fe87
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 226 lines (197 sloc) 5.079 kb
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
package couchbase

import (
"encoding/json"
"errors"
"log"
"net/http"
"net/url"
"runtime"
"sort"
"strings"

"github.com/dustin/gomemcached/client"
)

type poolsResponse struct {
ComponentsVersion map[string]string
ImplementationVersion string
IsAdmin bool `json:"isAdminCreds"`
UUID string
Pools []struct {
Name string
StreamingURI string
URI string
}
}

// A computer in a cluster running the couchbase software.
type Node struct {
ClusterCompatibility int
ClusterMembership string
CouchAPIBase string
Hostname string
InterestingStats map[string]float64
MCDMemoryAllocated float64
MCDMemoryReserved float64
MemoryFree float64
MemoryTotal float64
OS string
Ports map[string]int
Status string
Uptime int `json:"uptime,string"`
Version string
}

// A pool of nodes and buckets.
type Pool struct {
BucketMap map[string]Bucket
Nodes []Node

BucketURL map[string]string `json:"buckets"`

client Client
}

// An individual bucket. Herein lives the most useful stuff.
type Bucket struct {
AuthType string
Capabilities []string `json:"bucketCapabilities"`
CapabilitiesVersion string `json:"bucketCapabilitiesVer"`
Type string `json:"bucketType"`
Name string
NodeLocator string
Nodes []Node
Quota map[string]float64
Replicas int `json:"replicaNumber"`
Password string `json:"saslPassword"`
URI string
VBucketServerMap struct {
HashAlgorithm string
NumReplicas int
ServerList []string
VBucketMap [][]int
}

pool *Pool
connections []*memcached.Client
commonSufix string
}

// Get the (sorted) list of memcached node addresses (hostname:port).
func (b Bucket) NodeAddresses() []string {
rv := make([]string, len(b.VBucketServerMap.ServerList))
copy(rv, b.VBucketServerMap.ServerList)
sort.Strings(rv)
return rv
}

// Get the longest common suffix of all host:port strings in the node list.
func (b Bucket) CommonAddressSuffix() string {
input := []string{}
for _, n := range b.Nodes {
input = append(input, n.Hostname)
}
return FindCommonSuffix(input)
}

// The couchbase client gives access to all the things.
type Client struct {
BaseURL *url.URL
Info poolsResponse
Statuses [256]uint64
}

func (c *Client) parseURLResponse(path string, out interface{}) error {
u := *c.BaseURL
if q := strings.Index(path, "?"); q > 0 {
u.Path = path[:q]
u.RawQuery = path[q+1:]
} else {
u.Path = path
}

res, err := http.Get(u.String())
if err != nil {
return err
}
defer res.Body.Close()

d := json.NewDecoder(res.Body)
if err = d.Decode(&out); err != nil {
return err
}
return nil
}

// Connect to a couchbase cluster.
func Connect(baseU string) (c Client, err error) {
c.BaseURL, err = url.Parse(baseU)
if err != nil {
return
}
err = c.parseURLResponse("/pools", &c.Info)
return
}

func (b *Bucket) refresh() (err error) {
pool := b.pool
err = pool.client.parseURLResponse(b.URI, b)
if err != nil {
return err
}
b.pool = pool
b.connections = make([]*memcached.Client, len(b.VBucketServerMap.ServerList))
return nil
}

func (p *Pool) refresh() (err error) {
p.BucketMap = make(map[string]Bucket)

buckets := []Bucket{}
err = p.client.parseURLResponse(p.BucketURL["uri"], &buckets)
if err != nil {
return err
}
for _, b := range buckets {
b.pool = p
b.connections = make([]*memcached.Client, len(b.VBucketServerMap.ServerList))
p.BucketMap[b.Name] = b
}
return nil
}

// Get a pool from within the couchbase cluster (usually "default").
func (c *Client) GetPool(name string) (p Pool, err error) {
var poolURI string
for _, p := range c.Info.Pools {
if p.Name == name {
poolURI = p.URI
}
}
if poolURI == "" {
return p, errors.New("No pool named " + name)
}
err = c.parseURLResponse(poolURI, &p)

p.client = *c

p.refresh()
return
}

// Mark this bucket as no longer needed, closing connections it may have open.
func (b *Bucket) Close() {
if b.connections != nil {
for _, c := range b.connections {
if c != nil {
c.Close()
}
}
b.connections = nil
}
}

func bucket_finalizer(b *Bucket) {
if b.connections != nil {
log.Printf("Warning: Finalizing a bucket with active connections.")
}
}

// Get a bucket from within this pool.
func (p *Pool) GetBucket(name string) (b *Bucket, err error) {
rv, ok := p.BucketMap[name]
if !ok {
return nil, errors.New("No bucket named " + name)
}
runtime.SetFinalizer(&rv, bucket_finalizer)
return &rv, nil
}

// Convenience function for getting a named bucket from a URL
func GetBucket(endpoint, poolname, bucketname string) (*Bucket, error) {
var err error
client, err := Connect(endpoint)
if err != nil {
return nil, err
}

pool, err := client.GetPool("default")
if err != nil {
return nil, err
}

return pool.GetBucket("default")
}
Something went wrong with that request. Please try again.