From e4ed91297d2651613ee672b04c7d2ac18211a66b Mon Sep 17 00:00:00 2001 From: Radu Ioan Fericean Date: Thu, 20 Sep 2012 11:50:36 +0300 Subject: [PATCH] as dirs --- .gitignore | 1 + balancer2go/.travis.yml | 6 ++ balancer2go/LICENSE.txt | 9 +++ balancer2go/README.md | 10 +++ balancer2go/balancer.go | 88 ++++++++++++++++++++++++++ balancer2go/balancer_test.go | 76 +++++++++++++++++++++++ cache2go/.travis.yml | 6 ++ cache2go/LICENSE.txt | 9 +++ cache2go/README.md | 10 +++ cache2go/cache.go | 117 +++++++++++++++++++++++++++++++++++ cache2go/cache_test.go | 75 ++++++++++++++++++++++ 11 files changed, 407 insertions(+) create mode 100644 balancer2go/.travis.yml create mode 100644 balancer2go/LICENSE.txt create mode 100644 balancer2go/README.md create mode 100644 balancer2go/balancer.go create mode 100644 balancer2go/balancer_test.go create mode 100644 cache2go/.travis.yml create mode 100644 cache2go/LICENSE.txt create mode 100644 cache2go/README.md create mode 100644 cache2go/cache.go create mode 100644 cache2go/cache_test.go diff --git a/.gitignore b/.gitignore index f4c81506b..7fb48bd2e 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ a.out docs/_* bin .idea +.gitignore diff --git a/balancer2go/.travis.yml b/balancer2go/.travis.yml new file mode 100644 index 000000000..ffc3d37e0 --- /dev/null +++ b/balancer2go/.travis.yml @@ -0,0 +1,6 @@ +language: go + +notifications: + email: + on_success: change + on_failure: always diff --git a/balancer2go/LICENSE.txt b/balancer2go/LICENSE.txt new file mode 100644 index 000000000..9bdbcbf59 --- /dev/null +++ b/balancer2go/LICENSE.txt @@ -0,0 +1,9 @@ +Copyright (c) 2012, Radu Ioan Fericean +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +Neither the name of Radu Ioan Fericean nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/balancer2go/README.md b/balancer2go/README.md new file mode 100644 index 000000000..8b19c5f71 --- /dev/null +++ b/balancer2go/README.md @@ -0,0 +1,10 @@ +balancer2go +=========== + +Simple golang balancer library + +See the test file for wroking examples. + +API docs [here](http://go.pkgdoc.org/github.com/rif/balancer2go). + +Continous integration: [![Build Status](https://secure.travis-ci.org/rif/balancer2go.png)](http://travis-ci.org/rif/balancer2go) \ No newline at end of file diff --git a/balancer2go/balancer.go b/balancer2go/balancer.go new file mode 100644 index 000000000..519def5f9 --- /dev/null +++ b/balancer2go/balancer.go @@ -0,0 +1,88 @@ +// Simple RPC client balancer +package balancer2go + +import ( + "sync" +) + +// The main balancer type +type Balancer struct { + sync.RWMutex + clients map[string]Worker + balancerChannel chan Worker +} + +// Interface for RPC clients +type Worker interface { + Call(serviceMethod string, args interface{}, reply interface{}) error + Close() error +} + +// Constructor for RateList holding one slice for addreses and one slice for connections. +func NewBalancer() *Balancer { + r := &Balancer{clients: make(map[string]Worker), balancerChannel: make(chan Worker)} // leaving both slices to nil + go func() { + for { + if len(r.clients) > 0 { + for _, c := range r.clients { + r.balancerChannel <- c + } + } else { + r.balancerChannel <- nil + } + } + }() + return r +} + +// Adds a client to the two internal map. +func (bl *Balancer) AddClient(address string, client Worker) { + bl.Lock() + defer bl.Unlock() + bl.clients[address] = client + return +} + +// Removes a client from the map locking the readers and reseting the balancer index. +func (bl *Balancer) RemoveClient(address string) { + bl.Lock() + defer bl.Unlock() + delete(bl.clients, address) + <-bl.balancerChannel +} + +// Returns a client for the specifed address. +func (bl *Balancer) GetClient(address string) (c Worker, exists bool) { + bl.RLock() + defer bl.RUnlock() + c, exists = bl.clients[address] + return +} + +// Returns the next available connection at each call looping at the end of connections. +func (bl *Balancer) Balance() (result Worker) { + bl.RLock() + defer bl.RUnlock() + return <-bl.balancerChannel +} + +// Sends a shotdown call to the clients +func (bl *Balancer) Shutdown(shutdownMethod string) { + bl.Lock() + defer bl.Unlock() + var reply string + for _, client := range bl.clients { + client.Call(shutdownMethod, "", &reply) + } +} + +// Returns a string slice with all client addresses +func (bl *Balancer) GetClientAddresses() []string { + bl.RLock() + defer bl.RUnlock() + var addresses []string + for a, _ := range bl.clients { + addresses = append(addresses, a) + } + return addresses +} diff --git a/balancer2go/balancer_test.go b/balancer2go/balancer_test.go new file mode 100644 index 000000000..96db94ff2 --- /dev/null +++ b/balancer2go/balancer_test.go @@ -0,0 +1,76 @@ +package balancer2go + +import ( + "fmt" + "net/rpc" + "testing" +) + +func BenchmarkBalance(b *testing.B) { + balancer := NewBalancer() + balancer.AddClient("client 1", new(rpc.Client)) + balancer.AddClient("client 2", new(rpc.Client)) + balancer.AddClient("client 3", new(rpc.Client)) + for i := 0; i < b.N; i++ { + balancer.Balance() + } +} + +func TestRemoving(t *testing.T) { + balancer := NewBalancer() + c1 := new(rpc.Client) + c2 := new(rpc.Client) + c3 := new(rpc.Client) + balancer.AddClient("client 1", c1) + balancer.AddClient("client 2", c2) + balancer.AddClient("client 3", c3) + balancer.RemoveClient("client 2") + if balancer.clients["client 1"] != c1 || + balancer.clients["client 3"] != c3 || + len(balancer.clients) != 2 { + t.Error("Failed removing rater") + } +} + +func TestGet(t *testing.T) { + balancer := NewBalancer() + c1 := new(rpc.Client) + balancer.AddClient("client 1", c1) + result, ok := balancer.GetClient("client 1") + if !ok || c1 != result { + t.Error("Get failed") + } +} + +func TestOneBalancer(t *testing.T) { + balancer := NewBalancer() + balancer.AddClient("client 1", new(rpc.Client)) + c1 := balancer.Balance() + c2 := balancer.Balance() + if c1 != c2 { + t.Error("With only one rater these shoud be equal") + } +} + +func Test100Balancer(t *testing.T) { + balancer := NewBalancer() + var clients []Worker + for i := 0; i < 100; i++ { + c := new(rpc.Client) + balancer.AddClient(fmt.Sprintf("client%v", i), c) + } + for i := 0; i < 100; i++ { + c := balancer.Balance() + if c == nil { + t.Error("Retuned nil client!") + } + for _, o := range clients { + if c == o { + t.Error("Balance did not iterate all the available clients") + break + } + } + clients = append(clients, c) + } + +} diff --git a/cache2go/.travis.yml b/cache2go/.travis.yml new file mode 100644 index 000000000..ffc3d37e0 --- /dev/null +++ b/cache2go/.travis.yml @@ -0,0 +1,6 @@ +language: go + +notifications: + email: + on_success: change + on_failure: always diff --git a/cache2go/LICENSE.txt b/cache2go/LICENSE.txt new file mode 100644 index 000000000..9bdbcbf59 --- /dev/null +++ b/cache2go/LICENSE.txt @@ -0,0 +1,9 @@ +Copyright (c) 2012, Radu Ioan Fericean +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +Neither the name of Radu Ioan Fericean nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/cache2go/README.md b/cache2go/README.md new file mode 100644 index 000000000..ca572d755 --- /dev/null +++ b/cache2go/README.md @@ -0,0 +1,10 @@ +cache2go +===== + +Golang simple object caching library with expiration capabilities. + +See the test file for wroking examples. + +API docs [here](http://go.pkgdoc.org/github.com/rif/cache2go). + +Continous integration: [![Build Status](https://secure.travis-ci.org/rif/cache2go.png)](http://travis-ci.org/rif/cache2go) diff --git a/cache2go/cache.go b/cache2go/cache.go new file mode 100644 index 000000000..1560c8e51 --- /dev/null +++ b/cache2go/cache.go @@ -0,0 +1,117 @@ +//Simple caching library with expiration capabilities +package cache2go + +import ( + "errors" + "sync" + "time" +) + +type expiringCacheEntry interface { + XCache(key string, expire time.Duration, value expiringCacheEntry) + timer() *time.Timer + KeepAlive() +} + +// Structure that must be embeded in the objectst that must be cached with expiration. +// If the expiration is not needed this can be ignored +type XEntry struct { + sync.Mutex + key string + keepAlive bool + expireDuration time.Duration + t *time.Timer +} + +var ( + xcache = make(map[string]expiringCacheEntry) + xMux sync.RWMutex + cache = make(map[string]interface{}) + mux sync.RWMutex +) + +// The main function to cache with expiration +func (xe *XEntry) XCache(key string, expire time.Duration, value expiringCacheEntry) { + xe.keepAlive = true + xe.key = key + xe.expireDuration = expire + xMux.Lock() + xcache[key] = value + xMux.Unlock() + go xe.expire() +} + +// The internal mechanism for expiartion +func (xe *XEntry) expire() { + for xe.keepAlive { + xe.Lock() + xe.keepAlive = false + xe.Unlock() + xe.t = time.NewTimer(xe.expireDuration) + <-xe.t.C + if !xe.keepAlive { + xMux.Lock() + delete(xcache, xe.key) + xMux.Unlock() + } + } +} + +// Getter for the timer +func (xe *XEntry) timer() *time.Timer { + return xe.t +} + +// Mark entry to be kept another expirationDuration period +func (xe *XEntry) KeepAlive() { + xe.Lock() + defer xe.Unlock() + xe.keepAlive = true +} + +// Get an entry from the expiration cache and mark it for keeping alive +func GetXCached(key string) (ece expiringCacheEntry, err error) { + xMux.RLock() + defer xMux.RUnlock() + if r, ok := xcache[key]; ok { + r.KeepAlive() + return r, nil + } + return nil, errors.New("not found") +} + +// The function to be used to cache a key/value pair when expiration is not needed +func Cache(key string, value interface{}) { + mux.Lock() + defer mux.Unlock() + cache[key] = value +} + +// The function to extract a value for a key that never expire +func GetCached(key string) (v interface{}, err error) { + mux.RLock() + defer mux.RUnlock() + if r, ok := cache[key]; ok { + return r, nil + } + return nil, errors.New("not found") +} + +// Delete all keys from expiraton cache +func XFlush() { + xMux.Lock() + defer xMux.Unlock() + for _, v := range xcache { + if v.timer() != nil { + v.timer().Stop() + } + } + xcache = make(map[string]expiringCacheEntry) +} + +// Delete all keys from cache +func Flush() { + mux.Lock() + defer mux.Unlock() + cache = make(map[string]interface{}) +} diff --git a/cache2go/cache_test.go b/cache2go/cache_test.go new file mode 100644 index 000000000..f2af3f18d --- /dev/null +++ b/cache2go/cache_test.go @@ -0,0 +1,75 @@ +package cache2go + +import ( + "testing" + "time" +) + +type myStruct struct { + XEntry + data string +} + +func TestCache(t *testing.T) { + a := &myStruct{data: "mama are mere"} + a.XCache("mama", 1*time.Second, a) + b, err := GetXCached("mama") + if err != nil || b == nil || b != a { + t.Error("Error retriving data from cache", err) + } +} + +func TestCacheExpire(t *testing.T) { + a := &myStruct{data: "mama are mere"} + a.XCache("mama", 1*time.Second, a) + b, err := GetXCached("mama") + if err != nil || b == nil || b.(*myStruct).data != "mama are mere" { + t.Error("Error retriving data from cache", err) + } + time.Sleep(1001 * time.Millisecond) + b, err = GetXCached("mama") + if err == nil || b != nil { + t.Error("Error expiring data") + } +} + +func TestCacheKeepAlive(t *testing.T) { + a := &myStruct{data: "mama are mere"} + a.XCache("mama", 1*time.Second, a) + b, err := GetXCached("mama") + if err != nil || b == nil || b.(*myStruct).data != "mama are mere" { + t.Error("Error retriving data from cache", err) + } + time.Sleep(500 * time.Millisecond) + b.KeepAlive() + time.Sleep(501 * time.Millisecond) + if err != nil { + t.Error("Error keeping cached data alive", err) + } + time.Sleep(1000 * time.Millisecond) + b, err = GetXCached("mama") + if err == nil || b != nil { + t.Error("Error expiring data") + } +} + +func TestFlush(t *testing.T) { + a := &myStruct{data: "mama are mere"} + a.XCache("mama", 10*time.Second, a) + time.Sleep(1000 * time.Millisecond) + XFlush() + b, err := GetXCached("mama") + if err == nil || b != nil { + t.Error("Error expiring data") + } +} + +func TestFlushNoTimout(t *testing.T) { + a := &myStruct{data: "mama are mere"} + a.XCache("mama", 10*time.Second, a) + XFlush() + b, err := GetXCached("mama") + if err == nil || b != nil { + t.Error("Error expiring data") + } +}