federation in progress - associate a local slice to a foreign node
[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.Debug import profile
8 from PLC.Table import Row, Table
9 from PLC.SliceInstantiations import SliceInstantiations
10 from PLC.Nodes import Node, Nodes
11 from PLC.ForeignNodes import ForeignNode, ForeignNodes
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         'name': Parameter(str, "Slice name", max = 32),
28         'instantiation': Parameter(str, "Slice instantiation state"),
29         'url': Parameter(str, "URL further describing this slice", max = 254, nullok = True),
30         'description': Parameter(str, "Slice description", max = 2048, nullok = True),
31         'max_nodes': Parameter(int, "Maximum number of nodes that can be assigned to this slice"),
32         'creator_person_id': Parameter(int, "Identifier of the account that created this slice"),
33         'created': Parameter(int, "Date and time when slice was created, in seconds since UNIX epoch", ro = True),
34         'expires': Parameter(int, "Date and time when slice expires, in seconds since UNIX epoch"),
35         'node_ids': Parameter([int], "List of nodes in this slice", ro = True),
36         'person_ids': Parameter([int], "List of accounts that can use this slice", ro = True),
37         'slice_attribute_ids': Parameter([int], "List of slice attributes", ro = True),
38         }
39
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
43         # desired.
44
45         # 1. Lowercase.
46         # 2. Begins with login_base (only letters).
47         # 3. Then single underscore after login_base.
48         # 4. Then letters, numbers, or underscores.
49         good_name = r'^[a-z]+_[a-z0-9_]+$'
50         if not name or \
51            not re.match(good_name, name):
52             raise PLCInvalidArgument, "Invalid slice name"
53
54         conflicts = Slices(self.api, [name])
55         for slice_id, slice in conflicts.iteritems():
56             if 'slice_id' not in self or self['slice_id'] != slice_id:
57                 raise PLCInvalidArgument, "Slice name already in use"
58
59         return name
60
61     def validate_instantiation(self, instantiation):
62         instantiations = SliceInstantiations(self.api)
63         if instantiation not in instantiations:
64             raise PLCInvalidArgument, "No such instantiation state"
65
66         return instantiation
67
68     def validate_expires(self, expires):
69         # N.B.: Responsibility of the caller to ensure that expires is
70         # not too far into the future.
71         if expires < time.time():
72             raise PLCInvalidArgument, "Expiration date must be in the future"
73
74         return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires))
75
76     def validate_creator_person_id(self, person_id):
77         persons = PLC.Persons.Persons(self.api, [person_id])
78         if not persons:
79             raise PLCInvalidArgument, "Invalid creator"
80
81         return person_id
82
83     def add_person(self, person, commit = True):
84         """
85         Add person to existing slice.
86         """
87
88         assert 'slice_id' in self
89         assert isinstance(person, PLC.Persons.Person)
90         assert 'person_id' in person
91
92         slice_id = self['slice_id']
93         person_id = person['person_id']
94
95         if person_id not in self['person_ids']:
96             assert slice_id not in person['slice_ids']
97
98             self.api.db.do("INSERT INTO slice_person (person_id, slice_id)" \
99                            " VALUES(%(person_id)d, %(slice_id)d)",
100                            locals())
101
102             if commit:
103                 self.api.db.commit()
104
105             self['person_ids'].append(person_id)
106             person['slice_ids'].append(slice_id)
107
108     def remove_person(self, person, commit = True):
109         """
110         Remove person from existing slice.
111         """
112
113         assert 'slice_id' in self
114         assert isinstance(person, PLC.Persons.Person)
115         assert 'person_id' in person
116
117         slice_id = self['slice_id']
118         person_id = person['person_id']
119
120         if person_id in self['person_ids']:
121             assert slice_id in person['slice_ids']
122
123             self.api.db.do("DELETE FROM slice_person" \
124                            " WHERE person_id = %(person_id)d" \
125                            " AND slice_id = %(slice_id)d",
126                            locals())
127
128             if commit:
129                 self.api.db.commit()
130
131             self['person_ids'].remove(person_id)
132             person['slice_ids'].remove(slice_id)
133
134     def add_node(self, node, is_foreign_node = False, commit = True):
135         """
136         Add node to existing slice.
137         """
138
139         assert 'slice_id' in self
140         if not is_foreign_node:
141             assert isinstance(node, Node)
142         else:
143             assert isinstance(node, ForeignNode)
144         assert 'node_id' in node
145
146         slice_id = self['slice_id']
147         node_id = node['node_id']
148
149         if node_id not in self['node_ids']:
150             assert slice_id not in node['slice_ids']
151
152             self.api.db.do("INSERT INTO slice_node (node_id, slice_id)" \
153                            " VALUES(%(node_id)d, %(slice_id)d)",
154                            locals())
155
156             if commit:
157                 self.api.db.commit()
158
159             self['node_ids'].append(node_id)
160             node['slice_ids'].append(slice_id)
161
162     def remove_node(self, node, commit = True):
163         """
164         Remove node from existing slice.
165         """
166
167         assert 'slice_id' in self
168         assert isinstance(node, Node)
169         assert 'node_id' in node
170
171         slice_id = self['slice_id']
172         node_id = node['node_id']
173
174         if node_id in self['node_ids']:
175             assert slice_id in node['slice_ids']
176
177             self.api.db.do("DELETE FROM slice_node" \
178                            " WHERE node_id = %(node_id)d" \
179                            " AND slice_id = %(slice_id)d",
180                            locals())
181
182             if commit:
183                 self.api.db.commit()
184
185             self['node_ids'].remove(node_id)
186             node['slice_ids'].remove(slice_id)
187
188     def sync(self, commit = True):
189         """
190         Add or update a slice.
191         """
192
193         # Before a new slice is added, delete expired slices
194         if 'slice_id' not in self:
195             expired = Slices(self.api, expires = -int(time.time())).values()
196             for slice in expired:
197                 slice.delete(commit)
198
199         Row.sync(self, commit)
200
201     def delete(self, commit = True):
202         """
203         Delete existing slice.
204         """
205
206         assert 'slice_id' in self
207
208         # Clean up miscellaneous join tables
209         for table in ['slice_node', 'slice_person', 'slice_attribute']:
210             self.api.db.do("DELETE FROM %s" \
211                            " WHERE slice_id = %d" % \
212                            (table, self['slice_id']), self)
213
214         # Mark as deleted
215         self['is_deleted'] = True
216         self.sync(commit)
217
218 class Slices(Table):
219     """
220     Representation of row(s) from the slices table in the
221     database.
222     """
223
224     def __init__(self, api, slice_id_or_name_list = None, expires = int(time.time())):
225         self.api = api
226
227         sql = "SELECT %s FROM view_slices WHERE is_deleted IS False" % \
228               ", ".join(Slice.fields)
229
230         if expires is not None:
231             if expires >= 0:
232                 sql += " AND expires > %(expires)d"
233             else:
234                 expires = -expires
235                 sql += " AND expires < %(expires)d"
236
237         if slice_id_or_name_list:
238             # Separate the list into integers and strings
239             slice_ids = filter(lambda slice_id: isinstance(slice_id, (int, long)),
240                                slice_id_or_name_list)
241             names = filter(lambda name: isinstance(name, StringTypes),
242                            slice_id_or_name_list)
243             sql += " AND (False"
244             if slice_ids:
245                 sql += " OR slice_id IN (%s)" % ", ".join(map(str, slice_ids))
246             if names:
247                 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names))
248             sql += ")"
249
250         rows = self.api.db.selectall(sql, locals())
251
252         for row in rows:
253             self[row['slice_id']] = slice = Slice(api, row)
254             for aggregate in 'node_ids', 'person_ids', 'slice_attribute_ids':
255                 if not slice.has_key(aggregate) or slice[aggregate] is None:
256                     slice[aggregate] = []
257                 else:
258                     slice[aggregate] = map(int, slice[aggregate].split(','))