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