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
12 Representation of a row in the slices table. To use, optionally
13 instantiate with a dict of values. Update as you would a
14 dict. Commit to the database with sync().To use, instantiate
15 with a dict of values.
19 'slice_id': Parameter(int, "Slice type"),
20 'site_id': Parameter(int, "Identifier of the site to which this slice belongs"),
21 'name': Parameter(str, "Slice name", max = 32),
22 'state': Parameter(str, "Slice state"),
23 'url': Parameter(str, "URL further describing this slice", max = 254),
24 'description': Parameter(str, "Slice description", max = 2048),
25 'max_nodes': Parameter(int, "Maximum number of nodes that can be assigned to this slice"),
26 'creator_person_id': Parameter(int, "Identifier of the account that created this slice"),
27 'created': Parameter(int, "Date and time when slice was created, in seconds since UNIX epoch"),
28 'expires': Parameter(int, "Date and time when slice expires, in seconds since UNIX epoch"),
29 'is_deleted': Parameter(bool, "Has been deleted"),
30 'node_ids': Parameter([int], "List of nodes in this slice"),
31 'person_ids': Parameter([int], "List of accounts that can use this slice"),
32 'attribute_ids': Parameter([int], "List of slice attributes"),
35 def __init__(self, api, fields):
36 Row.__init__(self, fields)
39 def validate_name(self, name):
40 # N.B.: Responsibility of the caller to ensure that login_base
41 # portion of the slice name corresponds to a valid site, if
43 conflicts = Slices(self.api, [name])
44 for slice_id, slice in conflicts.iteritems():
45 if not slice['is_deleted'] and ('slice_id' not in self or self['slice_id'] != slice_id):
46 raise PLCInvalidArgument, "Slice name already in use"
50 def validate_instantiation(self, instantiation):
51 instantiations = SliceInstantiations(self.api)
52 if instantiation not in instantiations:
53 raise PLCInvalidArgument, "No such instantiation state"
57 def validate_expires(self, expires):
58 # N.B.: Responsibility of the caller to ensure that expires is
59 # not too far into the future.
60 if expires < time.time():
61 raise PLCInvalidArgument, "Expiration date must be in the future"
63 return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires))
65 def validate_creator_person_id(self, person_id):
66 persons = PLC.Persons.Persons(self.api, [person_id])
68 raise PLCInvalidArgument, "Invalid creator"
72 def sync(self, commit = True):
74 Flush changes back to the database.
81 raise PLCInvalidArgument, "Slice name must be specified"
85 # Fetch a new slice_id if necessary
86 if 'slice_id' not in self:
87 # N.B.: Responsibility of the caller to ensure that
88 # max_slices is not exceeded.
89 rows = self.api.db.selectall("SELECT NEXTVAL('slices_slice_id_seq') AS slice_id")
91 raise PLCDBError, "Unable to fetch new slice_id"
92 self['slice_id'] = rows[0]['slice_id']
97 # Filter out fields that cannot be set or updated directly
98 slices_fields = self.api.db.fields('slices')
99 fields = dict(filter(lambda (key, value): key in slices_fields,
101 for ro_field in 'created',:
102 if ro_field in fields:
105 # Parameterize for safety
107 values = [self.api.db.param(key, value) for (key, value) in fields.items()]
110 # Insert new row in slices table
111 sql = "INSERT INTO slices (%s) VALUES (%s)" % \
112 (", ".join(keys), ", ".join(values))
114 # Update existing row in slices table
115 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
116 sql = "UPDATE slices SET " + \
117 ", ".join(columns) + \
118 " WHERE slice_id = %(slice_id)d"
120 self.api.db.do(sql, fields)
125 def delete(self, commit = True):
127 Delete existing slice.
130 assert 'slice_id' in self
132 # Clean up miscellaneous join tables
133 for table in ['slice_node', 'slice_person', 'slice_attribute']:
134 self.api.db.do("DELETE FROM %s" \
135 " WHERE slice_id = %d" % \
136 (table, self['slice_id']), self)
139 self['is_deleted'] = True
144 Representation of row(s) from the slices table in the
148 def __init__(self, api, slice_id_or_name_list = None, deleted = False):
151 sql = "SELECT * FROM view_slices WHERE TRUE"
153 if deleted is not None:
154 sql += " AND view_slices.is_deleted IS %(deleted)s"
156 if slice_id_or_name_list:
157 # Separate the list into integers and strings
158 slice_ids = filter(lambda slice_id: isinstance(slice_id, (int, long)),
159 slice_id_or_name_list)
160 names = filter(lambda name: isinstance(name, StringTypes),
161 slice_id_or_name_list)
164 sql += " OR slice_id IN (%s)" % ", ".join(map(str, slice_ids))
166 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names))
169 rows = self.api.db.selectall(sql, locals())
172 self[row['slice_id']] = slice = Slice(api, row)
173 for aggregate in 'person_ids', 'slice_ids', 'attribute_ids':
174 if not slice.has_key(aggregate) or slice[aggregate] is None:
175 slice[aggregate] = []
177 slice[aggregate] = map(int, slice[aggregate].split(','))