pax_global_header00006660000000000000000000000064152071240270014512gustar00rootroot0000000000000052 comment=7f9ffa5c48b738f8965f2d9e0f10874087a37cd5 golang-github-rainycape-memcache-0.0~git20150622.1031fa0/000077500000000000000000000000001520712402700223075ustar00rootroot00000000000000golang-github-rainycape-memcache-0.0~git20150622.1031fa0/.gitignore000066400000000000000000000000141520712402700242720ustar00rootroot00000000000000_* *.out *~ golang-github-rainycape-memcache-0.0~git20150622.1031fa0/LICENSE000066400000000000000000000260741520712402700233250ustar00rootroot00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. golang-github-rainycape-memcache-0.0~git20150622.1031fa0/README.md000066400000000000000000000056751520712402700236030ustar00rootroot00000000000000Memcache Client in Go (golang) ============================= ## Installing $ go get github.com/rainycape/memcache After this command *memcache* is ready to use. Its source will be in: $GOPATH/src/github.com/rainycape/memcache You can use `go get -u -a` for update all installed packages. ## Example import ( "github.com/rainycape/memcache" ) func main() { mc := memcache.New("10.0.0.1:11211", "10.0.0.2:11211", "10.0.0.3:11212") mc.Set(&memcache.Item{Key: "foo", Value: []byte("my value")}) it, err := mc.Get("foo") ... } ## About This is a memcache client library for the Go programming language (http://golang.org/). This is a high performance fork of the original library at http://github.com/bradfitz/gomemcache. The following is a comparison between the original library and this one: benchmark old ns/op new ns/op delta BenchmarkSetGet 214443 138200 -35.55% BenchmarkSetGetLarge 262164 146594 -44.08% BenchmarkConcurrentSetGetSmall10_100 82561221 51282962 -37.88% BenchmarkConcurrentSetGetLarge10_100 96067285 63887183 -33.50% BenchmarkConcurrentSetGetSmall20_100 152834658 75607154 -50.53% BenchmarkConcurrentSetGetLarge20_100 202574186 96010615 -52.60% benchmark old MB/s new MB/s speedup BenchmarkSetGet 0.03 0.04 1.33x BenchmarkSetGetLarge 4.82 8.62 1.79x BenchmarkConcurrentSetGetSmall10_100 0.07 0.12 1.71x BenchmarkConcurrentSetGetLarge10_100 13.16 19.78 1.50x BenchmarkConcurrentSetGetSmall20_100 0.08 0.16 2.00x BenchmarkConcurrentSetGetLarge20_100 12.48 26.33 2.11x benchmark old allocs new allocs delta BenchmarkSetGet 18 6 -66.67% BenchmarkSetGetLarge 19 6 -68.42% BenchmarkConcurrentSetGetSmall10_100 58469 6199 -89.40% BenchmarkConcurrentSetGetLarge10_100 59848 6196 -89.65% BenchmarkConcurrentSetGetSmall20_100 117177 12432 -89.39% BenchmarkConcurrentSetGetLarge20_100 120173 12413 -89.67% benchmark old bytes new bytes delta BenchmarkSetGet 2479 170 -93.14% BenchmarkSetGetLarge 7537 1184 -84.29% BenchmarkConcurrentSetGetSmall10_100 3101520 187245 -93.96% BenchmarkConcurrentSetGetLarge10_100 8330341 1197783 -85.62% BenchmarkConcurrentSetGetSmall20_100 6318072 374977 -94.07% BenchmarkConcurrentSetGetLarge20_100 16884200 2398491 -85.79% golang-github-rainycape-memcache-0.0~git20150622.1031fa0/addr.go000066400000000000000000000003761520712402700235560ustar00rootroot00000000000000package memcache import ( "net" ) type Addr struct { net.Addr s string n string } func (a *Addr) String() string { return a.s } func NewAddr(addr net.Addr) *Addr { return &Addr{ Addr: addr, s: addr.String(), n: addr.Network(), } } golang-github-rainycape-memcache-0.0~git20150622.1031fa0/bench_test.go000066400000000000000000000055401520712402700247600ustar00rootroot00000000000000package memcache import ( "runtime" "strings" "sync" "testing" "time" ) func benchmarkSet(b *testing.B, item *Item) { cmd, c := newUnixServer(b) c.SetTimeout(time.Duration(-1)) b.SetBytes(int64(len(item.Key) + len(item.Value))) b.ResetTimer() for i := 0; i < b.N; i++ { if err := c.Set(item); err != nil { b.Fatal(err) } } b.StopTimer() cmd.Process.Kill() cmd.Wait() } func benchmarkSetGet(b *testing.B, item *Item) { cmd, c := newUnixServer(b) c.SetTimeout(time.Duration(-1)) key := item.Key b.SetBytes(int64(len(item.Key) + len(item.Value))) b.ResetTimer() for i := 0; i < b.N; i++ { if err := c.Set(item); err != nil { b.Fatal(err) } if _, err := c.Get(key); err != nil { b.Fatal(err) } } b.StopTimer() cmd.Process.Kill() cmd.Wait() } func largeItem() *Item { key := strings.Repeat("f", 240) value := make([]byte, 1024) return &Item{Key: key, Value: value} } func smallItem() *Item { return &Item{Key: "foo", Value: []byte("bar")} } func BenchmarkSet(b *testing.B) { benchmarkSet(b, smallItem()) } func BenchmarkSetLarge(b *testing.B) { benchmarkSet(b, largeItem()) } func BenchmarkSetGet(b *testing.B) { benchmarkSetGet(b, smallItem()) } func BenchmarkSetGetLarge(b *testing.B) { benchmarkSetGet(b, largeItem()) } func benchmarkConcurrentSetGet(b *testing.B, item *Item, count int, opcount int) { mp := runtime.GOMAXPROCS(0) defer runtime.GOMAXPROCS(mp) runtime.GOMAXPROCS(count) cmd, c := newUnixServer(b) c.SetTimeout(time.Duration(-1)) // Items are not thread safe items := make([]*Item, count) for ii := range items { items[ii] = &Item{Key: item.Key, Value: item.Value} } b.SetBytes(int64((len(item.Key) + len(item.Value)) * count * opcount)) b.ResetTimer() for i := 0; i < b.N; i++ { var wg sync.WaitGroup wg.Add(count) for j := 0; j < count; j++ { it := items[j] key := it.Key go func() { defer wg.Done() for k := 0; k < opcount; k++ { if err := c.Set(it); err != nil { b.Fatal(err) } if _, err := c.Get(key); err != nil { b.Fatal(err) } } }() } wg.Wait() } b.StopTimer() cmd.Process.Kill() cmd.Wait() } func BenchmarkGetCacheMiss(b *testing.B) { key := "not" cmd, c := newUnixServer(b) c.SetTimeout(time.Duration(-1)) c.Delete(key) b.ResetTimer() for i := 0; i < b.N; i++ { if _, err := c.Get(key); err != ErrCacheMiss { b.Fatal(err) } } b.StopTimer() cmd.Process.Kill() cmd.Wait() } func BenchmarkConcurrentSetGetSmall10_100(b *testing.B) { benchmarkConcurrentSetGet(b, smallItem(), 10, 100) } func BenchmarkConcurrentSetGetLarge10_100(b *testing.B) { benchmarkConcurrentSetGet(b, largeItem(), 10, 100) } func BenchmarkConcurrentSetGetSmall20_100(b *testing.B) { benchmarkConcurrentSetGet(b, smallItem(), 20, 100) } func BenchmarkConcurrentSetGetLarge20_100(b *testing.B) { benchmarkConcurrentSetGet(b, largeItem(), 20, 100) } golang-github-rainycape-memcache-0.0~git20150622.1031fa0/io.go000066400000000000000000000011701520712402700232440ustar00rootroot00000000000000package memcache import ( "io" ) // readAtLeast is an optimized version of io.ReadAtLeast, // which omits some checks that don't need to be performed // when called from Read() in this package. func readAtLeast(r io.Reader, buf []byte, min int) error { var n int var err error // Most common case, we get all the bytes in one read if n, err = r.Read(buf); n == min { return nil } if err != nil { return err } // Fall back to looping var nn int for n < min { nn, err = r.Read(buf[n:]) if err != nil { if err == io.EOF && n > 0 { err = io.ErrUnexpectedEOF } return err } n += nn } return nil } golang-github-rainycape-memcache-0.0~git20150622.1031fa0/memcache.go000066400000000000000000000457521520712402700244150ustar00rootroot00000000000000/* Copyright 2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package memcache provides a client for the memcached cache server. package memcache import ( "bytes" "encoding/binary" "errors" "io" "io/ioutil" "net" "runtime" "sync" "time" ) // Similar to: // http://code.google.com/appengine/docs/go/memcache/reference.html var ( // ErrCacheMiss means that a Get failed because the item wasn't present. ErrCacheMiss = errors.New("memcache: cache miss") // ErrCASConflict means that a CompareAndSwap call failed due to the // cached value being modified between the Get and the CompareAndSwap. // If the cached value was simply evicted rather than replaced, // ErrNotStored will be returned instead. ErrCASConflict = errors.New("memcache: compare-and-swap conflict") // ErrNotStored means that a conditional write operation (i.e. Add or // CompareAndSwap) failed because the condition was not satisfied. ErrNotStored = errors.New("memcache: item not stored") // ErrServer means that a server error occurred. ErrServerError = errors.New("memcache: server error") // ErrNoStats means that no statistics were available. ErrNoStats = errors.New("memcache: no statistics available") // ErrMalformedKey is returned when an invalid key is used. // Keys must be at maximum 250 bytes long, ASCII, and not // contain whitespace or control characters. ErrMalformedKey = errors.New("malformed: key is too long or contains invalid characters") // ErrNoServers is returned when no servers are configured or available. ErrNoServers = errors.New("memcache: no servers configured or available") // ErrBadMagic is returned when the magic number in a response is not valid. ErrBadMagic = errors.New("memcache: bad magic number in response") // ErrBadIncrDec is returned when performing a incr/decr on non-numeric values. ErrBadIncrDec = errors.New("memcache: incr or decr on non-numeric value") putUint16 = binary.BigEndian.PutUint16 putUint32 = binary.BigEndian.PutUint32 putUint64 = binary.BigEndian.PutUint64 bUint16 = binary.BigEndian.Uint16 bUint32 = binary.BigEndian.Uint32 bUint64 = binary.BigEndian.Uint64 ) // DefaultTimeout is the default socket read/write timeout. const DefaultTimeout = time.Duration(100) * time.Millisecond const ( buffered = 8 // arbitrary buffered channel size, for readability maxIdleConnsPerAddr = 2 // TODO(bradfitz): make this configurable? ) type command uint8 const ( cmdGet = iota cmdSet cmdAdd cmdReplace cmdDelete cmdIncr cmdDecr cmdQuit cmdFlush cmdGetQ cmdNoop cmdVersion cmdGetK cmdGetKQ cmdAppend cmdPrepend cmdStat cmdSetQ cmdAddQ cmdReplaceQ cmdDeleteQ cmdIncrementQ cmdDecrementQ cmdQuitQ cmdFlushQ cmdAppendQ cmdPrependQ ) type response uint16 const ( respOk = iota respKeyNotFound respKeyExists respValueTooLarge respInvalidArgs respItemNotStored respInvalidIncrDecr respWrongVBucket respAuthErr respAuthContinue respUnknownCmd = 0x81 respOOM = 0x82 respNotSupported = 0x83 respInternalErr = 0x85 respBusy = 0x85 respTemporaryErr = 0x86 ) func (r response) asError() error { switch r { case respKeyNotFound: return ErrCacheMiss case respKeyExists: return ErrNotStored case respInvalidIncrDecr: return ErrBadIncrDec case respItemNotStored: return ErrNotStored } return r } func (r response) Error() string { switch r { case respOk: return "Ok" case respKeyNotFound: return "key not found" case respKeyExists: return "key already exists" case respValueTooLarge: return "value too large" case respInvalidArgs: return "invalid arguments" case respItemNotStored: return "item not stored" case respInvalidIncrDecr: return "incr/decr on non-numeric value" case respWrongVBucket: return "wrong vbucket" case respAuthErr: return "auth error" case respAuthContinue: return "auth continue" } return "" } const ( reqMagic uint8 = 0x80 respMagic uint8 = 0x81 ) func legalKey(key string) bool { if len(key) > 250 { return false } for i := 0; i < len(key); i++ { if key[i] <= ' ' || key[i] > 0x7e { return false } } return true } func poolSize() int { s := 8 if mp := runtime.GOMAXPROCS(0); mp > s { s = mp } return s } // New returns a memcache client using the provided server(s) // with equal weight. If a server is listed multiple times, // it gets a proportional amount of weight. func New(server ...string) (*Client, error) { servers, err := NewServerList(server...) if err != nil { return nil, err } return NewFromServers(servers), nil } // NewFromServers returns a new Client using the provided Servers. func NewFromServers(servers Servers) *Client { return &Client{ timeout: DefaultTimeout, maxIdlePerAddr: maxIdleConnsPerAddr, servers: servers, freeconn: make(map[string]chan *conn), bufPool: make(chan []byte, poolSize()), } } // Client is a memcache client. // It is safe for unlocked use by multiple concurrent goroutines. type Client struct { timeout time.Duration maxIdlePerAddr int servers Servers mu sync.RWMutex freeconn map[string]chan *conn bufPool chan []byte } // Timeout returns the socket read/write timeout. By default, it's // DefaultTimeout. func (c *Client) Timeout() time.Duration { return c.timeout } // SetTimeout specifies the socket read/write timeout. // If zero, DefaultTimeout is used. If < 0, there's // no timeout. This method must be called before any // connections to the memcached server are opened. func (c *Client) SetTimeout(timeout time.Duration) { if timeout == time.Duration(0) { timeout = DefaultTimeout } c.timeout = timeout } // MaxIdleConnsPerAddr returns the maximum number of idle // connections kept per server address. func (c *Client) MaxIdleConnsPerAddr() int { return c.maxIdlePerAddr } // SetMaxIdleConnsPerAddr changes the maximum number of // idle connections kept per server. If maxIdle < 0, // no idle connections are kept. If maxIdle == 0, // the default number (currently 2) is used. func (c *Client) SetMaxIdleConnsPerAddr(maxIdle int) { if maxIdle == 0 { maxIdle = maxIdleConnsPerAddr } c.mu.Lock() defer c.mu.Unlock() c.maxIdlePerAddr = maxIdle if maxIdle > 0 { freeconn := make(map[string]chan *conn) for k, v := range c.freeconn { ch := make(chan *conn, maxIdle) ChanDone: for { select { case cn := <-v: select { case ch <- cn: default: cn.nc.Close() } default: freeconn[k] = ch break ChanDone } } } c.freeconn = freeconn } else { c.closeIdleConns() c.freeconn = nil } } // Close closes all currently open connections. func (c *Client) Close() error { c.mu.Lock() defer c.mu.Unlock() c.closeIdleConns() c.freeconn = nil c.maxIdlePerAddr = 0 return nil } // Item is an item to be got or stored in a memcached server. type Item struct { // Key is the Item's key (250 bytes maximum). Key string // Value is the Item's value. Value []byte // Object is the Item's value for use with a Codec. Object interface{} // Flags are server-opaque flags whose semantics are entirely // up to the app. Flags uint32 // Expiration is the cache expiration time, in seconds: either a relative // time from now (up to 1 month), or an absolute Unix epoch time. // Zero means the Item has no expiration time. Expiration int32 // Compare and swap ID. casid uint64 } // conn is a connection to a server. type conn struct { nc net.Conn addr *Addr } // condRelease releases this connection if the error pointed to by err // is is nil (not an error) or is only a protocol level error (e.g. a // cache miss). The purpose is to not recycle TCP connections that // are bad. func (c *Client) condRelease(cn *conn, err *error) { switch *err { case nil, ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrBadIncrDec: c.putFreeConn(cn) default: cn.nc.Close() } } func (c *Client) closeIdleConns() { for _, v := range c.freeconn { NextIdle: for { select { case cn := <-v: cn.nc.Close() default: break NextIdle } } } } func (c *Client) putFreeConn(cn *conn) { c.mu.RLock() freelist := c.freeconn[cn.addr.s] maxIdle := c.maxIdlePerAddr c.mu.RUnlock() if freelist == nil && maxIdle > 0 { freelist = make(chan *conn, maxIdle) c.mu.Lock() c.freeconn[cn.addr.s] = freelist c.mu.Unlock() } select { case freelist <- cn: break default: cn.nc.Close() } } func (c *Client) getFreeConn(addr *Addr) *conn { c.mu.RLock() freelist := c.freeconn[addr.s] c.mu.RUnlock() if freelist == nil { return nil } select { case cn := <-freelist: return cn default: return nil } } // ConnectTimeoutError is the error type used when it takes // too long to connect to the desired host. This level of // detail can generally be ignored. type ConnectTimeoutError struct { Addr net.Addr } func (cte *ConnectTimeoutError) Error() string { return "memcache: connect timeout to " + cte.Addr.String() } func (cte *ConnectTimeoutError) Timeout() bool { return true } func (cte *ConnectTimeoutError) Temporary() bool { return true } func (c *Client) dial(addr *Addr) (net.Conn, error) { if c.timeout > 0 { conn, err := net.DialTimeout(addr.n, addr.s, c.timeout) if err != nil { if ne, ok := err.(net.Error); ok && ne.Timeout() { return nil, &ConnectTimeoutError{addr} } return nil, err } return conn, nil } return net.Dial(addr.n, addr.s) } func (c *Client) getConn(addr *Addr) (*conn, error) { cn := c.getFreeConn(addr) if cn == nil { nc, err := c.dial(addr) if err != nil { return nil, err } cn = &conn{ nc: nc, addr: addr, } } if c.timeout > 0 { cn.nc.SetDeadline(time.Now().Add(c.timeout)) } return cn, nil } // Get gets the item for the given key. ErrCacheMiss is returned for a // memcache cache miss. The key must be at most 250 bytes in length. func (c *Client) Get(key string) (*Item, error) { cn, err := c.sendCommand(key, cmdGet, nil, 0, nil) if err != nil { return nil, err } return c.parseItemResponse(key, cn, true) } func (c *Client) sendCommand(key string, cmd command, value []byte, casid uint64, extras []byte) (*conn, error) { addr, err := c.servers.PickServer(key) if err != nil { return nil, err } cn, err := c.getConn(addr) if err != nil { return nil, err } err = c.sendConnCommand(cn, key, cmd, value, casid, extras) if err != nil { cn.nc.Close() return nil, err } return cn, err } func (c *Client) sendConnCommand(cn *conn, key string, cmd command, value []byte, casid uint64, extras []byte) (err error) { var buf []byte select { // 24 is header size case buf = <-c.bufPool: buf = buf[:24] default: buf = make([]byte, 24, 24+len(key)+len(extras)) // Magic (0) buf[0] = reqMagic } // Command (1) buf[1] = byte(cmd) kl := len(key) el := len(extras) // Key length (2-3) putUint16(buf[2:], uint16(kl)) // Extras length (4) buf[4] = byte(el) // Data type (5), always zero // VBucket (6-7), always zero // Total body length (8-11) vl := len(value) bl := uint32(kl + el + vl) putUint32(buf[8:], bl) // Opaque (12-15), always zero // CAS (16-23) putUint64(buf[16:], casid) // Extras if el > 0 { buf = append(buf, extras...) } if kl > 0 { // Key itself buf = append(buf, stobs(key)...) } if _, err = cn.nc.Write(buf); err != nil { return err } select { case c.bufPool <- buf: default: } if vl > 0 { if _, err = cn.nc.Write(value); err != nil { return err } } return nil } func (c *Client) parseResponse(rKey string, cn *conn) ([]byte, []byte, []byte, []byte, error) { var err error hdr := make([]byte, 24) if err = readAtLeast(cn.nc, hdr, 24); err != nil { return nil, nil, nil, nil, err } if hdr[0] != respMagic { return nil, nil, nil, nil, ErrBadMagic } total := int(bUint32(hdr[8:12])) status := bUint16(hdr[6:8]) if status != respOk { if _, err = io.CopyN(ioutil.Discard, cn.nc, int64(total)); err != nil { return nil, nil, nil, nil, err } if status == respInvalidArgs && !legalKey(rKey) { return nil, nil, nil, nil, ErrMalformedKey } return nil, nil, nil, nil, response(status).asError() } var extras []byte el := int(hdr[4]) if el > 0 { extras = make([]byte, el) if err = readAtLeast(cn.nc, extras, el); err != nil { return nil, nil, nil, nil, err } } var key []byte kl := int(bUint16(hdr[2:4])) if kl > 0 { key = make([]byte, int(kl)) if err = readAtLeast(cn.nc, key, kl); err != nil { return nil, nil, nil, nil, err } } var value []byte vl := total - el - kl if vl > 0 { value = make([]byte, vl) if err = readAtLeast(cn.nc, value, vl); err != nil { return nil, nil, nil, nil, err } } return hdr, key, extras, value, nil } func (c *Client) parseUintResponse(key string, cn *conn) (uint64, error) { _, _, _, value, err := c.parseResponse(key, cn) c.condRelease(cn, &err) if err != nil { return 0, err } return bUint64(value), nil } func (c *Client) parseItemResponse(key string, cn *conn, release bool) (*Item, error) { hdr, k, extras, value, err := c.parseResponse(key, cn) if release { c.condRelease(cn, &err) } if err != nil { return nil, err } var flags uint32 if len(extras) > 0 { flags = bUint32(extras) } if key == "" && len(k) > 0 { key = string(k) } return &Item{ Key: key, Value: value, Flags: flags, casid: bUint64(hdr[16:24]), }, nil } // GetMulti is a batch version of Get. The returned map from keys to // items may have fewer elements than the input slice, due to memcache // cache misses. Each key must be at most 250 bytes in length. // If no error is returned, the returned map will also be non-nil. func (c *Client) GetMulti(keys []string) (map[string]*Item, error) { keyMap := make(map[*Addr][]string) for _, key := range keys { addr, err := c.servers.PickServer(key) if err != nil { return nil, err } keyMap[addr] = append(keyMap[addr], key) } var chs []chan *Item for addr, keys := range keyMap { ch := make(chan *Item) chs = append(chs, ch) go func(addr *Addr, keys []string, ch chan *Item) { defer close(ch) cn, err := c.getConn(addr) if err != nil { return } defer c.condRelease(cn, &err) for _, k := range keys { if err = c.sendConnCommand(cn, k, cmdGetKQ, nil, 0, nil); err != nil { return } } if err = c.sendConnCommand(cn, "", cmdNoop, nil, 0, nil); err != nil { return } var item *Item for { item, err = c.parseItemResponse("", cn, false) if item == nil || item.Key == "" { // Noop response break } ch <- item } }(addr, keys, ch) } m := make(map[string]*Item) for _, ch := range chs { for item := range ch { m[item.Key] = item } } return m, nil } // Set writes the given item, unconditionally. func (c *Client) Set(item *Item) error { return c.populateOne(cmdSet, item, 0) } // Add writes the given item, if no value already exists for its // key. ErrNotStored is returned if that condition is not met. func (c *Client) Add(item *Item) error { return c.populateOne(cmdAdd, item, 0) } // CompareAndSwap writes the given item that was previously returned // by Get, if the value was neither modified or evicted between the // Get and the CompareAndSwap calls. The item's Key should not change // between calls but all other item fields may differ. ErrCASConflict // is returned if the value was modified in between the // calls. ErrNotStored is returned if the value was evicted in between // the calls. func (c *Client) CompareAndSwap(item *Item) error { return c.populateOne(cmdSet, item, item.casid) } func (c *Client) populateOne(cmd command, item *Item, casid uint64) error { extras := make([]byte, 8) putUint32(extras, item.Flags) putUint32(extras[4:8], uint32(item.Expiration)) cn, err := c.sendCommand(item.Key, cmd, item.Value, casid, extras) if err != nil { return err } hdr, _, _, _, err := c.parseResponse(item.Key, cn) if err != nil { c.condRelease(cn, &err) return err } c.putFreeConn(cn) item.casid = bUint64(hdr[16:24]) return nil } // Delete deletes the item with the provided key. The error ErrCacheMiss is // returned if the item didn't already exist in the cache. func (c *Client) Delete(key string) error { cn, err := c.sendCommand(key, cmdDelete, nil, 0, nil) if err != nil { return err } _, _, _, _, err = c.parseResponse(key, cn) c.condRelease(cn, &err) return err } // Increment atomically increments key by delta. The return value is // the new value after being incremented or an error. If the value // didn't exist in memcached the error is ErrCacheMiss. The value in // memcached must be an decimal number, or an error will be returned. // On 64-bit overflow, the new value wraps around. func (c *Client) Increment(key string, delta uint64) (newValue uint64, err error) { return c.incrDecr(cmdIncr, key, delta) } // Decrement atomically decrements key by delta. The return value is // the new value after being decremented or an error. If the value // didn't exist in memcached the error is ErrCacheMiss. The value in // memcached must be an decimal number, or an error will be returned. // On underflow, the new value is capped at zero and does not wrap // around. func (c *Client) Decrement(key string, delta uint64) (newValue uint64, err error) { return c.incrDecr(cmdDecr, key, delta) } func (c *Client) incrDecr(cmd command, key string, delta uint64) (uint64, error) { extras := make([]byte, 20) putUint64(extras, delta) // Set expiration to 0xfffffff, so the command fails if the key // does not exist. for ii := 16; ii < 20; ii++ { extras[ii] = 0xff } cn, err := c.sendCommand(key, cmd, nil, 0, extras) if err != nil { return 0, err } return c.parseUintResponse(key, cn) } // Flush removes all the items in the cache after expiration seconds. If // expiration is <= 0, it removes all the items right now. func (c *Client) Flush(expiration int) error { servers, err := c.servers.Servers() var failed []*Addr var errs []error if err != nil { return err } var extras []byte if expiration > 0 { extras = make([]byte, 4) putUint32(extras, uint32(expiration)) } for _, addr := range servers { cn, err := c.getConn(addr) if err != nil { failed = append(failed, addr) errs = append(errs, err) continue } if err = c.sendConnCommand(cn, "", cmdFlush, nil, 0, extras); err == nil { _, _, _, _, err = c.parseResponse("", cn) } if err != nil { failed = append(failed, addr) errs = append(errs, err) } c.condRelease(cn, &err) } if len(failed) > 0 { var buf bytes.Buffer buf.WriteString("failed to flush some servers: ") for ii, addr := range failed { if ii > 0 { buf.WriteString(", ") } buf.WriteString(addr.String()) buf.WriteString(": ") buf.WriteString(errs[ii].Error()) } return errors.New(buf.String()) } return nil } golang-github-rainycape-memcache-0.0~git20150622.1031fa0/memcache_test.go000066400000000000000000000120471520712402700254430ustar00rootroot00000000000000/* Copyright 2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package memcache provides a client for the memcached cache server. package memcache import ( "fmt" "net" "os" "os/exec" "strings" "testing" "time" ) const testServer = "localhost:11211" func (c *Client) totalOpen() int { c.mu.Lock() defer c.mu.Unlock() count := 0 for _, v := range c.freeconn { count += len(v) } return count } func newLocalhostServer(tb testing.TB) *Client { c, err := net.Dial("tcp", testServer) if err != nil { tb.Skip("skipping test; no server running at %s", testServer) return nil } c.Write([]byte("flush_all\r\n")) c.Close() client, err := New(testServer) if err != nil { tb.Fatal(err) } return client } func newUnixServer(tb testing.TB) (*exec.Cmd, *Client) { sock := fmt.Sprintf("/tmp/test-gomemcache-%d.sock", os.Getpid()) os.Remove(sock) cmd := exec.Command("memcached", "-s", sock) if err := cmd.Start(); err != nil { tb.Skip("skipping test; couldn't find memcached") return nil, nil } // Wait a bit for the socket to appear. for i := 0; i < 10; i++ { if _, err := os.Stat(sock); err == nil { break } time.Sleep(time.Duration(25*i) * time.Millisecond) } c, err := New(sock) if err != nil { tb.Fatal(err) } return cmd, c } func TestLocalhost(t *testing.T) { testWithClient(t, newLocalhostServer(t)) } // Run the memcached binary as a child process and connect to its unix socket. func TestUnixSocket(t *testing.T) { cmd, c := newUnixServer(t) defer cmd.Wait() defer cmd.Process.Kill() testWithClient(t, c) } func testWithClient(t *testing.T, c *Client) { checkErr := func(err error, format string, args ...interface{}) { if err != nil { t.Fatalf(format, args...) } } mustSet := func(it *Item) { if err := c.Set(it); err != nil { t.Fatalf("failed to Set %#v: %v", *it, err) } } // Set foo := &Item{Key: "foo", Value: []byte("fooval"), Flags: 123} err := c.Set(foo) checkErr(err, "first set(foo): %v", err) err = c.Set(foo) checkErr(err, "second set(foo): %v", err) // Get it, err := c.Get("foo") checkErr(err, "get(foo): %v", err) if it.Key != "foo" { t.Errorf("get(foo) Key = %q, want foo", it.Key) } if string(it.Value) != "fooval" { t.Errorf("get(foo) Value = %q, want fooval", string(it.Value)) } if it.Flags != 123 { t.Errorf("get(foo) Flags = %v, want 123", it.Flags) } // Get non-existant _, err = c.Get("not-exists") if err != ErrCacheMiss { t.Errorf("get(not-exists): expecting %v, got %v instead", ErrCacheMiss, err) } // Add bar := &Item{Key: "bar", Value: []byte("barval")} err = c.Add(bar) checkErr(err, "first add(bar): %v", err) if err := c.Add(bar); err != ErrNotStored { t.Fatalf("second add(bar) want ErrNotStored, got %v", err) } // GetMulti m, err := c.GetMulti([]string{"foo", "bar"}) checkErr(err, "GetMulti: %v", err) if g, e := len(m), 2; g != e { t.Errorf("GetMulti: got len(map) = %d, want = %d", g, e) } if _, ok := m["foo"]; !ok { t.Fatalf("GetMulti: didn't get key 'foo'") } if _, ok := m["bar"]; !ok { t.Fatalf("GetMulti: didn't get key 'bar'") } if g, e := string(m["foo"].Value), "fooval"; g != e { t.Errorf("GetMulti: foo: got %q, want %q", g, e) } if g, e := string(m["bar"].Value), "barval"; g != e { t.Errorf("GetMulti: bar: got %q, want %q", g, e) } // Delete err = c.Delete("foo") checkErr(err, "Delete: %v", err) _, err = c.Get("foo") if err != ErrCacheMiss { t.Errorf("post-Delete want ErrCacheMiss, got %v", err) } // Incr/Decr mustSet(&Item{Key: "num", Value: []byte("42")}) n, err := c.Increment("num", 8) checkErr(err, "Increment num + 8: %v", err) if n != 50 { t.Fatalf("Increment num + 8: want=50, got=%d", n) } n, err = c.Decrement("num", 49) checkErr(err, "Decrement: %v", err) if n != 1 { t.Fatalf("Decrement 49: want=1, got=%d", n) } err = c.Delete("num") checkErr(err, "delete num: %v", err) n, err = c.Increment("num", 1) if err != ErrCacheMiss { t.Fatalf("increment post-delete: want ErrCacheMiss, got %v", err) } mustSet(&Item{Key: "num", Value: []byte("not-numeric")}) n, err = c.Increment("num", 1) if err != ErrBadIncrDec { t.Fatalf("increment non-number: want %v, got %v", ErrBadIncrDec, err) } // Invalid key if err := c.Set(&Item{Key: strings.Repeat("f", 251), Value: []byte("bar")}); err != ErrMalformedKey { t.Errorf("expecting ErrMalformedKey when using key too long, got nil") } // Flush _, err = c.Get("bar") checkErr(err, "get(bar): %v", err) err = c.Flush(0) checkErr(err, "flush: %v", err) _, err = c.Get("bar") if err != ErrCacheMiss { t.Fatalf("post-flush: want ErrCacheMiss, got %v", err) } } golang-github-rainycape-memcache-0.0~git20150622.1031fa0/orig.txt000066400000000000000000000012171520712402700240110ustar00rootroot00000000000000PASS BenchmarkSetGet 5000 214443 ns/op 0.03 MB/s 2479 B/op 18 allocs/op BenchmarkSetGetLarge 10000 262164 ns/op 4.82 MB/s 7537 B/op 19 allocs/op BenchmarkConcurrentSetGetSmall10_100 20 82561221 ns/op 0.07 MB/s 3101520 B/op 58469 allocs/op BenchmarkConcurrentSetGetLarge10_100 20 96067285 ns/op 13.16 MB/s 8330341 B/op 59848 allocs/op BenchmarkConcurrentSetGetSmall20_100 10 152834658 ns/op 0.08 MB/s 6318072 B/op 117177 allocs/op BenchmarkConcurrentSetGetLarge20_100 5 202574186 ns/op 12.48 MB/s 16884200 B/op 120173 allocs/op ok gomemcache/memcache 11.902s golang-github-rainycape-memcache-0.0~git20150622.1031fa0/server.go000066400000000000000000000033041520712402700241440ustar00rootroot00000000000000package memcache import ( "hash/crc32" "net" "strings" ) // Servers is the interface used to manage a set of memcached // servers. // // Implementations must be safely accessible from multiple // goroutines. type Servers interface { // PickServer selects one server from the ones by // managed by the Servers instance, based on the // given key. PickServer(key string) (*Addr, error) // Servers returns all the servers managed by the // Servers instance. Servers() ([]*Addr, error) } // ServerList is an implementation of the Servers interface. // To initialize a ServerList use NewServerList. type ServerList struct { addrs []*Addr } // NewServerList returns a new ServerList with the given servers. // All servers have the same weight. To give a server more weight, // list it multiple times. // // NewServerList returns an error if any of the received addresses // is not valid or fails to resolve, but it doesn't try to connect // to the provided servers. func NewServerList(servers ...string) (*ServerList, error) { addrs := make([]*Addr, len(servers)) for i, server := range servers { if strings.Contains(server, "/") { addr, err := net.ResolveUnixAddr("unix", server) if err != nil { return nil, err } addrs[i] = NewAddr(addr) } else { tcpaddr, err := net.ResolveTCPAddr("tcp", server) if err != nil { return nil, err } addrs[i] = NewAddr(tcpaddr) } } return &ServerList{addrs: addrs}, nil } func (s *ServerList) PickServer(key string) (*Addr, error) { if len(s.addrs) == 0 { return nil, ErrNoServers } cs := crc32.ChecksumIEEE(stobs(key)) return s.addrs[cs%uint32(len(s.addrs))], nil } func (s *ServerList) Servers() ([]*Addr, error) { return s.addrs, nil } golang-github-rainycape-memcache-0.0~git20150622.1031fa0/util_safe.go000066400000000000000000000001311520712402700246040ustar00rootroot00000000000000// +build appengine package memcache func stobs(s string) []byte { return []byte(s) } golang-github-rainycape-memcache-0.0~git20150622.1031fa0/util_unsafe.go000066400000000000000000000002051520712402700251510ustar00rootroot00000000000000// +build !appengine package memcache import ( "unsafe" ) func stobs(s string) []byte { return *(*[]byte)(unsafe.Pointer(&s)) }