Package entropy :: Package services :: Module skel

Source Code for Module entropy.services.skel

  1  # -*- coding: utf-8 -*- 
  2  """ 
  3   
  4      @author: Fabio Erculiani <lxnay@sabayonlinux.org> 
  5      @contact: lxnay@sabayonlinux.org 
  6      @copyright: Fabio Erculiani 
  7      @license: GPL-2 
  8   
  9      B{Entropy Services Stub Interfaces}. 
 10   
 11  """ 
 12  import os 
 13  from entropy.const import const_convert_to_unicode 
 14  from entropy.tools import escape 
 15  from entropy.exceptions import * 
 16  from entropy.i18n import _ 
 17   
18 -class SocketCommands:
19
20 - def __str__(self):
21 return self.inst_name
22 23 inst_name = 'command-skel'
24 - def __init__(self, HostInterface, inst_name = 'command-skel'):
25 self.HostInterface = HostInterface 26 self.no_acked_commands = [] 27 self.termination_commands = [] 28 self.initialization_commands = [] 29 self.login_pass_commands = [] 30 self.no_session_commands = [] 31 self.raw_commands = [] 32 self.config_commands = [] 33 self.valid_commands = set() 34 self.inst_name = inst_name
35
36 - def register( 37 self, 38 valid_commands, 39 no_acked_commands, 40 termination_commands, 41 initialization_commands, 42 login_pass_commads, 43 no_session_commands, 44 raw_commands, 45 config_commands 46 ):
47 valid_commands.update(self.valid_commands) 48 no_acked_commands.extend(self.no_acked_commands) 49 termination_commands.extend(self.termination_commands) 50 initialization_commands.extend(self.initialization_commands) 51 login_pass_commads.extend(self.login_pass_commands) 52 no_session_commands.extend(self.no_session_commands) 53 raw_commands.extend(self.raw_commands) 54 config_commands.extend(self.config_commands)
55
56 -class SocketAuthenticator:
57 58 """ 59 Base class for Entropy SocketHost RPC authentication. 60 """ 61
62 - def __init__(self, HostInterface):
63 self.HostInterface = HostInterface 64 self.session = None
65
66 - def set_session(self, session):
67 """ 68 Set Entropy SocketHost connection session id. 69 70 @param session: connection session 71 @type session: int 72 """ 73 self.session = session
74
75 - def hide_login_data(self, args):
76 """ 77 Given Entropy SocketHost RPC login command in list form, hide password 78 data (which is going to be stored in log file). 79 NOTE: this method MUST be reimplemented 80 81 @param args: arguments of RPC login command 82 @type args: list 83 @return: filtered list 84 @rtype: list 85 """ 86 raise NotImplementedError()
87
88 - def set_exc_permissions(self, uid, gid):
89 """ 90 Set execution permissions (setuid, setgid) for the running process. 91 92 @param uid: user id 93 @type: int 94 @param gid: group id 95 @type: int 96 """ 97 if gid != None: 98 os.setgid(gid) 99 if uid != None: 100 os.setuid(uid)
101
102 - def terminate_instance(self):
103 """ 104 This function is called when the Authenticator is going to be destroyed. 105 You can reimplement this to execute arbitrary code (for eg. terminate 106 a database connection). 107 NOTE: there is no need to reimplement this if you are not using any 108 fancy stuff. 109 """ 110 pass
111
112 -class RemoteDatabase:
113
114 - def __init__(self):
115 self.dbconn = None 116 self.cursor = None 117 self.plain_cursor = None 118 self.escape_string = escape 119 self.connection_data = {} 120 try: 121 import MySQLdb, _mysql_exceptions 122 from MySQLdb.constants import FIELD_TYPE 123 from MySQLdb.converters import conversions 124 except ImportError: 125 raise LibraryNotFound('LibraryNotFound: dev-python/mysql-python not found') 126 self.mysql = MySQLdb 127 self.mysql_exceptions = _mysql_exceptions 128 self.FIELD_TYPE = FIELD_TYPE 129 self.conversion_dict = conversions.copy() 130 self.conversion_dict[self.FIELD_TYPE.DECIMAL] = int 131 self.conversion_dict[self.FIELD_TYPE.LONG] = int 132 self.conversion_dict[self.FIELD_TYPE.FLOAT] = float 133 self.conversion_dict[self.FIELD_TYPE.NEWDECIMAL] = float
134
135 - def check_connection(self):
136 if self.dbconn == None: 137 raise ConnectionError('ConnectionError: %s' % (_("not connected to database"),)) 138 self._check_needed_reconnect()
139
140 - def _check_needed_reconnect(self):
141 if self.dbconn == None: 142 return 143 try: 144 self.dbconn.ping() 145 except self.mysql_exceptions.OperationalError as e: 146 if e[0] != 2006: 147 raise 148 else: 149 self.connect() 150 return True 151 return False
152
154 raise NotImplementedError('NotImplementedError: %s' % (_('method not implemented'),))
155
156 - def set_connection_data(self, data):
157 self.connection_data = data.copy() 158 if 'converters' not in self.connection_data and self.conversion_dict: 159 self.connection_data['converters'] = self.conversion_dict.copy()
160
161 - def check_connection_data(self):
162 if not self.connection_data: 163 raise PermissionDenied('ConnectionError: %s' % (_("no connection data"),))
164
165 - def connect(self):
166 kwargs = {} 167 keys = [ 168 ('host', "hostname"), 169 ('user', "username"), 170 ('passwd', "password"), 171 ('db', "dbname"), 172 ('port', "port"), 173 ('conv', "converters"), # mysql type converter dict 174 ] 175 for ckey, dkey in keys: 176 if dkey not in self.connection_data: 177 continue 178 kwargs[ckey] = self.connection_data.get(dkey) 179 180 try: 181 self.dbconn = self.mysql.connect(**kwargs) 182 except self.mysql_exceptions.OperationalError as e: 183 raise ConnectionError('ConnectionError: %s' % (e,)) 184 self.plain_cursor = self.dbconn.cursor() 185 self.cursor = self.mysql.cursors.DictCursor(self.dbconn) 186 self.escape_string = self.dbconn.escape_string 187 return True
188
189 - def disconnect(self):
190 self.check_connection() 191 self.escape_string = escape 192 if hasattr(self.cursor, 'close'): 193 self.cursor.close() 194 if hasattr(self.dbconn, 'close'): 195 self.dbconn.close() 196 self.dbconn = None 197 self.cursor = None 198 self.plain_cursor = None 199 self.connection_data.clear() 200 return True
201
202 - def commit(self):
203 self.check_connection() 204 return self.dbconn.commit()
205
206 - def execute_script(self, myscript):
207 pty = None 208 for line in myscript.split(";"): 209 line = line.strip() 210 if not line: 211 continue 212 pty = self.cursor.execute(line) 213 return pty
214
215 - def execute_query(self, *args):
216 return self.cursor.execute(*args)
217
218 - def execute_many(self, query, myiter):
219 return self.cursor.executemany(query, myiter)
220
221 - def fetchone(self):
222 return self.cursor.fetchone()
223
224 - def fetchall(self):
225 return self.cursor.fetchall()
226
227 - def fetchmany(self, *args, **kwargs):
228 return self.cursor.fetchmany(*args,**kwargs)
229
230 - def lastrowid(self):
231 return self.cursor.lastrowid
232
233 - def table_exists(self, table):
234 self.check_connection() 235 self.cursor.execute("show tables like %s", (table,)) 236 rslt = self.cursor.fetchone() 237 if rslt: 238 return True 239 return False
240
241 - def column_in_table_exists(self, table, column):
242 t_ex = self.table_exists(table) 243 if not t_ex: 244 return False 245 self.cursor.execute("show columns from "+table) 246 data = self.cursor.fetchall() 247 for row in data: 248 if row['Field'] == column: 249 return True 250 return False
251
252 - def fetchall2set(self, item):
253 mycontent = set() 254 for x in item: 255 mycontent |= set(x) 256 return mycontent
257
258 - def fetchall2list(self, item):
259 content = [] 260 for x in item: 261 content += list(x) 262 return content
263
264 - def fetchone2list(self, item):
265 return list(item)
266
267 - def fetchone2set(self, item):
268 return set(item)
269
270 - def _generate_sql(self, action, table, data, where = ''):
271 sql = '' 272 keys = sorted(data.keys()) 273 if action == "update": 274 sql += 'UPDATE %s SET ' % (self.escape_string(table),) 275 keys_data = [] 276 for key in keys: 277 keys_data.append("%s = '%s'" % ( 278 self.escape_string(key), 279 self.escape_string( 280 const_convert_to_unicode(data[key], 'utf-8').encode('utf-8')).decode('utf-8') 281 ) 282 ) 283 sql += ', '.join(keys_data) 284 sql += ' WHERE %s' % (where,) 285 elif action == "insert": 286 sql = 'INSERT INTO %s (%s) VALUES (%s)' % ( 287 self.escape_string(table), 288 ', '.join([self.escape_string(x) for x in keys]), 289 ', '.join(["'" + \ 290 self.escape_string( 291 const_convert_to_unicode(data[x], 'utf-8').encode('utf-8')).decode('utf-8') + \ 292 "'" for x in keys]) 293 ) 294 return sql
295
296 -class Authenticator:
297
298 - def __init__(self):
299 self.login_data = {} 300 self.logged_in = False
301
302 - def check_login(self):
303 if not self.logged_in: 304 raise PermissionDenied('PermissionDenied: %s' % (_("not logged in"),))
305
306 - def set_login_data(self, data):
307 self.login_data = data.copy()
308
309 - def check_login_data(self):
310 if not self.login_data: 311 raise PermissionDenied('PermissionDenied: %s' % (_("no login data"),))
312
313 - def check_logged_in(self):
314 if not self.is_logged_in(): 315 raise PermissionDenied('PermissionDenied: %s' % (_("not logged in"),))
316
318 raise NotImplementedError('NotImplementedError: %s' % (_('method not implemented'),))
319
320 - def check_connection(self):
321 pass
322
323 - def login(self):
324 self.check_connection() 325 self.check_login_data() 326 self._raise_not_implemented_error() 327 self.logged_in = True 328 return True
329
330 - def logout(self):
331 self.check_connection() 332 self.check_login_data() 333 self._raise_not_implemented_error() 334 return True
335
336 - def is_developer(self):
337 self.check_connection() 338 self.check_login_data() 339 self.check_logged_in() 340 self._raise_not_implemented_error() 341 return True
342
343 - def is_administrator(self):
344 self.check_connection() 345 self.check_login_data() 346 self.check_logged_in() 347 self._raise_not_implemented_error() 348 return True
349
350 - def is_moderator(self):
351 self.check_connection() 352 self.check_login_data() 353 self.check_logged_in() 354 self._raise_not_implemented_error() 355 return True
356
357 - def is_user(self):
358 self.check_connection() 359 self.check_login_data() 360 self.check_logged_in() 361 self._raise_not_implemented_error() 362 return True
363
364 - def is_user_banned(self, user):
365 self.check_connection() 366 self._raise_not_implemented_error() 367 return False
368
369 - def is_in_group(self, group):
370 self.check_connection() 371 self.check_login_data() 372 self.check_logged_in() 373 self._raise_not_implemented_error() 374 return True
375
376 - def get_user_groups(self):
377 self.check_connection() 378 self.check_login_data() 379 self.check_logged_in() 380 self._raise_not_implemented_error() 381 return {}
382
383 - def get_user_group(self):
384 self.check_connection() 385 self.check_login_data() 386 self.check_logged_in() 387 self._raise_not_implemented_error() 388 return -1
389
390 - def get_user_id(self):
391 self.check_connection() 392 self.check_login_data() 393 self.check_logged_in() 394 self._raise_not_implemented_error() 395 return -1
396
397 - def is_logged_in(self):
398 return self.logged_in
399
400 - def get_permission_data(self):
401 self.check_connection() 402 self.check_login_data() 403 self.check_logged_in() 404 self._raise_not_implemented_error() 405 return {}
406
407 - def get_user_data(self):
408 self.check_connection() 409 self.check_login_data() 410 self.check_logged_in() 411 self._raise_not_implemented_error() 412 return {}
413
414 - def get_username(self):
415 self.check_connection() 416 self.check_login_data() 417 self.check_logged_in() 418 self._raise_not_implemented_error() 419 return {}
420