1 from types import StringTypes
5 from PLC.Faults import *
6 from PLC.Parameter import Parameter
7 from PLC.Filter import Filter
8 from PLC.Debug import profile
9 from PLC.Table import Row, Table
10 from PLC.SliceInstantiations import SliceInstantiations
11 from PLC.Nodes import Node, Nodes
12 from PLC.ForeignNodes import ForeignNode, ForeignNodes
17 Representation of a row in the slices table. To use, optionally
18 instantiate with a dict of values. Update as you would a
19 dict. Commit to the database with sync().To use, instantiate
20 with a dict of values.
24 primary_key = 'slice_id'
26 'slice_id': Parameter(int, "Slice identifier"),
27 'site_id': Parameter(int, "Identifier of the site to which this slice belongs"),
28 'name': Parameter(str, "Slice name", max = 32),
29 'instantiation': Parameter(str, "Slice instantiation state"),
30 'url': Parameter(str, "URL further describing this slice", max = 254, nullok = True),
31 'description': Parameter(str, "Slice description", max = 2048, nullok = True),
32 'max_nodes': Parameter(int, "Maximum number of nodes that can be assigned to this slice"),
33 'creator_person_id': Parameter(int, "Identifier of the account that created this slice"),
34 'created': Parameter(int, "Date and time when slice was created, in seconds since UNIX epoch", ro = True),
35 'expires': Parameter(int, "Date and time when slice expires, in seconds since UNIX epoch"),
36 'node_ids': Parameter([int], "List of nodes in this slice", ro = True),
37 'person_ids': Parameter([int], "List of accounts that can use this slice", ro = True),
38 'slice_attribute_ids': Parameter([int], "List of slice attributes", ro = True),
41 def validate_name(self, name):
42 # N.B.: Responsibility of the caller to ensure that login_base
43 # portion of the slice name corresponds to a valid site, if
47 # 2. Begins with login_base (only letters).
48 # 3. Then single underscore after login_base.
49 # 4. Then letters, numbers, or underscores.
50 good_name = r'^[a-z]+_[a-z0-9_]+$'
52 not re.match(good_name, name):
53 raise PLCInvalidArgument, "Invalid slice name"
55 conflicts = Slices(self.api, [name])
56 for slice in conflicts:
57 if 'slice_id' not in self or self['slice_id'] != slice['slice_id']:
58 raise PLCInvalidArgument, "Slice name already in use"
62 def validate_instantiation(self, instantiation):
63 instantiations = [row['instantiation'] for row in SliceInstantiations(self.api)]
64 if instantiation not in instantiations:
65 raise PLCInvalidArgument, "No such instantiation state"
69 def validate_expires(self, expires):
70 # N.B.: Responsibility of the caller to ensure that expires is
71 # not too far into the future.
72 if expires < time.time():
73 raise PLCInvalidArgument, "Expiration date must be in the future"
75 return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires))
77 def add_person(self, person, commit = True):
79 Add person to existing slice.
82 assert 'slice_id' in self
83 assert isinstance(person, PLC.Persons.Person)
84 assert 'person_id' in person
86 slice_id = self['slice_id']
87 person_id = person['person_id']
89 if person_id not in self['person_ids']:
90 assert slice_id not in person['slice_ids']
92 self.api.db.do("INSERT INTO slice_person (person_id, slice_id)" \
93 " VALUES(%(person_id)d, %(slice_id)d)",
99 self['person_ids'].append(person_id)
100 person['slice_ids'].append(slice_id)
102 def remove_person(self, person, commit = True):
104 Remove person from existing slice.
107 assert 'slice_id' in self
108 assert isinstance(person, PLC.Persons.Person)
109 assert 'person_id' in person
111 slice_id = self['slice_id']
112 person_id = person['person_id']
114 if person_id in self['person_ids']:
115 assert slice_id in person['slice_ids']
117 self.api.db.do("DELETE FROM slice_person" \
118 " WHERE person_id = %(person_id)d" \
119 " AND slice_id = %(slice_id)d",
125 self['person_ids'].remove(person_id)
126 person['slice_ids'].remove(slice_id)
128 def add_node(self, node, commit = True):
130 Add node to existing slice.
133 assert 'slice_id' in self
134 assert isinstance(node, (Node,ForeignNode))
135 assert 'node_id' in node
137 slice_id = self['slice_id']
138 node_id = node['node_id']
140 if node_id not in self['node_ids']:
141 assert slice_id not in node['slice_ids']
143 self.api.db.do("INSERT INTO slice_node (node_id, slice_id)" \
144 " VALUES(%(node_id)d, %(slice_id)d)",
150 self['node_ids'].append(node_id)
151 node['slice_ids'].append(slice_id)
153 def remove_node(self, node, commit = True):
155 Remove node from existing slice.
158 assert 'slice_id' in self
159 assert isinstance(node, (Node,ForeignNode))
160 assert 'node_id' in node
162 slice_id = self['slice_id']
163 node_id = node['node_id']
165 if node_id in self['node_ids']:
166 assert slice_id in node['slice_ids']
168 self.api.db.do("DELETE FROM slice_node" \
169 " WHERE node_id = %(node_id)d" \
170 " AND slice_id = %(slice_id)d",
176 self['node_ids'].remove(node_id)
177 node['slice_ids'].remove(slice_id)
179 def sync(self, commit = True):
181 Add or update a slice.
184 # Before a new slice is added, delete expired slices
185 if 'slice_id' not in self:
186 expired = Slices(self.api, expires = -int(time.time()))
187 for slice in expired:
190 Row.sync(self, commit)
192 def delete(self, commit = True):
194 Delete existing slice.
197 assert 'slice_id' in self
199 # Clean up miscellaneous join tables
200 for table in ['slice_node', 'slice_person', 'slice_attribute']:
201 self.api.db.do("DELETE FROM %s" \
202 " WHERE slice_id = %d" % \
203 (table, self['slice_id']), self)
206 self['deleted'] = True
211 Representation of row(s) from the slices table in the
215 def __init__(self, api, slice_filter = None, columns = None, expires = int(time.time())):
216 Table.__init__(self, api, Slice, columns)
218 sql = "SELECT %s FROM view_slices WHERE deleted IS False" % \
219 ", ".join(self.columns)
221 if expires is not None:
223 sql += " AND expires > %(expires)d"
226 sql += " AND expires < %(expires)d"
228 if slice_filter is not None:
229 if isinstance(slice_filter, (list, tuple, set)):
230 # Separate the list into integers and strings
231 ints = filter(lambda x: isinstance(x, (int, long)), slice_filter)
232 strs = filter(lambda x: isinstance(x, StringTypes), slice_filter)
233 slice_filter = Filter(Slice.fields, {'slice_id': ints, 'name': strs})
234 sql += " AND (%s)" % slice_filter.sql(api, "OR")
235 elif isinstance(slice_filter, dict):
236 slice_filter = Filter(Slice.fields, slice_filter)
237 sql += " AND (%s)" % slice_filter.sql(api, "AND")
239 self.selectall(sql, locals())