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