add interface to pcus
[plcapi.git] / PLC / Methods / AddPCU.py
1 from PLC.Faults import *
2 from PLC.Method import Method
3 from PLC.Parameter import Parameter, Mixed
4 from PLC.PCUs import PCU, PCUs
5 from PLC.Auth import PasswordAuth
6 from PLC.Sites import Site, Sites
7
8 class AddPCU(Method):
9     """
10     Adds a new power control unit (PCU) to the specified site. Any
11     fields specified in optional_vals are used, otherwise defaults are
12     used.
13
14     PIs and technical contacts may only add PCUs to their own sites.
15
16     Returns the new pcu_id (> 0) if successful, faults otherwise.
17     """
18
19     roles = ['admin', 'pi', 'tech']
20
21     can_update = lambda (field, value): field in \
22                  ['hostname', 'ip', 'protocol',
23                   'username', 'password',
24                   'model', 'notes']
25     update_fields = dict(filter(can_update, PCU.fields.items()))
26
27     accepts = [
28         PasswordAuth(),
29         Mixed(Site.fields['site_id'],
30               Site.fields['login_base']),
31         update_fields
32         ]
33
34     returns = Parameter(int, 'New pcu_id (> 0) if successful')
35
36     def call(self, auth, site_id_or_login_base, optional_vals = {}):
37         if filter(lambda field: field not in self.update_fields, optional_vals):
38             raise PLCInvalidArgument, "Invalid field specified"
39
40         # Get associated site details
41         sites = Sites(self.api, [site_id_or_login_base]).values()
42         if not sites:
43             raise PLCInvalidArgument, "No such site"
44         site = sites[0]
45
46         if 'admin' not in self.caller['roles']:
47             if site['site_id'] not in self.caller['site_ids']:
48                 raise PLCPermissionDenied, "Not allowed to add a PCU to that site"
49
50         pcu = PCU(self.api, optional_vals)
51         pcu['site_id'] = site['site_id']
52         pcu.sync()
53
54         return pcu['pcu_id']