X-Git-Url: http://git.onelab.eu/?a=blobdiff_plain;f=PLC%2FSlices.py;h=af6062d6ceae7d8ce61a03c7f375e27e86e5506a;hb=8c0ae6e3e6c872da288c4b4cc2fe017f18e70f20;hp=82e32afd3104428923f9abb2b64156fc18ebb5a7;hpb=9ef7bab81eab435622eea64e5150b004b419f194;p=plcapi.git diff --git a/PLC/Slices.py b/PLC/Slices.py index 82e32af..af6062d 100644 --- a/PLC/Slices.py +++ b/PLC/Slices.py @@ -1,11 +1,15 @@ from types import StringTypes import time +import re from PLC.Faults import * from PLC.Parameter import Parameter +from PLC.Filter import Filter from PLC.Debug import profile from PLC.Table import Row, Table -import PLC.Persons +from PLC.SliceInstantiations import SliceInstantiation, SliceInstantiations +from PLC.Nodes import Node, Nodes +from PLC.Persons import Person, Persons class Slice(Row): """ @@ -15,112 +19,92 @@ class Slice(Row): with a dict of values. """ + table_name = 'slices' + primary_key = 'slice_id' + join_tables = ['slice_node', 'slice_person', 'slice_attribute', 'peer_slice'] fields = { - 'slice_id': Parameter(int, "Slice type"), + 'slice_id': Parameter(int, "Slice identifier"), 'site_id': Parameter(int, "Identifier of the site to which this slice belongs"), 'name': Parameter(str, "Slice name", max = 32), - 'state': Parameter(str, "Slice state"), - 'url': Parameter(str, "URL further describing this slice", max = 254), - 'description': Parameter(str, "Slice description", max = 2048), + 'instantiation': Parameter(str, "Slice instantiation state"), + 'url': Parameter(str, "URL further describing this slice", max = 254, nullok = True), + 'description': Parameter(str, "Slice description", max = 2048, nullok = True), 'max_nodes': Parameter(int, "Maximum number of nodes that can be assigned to this slice"), 'creator_person_id': Parameter(int, "Identifier of the account that created this slice"), - 'created': Parameter(int, "Date and time when slice was created, in seconds since UNIX epoch"), + 'created': Parameter(int, "Date and time when slice was created, in seconds since UNIX epoch", ro = True), 'expires': Parameter(int, "Date and time when slice expires, in seconds since UNIX epoch"), - 'is_deleted': Parameter(bool, "Has been deleted"), - 'node_ids': Parameter([int], "List of nodes in this slice"), - 'person_ids': Parameter([int], "List of accounts that can use this slice"), - 'attribute_ids': Parameter([int], "List of slice attributes"), + 'node_ids': Parameter([int], "List of nodes in this slice", ro = True), + 'person_ids': Parameter([int], "List of accounts that can use this slice", ro = True), + 'slice_attribute_ids': Parameter([int], "List of slice attributes", ro = True), + 'peer_id': Parameter(int, "Peer to which this slice belongs", nullok = True), + 'peer_slice_id': Parameter(int, "Foreign slice identifier at peer", nullok = True), } - - def __init__(self, api, fields): - Row.__init__(self, fields) - self.api = api + # for Cache + class_key = 'name' + foreign_fields = ['instantiation', 'url', 'description', 'max_nodes', 'expires'] + foreign_xrefs = [ + {'field': 'node_ids' , 'class': 'Node', 'table': 'slice_node' }, + {'field': 'person_ids', 'class': 'Person', 'table': 'slice_person'}, + {'field': 'creator_person_id', 'class': 'Person', 'table': 'unused-on-direct-refs'}, + {'field': 'site_id', 'class': 'Site', 'table': 'unused-on-direct-refs'}, + ] + # forget about this one, it is read-only anyway + # handling it causes Cache to re-sync all over again + # 'created' def validate_name(self, name): # N.B.: Responsibility of the caller to ensure that login_base # portion of the slice name corresponds to a valid site, if # desired. + + # 1. Lowercase. + # 2. Begins with login_base (only letters). + # 3. Then single underscore after login_base. + # 4. Then letters, numbers, or underscores. + good_name = r'^[a-z]+_[a-z0-9_]+$' + if not name or \ + not re.match(good_name, name): + raise PLCInvalidArgument, "Invalid slice name" + conflicts = Slices(self.api, [name]) - for slice_id, slice in conflicts.iteritems(): - if not slice['is_deleted'] and ('slice_id' not in self or self['slice_id'] != slice_id): - raise PLCInvalidArgument, "Slice name already in use" + for slice in conflicts: + if 'slice_id' not in self or self['slice_id'] != slice['slice_id']: + raise PLCInvalidArgument, "Slice name already in use, %s"%name return name def validate_instantiation(self, instantiation): - instantiations = SliceInstantiations(self.api) + instantiations = [row['instantiation'] for row in SliceInstantiations(self.api)] if instantiation not in instantiations: raise PLCInvalidArgument, "No such instantiation state" - return state + return instantiation + + validate_created = Row.validate_timestamp def validate_expires(self, expires): # N.B.: Responsibility of the caller to ensure that expires is # not too far into the future. - if expires < time.time(): - raise PLCInvalidArgument, "Expiration date must be in the future" + return Row.validate_timestamp(self, expires, check_future = True) - return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires)) + add_person = Row.add_object(Person, 'slice_person') + remove_person = Row.remove_object(Person, 'slice_person') - def validate_creator_person_id(self, person_id): - persons = PLC.Persons.Persons(self.api, [person_id]) - if not persons: - raise PLCInvalidArgument, "Invalid creator" - - return person_id + add_node = Row.add_object(Node, 'slice_node') + remove_node = Row.remove_object(Node, 'slice_node') def sync(self, commit = True): """ - Flush changes back to the database. + Add or update a slice. """ - try: - if not self['name']: - raise KeyError - except KeyError: - raise PLCInvalidArgument, "Slice name must be specified" - - self.validate() - - # Fetch a new slice_id if necessary + # Before a new slice is added, delete expired slices if 'slice_id' not in self: - # N.B.: Responsibility of the caller to ensure that - # max_slices is not exceeded. - rows = self.api.db.selectall("SELECT NEXTVAL('slices_slice_id_seq') AS slice_id") - if not rows: - raise PLCDBError, "Unable to fetch new slice_id" - self['slice_id'] = rows[0]['slice_id'] - insert = True - else: - insert = False - - # Filter out fields that cannot be set or updated directly - slices_fields = self.api.db.fields('slices') - fields = dict(filter(lambda (key, value): key in slices_fields, - self.items())) - for ro_field in 'created',: - if ro_field in fields: - del fields[ro_field] - - # Parameterize for safety - keys = fields.keys() - values = [self.api.db.param(key, value) for (key, value) in fields.items()] - - if insert: - # Insert new row in slices table - sql = "INSERT INTO slices (%s) VALUES (%s)" % \ - (", ".join(keys), ", ".join(values)) - else: - # Update existing row in slices table - columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)] - sql = "UPDATE slices SET " + \ - ", ".join(columns) + \ - " WHERE slice_id = %(slice_id)d" - - self.api.db.do(sql, fields) - - if commit: - self.api.db.commit() + expired = Slices(self.api, expires = -int(time.time())) + for slice in expired: + slice.delete(commit) + + Row.sync(self, commit) def delete(self, commit = True): """ @@ -130,10 +114,9 @@ class Slice(Row): assert 'slice_id' in self # Clean up miscellaneous join tables - for table in ['slice_node', 'slice_person', 'slice_attribute']: - self.api.db.do("DELETE FROM %s" \ - " WHERE slice_id = %d" % \ - (table, self['slice_id']), self) + for table in self.join_tables: + self.api.db.do("DELETE FROM %s WHERE slice_id = %d" % \ + (table, self['slice_id'])) # Mark as deleted self['is_deleted'] = True @@ -145,33 +128,28 @@ class Slices(Table): database. """ - def __init__(self, api, slice_id_or_name_list = None, deleted = False): - self.api = api - - sql = "SELECT * FROM view_slices WHERE TRUE" - - if deleted is not None: - sql += " AND view_slices.is_deleted IS %(deleted)s" - - if slice_id_or_name_list: - # Separate the list into integers and strings - slice_ids = filter(lambda slice_id: isinstance(slice_id, (int, long)), - slice_id_or_name_list) - names = filter(lambda name: isinstance(name, StringTypes), - slice_id_or_name_list) - sql += " AND (False" - if slice_ids: - sql += " OR slice_id IN (%s)" % ", ".join(map(str, slice_ids)) - if names: - sql += " OR name IN (%s)" % ", ".join(api.db.quote(names)) - sql += ")" - - rows = self.api.db.selectall(sql, locals()) - - for row in rows: - self[row['slice_id']] = slice = Slice(api, row) - for aggregate in 'person_ids', 'slice_ids', 'attribute_ids': - if not slice.has_key(aggregate) or slice[aggregate] is None: - slice[aggregate] = [] - else: - slice[aggregate] = map(int, slice[aggregate].split(',')) + def __init__(self, api, slice_filter = None, columns = None, expires = int(time.time())): + Table.__init__(self, api, Slice, columns) + + sql = "SELECT %s FROM view_slices WHERE is_deleted IS False" % \ + ", ".join(self.columns) + + if expires is not None: + if expires >= 0: + sql += " AND expires > %(expires)d" + else: + expires = -expires + sql += " AND expires < %(expires)d" + + if slice_filter is not None: + if isinstance(slice_filter, (list, tuple, set)): + # Separate the list into integers and strings + ints = filter(lambda x: isinstance(x, (int, long)), slice_filter) + strs = filter(lambda x: isinstance(x, StringTypes), slice_filter) + slice_filter = Filter(Slice.fields, {'slice_id': ints, 'name': strs}) + sql += " AND (%s)" % slice_filter.sql(api, "OR") + elif isinstance(slice_filter, dict): + slice_filter = Filter(Slice.fields, slice_filter) + sql += " AND (%s)" % slice_filter.sql(api, "AND") + + self.selectall(sql, locals())