d311e378506e501d4d3c7f123ffeb86bf4b9a037
[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 can_update = lambda (field, value): field in \
9              ['hostname', 'protocol',
10               'username', 'password',
11               'model', 'notes']
12
13 class AddPCU(Method):
14     """
15     Adds a new power control unit (PCU) to the specified site. Any
16     fields specified in pcu_fields are used, otherwise defaults are
17     used.
18
19     PIs and technical contacts may only add PCUs to their own sites.
20
21     Returns the new pcu_id (> 0) if successful, faults otherwise.
22     """
23
24     roles = ['admin', 'pi', 'tech']
25
26     update_fields = dict(filter(can_update, PCU.fields.items()))
27
28     accepts = [
29         PasswordAuth(),
30         Mixed(Site.fields['site_id'],
31               Site.fields['login_base']),
32         PCU.fields['ip'],
33         update_fields
34         ]
35
36     returns = Parameter(int, 'New pcu_id (> 0) if successful')
37     
38     event_type = 'Add'
39     object_type = 'PCU'
40     object_ids = []
41
42     def call(self, auth, site_id_or_login_base, ip, pcu_fields = {}):
43         pcu_fields = dict(filter(can_update, pcu_fields.items()))
44
45         # Get associated site details
46         sites = Sites(self.api, [site_id_or_login_base]).values()
47         if not sites:
48             raise PLCInvalidArgument, "No such site"
49         site = sites[0]
50
51         if 'admin' not in self.caller['roles']:
52             if site['site_id'] not in self.caller['site_ids']:
53                 raise PLCPermissionDenied, "Not allowed to add a PCU to that site"
54
55         pcu = PCU(self.api, pcu_fields)
56         pcu['site_id'] = site['site_id']
57         pcu['ip'] = ip
58         pcu.sync()
59         self.object_ids = [pcu['pcu_id']]       
60
61         return pcu['pcu_id']