Cache:
[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         '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         'peer_id': Parameter(int, "Peer at which this slice was created", nullok = True),
39         }
40     # for Cache
41     class_key = 'name'
42     foreign_fields = ['instantiation', 'url', 'description', 'max_nodes', 'expires']
43     foreign_xrefs = [
44         {'field': 'node_ids' ,         'class': 'Node',   'table': 'slice_node' },
45         {'field': 'person_ids',        'class': 'Person', 'table': 'slice_person'},
46         {'field': 'creator_person_id', 'class': 'Person', 'table': 'unused-on-direct-refs'},
47         {'field': 'site_id',           'class': 'Site',   'table': 'unused-on-direct-refs'},
48     ]
49     # forget about this one, it is read-only anyway
50     # handling it causes Cache to re-sync all over again 
51     # 'created'
52
53     def validate_name(self, name):
54         # N.B.: Responsibility of the caller to ensure that login_base
55         # portion of the slice name corresponds to a valid site, if
56         # desired.
57
58         # 1. Lowercase.
59         # 2. Begins with login_base (only letters).
60         # 3. Then single underscore after login_base.
61         # 4. Then letters, numbers, or underscores.
62         good_name = r'^[a-z]+_[a-z0-9_]+$'
63         if not name or \
64            not re.match(good_name, name):
65             raise PLCInvalidArgument, "Invalid slice name"
66
67         conflicts = Slices(self.api, [name])
68         for slice in conflicts:
69             if 'slice_id' not in self or self['slice_id'] != slice['slice_id']:
70                 raise PLCInvalidArgument, "Slice name already in use, %s"%name
71
72         return name
73
74     def validate_instantiation(self, instantiation):
75         instantiations = [row['instantiation'] for row in SliceInstantiations(self.api)]
76         if instantiation not in instantiations:
77             raise PLCInvalidArgument, "No such instantiation state"
78
79         return instantiation
80
81     # timestamps
82     def validate_created (self, timestamp):
83         return self.validate_timestamp (timestamp)
84
85     def validate_expires(self, expires):
86         # N.B.: Responsibility of the caller to ensure that expires is
87         # not too far into the future.
88         return self.validate_timestamp (expires,True)
89
90     def add_person(self, person, commit = True):
91         """
92         Add person to existing slice.
93         """
94
95         assert 'slice_id' in self
96         assert isinstance(person, PLC.Persons.Person)
97         assert 'person_id' in person
98
99         slice_id = self['slice_id']
100         person_id = person['person_id']
101
102         if person_id not in self['person_ids']:
103             assert slice_id not in person['slice_ids']
104
105             self.api.db.do("INSERT INTO slice_person (person_id, slice_id)" \
106                            " VALUES(%(person_id)d, %(slice_id)d)",
107                            locals())
108
109             if commit:
110                 self.api.db.commit()
111
112             self['person_ids'].append(person_id)
113             person['slice_ids'].append(slice_id)
114
115     def remove_person(self, person, commit = True):
116         """
117         Remove person from existing slice.
118         """
119
120         assert 'slice_id' in self
121         assert isinstance(person, PLC.Persons.Person)
122         assert 'person_id' in person
123
124         slice_id = self['slice_id']
125         person_id = person['person_id']
126
127         if person_id in self['person_ids']:
128             assert slice_id in person['slice_ids']
129
130             self.api.db.do("DELETE FROM slice_person" \
131                            " WHERE person_id = %(person_id)d" \
132                            " AND slice_id = %(slice_id)d",
133                            locals())
134
135             if commit:
136                 self.api.db.commit()
137
138             self['person_ids'].remove(person_id)
139             person['slice_ids'].remove(slice_id)
140
141     def add_node(self, node, commit = True):
142         """
143         Add node to existing slice.
144         """
145
146         assert 'slice_id' in self
147         assert isinstance(node, Node)
148         assert 'node_id' in node
149
150         slice_id = self['slice_id']
151         node_id = node['node_id']
152
153         if node_id not in self['node_ids']:
154             assert slice_id not in node['slice_ids']
155
156             self.api.db.do("INSERT INTO slice_node (node_id, slice_id)" \
157                            " VALUES(%(node_id)d, %(slice_id)d)",
158                            locals())
159
160             if commit:
161                 self.api.db.commit()
162
163             self['node_ids'].append(node_id)
164             node['slice_ids'].append(slice_id)
165
166     def remove_node(self, node, commit = True):
167         """
168         Remove node from existing slice.
169         """
170
171         assert 'slice_id' in self
172         assert isinstance(node, Node)
173         assert 'node_id' in node
174
175         slice_id = self['slice_id']
176         node_id = node['node_id']
177
178         if node_id in self['node_ids']:
179             assert slice_id in node['slice_ids']
180
181             self.api.db.do("DELETE FROM slice_node" \
182                            " WHERE node_id = %(node_id)d" \
183                            " AND slice_id = %(slice_id)d",
184                            locals())
185
186             if commit:
187                 self.api.db.commit()
188
189             self['node_ids'].remove(node_id)
190             node['slice_ids'].remove(slice_id)
191
192     ##########
193     def sync(self, commit = True):
194         """
195         Add or update a slice.
196         """
197
198         # Before a new slice is added, delete expired slices
199         if 'slice_id' not in self:
200             expired = Slices(self.api, expires = -int(time.time()))
201             for slice in expired:
202                 slice.delete(commit)
203
204         Row.sync(self, commit)
205
206     def delete(self, commit = True):
207         """
208         Delete existing slice.
209         """
210
211         assert 'slice_id' in self
212
213         # Clean up miscellaneous join tables
214         for table in ['slice_node', 'slice_person', 'slice_attribute']:
215             self.api.db.do("DELETE FROM %s" \
216                            " WHERE slice_id = %d" % \
217                            (table, self['slice_id']), self)
218
219         # Mark as deleted
220         self['is_deleted'] = True
221         self.sync(commit)
222
223 class Slices(Table):
224     """
225     Representation of row(s) from the slices table in the
226     database.
227     """
228
229     def __init__(self, api, slice_filter = None, columns = None, expires = int(time.time())):
230         Table.__init__(self, api, Slice, columns)
231
232         sql = "SELECT %s FROM view_slices WHERE is_deleted IS False" % \
233               ", ".join(self.columns)
234
235         if expires is not None:
236             if expires >= 0:
237                 sql += " AND expires > %(expires)d"
238             else:
239                 expires = -expires
240                 sql += " AND expires < %(expires)d"
241
242         if slice_filter is not None:
243             if isinstance(slice_filter, (list, tuple, set)):
244                 # Separate the list into integers and strings
245                 ints = filter(lambda x: isinstance(x, (int, long)), slice_filter)
246                 strs = filter(lambda x: isinstance(x, StringTypes), slice_filter)
247                 slice_filter = Filter(Slice.fields, {'slice_id': ints, 'name': strs})
248                 sql += " AND (%s)" % slice_filter.sql(api, "OR")
249             elif isinstance(slice_filter, dict):
250                 slice_filter = Filter(Slice.fields, slice_filter)
251                 sql += " AND (%s)" % slice_filter.sql(api, "AND")
252
253         self.selectall(sql, locals())