cached Keys
[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         'peer_id': Parameter(int, "Peer at which this slice was created", nullok = True),
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     # for Cache
41     class_key = 'name'
42     foreign_fields = ['instantiation', 'url', 'description',
43                          'max_nodes', 'created', 'expires']
44     foreign_xrefs = { 'Node' : { 'field' : 'node_ids' ,
45                                  'table': 'slice_node' } }
46
47     def validate_name(self, name):
48         # N.B.: Responsibility of the caller to ensure that login_base
49         # portion of the slice name corresponds to a valid site, if
50         # desired.
51
52         # 1. Lowercase.
53         # 2. Begins with login_base (only letters).
54         # 3. Then single underscore after login_base.
55         # 4. Then letters, numbers, or underscores.
56         good_name = r'^[a-z]+_[a-z0-9_]+$'
57         if not name or \
58            not re.match(good_name, name):
59             raise PLCInvalidArgument, "Invalid slice name"
60
61         conflicts = Slices(self.api, [name])
62         for slice in conflicts:
63             if 'slice_id' not in self or self['slice_id'] != slice['slice_id']:
64                 raise PLCInvalidArgument, "Slice name already in use, %s"%name
65
66         return name
67
68     def validate_instantiation(self, instantiation):
69         instantiations = [row['instantiation'] for row in SliceInstantiations(self.api)]
70         if instantiation not in instantiations:
71             raise PLCInvalidArgument, "No such instantiation state"
72
73         return instantiation
74
75     def validate_expires(self, expires):
76         # N.B.: Responsibility of the caller to ensure that expires is
77         # not too far into the future.
78         if expires < time.time():
79             raise PLCInvalidArgument, "Expiration date must be in the future"
80
81         return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires))
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, commit = True):
135         """
136         Add node to existing slice.
137         """
138
139         assert 'slice_id' in self
140         assert isinstance(node, Node)
141         assert 'node_id' in node
142
143         slice_id = self['slice_id']
144         node_id = node['node_id']
145
146         if node_id not in self['node_ids']:
147             assert slice_id not in node['slice_ids']
148
149             self.api.db.do("INSERT INTO slice_node (node_id, slice_id)" \
150                            " VALUES(%(node_id)d, %(slice_id)d)",
151                            locals())
152
153             if commit:
154                 self.api.db.commit()
155
156             self['node_ids'].append(node_id)
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
171         if node_id in self['node_ids']:
172             assert slice_id in node['slice_ids']
173
174             self.api.db.do("DELETE FROM slice_node" \
175                            " WHERE node_id = %(node_id)d" \
176                            " AND slice_id = %(slice_id)d",
177                            locals())
178
179             if commit:
180                 self.api.db.commit()
181
182             self['node_ids'].remove(node_id)
183             node['slice_ids'].remove(slice_id)
184
185     ##########
186     def sync(self, commit = True):
187         """
188         Add or update a slice.
189         """
190
191         # Before a new slice is added, delete expired slices
192         if 'slice_id' not in self:
193             expired = Slices(self.api, expires = -int(time.time()))
194             for slice in expired:
195                 slice.delete(commit)
196
197         Row.sync(self, commit)
198
199     def delete(self, commit = True):
200         """
201         Delete existing slice.
202         """
203
204         assert 'slice_id' in self
205
206         # Clean up miscellaneous join tables
207         for table in ['slice_node', 'slice_person', 'slice_attribute']:
208             self.api.db.do("DELETE FROM %s" \
209                            " WHERE slice_id = %d" % \
210                            (table, self['slice_id']), self)
211
212         # Mark as deleted
213         self['is_deleted'] = True
214         self.sync(commit)
215
216 class Slices(Table):
217     """
218     Representation of row(s) from the slices table in the
219     database.
220     """
221
222     def __init__(self, api, slice_filter = None, columns = None, expires = int(time.time())):
223         Table.__init__(self, api, Slice, columns)
224
225         sql = "SELECT %s FROM view_slices WHERE is_deleted IS False" % \
226               ", ".join(self.columns)
227
228         if expires is not None:
229             if expires >= 0:
230                 sql += " AND expires > %(expires)d"
231             else:
232                 expires = -expires
233                 sql += " AND expires < %(expires)d"
234
235         if slice_filter is not None:
236             if isinstance(slice_filter, (list, tuple, set)):
237                 # Separate the list into integers and strings
238                 ints = filter(lambda x: isinstance(x, (int, long)), slice_filter)
239                 strs = filter(lambda x: isinstance(x, StringTypes), slice_filter)
240                 slice_filter = Filter(Slice.fields, {'slice_id': ints, 'name': strs})
241                 sql += " AND (%s)" % slice_filter.sql(api, "OR")
242             elif isinstance(slice_filter, dict):
243                 slice_filter = Filter(Slice.fields, slice_filter)
244                 sql += " AND (%s)" % slice_filter.sql(api, "AND")
245
246         self.selectall(sql, locals())