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