/[glsr]/trunk/glsr_framework/sessionutils.py
Gentoo

Contents of /trunk/glsr_framework/sessionutils.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 177 - (show annotations) (download) (as text)
Sat Nov 5 21:34:50 2005 UTC (9 years, 1 month ago) by hadfield
File MIME type: text/x-python
File size: 6204 byte(s)
simple code touch ups and minor bug fixes.
1 # Copyright 2005 Gentoo Foundation
2 # Distributed under the terms of the GNU General Public License v2
3 #
4
5 """Simple session handling objects"""
6
7 __revision__ = "$Id$"
8 __authors__ = ["Scott Hadfield <hadfield@gentoo.org>",
9 "Ian Leitch <port001@gentoo.org>"]
10 __modulename__ = "sessionutils"
11
12 import sha
13 import hmac
14 import cPickle
15 import threading
16 from time import time
17 from random import Random
18 from types import BooleanType
19 import os
20
21 from glsr.setup import config
22
23 class Session(object):
24
25 def __init__(self, session_store = None):
26
27 self.__id = ''
28 self.attrs = {}
29 self.__persistent = False
30 self.expires = ''
31 self.__removed = False
32 self.__modified = False
33 self.__end_init = False
34 self._session_store = session_store
35
36 def __setattr__(self, name, value):
37
38 if hasattr(self, '_Session__end_init'):
39 if self.__end_init:
40 if not self.__modified:
41 self.__dict__['_Session__modified'] = True
42
43 object.__setattr__(self, name, value)
44
45 def _end_init(self):
46
47 self.__end_init = True
48
49 def _set_id(self, id):
50
51 self.__id = id
52
53 def get_id(self):
54
55 return self.__id
56
57 def is_modified(self):
58
59 return self.__modified
60
61 def set_persistent(self, flag):
62
63 if type(flag) == BooleanType:
64
65 self.__persistent = flag
66
67 def is_persistent(self):
68
69 return self.__persistent
70
71 def set_removed(self):
72
73 self.__removed = True
74
75 self._session_store.remove_session(self.__id)
76
77 def is_removed(self):
78
79 return self.__removed
80
81 class SessionStorage:
82
83 def __init__(self, type):
84
85 # type is ['ram', 'flush2disk']
86 # TODO: We need a cleanup method called every n houres
87
88 self.__type = str(type).lower()
89 self.__lock = threading.Lock()
90 self.__store = {}
91
92 if self.__type == 'flush2disk':
93
94 if not os.path.exists(config.StoreDir):
95 raise "StoreDir '%s' does not exist" % config.StoreDir
96
97 if not os.path.isdir(config.StoreDir):
98 raise "StoreDir '%s' is not a directory" % config.StoreDir
99
100 def load_store(self):
101
102 if self.__type == 'flush2disk':
103 for file in os.listdir(config.StoreDir):
104 if file.endswith('.session'):
105 try:
106 session_dict = cPickle.load(
107 open(os.path.join(config.StoreDir, file), 'r'))
108 except IOError, e:
109 raise "Failed to load session file" + \
110 "'%s': %s" % (file, e)
111
112 self.__store[session_dict.keys()[0]] = (
113 session_dict[session_dict.keys()[0]])
114
115 def save_store(self):
116
117 if self.__type == 'flush2disk':
118 for session in self.__store.iterkeys():
119 try:
120 session_path = os.path.join(config.StoreDir,
121 "%s.session" % session)
122 cPickle.dump({session: self.__store[session]},
123 open(session_path, 'w'))
124 except IOError, e:
125 raise "Failed to save session file " + \
126 "'%s.session': %s" % (session, e)
127
128 def has_expired(self, sessionId):
129
130 if not self.has_session(sessionId):
131 return True
132
133 self.__lock.acquire()
134 if (self.__store[sessionId]['expires'] <= int(time())
135 and self.__store[sessionId]['persistent'] == False):
136 self.__lock.release()
137 return True
138
139 self.__lock.release()
140 return False
141
142 def has_session(self, sessionId):
143
144 self.__lock.acquire()
145 if self.__store.has_key(sessionId):
146 self.__lock.release()
147 return True
148
149 self.__lock.release()
150 return False
151
152 def remove_session(self, sessionId):
153
154 if self.has_session(sessionId):
155 self.__lock.acquire()
156 self.__store.pop(sessionId)
157 self.__lock.release()
158
159 def store_session(self, sessionId=None, expires=None):
160
161 self.__lock.acquire()
162 self.__store[sessionId] = {'expires': 0, 'attrs': {},
163 'persistent': False}
164 self.__store[sessionId]['expires'] = int(time() + (expires * 60))
165 self.__lock.release()
166
167 def set_persistent(self, sessionId, flag):
168
169 if self.has_session(sessionId):
170 self.__lock.acquire()
171 self.__store[sessionId]['persistent'] = flag
172 self.__lock.release()
173
174 def load_session(self, sessionId):
175
176 self.__lock.acquire()
177 if self.__store.has_key(sessionId):
178 self.__lock.release()
179 if self.has_expired(sessionId):
180
181 self.__lock.acquire()
182 self.__store.pop(sessionId)
183 self.__lock.release()
184 return None
185
186 self.__lock.acquire()
187 x = self.__store[sessionId]
188 self.__lock.release()
189 return x
190
191 else:
192 self.__lock.release()
193 return None
194
195 def update_session(self, sessionId, **args):
196
197 self.__lock.acquire()
198 if sessionId in self.__store.keys():
199 for key in args.keys():
200 if key in self.__store[sessionId].keys():
201 self.__store[sessionId][key] = args[key]
202
203 elif key in self.__store[sessionId]['attrs'].keys():
204 self.__store[sessionId]['attrs'][key] = args[key]
205
206 else:
207 self.__store[sessionId]['attrs'][key] = args[key]
208
209 self.__lock.release()
210
211 def gen_hash(sid):
212 return hmac.new(config.SecretKey, sid, sha).hexdigest()[:10]
213
214 def _gen_sid(client_addr, host):
215 ran = Random()
216 return sha.new(str(time() * ran.randint(0, 10000000000000000000000000)) + \
217 str(client_addr) + str(host)).hexdigest()
218
219 def gen_session_id(client_addr, host):
220 # TODO: Just using the client IP addr isn't great.
221 sid = _gen_sid(client_addr, host)
222 return sid + gen_hash(sid)

Properties

Name Value
svn:keywords Id

  ViewVC Help
Powered by ViewVC 1.1.20