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