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, is_foreign_node = False, commit = True):
130 Add node to existing slice.
133 assert 'slice_id' in self
134 if not is_foreign_node:
135 assert isinstance(node, Node)
137 assert isinstance(node, ForeignNode)
138 assert 'node_id' in node
140 slice_id = self['slice_id']
141 node_id = node['node_id']
143 if node_id not in self['node_ids']:
144 assert slice_id not in node['slice_ids']
146 self.api.db.do("INSERT INTO slice_node (node_id, slice_id)" \
147 " VALUES(%(node_id)d, %(slice_id)d)",
153 self['node_ids'].append(node_id)
154 node['slice_ids'].append(slice_id)
156 def remove_node(self, node, is_foreign_node = False, commit = True):
158 Remove node from existing slice.
161 assert 'slice_id' in self
162 if not is_foreign_node:
163 assert isinstance(node, Node)
165 assert isinstance(node, ForeignNode)
166 assert 'node_id' in node
168 slice_id = self['slice_id']
169 node_id = node['node_id']
171 if node_id in self['node_ids']:
172 assert slice_id in node['slice_ids']
174 self.api.db.do("DELETE FROM slice_node" \
175 " WHERE node_id = %(node_id)d" \
176 " AND slice_id = %(slice_id)d",
182 self['node_ids'].remove(node_id)
183 node['slice_ids'].remove(slice_id)
185 def sync(self, commit = True):
187 Add or update a slice.
190 # Before a new slice is added, delete expired slices
191 if 'slice_id' not in self:
192 expired = Slices(self.api, expires = -int(time.time()))
193 for slice in expired:
196 Row.sync(self, commit)
198 def delete(self, commit = True):
200 Delete existing slice.
203 assert 'slice_id' in self
205 # Clean up miscellaneous join tables
206 for table in ['slice_node', 'slice_person', 'slice_attribute']:
207 self.api.db.do("DELETE FROM %s" \
208 " WHERE slice_id = %d" % \
209 (table, self['slice_id']), self)
212 self['deleted'] = True
217 Representation of row(s) from the slices table in the
221 def __init__(self, api, slice_filter = None, columns = None, expires = int(time.time())):
222 Table.__init__(self, api, Slice, columns)
224 sql = "SELECT %s FROM view_slices WHERE deleted IS False" % \
225 ", ".join(self.columns)
227 if expires is not None:
229 sql += " AND expires > %(expires)d"
232 sql += " AND expires < %(expires)d"
234 if slice_filter is not None:
235 if isinstance(slice_filter, (list, tuple, set)):
236 # Separate the list into integers and strings
237 ints = filter(lambda x: isinstance(x, (int, long)), slice_filter)
238 strs = filter(lambda x: isinstance(x, StringTypes), slice_filter)
239 slice_filter = Filter(Slice.fields, {'slice_id': ints, 'name': strs})
240 sql += " AND (%s)" % slice_filter.sql(api, "OR")
241 elif isinstance(slice_filter, dict):
242 slice_filter = Filter(Slice.fields, slice_filter)
243 sql += " AND (%s)" % slice_filter.sql(api, "AND")
245 self.selectall(sql, locals())