- don't validate creator_person_id; if creator is deleted, then slice
[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 from PLC.ForeignNodes import ForeignNode, ForeignNodes
13 import PLC.Persons
14
15 class Slice(Row):
16     """
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.
21     """
22
23     table_name = 'slices'
24     primary_key = 'slice_id'
25     fields = {
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),
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_id, slice in conflicts.iteritems():
57             if 'slice_id' not in self or self['slice_id'] != slice_id:
58                 raise PLCInvalidArgument, "Slice name already in use"
59
60         return name
61
62     def validate_instantiation(self, instantiation):
63         instantiations = 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, is_foreign_node = False, commit = True):
129         """
130         Add node to existing slice.
131         """
132
133         assert 'slice_id' in self
134         if not is_foreign_node:
135             assert isinstance(node, Node)
136         else:
137             assert isinstance(node, ForeignNode)
138         assert 'node_id' in node
139
140         slice_id = self['slice_id']
141         node_id = node['node_id']
142
143         if node_id not in self['node_ids']:
144             assert slice_id not in node['slice_ids']
145
146             self.api.db.do("INSERT INTO slice_node (node_id, slice_id)" \
147                            " VALUES(%(node_id)d, %(slice_id)d)",
148                            locals())
149
150             if commit:
151                 self.api.db.commit()
152
153             self['node_ids'].append(node_id)
154             node['slice_ids'].append(slice_id)
155
156     def remove_node(self, node, commit = True):
157         """
158         Remove node from existing slice.
159         """
160
161         assert 'slice_id' in self
162         assert isinstance(node, Node)
163         assert 'node_id' in node
164
165         slice_id = self['slice_id']
166         node_id = node['node_id']
167
168         if node_id in self['node_ids']:
169             assert slice_id in node['slice_ids']
170
171             self.api.db.do("DELETE FROM slice_node" \
172                            " WHERE node_id = %(node_id)d" \
173                            " AND slice_id = %(slice_id)d",
174                            locals())
175
176             if commit:
177                 self.api.db.commit()
178
179             self['node_ids'].remove(node_id)
180             node['slice_ids'].remove(slice_id)
181
182     def sync(self, commit = True):
183         """
184         Add or update a slice.
185         """
186
187         # Before a new slice is added, delete expired slices
188         if 'slice_id' not in self:
189             expired = Slices(self.api, expires = -int(time.time())).values()
190             for slice in expired:
191                 slice.delete(commit)
192
193         Row.sync(self, commit)
194
195     def delete(self, commit = True):
196         """
197         Delete existing slice.
198         """
199
200         assert 'slice_id' in self
201
202         # Clean up miscellaneous join tables
203         for table in ['slice_node', 'slice_person', 'slice_attribute']:
204             self.api.db.do("DELETE FROM %s" \
205                            " WHERE slice_id = %d" % \
206                            (table, self['slice_id']), self)
207
208         # Mark as deleted
209         self['is_deleted'] = True
210         self.sync(commit)
211
212 class Slices(Table):
213     """
214     Representation of row(s) from the slices table in the
215     database.
216     """
217
218     def __init__(self, api, slice_filter = None, expires = int(time.time())):
219         Table.__init__(self, api, Slice)
220
221         sql = "SELECT %s FROM view_slices WHERE is_deleted IS False" % \
222               ", ".join(Slice.fields)
223
224         if expires is not None:
225             if expires >= 0:
226                 sql += " AND expires > %(expires)d"
227             else:
228                 expires = -expires
229                 sql += " AND expires < %(expires)d"
230
231         if slice_filter is not None:
232             if isinstance(slice_filter, list):
233                 # Separate the list into integers and strings
234                 ints = filter(lambda x: isinstance(x, (int, long)), slice_filter)
235                 strs = filter(lambda x: isinstance(x, StringTypes), slice_filter)
236                 slice_filter = Filter(Slice.fields, {'slice_id': ints, 'name': strs})
237                 sql += " AND (%s)" % slice_filter.sql(api, "OR")
238             elif isinstance(slice_filter, dict):
239                 slice_filter = Filter(Slice.fields, slice_filter)
240                 sql += " AND (%s)" % slice_filter.sql(api, "AND")
241
242         self.selectall(sql, locals())