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