/[glsr]/trunk/harmonious/_sessionutils.py
Gentoo

Contents of /trunk/harmonious/_sessionutils.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 109 - (show annotations) (download) (as text)
Mon Aug 1 14:40:49 2005 UTC (8 years, 11 months ago) by port001
File MIME type: text/x-python
File size: 6029 byte(s)
Added a 'flush2disk' mode to the SessionStorage class which pickles session data to disk when shut down, and unpickles it on startup.

1 __id__ = '$Id$'
2 __modulename__ = '_sessionutils'
3
4 import os
5 import sys
6 import sha
7 import hmac
8 import cPickle
9 import threading
10 from time import time
11 from random import Random
12 from types import BooleanType
13
14 from harmonious import server
15
16 class Session(object):
17
18 def __init__(self):
19
20 self.__id = ''
21 self.attrs = {}
22 self.__persistent = False
23 self.expires = ''
24 self.__removed = False
25 self.__modified = False
26 self.__end_init = False
27
28 def __setattr__(self, name, value):
29
30 if hasattr(self, '_Session__end_init'):
31 if self.__end_init:
32 if not self.__modified:
33 self.__dict__['_Session__modified'] = True
34
35 object.__setattr__(self, name, value)
36
37 def _end_init(self):
38
39 self.__end_init = True
40
41 def _set_id(self, id):
42
43 self.__id = id
44
45 def get_id(self):
46
47 return self.__id
48
49 def is_modified(self):
50
51 return self.__modified
52
53 def set_persistent(self, flag):
54
55 if type(flag) == BooleanType:
56
57 self.__persistent = flag
58
59 def is_persistent(self):
60
61 return self.__persistent
62
63 def set_removed(self):
64
65 self.__removed = True
66
67 server._sessionStore.remove_session(self.__id)
68
69 def is_removed(self):
70
71 return self.__removed
72
73 class SessionStorage:
74
75 def __init__(self, type):
76
77 # type is ['ram', 'flush2disk']
78 # TODO: We need a cleanup method called every n houres
79
80 self.__type = str(type).lower()
81 self.__lock = threading.Lock()
82 self.__store = {}
83
84 if self.__type == 'flush2disk':
85
86 if not os.path.exists(server.config.session['StoreDir']):
87
88 print >> sys.stderr, "Harmonious: StoreDir '%s' does not exist" % server.config.session['StoreDir']
89 sys.exit(1)
90
91 if not os.path.isdir(server.config.session['StoreDir']):
92
93 print >> sys.stderr, "Harmonious: StoreDir '%s' is not a directory" % server.config.session['StoreDir']
94 sys.exit(1)
95
96 def load_store(self):
97
98 if self.__type == 'flush2disk':
99
100 for file in os.listdir(server.config.session['StoreDir']):
101
102 if file.endswith('.session'):
103
104 try:
105 session_dict = cPickle.load(open(os.path.join(server.config.session['StoreDir'], file), 'r'))
106 except IOError, e:
107 print >> sys.stderr, "Harmonious: Failed to load session file '%s': %s" % (file, e)
108 sys.exit(1)
109
110 self.__store[session_dict.keys()[0]] = session_dict[session_dict.keys()[0]]
111
112 def save_store(self):
113
114 if self.__type == 'flush2disk':
115
116 for session in self.__store.iterkeys():
117
118 try:
119 cPickle.dump({session: self.__store[session]}, \
120 open(os.path.join(server.config.session['StoreDir'], "%s.session" % session), 'w'))
121 except IOError, e:
122 print >> sys.stderr, "Harmonious: Failed to save session file '%s.session': %s" % (session, e)
123 sys.exit(1)
124
125 def has_expired(self, sessionId):
126
127 if not self.has_session(sessionId):
128
129 return True
130
131 self.__lock.acquire()
132 if self.__store[sessionId]['expires'] <= int(time()) and self.__store[sessionId]['persistent'] == False:
133
134 self.__lock.release()
135 return True
136
137 self.__lock.release()
138 return False
139
140 def has_session(self, sessionId):
141
142 self.__lock.acquire()
143 if self.__store.has_key(sessionId):
144
145 self.__lock.release()
146 return True
147
148 self.__lock.release()
149 return False
150
151 def remove_session(self, sessionId):
152
153 if self.has_session(sessionId):
154
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': {}, 'persistent': False}
163 self.__store[sessionId]['expires'] = int(time() + (expires * 60))
164 self.__lock.release()
165
166 def set_persistent(self, sessionId, flag):
167
168 if self.has_session(sessionId):
169 self.__lock.acquire()
170 self.__store[sessionId]['persistent'] = flag
171 self.__lock.release()
172
173 def load_session(self, sessionId):
174
175 self.__lock.acquire()
176 if self.__store.has_key(sessionId):
177
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
193 self.__lock.release()
194 return None
195
196 def update_session(self, sessionId, **args):
197
198 self.__lock.acquire()
199
200 if sessionId in self.__store.keys():
201
202 for key in args.keys():
203
204 if key in self.__store[sessionId].keys():
205
206 self.__store[sessionId][key] = args[key]
207
208 elif key in self.__store[sessionId]['attrs'].keys():
209
210 self.__store[sessionId]['attrs'][key] = args[key]
211
212 else:
213
214 self.__store[sessionId]['attrs'][key] = args[key]
215
216 self.__lock.release()
217
218 def gen_hash(sid):
219
220 return hmac.new(server.config.server['SecretKey'], sid, sha).hexdigest()[:10]
221
222 def _gen_sid(client_addr, host):
223
224 ran = Random()
225
226 return sha.new(str(time() * ran.randint(0, 10000000000000000000000000)) + \
227 str(client_addr) + str(host)).hexdigest()
228
229 # TODO: Just using the client IP addr isn't great.
230
231 def gen_session_id(client_addr, host):
232
233 sid = _gen_sid(client_addr, host)
234
235 return sid + gen_hash(sid)

Properties

Name Value
svn:keyword Id
svn:keywords Id

  ViewVC Help
Powered by ViewVC 1.1.20