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