1 from types import StringTypes
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.Persons import Person, Persons
9 from PLC.Slices import Slice, Slices
10 from PLC.PCUs import PCU, PCUs
11 from PLC.Nodes import Node, Nodes
12 from PLC.NodeGroups import NodeGroup, NodeGroups
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().
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"),
37 # These fields are derived from join tables and are not actually
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"),
44 # These fields are derived from join tables and are not returned
45 # by default unless specified.
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"),
54 default_fields = dict(fields.items() + join_fields.items())
55 all_fields = dict(default_fields.items() + extra_fields.items())
57 # Number of slices assigned to each site at the time that the site is created
58 default_max_slices = 0
60 # XXX Useless, unclear what this value means
61 default_site_share = 1.0
63 def __init__(self, api, fields):
64 Row.__init__(self, fields)
67 def validate_login_base(self, login_base):
68 if len(login_base) > 20:
69 raise PLCInvalidArgument, "Login base must be <= 20 characters"
71 if not set(login_base).issubset(string.ascii_letters):
72 raise PLCInvalidArgument, "Login base must consist only of ASCII letters"
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"
82 def validate_latitude(self, latitude):
83 if latitude < -90.0 or latitude > 90.0:
84 raise PLCInvalidArgument, "Invalid latitude value"
86 if not self.has_key('longitude') or \
87 self['longitude'] is None:
88 raise PLCInvalidArgument, "Longitude must also be specified"
92 def validate_longitude(self, longitude):
93 if longitude < -180.0 or longitude > 180.0:
94 raise PLCInvalidArgument, "Invalid longitude value"
96 if not self.has_key('latitude') or \
97 self['latitude'] is None:
98 raise PLCInvalidArgument, "Latitude must also be specified"
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"
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"
114 return organization_id
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"
123 def flush(self, commit = True):
125 Flush changes back to the database.
131 if not self['name'] or \
132 not self['abbreviated_name'] or \
133 not self['login_base']:
136 raise PLCInvalidArgument, "name, abbreviated_name, and login_base must all be specified"
138 # Fetch a new site_id if necessary
139 if 'site_id' not in self:
140 rows = self.api.db.selectall("SELECT NEXTVAL('sites_site_id_seq') AS site_id")
142 raise PLCDBError, "Unable to fetch new site_id"
143 self['site_id'] = rows[0]['site_id']
148 # Create site node group if necessary
149 if 'nodegroup_id' not in self:
150 rows = self.api.db.selectall("SELECT NEXTVAL('nodegroups_nodegroup_id_seq') as nodegroup_id")
152 raise PLCDBError, "Unable to fetch new nodegroup_id"
153 self['nodegroup_id'] = rows[0]['nodegroup_id']
155 nodegroup_id = self['nodegroup_id']
156 # XXX Needs a unique name because we cannot delete site node groups yet
157 name = self['login_base'] + str(self['site_id'])
158 description = "Nodes at " + self['name']
160 self.api.db.do("INSERT INTO nodegroups (nodegroup_id, name, description, is_custom)" \
161 " VALUES (%(nodegroup_id)d, %(name)s, %(description)s, %(is_custom)s)",
164 # Filter out fields that cannot be set or updated directly
165 fields = dict(filter(lambda (key, value): key in self.fields,
168 # Parameterize for safety
170 values = [self.api.db.param(key, value) for (key, value) in fields.items()]
173 # Insert new row in sites table
174 self.api.db.do("INSERT INTO sites (%s) VALUES (%s)" % \
175 (", ".join(keys), ", ".join(values)),
178 # Setup default slice site info
179 # XXX Will go away soon
180 self['max_slices'] = self.default_max_slices
181 self['site_share'] = self.default_site_share
182 self.api.db.do("INSERT INTO dslice03_siteinfo (site_id, max_slices, site_share)" \
183 " VALUES (%(site_id)d, %(max_slices)d, %(site_share)f)",
186 # Update default slice site info
187 # XXX Will go away soon
188 if 'max_slices' in self and 'site_share' in self:
189 self.api.db.do("UPDATE dslice03_siteinfo SET " \
190 " max_slices = %(max_slices)d, site_share = %(site_share)f" \
191 " WHERE site_id = %(site_id)d",
194 # Update existing row in sites table
195 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
196 self.api.db.do("UPDATE sites SET " + \
197 ", ".join(columns) + \
198 " WHERE site_id = %(site_id)d",
204 def delete(self, commit = True):
206 Delete existing site.
209 assert 'site_id' in self
211 # Make sure extra fields are present
212 sites = Sites(self.api, [self['site_id']],
213 ['person_ids', 'slice_ids', 'pcu_ids', 'node_ids'])
215 self.update(sites.values()[0])
217 # Delete accounts of all people at the site who are not
218 # members of at least one other non-deleted site.
219 persons = Persons(self.api, self['person_ids'])
220 for person_id, person in persons.iteritems():
223 person_sites = Sites(self.api, person['site_ids'])
224 for person_site_id, person_site in person_sites.iteritems():
225 if person_site_id != self['site_id'] and \
226 not person_site['deleted']:
231 person.delete(commit = False)
233 # Delete all site slices
234 slices = Slices(self.api, self['slice_ids'])
235 for slice in slices.values():
236 slice.delete(commit = False)
238 # Delete all site PCUs
239 pcus = PCUs(self.api, self['pcu_ids'])
240 for pcu in pcus.values():
241 pcu.delete(commit = False)
243 # Delete all site nodes
244 nodes = Nodes(self.api, self['node_ids'])
245 for node in nodes.values():
246 node.delete(commit = False)
248 # Clean up miscellaneous join tables
249 for table in ['site_authorized_subnets',
250 'dslice03_defaultattribute',
251 'dslice03_siteinfo']:
252 self.api.db.do("DELETE FROM %s" \
253 " WHERE site_id = %d" % \
254 (table, self['site_id']))
256 # XXX Cannot delete site node groups yet
259 self['deleted'] = True
264 Representation of row(s) from the sites table in the
265 database. Specify extra_fields to be able to view and modify extra
269 def __init__(self, api, site_id_or_login_base_list = None, extra_fields = []):
272 sql = "SELECT sites.*" \
273 ", dslice03_siteinfo.max_slices"
275 # N.B.: Joined IDs may be marked as deleted in their primary tables
277 # extra_field: (extra_table, extra_column, join_using)
278 'person_ids': ('person_site', 'person_id', 'site_id'),
279 'slice_ids': ('dslice03_slices', 'slice_id', 'site_id'),
280 'defaultattribute_ids': ('dslice03_defaultattribute', 'defaultattribute_id', 'site_id'),
281 'pcu_ids': ('pcu', 'pcu_id', 'site_id'),
282 'node_ids': ('nodegroup_nodes', 'node_id', 'nodegroup_id'),
285 extra_fields = filter(join_tables.has_key, extra_fields)
286 extra_tables = ["%s USING (%s)" % \
287 (join_tables[field][0], join_tables[field][2]) \
288 for field in extra_fields]
289 extra_columns = ["%s.%s" % \
290 (join_tables[field][0], join_tables[field][1]) \
291 for field in extra_fields]
294 sql += ", " + ", ".join(extra_columns)
296 sql += " FROM sites" \
297 " LEFT JOIN dslice03_siteinfo USING (site_id)"
300 sql += " LEFT JOIN " + " LEFT JOIN ".join(extra_tables)
302 sql += " WHERE deleted IS False"
304 if site_id_or_login_base_list:
305 # Separate the list into integers and strings
306 site_ids = filter(lambda site_id: isinstance(site_id, (int, long)),
307 site_id_or_login_base_list)
308 login_bases = filter(lambda login_base: isinstance(login_base, StringTypes),
309 site_id_or_login_base_list)
312 sql += " OR site_id IN (%s)" % ", ".join(map(str, site_ids))
314 sql += " OR login_base IN (%s)" % ", ".join(api.db.quote(login_bases))
317 rows = self.api.db.selectall(sql)
319 if self.has_key(row['site_id']):
320 site = self[row['site_id']]
323 self[row['site_id']] = Site(api, row)