iteration 4 & last:
[plcapi.git] / PLC / Slices.py
1 from types import StringTypes
2 import time
3 import re
4
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 import PLC.Persons
13
14 class Slice(Row):
15     """
16     Representation of a row in the slices table. To use, optionally
17     instantiate with a dict of values. Update as you would a
18     dict. Commit to the database with sync().To use, instantiate
19     with a dict of values.
20     """
21
22     table_name = 'slices'
23     primary_key = 'slice_id'
24     fields = {
25         'slice_id': Parameter(int, "Slice identifier"),
26         'site_id': Parameter(int, "Identifier of the site to which this slice belongs"),
27         'peer_id': Parameter(int, "Peer at which this slice was created", nullok = True),
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),
39         }
40
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
44         # desired.
45
46         # 1. Lowercase.
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_]+$'
51         if not name or \
52            not re.match(good_name, name):
53             raise PLCInvalidArgument, "Invalid slice name"
54
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"
59
60         return name
61
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"
66
67         return instantiation
68
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"
74
75         return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires))
76
77     def add_person(self, person, commit = True):
78         """
79         Add person to existing slice.
80         """
81
82         assert 'slice_id' in self
83         assert isinstance(person, PLC.Persons.Person)
84         assert 'person_id' in person
85
86         slice_id = self['slice_id']
87         person_id = person['person_id']
88
89         if person_id not in self['person_ids']:
90             assert slice_id not in person['slice_ids']
91
92             self.api.db.do("INSERT INTO slice_person (person_id, slice_id)" \
93                            " VALUES(%(person_id)d, %(slice_id)d)",
94                            locals())
95
96             if commit:
97                 self.api.db.commit()
98
99             self['person_ids'].append(person_id)
100             person['slice_ids'].append(slice_id)
101
102     def remove_person(self, person, commit = True):
103         """
104         Remove person from existing slice.
105         """
106
107         assert 'slice_id' in self
108         assert isinstance(person, PLC.Persons.Person)
109         assert 'person_id' in person
110
111         slice_id = self['slice_id']
112         person_id = person['person_id']
113
114         if person_id in self['person_ids']:
115             assert slice_id in person['slice_ids']
116
117             self.api.db.do("DELETE FROM slice_person" \
118                            " WHERE person_id = %(person_id)d" \
119                            " AND slice_id = %(slice_id)d",
120                            locals())
121
122             if commit:
123                 self.api.db.commit()
124
125             self['person_ids'].remove(person_id)
126             person['slice_ids'].remove(slice_id)
127
128     def add_node(self, node, commit = True):
129         """
130         Add node to existing slice.
131         """
132
133         assert 'slice_id' in self
134         assert isinstance(node, Node)
135         assert 'node_id' in node
136
137         slice_id = self['slice_id']
138         node_id = node['node_id']
139
140         if node_id not in self['node_ids']:
141             assert slice_id not in node['slice_ids']
142
143             self.api.db.do("INSERT INTO slice_node (node_id, slice_id)" \
144                            " VALUES(%(node_id)d, %(slice_id)d)",
145                            locals())
146
147             if commit:
148                 self.api.db.commit()
149
150             self['node_ids'].append(node_id)
151             node['slice_ids'].append(slice_id)
152
153     def remove_node(self, node, commit = True):
154         """
155         Remove node from existing slice.
156         """
157
158         assert 'slice_id' in self
159         assert isinstance(node, Node)
160         assert 'node_id' in node
161
162         slice_id = self['slice_id']
163         node_id = node['node_id']
164
165         if node_id in self['node_ids']:
166             assert slice_id in node['slice_ids']
167
168             self.api.db.do("DELETE FROM slice_node" \
169                            " WHERE node_id = %(node_id)d" \
170                            " AND slice_id = %(slice_id)d",
171                            locals())
172
173             if commit:
174                 self.api.db.commit()
175
176             self['node_ids'].remove(node_id)
177             node['slice_ids'].remove(slice_id)
178
179     ########## for foreign slices update, from ForeignSlices
180     def purge_slice_node (self,commit=True):
181         sql = "DELETE FROM slice_node WHERE slice_id=%d"%self['slice_id']
182         self.api.db.do(sql)
183         if commit:
184             self.api.db.commit()
185
186     def add_slice_nodes (self, node_ids, commit=True):
187         slice_id = self['slice_id']
188         ### xxx needs to be optimized
189         ### tried to figure a way to use a single sql statement
190         ### like: insert into table (x,y) values (1,2),(3,4);
191         ### but apparently this is not supported under postgresql
192         for node_id in node_ids:
193             sql="INSERT INTO slice_node VALUES (%d,%d)"%(slice_id,node_id)
194             self.api.db.do(sql)
195         if commit:
196             self.api.db.commit()
197
198     def update_slice_nodes (self, node_ids):
199         # xxx to be optimized
200         # we could compute the (set) difference between
201         # current and updated set of node_ids
202         # and invoke the DB only based on that
203         #
204         # for now : clean all entries for this slice
205         self.purge_slice_node()
206         # and re-install new list
207         self.add_slice_nodes (node_ids)
208
209     ##########
210     def sync(self, commit = True):
211         """
212         Add or update a slice.
213         """
214
215         # Before a new slice is added, delete expired slices
216         if 'slice_id' not in self:
217             expired = Slices(self.api, expires = -int(time.time()))
218             for slice in expired:
219                 slice.delete(commit)
220
221         Row.sync(self, commit)
222
223     def delete(self, commit = True):
224         """
225         Delete existing slice.
226         """
227
228         assert 'slice_id' in self
229
230         # Clean up miscellaneous join tables
231         for table in ['slice_node', 'slice_person', 'slice_attribute']:
232             self.api.db.do("DELETE FROM %s" \
233                            " WHERE slice_id = %d" % \
234                            (table, self['slice_id']), self)
235
236         # Mark as deleted
237         self['is_deleted'] = True
238         self.sync(commit)
239
240 class Slices(Table):
241     """
242     Representation of row(s) from the slices table in the
243     database.
244     """
245
246     def __init__(self, api, slice_filter = None, columns = None, expires = int(time.time())):
247         Table.__init__(self, api, Slice, columns)
248
249         sql = "SELECT %s FROM view_slices WHERE is_deleted IS False" % \
250               ", ".join(self.columns)
251
252         if expires is not None:
253             if expires >= 0:
254                 sql += " AND expires > %(expires)d"
255             else:
256                 expires = -expires
257                 sql += " AND expires < %(expires)d"
258
259         if slice_filter is not None:
260             if isinstance(slice_filter, (list, tuple, set)):
261                 # Separate the list into integers and strings
262                 ints = filter(lambda x: isinstance(x, (int, long)), slice_filter)
263                 strs = filter(lambda x: isinstance(x, StringTypes), slice_filter)
264                 slice_filter = Filter(Slice.fields, {'slice_id': ints, 'name': strs})
265                 sql += " AND (%s)" % slice_filter.sql(api, "OR")
266             elif isinstance(slice_filter, dict):
267                 slice_filter = Filter(Slice.fields, slice_filter)
268                 sql += " AND (%s)" % slice_filter.sql(api, "AND")
269
270         self.selectall(sql, locals())