1 from types import StringTypes
4 from PLC.Faults import *
5 from PLC.Parameter import Parameter
6 from PLC.Debug import profile
7 from PLC.Table import Row, Table
8 from PLC.SliceInstantiations import SliceInstantiations
13 Representation of a row in the slices table. To use, optionally
14 instantiate with a dict of values. Update as you would a
15 dict. Commit to the database with sync().To use, instantiate
16 with a dict of values.
20 'slice_id': Parameter(int, "Slice type"),
21 'site_id': Parameter(int, "Identifier of the site to which this slice belongs"),
22 'name': Parameter(str, "Slice name", max = 32),
23 'state': Parameter(str, "Slice state"),
24 'url': Parameter(str, "URL further describing this slice", max = 254),
25 'description': Parameter(str, "Slice description", max = 2048),
26 'max_nodes': Parameter(int, "Maximum number of nodes that can be assigned to this slice"),
27 'creator_person_id': Parameter(int, "Identifier of the account that created this slice"),
28 'created': Parameter(int, "Date and time when slice was created, in seconds since UNIX epoch"),
29 'expires': Parameter(int, "Date and time when slice expires, in seconds since UNIX epoch"),
30 'is_deleted': Parameter(bool, "Has been deleted"),
31 'node_ids': Parameter([int], "List of nodes in this slice"),
32 'person_ids': Parameter([int], "List of accounts that can use this slice"),
33 'attribute_ids': Parameter([int], "List of slice attributes"),
36 def __init__(self, api, fields):
37 Row.__init__(self, fields)
40 def validate_name(self, name):
41 # N.B.: Responsibility of the caller to ensure that login_base
42 # portion of the slice name corresponds to a valid site, if
44 conflicts = Slices(self.api, [name])
45 for slice_id, slice in conflicts.iteritems():
46 if not slice['is_deleted'] and ('slice_id' not in self or self['slice_id'] != slice_id):
47 raise PLCInvalidArgument, "Slice name already in use"
51 def validate_instantiation(self, instantiation):
52 instantiations = SliceInstantiations(self.api)
53 if instantiation not in instantiations:
54 raise PLCInvalidArgument, "No such instantiation state"
58 def validate_expires(self, expires):
59 # N.B.: Responsibility of the caller to ensure that expires is
60 # not too far into the future.
61 if expires < time.time():
62 raise PLCInvalidArgument, "Expiration date must be in the future"
64 return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires))
66 def validate_creator_person_id(self, person_id):
67 persons = PLC.Persons.Persons(self.api, [person_id])
69 raise PLCInvalidArgument, "Invalid creator"
73 def sync(self, commit = True):
75 Flush changes back to the database.
82 raise PLCInvalidArgument, "Slice name must be specified"
86 # Fetch a new slice_id if necessary
87 if 'slice_id' not in self:
88 # N.B.: Responsibility of the caller to ensure that
89 # max_slices is not exceeded.
90 rows = self.api.db.selectall("SELECT NEXTVAL('slices_slice_id_seq') AS slice_id")
92 raise PLCDBError, "Unable to fetch new slice_id"
93 self['slice_id'] = rows[0]['slice_id']
98 # Filter out fields that cannot be set or updated directly
99 slices_fields = self.api.db.fields('slices')
100 fields = dict(filter(lambda (key, value): key in slices_fields,
102 for ro_field in 'created',:
103 if ro_field in fields:
106 # Parameterize for safety
108 values = [self.api.db.param(key, value) for (key, value) in fields.items()]
111 # Insert new row in slices table
112 sql = "INSERT INTO slices (%s) VALUES (%s)" % \
113 (", ".join(keys), ", ".join(values))
115 # Update existing row in slices table
116 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
117 sql = "UPDATE slices SET " + \
118 ", ".join(columns) + \
119 " WHERE slice_id = %(slice_id)d"
121 self.api.db.do(sql, fields)
126 def delete(self, commit = True):
128 Delete existing slice.
131 assert 'slice_id' in self
133 # Clean up miscellaneous join tables
134 for table in ['slice_node', 'slice_person', 'slice_attribute']:
135 self.api.db.do("DELETE FROM %s" \
136 " WHERE slice_id = %d" % \
137 (table, self['slice_id']), self)
140 self['is_deleted'] = True
145 Representation of row(s) from the slices table in the
149 def __init__(self, api, slice_id_or_name_list = None, deleted = False):
152 sql = "SELECT * FROM view_slices WHERE TRUE"
154 if deleted is not None:
155 sql += " AND view_slices.is_deleted IS %(deleted)s"
157 if slice_id_or_name_list:
158 # Separate the list into integers and strings
159 slice_ids = filter(lambda slice_id: isinstance(slice_id, (int, long)),
160 slice_id_or_name_list)
161 names = filter(lambda name: isinstance(name, StringTypes),
162 slice_id_or_name_list)
165 sql += " OR slice_id IN (%s)" % ", ".join(map(str, slice_ids))
167 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names))
170 rows = self.api.db.selectall(sql, locals())
173 self[row['slice_id']] = slice = Slice(api, row)
174 for aggregate in 'person_ids', 'slice_ids', 'attribute_ids':
175 if not slice.has_key(aggregate) or slice[aggregate] is None:
176 slice[aggregate] = []
178 slice[aggregate] = map(int, slice[aggregate].split(','))