make read-only a Parameter attribute
[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 from PLC.Addresses import Address, Addresses
13 import PLC.Persons
14
15 class Site(Row):
16     """
17     Representation of a row in the sites table. To use, optionally
18     instantiate with a dict of values. Update as you would a
19     dict. Commit to the database with sync().
20     """
21
22     fields = {
23         'site_id': Parameter(int, "Site identifier"),
24         'name': Parameter(str, "Full site name", max = 254),
25         'abbreviated_name': Parameter(str, "Abbreviated site name", max = 50),
26         'login_base': Parameter(str, "Site slice prefix", max = 20),
27         'is_public': Parameter(bool, "Publicly viewable site"),
28         'latitude': Parameter(float, "Decimal latitude of the site", min = -90.0, max = 90.0),
29         'longitude': Parameter(float, "Decimal longitude of the site", min = -180.0, max = 180.0),
30         'url': Parameter(str, "URL of a page that describes the site", max = 254),
31         'date_created': Parameter(int, "Date and time when site entry was created, in seconds since UNIX epoch", ro = True),
32         'last_updated': Parameter(int, "Date and time when site entry was last updated, in seconds since UNIX epoch", ro = True),
33         'max_slices': Parameter(int, "Maximum number of slices that the site is able to create"),
34         'max_slivers': Parameter(int, "Maximum number of slivers that the site is able to create"),
35         'person_ids': Parameter([int], "List of account identifiers", ro = True),
36         'slice_ids': Parameter([int], "List of slice identifiers", ro = True),
37         'address_ids': Parameter([int], "List of address identifiers", ro = True),
38         # 'pcu_ids': Parameter([int], "List of PCU identifiers", ro = True),
39         'node_ids': Parameter([int], "List of site node identifiers", ro = True),
40         }
41
42     def __init__(self, api, fields):
43         Row.__init__(self, fields)
44         self.api = api
45
46     def validate_login_base(self, login_base):
47         if not set(login_base).issubset(string.ascii_letters):
48             raise PLCInvalidArgument, "Login base must consist only of ASCII letters"
49
50         login_base = login_base.lower()
51         conflicts = Sites(self.api, [login_base])
52         for site_id, site in conflicts.iteritems():
53             if 'site_id' not in self or self['site_id'] != site_id:
54                 raise PLCInvalidArgument, "login_base already in use"
55
56         return login_base
57
58     def validate_latitude(self, latitude):
59         if not self.has_key('longitude') or \
60            self['longitude'] is None:
61             raise PLCInvalidArgument, "Longitude must also be specified"
62
63         return latitude
64
65     def validate_longitude(self, longitude):
66         if not self.has_key('latitude') or \
67            self['latitude'] is None:
68             raise PLCInvalidArgument, "Latitude must also be specified"
69
70         return longitude
71
72     def add_person(self, person, commit = True):
73         """
74         Add person to existing site.
75         """
76
77         assert 'site_id' in self
78         assert isinstance(person, PLC.Persons.Person)
79         assert 'person_id' in person
80
81         site_id = self['site_id']
82         person_id = person['person_id']
83         self.api.db.do("INSERT INTO person_site (person_id, site_id)" \
84                        " VALUES(%(person_id)d, %(site_id)d)",
85                        locals())
86
87         if commit:
88             self.api.db.commit()
89
90         if 'person_ids' in self and person_id not in self['person_ids']:
91             self['person_ids'].append(person_id)
92
93         if 'site_ids' in person and site_id not in person['site_ids']:
94             person['site_ids'].append(site_id)
95
96     def remove_person(self, person, commit = True):
97         """
98         Remove person from existing site.
99         """
100
101         assert 'site_id' in self
102         assert isinstance(person, PLC.Persons.Person)
103         assert 'person_id' in person
104
105         site_id = self['site_id']
106         person_id = person['person_id']
107         self.api.db.do("DELETE FROM person_site" \
108                        " WHERE person_id = %(person_id)d" \
109                        " AND site_id = %(site_id)d",
110                        locals())
111
112         if commit:
113             self.api.db.commit()
114
115         if 'person_ids' in self and person_id in self['person_ids']:
116             self['person_ids'].remove(person_id)
117
118         if 'site_ids' in person and site_id in person['site_ids']:
119             person['site_ids'].remove(site_id)
120
121     def sync(self, commit = True):
122         """
123         Flush changes back to the database.
124         """
125
126         self.validate()
127
128         try:
129             if not self['name'] or \
130                not self['abbreviated_name'] or \
131                not self['login_base']:
132                 raise KeyError
133         except KeyError:
134             raise PLCInvalidArgument, "name, abbreviated_name, and login_base must all be specified"
135
136         # Fetch a new site_id if necessary
137         if 'site_id' not in self:
138             rows = self.api.db.selectall("SELECT NEXTVAL('sites_site_id_seq') AS site_id")
139             if not rows:
140                 raise PLCDBError, "Unable to fetch new site_id"
141             self['site_id'] = rows[0]['site_id']
142             insert = True
143         else:
144             insert = False
145
146         # Filter out fields that cannot be set or updated directly
147         sites_fields = self.api.db.fields('sites')
148         fields = dict(filter(lambda (key, value): \
149                              key in sites_fields and \
150                              (key not in self.fields or not self.fields[key].ro),
151                              self.items()))
152
153         # Parameterize for safety
154         keys = fields.keys()
155         values = [self.api.db.param(key, value) for (key, value) in fields.items()]
156
157         if insert:
158             # Insert new row in sites table
159             sql = "INSERT INTO sites (%s) VALUES (%s)" % \
160                   (", ".join(keys), ", ".join(values))
161         else:
162             # Update existing row in sites table
163             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
164             sql = "UPDATE sites SET " + \
165                   ", ".join(columns) + \
166                   " WHERE site_id = %(site_id)d"
167
168         self.api.db.do(sql, fields)
169
170         if commit:
171             self.api.db.commit()
172
173     def delete(self, commit = True):
174         """
175         Delete existing site.
176         """
177
178         assert 'site_id' in self
179
180         # Delete accounts of all people at the site who are not
181         # members of at least one other non-deleted site.
182         persons = PLC.Persons.Persons(self.api, self['person_ids'])
183         for person_id, person in persons.iteritems():
184             delete = True
185
186             person_sites = Sites(self.api, person['site_ids'])
187             for person_site_id, person_site in person_sites.iteritems():
188                 if person_site_id != self['site_id']:
189                     delete = False
190                     break
191
192             if delete:
193                 person.delete(commit = False)
194
195         # Delete all site addresses
196         addresses = Addresses(self.api, self['address_ids'])
197         for address in addresses.values():
198            address.delete(commit = False)
199
200         # Delete all site slices
201         slices = Slices(self.api, self['slice_ids'])
202         for slice in slices.values():
203            slice.delete(commit = False)
204
205         # Delete all site PCUs
206         # pcus = PCUs(self.api, self['pcu_ids'])
207         # for pcu in pcus.values():
208         #    pcu.delete(commit = False)
209
210         # Delete all site nodes
211         nodes = Nodes(self.api, self['node_ids'])
212         for node in nodes.values():
213             node.delete(commit = False)
214
215         # Clean up miscellaneous join tables
216         for table in ['person_site']:
217             self.api.db.do("DELETE FROM %s" \
218                            " WHERE site_id = %d" % \
219                            (table, self['site_id']), self)
220
221         # Mark as deleted
222         self['deleted'] = True
223         self.sync(commit)
224
225 class Sites(Table):
226     """
227     Representation of row(s) from the sites table in the
228     database. Specify fields to limit columns to just the specified
229     fields.
230     """
231
232     def __init__(self, api, site_id_or_login_base_list = None, fields = Site.fields):
233         self.api = api
234
235         sql = "SELECT %s FROM view_sites WHERE deleted IS False" % \
236               ", ".join(fields)
237
238         if site_id_or_login_base_list:
239             # Separate the list into integers and strings
240             site_ids = filter(lambda site_id: isinstance(site_id, (int, long)),
241                               site_id_or_login_base_list)
242             login_bases = filter(lambda login_base: isinstance(login_base, StringTypes),
243                                  site_id_or_login_base_list)
244             sql += " AND (False"
245             if site_ids:
246                 sql += " OR site_id IN (%s)" % ", ".join(map(str, site_ids))
247             if login_bases:
248                 sql += " OR login_base IN (%s)" % ", ".join(api.db.quote(login_bases))
249             sql += ")"
250
251         rows = self.api.db.selectall(sql)
252
253         for row in rows:
254             self[row['site_id']] = site = Site(api, row)
255             for aggregate in ['person_ids', 'slice_ids', 'address_ids',
256                               'pcu_ids', 'node_ids']:
257                 if not site.has_key(aggregate) or site[aggregate] is None:
258                     site[aggregate] = []
259                 else:
260                     site[aggregate] = map(int, site[aggregate].split(','))