Debian Codegraph @

redis/redis.go

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright 2013 Beego Authors
2 // Copyright 2014 The Macaron Authors
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License"): you may
5 // not use this file except in compliance with the License. You may obtain
6 // a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 // License for the specific language governing permissions and limitations
14 // under the License.
15
16 package session
17
18 import (
19 "fmt"
20 "strings"
21 "sync"
22 "time"
23
24 "github.com/Unknwon/com"
25 "gopkg.in/ini.v1"
26 "gopkg.in/redis.v2"
27
28 "github.com/go-macaron/session"
29 )
30
31 // RedisStore represents a redis session store implementation.
32 type RedisStore struct {
33 c *redis.Client
34 prefix, sid string
35 duration time.Duration
36 lock sync.RWMutex
37 data map[interface{}]interface{}
38 }
39
40 // NewRedisStore creates and returns a redis session store.
41 func NewRedisStore(c *redis.Client, prefix, sid string, dur time.Duration, kv map[interface{}]interface{}) *RedisStore {
42 return &RedisStore{
43 c: c,
44 prefix: prefix,
45 sid: sid,
46 duration: dur,
47 data: kv,
48 }
49 }
50
51 // Set sets value to given key in session.
52 func (s *RedisStore) Set(key, val interface{}) error {
53 s.lock.Lock()
54 defer s.lock.Unlock()
55
56 s.data[key] = val
57 return nil
58 }
59
60 // Get gets value by given key in session.
61 func (s *RedisStore) Get(key interface{}) interface{} {
62 s.lock.RLock()
63 defer s.lock.RUnlock()
64
65 return s.data[key]
66 }
67
68 // Delete delete a key from session.
69 func (s *RedisStore) Delete(key interface{}) error {
70 s.lock.Lock()
71 defer s.lock.Unlock()
72
73 delete(s.data, key)
74 return nil
75 }
76
77 // ID returns current session ID.
78 func (s *RedisStore) ID() string {
79 return s.sid
80 }
81
82 // Release releases resource and save data to provider.
83 func (s *RedisStore) Release() error {
84 data, err := session.EncodeGob(s.data)
85 if err != nil {
86 return err
87 }
88
89 return s.c.SetEx(s.prefix+s.sid, s.duration, string(data)).Err()
90 }
91
92 // Flush deletes all session data.
93 func (s *RedisStore) Flush() error {
94 s.lock.Lock()
95 defer s.lock.Unlock()
96
97 s.data = make(map[interface{}]interface{})
98 return nil
99 }
100
101 // RedisProvider represents a redis session provider implementation.
102 type RedisProvider struct {
103 c *redis.Client
104 duration time.Duration
105 prefix string
106 }
107
108 // Init initializes redis session provider.
109 // configs: network=tcp,addr=:6379,password=macaron,db=0,pool_size=100,idle_timeout=180,prefix=session;
110 func (p *RedisProvider) Init(maxlifetime int64, configs string) (err error) {
111 p.duration, err = time.ParseDuration(fmt.Sprintf("%ds", maxlifetime))
112 if err != nil {
113 return err
114 }
115
116 cfg, err := ini.Load([]byte(strings.Replace(configs, ",", "\n", -1)))
117 if err != nil {
118 return err
119 }
120
121 opt := &redis.Options{
122 Network: "tcp",
123 }
124 for k, v := range cfg.Section("").KeysHash() {
125 switch k {
126 case "network":
127 opt.Network = v
128 case "addr":
129 opt.Addr = v
130 case "password":
131 opt.Password = v
132 case "db":
133 opt.DB = com.StrTo(v).MustInt64()
134 case "pool_size":
135 opt.PoolSize = com.StrTo(v).MustInt()
136 case "idle_timeout":
137 opt.IdleTimeout, err = time.ParseDuration(v + "s")
138 if err != nil {
139 return fmt.Errorf("error parsing idle timeout: %v", err)
140 }
141 case "prefix":
142 p.prefix = v
143 default:
144 return fmt.Errorf("session/redis: unsupported option '%s'", k)
145 }
146 }
147
148 p.c = redis.NewClient(opt)
149 return p.c.Ping().Err()
150 }
151
152 // Read returns raw session store by session ID.
153 func (p *RedisProvider) Read(sid string) (session.RawStore, error) {
154 psid := p.prefix + sid
155 if !p.Exist(sid) {
156 if err := p.c.Set(psid, "").Err(); err != nil {
157 return nil, err
158 }
159 }
160
161 var kv map[interface{}]interface{}
162 kvs, err := p.c.Get(psid).Result()
163 if err != nil {
164 return nil, err
165 }
166 if len(kvs) == 0 {
167 kv = make(map[interface{}]interface{})
168 } else {
169 kv, err = session.DecodeGob([]byte(kvs))
170 if err != nil {
171 return nil, err
172 }
173 }
174
175 return NewRedisStore(p.c, p.prefix, sid, p.duration, kv), nil
176 }
177
178 // Exist returns true if session with given ID exists.
179 func (p *RedisProvider) Exist(sid string) bool {
180 has, err := p.c.Exists(p.prefix + sid).Result()
181 return err == nil && has
182 }
183
184 // Destory deletes a session by session ID.
185 func (p *RedisProvider) Destory(sid string) error {
186 return p.c.Del(p.prefix + sid).Err()
187 }
188
189 // Regenerate regenerates a session store from old session ID to new one.
190 func (p *RedisProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) {
191 poldsid := p.prefix + oldsid
192 psid := p.prefix + sid
193
194 if p.Exist(sid) {
195 return nil, fmt.Errorf("new sid '%s' already exists", sid)
196 } else if !p.Exist(oldsid) {
197 // Make a fake old session.
198 if err = p.c.SetEx(poldsid, p.duration, "").Err(); err != nil {
199 return nil, err
200 }
201 }
202
203 if err = p.c.Rename(poldsid, psid).Err(); err != nil {
204 return nil, err
205 }
206
207 var kv map[interface{}]interface{}
208 kvs, err := p.c.Get(psid).Result()
209 if err != nil {
210 return nil, err
211 }
212
213 if len(kvs) == 0 {
214 kv = make(map[interface{}]interface{})
215 } else {
216 kv, err = session.DecodeGob([]byte(kvs))
217 if err != nil {
218 return nil, err
219 }
220 }
221
222 return NewRedisStore(p.c, p.prefix, sid, p.duration, kv), nil
223 }
224
225 // Count counts and returns number of sessions.
226 func (p *RedisProvider) Count() int {
227 return int(p.c.DbSize().Val())
228 }
229
230 // GC calls GC to clean expired sessions.
231 func (_ *RedisProvider) GC() {}
232
233 func init() {
234 session.Register("redis", &RedisProvider{})
235 }