- set min and max for str fields
[plcapi.git] / PLC / Sites.py
1 from types import StringTypes
2 import string
3
4 from PLC.Faults import *
5 from PLC.Parameter import Parameter
6 from PLC.Debug import profile
7 from PLC.Table import Row, Table
8 from PLC.Slices import Slice, Slices
9 from PLC.PCUs import PCU, PCUs
10 from PLC.Nodes import Node, Nodes
11 from PLC.NodeGroups import NodeGroup, NodeGroups
12 import PLC.Persons
13
14 class Site(Row):
15     """
16     Representation of a row in the sites table. To use, optionally
17     instantiate with a dict of values. Update as you would a
18     dict. Commit to the database with flush().
19     """
20
21     fields = {
22         'site_id': Parameter(int, "Site identifier"),
23         'name': Parameter(str, "Full site name", max = 254),
24         'abbreviated_name': Parameter(str, "Abbreviated site name", max = 50),
25         'login_base': Parameter(str, "Site slice prefix", max = 20),
26         'is_public': Parameter(bool, "Publicly viewable site"),
27         'latitude': Parameter(float, "Decimal latitude of the site", min = -90.0, max = 90.0),
28         'longitude': Parameter(float, "Decimal longitude of the site", min = -180.0, max = 180.0),
29         'url': Parameter(str, "URL of a page that describes the site", max = 254),
30         'nodegroup_id': Parameter(int, "Identifier of the nodegroup containing the site's nodes"),
31         'organization_id': Parameter(int, "Organizational identifier if the site is part of a larger organization"),
32         'ext_consortium_id': Parameter(int, "Consortium identifier if the site is part of an external consortium"),
33         'date_created': Parameter(str, "Date and time when node entry was created"),        
34         'deleted': Parameter(bool, "Has been deleted"),
35         }
36
37     # These fields are derived from join tables and are not actually
38     # in the sites table.
39     join_fields = {
40         'max_slices': Parameter(int, "Maximum number of slices that the site is able to create"),
41         'site_share': Parameter(float, "Relative resource share for this site's slices"),
42         }        
43
44     # These fields are derived from join tables and are not returned
45     # by default unless specified.
46     extra_fields = {
47         'person_ids': Parameter([int], "List of account identifiers"),
48         'slice_ids': Parameter([int], "List of slice identifiers"),
49         'defaultattribute_ids': Parameter([int], "List of default slice attribute identifiers"),
50         'pcu_ids': Parameter([int], "List of PCU identifiers"),
51         'node_ids': Parameter([int], "List of site node identifiers"),
52         }
53
54     default_fields = dict(fields.items() + join_fields.items())
55     all_fields = dict(default_fields.items() + extra_fields.items())
56
57     # Number of slices assigned to each site at the time that the site is created
58     default_max_slices = 0
59
60     # XXX Useless, unclear what this value means
61     default_site_share = 1.0
62
63     def __init__(self, api, fields):
64         Row.__init__(self, fields)
65         self.api = api
66
67     def validate_login_base(self, login_base):
68         if not set(login_base).issubset(string.ascii_letters):
69             raise PLCInvalidArgument, "Login base must consist only of ASCII letters"
70
71         login_base = login_base.lower()
72         conflicts = Sites(self.api, [login_base])
73         for site_id, site in conflicts.iteritems():
74             if not site['deleted'] and ('site_id' not in self or self['site_id'] != site_id):
75                 raise PLCInvalidArgument, "login_base already in use"
76
77         return login_base
78
79     def validate_latitude(self, latitude):
80         if not self.has_key('longitude') or \
81            self['longitude'] is None:
82             raise PLCInvalidArgument, "Longitude must also be specified"
83
84         return latitude
85
86     def validate_longitude(self, longitude):
87         if not self.has_key('latitude') or \
88            self['latitude'] is None:
89             raise PLCInvalidArgument, "Latitude must also be specified"
90
91         return longitude
92
93     def validate_nodegroup_id(self, nodegroup_id):
94         nodegroups = NodeGroups(self.api)
95         if nodegroup_id not in nodegroups:
96             raise PLCInvalidArgument, "No such nodegroup"
97
98         return nodegroup_id
99
100     def validate_organization_id(self, organization_id):
101         organizations = Organizations(self.api)
102         if role_id not in organizations:
103             raise PLCInvalidArgument, "No such organization"
104
105         return organization_id
106
107     def validate_ext_consortium_id(self, organization_id):
108         consortiums = Consortiums(self.api)
109         if consortium_id not in consortiums:
110             raise PLCInvalidArgument, "No such consortium"
111
112         return nodegroup_id
113
114     def add_person(self, person, commit = True):
115         """
116         Add person to existing site.
117         """
118
119         assert 'site_id' in self
120         assert isinstance(person, PLC.Persons.Person)
121         assert 'person_id' in person
122
123         site_id = self['site_id']
124         person_id = person['person_id']
125         self.api.db.do("INSERT INTO person_site (person_id, site_id)" \
126                        " VALUES(%(person_id)d, %(site_id)d)",
127                        locals())
128
129         if commit:
130             self.api.db.commit()
131
132         if 'person_ids' in self and person_id not in self['person_ids']:
133             self['person_ids'].append(person_id)
134
135         if 'site_ids' in person and site_id not in person['site_ids']:
136             person['site_ids'].append(site_id)
137
138     def remove_person(self, person, commit = True):
139         """
140         Remove person from existing site.
141         """
142
143         assert 'site_id' in self
144         assert isinstance(person, PLC.Persons.Person)
145         assert 'person_id' in person
146
147         site_id = self['site_id']
148         person_id = person['person_id']
149         self.api.db.do("DELETE FROM person_site" \
150                        " WHERE person_id = %(person_id)d" \
151                        " AND site_id = %(site_id)d",
152                        locals())
153
154         if commit:
155             self.api.db.commit()
156
157         if 'person_ids' in self and person_id in self['person_ids']:
158             self['person_ids'].remove(person_id)
159
160         if 'site_ids' in person and site_id in person['site_ids']:
161             person['site_ids'].remove(site_id)
162
163     def flush(self, commit = True):
164         """
165         Flush changes back to the database.
166         """
167
168         self.validate()
169
170         try:
171             if not self['name'] or \
172                not self['abbreviated_name'] or \
173                not self['login_base']:
174                 raise KeyError
175         except KeyError:
176             raise PLCInvalidArgument, "name, abbreviated_name, and login_base must all be specified"
177
178         # Fetch a new site_id if necessary
179         if 'site_id' not in self:
180             rows = self.api.db.selectall("SELECT NEXTVAL('sites_site_id_seq') AS site_id")
181             if not rows:
182                 raise PLCDBError, "Unable to fetch new site_id"
183             self['site_id'] = rows[0]['site_id']
184             insert = True
185         else:
186             insert = False
187
188         # Create site node group if necessary
189         if 'nodegroup_id' not in self:
190             rows = self.api.db.selectall("SELECT NEXTVAL('nodegroups_nodegroup_id_seq') as nodegroup_id")
191             if not rows:
192                 raise PLCDBError, "Unable to fetch new nodegroup_id"
193             self['nodegroup_id'] = rows[0]['nodegroup_id']
194
195             nodegroup_id = self['nodegroup_id']
196             # XXX Needs a unique name because we cannot delete site node groups yet
197             name = self['login_base'] + str(self['site_id'])
198             description = "Nodes at " + self['login_base']
199             is_custom = False
200             self.api.db.do("INSERT INTO nodegroups (nodegroup_id, name, description, is_custom)" \
201                            " VALUES (%(nodegroup_id)d, %(name)s, %(description)s, %(is_custom)s)",
202                            locals())
203
204         # Filter out fields that cannot be set or updated directly
205         fields = dict(filter(lambda (key, value): key in self.fields,
206                              self.items()))
207
208         # Parameterize for safety
209         keys = fields.keys()
210         values = [self.api.db.param(key, value) for (key, value) in fields.items()]
211
212         if insert:
213             # Insert new row in sites table
214             self.api.db.do("INSERT INTO sites (%s) VALUES (%s)" % \
215                            (", ".join(keys), ", ".join(values)),
216                            fields)
217
218             # Setup default slice site info
219             # XXX Will go away soon
220             self['max_slices'] = self.default_max_slices
221             self['site_share'] = self.default_site_share
222             self.api.db.do("INSERT INTO dslice03_siteinfo (site_id, max_slices, site_share)" \
223                            " VALUES (%(site_id)d, %(max_slices)d, %(site_share)f)",
224                            self)
225         else:
226             # Update default slice site info
227             # XXX Will go away soon
228             if 'max_slices' in self and 'site_share' in self:
229                 self.api.db.do("UPDATE dslice03_siteinfo SET " \
230                                " max_slices = %(max_slices)d, site_share = %(site_share)f" \
231                                " WHERE site_id = %(site_id)d",
232                                self)
233
234             # Update existing row in sites table
235             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
236             self.api.db.do("UPDATE sites SET " + \
237                            ", ".join(columns) + \
238                            " WHERE site_id = %(site_id)d",
239                            fields)
240
241         if commit:
242             self.api.db.commit()
243
244     def delete(self, commit = True):
245         """
246         Delete existing site.
247         """
248
249         assert 'site_id' in self
250
251         # Make sure extra fields are present
252         sites = Sites(self.api, [self['site_id']],
253                       ['person_ids', 'slice_ids', 'pcu_ids', 'node_ids'])
254         assert sites
255         self.update(sites.values()[0])
256
257         # Delete accounts of all people at the site who are not
258         # members of at least one other non-deleted site.
259         persons = PLC.Persons.Persons(self.api, self['person_ids'])
260         for person_id, person in persons.iteritems():
261             delete = True
262
263             person_sites = Sites(self.api, person['site_ids'])
264             for person_site_id, person_site in person_sites.iteritems():
265                 if person_site_id != self['site_id'] and \
266                    not person_site['deleted']:
267                     delete = False
268                     break
269
270             if delete:
271                 person.delete(commit = False)
272
273         # Delete all site slices
274         slices = Slices(self.api, self['slice_ids'])
275         for slice in slices.values():
276             slice.delete(commit = False)
277
278         # Delete all site PCUs
279         pcus = PCUs(self.api, self['pcu_ids'])
280         for pcu in pcus.values():
281             pcu.delete(commit = False)
282
283         # Delete all site nodes
284         nodes = Nodes(self.api, self['node_ids'])
285         for node in nodes.values():
286             node.delete(commit = False)
287
288         # Clean up miscellaneous join tables
289         for table in ['site_authorized_subnets',
290                       'dslice03_defaultattribute',
291                       'dslice03_siteinfo']:
292             self.api.db.do("DELETE FROM %s" \
293                            " WHERE site_id = %d" % \
294                            (table, self['site_id']))
295
296         # XXX Cannot delete site node groups yet
297
298         # Mark as deleted
299         self['deleted'] = True
300         self.flush(commit)
301
302 class Sites(Table):
303     """
304     Representation of row(s) from the sites table in the
305     database. Specify extra_fields to be able to view and modify extra
306     fields.
307     """
308
309     def __init__(self, api, site_id_or_login_base_list = None, extra_fields = []):
310         self.api = api
311
312         sql = "SELECT sites.*" \
313               ", dslice03_siteinfo.max_slices"
314
315         # N.B.: Joined IDs may be marked as deleted in their primary tables
316         join_tables = {
317             # extra_field: (extra_table, extra_column, join_using)
318             'person_ids': ('person_site', 'person_id', 'site_id'),
319             'slice_ids': ('dslice03_slices', 'slice_id', 'site_id'),
320             'defaultattribute_ids': ('dslice03_defaultattribute', 'defaultattribute_id', 'site_id'),
321             'pcu_ids': ('pcu', 'pcu_id', 'site_id'),
322             'node_ids': ('nodegroup_nodes', 'node_id', 'nodegroup_id'),
323             }
324
325         extra_fields = filter(join_tables.has_key, extra_fields)
326         extra_tables = ["%s USING (%s)" % \
327                         (join_tables[field][0], join_tables[field][2]) \
328                         for field in extra_fields]
329         extra_columns = ["%s.%s" % \
330                          (join_tables[field][0], join_tables[field][1]) \
331                          for field in extra_fields]
332
333         if extra_columns:
334             sql += ", " + ", ".join(extra_columns)
335
336         sql += " FROM sites" \
337                " LEFT JOIN dslice03_siteinfo USING (site_id)"
338
339         if extra_tables:
340             sql += " LEFT JOIN " + " LEFT JOIN ".join(extra_tables)
341
342         sql += " WHERE sites.deleted IS False"
343
344         if site_id_or_login_base_list:
345             # Separate the list into integers and strings
346             site_ids = filter(lambda site_id: isinstance(site_id, (int, long)),
347                               site_id_or_login_base_list)
348             login_bases = filter(lambda login_base: isinstance(login_base, StringTypes),
349                                  site_id_or_login_base_list)
350             sql += " AND (False"
351             if site_ids:
352                 sql += " OR site_id IN (%s)" % ", ".join(map(str, site_ids))
353             if login_bases:
354                 sql += " OR login_base IN (%s)" % ", ".join(api.db.quote(login_bases))
355             sql += ")"
356
357         rows = self.api.db.selectall(sql)
358         for row in rows:
359             if self.has_key(row['site_id']):
360                 site = self[row['site_id']]
361                 site.update(row)
362             else:
363                 self[row['site_id']] = Site(api, row)