- move common sync() functionality to Table.Row
[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 type"),
25         'site_id': Parameter(int, "Identifier of the site to which this slice belongs"),
26         'name': Parameter(str, "Slice name", max = 32),
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 __init__(self, api, fields = {}):
40         Row.__init__(self, fields)
41         self.api = api
42
43     def validate_name(self, name):
44         # N.B.: Responsibility of the caller to ensure that login_base
45         # portion of the slice name corresponds to a valid site, if
46         # desired.
47
48         # 1. Lowercase.
49         # 2. Begins with login_base (only letters).
50         # 3. Then single underscore after login_base.
51         # 4. Then letters, numbers, or underscores.
52         good_name = r'^[a-z]+_[a-z0-9_]+$'
53         if not name or \
54            not re.match(good_name, name):
55             raise PLCInvalidArgument, "Invalid slice name"
56
57         conflicts = Slices(self.api, [name])
58         for slice_id, slice in conflicts.iteritems():
59             if 'slice_id' not in self or self['slice_id'] != slice_id:
60                 raise PLCInvalidArgument, "Slice name already in use"
61
62         return name
63
64     def validate_instantiation(self, instantiation):
65         instantiations = SliceInstantiations(self.api)
66         if instantiation not in instantiations:
67             raise PLCInvalidArgument, "No such instantiation state"
68
69         return instantiation
70
71     def validate_expires(self, expires):
72         # N.B.: Responsibility of the caller to ensure that expires is
73         # not too far into the future.
74         if expires < time.time():
75             raise PLCInvalidArgument, "Expiration date must be in the future"
76
77         return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires))
78
79     def validate_creator_person_id(self, person_id):
80         persons = PLC.Persons.Persons(self.api, [person_id])
81         if not persons:
82             raise PLCInvalidArgument, "Invalid creator"
83
84         return person_id
85
86     def add_person(self, person, commit = True):
87         """
88         Add person to existing slice.
89         """
90
91         assert 'slice_id' in self
92         assert isinstance(person, PLC.Persons.Person)
93         assert 'person_id' in person
94
95         slice_id = self['slice_id']
96         person_id = person['person_id']
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         if 'person_ids' in self and person_id not in self['person_ids']:
105             self['person_ids'].append(person_id)
106
107         if 'slice_ids' in person and slice_id not in person['slice_ids']:
108             person['slice_ids'].append(slice_id)
109
110     def remove_person(self, person, commit = True):
111         """
112         Remove person from existing slice.
113         """
114
115         assert 'slice_id' in self
116         assert isinstance(person, PLC.Persons.Person)
117         assert 'person_id' in person
118
119         slice_id = self['slice_id']
120         person_id = person['person_id']
121         self.api.db.do("DELETE FROM slice_person" \
122                        " WHERE person_id = %(person_id)d" \
123                        " AND slice_id = %(slice_id)d",
124                        locals())
125
126         if commit:
127             self.api.db.commit()
128
129         if 'person_ids' in self and person_id in self['person_ids']:
130             self['person_ids'].remove(person_id)
131
132         if 'slice_ids' in person and slice_id in person['slice_ids']:
133             person['slice_ids'].remove(slice_id)
134
135     def add_node(self, node, commit = True):
136         """
137         Add node to existing slice.
138         """
139
140         assert 'slice_id' in self
141         assert isinstance(node, Node)
142         assert 'node_id' in node
143
144         slice_id = self['slice_id']
145         node_id = node['node_id']
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         if 'node_ids' in self and node_id not in self['node_ids']:
154             self['node_ids'].append(node_id)
155
156         if 'slice_ids' in node and slice_id not in node['slice_ids']:
157             node['slice_ids'].append(slice_id)
158
159     def remove_node(self, node, commit = True):
160         """
161         Remove node from existing slice.
162         """
163
164         assert 'slice_id' in self
165         assert isinstance(node, Node)
166         assert 'node_id' in node
167
168         slice_id = self['slice_id']
169         node_id = node['node_id']
170         self.api.db.do("DELETE FROM slice_node" \
171                        " WHERE node_id = %(node_id)d" \
172                        " AND slice_id = %(slice_id)d",
173                        locals())
174
175         if commit:
176             self.api.db.commit()
177
178         if 'node_ids' in self and node_id in self['node_ids']:
179             self['node_ids'].remove(node_id)
180
181         if 'slice_ids' in node and slice_id in node['slice_ids']:
182             node['slice_ids'].remove(slice_id)
183
184     def delete(self, commit = True):
185         """
186         Delete existing slice.
187         """
188
189         assert 'slice_id' in self
190
191         # Clean up miscellaneous join tables
192         for table in ['slice_node', 'slice_person', 'slice_attribute']:
193             self.api.db.do("DELETE FROM %s" \
194                            " WHERE slice_id = %d" % \
195                            (table, self['slice_id']), self)
196
197         # Mark as deleted
198         self['is_deleted'] = True
199         self.sync(commit)
200
201 class Slices(Table):
202     """
203     Representation of row(s) from the slices table in the
204     database.
205     """
206
207     def __init__(self, api, slice_id_or_name_list = None):
208         self.api = api
209
210         sql = "SELECT %s FROM view_slices WHERE is_deleted IS False" % \
211               ", ".join(Slice.fields)
212
213         if slice_id_or_name_list:
214             # Separate the list into integers and strings
215             slice_ids = filter(lambda slice_id: isinstance(slice_id, (int, long)),
216                                slice_id_or_name_list)
217             names = filter(lambda name: isinstance(name, StringTypes),
218                            slice_id_or_name_list)
219             sql += " AND (False"
220             if slice_ids:
221                 sql += " OR slice_id IN (%s)" % ", ".join(map(str, slice_ids))
222             if names:
223                 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names))
224             sql += ")"
225
226         rows = self.api.db.selectall(sql)
227
228         for row in rows:
229             self[row['slice_id']] = slice = Slice(api, row)
230             for aggregate in 'node_ids', 'person_ids', 'slice_attribute_ids':
231                 if not slice.has_key(aggregate) or slice[aggregate] is None:
232                     slice[aggregate] = []
233                 else:
234                     slice[aggregate] = map(int, slice[aggregate].split(','))