ff40541323081a993ec5da67e67ff17cb085575d
[plcapi.git] / PLC / Methods / AddNodeToPCU.py
1 from PLC.Faults import *
2 from PLC.Method import Method
3 from PLC.Parameter import Parameter, Mixed
4 from PLC.Nodes import Node, Nodes
5 from PLC.PCUs import PCU, PCUs
6 from PLC.Auth import Auth
7
8 class AddNodeToPCU(Method):
9     """
10     Adds a node to a port on a PCU. Faults if the node has already
11     been added to the PCU or if the port is already in use.
12
13     Non-admins may only update PCUs at their sites.
14
15     Returns 1 if successful, faults otherwise.
16     """
17
18     roles = ['admin', 'pi', 'tech']
19
20     accepts = [
21         Auth(),
22         Mixed(Node.fields['node_id'],
23               Node.fields['hostname']),
24         PCU.fields['pcu_id'],
25         Parameter(int, 'PCU port number')
26         ]
27
28     returns = Parameter(int, '1 if successful')
29
30     def call(self, auth, node_id_or_hostname, pcu_id, port):
31          # Get node
32         nodes = Nodes(self.api, [node_id_or_hostname])
33         if not nodes:
34             raise PLCInvalidArgument, "No such node"
35         node = nodes[0]
36
37         if node['peer_id'] is not None:
38             raise PLCInvalidArgument, "Not a local node"
39
40         # Get PCU
41         pcus = PCUs(self.api, [pcu_id])
42         if not pcus:
43             raise PLCInvalidArgument, "No such PCU"
44         pcu = pcus[0]
45
46         if 'admin' not in self.caller['roles']:
47             ok = False
48             sites = Sites(self.api, self.caller['site_ids'])
49             for site in sites:
50                 if pcu['pcu_id'] in site['pcu_ids']:
51                     ok = True
52                     break
53             if not ok:
54                 raise PLCPermissionDenied, "Not allowed to update that PCU"
55         
56         # Add node to PCU
57         if node['node_id'] in pcu['node_ids']:
58             raise PLCInvalidArgument, "Node already controlled by PCU"
59
60         if node['site_id'] != pcu['site_id']:
61             raise PLCInvalidArgument, "Node is at a different site than this PCU"
62
63         if port in pcu['ports']:
64             raise PLCInvalidArgument, "PCU port already in use"
65
66         pcu.add_node(node, port)
67
68         # Logging variables
69         self.object_ids = [node['node_id'], pcu['pcu_id']]
70         self.message = 'Node %d added to pcu %d on port %d' % \
71                 (node['node_id'], pcu['pcu_id'], port)
72         return 1